codebase-snapshot 0.20.4 → 0.20.5

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/bin.js CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { spawnSync as spawnSync4 } from "child_process";
5
- import * as fs26 from "fs";
6
- import * as path27 from "path";
5
+ import * as fs27 from "fs";
6
+ import * as path28 from "path";
7
7
  import { parseArgs } from "util";
8
8
 
9
9
  // src/diff.ts
@@ -167,8 +167,8 @@ function workspacePackageDirs(cwd, patterns) {
167
167
  function scanWorkspacePackages(cwd, patterns) {
168
168
  const files = /* @__PURE__ */ new Set();
169
169
  const dependencies = /* @__PURE__ */ new Set();
170
- for (const relative16 of workspacePackageDirs(cwd, patterns)) {
171
- const full = path.join(cwd, relative16);
170
+ for (const relative17 of workspacePackageDirs(cwd, patterns)) {
171
+ const full = path.join(cwd, relative17);
172
172
  try {
173
173
  for (const entry of fs.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
174
174
  } catch {
@@ -1382,7 +1382,7 @@ var DEFAULT_SECRET_PATTERNS = [
1382
1382
  // rendering of textual userinfo mixes cases, while the prose the earlier rules were
1383
1383
  // protecting (`Bearer authentication`) is a lowercase word.
1384
1384
  rule: "authorization-header",
1385
- pattern: /(?<=[Aa]uthorization["']?\s*[:=]\s*["']?[A-Za-z][A-Za-z0-9._~+/-]{0,31}\s{1,8})(?:[A-Za-z0-9_.+/-]{0,31}[0-9][A-Za-z0-9_.+/-]{0,1024}|[A-Za-z0-9_.+/-]{32,1024}|[A-Za-z0-9_.+/-]{8,1024}={1,2}|(?=[A-Za-z0-9_.+/-]{0,1023}[A-Z])(?=[A-Za-z0-9_.+/-]{0,1023}[a-z])[A-Za-z0-9_.+/-]{12,1024})(?![A-Za-z0-9_.+/=-])/
1385
+ pattern: /(?<=[Aa][Uu][Tt][Hh][Oo][Rr][Ii][Zz][Aa][Tt][Ii][Oo][Nn]["']?\s*[:=]\s*["']?[A-Za-z][A-Za-z0-9._~+/-]{0,31}\s{1,8})(?:[A-Za-z0-9_.+/-]{0,31}[0-9][A-Za-z0-9_.+/-]{0,1024}|[A-Za-z0-9_.+/-]{32,1024}|[A-Za-z0-9_.+/-]{8,1024}={1,2}|(?=[A-Za-z0-9_.+/-]{0,1023}[A-Z])(?=[A-Za-z0-9_.+/-]{0,1023}[a-z])[A-Za-z0-9_.+/-]{12,1024})(?![A-Za-z0-9_.+/=-])/
1386
1386
  },
1387
1387
  {
1388
1388
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -1960,6 +1960,7 @@ function redactStructuredValues(text2, filePath, recordFinding) {
1960
1960
  if (firstValue === void 0) continue;
1961
1961
  const valueIndent = (/^[ \t]*/.exec(firstValue)?.[0] ?? "").length;
1962
1962
  if (valueIndent <= baseIndent) continue;
1963
+ if (STRUCTURED_KEY.test(firstValue) || /^[ \t]*-[ \t]/.test(firstValue)) continue;
1963
1964
  let masked = false;
1964
1965
  while (cursor < segments.length) {
1965
1966
  const body = segments[cursor] ?? "";
@@ -2262,7 +2263,7 @@ function verifySnapshotSignature(snapshotDir) {
2262
2263
 
2263
2264
  // src/version.ts
2264
2265
  var GENERATOR_NAME = "codebase-snapshot";
2265
- var GENERATOR_VERSION = "0.20.4";
2266
+ var GENERATOR_VERSION = "0.20.5";
2266
2267
  var SCHEMA_VERSION = "3.0.0";
2267
2268
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2268
2269
  function isOurGeneratorName(name) {
@@ -2294,8 +2295,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
2294
2295
  };
2295
2296
  }
2296
2297
  function isInside(root, candidate) {
2297
- const relative16 = path3.relative(root, candidate);
2298
- return relative16 === "" || !relative16.startsWith(`..${path3.sep}`) && relative16 !== ".." && !path3.isAbsolute(relative16);
2298
+ const relative17 = path3.relative(root, candidate);
2299
+ return relative17 === "" || !relative17.startsWith(`..${path3.sep}`) && relative17 !== ".." && !path3.isAbsolute(relative17);
2299
2300
  }
2300
2301
  var GIT_OUTPUT_LIMIT = 68157440;
2301
2302
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -3014,7 +3015,7 @@ function collectFiles(cwd, options = {}) {
3014
3015
  candidates.push(extra);
3015
3016
  }
3016
3017
  }
3017
- const files = candidates.filter((file) => {
3018
+ let files = candidates.filter((file) => {
3018
3019
  if (isToolOwned(file)) return false;
3019
3020
  const ignored = defaultIgnoreReason(file, toolDirNames);
3020
3021
  if (ignored) {
@@ -3059,8 +3060,50 @@ function collectFiles(cwd, options = {}) {
3059
3060
  }
3060
3061
  return true;
3061
3062
  }).sort();
3063
+ files = dropSymlinksToUnincludedTargets(cwd, files, skipped);
3062
3064
  return { files, skipped: maskSkipPaths(skipped, pathRules) };
3063
3065
  }
3066
+ function dropSymlinksToUnincludedTargets(cwd, files, skipped) {
3067
+ const aliases = /* @__PURE__ */ new Set();
3068
+ for (const file of files) {
3069
+ try {
3070
+ if (fs3.lstatSync(path3.join(cwd, file)).isSymbolicLink()) aliases.add(file);
3071
+ } catch {
3072
+ }
3073
+ }
3074
+ if (aliases.size === 0) return [...files];
3075
+ const includedTargets = /* @__PURE__ */ new Set();
3076
+ for (const file of files) {
3077
+ try {
3078
+ includedTargets.add(fs3.realpathSync(path3.join(cwd, file)));
3079
+ } catch {
3080
+ }
3081
+ }
3082
+ const kept = [];
3083
+ for (const file of files) {
3084
+ if (!aliases.has(file)) {
3085
+ kept.push(file);
3086
+ continue;
3087
+ }
3088
+ let target;
3089
+ try {
3090
+ target = fs3.realpathSync(path3.join(cwd, file));
3091
+ } catch {
3092
+ skipped.push({ path: file, reason: "read-error", detail: "symlink target could not be resolved" });
3093
+ continue;
3094
+ }
3095
+ if (includedTargets.has(target)) {
3096
+ kept.push(file);
3097
+ continue;
3098
+ }
3099
+ skipped.push({
3100
+ path: file,
3101
+ reason: "symlink",
3102
+ detail: "link target was excluded from the snapshot; not followed"
3103
+ });
3104
+ }
3105
+ return kept;
3106
+ }
3064
3107
  function rootRealFor(root) {
3065
3108
  try {
3066
3109
  return fs3.realpathSync(root);
@@ -4013,13 +4056,13 @@ function readConfiguredBrief(cwd, value) {
4013
4056
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
4014
4057
  );
4015
4058
  }
4016
- const relative16 = path4.relative(rootReal, filePath);
4017
- if (relative16.length === 0 || relative16 === ".." || relative16.startsWith(`..${path4.sep}`) || path4.isAbsolute(relative16)) {
4059
+ const relative17 = path4.relative(rootReal, filePath);
4060
+ if (relative17.length === 0 || relative17 === ".." || relative17.startsWith(`..${path4.sep}`) || path4.isAbsolute(relative17)) {
4018
4061
  throw new Error(
4019
4062
  'brief "' + value + '" resolves outside the repository. A brief must be a file inside the repository being described; an absolute or parent path is refused.'
4020
4063
  );
4021
4064
  }
4022
- const posixRelative = relative16.split(path4.sep).join("/");
4065
+ const posixRelative = relative17.split(path4.sep).join("/");
4023
4066
  if (isSensitivePath(posixRelative) || isSensitivePath(value)) {
4024
4067
  throw new Error(
4025
4068
  'brief "' + value + '" is a credential-bearing file. A snapshot must not reproduce secrets, so it cannot be used as the owner brief.'
@@ -4141,11 +4184,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
4141
4184
  const patterns = [];
4142
4185
  for (const dir of [outDir, tmpDir]) {
4143
4186
  const absolute = path4.resolve(cwd, dir);
4144
- const relative16 = path4.relative(cwd, absolute);
4145
- if (!relative16 || relative16 === ".." || relative16.startsWith(`..${path4.sep}`) || path4.isAbsolute(relative16)) {
4187
+ const relative17 = path4.relative(cwd, absolute);
4188
+ if (!relative17 || relative17 === ".." || relative17.startsWith(`..${path4.sep}`) || path4.isAbsolute(relative17)) {
4146
4189
  continue;
4147
4190
  }
4148
- patterns.push(`${relative16.replace(/\\/g, "/")}/**`);
4191
+ patterns.push(`${relative17.replace(/\\/g, "/")}/**`);
4149
4192
  }
4150
4193
  return patterns;
4151
4194
  }
@@ -4657,7 +4700,7 @@ function resolveChangedScope(cwd, request) {
4657
4700
  const descriptions = [];
4658
4701
  if (request.changedSince !== void 0) {
4659
4702
  assertUsableRef(request.changedSince);
4660
- for (const path28 of gitPaths(cwd, [
4703
+ for (const path29 of gitPaths(cwd, [
4661
4704
  "diff",
4662
4705
  "--name-only",
4663
4706
  "-z",
@@ -4665,9 +4708,9 @@ function resolveChangedScope(cwd, request) {
4665
4708
  `${request.changedSince}...HEAD`,
4666
4709
  "--"
4667
4710
  ])) {
4668
- paths.add(path28);
4711
+ paths.add(path29);
4669
4712
  }
4670
- for (const path28 of gitPaths(cwd, [
4713
+ for (const path29 of gitPaths(cwd, [
4671
4714
  "diff",
4672
4715
  "--name-only",
4673
4716
  "-z",
@@ -4675,15 +4718,15 @@ function resolveChangedScope(cwd, request) {
4675
4718
  "HEAD",
4676
4719
  "--"
4677
4720
  ])) {
4678
- paths.add(path28);
4721
+ paths.add(path29);
4679
4722
  }
4680
- for (const path28 of gitPaths(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--"])) {
4681
- paths.add(path28);
4723
+ for (const path29 of gitPaths(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--"])) {
4724
+ paths.add(path29);
4682
4725
  }
4683
4726
  descriptions.push(`changed since ${request.changedSince}`);
4684
4727
  }
4685
4728
  if (request.staged === true) {
4686
- for (const path28 of gitPaths(cwd, [
4729
+ for (const path29 of gitPaths(cwd, [
4687
4730
  "diff",
4688
4731
  "--cached",
4689
4732
  "--name-only",
@@ -4691,10 +4734,10 @@ function resolveChangedScope(cwd, request) {
4691
4734
  "--relative",
4692
4735
  "--"
4693
4736
  ])) {
4694
- paths.add(path28);
4695
- stagedPaths.add(path28);
4737
+ paths.add(path29);
4738
+ stagedPaths.add(path29);
4696
4739
  }
4697
- for (const path28 of gitPaths(cwd, [
4740
+ for (const path29 of gitPaths(cwd, [
4698
4741
  "diff",
4699
4742
  "--cached",
4700
4743
  "--name-only",
@@ -4703,7 +4746,7 @@ function resolveChangedScope(cwd, request) {
4703
4746
  "--diff-filter=D",
4704
4747
  "--"
4705
4748
  ])) {
4706
- deletedPaths.add(path28);
4749
+ deletedPaths.add(path29);
4707
4750
  }
4708
4751
  descriptions.push("staged");
4709
4752
  }
@@ -4783,8 +4826,8 @@ function tsconfigPathsFor(cwd) {
4783
4826
  return value;
4784
4827
  }
4785
4828
  function repositoryRelative(cwd, target) {
4786
- const relative16 = path5.relative(cwd, target).replace(/\\/g, "/");
4787
- return relative16.length === 0 || !relative16.startsWith("..") && !path5.isAbsolute(relative16) ? relative16 : null;
4829
+ const relative17 = path5.relative(cwd, target).replace(/\\/g, "/");
4830
+ return relative17.length === 0 || !relative17.startsWith("..") && !path5.isAbsolute(relative17) ? relative17 : null;
4788
4831
  }
4789
4832
  function rememberFirst(map, key, value) {
4790
4833
  if (!map.has(key)) map.set(key, value);
@@ -5529,9 +5572,9 @@ var JAVA_METHOD = /^\s+(?:public|private|protected)\s+(?:static\s+)?(?:final\s+)
5529
5572
  var jvmProfile = {
5530
5573
  id: "jvm",
5531
5574
  extensions: [".java", ".kt", ".kts", ".scala"],
5532
- summarize(path28, content) {
5575
+ summarize(path29, content) {
5533
5576
  const summary = emptySummary();
5534
- const lower = path28.toLowerCase();
5577
+ const lower = path29.toLowerCase();
5535
5578
  const isJava = lower.endsWith(".java");
5536
5579
  const isKotlin = lower.endsWith(".kt") || lower.endsWith(".kts");
5537
5580
  eachLine(content, (line) => {
@@ -5754,9 +5797,9 @@ var rubyProfile = {
5754
5797
  eachLine(content, (line) => {
5755
5798
  const trimmed = line.trim();
5756
5799
  if (!trimmed || trimmed.startsWith("#")) return;
5757
- const relative16 = REQUIRE_RELATIVE.exec(trimmed);
5758
- if (relative16) {
5759
- summary.imports.push(`./${relative16[1]}`);
5800
+ const relative17 = REQUIRE_RELATIVE.exec(trimmed);
5801
+ if (relative17) {
5802
+ summary.imports.push(`./${relative17[1]}`);
5760
5803
  return;
5761
5804
  }
5762
5805
  const required = REQUIRE.exec(trimmed);
@@ -5852,17 +5895,17 @@ var rustProfile = {
5852
5895
  var SCRIPT_BLOCK = /<script([^>]*)>([\s\S]*?)<\/script>/gi;
5853
5896
  var JSX_LANG = /\blang\s*=\s*["']?[tj]sx\b/i;
5854
5897
  var ASTRO_FRONTMATTER = /^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?=\r?\n|$)/;
5855
- function componentName(path28) {
5856
- const base = path28.split("/").pop() ?? path28;
5898
+ function componentName(path29) {
5899
+ const base = path29.split("/").pop() ?? path29;
5857
5900
  return base.replace(/\.[^.]+$/, "");
5858
5901
  }
5859
5902
  var sfcProfile = {
5860
5903
  id: "sfc",
5861
5904
  extensions: [".vue", ".svelte", ".astro"],
5862
- summarize(path28, content) {
5905
+ summarize(path29, content) {
5863
5906
  let script = "";
5864
- let usesJsx = path28.toLowerCase().endsWith(".astro");
5865
- if (path28.toLowerCase().endsWith(".astro")) {
5907
+ let usesJsx = path29.toLowerCase().endsWith(".astro");
5908
+ if (path29.toLowerCase().endsWith(".astro")) {
5866
5909
  const frontmatter = ASTRO_FRONTMATTER.exec(content);
5867
5910
  if (frontmatter) script += `${frontmatter[1]}
5868
5911
  `;
@@ -5872,7 +5915,7 @@ var sfcProfile = {
5872
5915
  script += `${match[2]}
5873
5916
  `;
5874
5917
  }
5875
- const name = componentName(path28);
5918
+ const name = componentName(path29);
5876
5919
  if (!script.trim()) {
5877
5920
  const summary2 = emptySummary();
5878
5921
  if (name) {
@@ -6063,15 +6106,15 @@ for (const profile of LANGUAGE_PROFILES) {
6063
6106
  BY_EXTENSION.set(extension.toLowerCase(), profile);
6064
6107
  }
6065
6108
  }
6066
- function profileForPath(path28) {
6067
- const lower = path28.toLowerCase();
6109
+ function profileForPath(path29) {
6110
+ const lower = path29.toLowerCase();
6068
6111
  const dot = lower.lastIndexOf(".");
6069
6112
  if (dot === -1) return null;
6070
6113
  return BY_EXTENSION.get(lower.slice(dot)) ?? null;
6071
6114
  }
6072
- function summarizeWithProfile(path28, content) {
6073
- const profile = profileForPath(path28);
6074
- return profile ? profile.summarize(path28, content) : null;
6115
+ function summarizeWithProfile(path29, content) {
6116
+ const profile = profileForPath(path29);
6117
+ return profile ? profile.summarize(path29, content) : null;
6075
6118
  }
6076
6119
 
6077
6120
  // src/scanner/binary.ts
@@ -6805,12 +6848,16 @@ function validateSnapshot(configInput) {
6805
6848
  // discovery mode" meant `validate` could enumerate files one way while the snapshot
6806
6849
  // had been generated another way, and then blame the difference on drift.
6807
6850
  discovery: config.discovery,
6851
+ // `generate --staged` adds index-only paths to the candidate list. Without the same
6852
+ // extra paths, a staged file that is absent from the working tree was invisible to
6853
+ // this scan and then reported as deleted, although the snapshot matched the index.
6854
+ ...stagedScope === null ? {} : { extraPaths: [...stagedScope] },
6808
6855
  // The same exclusion `generate` applies: without it, `validate` recounted the tool's
6809
6856
  // own output directory as a set of files missing from the snapshot, so a correct
6810
6857
  // snapshot was reported as drifting.
6811
6858
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
6812
6859
  (directory) => path7.relative(config.cwd, path7.resolve(config.cwd, directory)).replace(/\\/g, "/")
6813
- ).filter((relative16) => relative16.length > 0 && !relative16.startsWith(".."))
6860
+ ).filter((relative17) => relative17.length > 0 && !relative17.startsWith(".."))
6814
6861
  });
6815
6862
  for (const diskFile of collection.files) {
6816
6863
  const snapshotHash = manifestFileMap.get(diskFile);
@@ -6851,6 +6898,12 @@ function validateSnapshot(configInput) {
6851
6898
  }
6852
6899
  }
6853
6900
  for (const snapshotFile of manifestFileMap.keys()) {
6901
+ if (recordedStaged && stagedScope?.has(snapshotFile)) {
6902
+ if (readStagedBlob(config.cwd, snapshotFile) === null) {
6903
+ drift.missingOnDisk.push(snapshotFile);
6904
+ }
6905
+ continue;
6906
+ }
6854
6907
  const confined = confineToDirectory(config.cwd, snapshotFile);
6855
6908
  if (confined === null) {
6856
6909
  drift.partIssues.push({
@@ -7291,8 +7344,8 @@ function validateSnapshot(configInput) {
7291
7344
  const target = match[1].split("#")[0];
7292
7345
  if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
7293
7346
  const resolved = path7.resolve(snapshotDir, "reports", target);
7294
- const relative16 = path7.relative(snapshotDir, resolved);
7295
- if (relative16.startsWith("..") || path7.isAbsolute(relative16) || !fs8.existsSync(resolved)) {
7347
+ const relative17 = path7.relative(snapshotDir, resolved);
7348
+ if (relative17.startsWith("..") || path7.isAbsolute(relative17) || !fs8.existsSync(resolved)) {
7296
7349
  drift.partIssues.push({
7297
7350
  part: key,
7298
7351
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -7799,6 +7852,9 @@ function countLines(content) {
7799
7852
  const last = content.charCodeAt(content.length - 1);
7800
7853
  return last === 10 || last === 13 ? breaks : breaks + 1;
7801
7854
  }
7855
+ function countBodyLines(content) {
7856
+ return content.length === 0 ? 0 : content.split("\n").length;
7857
+ }
7802
7858
  function truncateToBytes(content, maxBytes) {
7803
7859
  if (maxBytes <= 0) return { content: "", isTruncated: content.length > 0 };
7804
7860
  const buffer = Buffer.from(content, "utf8");
@@ -7948,23 +8004,23 @@ function describeMatcher(matcher) {
7948
8004
  function normalizeTarget(cwd, target) {
7949
8005
  const resolvedCwd = path10.resolve(cwd);
7950
8006
  const absolute = path10.resolve(resolvedCwd, target);
7951
- const relative16 = path10.relative(resolvedCwd, absolute);
7952
- if (relative16 === "" || relative16 === ".." || relative16.startsWith(`..${path10.sep}`) || path10.isAbsolute(relative16)) {
8007
+ const relative17 = path10.relative(resolvedCwd, absolute);
8008
+ if (relative17 === "" || relative17 === ".." || relative17.startsWith(`..${path10.sep}`) || path10.isAbsolute(relative17)) {
7953
8009
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
7954
8010
  }
7955
- return { relative: relative16.split(path10.sep).join("/"), outsideRoot: false };
8011
+ return { relative: relative17.split(path10.sep).join("/"), outsideRoot: false };
7956
8012
  }
7957
8013
  function findRuleMatch(rules, relativePath) {
7958
8014
  return rules.find(
7959
8015
  (rule) => matchRule(relativePath, rule.match)
7960
8016
  );
7961
8017
  }
7962
- function findRecordedAncestor(skipped, relative16, maskedPath2) {
8018
+ function findRecordedAncestor(skipped, relative17, maskedPath2) {
7963
8019
  let nearest;
7964
8020
  for (const record of skipped) {
7965
8021
  const ancestorPath = record.path;
7966
8022
  if (ancestorPath.length === 0) continue;
7967
- const isAncestor = relative16.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
8023
+ const isAncestor = relative17.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
7968
8024
  if (!isAncestor) continue;
7969
8025
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
7970
8026
  }
@@ -7980,8 +8036,8 @@ function readManifest2(config) {
7980
8036
  }
7981
8037
  function explainPath(config, target) {
7982
8038
  const normalized = normalizeTarget(config.cwd, target);
7983
- const relative16 = normalized.relative;
7984
- const maskedPath2 = findSecretInPath(relative16, config.secretRules)?.masked ?? relative16;
8039
+ const relative17 = normalized.relative;
8040
+ const maskedPath2 = findSecretInPath(relative17, config.secretRules)?.masked ?? relative17;
7985
8041
  if (normalized.outsideRoot) {
7986
8042
  return {
7987
8043
  path: maskedPath2,
@@ -7991,7 +8047,7 @@ function explainPath(config, target) {
7991
8047
  detail: "path resolves outside the configured repository root and was not inspected"
7992
8048
  };
7993
8049
  }
7994
- const absolute = path10.join(config.cwd, relative16);
8050
+ const absolute = path10.join(config.cwd, relative17);
7995
8051
  const result = {
7996
8052
  path: maskedPath2,
7997
8053
  exists: fs10.existsSync(absolute),
@@ -8009,11 +8065,11 @@ function explainPath(config, target) {
8009
8065
  // that is only missing because the walker dropped the tool's own output directory.
8010
8066
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
8011
8067
  (directory) => path10.relative(config.cwd, path10.resolve(config.cwd, directory)).replace(/\\/g, "/")
8012
- ).filter((relative17) => relative17.length > 0 && !relative17.startsWith(".."))
8068
+ ).filter((relative18) => relative18.length > 0 && !relative18.startsWith(".."))
8013
8069
  });
8014
- if (!collection.files.includes(relative16)) {
8070
+ if (!collection.files.includes(relative17)) {
8015
8071
  const record = collection.skipped.find(
8016
- (entry2) => entry2.path === relative16 || entry2.path === maskedPath2
8072
+ (entry2) => entry2.path === relative17 || entry2.path === maskedPath2
8017
8073
  );
8018
8074
  if (record) {
8019
8075
  result.reason = record.reason;
@@ -8022,7 +8078,7 @@ function explainPath(config, target) {
8022
8078
  result.reason = "missing";
8023
8079
  result.detail = "no such file or directory, relative to the configured cwd";
8024
8080
  } else {
8025
- const ancestor = findRecordedAncestor(collection.skipped, relative16, maskedPath2);
8081
+ const ancestor = findRecordedAncestor(collection.skipped, relative17, maskedPath2);
8026
8082
  if (ancestor) {
8027
8083
  result.reason = ancestor.reason;
8028
8084
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -8042,11 +8098,11 @@ function explainPath(config, target) {
8042
8098
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
8043
8099
  ...config.staged === true ? { staged: true } : {}
8044
8100
  });
8045
- inScope = scope.paths.has(relative16);
8101
+ inScope = scope.paths.has(relative17);
8046
8102
  if (!inScope && config.withDependents === true) {
8047
8103
  inScope = importsChangedFile(
8048
- relative16,
8049
- importsOfFile(relative16, absolute),
8104
+ relative17,
8105
+ importsOfFile(relative17, absolute),
8050
8106
  scope.paths,
8051
8107
  buildImportResolver(collection.files.map((file) => ({ relativePath: file })), {
8052
8108
  tsconfig: tsconfigPathsFor(config.cwd)
@@ -8106,15 +8162,15 @@ function explainPath(config, target) {
8106
8162
  result.bytes = buffer.length;
8107
8163
  result.lines = countLines(text2);
8108
8164
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
8109
- const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative16);
8165
+ const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative17);
8110
8166
  result.secretCount = findings.length;
8111
8167
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
8112
8168
  let inclusionMode = "full";
8113
- if (config.skeleton === true && isSkeletonizable(relative16)) {
8114
- const skeleton = skeletonizeTypeScript(text2, relative16);
8169
+ if (config.skeleton === true && isSkeletonizable(relative17)) {
8170
+ const skeleton = skeletonizeTypeScript(text2, relative17);
8115
8171
  if (skeleton.collapsed > 0) inclusionMode = "signatures";
8116
8172
  }
8117
- if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative16) && stripComments2(text2, relative16).removed > 0) {
8173
+ if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative17) && stripComments2(text2, relative17).removed > 0) {
8118
8174
  inclusionMode = "comments-stripped";
8119
8175
  }
8120
8176
  if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
@@ -8123,18 +8179,18 @@ function explainPath(config, target) {
8123
8179
  }
8124
8180
  result.inclusionMode = inclusionMode;
8125
8181
  }
8126
- result.layer = classifyLayer(relative16, config.layers);
8127
- result.kind = classifyKind(relative16, config.kinds);
8128
- result.language = detectLanguage(relative16);
8129
- const layerRule = findRuleMatch(config.layers, relative16);
8182
+ result.layer = classifyLayer(relative17, config.layers);
8183
+ result.kind = classifyKind(relative17, config.kinds);
8184
+ result.language = detectLanguage(relative17);
8185
+ const layerRule = findRuleMatch(config.layers, relative17);
8130
8186
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
8131
- const kindRule = findRuleMatch(config.kinds, relative16);
8187
+ const kindRule = findRuleMatch(config.kinds, relative17);
8132
8188
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
8133
8189
  const manifest = readManifest2(config);
8134
- const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative16) : void 0;
8190
+ const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative17) : void 0;
8135
8191
  result.part = entry?.part ?? null;
8136
8192
  if (entry === void 0) {
8137
- const record = manifest?.skipped?.find((skip) => skip.path === relative16);
8193
+ const record = manifest?.skipped?.find((skip) => skip.path === relative17);
8138
8194
  if (record !== void 0 && (record.reason === "not-selected" || record.reason === "unchanged")) {
8139
8195
  result.included = false;
8140
8196
  result.reason = record.reason;
@@ -8666,7 +8722,7 @@ function keyReader(input) {
8666
8722
  next() {
8667
8723
  const queued = queue.shift();
8668
8724
  if (queued) return Promise.resolve(queued);
8669
- return new Promise((resolve15) => waiters.push(resolve15));
8725
+ return new Promise((resolve16) => waiters.push(resolve16));
8670
8726
  },
8671
8727
  close() {
8672
8728
  input.off("keypress", onKey);
@@ -9099,11 +9155,11 @@ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
9099
9155
  const entries = [];
9100
9156
  for (const directory of [outDir, tmpDir]) {
9101
9157
  if (directory === null) continue;
9102
- const relative16 = path12.relative(cwd, path12.resolve(cwd, directory)).replace(/\\/g, "/");
9103
- if (relative16 === "" || relative16 === "." || relative16.startsWith("..") || path12.isAbsolute(relative16)) {
9158
+ const relative17 = path12.relative(cwd, path12.resolve(cwd, directory)).replace(/\\/g, "/");
9159
+ if (relative17 === "" || relative17 === "." || relative17.startsWith("..") || path12.isAbsolute(relative17)) {
9104
9160
  continue;
9105
9161
  }
9106
- entries.push(`/${relative16}/`);
9162
+ entries.push(`/${relative17}/`);
9107
9163
  }
9108
9164
  return [...new Set(entries)];
9109
9165
  }
@@ -9438,10 +9494,10 @@ async function runInit(options) {
9438
9494
  import * as fs13 from "fs";
9439
9495
  import * as path13 from "path";
9440
9496
  function describeTarget(cwd) {
9441
- const relative16 = path13.relative(process.cwd(), cwd);
9442
- if (relative16 === "") return "this directory";
9443
- if (relative16.startsWith("..") || path13.isAbsolute(relative16)) return cwd;
9444
- return relative16;
9497
+ const relative17 = path13.relative(process.cwd(), cwd);
9498
+ if (relative17 === "") return "this directory";
9499
+ if (relative17.startsWith("..") || path13.isAbsolute(relative17)) return cwd;
9500
+ return relative17;
9445
9501
  }
9446
9502
  function firstRunMessage(reason, cwd) {
9447
9503
  const where = describeTarget(cwd);
@@ -9546,9 +9602,9 @@ async function runWithStdoutCapture(fn) {
9546
9602
  }
9547
9603
 
9548
9604
  // src/index.ts
9549
- import * as fs24 from "fs";
9605
+ import * as fs25 from "fs";
9550
9606
  import * as os3 from "os";
9551
- import * as path25 from "path";
9607
+ import * as path26 from "path";
9552
9608
 
9553
9609
  // src/generator/audit.ts
9554
9610
  function generateAuditReport(manifest, secretFindings, secretRules) {
@@ -10050,7 +10106,7 @@ function applyTruncatedContent(file, content, reason) {
10050
10106
  file.truncationReason = reason;
10051
10107
  file.omittedRanges = keptLines >= file.originalLines ? file.originalLines > 0 ? [[file.originalLines, file.originalLines]] : [] : [[keptLines + 1, file.originalLines]];
10052
10108
  file.includedBytes = Buffer.byteLength(content, "utf8");
10053
- file.includedLines = countLines(content);
10109
+ file.includedLines = countBodyLines(content);
10054
10110
  }
10055
10111
  function rehashPart(part, markdown) {
10056
10112
  const estimatedTokens = estimateTokens(markdown.replace(TOKEN_LINE, ""));
@@ -10185,7 +10241,7 @@ function renderFileSection(file) {
10185
10241
  const content = file.content ?? "";
10186
10242
  const body = emittedBody(content);
10187
10243
  file.includedBytes = Buffer.byteLength(body, "utf8");
10188
- file.includedLines = countLines(body);
10244
+ file.includedLines = countBodyLines(body);
10189
10245
  const fence = fenceForContent(content);
10190
10246
  const anchor = anchorForPath(file.relativePath);
10191
10247
  return [
@@ -10480,10 +10536,10 @@ function resolveImport(from, specifier, byPath) {
10480
10536
  if (segment === "..") parts.pop();
10481
10537
  else parts.push(segment);
10482
10538
  }
10483
- const path28 = parts.join("/");
10484
- const withoutExtension = path28.replace(/\.[cm]?[jt]sx?$/, "");
10539
+ const path29 = parts.join("/");
10540
+ const withoutExtension = path29.replace(/\.[cm]?[jt]sx?$/, "");
10485
10541
  const candidates = [
10486
- path28,
10542
+ path29,
10487
10543
  withoutExtension + ".ts",
10488
10544
  withoutExtension + ".tsx",
10489
10545
  withoutExtension + ".js",
@@ -10492,18 +10548,18 @@ function resolveImport(from, specifier, byPath) {
10492
10548
  withoutExtension + ".go",
10493
10549
  withoutExtension + ".rs",
10494
10550
  withoutExtension + "/index.ts",
10495
- path28 + ".ts",
10496
- path28 + ".tsx",
10497
- path28 + ".js",
10498
- path28 + ".jsx",
10499
- path28 + ".mjs",
10500
- path28 + ".cjs",
10501
- path28 + ".py",
10502
- path28 + ".go",
10503
- path28 + ".rs",
10504
- path28 + ".java",
10505
- path28 + "/index.ts",
10506
- path28 + "/index.js"
10551
+ path29 + ".ts",
10552
+ path29 + ".tsx",
10553
+ path29 + ".js",
10554
+ path29 + ".jsx",
10555
+ path29 + ".mjs",
10556
+ path29 + ".cjs",
10557
+ path29 + ".py",
10558
+ path29 + ".go",
10559
+ path29 + ".rs",
10560
+ path29 + ".java",
10561
+ path29 + "/index.ts",
10562
+ path29 + "/index.js"
10507
10563
  ];
10508
10564
  for (const candidate of candidates) {
10509
10565
  const found = byPath.get(candidate);
@@ -10532,12 +10588,12 @@ function planForQuestion(manifest, question, options = {}) {
10532
10588
  const scored = [];
10533
10589
  for (const file of manifest.files) {
10534
10590
  if (isTest(file) && !wantsTests) continue;
10535
- const path28 = file.relativePath.toLowerCase();
10536
- const words = path28.split(/[^a-z0-9_]+/).filter((word) => word.length >= 3);
10591
+ const path29 = file.relativePath.toLowerCase();
10592
+ const words = path29.split(/[^a-z0-9_]+/).filter((word) => word.length >= 3);
10537
10593
  let score = 0;
10538
10594
  const reasons = [];
10539
10595
  for (const term of terms) {
10540
- if (path28.includes(term)) {
10596
+ if (path29.includes(term)) {
10541
10597
  score += 8;
10542
10598
  reasons.push("path:" + term);
10543
10599
  continue;
@@ -10678,24 +10734,119 @@ function formatNumber2(value) {
10678
10734
  // src/generator/diff.ts
10679
10735
  import { spawnSync } from "child_process";
10680
10736
  function runGit(cwd, args) {
10681
- const result = spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true, maxBuffer: 64 * 1024 * 1024 });
10737
+ const result = spawnSync(
10738
+ "git",
10739
+ ["-c", "core.quotepath=false", "-c", "diff.noprefix=false", ...args],
10740
+ { cwd, encoding: "utf8", windowsHide: true, maxBuffer: 64 * 1024 * 1024 }
10741
+ );
10682
10742
  if (result.status !== 0) return { ok: false, out: (result.stderr ?? "").trim() };
10683
10743
  return { ok: true, out: result.stdout ?? "" };
10684
10744
  }
10685
10745
  function isGitRepository(cwd) {
10686
10746
  return runGit(cwd, ["rev-parse", "--is-inside-work-tree"]).out.trim() === "true";
10687
10747
  }
10748
+ function unquoteGitPath(value) {
10749
+ if (!value.startsWith('"') || !value.endsWith('"')) return value;
10750
+ const body = value.slice(1, -1);
10751
+ let out = "";
10752
+ let bytes = [];
10753
+ const flushBytes = () => {
10754
+ if (bytes.length === 0) return;
10755
+ out += Buffer.from(bytes).toString("utf8");
10756
+ bytes = [];
10757
+ };
10758
+ const escapes = {
10759
+ a: "\x07",
10760
+ b: "\b",
10761
+ f: "\f",
10762
+ n: "\n",
10763
+ r: "\r",
10764
+ t: " ",
10765
+ v: "\v",
10766
+ "\\": "\\",
10767
+ '"': '"'
10768
+ };
10769
+ for (let index = 0; index < body.length; index += 1) {
10770
+ const char = body[index];
10771
+ if (char !== "\\") {
10772
+ flushBytes();
10773
+ out += char;
10774
+ continue;
10775
+ }
10776
+ const next = body[index + 1];
10777
+ if (next === void 0) {
10778
+ flushBytes();
10779
+ out += "\\";
10780
+ break;
10781
+ }
10782
+ index += 1;
10783
+ if (/[0-7]/.test(next)) {
10784
+ let octal = next;
10785
+ while (octal.length < 3 && /[0-7]/.test(body[index + 1] ?? "")) {
10786
+ index += 1;
10787
+ octal += body[index];
10788
+ }
10789
+ bytes.push(Number.parseInt(octal, 8) & 255);
10790
+ continue;
10791
+ }
10792
+ flushBytes();
10793
+ out += escapes[next] ?? next;
10794
+ }
10795
+ flushBytes();
10796
+ return out;
10797
+ }
10798
+ function takeGitPath(value) {
10799
+ if (value.length === 0) return null;
10800
+ if (value.startsWith('"')) {
10801
+ let index = 1;
10802
+ while (index < value.length) {
10803
+ if (value[index] === "\\") {
10804
+ index += 2;
10805
+ continue;
10806
+ }
10807
+ if (value[index] === '"') {
10808
+ return { token: value.slice(0, index + 1), rest: value.slice(index + 1).replace(/^ /, "") };
10809
+ }
10810
+ index += 1;
10811
+ }
10812
+ return null;
10813
+ }
10814
+ const space = value.indexOf(" ");
10815
+ if (space === -1) return { token: value, rest: "" };
10816
+ return { token: value.slice(0, space), rest: value.slice(space + 1) };
10817
+ }
10818
+ function pathFromGitToken(token, prefix) {
10819
+ const unquoted = unquoteGitPath(token);
10820
+ if (unquoted === "/dev/null") return null;
10821
+ if (!unquoted.startsWith(prefix)) return null;
10822
+ return unquoted.slice(prefix.length);
10823
+ }
10688
10824
  function diffSectionPaths(body) {
10689
10825
  const paths = /* @__PURE__ */ new Set();
10690
10826
  for (const line of body.split("\n")) {
10691
- const plus = /^\+\+\+ b\/(.*)$/.exec(line);
10692
- if (plus !== null) paths.add(plus[1]);
10693
- const minus = /^--- a\/(.*)$/.exec(line);
10694
- if (minus !== null) paths.add(minus[1]);
10695
- const header = /^diff --git a\/(.*?) b\/(.*)$/.exec(line);
10696
- if (header !== null) {
10697
- paths.add(header[1]);
10698
- paths.add(header[2]);
10827
+ if (line.startsWith("diff --git ")) {
10828
+ const first = takeGitPath(line.slice("diff --git ".length));
10829
+ if (first === null) continue;
10830
+ const second = takeGitPath(first.rest);
10831
+ if (second === null) continue;
10832
+ const left = pathFromGitToken(first.token, "a/");
10833
+ const right = pathFromGitToken(second.token, "b/");
10834
+ if (left !== null) paths.add(left);
10835
+ if (right !== null) paths.add(right);
10836
+ continue;
10837
+ }
10838
+ if (line.startsWith("+++ ")) {
10839
+ const token = takeGitPath(line.slice(4));
10840
+ if (token === null) continue;
10841
+ const path29 = pathFromGitToken(token.token, "b/");
10842
+ if (path29 !== null) paths.add(path29);
10843
+ continue;
10844
+ }
10845
+ if (line.startsWith("--- ")) {
10846
+ const token = takeGitPath(line.slice(4));
10847
+ if (token === null) continue;
10848
+ const path29 = pathFromGitToken(token.token, "a/");
10849
+ if (path29 !== null) paths.add(path29);
10699
10850
  }
10700
10851
  }
10701
10852
  return [...paths];
@@ -10706,6 +10857,7 @@ function generateDiffReport(cwd, options = {}) {
10706
10857
  const sections = [];
10707
10858
  let truncated = false;
10708
10859
  let omittedSensitive = 0;
10860
+ let omittedUnparseable = 0;
10709
10861
  const commands = [
10710
10862
  ["Unstaged", ["diff", "--no-color"]],
10711
10863
  ["Staged", ["diff", "--cached", "--no-color"]]
@@ -10716,7 +10868,11 @@ function generateDiffReport(cwd, options = {}) {
10716
10868
  const rawSections = result.out.split(/(?=^diff --git )/m).filter((section) => section.length > 0);
10717
10869
  for (const rawSection of rawSections) {
10718
10870
  const paths2 = diffSectionPaths(rawSection);
10719
- const blocked = paths2.some((path28) => isSensitivePath(path28) || options.excluded?.(path28) === true);
10871
+ if (paths2.length === 0) {
10872
+ omittedUnparseable += 1;
10873
+ continue;
10874
+ }
10875
+ const blocked = paths2.some((path29) => isSensitivePath(path29) || options.excluded?.(path29) === true);
10720
10876
  if (blocked) {
10721
10877
  omittedSensitive += 1;
10722
10878
  continue;
@@ -10727,7 +10883,13 @@ function generateDiffReport(cwd, options = {}) {
10727
10883
  truncated = true;
10728
10884
  break;
10729
10885
  }
10730
- const chunk = truncateToBytes(rawSection, remaining);
10886
+ const sourcePath = paths2[0] ?? "reports/diff.md";
10887
+ const redactedSection = scanAndRedactSecrets(
10888
+ rawSection,
10889
+ options.secretRules ?? [],
10890
+ sourcePath
10891
+ ).redacted;
10892
+ const chunk = truncateToBytes(redactedSection, remaining);
10731
10893
  if (chunk.isTruncated) truncated = true;
10732
10894
  sections.push(
10733
10895
  "## " + title + " changes\n\nRun: git " + args.join(" ") + "\n\n```diff\n" + chunk.content + "\n```"
@@ -10737,7 +10899,7 @@ function generateDiffReport(cwd, options = {}) {
10737
10899
  }
10738
10900
  if (sections.length === 0) return null;
10739
10901
  const paths = /* @__PURE__ */ new Set();
10740
- for (const section of sections) for (const path28 of diffSectionPaths(section)) paths.add(path28);
10902
+ for (const section of sections) for (const path29 of diffSectionPaths(section)) paths.add(path29);
10741
10903
  const joined = [
10742
10904
  "# Uncommitted changes",
10743
10905
  "",
@@ -10748,6 +10910,10 @@ function generateDiffReport(cwd, options = {}) {
10748
10910
  "> " + omittedSensitive + " file section(s) omitted: their path is credential-bearing or excluded from the snapshot.",
10749
10911
  ""
10750
10912
  ] : [],
10913
+ ...omittedUnparseable > 0 ? [
10914
+ "> " + omittedUnparseable + " file section(s) omitted: their diff header could not be attributed to a path, so the sensitive-path filter could not run.",
10915
+ ""
10916
+ ] : [],
10751
10917
  ...sections,
10752
10918
  ...truncated ? ["", "> Truncated at " + maxBytes + " bytes. Run git diff for the rest."] : [],
10753
10919
  ""
@@ -11023,7 +11189,7 @@ function systemSection(manifest, code, brief, escape, sawManifest) {
11023
11189
  " A change here reaches the most call sites; read it before judging anything that uses it."
11024
11190
  );
11025
11191
  }
11026
- const entryPoints = manifest.files.map((file) => file.relativePath).filter((path28) => ENTRY_POINT.test(path28)).sort((a, b) => a.split("/").length - b.split("/").length || a.length - b.length).slice(0, MAX_ENTRY_POINTS);
11192
+ const entryPoints = manifest.files.map((file) => file.relativePath).filter((path29) => ENTRY_POINT.test(path29)).sort((a, b) => a.split("/").length - b.split("/").length || a.length - b.length).slice(0, MAX_ENTRY_POINTS);
11027
11193
  out.push(
11028
11194
  entryPoints.length > 0 ? "- Entry points by convention: " + entryPoints.map(code).join(", ") + "." : "- No entry point was identifiable by name. The largest files below are where execution"
11029
11195
  );
@@ -11254,12 +11420,12 @@ function ownerNotesSection(brief, code, text2) {
11254
11420
  if (brief === void 0 || brief.notes.length === 0) return [];
11255
11421
  const out = ["## Owner notes", ""];
11256
11422
  for (const note of brief.notes) {
11257
- out.push("### " + note.heading, "", ...ownerBlock(note.body, brief.path, code, text2), "");
11423
+ out.push("### " + text2(note.heading), "", ...ownerBlock(note.body, brief.path, code, text2), "");
11258
11424
  }
11259
11425
  return out;
11260
11426
  }
11261
- function ownerBlock(body, path28, code, escape) {
11262
- return ["> Written by the project owner in " + code(path28) + ", not generated.", "", escape(body)];
11427
+ function ownerBlock(body, path29, code, escape) {
11428
+ return ["> Written by the project owner in " + code(path29) + ", not generated.", "", escape(body)];
11263
11429
  }
11264
11430
  function snapshotSection(manifest, code, partsWritten) {
11265
11431
  const out = ["## This snapshot", ""];
@@ -11475,27 +11641,31 @@ function generateReadme(manifest, artifacts) {
11475
11641
  const readOrder = [];
11476
11642
  if (wrote("prompt")) {
11477
11643
  readOrder.push(
11478
- "1. Hand `PROMPT.md` to the model that receives this snapshot: it names the parts, the partial files and the fingerprint of this run."
11644
+ "Hand `PROMPT.md` to the model that receives this snapshot: it names the parts, the partial files and the fingerprint of this run."
11479
11645
  );
11480
11646
  }
11481
11647
  if (wrote("navigation") || wrote("projectTree")) {
11482
11648
  const first = [wrote("navigation") ? "`reports/navigation.md`" : null, wrote("projectTree") ? "`reports/project-tree.md`" : null].filter(Boolean).join(" or ");
11483
- readOrder.push(`1. Read ${first} first to locate target features or files.`);
11649
+ readOrder.push(`Read ${first} first to locate target features or files.`);
11484
11650
  }
11485
11651
  if (wrote("parts")) {
11486
11652
  readOrder.push(
11487
- `${readOrder.length + 1}. Open only the specific \`parts/part-XXX.md\` file holding the target modules.`
11653
+ "Open only the specific `parts/part-XXX.md` file holding the target modules."
11488
11654
  );
11489
11655
  }
11490
11656
  if (wrote("manifest")) {
11491
- readOrder.push(
11492
- `${readOrder.length + 1}. Inspect \`manifest.json\` for precise dependency and AST symbol maps.`
11493
- );
11657
+ readOrder.push("Inspect `manifest.json` for precise dependency and AST symbol maps.");
11494
11658
  }
11495
11659
  readOrder.push(
11496
- wrote("manifest") ? `${readOrder.length + 1}. Check \`manifest.validation.status\` before trusting the snapshot; \`snapshot validate\` re-checks it against disk.` : `${readOrder.length + 1}. No manifest was written, so this snapshot cannot be re-checked; regenerate with the manifest artifact enabled before trusting it.`
11660
+ wrote("manifest") ? "Check `manifest.validation.status` before trusting the snapshot; `snapshot validate` re-checks it against disk." : "No manifest was written, so this snapshot cannot be re-checked; regenerate with the manifest artifact enabled before trusting it."
11661
+ );
11662
+ lines.push(
11663
+ "",
11664
+ "## AI Agent Ingestion Guide",
11665
+ "",
11666
+ ...readOrder.map((step, index) => `${index + 1}. ${step}`),
11667
+ ""
11497
11668
  );
11498
- lines.push("", "## AI Agent Ingestion Guide", "", ...readOrder, "");
11499
11669
  return lines.join("\n");
11500
11670
  }
11501
11671
 
@@ -11726,9 +11896,11 @@ function isPrivateIPv6(groups) {
11726
11896
  ]);
11727
11897
  if (allZeroThrough(5) && sixth === 65535) return mapped(6);
11728
11898
  if (allZeroThrough(6) && (seventh !== 0 || eighth !== 0)) return mapped(6);
11899
+ if (allZeroThrough(4) && fifth === 65535 && sixth === 0) return mapped(6);
11729
11900
  if (first === 100 && second === 65435 && third === 0 && fourth === 0 && fifth === 0 && sixth === 0) {
11730
11901
  return mapped(6);
11731
11902
  }
11903
+ if (first === 100 && second === 65435 && third === 1) return mapped(6);
11732
11904
  if (first === 8194) return mapped(1);
11733
11905
  return false;
11734
11906
  }
@@ -11842,61 +12014,69 @@ async function cloneRepository(source, options) {
11842
12014
  const dest = path15.resolve(options.dest);
11843
12015
  fs15.rmSync(dest, { recursive: true, force: true });
11844
12016
  fs15.mkdirSync(dest, { recursive: true });
11845
- const ref = options.ref ?? source.ref;
11846
- const args = [
11847
- "-c",
11848
- "http.followRedirects=false",
11849
- ...source.kind === "https" ? ["-c", "protocol.file.allow=never", "-c", "protocol.ssh.allow=never"] : [],
11850
- "clone",
11851
- "--depth",
11852
- "1",
11853
- "--single-branch",
11854
- "--no-tags",
11855
- "--quiet"
11856
- ];
11857
- if (ref !== void 0 && ref !== null && ref !== "") {
11858
- args.push("--branch", ref);
11859
- }
11860
- args.push(source.url, dest);
11861
- log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
11862
- const started = Date.now();
11863
- const result = spawnSync3("git", args, {
11864
- env: {
11865
- ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
11866
- ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
11867
- },
11868
- timeout: options.timeoutMs ?? 18e4,
11869
- encoding: "utf8",
11870
- windowsHide: true
11871
- });
11872
- if (result.error !== void 0 && result.error !== null) {
11873
- throw new Error("git clone could not run: " + result.error.message);
11874
- }
11875
- if (result.status !== 0) {
11876
- const detail = (result.stderr ?? "").trim().split("\n").slice(-3).join(" ");
11877
- throw new Error("git clone failed (exit " + result.status + "): " + (detail || "no output"));
11878
- }
11879
- const head = spawnSync3("git", ["-C", dest, "rev-parse", "HEAD"], { encoding: "utf8", windowsHide: true });
11880
- const commit = head.status === 0 ? (head.stdout ?? "").trim() : "";
11881
- if (commit === "") throw new Error("the clone has no HEAD; refusing to describe it");
11882
- const bytes = directorySize(dest);
11883
- log("clone: " + (bytes / 1024 / 1024).toFixed(1) + " MB in " + ((Date.now() - started) / 1e3).toFixed(1) + "s");
11884
- if (bytes > 1e9) {
11885
- throw new Error("the clone is larger than 1 GB (" + Math.round(bytes / 1024 / 1024) + " MB); refusing to scan it");
11886
- }
11887
- return {
11888
- directory: dest,
11889
- commit,
11890
- provenance: {
11891
- url: source.url,
11892
- host: source.host,
11893
- owner: source.owner,
11894
- repo: source.repo,
11895
- ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
12017
+ try {
12018
+ const ref = options.ref ?? source.ref;
12019
+ const args = [
12020
+ "-c",
12021
+ "http.followRedirects=false",
12022
+ ...source.kind === "https" ? ["-c", "protocol.file.allow=never", "-c", "protocol.ssh.allow=never"] : [],
12023
+ "clone",
12024
+ "--depth",
12025
+ "1",
12026
+ "--single-branch",
12027
+ "--no-tags",
12028
+ "--quiet"
12029
+ ];
12030
+ if (ref !== void 0 && ref !== null && ref !== "") {
12031
+ args.push("--branch", ref);
12032
+ }
12033
+ args.push(source.url, dest);
12034
+ log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
12035
+ const started = Date.now();
12036
+ const result = spawnSync3("git", args, {
12037
+ env: {
12038
+ ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
12039
+ ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
12040
+ },
12041
+ timeout: options.timeoutMs ?? 18e4,
12042
+ encoding: "utf8",
12043
+ windowsHide: true
12044
+ });
12045
+ if (result.error !== void 0 && result.error !== null) {
12046
+ throw new Error("git clone could not run: " + result.error.message);
12047
+ }
12048
+ if (result.status !== 0) {
12049
+ const detail = (result.stderr ?? "").trim().split("\n").slice(-3).join(" ");
12050
+ throw new Error("git clone failed (exit " + result.status + "): " + (detail || "no output"));
12051
+ }
12052
+ const head = spawnSync3("git", ["-C", dest, "rev-parse", "HEAD"], { encoding: "utf8", windowsHide: true });
12053
+ const commit = head.status === 0 ? (head.stdout ?? "").trim() : "";
12054
+ if (commit === "") throw new Error("the clone has no HEAD; refusing to describe it");
12055
+ const bytes = directorySize(dest);
12056
+ log("clone: " + (bytes / 1024 / 1024).toFixed(1) + " MB in " + ((Date.now() - started) / 1e3).toFixed(1) + "s");
12057
+ if (bytes > 1e9) {
12058
+ throw new Error("the clone is larger than 1 GB (" + Math.round(bytes / 1024 / 1024) + " MB); refusing to scan it");
12059
+ }
12060
+ return {
12061
+ directory: dest,
11896
12062
  commit,
11897
- fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
12063
+ provenance: {
12064
+ url: source.url,
12065
+ host: source.host,
12066
+ owner: source.owner,
12067
+ repo: source.repo,
12068
+ ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
12069
+ commit,
12070
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
12071
+ }
12072
+ };
12073
+ } catch (error) {
12074
+ try {
12075
+ fs15.rmSync(dest, { recursive: true, force: true });
12076
+ } catch {
11898
12077
  }
11899
- };
12078
+ throw error;
12079
+ }
11900
12080
  }
11901
12081
  function directorySize(root) {
11902
12082
  let total = 0;
@@ -11928,8 +12108,8 @@ function makeCloneDirectory() {
11928
12108
 
11929
12109
  // src/web/server.ts
11930
12110
  import * as http from "http";
11931
- import * as fs21 from "fs";
11932
- import * as path22 from "path";
12111
+ import * as fs22 from "fs";
12112
+ import * as path23 from "path";
11933
12113
  import { randomBytes, timingSafeEqual } from "crypto";
11934
12114
 
11935
12115
  // src/mcp/instructions.ts
@@ -12133,12 +12313,12 @@ function negotiateLegacyVersion(requested) {
12133
12313
  }
12134
12314
 
12135
12315
  // src/mcp/resources.ts
12136
- import * as fs19 from "fs";
12137
- import * as path20 from "path";
12316
+ import * as fs20 from "fs";
12317
+ import * as path21 from "path";
12138
12318
 
12139
12319
  // src/mcp/tools.ts
12140
- import * as fs18 from "fs";
12141
- import * as path19 from "path";
12320
+ import * as fs19 from "fs";
12321
+ import * as path20 from "path";
12142
12322
 
12143
12323
  // src/auditor/health.ts
12144
12324
  import * as fs16 from "fs";
@@ -12226,8 +12406,8 @@ function findSection(sections, relativePath) {
12226
12406
  if (exact) return exact;
12227
12407
  const foldedPath = rendered.toLowerCase();
12228
12408
  const folded = sections.filter((section) => {
12229
- const path28 = section.path.toLowerCase();
12230
- return path28 === relativePath.toLowerCase() || path28 === foldedPath;
12409
+ const path29 = section.path.toLowerCase();
12410
+ return path29 === relativePath.toLowerCase() || path29 === foldedPath;
12231
12411
  });
12232
12412
  return folded.length === 1 ? folded[0] : null;
12233
12413
  }
@@ -12284,9 +12464,9 @@ function walk(dir, prefix = "") {
12284
12464
  }
12285
12465
  const files = [];
12286
12466
  for (const entry of entries) {
12287
- const relative16 = prefix === "" ? entry.name : prefix + "/" + entry.name;
12288
- if (entry.isDirectory()) files.push(...walk(path16.join(dir, entry.name), relative16));
12289
- else if (entry.isFile()) files.push(relative16);
12467
+ const relative17 = prefix === "" ? entry.name : prefix + "/" + entry.name;
12468
+ if (entry.isDirectory()) files.push(...walk(path16.join(dir, entry.name), relative17));
12469
+ else if (entry.isFile()) files.push(relative17);
12290
12470
  }
12291
12471
  return files;
12292
12472
  }
@@ -12326,9 +12506,9 @@ function secretTokens(text2) {
12326
12506
  }
12327
12507
  function readArtifactTexts(snapshotDir) {
12328
12508
  const texts = [];
12329
- for (const relative16 of walk(snapshotDir)) {
12330
- if (!TEXT_ARTIFACT.test(relative16)) continue;
12331
- const text2 = readText2(path16.join(snapshotDir, relative16));
12509
+ for (const relative17 of walk(snapshotDir)) {
12510
+ if (!TEXT_ARTIFACT.test(relative17)) continue;
12511
+ const text2 = readText2(path16.join(snapshotDir, relative17));
12332
12512
  if (text2 !== null) texts.push(text2);
12333
12513
  }
12334
12514
  return texts;
@@ -12344,15 +12524,15 @@ function findHostPaths(snapshotDir, repoDir) {
12344
12524
  ];
12345
12525
  const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
12346
12526
  const hits = /* @__PURE__ */ new Set();
12347
- for (const relative16 of walk(snapshotDir)) {
12348
- if (!TEXT_ARTIFACT.test(relative16)) continue;
12349
- const text2 = readText2(path16.join(snapshotDir, relative16));
12527
+ for (const relative17 of walk(snapshotDir)) {
12528
+ if (!TEXT_ARTIFACT.test(relative17)) continue;
12529
+ const text2 = readText2(path16.join(snapshotDir, relative17));
12350
12530
  if (text2 === null) continue;
12351
12531
  for (const pattern of patterns) {
12352
- for (const match of text2.match(pattern) ?? []) hits.add(relative16 + ": " + match);
12532
+ for (const match of text2.match(pattern) ?? []) hits.add(relative17 + ": " + match);
12353
12533
  }
12354
12534
  repoPattern.lastIndex = 0;
12355
- if (repoPattern.test(text2)) hits.add(relative16 + ": the repository absolute path");
12535
+ if (repoPattern.test(text2)) hits.add(relative17 + ": the repository absolute path");
12356
12536
  }
12357
12537
  return [...hits];
12358
12538
  }
@@ -12599,13 +12779,13 @@ function auditSnapshot(options) {
12599
12779
  let artifactCount = 0;
12600
12780
  for (const [key, value] of Object.entries(artifacts)) {
12601
12781
  if (value === null || value === void 0) continue;
12602
- const relative16 = ARTIFACT_FILES[key];
12603
- if (relative16 === void 0) continue;
12782
+ const relative17 = ARTIFACT_FILES[key];
12783
+ if (relative17 === void 0) continue;
12604
12784
  artifactCount += 1;
12605
- const bytes = readBytes(path16.join(snapshotDir, relative16));
12606
- if (bytes === null) artifactProblems.push(relative16 + " is missing");
12785
+ const bytes = readBytes(path16.join(snapshotDir, relative17));
12786
+ if (bytes === null) artifactProblems.push(relative17 + " is missing");
12607
12787
  else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
12608
- artifactProblems.push(relative16 + " changed");
12788
+ artifactProblems.push(relative17 + " changed");
12609
12789
  }
12610
12790
  }
12611
12791
  checks.push(
@@ -13024,8 +13204,8 @@ function auditSnapshot(options) {
13024
13204
  for (const file of manifest.files) {
13025
13205
  if (!packed.has(file.relativePath)) problems.push(file.relativePath + " is in the manifest but not the pack");
13026
13206
  }
13027
- for (const path28 of packed) {
13028
- if (!known2.has(path28)) problems.push(path28 + " is in the pack but not the manifest");
13207
+ for (const path29 of packed) {
13208
+ if (!known2.has(path29)) problems.push(path29 + " is in the pack but not the manifest");
13029
13209
  }
13030
13210
  }
13031
13211
  }
@@ -13061,7 +13241,7 @@ function auditSnapshot(options) {
13061
13241
  bodyByPath.set(file.relativePath, section.body);
13062
13242
  bodiesChecked += 1;
13063
13243
  const bytes = Buffer.byteLength(section.body, "utf8");
13064
- const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
13244
+ const bodyLines = countBodyLines(section.body);
13065
13245
  if (bytes !== file.includedBytes) {
13066
13246
  bodyProblems.push(file.relativePath + ": manifest says " + file.includedBytes + " B, part holds " + bytes + " B");
13067
13247
  } else if (bodyLines !== file.includedLines) {
@@ -13335,25 +13515,25 @@ function auditSnapshot(options) {
13335
13515
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
13336
13516
  const leakHits = [];
13337
13517
  let scannedBytes = 0;
13338
- for (const relative16 of walk(snapshotDir)) {
13339
- if (!TEXT_ARTIFACT.test(relative16) || scannedBytes > scanBudget) continue;
13340
- if (relative16 === SIGNATURE_FILE) continue;
13341
- const text2 = readText2(path16.join(snapshotDir, relative16));
13518
+ for (const relative17 of walk(snapshotDir)) {
13519
+ if (!TEXT_ARTIFACT.test(relative17) || scannedBytes > scanBudget) continue;
13520
+ if (relative17 === SIGNATURE_FILE) continue;
13521
+ const text2 = readText2(path16.join(snapshotDir, relative17));
13342
13522
  if (text2 === null) continue;
13343
13523
  scannedBytes += Buffer.byteLength(text2, "utf8");
13344
13524
  let findingCount = 0;
13345
- if (/^parts[\\/].*\.md$/i.test(relative16)) {
13525
+ if (/^parts[\\/].*\.md$/i.test(relative17)) {
13346
13526
  let headerText = text2;
13347
13527
  for (const section of parsePartSections(text2)) {
13348
13528
  findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
13349
13529
  headerText = headerText.replace(section.body, "");
13350
13530
  }
13351
- findingCount += scanAndRedactSecrets(headerText, rules, relative16).findings.length;
13531
+ findingCount += scanAndRedactSecrets(headerText, rules, relative17).findings.length;
13352
13532
  } else {
13353
- findingCount = scanAndRedactSecrets(text2, rules, relative16).findings.length;
13533
+ findingCount = scanAndRedactSecrets(text2, rules, relative17).findings.length;
13354
13534
  }
13355
13535
  if (findingCount > 0) {
13356
- leakHits.push(relative16 + " (" + findingCount + " line(s))");
13536
+ leakHits.push(relative17 + " (" + findingCount + " line(s))");
13357
13537
  }
13358
13538
  }
13359
13539
  const signatureRecordPath = path16.join(snapshotDir, SIGNATURE_FILE);
@@ -13612,7 +13792,7 @@ const { parentPort, workerData } = require("node:worker_threads");
13612
13792
  })();
13613
13793
  `;
13614
13794
  function generateInWorker(cwd, cliOptions, options = {}) {
13615
- return new Promise((resolve15) => {
13795
+ return new Promise((resolve16) => {
13616
13796
  let settled = false;
13617
13797
  let worker = null;
13618
13798
  const finish = (result) => {
@@ -13623,7 +13803,7 @@ function generateInWorker(cwd, cliOptions, options = {}) {
13623
13803
  if (!result.ok && options.runId !== void 0 && options.lockRoots !== void 0) {
13624
13804
  releaseAbandonedRun(options.lockRoots, options.runId);
13625
13805
  }
13626
- resolve15(result);
13806
+ resolve16(result);
13627
13807
  });
13628
13808
  };
13629
13809
  const isCjs = typeof __dirname !== "undefined";
@@ -13694,45 +13874,105 @@ function windowText(body, fromLine, lineCount) {
13694
13874
  import { createHash as createHash8, randomUUID } from "crypto";
13695
13875
 
13696
13876
  // src/mcp/workspace.ts
13877
+ import * as fs18 from "fs";
13878
+ import * as path19 from "path";
13879
+
13880
+ // src/security/confine.ts
13697
13881
  import * as fs17 from "fs";
13698
13882
  import * as path18 from "path";
13883
+ function isInside2(parent, child) {
13884
+ const relative17 = path18.relative(parent, child);
13885
+ return relative17 === "" || !relative17.startsWith("..") && !path18.isAbsolute(relative17);
13886
+ }
13887
+ function readConfinedText(baseDir, relativePath) {
13888
+ if (relativePath.length === 0 || relativePath.includes("\0")) {
13889
+ return { ok: false, reason: "not-file", message: "the file name is empty or contains a NUL byte" };
13890
+ }
13891
+ if (path18.isAbsolute(relativePath)) {
13892
+ return { ok: false, reason: "outside", message: "an absolute path is not a snapshot-relative file" };
13893
+ }
13894
+ let baseReal;
13895
+ try {
13896
+ baseReal = fs17.realpathSync(path18.resolve(baseDir));
13897
+ } catch {
13898
+ return { ok: false, reason: "missing", message: "the snapshot directory does not exist" };
13899
+ }
13900
+ const candidate = path18.resolve(baseReal, relativePath);
13901
+ if (!isInside2(baseReal, candidate)) {
13902
+ return { ok: false, reason: "outside", message: "the path resolves outside the snapshot directory" };
13903
+ }
13904
+ let stats;
13905
+ try {
13906
+ stats = fs17.lstatSync(candidate);
13907
+ } catch (error) {
13908
+ const code = error.code;
13909
+ return {
13910
+ ok: false,
13911
+ reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unreadable",
13912
+ message: code === "ENOENT" || code === "ENOTDIR" ? "the file does not exist" : "the file could not be inspected"
13913
+ };
13914
+ }
13915
+ if (stats.isSymbolicLink()) {
13916
+ return { ok: false, reason: "not-file", message: "the file is a symbolic link" };
13917
+ }
13918
+ if (!stats.isFile()) {
13919
+ return { ok: false, reason: "not-file", message: "the path is not a regular file" };
13920
+ }
13921
+ let real;
13922
+ try {
13923
+ real = fs17.realpathSync(candidate);
13924
+ } catch {
13925
+ return { ok: false, reason: "unreadable", message: "the file could not be resolved" };
13926
+ }
13927
+ if (!isInside2(baseReal, real)) {
13928
+ return { ok: false, reason: "outside", message: "the file resolves outside the snapshot directory" };
13929
+ }
13930
+ try {
13931
+ const text2 = fs17.readFileSync(real, "utf8");
13932
+ return { ok: true, text: text2, path: real, stats: fs17.statSync(real) };
13933
+ } catch {
13934
+ return { ok: false, reason: "unreadable", message: "the file could not be read" };
13935
+ }
13936
+ }
13937
+
13938
+ // src/mcp/workspace.ts
13699
13939
  function foldForComparison(value) {
13700
13940
  return process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
13701
13941
  }
13702
13942
  function canonicalPath(value) {
13703
- const absolute = path18.resolve(value);
13943
+ const absolute = path19.resolve(value);
13704
13944
  try {
13705
- return fs17.realpathSync(absolute);
13945
+ return fs18.realpathSync(absolute);
13706
13946
  } catch {
13707
13947
  return absolute;
13708
13948
  }
13709
13949
  }
13710
- function isInside2(parent, child) {
13950
+ function isInside3(parent, child) {
13711
13951
  const foldedParent = foldForComparison(parent);
13712
13952
  const foldedChild = foldForComparison(child);
13713
- return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path18.sep}`);
13953
+ return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path19.sep}`);
13714
13954
  }
13715
13955
  function resolveThroughExistingAncestor(target) {
13716
13956
  let existing = target;
13717
13957
  const missing = [];
13718
- while (!fs17.existsSync(existing)) {
13719
- missing.unshift(path18.basename(existing));
13720
- const parent = path18.dirname(existing);
13958
+ while (!fs18.existsSync(existing)) {
13959
+ missing.unshift(path19.basename(existing));
13960
+ const parent = path19.dirname(existing);
13721
13961
  if (parent === existing) break;
13722
13962
  existing = parent;
13723
13963
  }
13724
13964
  const resolved = canonicalPath(existing);
13725
- return missing.length === 0 ? resolved : path18.join(resolved, ...missing);
13965
+ return missing.length === 0 ? resolved : path19.join(resolved, ...missing);
13726
13966
  }
13727
13967
  function resolveRoot(requested, context) {
13728
13968
  if (requested !== void 0 && (typeof requested !== "string" || requested.trim().length === 0)) {
13729
13969
  return { ok: false, message: '"root" must be a non-empty string when provided.' };
13730
13970
  }
13731
13971
  const wanted = typeof requested === "string" ? requested.trim() : context.cwd;
13732
- const absolute = path18.resolve(context.cwd, wanted);
13972
+ const absolute = path19.resolve(context.cwd, wanted);
13733
13973
  let stats;
13734
13974
  try {
13735
- stats = fs17.statSync(absolute);
13975
+ stats = fs18.statSync(absolute);
13736
13976
  } catch {
13737
13977
  return { ok: false, message: `"${wanted}" does not exist, so it cannot be a repository root.` };
13738
13978
  }
@@ -13741,7 +13981,7 @@ function resolveRoot(requested, context) {
13741
13981
  }
13742
13982
  const resolved = canonicalPath(absolute);
13743
13983
  for (const allowed of context.roots) {
13744
- if (isInside2(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
13984
+ if (isInside3(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
13745
13985
  }
13746
13986
  const shown = context.roots.join(", ");
13747
13987
  return {
@@ -13784,8 +14024,8 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
13784
14024
  }
13785
14025
  const requested = overrides.outDir.trim();
13786
14026
  const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
13787
- const resolved = resolveThroughExistingAncestor(path18.resolve(root, requested));
13788
- if (!permitted.some((allowed) => isInside2(canonicalPath(allowed), resolved))) {
14027
+ const resolved = resolveThroughExistingAncestor(path19.resolve(root, requested));
14028
+ if (!permitted.some((allowed) => isInside3(canonicalPath(allowed), resolved))) {
13789
14029
  const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
13790
14030
  return {
13791
14031
  ok: false,
@@ -13807,6 +14047,14 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
13807
14047
  if (overrides.sarif === true) cliOptions.sarif = true;
13808
14048
  if (overrides.staged === true) cliOptions.staged = true;
13809
14049
  if (overrides.withDependents === true) cliOptions.withDependents = true;
14050
+ for (const key of ["only", "ignore"]) {
14051
+ const value = overrides[key];
14052
+ if (value === void 0) continue;
14053
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
14054
+ return { ok: false, message: `"${key}" must be an array of glob strings.` };
14055
+ }
14056
+ cliOptions[key] = value;
14057
+ }
13810
14058
  try {
13811
14059
  const config = resolveConfig(loaded.config, cliOptions, root);
13812
14060
  return {
@@ -13826,25 +14074,25 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
13826
14074
  var MANIFEST_CACHE_LIMIT = 8;
13827
14075
  var manifestCache = /* @__PURE__ */ new Map();
13828
14076
  function manifestPathFor(workspace) {
13829
- return path18.resolve(workspace.root, workspace.config.outDir, "manifest.json");
14077
+ return path19.resolve(workspace.root, workspace.config.outDir, "manifest.json");
13830
14078
  }
13831
14079
  function partPathFor(workspace, filename) {
13832
14080
  if (filename.length === 0 || filename.includes("\0")) return null;
13833
- const partsDir = path18.resolve(workspace.root, workspace.config.outDir, "parts");
13834
- const resolved = path18.resolve(partsDir, filename);
13835
- const relative16 = path18.relative(partsDir, resolved);
13836
- if (relative16.length === 0 || relative16.includes(path18.sep) || relative16.includes("/") || relative16.includes("\\") || path18.isAbsolute(relative16)) {
14081
+ const partsDir = path19.resolve(workspace.root, workspace.config.outDir, "parts");
14082
+ const resolved = path19.resolve(partsDir, filename);
14083
+ const relative17 = path19.relative(partsDir, resolved);
14084
+ if (relative17.length === 0 || relative17.includes(path19.sep) || relative17.includes("/") || relative17.includes("\\") || path19.isAbsolute(relative17)) {
13837
14085
  return null;
13838
14086
  }
13839
14087
  let stats;
13840
14088
  try {
13841
- stats = fs17.lstatSync(resolved);
14089
+ stats = fs18.lstatSync(resolved);
13842
14090
  } catch {
13843
14091
  return null;
13844
14092
  }
13845
14093
  if (!stats.isFile()) return null;
13846
14094
  try {
13847
- if (path18.dirname(fs17.realpathSync(resolved)) !== fs17.realpathSync(partsDir)) return null;
14095
+ if (path19.dirname(fs18.realpathSync(resolved)) !== fs18.realpathSync(partsDir)) return null;
13848
14096
  } catch {
13849
14097
  return null;
13850
14098
  }
@@ -13852,31 +14100,28 @@ function partPathFor(workspace, filename) {
13852
14100
  }
13853
14101
  function readManifest3(workspace) {
13854
14102
  const file = manifestPathFor(workspace);
13855
- const shown = path18.relative(workspace.root, file).split(path18.sep).join("/") || file;
13856
- let stats;
13857
- try {
13858
- stats = fs17.statSync(file);
13859
- } catch {
14103
+ const shown = path19.relative(workspace.root, file).split(path19.sep).join("/") || file;
14104
+ const confined = readConfinedText(path19.dirname(file), path19.basename(file));
14105
+ if (!confined.ok) {
14106
+ if (confined.reason === "missing") {
14107
+ return {
14108
+ ok: false,
14109
+ missing: true,
14110
+ message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
14111
+ };
14112
+ }
13860
14113
  return {
13861
14114
  ok: false,
13862
- missing: true,
13863
- message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
14115
+ missing: false,
14116
+ message: `${shown} could not be read as a snapshot manifest: ${confined.message}.`
13864
14117
  };
13865
14118
  }
14119
+ const stats = confined.stats;
14120
+ const raw = confined.text;
13866
14121
  const cached = manifestCache.get(file);
13867
14122
  if (cached && cached.mtimeMs === stats.mtimeMs && cached.ctimeMs === stats.ctimeMs && cached.size === stats.size) {
13868
14123
  return { ok: true, manifest: cached.manifest, file };
13869
14124
  }
13870
- let raw;
13871
- try {
13872
- raw = fs17.readFileSync(file, "utf8");
13873
- } catch (error) {
13874
- return {
13875
- ok: false,
13876
- missing: false,
13877
- message: `${shown} exists but could not be read: ${error instanceof Error ? error.message : String(error)}`
13878
- };
13879
- }
13880
14125
  let parsed;
13881
14126
  try {
13882
14127
  parsed = JSON.parse(raw);
@@ -13906,6 +14151,96 @@ function forgetManifest(file) {
13906
14151
  manifestCache.delete(file);
13907
14152
  }
13908
14153
 
14154
+ // src/security/regex.ts
14155
+ var MAX_PATTERN_LENGTH = 256;
14156
+ var MAX_QUANTIFIER_REPEAT = 1e4;
14157
+ function unsafeRegExpReason(source) {
14158
+ if (source.length === 0) return null;
14159
+ if (source.length > MAX_PATTERN_LENGTH) {
14160
+ return `the pattern is longer than ${MAX_PATTERN_LENGTH} characters`;
14161
+ }
14162
+ let inClass = false;
14163
+ let unbounded = 0;
14164
+ const groups = [];
14165
+ for (let index = 0; index < source.length; index += 1) {
14166
+ const char = source[index];
14167
+ if (char === "\\") {
14168
+ index += 1;
14169
+ continue;
14170
+ }
14171
+ if (inClass) {
14172
+ if (char === "]") inClass = false;
14173
+ continue;
14174
+ }
14175
+ if (char === "[") {
14176
+ inClass = true;
14177
+ continue;
14178
+ }
14179
+ if (char === "(") {
14180
+ groups.push({ quantified: false, alternation: false });
14181
+ continue;
14182
+ }
14183
+ if (char === ")") {
14184
+ const group = groups.pop();
14185
+ if (group === void 0) continue;
14186
+ const next = source[index + 1];
14187
+ if (next === "*" || next === "+" || next === "{" && isUnboundedBrace(source, index + 1)) {
14188
+ if (group.quantified || group.alternation) {
14189
+ return "a quantified group contains another quantifier or an alternation";
14190
+ }
14191
+ }
14192
+ continue;
14193
+ }
14194
+ if (char === "|") {
14195
+ const group = groups[groups.length - 1];
14196
+ if (group !== void 0) group.alternation = true;
14197
+ continue;
14198
+ }
14199
+ if (char === "?") {
14200
+ const previous = source[index - 1];
14201
+ if (previous !== "(" && previous !== "?" && previous !== "*" && previous !== "+" && previous !== "}") {
14202
+ const group = groups[groups.length - 1];
14203
+ if (group !== void 0) group.quantified = true;
14204
+ }
14205
+ continue;
14206
+ }
14207
+ if (char === "*" || char === "+") {
14208
+ unbounded += 1;
14209
+ const group = groups[groups.length - 1];
14210
+ if (group !== void 0) group.quantified = true;
14211
+ continue;
14212
+ }
14213
+ if (char === "{") {
14214
+ const close = source.indexOf("}", index + 1);
14215
+ if (close === -1) continue;
14216
+ const body = source.slice(index + 1, close);
14217
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
14218
+ if (match === null) {
14219
+ index = close;
14220
+ continue;
14221
+ }
14222
+ const max = match[2] === void 0 ? Number(match[1]) : match[2] === "" ? Infinity : Number(match[2]);
14223
+ if (max > MAX_QUANTIFIER_REPEAT) {
14224
+ return "a repetition bound is larger than the search budget can evaluate safely";
14225
+ }
14226
+ if (max === Infinity) unbounded += 1;
14227
+ const group = groups[groups.length - 1];
14228
+ if (group !== void 0) group.quantified = true;
14229
+ index = close;
14230
+ }
14231
+ }
14232
+ if (unbounded > 1) {
14233
+ return "the pattern has more than one unbounded repetition";
14234
+ }
14235
+ return null;
14236
+ }
14237
+ function isUnboundedBrace(source, start) {
14238
+ const close = source.indexOf("}", start + 1);
14239
+ if (close === -1) return false;
14240
+ const body = source.slice(start + 1, close);
14241
+ return /^\d+,$/.test(body);
14242
+ }
14243
+
13909
14244
  // src/mcp/tools.ts
13910
14245
  var MAX_SEARCH_BYTES = 4 * 1024 * 1024;
13911
14246
  var READ_ONLY = {
@@ -13937,6 +14272,16 @@ var OUT_DIR_PROPERTY = {
13937
14272
  };
13938
14273
  var outDirOverride = (args) => ({ outDir: args.outDir });
13939
14274
  var SCOPE_PROPERTIES = {
14275
+ only: {
14276
+ type: "array",
14277
+ items: { type: "string" },
14278
+ description: "Globs to include: replaces the config allow-list for this run."
14279
+ },
14280
+ ignore: {
14281
+ type: "array",
14282
+ items: { type: "string" },
14283
+ description: "Globs to exclude, added to the config deny-list for this run."
14284
+ },
13940
14285
  maxPartTokens: {
13941
14286
  type: "string",
13942
14287
  description: 'Token ceiling per part, for example 32000 or "32k". Narrower than maxPartBytes; it converts at four bytes per token.'
@@ -13971,7 +14316,9 @@ function workspaceOverrides(args) {
13971
14316
  sarif: args.sarif,
13972
14317
  changedSince: args.changedSince,
13973
14318
  staged: args.staged,
13974
- withDependents: args.withDependents
14319
+ withDependents: args.withDependents,
14320
+ only: args.only,
14321
+ ignore: args.ignore
13975
14322
  };
13976
14323
  }
13977
14324
  function failure(message) {
@@ -13986,7 +14333,7 @@ function formatBytes2(bytes) {
13986
14333
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
13987
14334
  }
13988
14335
  function relativeFor(workspace, absolute) {
13989
- return path19.relative(workspace.root, absolute).split(path19.sep).join("/");
14336
+ return path20.relative(workspace.root, absolute).split(path20.sep).join("/");
13990
14337
  }
13991
14338
  function capped(values, limit = 20) {
13992
14339
  return { count: values.length, sample: values.slice(0, limit) };
@@ -14005,13 +14352,13 @@ function summarizeDrift(drift) {
14005
14352
  function toRelativePath(root, value) {
14006
14353
  const cleaned = value.trim();
14007
14354
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
14008
- const resolvedRoot = path19.resolve(root);
14009
- const absolute = path19.resolve(resolvedRoot, cleaned);
14010
- const relative16 = path19.relative(resolvedRoot, absolute);
14011
- if (relative16 === "" || relative16 === ".." || relative16.startsWith(`..${path19.sep}`) || path19.isAbsolute(relative16)) {
14355
+ const resolvedRoot = path20.resolve(root);
14356
+ const absolute = path20.resolve(resolvedRoot, cleaned);
14357
+ const relative17 = path20.relative(resolvedRoot, absolute);
14358
+ if (relative17 === "" || relative17 === ".." || relative17.startsWith(`..${path20.sep}`) || path20.isAbsolute(relative17)) {
14012
14359
  return null;
14013
14360
  }
14014
- return relative16.split(path19.sep).join("/");
14361
+ return relative17.split(path20.sep).join("/");
14015
14362
  }
14016
14363
  function symbolsOf(entry) {
14017
14364
  const summary = entry.summary;
@@ -14104,16 +14451,15 @@ var historyTool = {
14104
14451
  async handler(args, context) {
14105
14452
  const prepared = await prepare(args, context, outDirOverride(args));
14106
14453
  if (!prepared.ok) return prepared.outcome;
14107
- const reportPath = path19.resolve(prepared.workspace.root, prepared.workspace.config.outDir, "reports", "log.md");
14108
- let text2;
14109
- try {
14110
- text2 = fs18.readFileSync(reportPath, "utf8");
14111
- } catch {
14454
+ const snapshotDir = path20.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
14455
+ const reportRead = readConfinedText(snapshotDir, path20.posix.join("reports", "log.md"));
14456
+ if (!reportRead.ok) {
14112
14457
  return {
14113
- text: "This snapshot has no reports/log.md. Generate it with `snapshot_generate { includeLogs: 20 }`, or `generate --include-logs 20` on the command line; the report is opt-in because the commit subjects are repository content.",
14458
+ text: "This snapshot has no readable reports/log.md. Generate it with `snapshot_generate { includeLogs: 20 }`, or `generate --include-logs 20` on the command line; the report is opt-in because the commit subjects are repository content, and it must be a regular file inside the snapshot.",
14114
14459
  isError: true
14115
14460
  };
14116
14461
  }
14462
+ const text2 = reportRead.text;
14117
14463
  const manifestRead = readManifest3(prepared.workspace);
14118
14464
  const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
14119
14465
  if (recordedLog !== void 0 && recordedLog !== null) {
@@ -14174,7 +14520,7 @@ var budgetTool = {
14174
14520
  ...args.includeTests === true ? { includeTests: true } : {}
14175
14521
  });
14176
14522
  const paths = new Set(plan.files.map((file) => file.path));
14177
- const gained = [...paths].filter((path28) => !previous.has(path28)).sort();
14523
+ const gained = [...paths].filter((path29) => !previous.has(path29)).sort();
14178
14524
  previous = paths;
14179
14525
  rows.push({
14180
14526
  budget,
@@ -14277,20 +14623,16 @@ var workspaceTool = {
14277
14623
  async handler(args, context) {
14278
14624
  const prepared = await prepare(args, context, outDirOverride(args));
14279
14625
  if (!prepared.ok) return prepared.outcome;
14280
- const index = path19.resolve(
14281
- prepared.workspace.root,
14282
- prepared.workspace.config.outDir,
14283
- "WORKSPACE.json"
14284
- );
14285
- let text2;
14286
- try {
14287
- text2 = fs18.readFileSync(index, "utf8");
14288
- } catch {
14626
+ const snapshotDir = path20.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
14627
+ const index = path20.join(snapshotDir, "WORKSPACE.json");
14628
+ const read = readConfinedText(snapshotDir, "WORKSPACE.json");
14629
+ if (!read.ok) {
14289
14630
  return {
14290
- text: "No workspace index at " + index + ". Generate one with `generate --workspace member-a,member-b`; a single snapshot has no members to list.",
14631
+ text: "No workspace index at " + index + " (the file is absent, or it is not a regular file inside the snapshot). Generate one with `generate --workspace member-a,member-b`; a single snapshot has no members to list.",
14291
14632
  isError: true
14292
14633
  };
14293
14634
  }
14635
+ const text2 = read.text;
14294
14636
  const document = JSON.parse(text2);
14295
14637
  const members = document.members ?? [];
14296
14638
  const links = document.links ?? [];
@@ -14431,6 +14773,10 @@ var routesTool = {
14431
14773
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
14432
14774
  let filter = null;
14433
14775
  if (typeof args.pattern === "string") {
14776
+ const unsafe = unsafeRegExpReason(args.pattern);
14777
+ if (unsafe !== null) {
14778
+ return { text: "pattern is refused: " + unsafe + ".", isError: true };
14779
+ }
14434
14780
  try {
14435
14781
  filter = new RegExp(args.pattern, "i");
14436
14782
  } catch (error) {
@@ -14486,7 +14832,7 @@ var cyclesTool = {
14486
14832
  tsconfig: tsconfigPathsFor(prepared.workspace.root)
14487
14833
  });
14488
14834
  const edges = /* @__PURE__ */ new Map();
14489
- for (const path28 of byPath.keys()) edges.set(path28, []);
14835
+ for (const path29 of byPath.keys()) edges.set(path29, []);
14490
14836
  for (const entry of read.manifest.indexes.imports.byFile) {
14491
14837
  const targets = edges.get(entry.path);
14492
14838
  if (targets === void 0) continue;
@@ -14574,6 +14920,12 @@ var searchTool = {
14574
14920
  const cap = Math.max(1, Math.min(500, typeof args.maxMatches === "number" ? args.maxMatches : 50));
14575
14921
  const contextLines = Math.max(0, Math.min(10, typeof args.contextLines === "number" ? args.contextLines : 0));
14576
14922
  let pattern;
14923
+ if (args.regex === true) {
14924
+ const unsafe = unsafeRegExpReason(query);
14925
+ if (unsafe !== null) {
14926
+ return { text: "regex is refused: " + unsafe + ".", isError: true };
14927
+ }
14928
+ }
14577
14929
  try {
14578
14930
  pattern = args.regex === true ? new RegExp(query, "i") : new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
14579
14931
  } catch (error) {
@@ -14592,7 +14944,7 @@ var searchTool = {
14592
14944
  if (partPath === null) continue;
14593
14945
  let text2;
14594
14946
  try {
14595
- text2 = fs18.readFileSync(partPath, "utf8");
14947
+ text2 = fs19.readFileSync(partPath, "utf8");
14596
14948
  } catch {
14597
14949
  continue;
14598
14950
  }
@@ -14723,7 +15075,7 @@ var reviewTool = {
14723
15075
  return { text: error.message, isError: true };
14724
15076
  }
14725
15077
  const report2 = auditSnapshot({
14726
- snapshotDir: path19.resolve(workspace.root, workspace.config.outDir),
15078
+ snapshotDir: path20.resolve(workspace.root, workspace.config.outDir),
14727
15079
  repoDir: workspace.root
14728
15080
  });
14729
15081
  const failed = report2.checks.filter((check2) => check2.status === "fail").map((check2) => check2.id + ": " + check2.detail);
@@ -14745,7 +15097,7 @@ var reviewTool = {
14745
15097
  }
14746
15098
  let section = null;
14747
15099
  try {
14748
- section = findSection(parsePartSections(fs18.readFileSync(partPath, "utf8")), file.relativePath);
15100
+ section = findSection(parsePartSections(fs19.readFileSync(partPath, "utf8")), file.relativePath);
14749
15101
  } catch {
14750
15102
  section = null;
14751
15103
  }
@@ -14835,31 +15187,31 @@ var diffContextTool = {
14835
15187
  const changed = [];
14836
15188
  const text2 = [];
14837
15189
  let used = 0;
14838
- for (const path28 of wanted) {
14839
- const file = byPath.get(path28.toLowerCase());
15190
+ for (const path29 of wanted) {
15191
+ const file = byPath.get(path29.toLowerCase());
14840
15192
  if (file === void 0) {
14841
- missing.push(path28);
15193
+ missing.push(path29);
14842
15194
  continue;
14843
15195
  }
14844
15196
  const partPath = partPathFor(workspace, file.part);
14845
15197
  if (partPath === null) {
14846
- missing.push(path28 + " (part missing)");
15198
+ missing.push(path29 + " (part missing)");
14847
15199
  continue;
14848
15200
  }
14849
15201
  let section;
14850
15202
  try {
14851
- section = findSection(parsePartSections(fs18.readFileSync(partPath, "utf8")), file.relativePath);
15203
+ section = findSection(parsePartSections(fs19.readFileSync(partPath, "utf8")), file.relativePath);
14852
15204
  } catch {
14853
15205
  section = null;
14854
15206
  }
14855
15207
  if (section === null) {
14856
- missing.push(path28 + " (section not found)");
15208
+ missing.push(path29 + " (section not found)");
14857
15209
  continue;
14858
15210
  }
14859
15211
  const window = windowText(section.body, 1, linesPerFile);
14860
15212
  const tokens = Math.max(1, Math.ceil(Buffer.byteLength(window.text, "utf8") / 4));
14861
15213
  if (used + tokens > budget) {
14862
- missing.push(path28 + " (budget)");
15214
+ missing.push(path29 + " (budget)");
14863
15215
  continue;
14864
15216
  }
14865
15217
  used += tokens;
@@ -14934,7 +15286,7 @@ var symbolTool = {
14934
15286
  if (partPath === null) continue;
14935
15287
  let partText;
14936
15288
  try {
14937
- partText = fs18.readFileSync(partPath, "utf8");
15289
+ partText = fs19.readFileSync(partPath, "utf8");
14938
15290
  } catch {
14939
15291
  continue;
14940
15292
  }
@@ -14966,28 +15318,39 @@ var symbolTool = {
14966
15318
  };
14967
15319
  }
14968
15320
  const callSites = [];
15321
+ let referencesTruncated = false;
14969
15322
  if (args.references !== false) {
14970
15323
  const limit = Math.max(1, typeof args.maxReferences === "number" ? args.maxReferences : 20);
14971
15324
  const definitionKeys = new Set(matches.map((match) => match.path + ":" + match.line));
14972
15325
  const word = new RegExp("\\b" + name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b");
14973
- const parts = /* @__PURE__ */ new Map();
15326
+ const sectionsByPart = /* @__PURE__ */ new Map();
14974
15327
  let scanned = 0;
14975
15328
  for (const file of read.manifest.files) {
14976
15329
  if (callSites.length >= limit) break;
14977
15330
  const partPath = partPathFor(workspace, file.part);
14978
15331
  if (partPath === null) continue;
14979
- let partText = parts.get(partPath);
14980
- if (partText === void 0) {
15332
+ let sections = sectionsByPart.get(partPath);
15333
+ if (sections === void 0) {
15334
+ if (scanned >= MAX_SEARCH_BYTES) {
15335
+ referencesTruncated = true;
15336
+ break;
15337
+ }
15338
+ let partText;
14981
15339
  try {
14982
- partText = fs18.readFileSync(partPath, "utf8");
15340
+ partText = fs19.readFileSync(partPath, "utf8");
14983
15341
  } catch {
14984
15342
  continue;
14985
15343
  }
14986
- parts.set(partPath, partText);
15344
+ const bytes = Buffer.byteLength(partText, "utf8");
15345
+ if (scanned + bytes > MAX_SEARCH_BYTES) {
15346
+ referencesTruncated = true;
15347
+ break;
15348
+ }
15349
+ scanned += bytes;
15350
+ sections = parsePartSections(partText);
15351
+ sectionsByPart.set(partPath, sections);
14987
15352
  }
14988
- if (scanned > MAX_SEARCH_BYTES) break;
14989
- scanned += Buffer.byteLength(partText, "utf8");
14990
- const section = findSection(parsePartSections(partText), file.relativePath);
15353
+ const section = findSection(sections, file.relativePath);
14991
15354
  if (section === null) continue;
14992
15355
  const bodyLines = section.body.split("\n");
14993
15356
  for (let index = 0; index < bodyLines.length && callSites.length < limit; index += 1) {
@@ -15001,8 +15364,11 @@ var symbolTool = {
15001
15364
  }
15002
15365
  }
15003
15366
  }
15004
- const text2 = matches.map((match) => "### " + match.path + " (" + match.part + ", line " + match.line + ")\n" + match.text).join("\n\n") + (args.references === false ? "" : "\n\n" + (callSites.length === 0 ? "No call site was found in the snapshot." : "Call sites (" + callSites.length + "):\n" + callSites.map((site) => " " + site.path + ":" + site.line + " " + site.text).join("\n")));
15005
- return { text: text2, structured: { found: matches.length, matches, references: callSites } };
15367
+ const text2 = matches.map((match) => "### " + match.path + " (" + match.part + ", line " + match.line + ")\n" + match.text).join("\n\n") + (args.references === false ? "" : "\n\n" + (callSites.length === 0 ? "No call site was found in the snapshot." : "Call sites (" + callSites.length + "):\n" + callSites.map((site) => " " + site.path + ":" + site.line + " " + site.text).join("\n"))) + (referencesTruncated ? "\n\nSearch stopped at the 4 MB part budget; call sites in later parts were not read. Narrow the name or inspect the remaining parts directly." : "");
15368
+ return {
15369
+ text: text2,
15370
+ structured: { found: matches.length, matches, references: callSites, truncated: referencesTruncated }
15371
+ };
15006
15372
  }
15007
15373
  };
15008
15374
  var contextTool = {
@@ -15075,7 +15441,7 @@ var contextTool = {
15075
15441
  }
15076
15442
  if (!sectionsByPart.has(file.part)) {
15077
15443
  try {
15078
- sectionsByPart.set(file.part, parsePartSections(fs18.readFileSync(partPath, "utf8")));
15444
+ sectionsByPart.set(file.part, parsePartSections(fs19.readFileSync(partPath, "utf8")));
15079
15445
  } catch {
15080
15446
  sectionsByPart.set(file.part, null);
15081
15447
  }
@@ -15160,6 +15526,10 @@ var queryTool = {
15160
15526
  const maxFiles = typeof args.maxFiles === "number" ? Math.min(200, Math.max(1, args.maxFiles)) : 40;
15161
15527
  let pattern = null;
15162
15528
  if (typeof args.pathPattern === "string") {
15529
+ const unsafe = unsafeRegExpReason(args.pathPattern);
15530
+ if (unsafe !== null) {
15531
+ return { text: "pathPattern is refused: " + unsafe + ".", isError: true };
15532
+ }
15163
15533
  try {
15164
15534
  pattern = new RegExp(args.pathPattern, "i");
15165
15535
  } catch (error) {
@@ -15309,7 +15679,7 @@ var answerTool = {
15309
15679
  let partText = parts.get(partPath);
15310
15680
  if (partText === void 0) {
15311
15681
  try {
15312
- partText = fs18.readFileSync(partPath, "utf8");
15682
+ partText = fs19.readFileSync(partPath, "utf8");
15313
15683
  } catch {
15314
15684
  omitted.push({ path: planned.path, reason: "its part could not be read" });
15315
15685
  continue;
@@ -15406,7 +15776,7 @@ var healthTool = {
15406
15776
  if (!prepared.ok) return prepared.outcome;
15407
15777
  const workspace = prepared.workspace;
15408
15778
  const report2 = auditSnapshot({
15409
- snapshotDir: path19.resolve(workspace.root, workspace.config.outDir),
15779
+ snapshotDir: path20.resolve(workspace.root, workspace.config.outDir),
15410
15780
  repoDir: workspace.root,
15411
15781
  ...typeof args.maxScanBytes === "number" ? { maxScanBytes: args.maxScanBytes } : {},
15412
15782
  ...args.deep === true ? { deep: true } : {}
@@ -15635,16 +16005,6 @@ var generateTool = {
15635
16005
  minimum: 500,
15636
16006
  description: "Fit the snapshot into this token budget, highest value first."
15637
16007
  },
15638
- only: {
15639
- type: "array",
15640
- items: { type: "string" },
15641
- description: "Globs to include: replaces the config allow-list for this run."
15642
- },
15643
- ignore: {
15644
- type: "array",
15645
- items: { type: "string" },
15646
- description: "Globs to exclude, added to the config deny-list for this run."
15647
- },
15648
16008
  ...SCOPE_PROPERTIES
15649
16009
  },
15650
16010
  additionalProperties: false
@@ -15700,7 +16060,7 @@ var generateTool = {
15700
16060
  context.notify?.({ message: "writing the snapshot", progress: 2, total: 2 });
15701
16061
  const summary = result.summary;
15702
16062
  forgetManifest(manifestPathFor(workspace));
15703
- const written = relativeFor(workspace, path19.resolve(workspace.root, workspace.config.outDir));
16063
+ const written = relativeFor(workspace, path20.resolve(workspace.root, workspace.config.outDir));
15704
16064
  const lines = [
15705
16065
  `Wrote ${written}/`,
15706
16066
  `Files: ${summary.totalFiles} included, ${summary.skippedCount} skipped, ${plural(summary.partsCount, "part")}`,
@@ -16145,7 +16505,7 @@ var readTool = {
16145
16505
  }
16146
16506
  let partText;
16147
16507
  try {
16148
- partText = fs18.readFileSync(partPath, "utf8");
16508
+ partText = fs19.readFileSync(partPath, "utf8");
16149
16509
  } catch {
16150
16510
  return failure(
16151
16511
  `${entry.part} could not be read, so the snapshot is damaged. Run snapshot_generate to rebuild it.`
@@ -17823,7 +18183,7 @@ async function workspaceFor(context) {
17823
18183
  }
17824
18184
  function readFileIfPresent(file) {
17825
18185
  try {
17826
- return fs19.readFileSync(file, "utf8");
18186
+ return fs20.readFileSync(file, "utf8");
17827
18187
  } catch {
17828
18188
  return null;
17829
18189
  }
@@ -17862,9 +18222,9 @@ function buildResourceProvider() {
17862
18222
  }
17863
18223
  ];
17864
18224
  const workspace = await workspaceFor(context);
17865
- const reportsDir = "error" in workspace ? null : path20.resolve(workspace.root, workspace.config.outDir, "reports");
18225
+ const reportsDir = "error" in workspace ? null : path21.resolve(workspace.root, workspace.config.outDir, "reports");
17866
18226
  for (const [uri, report2] of REPORT_URIS) {
17867
- const present = reportsDir !== null && fs19.existsSync(path20.join(reportsDir, report2.file));
18227
+ const present = reportsDir !== null && fs20.existsSync(path21.join(reportsDir, report2.file));
17868
18228
  if (!present) continue;
17869
18229
  resources.push({
17870
18230
  uri,
@@ -17926,36 +18286,46 @@ function buildResourceProvider() {
17926
18286
  }
17927
18287
  const workspace = await workspaceFor(context);
17928
18288
  if ("error" in workspace) return null;
18289
+ const snapshotDir = path21.resolve(workspace.root, workspace.config.outDir);
17929
18290
  if (uri === PROMPT_URI) {
17930
- const text2 = readFileIfPresent(
17931
- path20.resolve(workspace.root, workspace.config.outDir, "PROMPT.md")
17932
- );
17933
- if (text2 === null) {
18291
+ const read = readConfinedText(snapshotDir, "PROMPT.md");
18292
+ if (!read.ok) {
17934
18293
  throw new ResourceNotFoundError(
17935
18294
  uri,
17936
- "This snapshot contains no PROMPT.md: the prompt artifact was disabled (artifacts.prompt = false or --skip-artifacts prompt), or nothing has been generated yet. Run snapshot_generate first."
18295
+ "This snapshot contains no readable PROMPT.md: the prompt artifact was disabled (artifacts.prompt = false or --skip-artifacts prompt), nothing has been generated yet, or the file is not a regular file inside the snapshot. Run snapshot_generate first."
17937
18296
  );
17938
18297
  }
17939
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, PROMPT_ADVICE) };
18298
+ return {
18299
+ uri,
18300
+ mimeType: "text/markdown",
18301
+ text: ensureSingleRead(uri, read.text, PROMPT_ADVICE)
18302
+ };
17940
18303
  }
17941
18304
  const report2 = REPORT_URIS.get(uri);
17942
18305
  if (report2) {
17943
- const text2 = readFileIfPresent(
17944
- path20.resolve(workspace.root, workspace.config.outDir, "reports", report2.file)
17945
- );
17946
- if (text2 === null) {
18306
+ const read = readConfinedText(snapshotDir, path21.posix.join("reports", report2.file));
18307
+ if (!read.ok) {
17947
18308
  throw new ResourceNotFoundError(
17948
18309
  uri,
17949
- "This snapshot contains no " + report2.file + ": that report was disabled, or nothing has been generated yet. Run snapshot_generate first."
18310
+ "This snapshot contains no readable " + report2.file + ": that report was disabled, nothing has been generated yet, or the file is not a regular file inside the snapshot. Run snapshot_generate first."
17950
18311
  );
17951
18312
  }
17952
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, REPORT_ADVICE) };
18313
+ return {
18314
+ uri,
18315
+ mimeType: "text/markdown",
18316
+ text: ensureSingleRead(uri, read.text, REPORT_ADVICE)
18317
+ };
17953
18318
  }
17954
18319
  if (uri === "snapshot://manifest") {
17955
18320
  const read = readManifest3(workspace);
17956
18321
  if (!read.ok) return null;
17957
- const text2 = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
17958
- return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text2, MANIFEST_ADVICE) };
18322
+ const confined = readConfinedText(path21.dirname(read.file), path21.basename(read.file));
18323
+ if (!confined.ok) return null;
18324
+ return {
18325
+ uri,
18326
+ mimeType: "application/json",
18327
+ text: ensureSingleRead(uri, confined.text, MANIFEST_ADVICE)
18328
+ };
17959
18329
  }
17960
18330
  const partMatch = PART_URI.exec(uri);
17961
18331
  if (partMatch) {
@@ -17968,7 +18338,7 @@ function buildResourceProvider() {
17968
18338
  if (partPath === null) return null;
17969
18339
  let partBytes;
17970
18340
  try {
17971
- partBytes = fs19.statSync(partPath).size;
18341
+ partBytes = fs20.statSync(partPath).size;
17972
18342
  } catch {
17973
18343
  return null;
17974
18344
  }
@@ -18004,52 +18374,52 @@ function validateArguments(schema, value) {
18004
18374
  }
18005
18375
  return problems;
18006
18376
  }
18007
- function checkValue(path28, schema, value) {
18377
+ function checkValue(path29, schema, value) {
18008
18378
  if (schema.enum && !schema.enum.includes(value)) {
18009
- return [`"${path28}" must be one of: ${schema.enum.join(", ")}`];
18379
+ return [`"${path29}" must be one of: ${schema.enum.join(", ")}`];
18010
18380
  }
18011
18381
  switch (schema.type) {
18012
18382
  case "string": {
18013
- if (typeof value !== "string") return [`"${path28}" must be a string`];
18383
+ if (typeof value !== "string") return [`"${path29}" must be a string`];
18014
18384
  const problems = [];
18015
18385
  if (schema.minLength !== void 0 && value.length < schema.minLength) {
18016
- problems.push(`"${path28}" must be at least ${schema.minLength} character(s)`);
18386
+ problems.push(`"${path29}" must be at least ${schema.minLength} character(s)`);
18017
18387
  }
18018
18388
  if (schema.maxLength !== void 0 && value.length > schema.maxLength) {
18019
- problems.push(`"${path28}" must be at most ${schema.maxLength} character(s)`);
18389
+ problems.push(`"${path29}" must be at most ${schema.maxLength} character(s)`);
18020
18390
  }
18021
18391
  return problems;
18022
18392
  }
18023
18393
  case "number":
18024
18394
  case "integer": {
18025
18395
  if (typeof value !== "number" || Number.isNaN(value)) {
18026
- return [`"${path28}" must be a number`];
18396
+ return [`"${path29}" must be a number`];
18027
18397
  }
18028
18398
  if (schema.type === "integer" && !Number.isInteger(value)) {
18029
- return [`"${path28}" must be an integer`];
18399
+ return [`"${path29}" must be an integer`];
18030
18400
  }
18031
18401
  const problems = [];
18032
18402
  if (schema.minimum !== void 0 && value < schema.minimum) {
18033
- problems.push(`"${path28}" must be >= ${schema.minimum}`);
18403
+ problems.push(`"${path29}" must be >= ${schema.minimum}`);
18034
18404
  }
18035
18405
  if (schema.maximum !== void 0 && value > schema.maximum) {
18036
- problems.push(`"${path28}" must be <= ${schema.maximum}`);
18406
+ problems.push(`"${path29}" must be <= ${schema.maximum}`);
18037
18407
  }
18038
18408
  return problems;
18039
18409
  }
18040
18410
  case "boolean":
18041
- return typeof value === "boolean" ? [] : [`"${path28}" must be a boolean`];
18411
+ return typeof value === "boolean" ? [] : [`"${path29}" must be a boolean`];
18042
18412
  case "array": {
18043
- if (!Array.isArray(value)) return [`"${path28}" must be an array`];
18413
+ if (!Array.isArray(value)) return [`"${path29}" must be an array`];
18044
18414
  if (!schema.items) return [];
18045
18415
  const problems = [];
18046
18416
  value.forEach((item, index) => {
18047
- problems.push(...checkValue(`${path28}[${index}]`, schema.items, item));
18417
+ problems.push(...checkValue(`${path29}[${index}]`, schema.items, item));
18048
18418
  });
18049
18419
  return problems;
18050
18420
  }
18051
18421
  case "object":
18052
- return isJsonObject(value) ? [] : [`"${path28}" must be an object`];
18422
+ return isJsonObject(value) ? [] : [`"${path29}" must be an object`];
18053
18423
  default:
18054
18424
  return [];
18055
18425
  }
@@ -18417,11 +18787,11 @@ var MAX_LINE_BYTES = 32 * 1024 * 1024;
18417
18787
  function createWriter(output) {
18418
18788
  return {
18419
18789
  write(value) {
18420
- return new Promise((resolve15, reject) => {
18790
+ return new Promise((resolve16, reject) => {
18421
18791
  output.write(`${JSON.stringify(value)}
18422
18792
  `, (error) => {
18423
18793
  if (error) reject(error);
18424
- else resolve15();
18794
+ else resolve16();
18425
18795
  });
18426
18796
  });
18427
18797
  }
@@ -18560,12 +18930,12 @@ async function runStdioServer(options) {
18560
18930
  });
18561
18931
  return writeChain;
18562
18932
  };
18563
- const MAX_IN_FLIGHT = 4;
18933
+ const MAX_IN_FLIGHT2 = 4;
18564
18934
  let inFlight = 0;
18565
18935
  let inputEnded = false;
18566
18936
  let resolveDone = () => void 0;
18567
- const finished = new Promise((resolve15) => {
18568
- resolveDone = resolve15;
18937
+ const finished = new Promise((resolve16) => {
18938
+ resolveDone = resolve16;
18569
18939
  });
18570
18940
  const finishIfIdle = () => {
18571
18941
  if (inputEnded && inFlight === 0) resolveDone(0);
@@ -18595,14 +18965,14 @@ async function runStdioServer(options) {
18595
18965
  errorResponse(
18596
18966
  id,
18597
18967
  ERROR_CODES.overloaded,
18598
- `The server is already handling ${MAX_IN_FLIGHT} requests; retry this one when it is free.`
18968
+ `The server is already handling ${MAX_IN_FLIGHT2} requests; retry this one when it is free.`
18599
18969
  )
18600
18970
  );
18601
18971
  };
18602
18972
  const stopReading = createLineReader(process.stdin, {
18603
18973
  onOverflow: (bytes) => log(`mcp: discarded an oversized message (${bytes} bytes)`),
18604
18974
  onLine: (line) => {
18605
- if (inFlight >= MAX_IN_FLIGHT) {
18975
+ if (inFlight >= MAX_IN_FLIGHT2) {
18606
18976
  rejectOverloaded(line);
18607
18977
  return;
18608
18978
  }
@@ -18629,8 +18999,8 @@ async function runStdioServer(options) {
18629
18999
  }
18630
19000
 
18631
19001
  // src/web/zip.ts
18632
- import * as fs20 from "fs";
18633
- import * as path21 from "path";
19002
+ import * as fs21 from "fs";
19003
+ import * as path22 from "path";
18634
19004
  var LOCAL_HEADER = 67324752;
18635
19005
  var CENTRAL_HEADER = 33639248;
18636
19006
  var END_RECORD = 101010256;
@@ -18660,10 +19030,10 @@ function dosDateTime(date) {
18660
19030
  }
18661
19031
  function walkFiles(root, prefix = "") {
18662
19032
  const files = [];
18663
- for (const entry of fs20.readdirSync(path21.join(root, prefix), { withFileTypes: true })) {
18664
- const relative16 = prefix === "" ? entry.name : prefix + "/" + entry.name;
18665
- if (entry.isDirectory()) files.push(...walkFiles(root, relative16));
18666
- else if (entry.isFile()) files.push(relative16);
19033
+ for (const entry of fs21.readdirSync(path22.join(root, prefix), { withFileTypes: true })) {
19034
+ const relative17 = prefix === "" ? entry.name : prefix + "/" + entry.name;
19035
+ if (entry.isDirectory()) files.push(...walkFiles(root, relative17));
19036
+ else if (entry.isFile()) files.push(relative17);
18667
19037
  }
18668
19038
  return files;
18669
19039
  }
@@ -18671,11 +19041,11 @@ function writeZip(options) {
18671
19041
  const entries = [...options.entries ?? []];
18672
19042
  if (options.directory !== void 0) {
18673
19043
  const root = options.directory;
18674
- for (const relative16 of walkFiles(root)) {
18675
- if (options.skip !== void 0 && options.skip(relative16)) continue;
18676
- const full = path21.join(root, relative16);
18677
- const stat = fs20.statSync(full);
18678
- entries.push({ name: relative16, content: fs20.readFileSync(full), mtime: stat.mtime });
19044
+ for (const relative17 of walkFiles(root)) {
19045
+ if (options.skip !== void 0 && options.skip(relative17)) continue;
19046
+ const full = path22.join(root, relative17);
19047
+ const stat = fs21.statSync(full);
19048
+ entries.push({ name: relative17, content: fs21.readFileSync(full), mtime: stat.mtime });
18679
19049
  }
18680
19050
  }
18681
19051
  if (entries.length > 65535) {
@@ -18895,6 +19265,7 @@ var SERVE_PAGE = `<!doctype html>
18895
19265
  var DEFAULT_PORT = 4788;
18896
19266
  var MAX_BODY = 64 * 1024;
18897
19267
  var MAX_PREVIEW = 64 * 1024;
19268
+ var MAX_MCP_IN_FLIGHT = 4;
18898
19269
  function isLoopback(origin) {
18899
19270
  try {
18900
19271
  const url = new URL(origin);
@@ -18922,10 +19293,11 @@ async function startWebServer(options) {
18922
19293
  return server2;
18923
19294
  };
18924
19295
  const temporaryClones = /* @__PURE__ */ new Set();
18925
- const allowedRoots = [path22.resolve(options.cwd)];
19296
+ let mcpInFlight = 0;
19297
+ const allowedRoots = [path23.resolve(options.cwd)];
18926
19298
  const canonical = (candidate) => {
18927
19299
  try {
18928
- return fs21.realpathSync(candidate);
19300
+ return fs22.realpathSync(candidate);
18929
19301
  } catch {
18930
19302
  return null;
18931
19303
  }
@@ -18933,32 +19305,32 @@ async function startWebServer(options) {
18933
19305
  const inside = (resolved) => allowedRoots.some((root) => {
18934
19306
  const canonicalRoot = canonical(root);
18935
19307
  if (canonicalRoot === null) return false;
18936
- const relative16 = path22.relative(canonicalRoot, resolved);
18937
- return relative16 === "" || !relative16.startsWith(`..${path22.sep}`) && relative16 !== ".." && !path22.isAbsolute(relative16);
19308
+ const relative17 = path23.relative(canonicalRoot, resolved);
19309
+ return relative17 === "" || !relative17.startsWith(`..${path23.sep}`) && relative17 !== ".." && !path23.isAbsolute(relative17);
18938
19310
  });
18939
19311
  const insideAllowedRoots = (candidate) => {
18940
19312
  const resolved = canonical(candidate);
18941
19313
  return resolved === null ? false : inside(resolved);
18942
19314
  };
18943
19315
  const lexicallyInside = (candidate) => {
18944
- const resolved = path22.resolve(candidate);
19316
+ const resolved = path23.resolve(candidate);
18945
19317
  return allowedRoots.some((root) => {
18946
- const prefix = path22.resolve(root) + path22.sep;
18947
- return resolved === path22.resolve(root) || resolved.startsWith(prefix);
19318
+ const prefix = path23.resolve(root) + path23.sep;
19319
+ return resolved === path23.resolve(root) || resolved.startsWith(prefix);
18948
19320
  });
18949
19321
  };
18950
19322
  const insideAllowedRootsForWrite = (candidate) => {
18951
- let existing = path22.resolve(candidate);
19323
+ let existing = path23.resolve(candidate);
18952
19324
  const tail = [];
18953
- while (!fs21.existsSync(existing)) {
18954
- tail.unshift(path22.basename(existing));
18955
- const parent = path22.dirname(existing);
19325
+ while (!fs22.existsSync(existing)) {
19326
+ tail.unshift(path23.basename(existing));
19327
+ const parent = path23.dirname(existing);
18956
19328
  if (parent === existing) break;
18957
19329
  existing = parent;
18958
19330
  }
18959
19331
  const resolved = canonical(existing);
18960
19332
  if (resolved === null) return false;
18961
- return inside(tail.length === 0 ? resolved : path22.join(resolved, ...tail));
19333
+ return inside(tail.length === 0 ? resolved : path23.join(resolved, ...tail));
18962
19334
  };
18963
19335
  const authorized = (request) => {
18964
19336
  if (token === null) return true;
@@ -19048,8 +19420,25 @@ async function startWebServer(options) {
19048
19420
  const server2 = mcpFor(request.socket);
19049
19421
  const answers = [];
19050
19422
  for (const item of batch) {
19051
- const answer = await server2.handle(item);
19052
- if (answer !== null) answers.push(answer);
19423
+ const gated = item !== null && typeof item === "object" && item.method === "tools/call";
19424
+ if (gated && mcpInFlight >= MAX_MCP_IN_FLIGHT) {
19425
+ answers.push({
19426
+ jsonrpc: "2.0",
19427
+ id: item.id ?? null,
19428
+ error: {
19429
+ code: -32001,
19430
+ message: "server busy: too many tool calls are already in flight"
19431
+ }
19432
+ });
19433
+ continue;
19434
+ }
19435
+ if (gated) mcpInFlight += 1;
19436
+ try {
19437
+ const answer = await server2.handle(item);
19438
+ if (answer !== null) answers.push(answer);
19439
+ } finally {
19440
+ if (gated) mcpInFlight -= 1;
19441
+ }
19053
19442
  }
19054
19443
  if (answers.length === 0) send(202, "");
19055
19444
  else send(200, Array.isArray(message) ? answers : answers[0]);
@@ -19129,7 +19518,7 @@ async function startWebServer(options) {
19129
19518
  return;
19130
19519
  }
19131
19520
  } else {
19132
- target = path22.resolve(options.cwd, source);
19521
+ target = path23.resolve(options.cwd, source);
19133
19522
  if (!insideAllowedRoots(target)) {
19134
19523
  send(403, { error: "outside the served directory: " + target });
19135
19524
  return;
@@ -19137,7 +19526,7 @@ async function startWebServer(options) {
19137
19526
  }
19138
19527
  let stat;
19139
19528
  try {
19140
- stat = fs21.statSync(target);
19529
+ stat = fs22.statSync(target);
19141
19530
  } catch {
19142
19531
  send(404, { error: "no such path: " + target });
19143
19532
  return;
@@ -19158,11 +19547,17 @@ async function startWebServer(options) {
19158
19547
  hooks: {}
19159
19548
  } : loaded.config ?? {};
19160
19549
  const configuredOutDir = typeof runConfig.outDir === "string" && runConfig.outDir.trim() !== "" ? runConfig.outDir : "snapshot";
19161
- const snapshotDir = path22.resolve(target, configuredOutDir);
19550
+ const snapshotDir = path23.resolve(target, configuredOutDir);
19162
19551
  if (!insideAllowedRootsForWrite(snapshotDir)) {
19163
19552
  send(403, { error: "the configured outDir resolves outside the served directory" });
19164
19553
  return;
19165
19554
  }
19555
+ const configuredTmpDir = typeof runConfig.tmpDir === "string" && runConfig.tmpDir.trim() !== "" ? runConfig.tmpDir : "snapshot.tmp";
19556
+ const stagingDir = path23.resolve(target, configuredTmpDir);
19557
+ if (!insideAllowedRootsForWrite(stagingDir)) {
19558
+ send(403, { error: "the configured tmpDir resolves outside the served directory" });
19559
+ return;
19560
+ }
19166
19561
  const started = Date.now();
19167
19562
  try {
19168
19563
  const manifest = generateSnapshot({ ...runConfig, cwd: target }, {
@@ -19197,12 +19592,12 @@ async function startWebServer(options) {
19197
19592
  return;
19198
19593
  }
19199
19594
  if (request.method === "GET" && request.url?.startsWith("/api/health?") === true) {
19200
- const target = path22.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
19595
+ const target = path23.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
19201
19596
  if (!lexicallyInside(target)) {
19202
19597
  send(403, { error: "outside the served directory: " + target });
19203
19598
  return;
19204
19599
  }
19205
- if (!fs21.existsSync(path22.join(target, "manifest.json"))) {
19600
+ if (!fs22.existsSync(path23.join(target, "manifest.json"))) {
19206
19601
  send(404, { error: "no manifest.json under " + target });
19207
19602
  return;
19208
19603
  }
@@ -19210,17 +19605,17 @@ async function startWebServer(options) {
19210
19605
  send(403, { error: "outside the served directory: " + target });
19211
19606
  return;
19212
19607
  }
19213
- const report2 = auditSnapshot({ snapshotDir: target, repoDir: path22.dirname(target) });
19608
+ const report2 = auditSnapshot({ snapshotDir: target, repoDir: path23.dirname(target) });
19214
19609
  send(200, { score: report2.score, counts: report2.counts, checks: report2.checks });
19215
19610
  return;
19216
19611
  }
19217
19612
  if (request.method === "GET" && (request.url?.startsWith("/api/snapshot?") === true || request.url === "/api/snapshot")) {
19218
- const target = path22.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
19613
+ const target = path23.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
19219
19614
  if (!lexicallyInside(target)) {
19220
19615
  send(403, { error: "outside the served directory: " + target });
19221
19616
  return;
19222
19617
  }
19223
- if (!fs21.existsSync(path22.join(target, "manifest.json"))) {
19618
+ if (!fs22.existsSync(path23.join(target, "manifest.json"))) {
19224
19619
  send(404, { error: "no manifest.json under " + target });
19225
19620
  return;
19226
19621
  }
@@ -19228,10 +19623,18 @@ async function startWebServer(options) {
19228
19623
  send(403, { error: "outside the served directory: " + target });
19229
19624
  return;
19230
19625
  }
19231
- const manifestFile = path22.join(target, "manifest.json");
19626
+ const manifestRead = readConfinedText(target, "manifest.json");
19627
+ if (!manifestRead.ok) {
19628
+ if (manifestRead.reason === "outside") {
19629
+ send(403, { error: "manifest.json resolves outside the snapshot directory" });
19630
+ } else {
19631
+ send(404, { error: "no readable manifest.json under " + target });
19632
+ }
19633
+ return;
19634
+ }
19232
19635
  let manifest;
19233
19636
  try {
19234
- manifest = JSON.parse(fs21.readFileSync(manifestFile, "utf8"));
19637
+ manifest = JSON.parse(manifestRead.text);
19235
19638
  } catch {
19236
19639
  send(404, { error: "no manifest.json under " + target });
19237
19640
  return;
@@ -19241,12 +19644,8 @@ async function startWebServer(options) {
19241
19644
  send(400, { error: "manifest.json is not a snapshot manifest: " + shapeProblem });
19242
19645
  return;
19243
19646
  }
19244
- let prompt = "";
19245
- try {
19246
- prompt = fs21.readFileSync(path22.join(target, "PROMPT.md"), "utf8").slice(0, MAX_PREVIEW);
19247
- } catch {
19248
- prompt = "(this snapshot has no PROMPT.md)";
19249
- }
19647
+ const promptRead = readConfinedText(target, "PROMPT.md");
19648
+ const prompt = promptRead.ok ? promptRead.text.slice(0, MAX_PREVIEW) : "(this snapshot has no readable PROMPT.md)";
19250
19649
  send(200, {
19251
19650
  fingerprint: manifest.fingerprint ?? "",
19252
19651
  generatedAt: manifest.generatedAt ?? "",
@@ -19259,12 +19658,12 @@ async function startWebServer(options) {
19259
19658
  return;
19260
19659
  }
19261
19660
  if (request.method === "GET" && request.url?.startsWith("/api/snapshot.zip") === true) {
19262
- const target = path22.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
19661
+ const target = path23.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
19263
19662
  if (!lexicallyInside(target)) {
19264
19663
  send(403, { error: "outside the served directory: " + target });
19265
19664
  return;
19266
19665
  }
19267
- if (!fs21.existsSync(path22.join(target, "manifest.json")) && !fs21.existsSync(path22.join(target, ".codebase-snapshot"))) {
19666
+ if (!fs22.existsSync(path23.join(target, "manifest.json")) && !fs22.existsSync(path23.join(target, ".codebase-snapshot"))) {
19268
19667
  send(404, { error: "not a snapshot directory: " + target });
19269
19668
  return;
19270
19669
  }
@@ -19288,11 +19687,11 @@ async function startWebServer(options) {
19288
19687
  }
19289
19688
  send(404, { error: "not found" });
19290
19689
  });
19291
- await new Promise((resolve15, reject) => {
19690
+ await new Promise((resolve16, reject) => {
19292
19691
  server.once("error", reject);
19293
19692
  server.listen(port, host, () => {
19294
19693
  server.removeListener("error", reject);
19295
- resolve15();
19694
+ resolve16();
19296
19695
  });
19297
19696
  });
19298
19697
  const address = server.address();
@@ -19304,24 +19703,24 @@ async function startWebServer(options) {
19304
19703
  port: actualPort,
19305
19704
  host,
19306
19705
  token,
19307
- close: () => new Promise((resolve15) => {
19706
+ close: () => new Promise((resolve16) => {
19308
19707
  for (const directory of temporaryClones) {
19309
19708
  try {
19310
- fs21.rmSync(directory, { recursive: true, force: true });
19709
+ fs22.rmSync(directory, { recursive: true, force: true });
19311
19710
  } catch {
19312
19711
  }
19313
19712
  }
19314
- server.close(() => resolve15());
19713
+ server.close(() => resolve16());
19315
19714
  })
19316
19715
  };
19317
19716
  }
19318
19717
 
19319
19718
  // src/update-check.ts
19320
- import * as fs22 from "fs";
19719
+ import * as fs23 from "fs";
19321
19720
  import * as http2 from "http";
19322
19721
  import * as https from "https";
19323
19722
  import * as os2 from "os";
19324
- import * as path23 from "path";
19723
+ import * as path24 from "path";
19325
19724
  var PACKAGE_LATEST_URL = "https://registry.npmjs.org/codebase-snapshot/latest";
19326
19725
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
19327
19726
  var UP_TO_DATE_INTERVAL_MS = 60 * 60 * 1e3;
@@ -19370,17 +19769,17 @@ function isNewer(candidate, current) {
19370
19769
  }
19371
19770
  function cacheDirectory(env = process.env, platform = process.platform) {
19372
19771
  if (platform === "win32") {
19373
- const base2 = env.LOCALAPPDATA ?? path23.join(os2.homedir(), "AppData", "Local");
19374
- return path23.join(base2, "codebase-snapshot");
19772
+ const base2 = env.LOCALAPPDATA ?? path24.join(os2.homedir(), "AppData", "Local");
19773
+ return path24.join(base2, "codebase-snapshot");
19375
19774
  }
19376
19775
  if (platform === "darwin") {
19377
- return path23.join(os2.homedir(), "Library", "Caches", "codebase-snapshot");
19776
+ return path24.join(os2.homedir(), "Library", "Caches", "codebase-snapshot");
19378
19777
  }
19379
- const base = env.XDG_CACHE_HOME ?? path23.join(os2.homedir(), ".cache");
19380
- return path23.join(base, "codebase-snapshot");
19778
+ const base = env.XDG_CACHE_HOME ?? path24.join(os2.homedir(), ".cache");
19779
+ return path24.join(base, "codebase-snapshot");
19381
19780
  }
19382
19781
  function cacheFilePath(env = process.env) {
19383
- return path23.join(cacheDirectory(env), "update-check.json");
19782
+ return path24.join(cacheDirectory(env), "update-check.json");
19384
19783
  }
19385
19784
  function shouldCheck(argv, env) {
19386
19785
  const disabled = ["1", "true", "yes"].includes(
@@ -19410,7 +19809,7 @@ function shouldCheck(argv, env) {
19410
19809
  function readCache(file) {
19411
19810
  let raw;
19412
19811
  try {
19413
- raw = fs22.readFileSync(file, "utf8");
19812
+ raw = fs23.readFileSync(file, "utf8");
19414
19813
  } catch {
19415
19814
  return null;
19416
19815
  }
@@ -19427,21 +19826,21 @@ function readCache(file) {
19427
19826
  }
19428
19827
  function writeCache(file, entry) {
19429
19828
  try {
19430
- fs22.mkdirSync(path23.dirname(file), { recursive: true });
19431
- fs22.writeFileSync(file, `${JSON.stringify(entry)}
19829
+ fs23.mkdirSync(path24.dirname(file), { recursive: true });
19830
+ fs23.writeFileSync(file, `${JSON.stringify(entry)}
19432
19831
  `, "utf8");
19433
19832
  } catch {
19434
19833
  }
19435
19834
  }
19436
19835
  function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
19437
- return new Promise((resolve15) => {
19836
+ return new Promise((resolve16) => {
19438
19837
  let settled = false;
19439
19838
  let request = null;
19440
19839
  const finish = (value) => {
19441
19840
  if (settled) return;
19442
19841
  settled = true;
19443
19842
  clearTimeout(deadline);
19444
- resolve15(value);
19843
+ resolve16(value);
19445
19844
  };
19446
19845
  const deadline = setTimeout(() => {
19447
19846
  request?.destroy();
@@ -19527,8 +19926,8 @@ function formatUpdateNotice(notice, kind) {
19527
19926
 
19528
19927
  // src/agent/hook.ts
19529
19928
  import * as childProcess2 from "child_process";
19530
- import * as fs23 from "fs";
19531
- import * as path24 from "path";
19929
+ import * as fs24 from "fs";
19930
+ import * as path25 from "path";
19532
19931
  var HOOK_MARKER = `# ${GENERATOR_NAME}: pre-commit snapshot check`;
19533
19932
  function shellQuote(value) {
19534
19933
  return value.replace(/[\\"`$]/g, (character) => `\\${character}`);
@@ -19570,36 +19969,52 @@ fi
19570
19969
  `;
19571
19970
  }
19572
19971
  function gitDirectory(cwd) {
19573
- const dotGit = path24.join(cwd, ".git");
19972
+ const dotGit = path25.join(cwd, ".git");
19574
19973
  let stats;
19575
19974
  try {
19576
- stats = fs23.statSync(dotGit);
19975
+ stats = fs24.statSync(dotGit);
19577
19976
  } catch {
19578
19977
  return null;
19579
19978
  }
19580
19979
  if (stats.isDirectory()) return dotGit;
19581
19980
  if (!stats.isFile()) return null;
19582
19981
  try {
19583
- const contents = fs23.readFileSync(dotGit, "utf8");
19982
+ const contents = fs24.readFileSync(dotGit, "utf8");
19584
19983
  const match = /^gitdir:\s*(.+)$/m.exec(contents);
19585
19984
  if (!match) return null;
19586
19985
  const target = match[1];
19587
- const resolved = path24.isAbsolute(target.trim()) ? target.trim() : path24.join(cwd, target.trim());
19588
- if (!fs23.statSync(resolved).isDirectory()) return null;
19589
- if (isInside3(path24.resolve(cwd), path24.resolve(resolved))) return resolved;
19590
- return isRegisteredWorktree(path24.resolve(resolved), cwd) ? resolved : null;
19986
+ const resolved = path25.isAbsolute(target.trim()) ? target.trim() : path25.join(cwd, target.trim());
19987
+ if (!fs24.statSync(resolved).isDirectory()) return null;
19988
+ if (isInside4(path25.resolve(cwd), path25.resolve(resolved))) return resolved;
19989
+ return isRegisteredWorktree(path25.resolve(resolved), cwd) ? resolved : null;
19591
19990
  } catch {
19592
19991
  return null;
19593
19992
  }
19594
19993
  }
19595
- function isInside3(parent, child) {
19596
- const relative16 = path24.relative(parent, child);
19597
- return relative16 === "" || !relative16.startsWith("..") && !path24.isAbsolute(relative16);
19994
+ function isInside4(parent, child) {
19995
+ const relative17 = path25.relative(parent, child);
19996
+ return relative17 === "" || !relative17.startsWith("..") && !path25.isAbsolute(relative17);
19997
+ }
19998
+ function canonicalForWrite(target) {
19999
+ let existing = path25.resolve(target);
20000
+ const tail = [];
20001
+ while (!fs24.existsSync(existing)) {
20002
+ tail.unshift(path25.basename(existing));
20003
+ const parent = path25.dirname(existing);
20004
+ if (parent === existing) break;
20005
+ existing = parent;
20006
+ }
20007
+ try {
20008
+ const real = fs24.realpathSync(existing);
20009
+ return tail.length === 0 ? real : path25.join(real, ...tail);
20010
+ } catch {
20011
+ return null;
20012
+ }
19598
20013
  }
19599
20014
  function isRegisteredWorktree(gitDir, cwd) {
19600
20015
  try {
19601
- const back = fs23.readFileSync(path24.join(gitDir, "gitdir"), "utf8").trim();
19602
- return path24.resolve(gitDir, back) === path24.join(path24.resolve(cwd), ".git");
20016
+ const back = fs24.readFileSync(path25.join(gitDir, "gitdir"), "utf8").trim();
20017
+ return path25.resolve(gitDir, back) === path25.join(path25.resolve(cwd), ".git");
19603
20018
  } catch {
19604
20019
  return false;
19605
20020
  }
@@ -19620,11 +20035,18 @@ function gitOutput(cwd, args) {
19620
20035
  function configuredHooksDirectory(cwd) {
19621
20036
  const hooks = gitOutput(cwd, ["rev-parse", "--git-path", "hooks"]);
19622
20037
  if (hooks === null) return null;
19623
- const resolved = path24.resolve(cwd, hooks);
20038
+ const resolved = path25.resolve(cwd, hooks);
19624
20039
  const common = gitOutput(cwd, ["rev-parse", "--git-common-dir"]);
19625
- const commonDir = common === null ? null : path24.resolve(cwd, common);
19626
- if (isInside3(path24.resolve(cwd), resolved)) return { dir: resolved };
19627
- if (commonDir !== null && isInside3(commonDir, resolved)) return { dir: resolved };
20040
+ const commonDir = common === null ? null : canonicalForWrite(path25.resolve(cwd, common));
20041
+ const cwdReal = canonicalForWrite(cwd);
20042
+ const hooksReal = canonicalForWrite(resolved);
20043
+ if (hooksReal === null || cwdReal === null) {
20044
+ return {
20045
+ refusal: `The hooks directory git reports (${resolved}) could not be resolved, so no hook was written.`
20046
+ };
20047
+ }
20048
+ if (isInside4(cwdReal, hooksReal)) return { dir: hooksReal };
20049
+ if (commonDir !== null && isInside4(commonDir, hooksReal)) return { dir: hooksReal };
19628
20050
  return {
19629
20051
  refusal: `The hooks directory git reports (${resolved}) is outside this repository, so no hook was written. Add \`npx ${GENERATOR_NAME} validate\` to the hook manager that owns it instead.`
19630
20052
  };
@@ -19644,10 +20066,42 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
19644
20066
  ]
19645
20067
  };
19646
20068
  }
19647
- const hooksDir = configured === null ? path24.join(gitDir, "hooks") : configured.dir;
19648
- const hookPath = path24.join(hooksDir, "pre-commit");
20069
+ const hooksDir = configured === null ? path25.join(gitDir, "hooks") : configured.dir;
20070
+ const hookPath = path25.join(hooksDir, "pre-commit");
19649
20071
  try {
19650
- fs23.mkdirSync(hooksDir, { recursive: true });
20072
+ const existingStats = fs24.lstatSync(hookPath);
20073
+ if (existingStats.isSymbolicLink()) {
20074
+ return {
20075
+ path: hookPath,
20076
+ written: false,
20077
+ notes: [`Refusing to write ${hookPath}: it is a symbolic link.`]
20078
+ };
20079
+ }
20080
+ if (existingStats.isFile() && existingStats.nlink > 1) {
20081
+ return {
20082
+ path: hookPath,
20083
+ written: false,
20084
+ notes: [`Refusing to write ${hookPath}: it has ${existingStats.nlink} hard links.`]
20085
+ };
20086
+ }
20087
+ if (!existingStats.isFile()) {
20088
+ return {
20089
+ path: hookPath,
20090
+ written: false,
20091
+ notes: [`Refusing to write ${hookPath}: it is not a regular file.`]
20092
+ };
20093
+ }
20094
+ } catch (error) {
20095
+ if (error.code !== "ENOENT") {
20096
+ return {
20097
+ path: hookPath,
20098
+ written: false,
20099
+ notes: [`Refusing to write ${hookPath}: ${error.message}`]
20100
+ };
20101
+ }
20102
+ }
20103
+ try {
20104
+ fs24.mkdirSync(hooksDir, { recursive: true });
19651
20105
  } catch (err) {
19652
20106
  return {
19653
20107
  path: hookPath,
@@ -19657,7 +20111,7 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
19657
20111
  }
19658
20112
  let existing = null;
19659
20113
  try {
19660
- existing = fs23.readFileSync(hookPath, "utf8");
20114
+ existing = fs24.readFileSync(hookPath, "utf8");
19661
20115
  } catch {
19662
20116
  existing = null;
19663
20117
  }
@@ -19672,8 +20126,8 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
19672
20126
  };
19673
20127
  }
19674
20128
  try {
19675
- fs23.writeFileSync(hookPath, hookScript(outDir), "utf8");
19676
- fs23.chmodSync(hookPath, 493);
20129
+ fs24.writeFileSync(hookPath, hookScript(outDir), "utf8");
20130
+ fs24.chmodSync(hookPath, 493);
19677
20131
  } catch (err) {
19678
20132
  return {
19679
20133
  path: hookPath,
@@ -19695,23 +20149,23 @@ var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
19695
20149
  var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
19696
20150
  var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
19697
20151
  var fileDerivationBytes = 0;
19698
- function takeDerivation(path28, hash, settings) {
19699
- const cached = FILE_DERIVATIONS.get(path28);
20152
+ function takeDerivation(path29, hash, settings) {
20153
+ const cached = FILE_DERIVATIONS.get(path29);
19700
20154
  if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
19701
- FILE_DERIVATIONS.delete(path28);
19702
- FILE_DERIVATIONS.set(path28, cached);
20155
+ FILE_DERIVATIONS.delete(path29);
20156
+ FILE_DERIVATIONS.set(path29, cached);
19703
20157
  return cached;
19704
20158
  }
19705
- function rememberDerivation(path28, hash, settings, derivation) {
20159
+ function rememberDerivation(path29, hash, settings, derivation) {
19706
20160
  const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
19707
20161
  const bytes = bodyBytes * 2 + 512;
19708
20162
  if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
19709
- const previous = FILE_DERIVATIONS.get(path28);
20163
+ const previous = FILE_DERIVATIONS.get(path29);
19710
20164
  if (previous !== void 0) {
19711
- FILE_DERIVATIONS.delete(path28);
20165
+ FILE_DERIVATIONS.delete(path29);
19712
20166
  fileDerivationBytes -= previous.bytes;
19713
20167
  } else {
19714
- FILE_DERIVATIONS.delete(path28);
20168
+ FILE_DERIVATIONS.delete(path29);
19715
20169
  }
19716
20170
  while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
19717
20171
  const oldest = FILE_DERIVATIONS.keys().next();
@@ -19720,7 +20174,7 @@ function rememberDerivation(path28, hash, settings, derivation) {
19720
20174
  FILE_DERIVATIONS.delete(oldest.value);
19721
20175
  if (evicted !== void 0) fileDerivationBytes -= evicted.bytes;
19722
20176
  }
19723
- FILE_DERIVATIONS.set(path28, { ...derivation, hash, settings, bytes });
20177
+ FILE_DERIVATIONS.set(path29, { ...derivation, hash, settings, bytes });
19724
20178
  fileDerivationBytes += bytes;
19725
20179
  }
19726
20180
  function derivationSettings(config) {
@@ -20001,11 +20455,11 @@ function verifyInMemory(files, parts, unaccounted) {
20001
20455
  return errors;
20002
20456
  }
20003
20457
  function resolveSafeOutputDirs(config) {
20004
- const cwd = path25.resolve(config.cwd);
20005
- const outDir = path25.resolve(cwd, config.outDir);
20006
- const tmpDir = path25.resolve(cwd, config.tmpDir);
20007
- const root = path25.parse(cwd).root;
20008
- const contains = (parent, child) => child === parent || child.startsWith(`${parent}${path25.sep}`);
20458
+ const cwd = path26.resolve(config.cwd);
20459
+ const outDir = path26.resolve(cwd, config.outDir);
20460
+ const tmpDir = path26.resolve(cwd, config.tmpDir);
20461
+ const root = path26.parse(cwd).root;
20462
+ const contains = (parent, child) => child === parent || child.startsWith(`${parent}${path26.sep}`);
20009
20463
  const reject = (reason) => {
20010
20464
  throw new Error(
20011
20465
  `Refusing to generate: ${reason}. outDir=${outDir} tmpDir=${tmpDir} cwd=${cwd}`
@@ -20047,7 +20501,7 @@ function maskPathText(value, secretRules) {
20047
20501
  }
20048
20502
  function maskOwnerBrief(brief, secretRules) {
20049
20503
  if (brief === void 0) return void 0;
20050
- const mask = (value) => scanAndRedactSecrets(value, secretRules ?? [], "owner-brief").redacted;
20504
+ const mask = (value) => maskProse(value, secretRules, "owner-brief");
20051
20505
  return {
20052
20506
  ...brief,
20053
20507
  path: mask(brief.path),
@@ -20057,11 +20511,17 @@ function maskOwnerBrief(brief, secretRules) {
20057
20511
  ...brief.bar === void 0 ? {} : { bar: mask(brief.bar) },
20058
20512
  ...brief.calibration === void 0 ? {} : { calibration: mask(brief.calibration) },
20059
20513
  ...brief.preamble === void 0 ? {} : { preamble: mask(brief.preamble) },
20060
- notes: brief.notes.map((note) => ({ heading: note.heading, body: mask(note.body) }))
20514
+ // The heading is prose too. Masking only the body left `## Incident ghp_…` in PROMPT.md:
20515
+ // ownerNotesSection reproduced the heading as a Markdown title, where no line rule that
20516
+ // expects `key: value` can see it.
20517
+ notes: brief.notes.map((note) => ({ heading: mask(note.heading), body: mask(note.body) }))
20061
20518
  };
20062
20519
  }
20520
+ function maskProse(value, secretRules, scope) {
20521
+ return scanAndRedactSecrets(value, secretRules ?? [], scope).redacted;
20522
+ }
20063
20523
  function maskOverview(overview, secretRules) {
20064
- const mask = (value) => maskPathText(value, secretRules);
20524
+ const mask = (value) => maskProse(value, secretRules, "overview");
20065
20525
  return {
20066
20526
  ...overview.description === void 0 ? {} : { description: mask(overview.description) },
20067
20527
  ...overview.summary === void 0 ? {} : { summary: mask(overview.summary) },
@@ -20088,14 +20548,14 @@ function listEntries(dir) {
20088
20548
  const walk2 = (absolute, prefix) => {
20089
20549
  let children;
20090
20550
  try {
20091
- children = fs24.readdirSync(absolute, { withFileTypes: true });
20551
+ children = fs25.readdirSync(absolute, { withFileTypes: true });
20092
20552
  } catch {
20093
20553
  return;
20094
20554
  }
20095
20555
  for (const child of children) {
20096
- const relative16 = prefix === "" ? child.name : `${prefix}/${child.name}`;
20097
- entries.push(relative16);
20098
- if (child.isDirectory()) walk2(path25.join(absolute, child.name), relative16);
20556
+ const relative17 = prefix === "" ? child.name : `${prefix}/${child.name}`;
20557
+ entries.push(relative17);
20558
+ if (child.isDirectory()) walk2(path26.join(absolute, child.name), relative17);
20099
20559
  }
20100
20560
  };
20101
20561
  walk2(dir, "");
@@ -20107,10 +20567,10 @@ function markerInventory(dir, written) {
20107
20567
  for (const entry of entries) {
20108
20568
  if (entry === OWNERSHIP_MARKER) continue;
20109
20569
  if (isIgnorableEntry(entry)) continue;
20110
- const full = path25.join(dir, ...entry.split("/"));
20570
+ const full = path26.join(dir, ...entry.split("/"));
20111
20571
  let stats;
20112
20572
  try {
20113
- stats = fs24.lstatSync(full);
20573
+ stats = fs25.lstatSync(full);
20114
20574
  } catch {
20115
20575
  continue;
20116
20576
  }
@@ -20122,7 +20582,7 @@ function markerInventory(dir, written) {
20122
20582
  }
20123
20583
  let digest;
20124
20584
  try {
20125
- digest = sha256Hex2(fs24.readFileSync(full));
20585
+ digest = sha256Hex2(fs25.readFileSync(full));
20126
20586
  } catch {
20127
20587
  continue;
20128
20588
  }
@@ -20144,15 +20604,15 @@ function markerPayload(dir, state, id, createdAt, written, runId) {
20144
20604
  entries,
20145
20605
  files
20146
20606
  };
20147
- const manifestPath = path25.join(dir, "manifest.json");
20148
- if (fs24.existsSync(manifestPath)) {
20149
- marker2.manifestSha256 = sha256Hex2(fs24.readFileSync(manifestPath));
20607
+ const manifestPath = path26.join(dir, "manifest.json");
20608
+ if (fs25.existsSync(manifestPath)) {
20609
+ marker2.manifestSha256 = sha256Hex2(fs25.readFileSync(manifestPath));
20150
20610
  }
20151
20611
  return marker2;
20152
20612
  }
20153
20613
  function writeOwnershipMarker(dir, marker2) {
20154
- fs24.writeFileSync(
20155
- path25.join(dir, OWNERSHIP_MARKER),
20614
+ fs25.writeFileSync(
20615
+ path26.join(dir, OWNERSHIP_MARKER),
20156
20616
  `${JSON.stringify(marker2, null, 2)}
20157
20617
  `,
20158
20618
  "utf8"
@@ -20164,13 +20624,13 @@ function markerBelongsTo(dir, id) {
20164
20624
  return evidence.marker.id === id;
20165
20625
  }
20166
20626
  function readOwnershipMarker(dir) {
20167
- const markerPath = path25.join(dir, OWNERSHIP_MARKER);
20168
- if (!fs24.existsSync(markerPath)) {
20627
+ const markerPath = path26.join(dir, OWNERSHIP_MARKER);
20628
+ if (!fs25.existsSync(markerPath)) {
20169
20629
  return { marker: null, problem: "it holds no .codebase-snapshot marker" };
20170
20630
  }
20171
20631
  let raw;
20172
20632
  try {
20173
- raw = fs24.readFileSync(markerPath, "utf8");
20633
+ raw = fs25.readFileSync(markerPath, "utf8");
20174
20634
  } catch {
20175
20635
  return { marker: null, problem: "its .codebase-snapshot marker could not be read" };
20176
20636
  }
@@ -20271,10 +20731,10 @@ function verifyMarkerInventory(dir, entries, files) {
20271
20731
  for (const entry of entries) {
20272
20732
  if (entry === OWNERSHIP_MARKER) continue;
20273
20733
  if (IGNORABLE_ENTRIES.has(entry.slice(entry.lastIndexOf("/") + 1))) continue;
20274
- const full = path25.join(dir, ...entry.split("/"));
20734
+ const full = path26.join(dir, ...entry.split("/"));
20275
20735
  let stats;
20276
20736
  try {
20277
- stats = fs24.lstatSync(full);
20737
+ stats = fs25.lstatSync(full);
20278
20738
  } catch {
20279
20739
  return `its .codebase-snapshot inventory lists ${entry}, which cannot be read`;
20280
20740
  }
@@ -20299,7 +20759,7 @@ function verifyMarkerInventory(dir, entries, files) {
20299
20759
  }
20300
20760
  let digest;
20301
20761
  try {
20302
- digest = sha256Hex2(fs24.readFileSync(full));
20762
+ digest = sha256Hex2(fs25.readFileSync(full));
20303
20763
  } catch {
20304
20764
  return `its .codebase-snapshot inventory cannot verify ${entry}: the file could not be read`;
20305
20765
  }
@@ -20320,12 +20780,12 @@ function assessSnapshotDirectory(dir) {
20320
20780
  marker: marker2
20321
20781
  };
20322
20782
  }
20323
- const manifestPath = path25.join(dir, "manifest.json");
20324
- const hasManifest = fs24.existsSync(manifestPath);
20783
+ const manifestPath = path26.join(dir, "manifest.json");
20784
+ const hasManifest = fs25.existsSync(manifestPath);
20325
20785
  if (hasManifest) {
20326
20786
  let raw;
20327
20787
  try {
20328
- raw = fs24.readFileSync(manifestPath, "utf8");
20788
+ raw = fs25.readFileSync(manifestPath, "utf8");
20329
20789
  } catch {
20330
20790
  return {
20331
20791
  owned: false,
@@ -20426,13 +20886,13 @@ function containsNoFiles(dir) {
20426
20886
  const current = pending.pop();
20427
20887
  let entries;
20428
20888
  try {
20429
- entries = fs24.readdirSync(current, { withFileTypes: true });
20889
+ entries = fs25.readdirSync(current, { withFileTypes: true });
20430
20890
  } catch {
20431
20891
  return false;
20432
20892
  }
20433
20893
  for (const entry of entries) {
20434
20894
  if (entry.isDirectory()) {
20435
- pending.push(path25.join(current, entry.name));
20895
+ pending.push(path26.join(current, entry.name));
20436
20896
  } else if (!IGNORABLE_ENTRIES.has(entry.name)) {
20437
20897
  return false;
20438
20898
  }
@@ -20441,13 +20901,13 @@ function containsNoFiles(dir) {
20441
20901
  return true;
20442
20902
  }
20443
20903
  function assertReplaceable(target, label, secretRules) {
20444
- if (!fs24.existsSync(target)) return;
20445
- if (!fs24.statSync(target).isDirectory()) {
20904
+ if (!fs25.existsSync(target)) return;
20905
+ if (!fs25.statSync(target).isDirectory()) {
20446
20906
  throw new Error(
20447
20907
  `Refusing to write into ${label} ${target}: it exists but is not a directory.`
20448
20908
  );
20449
20909
  }
20450
- const entries = fs24.readdirSync(target);
20910
+ const entries = fs25.readdirSync(target);
20451
20911
  if (entries.length === 0) return;
20452
20912
  if (entries.every((name) => IGNORABLE_ENTRIES.has(name))) return;
20453
20913
  if (containsNoFiles(target)) return;
@@ -20467,18 +20927,18 @@ function assertReplaceable(target, label, secretRules) {
20467
20927
  );
20468
20928
  }
20469
20929
  function assertStagingRootUsable(tmpDir, secretRules) {
20470
- if (!fs24.existsSync(tmpDir)) return;
20471
- if (!fs24.statSync(tmpDir).isDirectory()) {
20930
+ if (!fs25.existsSync(tmpDir)) return;
20931
+ if (!fs25.statSync(tmpDir).isDirectory()) {
20472
20932
  throw new Error(`Refusing to write into tmpDir ${tmpDir}: it exists but is not a directory.`);
20473
20933
  }
20474
- const entries = fs24.readdirSync(tmpDir);
20934
+ const entries = fs25.readdirSync(tmpDir);
20475
20935
  if (entries.length === 0) return;
20476
20936
  const foreign = entries.filter((name) => {
20477
- const full = path25.join(tmpDir, name);
20937
+ const full = path26.join(tmpDir, name);
20478
20938
  if (!name.startsWith(RUN_DIR_PREFIX)) return true;
20479
20939
  let stats;
20480
20940
  try {
20481
- stats = fs24.statSync(full);
20941
+ stats = fs25.statSync(full);
20482
20942
  } catch {
20483
20943
  return true;
20484
20944
  }
@@ -20486,7 +20946,7 @@ function assertStagingRootUsable(tmpDir, secretRules) {
20486
20946
  const { marker: marker2 } = readOwnershipMarker(full);
20487
20947
  if (marker2) return false;
20488
20948
  try {
20489
- return fs24.readdirSync(full).length > 0;
20949
+ return fs25.readdirSync(full).length > 0;
20490
20950
  } catch {
20491
20951
  return true;
20492
20952
  }
@@ -20501,13 +20961,13 @@ function assertStagingRootUsable(tmpDir, secretRules) {
20501
20961
  function cleanStaleRunDirs(tmpDir) {
20502
20962
  let entries;
20503
20963
  try {
20504
- entries = fs24.readdirSync(tmpDir);
20964
+ entries = fs25.readdirSync(tmpDir);
20505
20965
  } catch {
20506
20966
  return;
20507
20967
  }
20508
20968
  for (const name of entries) {
20509
20969
  if (!name.startsWith(RUN_DIR_PREFIX)) continue;
20510
- const full = path25.join(tmpDir, name);
20970
+ const full = path26.join(tmpDir, name);
20511
20971
  const { marker: marker2 } = readOwnershipMarker(full);
20512
20972
  if (marker2) {
20513
20973
  const created = Date.parse(marker2.createdAt);
@@ -20515,33 +20975,33 @@ function cleanStaleRunDirs(tmpDir) {
20515
20975
  const abandoned = typeof marker2.pid === "number" && !isProcessAlive(marker2.pid);
20516
20976
  if (aged || abandoned) {
20517
20977
  try {
20518
- fs24.rmSync(full, { recursive: true, force: true });
20978
+ fs25.rmSync(full, { recursive: true, force: true });
20519
20979
  } catch {
20520
20980
  }
20521
20981
  }
20522
20982
  continue;
20523
20983
  }
20524
20984
  try {
20525
- if (fs24.readdirSync(full).length === 0) fs24.rmSync(full, { recursive: true, force: true });
20985
+ if (fs25.readdirSync(full).length === 0) fs25.rmSync(full, { recursive: true, force: true });
20526
20986
  } catch {
20527
20987
  }
20528
20988
  }
20529
20989
  }
20530
20990
  function removeIfEmpty(dir) {
20531
20991
  try {
20532
- if (fs24.readdirSync(dir).length === 0) fs24.rmSync(dir, { recursive: true, force: true });
20992
+ if (fs25.readdirSync(dir).length === 0) fs25.rmSync(dir, { recursive: true, force: true });
20533
20993
  } catch {
20534
20994
  }
20535
20995
  }
20536
20996
  function ensureParentDirectory(target, label) {
20537
- const parent = path25.dirname(target);
20538
- if (fs24.existsSync(parent) && !fs24.statSync(parent).isDirectory()) {
20997
+ const parent = path26.dirname(target);
20998
+ if (fs25.existsSync(parent) && !fs25.statSync(parent).isDirectory()) {
20539
20999
  throw new Error(
20540
21000
  `Refusing to create ${label} ${target}: ${parent} exists but is not a directory.`
20541
21001
  );
20542
21002
  }
20543
21003
  try {
20544
- fs24.mkdirSync(parent, { recursive: true });
21004
+ fs25.mkdirSync(parent, { recursive: true });
20545
21005
  } catch (err) {
20546
21006
  throw new Error(
20547
21007
  `Refusing to create ${label} ${target}: its parent ${parent} could not be created (${err.message}).`
@@ -20550,6 +21010,7 @@ function ensureParentDirectory(target, label) {
20550
21010
  }
20551
21011
  var LOCK_HEARTBEAT_MS = 5e3;
20552
21012
  var LOCK_STALE_HEARTBEAT_MS = 12e4;
21013
+ var LOCK_EMPTY_GRACE_MS = 5e3;
20553
21014
  var LOCK_HEARTBEAT_SOURCE = `
20554
21015
  const { parentPort, workerData } = require("node:worker_threads");
20555
21016
  const fs = require("node:fs");
@@ -20599,17 +21060,17 @@ function acquireRunLock(stagingRoot, runId) {
20599
21060
  `;
20600
21061
  for (let attempt = 0; attempt < 2; attempt += 1) {
20601
21062
  try {
20602
- const handle = fs24.openSync(lockPath, "wx");
21063
+ const handle = fs25.openSync(lockPath, "wx");
20603
21064
  try {
20604
- fs24.writeSync(handle, payload);
21065
+ fs25.writeSync(handle, payload);
20605
21066
  } finally {
20606
- fs24.closeSync(handle);
21067
+ fs25.closeSync(handle);
20607
21068
  }
20608
21069
  const stopHeartbeat = startLockHeartbeat(lockPath);
20609
21070
  return () => {
20610
21071
  stopHeartbeat();
20611
21072
  try {
20612
- fs24.rmSync(lockPath, { force: true });
21073
+ fs25.rmSync(lockPath, { force: true });
20613
21074
  } catch {
20614
21075
  }
20615
21076
  };
@@ -20629,45 +21090,45 @@ function lockKeyFor(stagingRoot) {
20629
21090
  return sha256Hex2(key).slice(0, 16);
20630
21091
  }
20631
21092
  function canonicalLockTarget(targetPath2) {
20632
- const resolved = path25.resolve(targetPath2);
21093
+ const resolved = path26.resolve(targetPath2);
20633
21094
  let existing = resolved;
20634
21095
  const tail = [];
20635
21096
  for (; ; ) {
20636
21097
  try {
20637
- return path25.join(fs24.realpathSync(existing), ...tail);
21098
+ return path26.join(fs25.realpathSync(existing), ...tail);
20638
21099
  } catch {
20639
- const parent = path25.dirname(existing);
21100
+ const parent = path26.dirname(existing);
20640
21101
  if (parent === existing) return resolved;
20641
- tail.unshift(path25.basename(existing));
21102
+ tail.unshift(path26.basename(existing));
20642
21103
  existing = parent;
20643
21104
  }
20644
21105
  }
20645
21106
  }
20646
21107
  function lockPathFor(stagingRoot) {
20647
- return path25.join(os3.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
21108
+ return path26.join(os3.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
20648
21109
  }
20649
21110
  function releaseAbandonedRun(stagingRoots, runId) {
20650
21111
  if (runId.length === 0) return;
20651
21112
  for (const root of new Set(stagingRoots)) {
20652
21113
  const lockPath = lockPathFor(root);
20653
21114
  try {
20654
- const payload = JSON.parse(fs24.readFileSync(lockPath, "utf8"));
20655
- if (payload.runId === runId) fs24.rmSync(lockPath, { force: true });
21115
+ const payload = JSON.parse(fs25.readFileSync(lockPath, "utf8"));
21116
+ if (payload.runId === runId) fs25.rmSync(lockPath, { force: true });
20656
21117
  } catch {
20657
21118
  }
20658
21119
  let entries;
20659
21120
  try {
20660
- entries = fs24.readdirSync(root);
21121
+ entries = fs25.readdirSync(root);
20661
21122
  } catch {
20662
21123
  continue;
20663
21124
  }
20664
21125
  for (const name of entries) {
20665
21126
  if (!name.startsWith(RUN_DIR_PREFIX)) continue;
20666
- const directory = path25.join(root, name);
21127
+ const directory = path26.join(root, name);
20667
21128
  const { marker: marker2 } = readOwnershipMarker(directory);
20668
21129
  if (marker2?.runId !== runId) continue;
20669
21130
  try {
20670
- fs24.rmSync(directory, { recursive: true, force: true });
21131
+ fs25.rmSync(directory, { recursive: true, force: true });
20671
21132
  } catch {
20672
21133
  }
20673
21134
  }
@@ -20675,7 +21136,7 @@ function releaseAbandonedRun(stagingRoots, runId) {
20675
21136
  }
20676
21137
  function lockHeartbeatAgeMs(lockPath) {
20677
21138
  try {
20678
- return Date.now() - fs24.statSync(lockPath).mtimeMs;
21139
+ return Date.now() - fs25.statSync(lockPath).mtimeMs;
20679
21140
  } catch {
20680
21141
  return Number.POSITIVE_INFINITY;
20681
21142
  }
@@ -20683,7 +21144,7 @@ function lockHeartbeatAgeMs(lockPath) {
20683
21144
  function lockOwnerIsGone(lockPath) {
20684
21145
  let raw;
20685
21146
  try {
20686
- raw = fs24.readFileSync(lockPath, "utf8");
21147
+ raw = fs25.readFileSync(lockPath, "utf8");
20687
21148
  } catch {
20688
21149
  return false;
20689
21150
  }
@@ -20691,9 +21152,11 @@ function lockOwnerIsGone(lockPath) {
20691
21152
  try {
20692
21153
  pid = JSON.parse(raw).pid;
20693
21154
  } catch {
20694
- return lockFileIsAncient(lockPath);
21155
+ return lockFileIsAncient(lockPath, LOCK_EMPTY_GRACE_MS);
21156
+ }
21157
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) {
21158
+ return lockFileIsAncient(lockPath, LOCK_EMPTY_GRACE_MS);
20695
21159
  }
20696
- if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return lockFileIsAncient(lockPath);
20697
21160
  try {
20698
21161
  process.kill(pid, 0);
20699
21162
  return lockFileIsAncient(lockPath);
@@ -20705,44 +21168,44 @@ function lockOwnerIsGone(lockPath) {
20705
21168
  function reclaimStaleLock(lockPath) {
20706
21169
  let before;
20707
21170
  try {
20708
- before = fs24.statSync(lockPath);
21171
+ before = fs25.statSync(lockPath);
20709
21172
  } catch {
20710
21173
  return true;
20711
21174
  }
20712
21175
  if (!lockOwnerIsGone(lockPath)) return false;
20713
21176
  try {
20714
- const current = fs24.statSync(lockPath);
21177
+ const current = fs25.statSync(lockPath);
20715
21178
  const sameFile = current.ino === before.ino && current.birthtimeMs === before.birthtimeMs && current.mtimeMs === before.mtimeMs;
20716
21179
  if (!sameFile) return false;
20717
- fs24.rmSync(lockPath, { force: true });
21180
+ fs25.rmSync(lockPath, { force: true });
20718
21181
  return true;
20719
21182
  } catch {
20720
21183
  return false;
20721
21184
  }
20722
21185
  }
20723
- function lockFileIsAncient(lockPath) {
20724
- return lockHeartbeatAgeMs(lockPath) > LOCK_STALE_HEARTBEAT_MS;
21186
+ function lockFileIsAncient(lockPath, thresholdMs = LOCK_STALE_HEARTBEAT_MS) {
21187
+ return lockHeartbeatAgeMs(lockPath) > thresholdMs;
20725
21188
  }
20726
21189
  function writeManifestAtomically(manifestPath, manifest) {
20727
21190
  const tempPath = `${manifestPath}.${process.pid}.tmp`;
20728
- fs24.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
21191
+ fs25.writeFileSync(tempPath, JSON.stringify(manifest, null, 2), "utf8");
20729
21192
  try {
20730
- fs24.renameSync(tempPath, manifestPath);
21193
+ fs25.renameSync(tempPath, manifestPath);
20731
21194
  } catch (err) {
20732
21195
  try {
20733
- fs24.rmSync(tempPath, { force: true });
21196
+ fs25.rmSync(tempPath, { force: true });
20734
21197
  } catch {
20735
21198
  }
20736
21199
  throw err;
20737
21200
  }
20738
21201
  }
20739
- function swapIntoPlace(stagingDir, outDir, beforeSwap) {
21202
+ function swapIntoPlace(stagingDir, outDir, beforeSwap, onStagingPreserved) {
20740
21203
  ensureParentDirectory(outDir, "outDir");
20741
21204
  const deadline = Date.now() + 3e3;
20742
21205
  let delay = 25;
20743
21206
  for (; ; ) {
20744
21207
  try {
20745
- swapOnce(stagingDir, outDir, beforeSwap);
21208
+ swapOnce(stagingDir, outDir, beforeSwap, onStagingPreserved);
20746
21209
  return;
20747
21210
  } catch (err) {
20748
21211
  const code = err.code;
@@ -20755,21 +21218,21 @@ function swapIntoPlace(stagingDir, outDir, beforeSwap) {
20755
21218
  }
20756
21219
  }
20757
21220
  function recoverInterruptedPublish(outDir) {
20758
- if (fs24.existsSync(outDir)) return;
20759
- const parent = path25.dirname(outDir);
20760
- const base = path25.basename(outDir);
21221
+ if (fs25.existsSync(outDir)) return;
21222
+ const parent = path26.dirname(outDir);
21223
+ const base = path26.basename(outDir);
20761
21224
  let backups;
20762
21225
  try {
20763
- backups = fs24.readdirSync(parent).filter((name) => name.startsWith(`${base}.backup-`));
21226
+ backups = fs25.readdirSync(parent).filter((name) => name.startsWith(`${base}.backup-`));
20764
21227
  } catch {
20765
21228
  return;
20766
21229
  }
20767
21230
  if (backups.length !== 1) return;
20768
- const backupDir = path25.join(parent, backups[0]);
21231
+ const backupDir = path26.join(parent, backups[0]);
20769
21232
  const { marker: marker2, problem } = readOwnershipMarker(backupDir);
20770
21233
  if (problem !== null || marker2 === null || marker2.state !== "complete") return;
20771
21234
  try {
20772
- fs24.renameSync(backupDir, outDir);
21235
+ fs25.renameSync(backupDir, outDir);
20773
21236
  process.stderr.write(
20774
21237
  `\u26A0 Recovered ${outDir} from ${backupDir}, left by an interrupted run. That snapshot is the one from before the interrupted run.
20775
21238
  `
@@ -20777,18 +21240,19 @@ function recoverInterruptedPublish(outDir) {
20777
21240
  } catch {
20778
21241
  }
20779
21242
  }
20780
- function swapOnce(stagingDir, outDir, beforeSwap) {
21243
+ function swapOnce(stagingDir, outDir, beforeSwap, onStagingPreserved) {
20781
21244
  const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
20782
- const hadPrevious = fs24.existsSync(outDir);
21245
+ const hadPrevious = fs25.existsSync(outDir);
20783
21246
  if (hadPrevious) beforeSwap?.();
20784
21247
  let movedAside = false;
20785
21248
  if (hadPrevious) {
20786
21249
  try {
20787
- fs24.renameSync(outDir, backupDir);
21250
+ fs25.renameSync(outDir, backupDir);
20788
21251
  movedAside = true;
20789
21252
  } catch (err) {
20790
21253
  if (!isLockError(err)) throw err;
20791
- fs24.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
21254
+ onStagingPreserved?.();
21255
+ fs25.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
20792
21256
  process.stderr.write(
20793
21257
  `\u26A0 ${outDir} could not be moved aside (${err.message}), so it was replaced in place. Close anything holding the old snapshot open to avoid this next time.
20794
21258
  `
@@ -20797,27 +21261,28 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
20797
21261
  }
20798
21262
  try {
20799
21263
  try {
20800
- fs24.renameSync(stagingDir, outDir);
21264
+ fs25.renameSync(stagingDir, outDir);
20801
21265
  } catch (err) {
20802
21266
  if (err.code !== "EXDEV") throw err;
20803
21267
  const partialDir = `${outDir}.partial-${process.pid}-${Date.now()}`;
20804
21268
  try {
20805
- fs24.cpSync(stagingDir, partialDir, { recursive: true });
20806
- fs24.renameSync(partialDir, outDir);
20807
- fs24.rmSync(stagingDir, { recursive: true, force: true });
21269
+ fs25.cpSync(stagingDir, partialDir, { recursive: true });
21270
+ fs25.renameSync(partialDir, outDir);
21271
+ fs25.rmSync(stagingDir, { recursive: true, force: true });
20808
21272
  } catch (copyErr) {
20809
21273
  try {
20810
- fs24.rmSync(partialDir, { recursive: true, force: true });
21274
+ fs25.rmSync(partialDir, { recursive: true, force: true });
20811
21275
  } catch {
20812
21276
  }
20813
21277
  throw copyErr;
20814
21278
  }
20815
21279
  }
20816
21280
  } catch (err) {
20817
- if (hadPrevious && movedAside && fs24.existsSync(backupDir)) {
20818
- if (fs24.existsSync(outDir)) fs24.rmSync(outDir, { recursive: true, force: true });
20819
- fs24.renameSync(backupDir, outDir);
21281
+ if (hadPrevious && movedAside && fs25.existsSync(backupDir)) {
21282
+ if (fs25.existsSync(outDir)) fs25.rmSync(outDir, { recursive: true, force: true });
21283
+ fs25.renameSync(backupDir, outDir);
20820
21284
  } else if (hadPrevious && !movedAside) {
21285
+ onStagingPreserved?.();
20821
21286
  process.stderr.write(
20822
21287
  `\u26A0 The previous snapshot at ${outDir} was removed and the new one could not be moved into place. It is complete at ${stagingDir}.
20823
21288
  `
@@ -20827,7 +21292,7 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
20827
21292
  }
20828
21293
  if (hadPrevious) {
20829
21294
  try {
20830
- fs24.rmSync(backupDir, { recursive: true, force: true });
21295
+ fs25.rmSync(backupDir, { recursive: true, force: true });
20831
21296
  } catch (err) {
20832
21297
  process.stderr.write(
20833
21298
  `\u26A0 The previous snapshot could not be removed from ${backupDir} (${err.message}). The new snapshot is in place; delete that directory by hand when convenient.
@@ -21006,8 +21471,8 @@ function generateSnapshot(configInput, options) {
21006
21471
  // first run cannot have marked them yet, so the name alone keeps a run from recording its own
21007
21472
  // output — but only at these exact paths, not at every directory that shares the name.
21008
21473
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
21009
- (directory) => path25.relative(config.cwd, path25.resolve(config.cwd, directory)).replace(/\\/g, "/")
21010
- ).filter((relative16) => relative16.length > 0 && !relative16.startsWith("..")),
21474
+ (directory) => path26.relative(config.cwd, path26.resolve(config.cwd, directory)).replace(/\\/g, "/")
21475
+ ).filter((relative17) => relative17.length > 0 && !relative17.startsWith("..")),
21011
21476
  // A staged path can be absent from the working tree while its index blob exists. Discovery
21012
21477
  // lists the working tree, so those paths would never reach the scan at all.
21013
21478
  ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
@@ -21035,7 +21500,7 @@ function generateSnapshot(configInput, options) {
21035
21500
  let totalSizeBytes = 0;
21036
21501
  let largeFileCount = 0;
21037
21502
  for (const relativePath of candidateFiles) {
21038
- const absolutePath = path25.join(config.cwd, relativePath);
21503
+ const absolutePath = path26.join(config.cwd, relativePath);
21039
21504
  const fromIndex = stagedPaths.has(relativePath);
21040
21505
  let buffer;
21041
21506
  let sizeBytes;
@@ -21066,9 +21531,9 @@ function generateSnapshot(configInput, options) {
21066
21531
  } else {
21067
21532
  let stats;
21068
21533
  try {
21069
- stats = fs24.statSync(absolutePath);
21534
+ stats = fs25.statSync(absolutePath);
21070
21535
  if (!stats.isFile()) {
21071
- const nestedRepository = stats.isDirectory() && fs24.existsSync(path25.join(absolutePath, ".git"));
21536
+ const nestedRepository = stats.isDirectory() && fs25.existsSync(path26.join(absolutePath, ".git"));
21072
21537
  skipped.push(
21073
21538
  nestedRepository ? {
21074
21539
  path: relativePath,
@@ -21104,7 +21569,7 @@ function generateSnapshot(configInput, options) {
21104
21569
  continue;
21105
21570
  }
21106
21571
  try {
21107
- buffer = fs24.readFileSync(absolutePath);
21572
+ buffer = fs25.readFileSync(absolutePath);
21108
21573
  } catch (err) {
21109
21574
  const code = err.code;
21110
21575
  skipped.push({
@@ -21219,14 +21684,14 @@ function generateSnapshot(configInput, options) {
21219
21684
  }
21220
21685
  retain(secretFindings, (finding) => finding.path === void 0 || keep.has(finding.path));
21221
21686
  retain(encodingNotes, (note) => keep.has(note.path));
21222
- retain(oversizeSummaryPaths, (path28) => keep.has(path28));
21223
- retain(previewSummaryPaths, (path28) => keep.has(path28));
21687
+ retain(oversizeSummaryPaths, (path29) => keep.has(path29));
21688
+ retain(previewSummaryPaths, (path29) => keep.has(path29));
21224
21689
  retain(fileWarnings, (warning) => keep.has(warning.path));
21225
- for (const path28 of [...monolithBodies.keys()]) {
21226
- if (!keep.has(path28)) monolithBodies.delete(path28);
21690
+ for (const path29 of [...monolithBodies.keys()]) {
21691
+ if (!keep.has(path29)) monolithBodies.delete(path29);
21227
21692
  }
21228
- for (const path28 of [...skippedSummaryImports.keys()]) {
21229
- if (!keep.has(path28)) skippedSummaryImports.delete(path28);
21693
+ for (const path29 of [...skippedSummaryImports.keys()]) {
21694
+ if (!keep.has(path29)) skippedSummaryImports.delete(path29);
21230
21695
  }
21231
21696
  };
21232
21697
  if (changedScope !== null && changedPaths !== null && config.withDependents === true) {
@@ -21697,7 +22162,7 @@ function generateSnapshot(configInput, options) {
21697
22162
  const reportExcludes = [...config.excludePatterns, ...config.presetExclude];
21698
22163
  const diffReport = artifacts.diff ? generateDiffReport(config.cwd, {
21699
22164
  secretRules: config.secretRules,
21700
- excluded: (relativePath) => reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
22165
+ excluded: (relativePath) => isSensitivePath(relativePath) || defaultIgnoreReason(relativePath) !== null || config.include.length > 0 && !config.include.some((pattern) => matchesExclude(relativePath, pattern)) || reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
21701
22166
  }) : null;
21702
22167
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
21703
22168
  const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount, secretRules: config.secretRules }) : null;
@@ -21723,8 +22188,8 @@ function generateSnapshot(configInput, options) {
21723
22188
  task: config.promptTask,
21724
22189
  brief: maskOwnerBrief(config.brief, config.secretRules),
21725
22190
  history: recentCommits(config.cwd).map((commit) => ({
21726
- subject: maskPathText(commit.subject, config.secretRules),
21727
- body: maskPathText(commit.body, config.secretRules)
22191
+ subject: maskProse(commit.subject, config.secretRules, "git-log"),
22192
+ body: maskProse(commit.body, config.secretRules, "git-log")
21728
22193
  })),
21729
22194
  overview: maskOverview(readProjectOverview(config.cwd), config.secretRules)
21730
22195
  }) : null;
@@ -21824,15 +22289,16 @@ function generateSnapshot(configInput, options) {
21824
22289
  recoverInterruptedPublish(outDir);
21825
22290
  assertReplaceable(outDir, "outDir", config.secretRules);
21826
22291
  let stagingDir = null;
22292
+ let stagingPreserved = false;
21827
22293
  let releaseDeferred = false;
21828
22294
  try {
21829
22295
  ensureParentDirectory(outDir, "outDir");
21830
- fs24.mkdirSync(tmpDir, { recursive: true });
22296
+ fs25.mkdirSync(tmpDir, { recursive: true });
21831
22297
  cleanStaleRunDirs(tmpDir);
21832
22298
  const snapshotId = crypto5.randomUUID();
21833
22299
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
21834
- stagingDir = path25.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
21835
- fs24.mkdirSync(stagingDir);
22300
+ stagingDir = path26.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
22301
+ fs25.mkdirSync(stagingDir);
21836
22302
  writeOwnershipMarker(stagingDir, {
21837
22303
  generator: GENERATOR_NAME,
21838
22304
  version: GENERATOR_VERSION,
@@ -21843,30 +22309,30 @@ function generateSnapshot(configInput, options) {
21843
22309
  runId,
21844
22310
  pid: process.pid
21845
22311
  });
21846
- const partsDir = path25.join(stagingDir, "parts");
21847
- const reportsDir = path25.join(stagingDir, "reports");
21848
- if (artifacts.parts) fs24.mkdirSync(partsDir, { recursive: true });
22312
+ const partsDir = path26.join(stagingDir, "parts");
22313
+ const reportsDir = path26.join(stagingDir, "reports");
22314
+ if (artifacts.parts) fs25.mkdirSync(partsDir, { recursive: true });
21849
22315
  if (artifacts.navigation || artifacts.projectTree || artifacts.audit || artifacts.diff || artifacts.log || artifacts.tokenTree || config.sarif === true) {
21850
- fs24.mkdirSync(reportsDir, { recursive: true });
22316
+ fs25.mkdirSync(reportsDir, { recursive: true });
21851
22317
  }
21852
22318
  const writtenArtifacts = /* @__PURE__ */ new Map();
21853
22319
  const writeArtifact = (targetDir, relativeEntry, data) => {
21854
- const full = path25.join(targetDir, ...relativeEntry.split("/"));
21855
- fs24.writeFileSync(full, data, "utf8");
21856
- const stats = fs24.statSync(full);
22320
+ const full = path26.join(targetDir, ...relativeEntry.split("/"));
22321
+ fs25.writeFileSync(full, data, "utf8");
22322
+ const stats = fs25.statSync(full);
21857
22323
  writtenArtifacts.set(relativeEntry, {
21858
22324
  digest: { path: relativeEntry, bytes: stats.size, sha256: sha256Hex2(data) },
21859
22325
  mtimeMs: stats.mtimeMs
21860
22326
  });
21861
22327
  };
21862
22328
  const recordArtifact = (targetDir, relativeEntry) => {
21863
- const full = path25.join(targetDir, ...relativeEntry.split("/"));
21864
- const stats = fs24.statSync(full);
22329
+ const full = path26.join(targetDir, ...relativeEntry.split("/"));
22330
+ const stats = fs25.statSync(full);
21865
22331
  writtenArtifacts.set(relativeEntry, {
21866
22332
  digest: {
21867
22333
  path: relativeEntry,
21868
22334
  bytes: stats.size,
21869
- sha256: sha256Hex2(fs24.readFileSync(full))
22335
+ sha256: sha256Hex2(fs25.readFileSync(full))
21870
22336
  },
21871
22337
  mtimeMs: stats.mtimeMs
21872
22338
  });
@@ -21915,7 +22381,7 @@ function generateSnapshot(configInput, options) {
21915
22381
  "Refusing to sign: manifest.json is disabled for this run. Signing covers the manifest, so enable the manifest artifact or drop --sign."
21916
22382
  );
21917
22383
  }
21918
- const record = signManifest(path25.join(stagingDir, "manifest.json"), {
22384
+ const record = signManifest(path26.join(stagingDir, "manifest.json"), {
21919
22385
  key: options.sign.key ?? null
21920
22386
  });
21921
22387
  writeArtifact(stagingDir, SIGNATURE_FILE, JSON.stringify(record, null, 2) + "\n");
@@ -21933,17 +22399,24 @@ function generateSnapshot(configInput, options) {
21933
22399
  stagingDir,
21934
22400
  markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21935
22401
  );
21936
- swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
22402
+ swapIntoPlace(
22403
+ stagingDir,
22404
+ outDir,
22405
+ () => assertReplaceable(outDir, "outDir", config.secretRules),
22406
+ () => {
22407
+ stagingPreserved = true;
22408
+ }
22409
+ );
21937
22410
  stagingDir = null;
21938
22411
  const warningsBeforeHook = manifest.warnings.length;
21939
22412
  const pendingHook = runAfterGenerate(config, manifest);
21940
22413
  const shipHookState = () => {
21941
22414
  if (!markerBelongsTo(outDir, snapshotId)) return;
21942
22415
  if (artifacts.manifest && manifest.warnings.length !== warningsBeforeHook) {
21943
- writeManifestAtomically(path25.join(outDir, "manifest.json"), manifest);
22416
+ writeManifestAtomically(path26.join(outDir, "manifest.json"), manifest);
21944
22417
  recordArtifact(outDir, "manifest.json");
21945
22418
  if (options?.sign !== void 0) {
21946
- const record = signManifest(path25.join(outDir, "manifest.json"), {
22419
+ const record = signManifest(path26.join(outDir, "manifest.json"), {
21947
22420
  key: options.sign.key ?? null
21948
22421
  });
21949
22422
  writeArtifact(outDir, SIGNATURE_FILE, JSON.stringify(record, null, 2) + "\n");
@@ -21987,9 +22460,9 @@ function generateSnapshot(configInput, options) {
21987
22460
  }
21988
22461
  return manifest;
21989
22462
  } catch (err) {
21990
- if (stagingDir !== null) {
22463
+ if (stagingDir !== null && !stagingPreserved) {
21991
22464
  try {
21992
- fs24.rmSync(stagingDir, { recursive: true, force: true });
22465
+ fs25.rmSync(stagingDir, { recursive: true, force: true });
21993
22466
  } catch {
21994
22467
  }
21995
22468
  }
@@ -22004,25 +22477,25 @@ function generateSnapshot(configInput, options) {
22004
22477
  var pendingHooks = /* @__PURE__ */ new Map();
22005
22478
 
22006
22479
  // src/agent/install-skill.ts
22007
- import * as fs25 from "fs";
22008
- import * as path26 from "path";
22480
+ import * as fs26 from "fs";
22481
+ import * as path27 from "path";
22009
22482
  var SKILL_TARGETS = ["claude", "cursor", "all"];
22010
22483
  var REFUSED = "Refusing to install the agent skill";
22011
22484
  var LEGACY_AGENTS_MARKER = "<!-- codebase-snapshot:skill:start -->";
22012
22485
  function targetPath(cwd, target) {
22013
22486
  switch (target) {
22014
22487
  case "claude":
22015
- return path26.join(cwd, ".claude", "skills", SKILL_NAME, "SKILL.md");
22488
+ return path27.join(cwd, ".claude", "skills", SKILL_NAME, "SKILL.md");
22016
22489
  case "cursor":
22017
- return path26.join(cwd, ".cursor", "rules", `${SKILL_NAME}.mdc`);
22490
+ return path27.join(cwd, ".cursor", "rules", `${SKILL_NAME}.mdc`);
22018
22491
  }
22019
22492
  }
22020
22493
  function assertWritableInsideRepository(cwd, filePath) {
22021
- const root = fs25.realpathSync(cwd);
22022
- const shown = path26.relative(root, filePath) || filePath;
22494
+ const root = fs26.realpathSync(cwd);
22495
+ const shown = path27.relative(root, filePath) || filePath;
22023
22496
  let stat = null;
22024
22497
  try {
22025
- stat = fs25.lstatSync(filePath);
22498
+ stat = fs26.lstatSync(filePath);
22026
22499
  } catch {
22027
22500
  stat = null;
22028
22501
  }
@@ -22038,32 +22511,32 @@ function assertWritableInsideRepository(cwd, filePath) {
22038
22511
  }
22039
22512
  let existing = filePath;
22040
22513
  const missing = [];
22041
- while (!fs25.existsSync(existing)) {
22042
- missing.unshift(path26.basename(existing));
22043
- const parent = path26.dirname(existing);
22514
+ while (!fs26.existsSync(existing)) {
22515
+ missing.unshift(path27.basename(existing));
22516
+ const parent = path27.dirname(existing);
22044
22517
  if (parent === existing) break;
22045
22518
  existing = parent;
22046
22519
  }
22047
- const realAncestor = fs25.realpathSync(existing);
22048
- const resolved = missing.length === 0 ? realAncestor : path26.join(realAncestor, ...missing);
22049
- if (resolved !== root && !resolved.startsWith(`${root}${path26.sep}`)) {
22520
+ const realAncestor = fs26.realpathSync(existing);
22521
+ const resolved = missing.length === 0 ? realAncestor : path27.join(realAncestor, ...missing);
22522
+ if (resolved !== root && !resolved.startsWith(`${root}${path27.sep}`)) {
22050
22523
  throw new Error(
22051
22524
  `${REFUSED}: ${shown} resolves outside the repository (${resolved}). Move it back inside ${root}, or remove the link, and run again.`
22052
22525
  );
22053
22526
  }
22054
22527
  }
22055
22528
  function writeIfChanged(target, filePath, content) {
22056
- const existing = fs25.existsSync(filePath) ? fs25.readFileSync(filePath, "utf8") : null;
22529
+ const existing = fs26.existsSync(filePath) ? fs26.readFileSync(filePath, "utf8") : null;
22057
22530
  if (existing === content) return { target, path: filePath, action: "unchanged" };
22058
- fs25.mkdirSync(path26.dirname(filePath), { recursive: true });
22059
- fs25.writeFileSync(filePath, content, "utf8");
22531
+ fs26.mkdirSync(path27.dirname(filePath), { recursive: true });
22532
+ fs26.writeFileSync(filePath, content, "utf8");
22060
22533
  return { target, path: filePath, action: existing === null ? "created" : "updated" };
22061
22534
  }
22062
22535
  function legacyAgentsNote(cwd) {
22063
- const filePath = path26.join(cwd, "AGENTS.md");
22536
+ const filePath = path27.join(cwd, "AGENTS.md");
22064
22537
  try {
22065
- if (!fs25.existsSync(filePath)) return null;
22066
- if (!fs25.readFileSync(filePath, "utf8").includes(LEGACY_AGENTS_MARKER)) return null;
22538
+ if (!fs26.existsSync(filePath)) return null;
22539
+ if (!fs26.readFileSync(filePath, "utf8").includes(LEGACY_AGENTS_MARKER)) return null;
22067
22540
  } catch {
22068
22541
  return null;
22069
22542
  }
@@ -22075,9 +22548,9 @@ function installSkill(cwd, target = "all") {
22075
22548
  const notes = [];
22076
22549
  const wanted = target === "all" ? ["claude", "cursor"] : [target];
22077
22550
  for (const item of wanted) assertWritableInsideRepository(cwd, targetPath(cwd, item));
22078
- const createsSomething = wanted.some((item) => !fs25.existsSync(targetPath(cwd, item)));
22551
+ const createsSomething = wanted.some((item) => !fs26.existsSync(targetPath(cwd, item)));
22079
22552
  if (createsSomething) {
22080
- assertWritableInsideRepository(cwd, path26.join(cwd, ".gitignore"));
22553
+ assertWritableInsideRepository(cwd, path27.join(cwd, ".gitignore"));
22081
22554
  }
22082
22555
  for (const item of wanted) {
22083
22556
  written.push(writeIfChanged(item, targetPath(cwd, item), skill));
@@ -22100,6 +22573,9 @@ var DEFAULT_PORT2 = 4789;
22100
22573
  var DEFAULT_MAX_BODY = 2 * 1024 * 1024;
22101
22574
  var RATE_LIMIT = 60;
22102
22575
  var RATE_WINDOW_MS = 1e4;
22576
+ var MAX_IN_FLIGHT = 4;
22577
+ var MAX_SESSION_ENTRIES = 64;
22578
+ var MAX_RATE_WINDOWS = 1024;
22103
22579
  function generateToken() {
22104
22580
  return crypto6.randomBytes(24).toString("base64url");
22105
22581
  }
@@ -22135,6 +22611,13 @@ async function startHttpTransport(options) {
22135
22611
  const toolCount = buildTools().length;
22136
22612
  const mcpSessions = /* @__PURE__ */ new Map();
22137
22613
  const socketServers = /* @__PURE__ */ new WeakMap();
22614
+ const rememberSession = (id, server) => {
22615
+ if (!mcpSessions.has(id) && mcpSessions.size >= MAX_SESSION_ENTRIES) {
22616
+ const oldest = mcpSessions.keys().next().value;
22617
+ if (oldest !== void 0) mcpSessions.delete(oldest);
22618
+ }
22619
+ mcpSessions.set(id, server);
22620
+ };
22138
22621
  const anonymousServers = /* @__PURE__ */ new Map();
22139
22622
  const serverFor = (request) => {
22140
22623
  const header = request.headers["mcp-session-id"];
@@ -22143,11 +22626,7 @@ async function startHttpTransport(options) {
22143
22626
  let existing = mcpSessions.get(supplied);
22144
22627
  if (existing === void 0) {
22145
22628
  existing = createMcp();
22146
- if (mcpSessions.size >= 64) {
22147
- const oldest = mcpSessions.keys().next().value;
22148
- if (oldest !== void 0) mcpSessions.delete(oldest);
22149
- }
22150
- mcpSessions.set(supplied, existing);
22629
+ rememberSession(supplied, existing);
22151
22630
  }
22152
22631
  return existing;
22153
22632
  }
@@ -22178,6 +22657,35 @@ async function startHttpTransport(options) {
22178
22657
  return fromQuery !== null && timingSafeEqual3(fromQuery, token);
22179
22658
  };
22180
22659
  const sessions = /* @__PURE__ */ new Map();
22660
+ let inFlight = 0;
22661
+ const acquireToolSlot = () => {
22662
+ if (inFlight >= MAX_IN_FLIGHT) return false;
22663
+ inFlight += 1;
22664
+ return true;
22665
+ };
22666
+ const releaseToolSlot = () => {
22667
+ if (inFlight > 0) inFlight -= 1;
22668
+ };
22669
+ const busyResponse = (id) => ({
22670
+ jsonrpc: "2.0",
22671
+ id: typeof id === "string" || typeof id === "number" || id === null ? id : null,
22672
+ error: {
22673
+ code: -32001,
22674
+ message: "server busy: too many tool calls are already in flight"
22675
+ }
22676
+ });
22677
+ const isToolCall = (message) => message !== null && typeof message === "object" && message.method === "tools/call";
22678
+ const rememberRateWindow = (remote, now) => {
22679
+ if (!sessions.has(remote) && sessions.size >= MAX_RATE_WINDOWS) {
22680
+ for (const [key, value] of sessions) if (value.resetAt <= now) sessions.delete(key);
22681
+ while (sessions.size >= MAX_RATE_WINDOWS) {
22682
+ const oldest = sessions.keys().next().value;
22683
+ if (oldest === void 0) break;
22684
+ sessions.delete(oldest);
22685
+ }
22686
+ }
22687
+ sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
22688
+ };
22181
22689
  const metrics = {
22182
22690
  requests: 0,
22183
22691
  byMethod: /* @__PURE__ */ new Map(),
@@ -22195,7 +22703,7 @@ async function startHttpTransport(options) {
22195
22703
  const now = Date.now();
22196
22704
  const window = sessions.get(remote);
22197
22705
  if (window === void 0 || window.resetAt <= now) {
22198
- sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
22706
+ rememberRateWindow(remote, now);
22199
22707
  return false;
22200
22708
  }
22201
22709
  if (window.count >= RATE_LIMIT) return true;
@@ -22355,8 +22863,19 @@ async function startHttpTransport(options) {
22355
22863
  send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: String(error) } });
22356
22864
  return;
22357
22865
  }
22358
- const answer = await stream.server.handle(message);
22359
- if (answer !== null) stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
22866
+ const gated = isToolCall(message);
22867
+ if (gated && !acquireToolSlot()) {
22868
+ const answer = busyResponse(message.id);
22869
+ stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
22870
+ send(202, "", cors);
22871
+ return;
22872
+ }
22873
+ try {
22874
+ const answer = await stream.server.handle(message);
22875
+ if (answer !== null) stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
22876
+ } finally {
22877
+ if (gated) releaseToolSlot();
22878
+ }
22360
22879
  send(202, "", cors);
22361
22880
  })();
22362
22881
  });
@@ -22421,13 +22940,22 @@ async function startHttpTransport(options) {
22421
22940
  }
22422
22941
  if (sessionId === "" && !Array.isArray(message) && message.method === "initialize") {
22423
22942
  sessionId = newSessionId();
22424
- mcpSessions.set(sessionId, activeServer);
22943
+ rememberSession(sessionId, activeServer);
22425
22944
  }
22426
22945
  const sessionHeaders = sessionId === "" ? cors : { ...cors, "mcp-session-id": sessionId };
22427
22946
  const answers = [];
22428
22947
  for (const item of batch) {
22429
- const answer = await activeServer.handle(item);
22430
- if (answer !== null) answers.push(answer);
22948
+ const gated = isToolCall(item);
22949
+ if (gated && !acquireToolSlot()) {
22950
+ answers.push(busyResponse(item.id));
22951
+ continue;
22952
+ }
22953
+ try {
22954
+ const answer = await activeServer.handle(item);
22955
+ if (answer !== null) answers.push(answer);
22956
+ } finally {
22957
+ if (gated) releaseToolSlot();
22958
+ }
22431
22959
  }
22432
22960
  if (answers.length === 0) {
22433
22961
  send(202, "", sessionHeaders);
@@ -22446,11 +22974,11 @@ async function startHttpTransport(options) {
22446
22974
  }
22447
22975
  });
22448
22976
  });
22449
- await new Promise((resolve15, reject) => {
22977
+ await new Promise((resolve16, reject) => {
22450
22978
  httpServer.once("error", reject);
22451
22979
  httpServer.listen(port, host, () => {
22452
22980
  httpServer.removeListener("error", reject);
22453
- resolve15();
22981
+ resolve16();
22454
22982
  });
22455
22983
  });
22456
22984
  const address = httpServer.address();
@@ -22461,7 +22989,7 @@ async function startHttpTransport(options) {
22461
22989
  port: actualPort,
22462
22990
  host,
22463
22991
  token,
22464
- close: () => new Promise((resolve15) => {
22992
+ close: () => new Promise((resolve16) => {
22465
22993
  for (const [, session] of sseSessions) {
22466
22994
  try {
22467
22995
  session.end();
@@ -22469,7 +22997,7 @@ async function startHttpTransport(options) {
22469
22997
  }
22470
22998
  }
22471
22999
  sseSessions.clear();
22472
- httpServer.close(() => resolve15());
23000
+ httpServer.close(() => resolve16());
22473
23001
  httpServer.closeAllConnections();
22474
23002
  })
22475
23003
  };
@@ -22723,6 +23251,13 @@ function parseByteOption(raw, optionName, minimum, unit = "byte count") {
22723
23251
  }
22724
23252
  return value;
22725
23253
  }
23254
+ function parsePort(raw) {
23255
+ const value = parsePositiveInteger(raw, "port", 0);
23256
+ if (value !== void 0 && value > 65535) {
23257
+ throw new UsageError(`--port must be at most 65535, received "${raw}".`);
23258
+ }
23259
+ return value;
23260
+ }
22726
23261
  function parseCountOption(raw, optionName, minimum = 0) {
22727
23262
  if (raw === void 0) return void 0;
22728
23263
  const trimmed = raw.trim();
@@ -22808,10 +23343,10 @@ function parseCliArgs(argv) {
22808
23343
  }
22809
23344
  if (values.cwd !== void 0) {
22810
23345
  const target = String(values.cwd);
22811
- if (!fs26.existsSync(target)) {
23346
+ if (!fs27.existsSync(target)) {
22812
23347
  throw new UsageError(`--cwd directory does not exist: ${target}`);
22813
23348
  }
22814
- if (!fs26.statSync(target).isDirectory()) {
23349
+ if (!fs27.statSync(target).isDirectory()) {
22815
23350
  throw new UsageError(`--cwd is not a directory: ${target}`);
22816
23351
  }
22817
23352
  }
@@ -22957,7 +23492,7 @@ function parseCliArgs(argv) {
22957
23492
  install: values.install === true,
22958
23493
  noInstall: values["no-install"] === true,
22959
23494
  target: values.target === void 0 ? void 0 : String(values.target),
22960
- cwd: values.cwd === void 0 ? process.cwd() : path27.resolve(String(values.cwd)),
23495
+ cwd: values.cwd === void 0 ? process.cwd() : path28.resolve(String(values.cwd)),
22961
23496
  outDir: values["out-dir"] === void 0 ? void 0 : String(values["out-dir"]),
22962
23497
  includeMonolith: values["include-monolith"] === true || onlyNamesMonolith === true ? true : void 0,
22963
23498
  includeSensitiveFiles: values["include-sensitive-files"] === true ? true : void 0,
@@ -23011,7 +23546,7 @@ function parseCliArgs(argv) {
23011
23546
  sarif: values.sarif === true ? true : void 0,
23012
23547
  strict: values.strict === true ? true : void 0,
23013
23548
  http: values.http === true ? true : void 0,
23014
- port: parsePositiveInteger(values.port, "port", 1),
23549
+ port: parsePort(values.port),
23015
23550
  host: values.host === void 0 ? void 0 : String(values.host),
23016
23551
  token: values.token === void 0 ? void 0 : String(values.token),
23017
23552
  noAuth: values["no-auth"] === true ? true : void 0,
@@ -23074,9 +23609,9 @@ function splitList(value) {
23074
23609
  return value.split(",").map((entry) => entry.trim()).filter(Boolean);
23075
23610
  }
23076
23611
  function displayOutPath(cwd, outDir, ...segments) {
23077
- const absolute = path27.resolve(cwd, outDir, ...segments);
23078
- const relative16 = path27.relative(cwd, absolute);
23079
- if (relative16 && !relative16.startsWith("..") && !path27.isAbsolute(relative16)) return relative16;
23612
+ const absolute = path28.resolve(cwd, outDir, ...segments);
23613
+ const relative17 = path28.relative(cwd, absolute);
23614
+ if (relative17 && !relative17.startsWith("..") && !path28.isAbsolute(relative17)) return relative17;
23080
23615
  return absolute;
23081
23616
  }
23082
23617
  function nextStepHint(cwd, scriptsAddedNow) {
@@ -23084,7 +23619,7 @@ function nextStepHint(cwd, scriptsAddedNow) {
23084
23619
  if (!hasScript) {
23085
23620
  try {
23086
23621
  const parsed = JSON.parse(
23087
- stripJsonComments(fs26.readFileSync(path27.join(cwd, "package.json"), "utf8"))
23622
+ stripJsonComments(fs27.readFileSync(path28.join(cwd, "package.json"), "utf8"))
23088
23623
  );
23089
23624
  hasScript = typeof parsed.scripts?.snapshot === "string";
23090
23625
  } catch {
@@ -23092,8 +23627,8 @@ function nextStepHint(cwd, scriptsAddedNow) {
23092
23627
  }
23093
23628
  }
23094
23629
  if (!hasScript) return `npx ${GENERATOR_NAME} generate`;
23095
- const bin = path27.join(cwd, "node_modules", ".bin", "codebase-snapshot");
23096
- const installed = fs26.existsSync(bin) || fs26.existsSync(`${bin}.cmd`);
23630
+ const bin = path28.join(cwd, "node_modules", ".bin", "codebase-snapshot");
23631
+ const installed = fs27.existsSync(bin) || fs27.existsSync(`${bin}.cmd`);
23097
23632
  return installed ? "npm run snapshot" : "npm install && npm run snapshot";
23098
23633
  }
23099
23634
  function presetSummary(init) {
@@ -23129,7 +23664,7 @@ async function runInitCommand(invocation) {
23129
23664
  if (hook) for (const note of hook.notes) info(` ${note}`);
23130
23665
  return 0;
23131
23666
  }
23132
- info(`\u2705 Created ${path27.basename(result.configPath)} (${presetSummary(result)})`);
23667
+ info(`\u2705 Created ${path28.basename(result.configPath)} (${presetSummary(result)})`);
23133
23668
  if (result.scripts.length > 0) info(` Added npm scripts: ${result.scripts.join(", ")}`);
23134
23669
  if (result.dependency.added && result.dependency.range !== null) {
23135
23670
  info(` Added devDependency: ${result.dependency.name} ${result.dependency.range}`);
@@ -23139,10 +23674,10 @@ async function runInitCommand(invocation) {
23139
23674
  }
23140
23675
  if (result.briefWritten) {
23141
23676
  info(
23142
- ` Wrote ${path27.basename(result.briefPath)}: a scaffold for the half of PROMPT.md only you can write. Fill it in, then set brief: ${JSON.stringify(path27.basename(result.briefPath))} in the config to merge it.`
23677
+ ` Wrote ${path28.basename(result.briefPath)}: a scaffold for the half of PROMPT.md only you can write. Fill it in, then set brief: ${JSON.stringify(path28.basename(result.briefPath))} in the config to merge it.`
23143
23678
  );
23144
- } else if (fs26.existsSync(result.briefPath)) {
23145
- info(` Kept ${path27.basename(result.briefPath)}: it already exists, and is never overwritten.`);
23679
+ } else if (fs27.existsSync(result.briefPath)) {
23680
+ info(` Kept ${path28.basename(result.briefPath)}: it already exists, and is never overwritten.`);
23146
23681
  }
23147
23682
  for (const note of result.notes) info(` \u26A0 ${note}`);
23148
23683
  if (hook) for (const note of hook.notes) info(` ${note}`);
@@ -23179,18 +23714,18 @@ function renderHealthText(report2) {
23179
23714
  function generatorOrigin(cwd) {
23180
23715
  try {
23181
23716
  const pkg = JSON.parse(
23182
- stripJsonComments(fs26.readFileSync(path27.join(cwd, "package.json"), "utf8"))
23717
+ stripJsonComments(fs27.readFileSync(path28.join(cwd, "package.json"), "utf8"))
23183
23718
  );
23184
23719
  const spec = pkg.dependencies?.["codebase-snapshot"] ?? pkg.devDependencies?.["codebase-snapshot"];
23185
23720
  if (typeof spec === "string") return `project dependency ${spec}`;
23186
23721
  } catch {
23187
23722
  }
23188
23723
  const entry = process.argv[1] ?? "";
23189
- if (entry.includes("_npx") || entry.includes(`${path27.sep}npx${path27.sep}`)) return "via npx";
23724
+ if (entry.includes("_npx") || entry.includes(`${path28.sep}npx${path28.sep}`)) return "via npx";
23190
23725
  return "global or direct install";
23191
23726
  }
23192
23727
  function detectPackageManager(cwd) {
23193
- const has = (name) => fs26.existsSync(path27.join(cwd, name));
23728
+ const has = (name) => fs27.existsSync(path28.join(cwd, name));
23194
23729
  if (has("bun.lockb") || has("bun.lock")) return { name: "bun", command: "bun", args: ["install"] };
23195
23730
  if (has("pnpm-lock.yaml")) return { name: "pnpm", command: "pnpm", args: ["install"] };
23196
23731
  if (has("yarn.lock")) return { name: "yarn", command: "yarn", args: ["install"] };
@@ -23307,7 +23842,7 @@ async function runSetupCommand(invocation, options = {}) {
23307
23842
  }
23308
23843
  info("\n\u{1F9EA} Dry run \u2014 setup would:");
23309
23844
  info(
23310
- ` 1. ${init.reused ? `keep ${path27.basename(keptConfigPath)}` : `write ${path27.basename(keptConfigPath)} (preset: ${appliedPreset})`}`
23845
+ ` 1. ${init.reused ? `keep ${path28.basename(keptConfigPath)}` : `write ${path28.basename(keptConfigPath)} (preset: ${appliedPreset})`}`
23311
23846
  );
23312
23847
  info(" 2. add the npm scripts, the devDependency and the .gitignore entries");
23313
23848
  if (manager !== null) info(` 3. install with ${manager}`);
@@ -23320,9 +23855,9 @@ async function runSetupCommand(invocation, options = {}) {
23320
23855
  if (invocation.format !== "json") {
23321
23856
  if (!interactive) info(`\u{1F680} Setup for: ${invocation.cwd}`);
23322
23857
  if (init.reused) {
23323
- info(`\u267B Keeping ${path27.basename(keptConfigPath)}`);
23858
+ info(`\u267B Keeping ${path28.basename(keptConfigPath)}`);
23324
23859
  } else {
23325
- info(`\u2705 Created ${path27.basename(keptConfigPath)} (${presetSummary(init)})`);
23860
+ info(`\u2705 Created ${path28.basename(keptConfigPath)} (${presetSummary(init)})`);
23326
23861
  }
23327
23862
  if (init.scripts.length > 0) info(` Added npm scripts: ${init.scripts.join(", ")}`);
23328
23863
  if (init.dependency.added && init.dependency.range !== null) {
@@ -23333,7 +23868,7 @@ async function runSetupCommand(invocation, options = {}) {
23333
23868
  }
23334
23869
  if (init.briefWritten) {
23335
23870
  info(
23336
- ` Wrote ${path27.basename(init.briefPath)}: a scaffold for the half of PROMPT.md only you can write. Fill it in, then set brief: ${JSON.stringify(path27.basename(init.briefPath))} in the config to merge it.`
23871
+ ` Wrote ${path28.basename(init.briefPath)}: a scaffold for the half of PROMPT.md only you can write. Fill it in, then set brief: ${JSON.stringify(path28.basename(init.briefPath))} in the config to merge it.`
23337
23872
  );
23338
23873
  }
23339
23874
  if (hook) for (const note of hook.notes) info(` ${note}`);
@@ -23341,7 +23876,7 @@ async function runSetupCommand(invocation, options = {}) {
23341
23876
  info(` \u26A0 --preset ${invocation.preset} was not applied: the existing config is kept.`);
23342
23877
  }
23343
23878
  }
23344
- const hasManifest = fs26.existsSync(path27.join(invocation.cwd, "package.json"));
23879
+ const hasManifest = fs27.existsSync(path28.join(invocation.cwd, "package.json"));
23345
23880
  let install = null;
23346
23881
  if (invocation.noInstall) {
23347
23882
  if (invocation.format !== "json") info(" Skipped the install (--no-install)");
@@ -23504,7 +24039,7 @@ function runSkillCommand(invocation) {
23504
24039
  }
23505
24040
  info(`\u2705 Agent skill installed (${SKILL_NAME}):`);
23506
24041
  for (const item of result.written) {
23507
- const shown = path27.relative(invocation.cwd, item.path) || item.path;
24042
+ const shown = path28.relative(invocation.cwd, item.path) || item.path;
23508
24043
  info(` - ${item.action.padEnd(9)} ${shown}`);
23509
24044
  }
23510
24045
  if (result.gitignored.length > 0) {
@@ -23665,7 +24200,7 @@ ${USAGE}
23665
24200
  }
23666
24201
  if (invocation.command === "serve") {
23667
24202
  const server = await startWebServer({
23668
- cwd: path27.resolve(invocation.cwd),
24203
+ cwd: path28.resolve(invocation.cwd),
23669
24204
  ...invocation.host === void 0 ? {} : { host: invocation.host },
23670
24205
  ...invocation.port === void 0 ? {} : { port: invocation.port },
23671
24206
  ...invocation.noAuth === true ? { token: null } : {},
@@ -23681,9 +24216,9 @@ ${USAGE}
23681
24216
  } else {
23682
24217
  warn(" WARNING: --no-auth is on. Any page on this machine can read the repository.");
23683
24218
  }
23684
- await new Promise((resolve15) => {
24219
+ await new Promise((resolve16) => {
23685
24220
  const stop = () => {
23686
- void server.close().then(resolve15);
24221
+ void server.close().then(resolve16);
23687
24222
  };
23688
24223
  process.once("SIGINT", stop);
23689
24224
  process.once("SIGTERM", stop);
@@ -23693,7 +24228,7 @@ ${USAGE}
23693
24228
  if (invocation.command === "mcp") {
23694
24229
  if (invocation.http === true) {
23695
24230
  const transport = await startHttpTransport({
23696
- cwd: path27.resolve(invocation.cwd),
24231
+ cwd: path28.resolve(invocation.cwd),
23697
24232
  ...invocation.host === void 0 ? {} : { host: invocation.host },
23698
24233
  ...invocation.port === void 0 ? {} : { port: invocation.port },
23699
24234
  ...invocation.noAuth === true ? { token: null } : {},
@@ -23709,16 +24244,16 @@ ${USAGE}
23709
24244
  } else {
23710
24245
  warn(" WARNING: --no-auth is on. Any page on this machine can read the repository.");
23711
24246
  }
23712
- await new Promise((resolve15) => {
24247
+ await new Promise((resolve16) => {
23713
24248
  const stop = () => {
23714
- void transport.close().then(resolve15);
24249
+ void transport.close().then(resolve16);
23715
24250
  };
23716
24251
  process.once("SIGINT", stop);
23717
24252
  process.once("SIGTERM", stop);
23718
24253
  });
23719
24254
  return 0;
23720
24255
  }
23721
- return await runStdioServer({ cwd: path27.resolve(invocation.cwd) });
24256
+ return await runStdioServer({ cwd: path28.resolve(invocation.cwd) });
23722
24257
  }
23723
24258
  if (invocation.command === "setup") {
23724
24259
  return runSetupCommand(invocation);
@@ -23746,7 +24281,7 @@ ${USAGE}
23746
24281
  log: (line) => info(" " + line)
23747
24282
  });
23748
24283
  sourceProvenance = clone.provenance;
23749
- const outDir = path27.resolve(invocation.cwd, invocation.outDir ?? "snapshot");
24284
+ const outDir = path28.resolve(invocation.cwd, invocation.outDir ?? "snapshot");
23750
24285
  invocation = { ...invocation, cwd: clone.directory, outDir, noConfig: true };
23751
24286
  info(
23752
24287
  " Source: " + parsed.source.owner + "/" + parsed.source.repo + "@" + clone.commit.slice(0, 12) + " (fetched " + clone.provenance.fetchedAt + ")"
@@ -23757,7 +24292,7 @@ ${USAGE}
23757
24292
  const directory = clone.directory;
23758
24293
  process.once("exit", () => {
23759
24294
  try {
23760
- fs26.rmSync(directory, { recursive: true, force: true });
24295
+ fs27.rmSync(directory, { recursive: true, force: true });
23761
24296
  } catch {
23762
24297
  }
23763
24298
  });
@@ -23776,7 +24311,7 @@ ${USAGE}
23776
24311
  );
23777
24312
  }
23778
24313
  for (const warning of loaded.warnings) warn(`\u26A0 Config: ${warning}`);
23779
- if (loaded.file) info(`\u2699 Using config ${path27.relative(process.cwd(), loaded.file) || loaded.file}`);
24314
+ if (loaded.file) info(`\u2699 Using config ${path28.relative(process.cwd(), loaded.file) || loaded.file}`);
23780
24315
  let resolved;
23781
24316
  try {
23782
24317
  resolved = resolveConfig(
@@ -23794,9 +24329,9 @@ ${USAGE}
23794
24329
  }
23795
24330
  if (invocation.command === "health") {
23796
24331
  if (invocation.allMembers === true) {
23797
- const outRoot = path27.resolve(resolved.cwd, resolved.outDir);
23798
- const indexPath = path27.join(outRoot, "WORKSPACE.json");
23799
- if (!fs26.existsSync(indexPath)) {
24332
+ const outRoot = path28.resolve(resolved.cwd, resolved.outDir);
24333
+ const indexPath = path28.join(outRoot, "WORKSPACE.json");
24334
+ if (!fs27.existsSync(indexPath)) {
23800
24335
  return fail(
23801
24336
  invocation.format,
23802
24337
  `No workspace index at ${indexPath}. Run generate --workspace <a,b> first, or drop --all-members.`
@@ -23804,16 +24339,16 @@ ${USAGE}
23804
24339
  }
23805
24340
  let index;
23806
24341
  try {
23807
- index = JSON.parse(fs26.readFileSync(indexPath, "utf8"));
24342
+ index = JSON.parse(fs27.readFileSync(indexPath, "utf8"));
23808
24343
  } catch (error) {
23809
24344
  return fail(invocation.format, `Could not read ${indexPath}: ${error.message}`);
23810
24345
  }
23811
24346
  const rows = [];
23812
24347
  for (const member of index.members ?? []) {
23813
24348
  const name = member.name ?? "?";
23814
- const snapshotDir2 = path27.join(outRoot, name);
23815
- const repoDir = path27.resolve(resolved.cwd, member.path ?? name);
23816
- if (!fs26.existsSync(path27.join(snapshotDir2, "manifest.json"))) {
24349
+ const snapshotDir2 = path28.join(outRoot, name);
24350
+ const repoDir = path28.resolve(resolved.cwd, member.path ?? name);
24351
+ if (!fs27.existsSync(path28.join(snapshotDir2, "manifest.json"))) {
23817
24352
  rows.push({ name, score: 0, counts: { pass: 0, warn: 0, fail: 1 }, failed: [], error: "no snapshot at " + snapshotDir2 });
23818
24353
  continue;
23819
24354
  }
@@ -23849,7 +24384,7 @@ ${USAGE}
23849
24384
  if (invocation.strict === true && totals.warn > 0) return 1;
23850
24385
  return 0;
23851
24386
  }
23852
- const snapshotDir = path27.resolve(resolved.cwd, resolved.outDir);
24387
+ const snapshotDir = path28.resolve(resolved.cwd, resolved.outDir);
23853
24388
  const report2 = auditSnapshot({
23854
24389
  snapshotDir,
23855
24390
  repoDir: resolved.cwd,
@@ -23861,13 +24396,13 @@ ${USAGE}
23861
24396
  return 0;
23862
24397
  }
23863
24398
  if (invocation.command === "report") {
23864
- const manifestPath = path27.resolve(resolved.cwd, resolved.outDir, "manifest.json");
23865
- if (!fs26.existsSync(manifestPath)) {
24399
+ const manifestPath = path28.resolve(resolved.cwd, resolved.outDir, "manifest.json");
24400
+ if (!fs27.existsSync(manifestPath)) {
23866
24401
  return fail(invocation.format, `Manifest not found at ${manifestPath}. Run generate first.`);
23867
24402
  }
23868
24403
  let manifest;
23869
24404
  try {
23870
- manifest = JSON.parse(fs26.readFileSync(manifestPath, "utf8"));
24405
+ manifest = JSON.parse(fs27.readFileSync(manifestPath, "utf8"));
23871
24406
  } catch (err) {
23872
24407
  return fail(invocation.format, `Could not read ${manifestPath}: ${err.message}`);
23873
24408
  }
@@ -23924,7 +24459,7 @@ ${USAGE}
23924
24459
  if (manifest.delta !== void 0) {
23925
24460
  const delta = manifest.delta;
23926
24461
  info("\n Selection (delta):");
23927
- info(` - Against: ${path27.basename(delta.base.path)} (${delta.base.fingerprint.slice(0, 12)})`);
24462
+ info(` - Against: ${path28.basename(delta.base.path)} (${delta.base.fingerprint.slice(0, 12)})`);
23928
24463
  info(
23929
24464
  ` - Changed: ${delta.changed.length} changed, ${delta.added.length} added, ${delta.removed.length} removed, ${delta.unchanged.length} unchanged`
23930
24465
  );
@@ -23979,15 +24514,23 @@ ${USAGE}
23979
24514
  "--workspace writes one snapshot per member; --remote, --delta, --slice, --budget-tokens and --sign do not combine with it."
23980
24515
  );
23981
24516
  }
23982
- const outRoot = path27.resolve(invocation.cwd, invocation.outDir ?? "snapshot");
24517
+ const outRoot = path28.resolve(invocation.cwd, invocation.outDir ?? "snapshot");
24518
+ const workspaceCwd = path28.resolve(invocation.cwd);
24519
+ const outRootRelative = path28.relative(outRoot, workspaceCwd);
24520
+ if (outRootRelative === "" || !outRootRelative.startsWith("..") && !path28.isAbsolute(outRootRelative)) {
24521
+ return fail(
24522
+ invocation.format,
24523
+ `--workspace refuses --out-dir ${outRoot}: it is the working directory or one of its ancestors.`
24524
+ );
24525
+ }
23983
24526
  const records = [];
23984
24527
  let failed = 0;
23985
24528
  for (const member of members) {
23986
- const directory = path27.resolve(invocation.cwd, member);
23987
- const name = path27.basename(directory);
24529
+ const directory = path28.resolve(invocation.cwd, member);
24530
+ const name = path28.basename(directory);
23988
24531
  let stat;
23989
24532
  try {
23990
- stat = fs26.statSync(directory);
24533
+ stat = fs27.statSync(directory);
23991
24534
  } catch {
23992
24535
  warn("\u26A0 Workspace member missing: " + member);
23993
24536
  failed += 1;
@@ -23999,7 +24542,10 @@ ${USAGE}
23999
24542
  continue;
24000
24543
  }
24001
24544
  try {
24002
- const manifest = generateSnapshot({ cwd: directory, outDir: path27.join(outRoot, name) });
24545
+ const manifest = generateSnapshot(
24546
+ { cwd: directory, outDir: path28.join(outRoot, name) },
24547
+ { dryRun: invocation.dryRun }
24548
+ );
24003
24549
  records.push({
24004
24550
  name,
24005
24551
  path: directory,
@@ -24015,17 +24561,17 @@ ${USAGE}
24015
24561
  failed += 1;
24016
24562
  }
24017
24563
  }
24018
- fs26.mkdirSync(outRoot, { recursive: true });
24564
+ if (!invocation.dryRun) fs27.mkdirSync(outRoot, { recursive: true });
24019
24565
  const links = [];
24020
24566
  for (const record of records) {
24021
24567
  const counts = /* @__PURE__ */ new Map();
24022
24568
  for (const entry of record.imports) {
24023
24569
  for (const specifier of entry.imports) {
24024
24570
  if (!specifier.startsWith(".")) continue;
24025
- const resolved2 = path27.resolve(record.path, path27.dirname(entry.path), specifier);
24571
+ const resolved2 = path28.resolve(record.path, path28.dirname(entry.path), specifier);
24026
24572
  for (const other of records) {
24027
24573
  if (other === record) continue;
24028
- const prefix = other.path + path27.sep;
24574
+ const prefix = other.path + path28.sep;
24029
24575
  if (!resolved2.startsWith(prefix) && resolved2 !== other.path) continue;
24030
24576
  const bucket = counts.get(other.name) ?? { count: 0, examples: [] };
24031
24577
  bucket.count += 1;
@@ -24045,9 +24591,17 @@ ${USAGE}
24045
24591
  members: records.map(({ imports: _imports, ...rest }) => rest),
24046
24592
  links
24047
24593
  };
24048
- fs26.writeFileSync(path27.join(outRoot, "WORKSPACE.json"), JSON.stringify(document, null, 2) + "\n", "utf8");
24594
+ if (!invocation.dryRun) {
24595
+ fs27.writeFileSync(
24596
+ path28.join(outRoot, "WORKSPACE.json"),
24597
+ JSON.stringify(document, null, 2) + "\n",
24598
+ "utf8"
24599
+ );
24600
+ }
24049
24601
  emit(invocation.format, document, () => {
24050
- info("\n\u{1F5C2} Workspace: " + records.length + " of " + members.length + " member(s) written under " + outRoot);
24602
+ info(
24603
+ "\n\u{1F5C2} Workspace: " + records.length + " of " + members.length + (invocation.dryRun ? " member(s) planned; nothing was written." : " member(s) written under " + outRoot)
24604
+ );
24051
24605
  for (const record of records) {
24052
24606
  info(" - " + record.name + " (" + record.fingerprint.slice(0, 12) + ")");
24053
24607
  }
@@ -24066,14 +24620,14 @@ ${USAGE}
24066
24620
  try {
24067
24621
  let deltaBase;
24068
24622
  if (invocation.delta !== void 0) {
24069
- const basePath = path27.resolve(invocation.cwd, invocation.delta);
24070
- const manifestPath = fs26.existsSync(basePath) && fs26.statSync(basePath).isDirectory() ? path27.join(basePath, "manifest.json") : basePath;
24071
- if (!fs26.existsSync(manifestPath)) {
24623
+ const basePath = path28.resolve(invocation.cwd, invocation.delta);
24624
+ const manifestPath = fs27.existsSync(basePath) && fs27.statSync(basePath).isDirectory() ? path28.join(basePath, "manifest.json") : basePath;
24625
+ if (!fs27.existsSync(manifestPath)) {
24072
24626
  return fail(invocation.format, "No manifest at " + manifestPath + ". Point --delta at a snapshot directory or its manifest.json.");
24073
24627
  }
24074
24628
  let base;
24075
24629
  try {
24076
- base = JSON.parse(fs26.readFileSync(manifestPath, "utf8"));
24630
+ base = JSON.parse(fs27.readFileSync(manifestPath, "utf8"));
24077
24631
  } catch (error) {
24078
24632
  return fail(invocation.format, "Could not read " + manifestPath + ": " + error.message);
24079
24633
  }
@@ -24098,9 +24652,9 @@ ${USAGE}
24098
24652
  ...invocation.sign === true && !invocation.dryRun ? { sign: { key: loadSigningKey() } } : {}
24099
24653
  });
24100
24654
  if (invocation.sign === true && !invocation.dryRun) {
24101
- const signaturePath = path27.resolve(resolved.cwd, resolved.outDir, SIGNATURE_FILE);
24655
+ const signaturePath = path28.resolve(resolved.cwd, resolved.outDir, SIGNATURE_FILE);
24102
24656
  try {
24103
- const record = JSON.parse(fs26.readFileSync(signaturePath, "utf8"));
24657
+ const record = JSON.parse(fs27.readFileSync(signaturePath, "utf8"));
24104
24658
  info(
24105
24659
  " Signature: ed25519, " + (record.keyOrigin ?? "unknown") + " key, " + (record.fingerprint ?? manifest.fingerprint).slice(0, 12)
24106
24660
  );
@@ -24253,19 +24807,19 @@ function finishWatchRun(state, now) {
24253
24807
  };
24254
24808
  }
24255
24809
  function comparablePath(value) {
24256
- const absolute = path27.resolve(value);
24810
+ const absolute = path28.resolve(value);
24257
24811
  return process.platform === "win32" ? absolute.toLowerCase() : absolute;
24258
24812
  }
24259
24813
  function isSameOrInside(parent, candidate) {
24260
- const relative16 = path27.relative(parent, candidate);
24261
- return relative16 === "" || relative16 !== ".." && !relative16.startsWith(`..${path27.sep}`) && !path27.isAbsolute(relative16);
24814
+ const relative17 = path28.relative(parent, candidate);
24815
+ return relative17 === "" || relative17 !== ".." && !relative17.startsWith(`..${path28.sep}`) && !path28.isAbsolute(relative17);
24262
24816
  }
24263
24817
  function isGeneratedWatchPath(candidate, paths) {
24264
- const absolute = comparablePath(path27.resolve(paths.cwd, candidate));
24265
- const outDir = comparablePath(path27.resolve(paths.cwd, paths.outDir));
24266
- const tmpDir = comparablePath(path27.resolve(paths.cwd, paths.tmpDir));
24818
+ const absolute = comparablePath(path28.resolve(paths.cwd, candidate));
24819
+ const outDir = comparablePath(path28.resolve(paths.cwd, paths.outDir));
24820
+ const tmpDir = comparablePath(path28.resolve(paths.cwd, paths.tmpDir));
24267
24821
  if (isSameOrInside(outDir, absolute) || isSameOrInside(tmpDir, absolute)) return true;
24268
- const offsets = [path27.basename(outDir), path27.basename(tmpDir)].filter((name) => name.length > 0);
24822
+ const offsets = [path28.basename(outDir), path28.basename(tmpDir)].filter((name) => name.length > 0);
24269
24823
  const leftover = absolute.split(/[\\/]+/).some(
24270
24824
  (segment) => offsets.some(
24271
24825
  (name) => segment.startsWith(`${name}.backup-`) || segment.startsWith(`${name}.partial-`)
@@ -24288,8 +24842,8 @@ function decideWatchEvent(state, event, paths) {
24288
24842
  function watchPathsFor(config) {
24289
24843
  return {
24290
24844
  cwd: config.cwd,
24291
- outDir: path27.resolve(config.cwd, config.outDir),
24292
- tmpDir: path27.resolve(config.cwd, config.tmpDir)
24845
+ outDir: path28.resolve(config.cwd, config.outDir),
24846
+ tmpDir: path28.resolve(config.cwd, config.tmpDir)
24293
24847
  };
24294
24848
  }
24295
24849
  function watchSupportProblem(platform = process.platform, version = process.versions.node) {
@@ -24364,11 +24918,11 @@ async function runWatchLoop(invocation, resolved, options) {
24364
24918
  if (!options.generatedAlready) void regenerate();
24365
24919
  let watcher;
24366
24920
  try {
24367
- watcher = fs26.watch(resolved.cwd, { recursive: true }, (_event, filename) => {
24921
+ watcher = fs27.watch(resolved.cwd, { recursive: true }, (_event, filename) => {
24368
24922
  const decision = decideWatchEvent(
24369
24923
  state,
24370
24924
  {
24371
- path: filename ? path27.resolve(resolved.cwd, filename.toString()) : null,
24925
+ path: filename ? path28.resolve(resolved.cwd, filename.toString()) : null,
24372
24926
  now: performance.now()
24373
24927
  },
24374
24928
  paths
@@ -24394,12 +24948,12 @@ async function runWatchLoop(invocation, resolved, options) {
24394
24948
  info(`\u26A0 Watch error: ${err.message}`);
24395
24949
  info(" The watcher may have missed changes. Restart with Ctrl+C if they stop arriving.");
24396
24950
  });
24397
- await new Promise((resolve15) => {
24951
+ await new Promise((resolve16) => {
24398
24952
  const stop = () => {
24399
24953
  stopped = true;
24400
24954
  if (timer) clearTimeout(timer);
24401
24955
  watcher.close();
24402
- resolve15();
24956
+ resolve16();
24403
24957
  };
24404
24958
  process.once("SIGINT", stop);
24405
24959
  process.once("SIGTERM", stop);
@@ -24407,7 +24961,7 @@ async function runWatchLoop(invocation, resolved, options) {
24407
24961
  return 0;
24408
24962
  }
24409
24963
  var entryFile = process.argv[1] ?? "";
24410
- var entryName = path27.basename(entryFile).toLowerCase();
24964
+ var entryName = path28.basename(entryFile).toLowerCase();
24411
24965
  var invokedDirectly = entryName === "cli.js" || entryName === "cli.cjs";
24412
24966
  if (invokedDirectly) {
24413
24967
  void main().then(