codebase-snapshot 0.20.4 → 0.20.6

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/cli.cjs CHANGED
@@ -48,6 +48,180 @@ var http__namespace = /*#__PURE__*/_interopNamespace(http);
48
48
  var https__namespace = /*#__PURE__*/_interopNamespace(https);
49
49
 
50
50
  // src/cli.ts
51
+
52
+ // src/ast/structured.ts
53
+ function stripJsonComments(content) {
54
+ const text2 = content.replace(/^\uFEFF/, "");
55
+ const withoutComments = stripComments(text2);
56
+ return stripTrailingCommas(withoutComments);
57
+ }
58
+ function stripComments(text2) {
59
+ let out = "";
60
+ let inString = false;
61
+ let escaped = false;
62
+ for (let index = 0; index < text2.length; index += 1) {
63
+ const char = text2[index];
64
+ if (inString) {
65
+ out += char;
66
+ if (escaped) escaped = false;
67
+ else if (char === "\\") escaped = true;
68
+ else if (char === '"') inString = false;
69
+ continue;
70
+ }
71
+ if (char === '"') {
72
+ inString = true;
73
+ out += char;
74
+ continue;
75
+ }
76
+ if (char === "/" && text2[index + 1] === "/") {
77
+ while (index < text2.length && text2[index] !== "\n" && text2[index] !== "\r") index += 1;
78
+ index -= 1;
79
+ continue;
80
+ }
81
+ if (char === "/" && text2[index + 1] === "*") {
82
+ index += 2;
83
+ while (index < text2.length && !(text2[index] === "*" && text2[index + 1] === "/")) {
84
+ if (text2[index] === "\n" || text2[index] === "\r") out += text2[index];
85
+ index += 1;
86
+ }
87
+ index += 1;
88
+ continue;
89
+ }
90
+ out += char;
91
+ }
92
+ return out;
93
+ }
94
+ function stripTrailingCommas(text2) {
95
+ let out = "";
96
+ let inString = false;
97
+ let escaped = false;
98
+ for (let index = 0; index < text2.length; index += 1) {
99
+ const char = text2[index];
100
+ if (inString) {
101
+ out += char;
102
+ if (escaped) escaped = false;
103
+ else if (char === "\\") escaped = true;
104
+ else if (char === '"') inString = false;
105
+ continue;
106
+ }
107
+ if (char === '"') {
108
+ inString = true;
109
+ out += char;
110
+ continue;
111
+ }
112
+ if (char === ",") {
113
+ let next = index + 1;
114
+ while (next < text2.length && /\s/.test(text2[next])) next += 1;
115
+ if (text2[next] === "}" || text2[next] === "]") continue;
116
+ }
117
+ out += char;
118
+ }
119
+ return out;
120
+ }
121
+ function summarizeJson(content) {
122
+ try {
123
+ const parsed = JSON.parse(stripJsonComments(content));
124
+ if (Array.isArray(parsed)) {
125
+ const sample2 = parsed[0];
126
+ const sampleKeys = sample2 && typeof sample2 === "object" && !Array.isArray(sample2) ? Object.keys(sample2).slice(0, 10).sort() : [];
127
+ return {
128
+ shape: "array",
129
+ itemCount: parsed.length,
130
+ keys: [],
131
+ sampleKeys
132
+ };
133
+ }
134
+ if (parsed && typeof parsed === "object") {
135
+ const keys = Object.keys(parsed).sort();
136
+ return {
137
+ shape: "object",
138
+ itemCount: keys.length,
139
+ keys: keys.slice(0, 30),
140
+ sampleKeys: []
141
+ };
142
+ }
143
+ return {
144
+ shape: typeof parsed,
145
+ itemCount: null,
146
+ keys: [],
147
+ sampleKeys: []
148
+ };
149
+ } catch {
150
+ return {
151
+ shape: "invalid-json",
152
+ itemCount: null,
153
+ keys: [],
154
+ sampleKeys: []
155
+ };
156
+ }
157
+ }
158
+ function frontMatterEnd(lines) {
159
+ if (lines.length < 3 || lines[0].trim() !== "---") return 0;
160
+ for (let index = 1; index < lines.length; index += 1) {
161
+ const line = lines[index];
162
+ const candidate = line.trim();
163
+ if (candidate === "---" || candidate === "...") {
164
+ return index > 1 ? index : 0;
165
+ }
166
+ if (candidate === "") continue;
167
+ if (/^#(\s|$)/.test(candidate)) continue;
168
+ if (/^(`{3,}|~{3,})/.test(candidate)) return 0;
169
+ if (/^#{1,6}\s+\S/.test(candidate)) return 0;
170
+ const isYamlMapping = /^[A-Za-z0-9_.-]+\s*:(\s|$)/.test(candidate);
171
+ const isListItem = /^-(?:(\s|$))/.test(candidate);
172
+ const isIndented = /^[ \t]/.test(line);
173
+ if (!isYamlMapping && !isListItem && !isIndented) return 0;
174
+ }
175
+ return 0;
176
+ }
177
+ function summarizeMarkdown(content) {
178
+ const headings = [];
179
+ const frontmatterKeys = [];
180
+ const lines = content.replace(/^\uFEFF/, "").split(/\r\n|\n|\r/);
181
+ let inFrontmatter = false;
182
+ let fence = null;
183
+ const frontMatterEndLine = frontMatterEnd(lines);
184
+ for (let index = 0; index < lines.length; index++) {
185
+ const line = lines[index];
186
+ if (index === 0 && frontMatterEndLine > 0) {
187
+ inFrontmatter = true;
188
+ continue;
189
+ }
190
+ if (inFrontmatter) {
191
+ const trimmedFrontmatter = line.trim();
192
+ if (trimmedFrontmatter === "---" || trimmedFrontmatter === "...") {
193
+ inFrontmatter = false;
194
+ continue;
195
+ }
196
+ const match = /^([A-Za-z0-9_.-]+)\s*:/.exec(line);
197
+ if (match) frontmatterKeys.push(match[1]);
198
+ continue;
199
+ }
200
+ const trimmed = line.trim();
201
+ const fenceMatch = /^(`{3,}|~{3,})(.*)$/.exec(trimmed);
202
+ if (fenceMatch) {
203
+ const run = fenceMatch[1];
204
+ const rest = fenceMatch[2].trim();
205
+ if (fence === null) {
206
+ fence = { marker: run[0], length: run.length };
207
+ } else if (run[0] === fence.marker && run.length >= fence.length && rest === "") {
208
+ fence = null;
209
+ }
210
+ continue;
211
+ }
212
+ if (fence !== null) continue;
213
+ const headingMatch = /^(#{1,6})\s+(.+)$/.exec(trimmed);
214
+ if (headingMatch) {
215
+ headings.push(`${headingMatch[1]} ${headingMatch[2].trim()}`);
216
+ }
217
+ }
218
+ return {
219
+ headings: headings.slice(0, 40),
220
+ frontmatterKeys: Array.from(new Set(frontmatterKeys)).sort()
221
+ };
222
+ }
223
+
224
+ // src/presets/context.ts
51
225
  var MANIFEST_FILES = [
52
226
  "package.json",
53
227
  "pyproject.toml",
@@ -107,7 +281,7 @@ function readManifest(cwd, name) {
107
281
  function dependenciesFromPackageJson(raw) {
108
282
  const names = /* @__PURE__ */ new Set();
109
283
  try {
110
- const parsed = JSON.parse(raw);
284
+ const parsed = JSON.parse(stripJsonComments(raw.replace(/^\uFEFF/, "")));
111
285
  for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
112
286
  const block = parsed[section];
113
287
  if (block && typeof block === "object") {
@@ -197,8 +371,8 @@ function workspacePackageDirs(cwd, patterns) {
197
371
  function scanWorkspacePackages(cwd, patterns) {
198
372
  const files = /* @__PURE__ */ new Set();
199
373
  const dependencies = /* @__PURE__ */ new Set();
200
- for (const relative16 of workspacePackageDirs(cwd, patterns)) {
201
- const full = path27__namespace.join(cwd, relative16);
374
+ for (const relative17 of workspacePackageDirs(cwd, patterns)) {
375
+ const full = path27__namespace.join(cwd, relative17);
202
376
  try {
203
377
  for (const entry of fs24__namespace.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
204
378
  } catch {
@@ -1412,7 +1586,7 @@ var DEFAULT_SECRET_PATTERNS = [
1412
1586
  // rendering of textual userinfo mixes cases, while the prose the earlier rules were
1413
1587
  // protecting (`Bearer authentication`) is a lowercase word.
1414
1588
  rule: "authorization-header",
1415
- 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_.+/=-])/
1589
+ 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_.+/=-])/
1416
1590
  },
1417
1591
  {
1418
1592
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -1990,6 +2164,7 @@ function redactStructuredValues(text2, filePath, recordFinding) {
1990
2164
  if (firstValue === void 0) continue;
1991
2165
  const valueIndent = (/^[ \t]*/.exec(firstValue)?.[0] ?? "").length;
1992
2166
  if (valueIndent <= baseIndent) continue;
2167
+ if (STRUCTURED_KEY.test(firstValue) || /^[ \t]*-[ \t]/.test(firstValue)) continue;
1993
2168
  let masked = false;
1994
2169
  while (cursor < segments.length) {
1995
2170
  const body = segments[cursor] ?? "";
@@ -2005,7 +2180,7 @@ function redactStructuredValues(text2, filePath, recordFinding) {
2005
2180
  }
2006
2181
  return segments.join("");
2007
2182
  }
2008
- var DOCKERFILE_ENV = /^([ \t]*ENV[ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]+)(\S.*)$/;
2183
+ var DOCKERFILE_ENV = /^([ \t]*)(ENV|ARG)([ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]*=[ \t]*|[ \t]+)(\S.*)$/i;
2009
2184
  function redactDockerfileEnv(text2, filePath, recordFinding) {
2010
2185
  if (!isDockerfile(filePath)) return text2;
2011
2186
  const segments = text2.split(LINE_BREAK);
@@ -2014,10 +2189,9 @@ function redactDockerfileEnv(text2, filePath, recordFinding) {
2014
2189
  if (line === void 0) continue;
2015
2190
  const match = DOCKERFILE_ENV.exec(line);
2016
2191
  if (match === null) continue;
2017
- if (!CREDENTIAL_KEY_TAIL.test(match[2] ?? "")) continue;
2018
- const value = match[4] ?? "";
2019
- if (value.startsWith("=")) continue;
2020
- segments[index] = `${match[1]}${match[2]}${match[3]}${REDACTION_MARKER}`;
2192
+ if (!CREDENTIAL_KEY_TAIL.test(match[4] ?? "")) continue;
2193
+ const separator = match[5] ?? "";
2194
+ segments[index] = `${match[1]}${match[2]}${match[3]}${match[4]}${separator}${REDACTION_MARKER}`;
2021
2195
  recordFinding(index / 2 + 1, ["dockerfile-env-secret"]);
2022
2196
  }
2023
2197
  return segments.join("");
@@ -2102,6 +2276,7 @@ function isSourceCodeFile(filePath) {
2102
2276
  var PLACEHOLDER_PATTERNS = [
2103
2277
  /^<[^>]*>?$/,
2104
2278
  /^\.{3,}$/,
2279
+ /^(?:[A-Za-z0-9_-]{1,8}-)?\.{3,}$/,
2105
2280
  /^(?:x{4,}|X{4,}|\*{3,})$/,
2106
2281
  /^(?:replace|change)[-_ ]?me(?:[-_ ].*)?$/i,
2107
2282
  /^your[-_ ].*$/i,
@@ -2115,7 +2290,7 @@ function isPlaceholderValue(value) {
2115
2290
  if (trimmed.length === 0) return false;
2116
2291
  if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
2117
2292
  if (trimmed.includes(REDACTION_MARKER) || trimmed.includes(PEM_REDACTION_MARKER)) return true;
2118
- return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
2293
+ return false;
2119
2294
  }
2120
2295
  function quotesAreBalanced(text2) {
2121
2296
  let single = 0;
@@ -2167,6 +2342,7 @@ var ASSIGNMENT_FILE = /\.(?:sh|bash|zsh|ksh|fish|env|ya?ml|toml|ini|conf|cfg|pro
2167
2342
  var ASSIGNMENT_BASENAME = /^(?:\.env(?:\.[^/]*)?|\.envrc|\.profile|\.bashrc|\.zshrc|\.bash_profile)$/i;
2168
2343
  function isAssignmentFile(filePath) {
2169
2344
  if (filePath === void 0) return false;
2345
+ if (isDockerfile(filePath)) return true;
2170
2346
  const normalised = filePath.replace(/\\/g, "/");
2171
2347
  if (ASSIGNMENT_FILE.test(normalised)) return true;
2172
2348
  const base = normalised.slice(normalised.lastIndexOf("/") + 1);
@@ -2275,6 +2451,15 @@ function verifySnapshotSignature(snapshotDir) {
2275
2451
  if (sha2562 !== record.manifestSha256) {
2276
2452
  return { ok: false, reason: "manifest.json changed after it was signed" };
2277
2453
  }
2454
+ let signedFingerprint;
2455
+ try {
2456
+ signedFingerprint = JSON.parse(bytes.toString("utf8")).fingerprint;
2457
+ } catch {
2458
+ return { ok: false, reason: "the signed manifest is not JSON" };
2459
+ }
2460
+ if (typeof record.fingerprint !== "string" || record.fingerprint !== signedFingerprint) {
2461
+ return { ok: false, reason: "signature.json names a different fingerprint than the manifest" };
2462
+ }
2278
2463
  let verified = false;
2279
2464
  try {
2280
2465
  const key = crypto__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
@@ -2287,7 +2472,7 @@ function verifySnapshotSignature(snapshotDir) {
2287
2472
 
2288
2473
  // src/version.ts
2289
2474
  var GENERATOR_NAME = "codebase-snapshot";
2290
- var GENERATOR_VERSION = "0.20.4";
2475
+ var GENERATOR_VERSION = "0.20.6";
2291
2476
  var SCHEMA_VERSION = "3.0.0";
2292
2477
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2293
2478
  function isOurGeneratorName(name) {
@@ -2319,8 +2504,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
2319
2504
  };
2320
2505
  }
2321
2506
  function isInside(root, candidate) {
2322
- const relative16 = path27__namespace.relative(root, candidate);
2323
- return relative16 === "" || !relative16.startsWith(`..${path27__namespace.sep}`) && relative16 !== ".." && !path27__namespace.isAbsolute(relative16);
2507
+ const relative17 = path27__namespace.relative(root, candidate);
2508
+ return relative17 === "" || !relative17.startsWith(`..${path27__namespace.sep}`) && relative17 !== ".." && !path27__namespace.isAbsolute(relative17);
2324
2509
  }
2325
2510
  var GIT_OUTPUT_LIMIT = 68157440;
2326
2511
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -2386,7 +2571,7 @@ var DEFAULT_IGNORED_FILES = [
2386
2571
  var SENSITIVE_BASENAME = /^(?:\.env(?:[._-][A-Za-z0-9_-]*)*|\.env(?:backup|bak|old|orig|copy|save)|\.envrc|\.npmrc(?:\.[A-Za-z0-9_-]+)?|\.yarnrc(?:\.yml)?|\.netrc(?:\.[A-Za-z0-9_-]+)?|\.git-credentials|\.htpasswd|\.pgpass|\.pypirc|\.vault-token|vault[-_]agent[-_]token|\.composer-auth\.json|auth\.json|application_default_credentials\.json|id_[a-z0-9_]+(?:\.[A-Za-z0-9_-]+)?|credentials(?:\.(?:json|ya?ml|toml))?|service[-_]?account(?:\.[a-z0-9_-]+)*\.json|secrets?\.(?:json|ya?ml|toml)|env|[A-Za-z0-9_-]{1,64}\.env)$/i;
2387
2572
  var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$|(?:^|\/)\.config\/gcloud\/|(?:^|\/)\.composer\/|(?:^|\/)\.terraform\/credentials\.tfrc\.json$/i;
2388
2573
  var SENSITIVE_EXT = /\.(?:pem|key|p12|pfx|jks|keystore|ppk|asc|kdbx|tfstate|tfvars)$/i;
2389
- var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.[A-Za-z0-9_-]+)?$/i;
2574
+ var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.(?:json|ya?ml|toml|ini|txt|md|properties|conf|cfg))?$/i;
2390
2575
  var BACKUP_SUFFIX = /(?:~|\.(?:bak|backup|old|orig|save|copy|swp|swo|tmp|part))$/i;
2391
2576
  function normaliseName(name) {
2392
2577
  let normalised = name.trim().replace(/[. ]+$/, "");
@@ -2815,30 +3000,67 @@ function isToolOwnedDirectory2(dir) {
2815
3000
  }
2816
3001
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
2817
3002
  const marker2 = parsed;
2818
- if (marker2.generator !== GENERATOR_NAME || marker2.state !== "complete" || typeof marker2.id !== "string" || !Array.isArray(marker2.files)) {
3003
+ if (marker2.generator !== GENERATOR_NAME || marker2.state !== "complete" || marker2.schemaVersion !== SCHEMA_VERSION || typeof marker2.id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(marker2.id) || typeof marker2.manifestSha256 !== "string" || !Array.isArray(marker2.files)) {
2819
3004
  return false;
2820
3005
  }
2821
- const accounted = /* @__PURE__ */ new Set();
3006
+ let manifestBytes;
3007
+ try {
3008
+ manifestBytes = fs24__namespace.readFileSync(path27__namespace.join(dir, "manifest.json"));
3009
+ } catch {
3010
+ return false;
3011
+ }
3012
+ if (crypto.createHash("sha256").update(manifestBytes).digest("hex") !== marker2.manifestSha256) {
3013
+ return false;
3014
+ }
3015
+ const recordedFiles = /* @__PURE__ */ new Set();
2822
3016
  for (const item of marker2.files) {
2823
3017
  if (!item || typeof item !== "object" || Array.isArray(item)) return false;
2824
- const entry = item.path;
2825
- if (typeof entry !== "string" || entry.length === 0) return false;
2826
- const parts = entry.split("/");
2827
- for (let depth = 1; depth <= parts.length; depth += 1) {
2828
- accounted.add(parts.slice(0, depth).join("/"));
3018
+ const record = item;
3019
+ const entry = record.path;
3020
+ if (typeof entry !== "string" || entry.length === 0 || entry.includes(String.fromCharCode(92)) || entry.includes("\0") || path27__namespace.isAbsolute(entry) || entry.split("/").includes("..") || typeof record.bytes !== "number" || !Number.isSafeInteger(record.bytes) || record.bytes < 0 || typeof record.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(record.sha256)) {
3021
+ return false;
3022
+ }
3023
+ const full = path27__namespace.join(dir, ...entry.split("/"));
3024
+ let stats;
3025
+ try {
3026
+ stats = fs24__namespace.lstatSync(full);
3027
+ } catch {
3028
+ return false;
3029
+ }
3030
+ if (!stats.isFile() || stats.size !== record.bytes) return false;
3031
+ let digest;
3032
+ try {
3033
+ digest = crypto.createHash("sha256").update(fs24__namespace.readFileSync(full)).digest("hex");
3034
+ } catch {
3035
+ return false;
2829
3036
  }
3037
+ if (digest !== record.sha256) return false;
3038
+ recordedFiles.add(entry);
2830
3039
  }
2831
- let entries;
2832
- try {
2833
- entries = fs24__namespace.readdirSync(dir);
2834
- } catch {
2835
- return false;
3040
+ const stack = [""];
3041
+ while (stack.length > 0) {
3042
+ const current = stack.pop();
3043
+ let entries;
3044
+ try {
3045
+ entries = fs24__namespace.readdirSync(path27__namespace.join(dir, current), { withFileTypes: true });
3046
+ } catch {
3047
+ return false;
3048
+ }
3049
+ for (const entry of entries) {
3050
+ const relative17 = current === "" ? entry.name : current + "/" + entry.name;
3051
+ if (relative17 === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry.name)) continue;
3052
+ if (entry.isDirectory()) {
3053
+ stack.push(relative17);
3054
+ continue;
3055
+ }
3056
+ if (!entry.isFile()) return false;
3057
+ if (relative17 === "signature.json" && !recordedFiles.has(relative17) && verifySnapshotSignature(dir).ok) {
3058
+ continue;
3059
+ }
3060
+ if (!recordedFiles.has(relative17)) return false;
3061
+ }
2836
3062
  }
2837
- return entries.every(
2838
- (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || // A snapshot signed before signing moved into staging has a valid signature.json the old
2839
- // marker could not record. It is our artifact when the signature verifies.
2840
- entry === "signature.json" && verifySnapshotSignature(dir).ok || accounted.has(entry)
2841
- );
3063
+ return true;
2842
3064
  }
2843
3065
  function makeToolOwnedDecider(cwd, toolOwnedPaths) {
2844
3066
  const markers = /* @__PURE__ */ new Map();
@@ -3039,7 +3261,7 @@ function collectFiles(cwd, options = {}) {
3039
3261
  candidates.push(extra);
3040
3262
  }
3041
3263
  }
3042
- const files = candidates.filter((file) => {
3264
+ let files = candidates.filter((file) => {
3043
3265
  if (isToolOwned(file)) return false;
3044
3266
  const ignored = defaultIgnoreReason(file, toolDirNames);
3045
3267
  if (ignored) {
@@ -3084,8 +3306,51 @@ function collectFiles(cwd, options = {}) {
3084
3306
  }
3085
3307
  return true;
3086
3308
  }).sort();
3309
+ files = dropSymlinksToUnincludedTargets(cwd, files, skipped);
3087
3310
  return { files, skipped: maskSkipPaths(skipped, pathRules) };
3088
3311
  }
3312
+ function dropSymlinksToUnincludedTargets(cwd, files, skipped) {
3313
+ const aliases = /* @__PURE__ */ new Set();
3314
+ for (const file of files) {
3315
+ try {
3316
+ if (fs24__namespace.lstatSync(path27__namespace.join(cwd, file)).isSymbolicLink()) aliases.add(file);
3317
+ } catch {
3318
+ }
3319
+ }
3320
+ if (aliases.size === 0) return [...files];
3321
+ const includedTargets = /* @__PURE__ */ new Set();
3322
+ for (const file of files) {
3323
+ if (aliases.has(file)) continue;
3324
+ try {
3325
+ includedTargets.add(fs24__namespace.realpathSync(path27__namespace.join(cwd, file)));
3326
+ } catch {
3327
+ }
3328
+ }
3329
+ const kept = [];
3330
+ for (const file of files) {
3331
+ if (!aliases.has(file)) {
3332
+ kept.push(file);
3333
+ continue;
3334
+ }
3335
+ let target;
3336
+ try {
3337
+ target = fs24__namespace.realpathSync(path27__namespace.join(cwd, file));
3338
+ } catch {
3339
+ skipped.push({ path: file, reason: "read-error", detail: "symlink target could not be resolved" });
3340
+ continue;
3341
+ }
3342
+ if (includedTargets.has(target)) {
3343
+ kept.push(file);
3344
+ continue;
3345
+ }
3346
+ skipped.push({
3347
+ path: file,
3348
+ reason: "symlink",
3349
+ detail: "link target was excluded from the snapshot; not followed"
3350
+ });
3351
+ }
3352
+ return kept;
3353
+ }
3089
3354
  function rootRealFor(root) {
3090
3355
  try {
3091
3356
  return fs24__namespace.realpathSync(root);
@@ -3221,178 +3486,6 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3221
3486
  }
3222
3487
  return results;
3223
3488
  }
3224
-
3225
- // src/ast/structured.ts
3226
- function stripJsonComments(content) {
3227
- const text2 = content.replace(/^\uFEFF/, "");
3228
- const withoutComments = stripComments(text2);
3229
- return stripTrailingCommas(withoutComments);
3230
- }
3231
- function stripComments(text2) {
3232
- let out = "";
3233
- let inString = false;
3234
- let escaped = false;
3235
- for (let index = 0; index < text2.length; index += 1) {
3236
- const char = text2[index];
3237
- if (inString) {
3238
- out += char;
3239
- if (escaped) escaped = false;
3240
- else if (char === "\\") escaped = true;
3241
- else if (char === '"') inString = false;
3242
- continue;
3243
- }
3244
- if (char === '"') {
3245
- inString = true;
3246
- out += char;
3247
- continue;
3248
- }
3249
- if (char === "/" && text2[index + 1] === "/") {
3250
- while (index < text2.length && text2[index] !== "\n" && text2[index] !== "\r") index += 1;
3251
- index -= 1;
3252
- continue;
3253
- }
3254
- if (char === "/" && text2[index + 1] === "*") {
3255
- index += 2;
3256
- while (index < text2.length && !(text2[index] === "*" && text2[index + 1] === "/")) {
3257
- if (text2[index] === "\n" || text2[index] === "\r") out += text2[index];
3258
- index += 1;
3259
- }
3260
- index += 1;
3261
- continue;
3262
- }
3263
- out += char;
3264
- }
3265
- return out;
3266
- }
3267
- function stripTrailingCommas(text2) {
3268
- let out = "";
3269
- let inString = false;
3270
- let escaped = false;
3271
- for (let index = 0; index < text2.length; index += 1) {
3272
- const char = text2[index];
3273
- if (inString) {
3274
- out += char;
3275
- if (escaped) escaped = false;
3276
- else if (char === "\\") escaped = true;
3277
- else if (char === '"') inString = false;
3278
- continue;
3279
- }
3280
- if (char === '"') {
3281
- inString = true;
3282
- out += char;
3283
- continue;
3284
- }
3285
- if (char === ",") {
3286
- let next = index + 1;
3287
- while (next < text2.length && /\s/.test(text2[next])) next += 1;
3288
- if (text2[next] === "}" || text2[next] === "]") continue;
3289
- }
3290
- out += char;
3291
- }
3292
- return out;
3293
- }
3294
- function summarizeJson(content) {
3295
- try {
3296
- const parsed = JSON.parse(stripJsonComments(content));
3297
- if (Array.isArray(parsed)) {
3298
- const sample2 = parsed[0];
3299
- const sampleKeys = sample2 && typeof sample2 === "object" && !Array.isArray(sample2) ? Object.keys(sample2).slice(0, 10).sort() : [];
3300
- return {
3301
- shape: "array",
3302
- itemCount: parsed.length,
3303
- keys: [],
3304
- sampleKeys
3305
- };
3306
- }
3307
- if (parsed && typeof parsed === "object") {
3308
- const keys = Object.keys(parsed).sort();
3309
- return {
3310
- shape: "object",
3311
- itemCount: keys.length,
3312
- keys: keys.slice(0, 30),
3313
- sampleKeys: []
3314
- };
3315
- }
3316
- return {
3317
- shape: typeof parsed,
3318
- itemCount: null,
3319
- keys: [],
3320
- sampleKeys: []
3321
- };
3322
- } catch {
3323
- return {
3324
- shape: "invalid-json",
3325
- itemCount: null,
3326
- keys: [],
3327
- sampleKeys: []
3328
- };
3329
- }
3330
- }
3331
- function frontMatterEnd(lines) {
3332
- if (lines.length < 3 || lines[0].trim() !== "---") return 0;
3333
- for (let index = 1; index < lines.length; index += 1) {
3334
- const line = lines[index];
3335
- const candidate = line.trim();
3336
- if (candidate === "---" || candidate === "...") {
3337
- return index > 1 ? index : 0;
3338
- }
3339
- if (candidate === "") continue;
3340
- if (/^#(\s|$)/.test(candidate)) continue;
3341
- if (/^(`{3,}|~{3,})/.test(candidate)) return 0;
3342
- if (/^#{1,6}\s+\S/.test(candidate)) return 0;
3343
- const isYamlMapping = /^[A-Za-z0-9_.-]+\s*:(\s|$)/.test(candidate);
3344
- const isListItem = /^-(?:(\s|$))/.test(candidate);
3345
- const isIndented = /^[ \t]/.test(line);
3346
- if (!isYamlMapping && !isListItem && !isIndented) return 0;
3347
- }
3348
- return 0;
3349
- }
3350
- function summarizeMarkdown(content) {
3351
- const headings = [];
3352
- const frontmatterKeys = [];
3353
- const lines = content.replace(/^\uFEFF/, "").split(/\r\n|\n|\r/);
3354
- let inFrontmatter = false;
3355
- let fence = null;
3356
- const frontMatterEndLine = frontMatterEnd(lines);
3357
- for (let index = 0; index < lines.length; index++) {
3358
- const line = lines[index];
3359
- if (index === 0 && frontMatterEndLine > 0) {
3360
- inFrontmatter = true;
3361
- continue;
3362
- }
3363
- if (inFrontmatter) {
3364
- const trimmedFrontmatter = line.trim();
3365
- if (trimmedFrontmatter === "---" || trimmedFrontmatter === "...") {
3366
- inFrontmatter = false;
3367
- continue;
3368
- }
3369
- const match = /^([A-Za-z0-9_.-]+)\s*:/.exec(line);
3370
- if (match) frontmatterKeys.push(match[1]);
3371
- continue;
3372
- }
3373
- const trimmed = line.trim();
3374
- const fenceMatch = /^(`{3,}|~{3,})(.*)$/.exec(trimmed);
3375
- if (fenceMatch) {
3376
- const run = fenceMatch[1];
3377
- const rest = fenceMatch[2].trim();
3378
- if (fence === null) {
3379
- fence = { marker: run[0], length: run.length };
3380
- } else if (run[0] === fence.marker && run.length >= fence.length && rest === "") {
3381
- fence = null;
3382
- }
3383
- continue;
3384
- }
3385
- if (fence !== null) continue;
3386
- const headingMatch = /^(#{1,6})\s+(.+)$/.exec(trimmed);
3387
- if (headingMatch) {
3388
- headings.push(`${headingMatch[1]} ${headingMatch[2].trim()}`);
3389
- }
3390
- }
3391
- return {
3392
- headings: headings.slice(0, 40),
3393
- frontmatterKeys: Array.from(new Set(frontmatterKeys)).sort()
3394
- };
3395
- }
3396
3489
  var OWNER_SECTIONS = ["Stakes", "The system", "What came before", "The bar", "Calibration"];
3397
3490
  var RESERVED_SECTIONS = [
3398
3491
  "The job",
@@ -3588,8 +3681,25 @@ function normalizeResolvedConfig(config) {
3588
3681
  monolithWanted,
3589
3682
  monolithWanted
3590
3683
  );
3684
+ if (!Number.isSafeInteger(config.maxPartBytes) || config.maxPartBytes < MIN_MAX_PART_BYTES) {
3685
+ throw new Error(
3686
+ `maxPartBytes must be at least ${MIN_MAX_PART_BYTES} bytes (received ${String(config.maxPartBytes)}).`
3687
+ );
3688
+ }
3689
+ if (!Number.isSafeInteger(config.largeFileBytes) || config.largeFileBytes < 0) {
3690
+ throw new Error(
3691
+ `largeFileBytes must be a non-negative integer; received ${String(config.largeFileBytes)}.`
3692
+ );
3693
+ }
3694
+ const maxPartTokens = config.maxPartTokens ?? Math.floor(config.maxPartBytes / 4);
3695
+ if (!Number.isSafeInteger(maxPartTokens) || maxPartTokens < MIN_MAX_PART_TOKENS) {
3696
+ throw new Error(
3697
+ `maxPartTokens must be at least ${MIN_MAX_PART_TOKENS} tokens; received ${String(maxPartTokens)}.`
3698
+ );
3699
+ }
3591
3700
  return markResolvedConfig({
3592
3701
  ...config,
3702
+ maxPartTokens,
3593
3703
  discovery,
3594
3704
  // A spread copy built before the field existed carries no value; the default applies, and it
3595
3705
  // is re-validated because the number reaches a rendered artifact.
@@ -4023,13 +4133,13 @@ function readConfiguredBrief(cwd, value) {
4023
4133
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
4024
4134
  );
4025
4135
  }
4026
- const relative16 = path27__namespace.relative(rootReal, filePath);
4027
- if (relative16.length === 0 || relative16 === ".." || relative16.startsWith(`..${path27__namespace.sep}`) || path27__namespace.isAbsolute(relative16)) {
4136
+ const relative17 = path27__namespace.relative(rootReal, filePath);
4137
+ if (relative17.length === 0 || relative17 === ".." || relative17.startsWith(`..${path27__namespace.sep}`) || path27__namespace.isAbsolute(relative17)) {
4028
4138
  throw new Error(
4029
4139
  'brief "' + value + '" resolves outside the repository. A brief must be a file inside the repository being described; an absolute or parent path is refused.'
4030
4140
  );
4031
4141
  }
4032
- const posixRelative = relative16.split(path27__namespace.sep).join("/");
4142
+ const posixRelative = relative17.split(path27__namespace.sep).join("/");
4033
4143
  if (isSensitivePath(posixRelative) || isSensitivePath(value)) {
4034
4144
  throw new Error(
4035
4145
  'brief "' + value + '" is a credential-bearing file. A snapshot must not reproduce secrets, so it cannot be used as the owner brief.'
@@ -4037,9 +4147,16 @@ function readConfiguredBrief(cwd, value) {
4037
4147
  }
4038
4148
  let text2;
4039
4149
  try {
4040
- if (!fs24__namespace.statSync(filePath).isFile()) throw new Error("not a file");
4150
+ const stats = fs24__namespace.statSync(filePath);
4151
+ if (!stats.isFile()) throw new Error("not a file");
4152
+ if (stats.size > MAX_BRIEF_BYTES) {
4153
+ throw new Error(
4154
+ 'brief "' + value + '" is ' + stats.size + " bytes; the limit is " + MAX_BRIEF_BYTES + ". Keep it to what a reader can act on, or move the detail into a document the snapshot carries."
4155
+ );
4156
+ }
4041
4157
  text2 = fs24__namespace.readFileSync(filePath, "utf8");
4042
- } catch {
4158
+ } catch (error) {
4159
+ if (error instanceof Error && error.message.startsWith('brief "')) throw error;
4043
4160
  throw new Error(
4044
4161
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
4045
4162
  );
@@ -4151,11 +4268,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
4151
4268
  const patterns = [];
4152
4269
  for (const dir of [outDir, tmpDir]) {
4153
4270
  const absolute = path27__namespace.resolve(cwd, dir);
4154
- const relative16 = path27__namespace.relative(cwd, absolute);
4155
- if (!relative16 || relative16 === ".." || relative16.startsWith(`..${path27__namespace.sep}`) || path27__namespace.isAbsolute(relative16)) {
4271
+ const relative17 = path27__namespace.relative(cwd, absolute);
4272
+ if (!relative17 || relative17 === ".." || relative17.startsWith(`..${path27__namespace.sep}`) || path27__namespace.isAbsolute(relative17)) {
4156
4273
  continue;
4157
4274
  }
4158
- patterns.push(`${relative16.replace(/\\/g, "/")}/**`);
4275
+ patterns.push(`${relative17.replace(/\\/g, "/")}/**`);
4159
4276
  }
4160
4277
  return patterns;
4161
4278
  }
@@ -4442,7 +4559,10 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
4442
4559
  outDir,
4443
4560
  tmpDir,
4444
4561
  maxPartBytes: resolvedMaxPartBytes,
4445
- ...maxPartTokens === void 0 ? {} : { maxPartTokens },
4562
+ // Record the effective value even when the user did not set it. normalizeResolvedConfig
4563
+ // derives it for the manifest; leaving validate's fresh resolution unset made a clean
4564
+ // snapshot report a configuration mismatch.
4565
+ maxPartTokens: maxPartTokens ?? Math.floor(resolvedMaxPartBytes / 4),
4446
4566
  largeFileBytes: largeFileBytesFor(resolvedMaxPartBytes, cliOptions, userConfig),
4447
4567
  previewHeadLines: strictPositiveInteger(userConfig?.previewHeadLines, 80, "`previewHeadLines`"),
4448
4568
  previewTailLines: strictPositiveInteger(userConfig?.previewTailLines, 40, "`previewTailLines`"),
@@ -4757,6 +4877,10 @@ function tsconfigPathsFor(cwd) {
4757
4877
  return null;
4758
4878
  }
4759
4879
  const key = `${stats.mtimeMs}:${stats.size}`;
4880
+ if (!TSCONFIG_CACHE.has(configPath) && TSCONFIG_CACHE.size >= 64) {
4881
+ const oldest = TSCONFIG_CACHE.keys().next().value;
4882
+ if (oldest !== void 0) TSCONFIG_CACHE.delete(oldest);
4883
+ }
4760
4884
  const cached = TSCONFIG_CACHE.get(configPath);
4761
4885
  if (cached !== void 0 && cached.key === key) return cached.value;
4762
4886
  let value = null;
@@ -4785,8 +4909,8 @@ function tsconfigPathsFor(cwd) {
4785
4909
  return value;
4786
4910
  }
4787
4911
  function repositoryRelative(cwd, target) {
4788
- const relative16 = path27__namespace.relative(cwd, target).replace(/\\/g, "/");
4789
- return relative16.length === 0 || !relative16.startsWith("..") && !path27__namespace.isAbsolute(relative16) ? relative16 : null;
4912
+ const relative17 = path27__namespace.relative(cwd, target).replace(/\\/g, "/");
4913
+ return relative17.length === 0 || !relative17.startsWith("..") && !path27__namespace.isAbsolute(relative17) ? relative17 : null;
4790
4914
  }
4791
4915
  function rememberFirst(map, key, value) {
4792
4916
  if (!map.has(key)) map.set(key, value);
@@ -5009,7 +5133,7 @@ function summarizeTypeScriptSource(relativePath, content) {
5009
5133
  routeHandlers: []
5010
5134
  };
5011
5135
  const lowerPath = relativePath.toLowerCase();
5012
- const scriptKind2 = /.tsx$/.test(lowerPath) ? ts2__default.default.ScriptKind.TSX : /.jsx$/.test(lowerPath) ? ts2__default.default.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts2__default.default.ScriptKind.JS : ts2__default.default.ScriptKind.TS;
5136
+ const scriptKind2 = /\.tsx$/.test(lowerPath) ? ts2__default.default.ScriptKind.TSX : /\.jsx$/.test(lowerPath) ? ts2__default.default.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts2__default.default.ScriptKind.JS : ts2__default.default.ScriptKind.TS;
5013
5137
  const sourceFile = ts2__default.default.createSourceFile(
5014
5138
  relativePath,
5015
5139
  content,
@@ -5245,7 +5369,7 @@ function finalizeSummary(summary) {
5245
5369
  }
5246
5370
  function eachLine(content, visit) {
5247
5371
  const text2 = content.length > MAX_SUMMARY_CHARS ? content.slice(0, MAX_SUMMARY_CHARS) : content;
5248
- for (const line of text2.split(/\r?\n/)) visit(line);
5372
+ for (const line of text2.split(/\r\n|\n|\r/)) visit(line);
5249
5373
  }
5250
5374
  function isTopLevel(line) {
5251
5375
  return !/^[\s]/.test(line);
@@ -5750,9 +5874,9 @@ var rubyProfile = {
5750
5874
  eachLine(content, (line) => {
5751
5875
  const trimmed = line.trim();
5752
5876
  if (!trimmed || trimmed.startsWith("#")) return;
5753
- const relative16 = REQUIRE_RELATIVE.exec(trimmed);
5754
- if (relative16) {
5755
- summary.imports.push(`./${relative16[1]}`);
5877
+ const relative17 = REQUIRE_RELATIVE.exec(trimmed);
5878
+ if (relative17) {
5879
+ summary.imports.push(`./${relative17[1]}`);
5756
5880
  return;
5757
5881
  }
5758
5882
  const required = REQUIRE.exec(trimmed);
@@ -6238,17 +6362,17 @@ function decodeText(buffer) {
6238
6362
  };
6239
6363
  }
6240
6364
  const invalidBytes = countInvalidUtf8Bytes(buffer);
6365
+ const controlBytes = countControlBytes(buffer);
6366
+ if (controlBytes > CONTROL_BYTES_FLOOR && controlBytes * 100 > buffer.length) {
6367
+ return {
6368
+ text: "",
6369
+ encoding: "utf-8",
6370
+ invalidBytes,
6371
+ binary: true,
6372
+ binaryReason: `${controlBytes} control byte(s) in ${buffer.length} B; not text`
6373
+ };
6374
+ }
6241
6375
  if (invalidBytes === 0) {
6242
- const controlBytes = countControlBytes(buffer);
6243
- if (controlBytes > CONTROL_BYTES_FLOOR && controlBytes * 100 > buffer.length) {
6244
- return {
6245
- text: "",
6246
- encoding: "utf-8",
6247
- invalidBytes: 0,
6248
- binary: true,
6249
- binaryReason: `${controlBytes} control byte(s) in ${buffer.length} B; valid UTF-8 but not text`
6250
- };
6251
- }
6252
6376
  return {
6253
6377
  text: new TextDecoder("utf-8").decode(buffer),
6254
6378
  encoding: "utf-8",
@@ -6335,6 +6459,75 @@ function importsOfFile(relativePath, absolutePath) {
6335
6459
  if (decoded.binary) return [];
6336
6460
  return importsOfText(relativePath, decoded.text);
6337
6461
  }
6462
+ function isInside2(parent, child) {
6463
+ const relative17 = path27__namespace.relative(parent, child);
6464
+ return relative17 === "" || !relative17.startsWith("..") && !path27__namespace.isAbsolute(relative17);
6465
+ }
6466
+ function resolveConfined(baseDir, relativePath) {
6467
+ if (relativePath.length === 0 || relativePath.includes("\0")) {
6468
+ return { ok: false, reason: "not-file", message: "the file name is empty or contains a NUL byte" };
6469
+ }
6470
+ if (path27__namespace.isAbsolute(relativePath)) {
6471
+ return { ok: false, reason: "outside", message: "an absolute path is not a snapshot-relative file" };
6472
+ }
6473
+ let baseReal;
6474
+ try {
6475
+ baseReal = fs24__namespace.realpathSync(path27__namespace.resolve(baseDir));
6476
+ } catch {
6477
+ return { ok: false, reason: "missing", message: "the snapshot directory does not exist" };
6478
+ }
6479
+ const candidate = path27__namespace.resolve(baseReal, relativePath);
6480
+ if (!isInside2(baseReal, candidate)) {
6481
+ return { ok: false, reason: "outside", message: "the path resolves outside the snapshot directory" };
6482
+ }
6483
+ let stats;
6484
+ try {
6485
+ stats = fs24__namespace.lstatSync(candidate);
6486
+ } catch (error) {
6487
+ const code = error.code;
6488
+ return {
6489
+ ok: false,
6490
+ reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unreadable",
6491
+ message: code === "ENOENT" || code === "ENOTDIR" ? "the file does not exist" : "the file could not be inspected"
6492
+ };
6493
+ }
6494
+ if (stats.isSymbolicLink()) {
6495
+ return { ok: false, reason: "not-file", message: "the file is a symbolic link" };
6496
+ }
6497
+ if (!stats.isFile()) {
6498
+ return { ok: false, reason: "not-file", message: "the path is not a regular file" };
6499
+ }
6500
+ let real;
6501
+ try {
6502
+ real = fs24__namespace.realpathSync(candidate);
6503
+ } catch {
6504
+ return { ok: false, reason: "unreadable", message: "the file could not be resolved" };
6505
+ }
6506
+ if (!isInside2(baseReal, real)) {
6507
+ return { ok: false, reason: "outside", message: "the file resolves outside the snapshot directory" };
6508
+ }
6509
+ return { ok: true, path: real, stats };
6510
+ }
6511
+ function readConfinedBytes(baseDir, relativePath) {
6512
+ const resolved = resolveConfined(baseDir, relativePath);
6513
+ if (!resolved.ok) return resolved;
6514
+ try {
6515
+ const bytes = fs24__namespace.readFileSync(resolved.path);
6516
+ return { ok: true, bytes, path: resolved.path, stats: fs24__namespace.statSync(resolved.path) };
6517
+ } catch {
6518
+ return { ok: false, reason: "unreadable", message: "the file could not be read" };
6519
+ }
6520
+ }
6521
+ function readConfinedText(baseDir, relativePath) {
6522
+ const resolved = resolveConfined(baseDir, relativePath);
6523
+ if (!resolved.ok) return resolved;
6524
+ try {
6525
+ const text2 = fs24__namespace.readFileSync(resolved.path, "utf8");
6526
+ return { ok: true, text: text2, path: resolved.path, stats: fs24__namespace.statSync(resolved.path) };
6527
+ } catch {
6528
+ return { ok: false, reason: "unreadable", message: "the file could not be read" };
6529
+ }
6530
+ }
6338
6531
 
6339
6532
  // src/validator/validate.ts
6340
6533
  function maskedPath(value, secretRules) {
@@ -6587,6 +6780,9 @@ function describeManifestShapeProblem(value) {
6587
6780
  if (typeof fields.relativePath !== "string") {
6588
6781
  return 'a "files" entry has no "relativePath"';
6589
6782
  }
6783
+ if (!isConfinedRelative(fields.relativePath)) {
6784
+ return 'a "files" entry "relativePath" resolves outside the repository and was not inspected';
6785
+ }
6590
6786
  if (!currentSchema) continue;
6591
6787
  if (typeof fields.part !== "string" || fields.part.length === 0) {
6592
6788
  return 'a "files" entry records no "part"';
@@ -6605,6 +6801,18 @@ function describeManifestShapeProblem(value) {
6605
6801
  }
6606
6802
  }
6607
6803
  if (!Array.isArray(candidate.skipped)) return 'missing "skipped" array';
6804
+ for (const entry of candidate.skipped) {
6805
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
6806
+ return 'a "skipped" entry is not an object';
6807
+ }
6808
+ const fields = entry;
6809
+ if (typeof fields.path !== "string" || !isConfinedRelative(fields.path)) {
6810
+ return 'a "skipped" entry "path" resolves outside the repository and was not inspected';
6811
+ }
6812
+ if (typeof fields.reason !== "string" || fields.reason.length === 0) {
6813
+ return 'a "skipped" entry has no "reason"';
6814
+ }
6815
+ }
6608
6816
  if (!Array.isArray(candidate.parts)) return 'missing "parts" array';
6609
6817
  for (const entry of candidate.parts) {
6610
6818
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
@@ -6665,10 +6873,12 @@ function validateSnapshot(configInput) {
6665
6873
  }
6666
6874
  const shapeProblem = describeManifestShapeProblem(manifest);
6667
6875
  if (shapeProblem) {
6876
+ const drift2 = emptyDrift();
6877
+ drift2.partIssues.push({ part: "manifest.json", issue: shapeProblem });
6668
6878
  return {
6669
6879
  valid: false,
6670
6880
  manifestPresent: true,
6671
- drift: emptyDrift(),
6881
+ drift: drift2,
6672
6882
  errors: [`${manifestPath} is not a snapshot manifest: ${shapeProblem}`],
6673
6883
  warnings: []
6674
6884
  };
@@ -6797,12 +7007,16 @@ function validateSnapshot(configInput) {
6797
7007
  // discovery mode" meant `validate` could enumerate files one way while the snapshot
6798
7008
  // had been generated another way, and then blame the difference on drift.
6799
7009
  discovery: config.discovery,
7010
+ // `generate --staged` adds index-only paths to the candidate list. Without the same
7011
+ // extra paths, a staged file that is absent from the working tree was invisible to
7012
+ // this scan and then reported as deleted, although the snapshot matched the index.
7013
+ ...stagedScope === null ? {} : { extraPaths: [...stagedScope] },
6800
7014
  // The same exclusion `generate` applies: without it, `validate` recounted the tool's
6801
7015
  // own output directory as a set of files missing from the snapshot, so a correct
6802
7016
  // snapshot was reported as drifting.
6803
7017
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
6804
7018
  (directory) => path27__namespace.relative(config.cwd, path27__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
6805
- ).filter((relative16) => relative16.length > 0 && !relative16.startsWith(".."))
7019
+ ).filter((relative17) => relative17.length > 0 && !relative17.startsWith(".."))
6806
7020
  });
6807
7021
  for (const diskFile of collection.files) {
6808
7022
  const snapshotHash = manifestFileMap.get(diskFile);
@@ -6843,6 +7057,12 @@ function validateSnapshot(configInput) {
6843
7057
  }
6844
7058
  }
6845
7059
  for (const snapshotFile of manifestFileMap.keys()) {
7060
+ if (recordedStaged && stagedScope?.has(snapshotFile)) {
7061
+ if (readStagedBlob(config.cwd, snapshotFile) === null) {
7062
+ drift.missingOnDisk.push(snapshotFile);
7063
+ }
7064
+ continue;
7065
+ }
6846
7066
  const confined = confineToDirectory(config.cwd, snapshotFile);
6847
7067
  if (confined === null) {
6848
7068
  drift.partIssues.push({
@@ -6886,13 +7106,15 @@ function validateSnapshot(configInput) {
6886
7106
  });
6887
7107
  continue;
6888
7108
  }
6889
- let buffer;
6890
- try {
6891
- buffer = fs24__namespace.readFileSync(partPath);
6892
- } catch {
6893
- drift.partIssues.push({ part: part.filename, issue: "missing from snapshot/parts" });
7109
+ const partRead = readConfinedBytes(partsDir, part.filename);
7110
+ if (!partRead.ok) {
7111
+ drift.partIssues.push({
7112
+ part: part.filename,
7113
+ issue: `missing or not a regular file in snapshot/parts (${partRead.reason})`
7114
+ });
6894
7115
  continue;
6895
7116
  }
7117
+ const buffer = partRead.bytes;
6896
7118
  if (buffer.length !== part.byteSize) {
6897
7119
  drift.partIssues.push({
6898
7120
  part: part.filename,
@@ -7265,15 +7487,15 @@ function validateSnapshot(configInput) {
7265
7487
  ];
7266
7488
  for (const [key, artifact] of declaredArtifacts) {
7267
7489
  if (!artifact) continue;
7268
- const artifactPath = path27__namespace.join(snapshotDir, ...key.split("/"));
7269
- let buffer;
7270
- try {
7271
- if (!fs24__namespace.statSync(artifactPath).isFile()) throw new Error("not a regular file");
7272
- buffer = fs24__namespace.readFileSync(artifactPath);
7273
- } catch {
7274
- drift.partIssues.push({ part: key, issue: "declared artifact is missing" });
7490
+ const artifactRead = readConfinedBytes(snapshotDir, key);
7491
+ if (!artifactRead.ok) {
7492
+ drift.partIssues.push({
7493
+ part: key,
7494
+ issue: `declared artifact is missing or not a regular file (${artifactRead.reason})`
7495
+ });
7275
7496
  continue;
7276
7497
  }
7498
+ const buffer = artifactRead.bytes;
7277
7499
  if (sha256Hex(buffer) !== artifact.sha256 || buffer.length !== artifact.byteSize) {
7278
7500
  drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
7279
7501
  continue;
@@ -7283,8 +7505,8 @@ function validateSnapshot(configInput) {
7283
7505
  const target = match[1].split("#")[0];
7284
7506
  if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
7285
7507
  const resolved = path27__namespace.resolve(snapshotDir, "reports", target);
7286
- const relative16 = path27__namespace.relative(snapshotDir, resolved);
7287
- if (relative16.startsWith("..") || path27__namespace.isAbsolute(relative16) || !fs24__namespace.existsSync(resolved)) {
7508
+ const relative17 = path27__namespace.relative(snapshotDir, resolved);
7509
+ if (relative17.startsWith("..") || path27__namespace.isAbsolute(relative17) || !fs24__namespace.existsSync(resolved)) {
7288
7510
  drift.partIssues.push({
7289
7511
  part: key,
7290
7512
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -7296,13 +7518,11 @@ function validateSnapshot(configInput) {
7296
7518
  const sarifArtifact = manifest.artifacts?.sarif;
7297
7519
  if (sarifArtifact) {
7298
7520
  const sarifKey = "reports/audit.sarif";
7299
- try {
7300
- const buffer = fs24__namespace.readFileSync(path27__namespace.join(snapshotDir, "reports", "audit.sarif"));
7301
- if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
7302
- drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
7303
- }
7304
- } catch {
7305
- drift.partIssues.push({ part: sarifKey, issue: "declared artifact is missing" });
7521
+ const sarifRead = readConfinedBytes(snapshotDir, "reports/audit.sarif");
7522
+ if (!sarifRead.ok) {
7523
+ drift.partIssues.push({ part: sarifKey, issue: "declared artifact is missing or not a regular file" });
7524
+ } else if (sha256Hex(sarifRead.bytes) !== sarifArtifact.sha256 || sarifRead.bytes.length !== sarifArtifact.byteSize) {
7525
+ drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
7306
7526
  }
7307
7527
  }
7308
7528
  if (manifest.git && manifest.git.branch && manifest.git.branch !== config.branch) {
@@ -7688,9 +7908,15 @@ function skeletonizeTypeScript(source, fileName = "file.ts") {
7688
7908
  if (end > start) spans.push({ start, end });
7689
7909
  }
7690
7910
  }
7691
- ts2__default.default.forEachChild(node, visit);
7692
7911
  };
7693
- visit(sourceFile);
7912
+ const stack = [sourceFile];
7913
+ while (stack.length > 0) {
7914
+ const node = stack.pop();
7915
+ visit(node);
7916
+ ts2__default.default.forEachChild(node, (child) => {
7917
+ stack.push(child);
7918
+ });
7919
+ }
7694
7920
  if (spans.length === 0) return { text: source, collapsed: 0 };
7695
7921
  const outermost = [];
7696
7922
  for (const span of spans.sort((a, b) => a.start - b.start || b.end - a.end)) {
@@ -7736,12 +7962,15 @@ function stripComments2(text2, relativePath) {
7736
7962
  if (ranges_ === void 0) return;
7737
7963
  for (const range of ranges_) ranges.push([range.pos, range.end]);
7738
7964
  };
7739
- const visit = (node) => {
7965
+ const stack = [source];
7966
+ while (stack.length > 0) {
7967
+ const node = stack.pop();
7740
7968
  collect(ts2__default.default.getLeadingCommentRanges(text2, node.getFullStart()));
7741
7969
  collect(ts2__default.default.getTrailingCommentRanges(text2, node.getEnd()));
7742
- ts2__default.default.forEachChild(node, visit);
7743
- };
7744
- visit(source);
7970
+ ts2__default.default.forEachChild(node, (child) => {
7971
+ stack.push(child);
7972
+ });
7973
+ }
7745
7974
  collect(ts2__default.default.getLeadingCommentRanges(text2, source.endOfFileToken.getFullStart()));
7746
7975
  if (ranges.length === 0) return { text: text2, removed: 0 };
7747
7976
  ranges.sort((left, right) => left[0] - right[0]);
@@ -7781,6 +8010,9 @@ function countLines(content) {
7781
8010
  const last = content.charCodeAt(content.length - 1);
7782
8011
  return last === 10 || last === 13 ? breaks : breaks + 1;
7783
8012
  }
8013
+ function countBodyLines(content) {
8014
+ return content.length === 0 ? 0 : content.split("\n").length;
8015
+ }
7784
8016
  function truncateToBytes(content, maxBytes) {
7785
8017
  if (maxBytes <= 0) return { content: "", isTruncated: content.length > 0 };
7786
8018
  const buffer = Buffer.from(content, "utf8");
@@ -7916,6 +8148,17 @@ function formatNumber(value) {
7916
8148
  }
7917
8149
 
7918
8150
  // src/explain.ts
8151
+ function safeRegularFile(cwd, absolute) {
8152
+ try {
8153
+ if (!fs24__namespace.lstatSync(absolute).isFile()) return false;
8154
+ const root = fs24__namespace.realpathSync(cwd);
8155
+ const real = fs24__namespace.realpathSync(absolute);
8156
+ const relative17 = path27__namespace.relative(root, real);
8157
+ return relative17 !== ".." && !relative17.startsWith(".." + path27__namespace.sep) && !path27__namespace.isAbsolute(relative17);
8158
+ } catch {
8159
+ return false;
8160
+ }
8161
+ }
7919
8162
  function describeMatcher(matcher) {
7920
8163
  if (typeof matcher === "string") return matcher;
7921
8164
  if (matcher instanceof RegExp) return String(matcher);
@@ -7927,23 +8170,23 @@ function describeMatcher(matcher) {
7927
8170
  function normalizeTarget(cwd, target) {
7928
8171
  const resolvedCwd = path27__namespace.resolve(cwd);
7929
8172
  const absolute = path27__namespace.resolve(resolvedCwd, target);
7930
- const relative16 = path27__namespace.relative(resolvedCwd, absolute);
7931
- if (relative16 === "" || relative16 === ".." || relative16.startsWith(`..${path27__namespace.sep}`) || path27__namespace.isAbsolute(relative16)) {
8173
+ const relative17 = path27__namespace.relative(resolvedCwd, absolute);
8174
+ if (relative17 === "" || relative17 === ".." || relative17.startsWith(`..${path27__namespace.sep}`) || path27__namespace.isAbsolute(relative17)) {
7932
8175
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
7933
8176
  }
7934
- return { relative: relative16.split(path27__namespace.sep).join("/"), outsideRoot: false };
8177
+ return { relative: relative17.split(path27__namespace.sep).join("/"), outsideRoot: false };
7935
8178
  }
7936
8179
  function findRuleMatch(rules, relativePath) {
7937
8180
  return rules.find(
7938
8181
  (rule) => matchRule(relativePath, rule.match)
7939
8182
  );
7940
8183
  }
7941
- function findRecordedAncestor(skipped, relative16, maskedPath2) {
8184
+ function findRecordedAncestor(skipped, relative17, maskedPath2) {
7942
8185
  let nearest;
7943
8186
  for (const record of skipped) {
7944
8187
  const ancestorPath = record.path;
7945
8188
  if (ancestorPath.length === 0) continue;
7946
- const isAncestor = relative16.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
8189
+ const isAncestor = relative17.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
7947
8190
  if (!isAncestor) continue;
7948
8191
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
7949
8192
  }
@@ -7959,8 +8202,8 @@ function readManifest2(config) {
7959
8202
  }
7960
8203
  function explainPath(config, target) {
7961
8204
  const normalized = normalizeTarget(config.cwd, target);
7962
- const relative16 = normalized.relative;
7963
- const maskedPath2 = findSecretInPath(relative16, config.secretRules)?.masked ?? relative16;
8205
+ const relative17 = normalized.relative;
8206
+ const maskedPath2 = findSecretInPath(relative17, config.secretRules)?.masked ?? relative17;
7964
8207
  if (normalized.outsideRoot) {
7965
8208
  return {
7966
8209
  path: maskedPath2,
@@ -7970,10 +8213,14 @@ function explainPath(config, target) {
7970
8213
  detail: "path resolves outside the configured repository root and was not inspected"
7971
8214
  };
7972
8215
  }
7973
- const absolute = path27__namespace.join(config.cwd, relative16);
8216
+ const absolute = path27__namespace.join(config.cwd, relative17);
8217
+ const stagedBlob = config.staged === true ? readStagedBlob(config.cwd, relative17) : null;
7974
8218
  const result = {
7975
8219
  path: maskedPath2,
7976
- exists: fs24__namespace.existsSync(absolute),
8220
+ // `existsSync` follows a symlink, so an in-repo link to /etc/passwd answered "exists" for a
8221
+ // file the scanner refuses. `lstat` plus a canonical containment check keeps the answer about
8222
+ // a regular file the repository actually contains; a staged blob is the index's answer.
8223
+ exists: stagedBlob !== null || safeRegularFile(config.cwd, absolute),
7977
8224
  included: false
7978
8225
  };
7979
8226
  const collection = collectFiles(config.cwd, {
@@ -7988,11 +8235,11 @@ function explainPath(config, target) {
7988
8235
  // that is only missing because the walker dropped the tool's own output directory.
7989
8236
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
7990
8237
  (directory) => path27__namespace.relative(config.cwd, path27__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
7991
- ).filter((relative17) => relative17.length > 0 && !relative17.startsWith(".."))
8238
+ ).filter((relative18) => relative18.length > 0 && !relative18.startsWith(".."))
7992
8239
  });
7993
- if (!collection.files.includes(relative16)) {
8240
+ if (!collection.files.includes(relative17)) {
7994
8241
  const record = collection.skipped.find(
7995
- (entry2) => entry2.path === relative16 || entry2.path === maskedPath2
8242
+ (entry2) => entry2.path === relative17 || entry2.path === maskedPath2
7996
8243
  );
7997
8244
  if (record) {
7998
8245
  result.reason = record.reason;
@@ -8001,7 +8248,7 @@ function explainPath(config, target) {
8001
8248
  result.reason = "missing";
8002
8249
  result.detail = "no such file or directory, relative to the configured cwd";
8003
8250
  } else {
8004
- const ancestor = findRecordedAncestor(collection.skipped, relative16, maskedPath2);
8251
+ const ancestor = findRecordedAncestor(collection.skipped, relative17, maskedPath2);
8005
8252
  if (ancestor) {
8006
8253
  result.reason = ancestor.reason;
8007
8254
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -8021,11 +8268,11 @@ function explainPath(config, target) {
8021
8268
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
8022
8269
  ...config.staged === true ? { staged: true } : {}
8023
8270
  });
8024
- inScope = scope.paths.has(relative16);
8271
+ inScope = scope.paths.has(relative17);
8025
8272
  if (!inScope && config.withDependents === true) {
8026
8273
  inScope = importsChangedFile(
8027
- relative16,
8028
- importsOfFile(relative16, absolute),
8274
+ relative17,
8275
+ importsOfFile(relative17, absolute),
8029
8276
  scope.paths,
8030
8277
  buildImportResolver(collection.files.map((file) => ({ relativePath: file })), {
8031
8278
  tsconfig: tsconfigPathsFor(config.cwd)
@@ -8052,11 +8299,13 @@ function explainPath(config, target) {
8052
8299
  result.detail = "binary extension; generate skips it without reading and records `binary` in manifest.skipped[]";
8053
8300
  return result;
8054
8301
  }
8055
- let sizeOnDisk = null;
8056
- try {
8057
- sizeOnDisk = fs24__namespace.statSync(absolute).size;
8058
- } catch {
8059
- sizeOnDisk = null;
8302
+ let sizeOnDisk = stagedBlob?.length ?? null;
8303
+ if (sizeOnDisk === null) {
8304
+ try {
8305
+ sizeOnDisk = fs24__namespace.statSync(absolute).size;
8306
+ } catch {
8307
+ sizeOnDisk = null;
8308
+ }
8060
8309
  }
8061
8310
  if (sizeOnDisk !== null && sizeOnDisk > BINARY_SCAN_BYTES && isBinaryFile(absolute)) {
8062
8311
  result.included = false;
@@ -8064,10 +8313,10 @@ function explainPath(config, target) {
8064
8313
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
8065
8314
  return result;
8066
8315
  }
8067
- if (fs24__namespace.existsSync(absolute) && fs24__namespace.statSync(absolute).isFile()) {
8316
+ if (stagedBlob !== null || safeRegularFile(config.cwd, absolute)) {
8068
8317
  let buffer;
8069
8318
  try {
8070
- buffer = fs24__namespace.readFileSync(absolute);
8319
+ buffer = stagedBlob ?? fs24__namespace.readFileSync(absolute);
8071
8320
  } catch (err) {
8072
8321
  result.included = false;
8073
8322
  result.reason = "read-error";
@@ -8085,15 +8334,15 @@ function explainPath(config, target) {
8085
8334
  result.bytes = buffer.length;
8086
8335
  result.lines = countLines(text2);
8087
8336
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
8088
- const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative16);
8337
+ const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative17);
8089
8338
  result.secretCount = findings.length;
8090
8339
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
8091
8340
  let inclusionMode = "full";
8092
- if (config.skeleton === true && isSkeletonizable(relative16)) {
8093
- const skeleton = skeletonizeTypeScript(text2, relative16);
8341
+ if (config.skeleton === true && isSkeletonizable(relative17)) {
8342
+ const skeleton = skeletonizeTypeScript(text2, relative17);
8094
8343
  if (skeleton.collapsed > 0) inclusionMode = "signatures";
8095
8344
  }
8096
- if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative16) && stripComments2(text2, relative16).removed > 0) {
8345
+ if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative17) && stripComments2(text2, relative17).removed > 0) {
8097
8346
  inclusionMode = "comments-stripped";
8098
8347
  }
8099
8348
  if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
@@ -8102,20 +8351,36 @@ function explainPath(config, target) {
8102
8351
  }
8103
8352
  result.inclusionMode = inclusionMode;
8104
8353
  }
8105
- result.layer = classifyLayer(relative16, config.layers);
8106
- result.kind = classifyKind(relative16, config.kinds);
8107
- result.language = detectLanguage(relative16);
8108
- const layerRule = findRuleMatch(config.layers, relative16);
8354
+ result.layer = classifyLayer(relative17, config.layers);
8355
+ result.kind = classifyKind(relative17, config.kinds);
8356
+ result.language = detectLanguage(relative17);
8357
+ const layerRule = findRuleMatch(config.layers, relative17);
8109
8358
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
8110
- const kindRule = findRuleMatch(config.kinds, relative16);
8359
+ const kindRule = findRuleMatch(config.kinds, relative17);
8111
8360
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
8112
8361
  const manifest = readManifest2(config);
8113
- const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative16) : void 0;
8362
+ const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative17) : void 0;
8114
8363
  result.part = entry?.part ?? null;
8115
8364
  if (entry === void 0) {
8116
- const record = manifest?.skipped?.find((skip) => skip.path === relative16);
8365
+ const record = manifest?.skipped?.find((skip) => skip.path === relative17);
8117
8366
  if (record !== void 0 && (record.reason === "not-selected" || record.reason === "unchanged")) {
8118
8367
  result.included = false;
8368
+ for (const key of [
8369
+ "layer",
8370
+ "layerMatch",
8371
+ "kind",
8372
+ "kindMatch",
8373
+ "language",
8374
+ "inclusionMode",
8375
+ "lines",
8376
+ "bytes",
8377
+ "encoding",
8378
+ "secretCount",
8379
+ "secrets"
8380
+ ]) {
8381
+ delete result[key];
8382
+ }
8383
+ result.part = null;
8119
8384
  result.reason = record.reason;
8120
8385
  result.detail = record.detail ?? (record.reason === "not-selected" ? "the snapshot was generated for a selection (--slice or --budget-tokens) that did not include this path" : "the snapshot was generated with a changed-files scope that did not include this path");
8121
8386
  }
@@ -8209,9 +8474,25 @@ function appendGitignoreEntries(cwd, entries) {
8209
8474
  let decoded = { text: "", bom: Buffer.alloc(0), encoding: "utf8" };
8210
8475
  try {
8211
8476
  if (fs24__namespace.existsSync(ignorePath)) {
8212
- if (fs24__namespace.statSync(ignorePath).isDirectory()) {
8477
+ const stats = fs24__namespace.lstatSync(ignorePath);
8478
+ if (stats.isDirectory()) {
8213
8479
  return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
8214
8480
  }
8481
+ if (stats.isSymbolicLink() || !stats.isFile() || stats.nlink > 1) {
8482
+ return {
8483
+ added: [],
8484
+ note: `${ignorePath} is a symbolic link, a hard link, or not a regular file, so it was not updated. ` + manual
8485
+ };
8486
+ }
8487
+ const rootReal = fs24__namespace.realpathSync(cwd);
8488
+ const fileReal = fs24__namespace.realpathSync(ignorePath);
8489
+ const relative17 = path27__namespace.relative(rootReal, fileReal);
8490
+ if (relative17 === ".." || relative17.startsWith(`..${path27__namespace.sep}`) || path27__namespace.isAbsolute(relative17)) {
8491
+ return {
8492
+ added: [],
8493
+ note: `${ignorePath} resolves outside the repository, so it was not updated. ${manual}`
8494
+ };
8495
+ }
8215
8496
  const read = decodeGitignore(fs24__namespace.readFileSync(ignorePath));
8216
8497
  if (read === null) {
8217
8498
  return {
@@ -8233,12 +8514,19 @@ function appendGitignoreEntries(cwd, entries) {
8233
8514
  if (added.length === 0) return { added: [], note: null };
8234
8515
  const newline = existing.includes("\r\n") ? "\r\n" : "\n";
8235
8516
  const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : newline;
8517
+ const tempPath = `${ignorePath}.${process.pid}.${Date.now()}.tmp`;
8236
8518
  try {
8237
8519
  fs24__namespace.writeFileSync(
8238
- ignorePath,
8239
- encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`)
8520
+ tempPath,
8521
+ encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`),
8522
+ { flag: "wx" }
8240
8523
  );
8524
+ fs24__namespace.renameSync(tempPath, ignorePath);
8241
8525
  } catch (err) {
8526
+ try {
8527
+ fs24__namespace.rmSync(tempPath, { force: true });
8528
+ } catch {
8529
+ }
8242
8530
  return { added: [], note: `${err.message}. ${manual}` };
8243
8531
  }
8244
8532
  return { added, note: null };
@@ -8629,7 +8917,7 @@ function keyReader(input) {
8629
8917
  next() {
8630
8918
  const queued = queue.shift();
8631
8919
  if (queued) return Promise.resolve(queued);
8632
- return new Promise((resolve15) => waiters.push(resolve15));
8920
+ return new Promise((resolve16) => waiters.push(resolve16));
8633
8921
  },
8634
8922
  close() {
8635
8923
  input.off("keypress", onKey);
@@ -9062,11 +9350,11 @@ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
9062
9350
  const entries = [];
9063
9351
  for (const directory of [outDir, tmpDir]) {
9064
9352
  if (directory === null) continue;
9065
- const relative16 = path27__namespace.relative(cwd, path27__namespace.resolve(cwd, directory)).replace(/\\/g, "/");
9066
- if (relative16 === "" || relative16 === "." || relative16.startsWith("..") || path27__namespace.isAbsolute(relative16)) {
9353
+ const relative17 = path27__namespace.relative(cwd, path27__namespace.resolve(cwd, directory)).replace(/\\/g, "/");
9354
+ if (relative17 === "" || relative17 === "." || relative17.startsWith("..") || path27__namespace.isAbsolute(relative17)) {
9067
9355
  continue;
9068
9356
  }
9069
- entries.push(`/${relative16}/`);
9357
+ entries.push(`/${relative17}/`);
9070
9358
  }
9071
9359
  return [...new Set(entries)];
9072
9360
  }
@@ -9222,7 +9510,14 @@ async function runInit(options) {
9222
9510
  try {
9223
9511
  const raw = await text(io, "Part size (e.g. 150k, 1.5mb, 900000)", {
9224
9512
  defaultValue: currentBudget,
9225
- validate: (value) => parseByteSize(value) === void 0 ? "Not a valid size." : null,
9513
+ validate: (value) => {
9514
+ const parsed = parseByteSize(value);
9515
+ if (parsed === void 0) return "Not a valid size.";
9516
+ if (parsed < MIN_MAX_PART_BYTES) {
9517
+ return `A part budget below ${MIN_MAX_PART_BYTES} bytes cannot hold the truncation notice.`;
9518
+ }
9519
+ return null;
9520
+ },
9226
9521
  allowBack: true
9227
9522
  });
9228
9523
  answers.maxPartBytes = parseByteSize(raw) ?? answers.maxPartBytes;
@@ -9397,10 +9692,10 @@ async function runInit(options) {
9397
9692
  };
9398
9693
  }
9399
9694
  function describeTarget(cwd) {
9400
- const relative16 = path27__namespace.relative(process.cwd(), cwd);
9401
- if (relative16 === "") return "this directory";
9402
- if (relative16.startsWith("..") || path27__namespace.isAbsolute(relative16)) return cwd;
9403
- return relative16;
9695
+ const relative17 = path27__namespace.relative(process.cwd(), cwd);
9696
+ if (relative17 === "") return "this directory";
9697
+ if (relative17.startsWith("..") || path27__namespace.isAbsolute(relative17)) return cwd;
9698
+ return relative17;
9404
9699
  }
9405
9700
  function firstRunMessage(reason, cwd) {
9406
9701
  const where = describeTarget(cwd);
@@ -9686,7 +9981,8 @@ function generateSarifReport(manifest, findings, rules, toolVersion) {
9686
9981
  const results = findings.filter((finding) => typeof finding.path === "string" && finding.path.length > 0).map((finding) => {
9687
9982
  const primary = finding.rules[0] ?? "unknown";
9688
9983
  const line = Math.max(1, finding.line);
9689
- const findingPath = String(finding.path).replace(/\\/g, "/");
9984
+ const rawPath = findSecretInPath(String(finding.path), rules)?.masked ?? String(finding.path);
9985
+ const findingPath = rawPath.replace(/\\/g, "/").split("/").map((segment) => encodeURIComponent(segment)).join("/");
9690
9986
  return {
9691
9987
  ruleId: ruleIdFor(primary),
9692
9988
  ruleIndex: ruleIndex.get(primary) ?? 0,
@@ -9984,14 +10280,16 @@ function fenceIsOpen(text2, fence) {
9984
10280
  }
9985
10281
  var OMISSION_NOTICE_LINE = /^\.\.\. \[\d+ lines omitted: [^\]]*\] \.\.\.$/;
9986
10282
  function applyTruncatedContent(file, content, reason) {
9987
- const keptLines = content.split("\n").filter((line) => !OMISSION_NOTICE_LINE.test(line)).length;
10283
+ const keptLines = content.split("\n").filter(
10284
+ (line) => !OMISSION_NOTICE_LINE.test(line) && line.trim() !== SECTION_TRUNCATION_NOTICE
10285
+ ).length;
9988
10286
  file.content = content;
9989
10287
  file.isPreviewTruncated = true;
9990
10288
  file.inclusionMode = "preview";
9991
10289
  file.truncationReason = reason;
9992
10290
  file.omittedRanges = keptLines >= file.originalLines ? file.originalLines > 0 ? [[file.originalLines, file.originalLines]] : [] : [[keptLines + 1, file.originalLines]];
9993
10291
  file.includedBytes = Buffer.byteLength(content, "utf8");
9994
- file.includedLines = countLines(content);
10292
+ file.includedLines = countBodyLines(content);
9995
10293
  }
9996
10294
  function rehashPart(part, markdown) {
9997
10295
  const estimatedTokens = estimateTokens(markdown.replace(TOKEN_LINE, ""));
@@ -10004,7 +10302,8 @@ function rehashPart(part, markdown) {
10004
10302
  byteSize: Buffer.byteLength(redistributed, "utf8"),
10005
10303
  sha256: crypto__namespace.createHash("sha256").update(redistributed).digest("hex"),
10006
10304
  lines: countLines(redistributed),
10007
- estimatedTokens
10305
+ estimatedTokens,
10306
+ hardClipped: true
10008
10307
  }
10009
10308
  };
10010
10309
  }
@@ -10126,7 +10425,7 @@ function renderFileSection(file) {
10126
10425
  const content = file.content ?? "";
10127
10426
  const body = emittedBody(content);
10128
10427
  file.includedBytes = Buffer.byteLength(body, "utf8");
10129
- file.includedLines = countLines(body);
10428
+ file.includedLines = countBodyLines(body);
10130
10429
  const fence = fenceForContent(content);
10131
10430
  const anchor = anchorForPath(file.relativePath);
10132
10431
  return [
@@ -10180,11 +10479,14 @@ function generateMonolithJson(manifest, filesWithContent) {
10180
10479
  );
10181
10480
  return JSON.stringify({ manifest: embedded, files }, null, 2);
10182
10481
  }
10482
+ function xmlSafe(value) {
10483
+ return value.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]/g, "\uFFFD");
10484
+ }
10183
10485
  function xmlAttribute(value) {
10184
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
10486
+ return xmlSafe(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
10185
10487
  }
10186
10488
  function cdata(value) {
10187
- return "<![CDATA[" + value.replace(/\]\]>/g, "]]]]><![CDATA[>") + "]]>";
10489
+ return "<![CDATA[" + xmlSafe(value).replace(/\]\]>/g, "]]]]><![CDATA[>") + "]]>";
10188
10490
  }
10189
10491
  function generateMonolithXml(manifest, filesWithContent) {
10190
10492
  const files = filesWithContent.map((file) => {
@@ -10285,14 +10587,19 @@ function generateNavigation(manifest) {
10285
10587
  }
10286
10588
 
10287
10589
  // src/generator/selection.ts
10590
+ function cell(value) {
10591
+ return escapeControls(value).replace(/\r?\n/g, " ").replace(/\|/g, "\\|");
10592
+ }
10288
10593
  function generateSelectionReport(manifest, selection) {
10289
10594
  const lines = [];
10290
10595
  lines.push("# Selection");
10291
10596
  lines.push("");
10292
10597
  lines.push("**Kind:** `" + selection.kind + "` ");
10293
- for (const detailLine of selection.detail.split("\n")) {
10294
- lines.push("**" + detailLine.slice(0, detailLine.indexOf(":")) + ":**" + detailLine.slice(detailLine.indexOf(":") + 1) + " ");
10295
- }
10598
+ const detail = selection.detail.replace(/\r?\n/g, " ");
10599
+ const colon = detail.indexOf(":");
10600
+ lines.push(
10601
+ "**" + (colon === -1 ? "Selection" : detail.slice(0, colon)) + ":**" + (colon === -1 ? " " + detail : detail.slice(colon + 1)) + " "
10602
+ );
10296
10603
  lines.push("**Selected files:** " + selection.files.length + " ");
10297
10604
  const spent = manifest.budget?.usedTokens ?? manifest.slice?.usedTokens ?? 0;
10298
10605
  lines.push("**Tokens spent:** " + spent.toLocaleString("en-US"));
@@ -10302,7 +10609,7 @@ function generateSelectionReport(manifest, selection) {
10302
10609
  lines.push("| File | Tokens | Reason |");
10303
10610
  lines.push("| :-- | --: | :-- |");
10304
10611
  for (const file of selection.files) {
10305
- lines.push("| `" + file.path + "` | " + file.tokens.toLocaleString("en-US") + " | " + file.why + " |");
10612
+ lines.push("| `" + cell(file.path) + "` | " + file.tokens.toLocaleString("en-US") + " | " + cell(file.why) + " |");
10306
10613
  }
10307
10614
  lines.push("");
10308
10615
  const dropped = selection.kind === "slice" ? manifest.slice?.dropped : manifest.budget?.dropped;
@@ -10322,7 +10629,7 @@ function generateSelectionReport(manifest, selection) {
10322
10629
  lines.push("| File | Tokens |");
10323
10630
  lines.push("| :-- | --: |");
10324
10631
  for (const item of next) {
10325
- lines.push("| `" + item.path + "` | " + item.tokens.toLocaleString("en-US") + " |");
10632
+ lines.push("| `" + cell(item.path) + "` | " + item.tokens.toLocaleString("en-US") + " |");
10326
10633
  }
10327
10634
  lines.push("");
10328
10635
  }
@@ -10529,7 +10836,9 @@ function planForQuestion(manifest, question, options = {}) {
10529
10836
  notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
10530
10837
  }
10531
10838
  }
10532
- scored.sort((left, right) => right.score - left.score || left.file.relativePath.localeCompare(right.file.relativePath));
10839
+ scored.sort(
10840
+ (left, right) => right.score - left.score || (left.file.relativePath < right.file.relativePath ? -1 : left.file.relativePath > right.file.relativePath ? 1 : 0)
10841
+ );
10533
10842
  const chosen = /* @__PURE__ */ new Map();
10534
10843
  const skipped = [];
10535
10844
  let used = 0;
@@ -10616,26 +10925,113 @@ function formatNumber2(value) {
10616
10925
  return String(value).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
10617
10926
  }
10618
10927
  function runGit(cwd, args) {
10619
- const result = childProcess.spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true, maxBuffer: 64 * 1024 * 1024 });
10928
+ const result = childProcess.spawnSync(
10929
+ "git",
10930
+ [
10931
+ "-c",
10932
+ "core.quotepath=false",
10933
+ "-c",
10934
+ "diff.noprefix=false",
10935
+ "-c",
10936
+ "diff.mnemonicPrefix=false",
10937
+ ...args
10938
+ ],
10939
+ { cwd, encoding: "utf8", windowsHide: true, maxBuffer: 64 * 1024 * 1024 }
10940
+ );
10620
10941
  if (result.status !== 0) return { ok: false, out: (result.stderr ?? "").trim() };
10621
10942
  return { ok: true, out: result.stdout ?? "" };
10622
10943
  }
10623
10944
  function isGitRepository(cwd) {
10624
10945
  return runGit(cwd, ["rev-parse", "--is-inside-work-tree"]).out.trim() === "true";
10625
10946
  }
10947
+ function unquoteGitPath(value) {
10948
+ if (!value.startsWith('"') || !value.endsWith('"')) return value;
10949
+ const body = value.slice(1, -1);
10950
+ let out = "";
10951
+ let bytes = [];
10952
+ const flushBytes = () => {
10953
+ if (bytes.length === 0) return;
10954
+ out += Buffer.from(bytes).toString("utf8");
10955
+ bytes = [];
10956
+ };
10957
+ const escapes = {
10958
+ a: "\x07",
10959
+ b: "\b",
10960
+ f: "\f",
10961
+ n: "\n",
10962
+ r: "\r",
10963
+ t: " ",
10964
+ v: "\v",
10965
+ "\\": "\\",
10966
+ '"': '"'
10967
+ };
10968
+ for (let index = 0; index < body.length; index += 1) {
10969
+ const char = body[index];
10970
+ if (char !== "\\") {
10971
+ flushBytes();
10972
+ out += char;
10973
+ continue;
10974
+ }
10975
+ const next = body[index + 1];
10976
+ if (next === void 0) {
10977
+ flushBytes();
10978
+ out += "\\";
10979
+ break;
10980
+ }
10981
+ index += 1;
10982
+ if (/[0-7]/.test(next)) {
10983
+ let octal = next;
10984
+ while (octal.length < 3 && /[0-7]/.test(body[index + 1] ?? "")) {
10985
+ index += 1;
10986
+ octal += body[index];
10987
+ }
10988
+ bytes.push(Number.parseInt(octal, 8) & 255);
10989
+ continue;
10990
+ }
10991
+ flushBytes();
10992
+ out += escapes[next] ?? next;
10993
+ }
10994
+ flushBytes();
10995
+ return out;
10996
+ }
10997
+ function wholeLinePath(value, prefix) {
10998
+ const withoutTimestamp = value.endsWith(" ") ? value.slice(0, -1) : value;
10999
+ const unquoted = unquoteGitPath(withoutTimestamp);
11000
+ if (unquoted === "/dev/null") return null;
11001
+ if (!unquoted.startsWith(prefix)) return null;
11002
+ return unquoted.slice(prefix.length);
11003
+ }
11004
+ function headerPaths(value) {
11005
+ const separator = value.lastIndexOf(" b/");
11006
+ if (separator <= 0) return [];
11007
+ const left = unquoteGitPath(value.slice(0, separator));
11008
+ const right = unquoteGitPath(value.slice(separator + 1));
11009
+ const paths = [];
11010
+ if (left.startsWith("a/")) paths.push(left.slice(2));
11011
+ if (right.startsWith("b/")) paths.push(right.slice(2));
11012
+ return paths;
11013
+ }
10626
11014
  function diffSectionPaths(body) {
10627
11015
  const paths = /* @__PURE__ */ new Set();
11016
+ let header = null;
10628
11017
  for (const line of body.split("\n")) {
10629
- const plus = /^\+\+\+ b\/(.*)$/.exec(line);
10630
- if (plus !== null) paths.add(plus[1]);
10631
- const minus = /^--- a\/(.*)$/.exec(line);
10632
- if (minus !== null) paths.add(minus[1]);
10633
- const header = /^diff --git a\/(.*?) b\/(.*)$/.exec(line);
10634
- if (header !== null) {
10635
- paths.add(header[1]);
10636
- paths.add(header[2]);
11018
+ if (line.startsWith("diff --git ")) {
11019
+ header = line.slice("diff --git ".length);
11020
+ continue;
11021
+ }
11022
+ if (line.startsWith("+++ ")) {
11023
+ const path28 = wholeLinePath(line.slice(4), "b/");
11024
+ if (path28 !== null) paths.add(path28);
11025
+ continue;
11026
+ }
11027
+ if (line.startsWith("--- ")) {
11028
+ const path28 = wholeLinePath(line.slice(4), "a/");
11029
+ if (path28 !== null) paths.add(path28);
10637
11030
  }
10638
11031
  }
11032
+ if (paths.size === 0 && header !== null) {
11033
+ for (const path28 of headerPaths(header)) paths.add(path28);
11034
+ }
10639
11035
  return [...paths];
10640
11036
  }
10641
11037
  function generateDiffReport(cwd, options = {}) {
@@ -10644,6 +11040,7 @@ function generateDiffReport(cwd, options = {}) {
10644
11040
  const sections = [];
10645
11041
  let truncated = false;
10646
11042
  let omittedSensitive = 0;
11043
+ let omittedUnparseable = 0;
10647
11044
  const commands = [
10648
11045
  ["Unstaged", ["diff", "--no-color"]],
10649
11046
  ["Staged", ["diff", "--cached", "--no-color"]]
@@ -10654,6 +11051,10 @@ function generateDiffReport(cwd, options = {}) {
10654
11051
  const rawSections = result.out.split(/(?=^diff --git )/m).filter((section) => section.length > 0);
10655
11052
  for (const rawSection of rawSections) {
10656
11053
  const paths2 = diffSectionPaths(rawSection);
11054
+ if (paths2.length === 0) {
11055
+ omittedUnparseable += 1;
11056
+ continue;
11057
+ }
10657
11058
  const blocked = paths2.some((path28) => isSensitivePath(path28) || options.excluded?.(path28) === true);
10658
11059
  if (blocked) {
10659
11060
  omittedSensitive += 1;
@@ -10665,7 +11066,13 @@ function generateDiffReport(cwd, options = {}) {
10665
11066
  truncated = true;
10666
11067
  break;
10667
11068
  }
10668
- const chunk = truncateToBytes(rawSection, remaining);
11069
+ const sourcePath = paths2[0] ?? "reports/diff.md";
11070
+ const redactedSection = scanAndRedactSecrets(
11071
+ rawSection,
11072
+ options.secretRules ?? [],
11073
+ sourcePath
11074
+ ).redacted;
11075
+ const chunk = truncateToBytes(redactedSection, remaining);
10669
11076
  if (chunk.isTruncated) truncated = true;
10670
11077
  sections.push(
10671
11078
  "## " + title + " changes\n\nRun: git " + args.join(" ") + "\n\n```diff\n" + chunk.content + "\n```"
@@ -10686,6 +11093,10 @@ function generateDiffReport(cwd, options = {}) {
10686
11093
  "> " + omittedSensitive + " file section(s) omitted: their path is credential-bearing or excluded from the snapshot.",
10687
11094
  ""
10688
11095
  ] : [],
11096
+ ...omittedUnparseable > 0 ? [
11097
+ "> " + omittedUnparseable + " file section(s) omitted: their diff header could not be attributed to a path, so the sensitive-path filter could not run.",
11098
+ ""
11099
+ ] : [],
10689
11100
  ...sections,
10690
11101
  ...truncated ? ["", "> Truncated at " + maxBytes + " bytes. Run git diff for the rest."] : [],
10691
11102
  ""
@@ -10721,28 +11132,39 @@ function generateLogReport(cwd, options = {}) {
10721
11132
  }
10722
11133
 
10723
11134
  // src/generator/tokens.ts
11135
+ function cell2(value) {
11136
+ return escapeControls(value).replace(/\r?\n/g, " ").replace(/\|/g, "\\|");
11137
+ }
11138
+ function byCodeUnit(left, right) {
11139
+ return left < right ? -1 : left > right ? 1 : 0;
11140
+ }
10724
11141
  function tokensOf2(bytes) {
10725
11142
  return Math.max(1, Math.ceil(bytes * 0.25));
10726
11143
  }
10727
11144
  function generateTokenTree(manifest) {
10728
11145
  if (manifest.files.length === 0) return null;
10729
- const rows = manifest.files.map((file) => ({ path: file.relativePath, layer: file.layer, part: file.part, tokens: tokensOf2(file.includedBytes) })).sort((left, right) => right.tokens - left.tokens || left.path.localeCompare(right.path));
11146
+ const rows = manifest.files.map((file) => ({ path: file.relativePath, layer: file.layer, part: file.part, tokens: tokensOf2(file.includedBytes) })).sort((left, right) => right.tokens - left.tokens || byCodeUnit(left.path, right.path));
10730
11147
  const byDirectory = /* @__PURE__ */ new Map();
10731
11148
  for (const row of rows) {
10732
11149
  const directory = row.path.includes("/") ? row.path.slice(0, row.path.lastIndexOf("/")) : ".";
10733
11150
  byDirectory.set(directory, (byDirectory.get(directory) ?? 0) + row.tokens);
10734
11151
  }
10735
- const directories = [...byDirectory.entries()].sort((left, right) => right[1] - left[1]);
11152
+ const directories = [...byDirectory.entries()].sort(
11153
+ (left, right) => right[1] - left[1] || byCodeUnit(left[0], right[0])
11154
+ );
10736
11155
  const total = rows.reduce((sum, row) => sum + row.tokens, 0);
10737
- const rowsTable = rows.map((row) => "| " + row.path + " | " + row.layer + " | " + row.part + " | " + row.tokens + " |");
11156
+ const rowsTable = rows.map(
11157
+ (row) => "| " + cell2(row.path) + " | " + cell2(row.layer) + " | " + cell2(row.part) + " | " + row.tokens + " |"
11158
+ );
10738
11159
  const directoryTable = directories.map(
10739
- (entry) => "| " + entry[0] + " | " + entry[1] + " | " + (entry[1] / total * 100).toFixed(1) + "% |"
11160
+ (entry) => "| " + cell2(entry[0]) + " | " + entry[1] + " | " + (entry[1] / total * 100).toFixed(1) + "% |"
10740
11161
  );
10741
11162
  const text2 = [
10742
11163
  "# Token tree",
10743
11164
  "",
10744
- "Estimated tokens per file (one token per four bytes of emitted body), sorted by cost. The total",
10745
- "is the same estimate the manifest carries: an estimate, not a count.",
11165
+ "Estimated tokens per file (one token per four bytes of emitted body), sorted by cost. Each",
11166
+ "row is an estimate; the manifest total is estimated from the assembled parts, so the two can",
11167
+ "differ slightly and neither is a tokenizer count.",
10746
11168
  "",
10747
11169
  "## Directories",
10748
11170
  "",
@@ -10944,7 +11366,9 @@ function systemSection(manifest, code, brief, escape, sawManifest) {
10944
11366
  if (brief?.system !== void 0) {
10945
11367
  out.push(...ownerBlock(brief.system, brief.path, code, escape), "", "What the index records:", "");
10946
11368
  }
10947
- const layers = Object.entries(manifest.layers).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
11369
+ const layers = Object.entries(manifest.layers).sort(
11370
+ (a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)
11371
+ );
10948
11372
  if (layers.length > 0) {
10949
11373
  const shown = layers.slice(0, MAX_LAYER_ROWS).map(([name, count]) => code(name) + " " + formatNumber(count));
10950
11374
  const rest = layers.length > MAX_LAYER_ROWS ? ", and " + formatNumber(layers.length - MAX_LAYER_ROWS) + " more" : "";
@@ -11062,7 +11486,7 @@ function coverageSection(manifest, code, auditWritten, partsWritten, sawManifest
11062
11486
  for (const record of manifest.skipped) {
11063
11487
  reasons.set(record.reason, (reasons.get(record.reason) ?? 0) + 1);
11064
11488
  }
11065
- const tally = [...reasons.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([reason, count]) => code(reason) + " " + formatNumber(count)).join(", ");
11489
+ const tally = [...reasons.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([reason, count]) => code(reason) + " " + formatNumber(count)).join(", ");
11066
11490
  const found = manifest.totals.candidateFiles;
11067
11491
  const included = manifest.totals.includedFiles;
11068
11492
  const skipped = manifest.counts.skippedCount;
@@ -11189,7 +11613,7 @@ function ownerNotesSection(brief, code, text2) {
11189
11613
  if (brief === void 0 || brief.notes.length === 0) return [];
11190
11614
  const out = ["## Owner notes", ""];
11191
11615
  for (const note of brief.notes) {
11192
- out.push("### " + note.heading, "", ...ownerBlock(note.body, brief.path, code, text2), "");
11616
+ out.push("### " + text2(note.heading), "", ...ownerBlock(note.body, brief.path, code, text2), "");
11193
11617
  }
11194
11618
  return out;
11195
11619
  }
@@ -11410,27 +11834,31 @@ function generateReadme(manifest, artifacts) {
11410
11834
  const readOrder = [];
11411
11835
  if (wrote("prompt")) {
11412
11836
  readOrder.push(
11413
- "1. Hand `PROMPT.md` to the model that receives this snapshot: it names the parts, the partial files and the fingerprint of this run."
11837
+ "Hand `PROMPT.md` to the model that receives this snapshot: it names the parts, the partial files and the fingerprint of this run."
11414
11838
  );
11415
11839
  }
11416
11840
  if (wrote("navigation") || wrote("projectTree")) {
11417
11841
  const first = [wrote("navigation") ? "`reports/navigation.md`" : null, wrote("projectTree") ? "`reports/project-tree.md`" : null].filter(Boolean).join(" or ");
11418
- readOrder.push(`1. Read ${first} first to locate target features or files.`);
11842
+ readOrder.push(`Read ${first} first to locate target features or files.`);
11419
11843
  }
11420
11844
  if (wrote("parts")) {
11421
11845
  readOrder.push(
11422
- `${readOrder.length + 1}. Open only the specific \`parts/part-XXX.md\` file holding the target modules.`
11846
+ "Open only the specific `parts/part-XXX.md` file holding the target modules."
11423
11847
  );
11424
11848
  }
11425
11849
  if (wrote("manifest")) {
11426
- readOrder.push(
11427
- `${readOrder.length + 1}. Inspect \`manifest.json\` for precise dependency and AST symbol maps.`
11428
- );
11850
+ readOrder.push("Inspect `manifest.json` for precise dependency and AST symbol maps.");
11429
11851
  }
11430
11852
  readOrder.push(
11431
- 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.`
11853
+ 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."
11854
+ );
11855
+ lines.push(
11856
+ "",
11857
+ "## AI Agent Ingestion Guide",
11858
+ "",
11859
+ ...readOrder.map((step, index) => `${index + 1}. ${step}`),
11860
+ ""
11432
11861
  );
11433
- lines.push("", "## AI Agent Ingestion Guide", "", ...readOrder, "");
11434
11862
  return lines.join("\n");
11435
11863
  }
11436
11864
 
@@ -11517,6 +11945,8 @@ function treeTruncationWarnings(treeText) {
11517
11945
  }
11518
11946
  return warnings;
11519
11947
  }
11948
+
11949
+ // src/generator/overview.ts
11520
11950
  var SUMMARY_LIMIT = 400;
11521
11951
  var MAX_RELEASES = 2;
11522
11952
  function readProjectOverview(cwd) {
@@ -11526,15 +11956,12 @@ function readProjectOverview(cwd) {
11526
11956
  releases: readReleases(cwd)
11527
11957
  };
11528
11958
  }
11529
- function readText(file) {
11530
- try {
11531
- return fs24__namespace.readFileSync(file, "utf8");
11532
- } catch {
11533
- return null;
11534
- }
11959
+ function readText(cwd, relative17) {
11960
+ const read = readConfinedText(cwd, relative17);
11961
+ return read.ok ? read.text : null;
11535
11962
  }
11536
11963
  function readDescription(cwd) {
11537
- const raw = readText(path27__namespace.join(cwd, "package.json"));
11964
+ const raw = readText(cwd, "package.json");
11538
11965
  if (raw === null) return {};
11539
11966
  try {
11540
11967
  const parsed = JSON.parse(stripJsonComments(raw));
@@ -11544,7 +11971,7 @@ function readDescription(cwd) {
11544
11971
  }
11545
11972
  }
11546
11973
  function readSummary(cwd) {
11547
- const raw = readText(path27__namespace.join(cwd, "README.md"));
11974
+ const raw = readText(cwd, "README.md");
11548
11975
  if (raw === null) return {};
11549
11976
  const text2 = raw.replace(/<h[1-6][^>]*>[\s\S]*?<\/h[1-6]>/gi, "\n").replace(/<\/(p|div|section|header|footer|li)>/gi, "\n").replace(/<br\s*\/?>/gi, " ").replace(/<[^>]*>/g, " ").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'");
11550
11977
  const paragraph = [];
@@ -11570,7 +11997,7 @@ function truncate(text2, limit) {
11570
11997
  return (space > limit / 2 ? window.slice(0, space) : window).trim() + "\u2026";
11571
11998
  }
11572
11999
  function readReleases(cwd) {
11573
- const raw = readText(path27__namespace.join(cwd, "CHANGELOG.md"));
12000
+ const raw = readText(cwd, "CHANGELOG.md");
11574
12001
  if (raw === null) return [];
11575
12002
  const headings = raw.split(/\r?\n/).map((line) => /^##\s+(.+?)\s*$/.exec(line)?.[1]?.trim()).filter((heading) => heading !== void 0 && /^v?\d+\.\d+/.test(heading));
11576
12003
  return headings.slice(0, MAX_RELEASES);
@@ -11649,9 +12076,11 @@ function isPrivateIPv6(groups) {
11649
12076
  ]);
11650
12077
  if (allZeroThrough(5) && sixth === 65535) return mapped(6);
11651
12078
  if (allZeroThrough(6) && (seventh !== 0 || eighth !== 0)) return mapped(6);
12079
+ if (allZeroThrough(4) && fifth === 65535 && sixth === 0) return mapped(6);
11652
12080
  if (first === 100 && second === 65435 && third === 0 && fourth === 0 && fifth === 0 && sixth === 0) {
11653
12081
  return mapped(6);
11654
12082
  }
12083
+ if (first === 100 && second === 65435 && third === 1) return mapped(6);
11655
12084
  if (first === 8194) return mapped(1);
11656
12085
  return false;
11657
12086
  }
@@ -11765,61 +12194,69 @@ async function cloneRepository(source, options) {
11765
12194
  const dest = path27__namespace.resolve(options.dest);
11766
12195
  fs24__namespace.rmSync(dest, { recursive: true, force: true });
11767
12196
  fs24__namespace.mkdirSync(dest, { recursive: true });
11768
- const ref = options.ref ?? source.ref;
11769
- const args = [
11770
- "-c",
11771
- "http.followRedirects=false",
11772
- ...source.kind === "https" ? ["-c", "protocol.file.allow=never", "-c", "protocol.ssh.allow=never"] : [],
11773
- "clone",
11774
- "--depth",
11775
- "1",
11776
- "--single-branch",
11777
- "--no-tags",
11778
- "--quiet"
11779
- ];
11780
- if (ref !== void 0 && ref !== null && ref !== "") {
11781
- args.push("--branch", ref);
11782
- }
11783
- args.push(source.url, dest);
11784
- log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
11785
- const started = Date.now();
11786
- const result = childProcess.spawnSync("git", args, {
11787
- env: {
11788
- ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
11789
- ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
11790
- },
11791
- timeout: options.timeoutMs ?? 18e4,
11792
- encoding: "utf8",
11793
- windowsHide: true
11794
- });
11795
- if (result.error !== void 0 && result.error !== null) {
11796
- throw new Error("git clone could not run: " + result.error.message);
11797
- }
11798
- if (result.status !== 0) {
11799
- const detail = (result.stderr ?? "").trim().split("\n").slice(-3).join(" ");
11800
- throw new Error("git clone failed (exit " + result.status + "): " + (detail || "no output"));
11801
- }
11802
- const head = childProcess.spawnSync("git", ["-C", dest, "rev-parse", "HEAD"], { encoding: "utf8", windowsHide: true });
11803
- const commit = head.status === 0 ? (head.stdout ?? "").trim() : "";
11804
- if (commit === "") throw new Error("the clone has no HEAD; refusing to describe it");
11805
- const bytes = directorySize(dest);
11806
- log("clone: " + (bytes / 1024 / 1024).toFixed(1) + " MB in " + ((Date.now() - started) / 1e3).toFixed(1) + "s");
11807
- if (bytes > 1e9) {
11808
- throw new Error("the clone is larger than 1 GB (" + Math.round(bytes / 1024 / 1024) + " MB); refusing to scan it");
11809
- }
11810
- return {
11811
- directory: dest,
11812
- commit,
11813
- provenance: {
11814
- url: source.url,
11815
- host: source.host,
11816
- owner: source.owner,
11817
- repo: source.repo,
11818
- ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
12197
+ try {
12198
+ const ref = options.ref ?? source.ref;
12199
+ const args = [
12200
+ "-c",
12201
+ "http.followRedirects=false",
12202
+ ...source.kind === "https" ? ["-c", "protocol.file.allow=never", "-c", "protocol.ssh.allow=never"] : [],
12203
+ "clone",
12204
+ "--depth",
12205
+ "1",
12206
+ "--single-branch",
12207
+ "--no-tags",
12208
+ "--quiet"
12209
+ ];
12210
+ if (ref !== void 0 && ref !== null && ref !== "") {
12211
+ args.push("--branch", ref);
12212
+ }
12213
+ args.push(source.url, dest);
12214
+ log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
12215
+ const started = Date.now();
12216
+ const result = childProcess.spawnSync("git", args, {
12217
+ env: {
12218
+ ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
12219
+ ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
12220
+ },
12221
+ timeout: options.timeoutMs ?? 18e4,
12222
+ encoding: "utf8",
12223
+ windowsHide: true
12224
+ });
12225
+ if (result.error !== void 0 && result.error !== null) {
12226
+ throw new Error("git clone could not run: " + result.error.message);
12227
+ }
12228
+ if (result.status !== 0) {
12229
+ const detail = (result.stderr ?? "").trim().split("\n").slice(-3).join(" ");
12230
+ throw new Error("git clone failed (exit " + result.status + "): " + (detail || "no output"));
12231
+ }
12232
+ const head = childProcess.spawnSync("git", ["-C", dest, "rev-parse", "HEAD"], { encoding: "utf8", windowsHide: true });
12233
+ const commit = head.status === 0 ? (head.stdout ?? "").trim() : "";
12234
+ if (commit === "") throw new Error("the clone has no HEAD; refusing to describe it");
12235
+ const bytes = directorySize(dest);
12236
+ log("clone: " + (bytes / 1024 / 1024).toFixed(1) + " MB in " + ((Date.now() - started) / 1e3).toFixed(1) + "s");
12237
+ if (bytes > 1e9) {
12238
+ throw new Error("the clone is larger than 1 GB (" + Math.round(bytes / 1024 / 1024) + " MB); refusing to scan it");
12239
+ }
12240
+ return {
12241
+ directory: dest,
11819
12242
  commit,
11820
- fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
12243
+ provenance: {
12244
+ url: source.url,
12245
+ host: source.host,
12246
+ owner: source.owner,
12247
+ repo: source.repo,
12248
+ ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
12249
+ commit,
12250
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
12251
+ }
12252
+ };
12253
+ } catch (error) {
12254
+ try {
12255
+ fs24__namespace.rmSync(dest, { recursive: true, force: true });
12256
+ } catch {
11821
12257
  }
11822
- };
12258
+ throw error;
12259
+ }
11823
12260
  }
11824
12261
  function directorySize(root) {
11825
12262
  let total = 0;
@@ -12052,7 +12489,7 @@ var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
12052
12489
  var META_PREFIX = "- Meta: ";
12053
12490
  var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
12054
12491
  var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
12055
- var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
12492
+ var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures", "comments-stripped"]);
12056
12493
  var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
12057
12494
  function readIncludedLines(fields) {
12058
12495
  const last = fields[fields.length - 1];
@@ -12147,17 +12584,10 @@ var ARTIFACT_FILES = {
12147
12584
  fullXml: "full-codebase.xml",
12148
12585
  sarif: "reports/audit.sarif"
12149
12586
  };
12150
- var TEXT_ARTIFACT = /\.(md|json|txt|sarif)$/i;
12587
+ var TEXT_ARTIFACT = /\.(md|json|txt|sarif|xml)$/i;
12151
12588
  function sha256(buffer) {
12152
12589
  return crypto.createHash("sha256").update(buffer).digest("hex");
12153
12590
  }
12154
- function readBytes(file) {
12155
- try {
12156
- return fs24__namespace.readFileSync(file);
12157
- } catch {
12158
- return null;
12159
- }
12160
- }
12161
12591
  function readText2(file) {
12162
12592
  try {
12163
12593
  return fs24__namespace.readFileSync(file, "utf8");
@@ -12165,8 +12595,17 @@ function readText2(file) {
12165
12595
  return null;
12166
12596
  }
12167
12597
  }
12598
+ function snapshotText(snapshotDir, relative17) {
12599
+ const read = readConfinedText(snapshotDir, relative17);
12600
+ return read.ok ? read.text : null;
12601
+ }
12602
+ function snapshotBytes(snapshotDir, relative17) {
12603
+ const read = readConfinedBytes(snapshotDir, relative17);
12604
+ return read.ok ? read.bytes : null;
12605
+ }
12168
12606
  function readJson(file) {
12169
- const text2 = readText2(file);
12607
+ const confined = readConfinedText(path27__namespace.dirname(file), path27__namespace.basename(file));
12608
+ const text2 = confined.ok ? confined.text : null;
12170
12609
  if (text2 === null) return null;
12171
12610
  try {
12172
12611
  return JSON.parse(text2);
@@ -12183,9 +12622,9 @@ function walk(dir, prefix = "") {
12183
12622
  }
12184
12623
  const files = [];
12185
12624
  for (const entry of entries) {
12186
- const relative16 = prefix === "" ? entry.name : prefix + "/" + entry.name;
12187
- if (entry.isDirectory()) files.push(...walk(path27__namespace.join(dir, entry.name), relative16));
12188
- else if (entry.isFile()) files.push(relative16);
12625
+ const relative17 = prefix === "" ? entry.name : prefix + "/" + entry.name;
12626
+ if (entry.isDirectory()) files.push(...walk(path27__namespace.join(dir, entry.name), relative17));
12627
+ else if (entry.isFile()) files.push(relative17);
12189
12628
  }
12190
12629
  return files;
12191
12630
  }
@@ -12223,16 +12662,28 @@ function secretTokens(text2) {
12223
12662
  }
12224
12663
  return [...tokens];
12225
12664
  }
12226
- function readArtifactTexts(snapshotDir) {
12665
+ function readArtifactTexts(snapshotDir, maxBytes = 32 * 1024 * 1024) {
12227
12666
  const texts = [];
12228
- for (const relative16 of walk(snapshotDir)) {
12229
- if (!TEXT_ARTIFACT.test(relative16)) continue;
12230
- const text2 = readText2(path27__namespace.join(snapshotDir, relative16));
12231
- if (text2 !== null) texts.push(text2);
12667
+ let bytes = 0;
12668
+ for (const relative17 of walk(snapshotDir)) {
12669
+ if (!TEXT_ARTIFACT.test(relative17)) continue;
12670
+ const full = path27__namespace.join(snapshotDir, relative17);
12671
+ let size2;
12672
+ try {
12673
+ size2 = fs24__namespace.statSync(full).size;
12674
+ } catch {
12675
+ continue;
12676
+ }
12677
+ if (bytes + size2 > maxBytes) break;
12678
+ const text2 = snapshotText(snapshotDir, relative17);
12679
+ if (text2 !== null) {
12680
+ texts.push(text2);
12681
+ bytes += Buffer.byteLength(text2, "utf8");
12682
+ }
12232
12683
  }
12233
12684
  return texts;
12234
12685
  }
12235
- function findHostPaths(snapshotDir, repoDir) {
12686
+ function findHostPaths(snapshotDir, repoDir, maxBytes = 32 * 1024 * 1024) {
12236
12687
  const patterns = [
12237
12688
  /\/home\/[A-Za-z0-9._-]+/g,
12238
12689
  /\/Users\/[A-Za-z0-9._-]+/g,
@@ -12243,15 +12694,24 @@ function findHostPaths(snapshotDir, repoDir) {
12243
12694
  ];
12244
12695
  const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
12245
12696
  const hits = /* @__PURE__ */ new Set();
12246
- for (const relative16 of walk(snapshotDir)) {
12247
- if (!TEXT_ARTIFACT.test(relative16)) continue;
12248
- const text2 = readText2(path27__namespace.join(snapshotDir, relative16));
12697
+ let scanned = 0;
12698
+ for (const relative17 of walk(snapshotDir)) {
12699
+ if (!TEXT_ARTIFACT.test(relative17)) continue;
12700
+ let size2;
12701
+ try {
12702
+ size2 = fs24__namespace.statSync(path27__namespace.join(snapshotDir, relative17)).size;
12703
+ } catch {
12704
+ continue;
12705
+ }
12706
+ if (scanned + size2 > maxBytes) break;
12707
+ const text2 = snapshotText(snapshotDir, relative17);
12249
12708
  if (text2 === null) continue;
12709
+ scanned += Buffer.byteLength(text2, "utf8");
12250
12710
  for (const pattern of patterns) {
12251
- for (const match of text2.match(pattern) ?? []) hits.add(relative16 + ": " + match);
12711
+ for (const match of text2.match(pattern) ?? []) hits.add(relative17 + ": " + match);
12252
12712
  }
12253
12713
  repoPattern.lastIndex = 0;
12254
- if (repoPattern.test(text2)) hits.add(relative16 + ": the repository absolute path");
12714
+ if (repoPattern.test(text2)) hits.add(relative17 + ": the repository absolute path");
12255
12715
  }
12256
12716
  return [...hits];
12257
12717
  }
@@ -12433,7 +12893,7 @@ function auditSnapshot(options) {
12433
12893
  const missingParts = [];
12434
12894
  const mismatched = [];
12435
12895
  for (const part of manifest.parts) {
12436
- const bytes = readBytes(path27__namespace.join(snapshotDir, "parts", part.filename));
12896
+ const bytes = snapshotBytes(snapshotDir, "parts/" + part.filename);
12437
12897
  if (bytes === null) {
12438
12898
  missingParts.push(part.filename);
12439
12899
  continue;
@@ -12498,13 +12958,13 @@ function auditSnapshot(options) {
12498
12958
  let artifactCount = 0;
12499
12959
  for (const [key, value] of Object.entries(artifacts)) {
12500
12960
  if (value === null || value === void 0) continue;
12501
- const relative16 = ARTIFACT_FILES[key];
12502
- if (relative16 === void 0) continue;
12961
+ const relative17 = ARTIFACT_FILES[key];
12962
+ if (relative17 === void 0) continue;
12503
12963
  artifactCount += 1;
12504
- const bytes = readBytes(path27__namespace.join(snapshotDir, relative16));
12505
- if (bytes === null) artifactProblems.push(relative16 + " is missing");
12964
+ const bytes = snapshotBytes(snapshotDir, relative17);
12965
+ if (bytes === null) artifactProblems.push(relative17 + " is missing");
12506
12966
  else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
12507
- artifactProblems.push(relative16 + " changed");
12967
+ artifactProblems.push(relative17 + " changed");
12508
12968
  }
12509
12969
  }
12510
12970
  checks.push(
@@ -12614,7 +13074,7 @@ function auditSnapshot(options) {
12614
13074
  manifest.files.map((file) => [anchorForPath(file.relativePath), file.relativePath])
12615
13075
  );
12616
13076
  for (const part of manifest.parts) {
12617
- const partText = readText2(path27__namespace.join(snapshotDir, "parts", part.filename));
13077
+ const partText = snapshotText(snapshotDir, "parts/" + part.filename);
12618
13078
  if (partText === null) continue;
12619
13079
  const sections = parsePartSections(partText);
12620
13080
  partTexts.set(part.filename, partText);
@@ -12681,7 +13141,7 @@ function auditSnapshot(options) {
12681
13141
  }
12682
13142
  };
12683
13143
  if (manifest.artifacts?.readme != null) {
12684
- const text2 = readText2(path27__namespace.join(snapshotDir, "README.md"));
13144
+ const text2 = snapshotText(snapshotDir, "README.md");
12685
13145
  if (text2 === null) {
12686
13146
  reportProblems.push("README.md is recorded but unreadable");
12687
13147
  } else {
@@ -12721,7 +13181,7 @@ function auditSnapshot(options) {
12721
13181
  }
12722
13182
  }
12723
13183
  if (manifest.artifacts?.prompt != null) {
12724
- const text2 = readText2(path27__namespace.join(snapshotDir, "PROMPT.md"));
13184
+ const text2 = snapshotText(snapshotDir, "PROMPT.md");
12725
13185
  if (text2 === null) {
12726
13186
  reportProblems.push("PROMPT.md is recorded but unreadable");
12727
13187
  } else {
@@ -12910,7 +13370,7 @@ function auditSnapshot(options) {
12910
13370
  ];
12911
13371
  for (const reader of packReaders) {
12912
13372
  if (manifest.artifacts?.[reader.key] == null) continue;
12913
- const packText = readText2(path27__namespace.join(snapshotDir, reader.file));
13373
+ const packText = snapshotText(snapshotDir, reader.file);
12914
13374
  const problems = [];
12915
13375
  if (packText === null) {
12916
13376
  problems.push(reader.file + " is recorded but unreadable");
@@ -12960,7 +13420,7 @@ function auditSnapshot(options) {
12960
13420
  bodyByPath.set(file.relativePath, section.body);
12961
13421
  bodiesChecked += 1;
12962
13422
  const bytes = Buffer.byteLength(section.body, "utf8");
12963
- const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
13423
+ const bodyLines = countBodyLines(section.body);
12964
13424
  if (bytes !== file.includedBytes) {
12965
13425
  bodyProblems.push(file.relativePath + ": manifest says " + file.includedBytes + " B, part holds " + bytes + " B");
12966
13426
  } else if (bodyLines !== file.includedLines) {
@@ -13073,7 +13533,7 @@ function auditSnapshot(options) {
13073
13533
  let packBodies = 0;
13074
13534
  let packSkipped = 0;
13075
13535
  for (const pack of packsWanted) {
13076
- const text2 = readText2(path27__namespace.join(snapshotDir, pack.file));
13536
+ const text2 = snapshotText(snapshotDir, pack.file);
13077
13537
  if (text2 === null) continue;
13078
13538
  const bodies = pack.read(text2);
13079
13539
  if (bodies === null) {
@@ -13137,7 +13597,8 @@ function auditSnapshot(options) {
13137
13597
  unreplayable += 1;
13138
13598
  continue;
13139
13599
  }
13140
- const bytes = readBytes(path27__namespace.join(repoDir, file.relativePath));
13600
+ const repoBytes = readConfinedBytes(repoDir, file.relativePath);
13601
+ const bytes = repoBytes.ok ? repoBytes.bytes : null;
13141
13602
  if (bytes === null || sha256(bytes) !== file.hashSha256) {
13142
13603
  unreplayable += 1;
13143
13604
  continue;
@@ -13234,30 +13695,37 @@ function auditSnapshot(options) {
13234
13695
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
13235
13696
  const leakHits = [];
13236
13697
  let scannedBytes = 0;
13237
- for (const relative16 of walk(snapshotDir)) {
13238
- if (!TEXT_ARTIFACT.test(relative16) || scannedBytes > scanBudget) continue;
13239
- if (relative16 === SIGNATURE_FILE) continue;
13240
- const text2 = readText2(path27__namespace.join(snapshotDir, relative16));
13698
+ for (const relative17 of walk(snapshotDir)) {
13699
+ if (!TEXT_ARTIFACT.test(relative17) || scannedBytes > scanBudget) continue;
13700
+ if (relative17 === SIGNATURE_FILE) continue;
13701
+ let size2;
13702
+ try {
13703
+ size2 = fs24__namespace.statSync(path27__namespace.join(snapshotDir, relative17)).size;
13704
+ } catch {
13705
+ continue;
13706
+ }
13707
+ if (scannedBytes + size2 > scanBudget) break;
13708
+ const text2 = snapshotText(snapshotDir, relative17);
13241
13709
  if (text2 === null) continue;
13242
13710
  scannedBytes += Buffer.byteLength(text2, "utf8");
13243
13711
  let findingCount = 0;
13244
- if (/^parts[\\/].*\.md$/i.test(relative16)) {
13712
+ if (/^parts[\\/].*\.md$/i.test(relative17)) {
13245
13713
  let headerText = text2;
13246
13714
  for (const section of parsePartSections(text2)) {
13247
13715
  findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
13248
13716
  headerText = headerText.replace(section.body, "");
13249
13717
  }
13250
- findingCount += scanAndRedactSecrets(headerText, rules, relative16).findings.length;
13718
+ findingCount += scanAndRedactSecrets(headerText, rules, relative17).findings.length;
13251
13719
  } else {
13252
- findingCount = scanAndRedactSecrets(text2, rules, relative16).findings.length;
13720
+ findingCount = scanAndRedactSecrets(text2, rules, relative17).findings.length;
13253
13721
  }
13254
13722
  if (findingCount > 0) {
13255
- leakHits.push(relative16 + " (" + findingCount + " line(s))");
13723
+ leakHits.push(relative17 + " (" + findingCount + " line(s))");
13256
13724
  }
13257
13725
  }
13258
13726
  const signatureRecordPath = path27__namespace.join(snapshotDir, SIGNATURE_FILE);
13259
13727
  if (fs24__namespace.existsSync(signatureRecordPath)) {
13260
- const recordText = readText2(signatureRecordPath);
13728
+ const recordText = snapshotText(snapshotDir, SIGNATURE_FILE);
13261
13729
  if (recordText !== null) {
13262
13730
  scannedBytes += Buffer.byteLength(recordText, "utf8");
13263
13731
  let scanText = recordText;
@@ -13297,11 +13765,17 @@ function auditSnapshot(options) {
13297
13765
  );
13298
13766
  const leakedFrom = [];
13299
13767
  let compared = 0;
13300
- const artifactTexts = readArtifactTexts(snapshotDir);
13768
+ const artifactTexts = readArtifactTexts(snapshotDir, scanBudget);
13301
13769
  const artifactContains = (token) => artifactTexts.some((text2) => text2.includes(token));
13302
13770
  for (const record of skippedSensitive.slice(0, 40)) {
13303
13771
  if (record.path.includes("[REDACTED") || compared > 400) continue;
13304
- const text2 = readText2(path27__namespace.join(repoDir, record.path));
13772
+ try {
13773
+ if (fs24__namespace.statSync(path27__namespace.join(repoDir, record.path)).size > scanBudget) continue;
13774
+ } catch {
13775
+ continue;
13776
+ }
13777
+ const repoRead = readConfinedText(repoDir, record.path);
13778
+ const text2 = repoRead.ok ? repoRead.text : null;
13305
13779
  if (text2 === null) continue;
13306
13780
  for (const token of secretTokens(text2)) {
13307
13781
  compared += 1;
@@ -13323,7 +13797,7 @@ function auditSnapshot(options) {
13323
13797
  "A value from " + sample([...new Set(leakedFrom)]) + " appears in the snapshot."
13324
13798
  )
13325
13799
  );
13326
- const pii = findHostPaths(snapshotDir, repoDir);
13800
+ const pii = findHostPaths(snapshotDir, repoDir, scanBudget);
13327
13801
  checks.push(
13328
13802
  pii.length === 0 ? check(
13329
13803
  "pii.paths",
@@ -13454,7 +13928,10 @@ const { parentPort, workerData } = require("node:worker_threads");
13454
13928
  (async () => {
13455
13929
  try {
13456
13930
  const mod = await import(workerData.entryUrl);
13457
- const loaded = await mod.loadConfigFileDetailed(workerData.cwd);
13931
+ const loaded =
13932
+ workerData.config === null || workerData.config === undefined
13933
+ ? await mod.loadConfigFileDetailed(workerData.cwd, { allowExecutableConfig: false })
13934
+ : { config: workerData.config, errors: [] };
13458
13935
  if (loaded.errors.length > 0) {
13459
13936
  parentPort.postMessage({ ok: false, message: loaded.errors.join("; ") });
13460
13937
  return;
@@ -13466,6 +13943,7 @@ const { parentPort, workerData } = require("node:worker_threads");
13466
13943
  const manifest = mod.generateSnapshot(config, {
13467
13944
  dryRun: workerData.dryRun === true,
13468
13945
  ...(workerData.narrow ?? {}),
13946
+ ...(workerData.source === undefined ? {} : { source: workerData.source }),
13469
13947
  ...(workerData.runId === undefined ? {} : { runId: workerData.runId }),
13470
13948
  });
13471
13949
  const skipCounts = new Map();
@@ -13506,7 +13984,7 @@ const { parentPort, workerData } = require("node:worker_threads");
13506
13984
  })();
13507
13985
  `;
13508
13986
  function generateInWorker(cwd, cliOptions, options = {}) {
13509
- return new Promise((resolve15) => {
13987
+ return new Promise((resolve16) => {
13510
13988
  let settled = false;
13511
13989
  let worker = null;
13512
13990
  const finish = (result) => {
@@ -13517,7 +13995,7 @@ function generateInWorker(cwd, cliOptions, options = {}) {
13517
13995
  if (!result.ok && options.runId !== void 0 && options.lockRoots !== void 0) {
13518
13996
  releaseAbandonedRun(options.lockRoots, options.runId);
13519
13997
  }
13520
- resolve15(result);
13998
+ resolve16(result);
13521
13999
  });
13522
14000
  };
13523
14001
  const isCjs = typeof __dirname !== "undefined";
@@ -13531,6 +14009,8 @@ function generateInWorker(cwd, cliOptions, options = {}) {
13531
14009
  cliOptions,
13532
14010
  dryRun: options.dryRun === true,
13533
14011
  narrow: options.narrow ?? {},
14012
+ ...options.config === void 0 ? {} : { config: options.config },
14013
+ ...options.source === void 0 ? {} : { source: options.source },
13534
14014
  ...options.runId === void 0 ? {} : { runId: options.runId }
13535
14015
  }
13536
14016
  });
@@ -13594,7 +14074,7 @@ function canonicalPath(value) {
13594
14074
  return absolute;
13595
14075
  }
13596
14076
  }
13597
- function isInside2(parent, child) {
14077
+ function isInside3(parent, child) {
13598
14078
  const foldedParent = foldForComparison(parent);
13599
14079
  const foldedChild = foldForComparison(child);
13600
14080
  return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path27__namespace.sep}`);
@@ -13628,7 +14108,7 @@ function resolveRoot(requested, context) {
13628
14108
  }
13629
14109
  const resolved = canonicalPath(absolute);
13630
14110
  for (const allowed of context.roots) {
13631
- if (isInside2(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
14111
+ if (isInside3(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
13632
14112
  }
13633
14113
  const shown = context.roots.join(", ");
13634
14114
  return {
@@ -13672,7 +14152,7 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
13672
14152
  const requested = overrides.outDir.trim();
13673
14153
  const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
13674
14154
  const resolved = resolveThroughExistingAncestor(path27__namespace.resolve(root, requested));
13675
- if (!permitted.some((allowed) => isInside2(canonicalPath(allowed), resolved))) {
14155
+ if (!permitted.some((allowed) => isInside3(canonicalPath(allowed), resolved))) {
13676
14156
  const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
13677
14157
  return {
13678
14158
  ok: false,
@@ -13694,6 +14174,14 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
13694
14174
  if (overrides.sarif === true) cliOptions.sarif = true;
13695
14175
  if (overrides.staged === true) cliOptions.staged = true;
13696
14176
  if (overrides.withDependents === true) cliOptions.withDependents = true;
14177
+ for (const key of ["only", "ignore"]) {
14178
+ const value = overrides[key];
14179
+ if (value === void 0) continue;
14180
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
14181
+ return { ok: false, message: `"${key}" must be an array of glob strings.` };
14182
+ }
14183
+ cliOptions[key] = value;
14184
+ }
13697
14185
  try {
13698
14186
  const config = resolveConfig(loaded.config, cliOptions, root);
13699
14187
  return {
@@ -13719,8 +14207,8 @@ function partPathFor(workspace, filename) {
13719
14207
  if (filename.length === 0 || filename.includes("\0")) return null;
13720
14208
  const partsDir = path27__namespace.resolve(workspace.root, workspace.config.outDir, "parts");
13721
14209
  const resolved = path27__namespace.resolve(partsDir, filename);
13722
- const relative16 = path27__namespace.relative(partsDir, resolved);
13723
- if (relative16.length === 0 || relative16.includes(path27__namespace.sep) || relative16.includes("/") || relative16.includes("\\") || path27__namespace.isAbsolute(relative16)) {
14210
+ const relative17 = path27__namespace.relative(partsDir, resolved);
14211
+ if (relative17.length === 0 || relative17.includes(path27__namespace.sep) || relative17.includes("/") || relative17.includes("\\") || path27__namespace.isAbsolute(relative17)) {
13724
14212
  return null;
13725
14213
  }
13726
14214
  let stats;
@@ -13740,30 +14228,27 @@ function partPathFor(workspace, filename) {
13740
14228
  function readManifest3(workspace) {
13741
14229
  const file = manifestPathFor(workspace);
13742
14230
  const shown = path27__namespace.relative(workspace.root, file).split(path27__namespace.sep).join("/") || file;
13743
- let stats;
13744
- try {
13745
- stats = fs24__namespace.statSync(file);
13746
- } catch {
14231
+ const confined = readConfinedText(path27__namespace.dirname(file), path27__namespace.basename(file));
14232
+ if (!confined.ok) {
14233
+ if (confined.reason === "missing") {
14234
+ return {
14235
+ ok: false,
14236
+ missing: true,
14237
+ message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
14238
+ };
14239
+ }
13747
14240
  return {
13748
14241
  ok: false,
13749
- missing: true,
13750
- message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
14242
+ missing: false,
14243
+ message: `${shown} could not be read as a snapshot manifest: ${confined.message}.`
13751
14244
  };
13752
14245
  }
14246
+ const stats = confined.stats;
14247
+ const raw = confined.text;
13753
14248
  const cached = manifestCache.get(file);
13754
14249
  if (cached && cached.mtimeMs === stats.mtimeMs && cached.ctimeMs === stats.ctimeMs && cached.size === stats.size) {
13755
14250
  return { ok: true, manifest: cached.manifest, file };
13756
14251
  }
13757
- let raw;
13758
- try {
13759
- raw = fs24__namespace.readFileSync(file, "utf8");
13760
- } catch (error) {
13761
- return {
13762
- ok: false,
13763
- missing: false,
13764
- message: `${shown} exists but could not be read: ${error instanceof Error ? error.message : String(error)}`
13765
- };
13766
- }
13767
14252
  let parsed;
13768
14253
  try {
13769
14254
  parsed = JSON.parse(raw);
@@ -13787,10 +14272,127 @@ function readManifest3(workspace) {
13787
14272
  if (oldest === void 0) break;
13788
14273
  manifestCache.delete(oldest);
13789
14274
  }
13790
- return { ok: true, manifest, file };
14275
+ return { ok: true, manifest, file };
14276
+ }
14277
+ function forgetManifest(file) {
14278
+ manifestCache.delete(file);
14279
+ }
14280
+
14281
+ // src/security/regex.ts
14282
+ var MAX_PATTERN_LENGTH = 256;
14283
+ var MAX_QUANTIFIER_REPEAT = 1e4;
14284
+ function unsafeRegExpReason(source) {
14285
+ if (source.length === 0) return null;
14286
+ if (source.length > MAX_PATTERN_LENGTH) {
14287
+ return `the pattern is longer than ${MAX_PATTERN_LENGTH} characters`;
14288
+ }
14289
+ let inClass = false;
14290
+ let unbounded = 0;
14291
+ const groups = [];
14292
+ for (let index = 0; index < source.length; index += 1) {
14293
+ const char = source[index];
14294
+ if (char === "\\") {
14295
+ index += 1;
14296
+ continue;
14297
+ }
14298
+ if (inClass) {
14299
+ if (char === "]") inClass = false;
14300
+ continue;
14301
+ }
14302
+ if (char === "[") {
14303
+ inClass = true;
14304
+ continue;
14305
+ }
14306
+ if (char === "(") {
14307
+ groups.push({ quantified: false, alternation: false });
14308
+ continue;
14309
+ }
14310
+ if (char === ")") {
14311
+ const group = groups.pop();
14312
+ if (group === void 0) continue;
14313
+ if (isQuantifiedAt(source, index + 1)) {
14314
+ if (group.quantified || group.alternation) {
14315
+ return "a quantified group contains another quantifier or an alternation";
14316
+ }
14317
+ group.quantified = true;
14318
+ } else if (isOptionalQuantifierAt(source, index + 1)) {
14319
+ group.quantified = true;
14320
+ }
14321
+ const parent = groups[groups.length - 1];
14322
+ if (parent !== void 0) {
14323
+ parent.quantified = parent.quantified || group.quantified;
14324
+ parent.alternation = parent.alternation || group.alternation;
14325
+ }
14326
+ continue;
14327
+ }
14328
+ if (char === "|") {
14329
+ const group = groups[groups.length - 1];
14330
+ if (group !== void 0) group.alternation = true;
14331
+ continue;
14332
+ }
14333
+ if (char === "?") {
14334
+ const previous = source[index - 1];
14335
+ if (previous !== "(" && previous !== "?" && previous !== "*" && previous !== "+" && previous !== "}") {
14336
+ const group = groups[groups.length - 1];
14337
+ if (group !== void 0) group.quantified = true;
14338
+ }
14339
+ continue;
14340
+ }
14341
+ if (char === "*" || char === "+") {
14342
+ unbounded += 1;
14343
+ const group = groups[groups.length - 1];
14344
+ if (group !== void 0) group.quantified = true;
14345
+ continue;
14346
+ }
14347
+ if (char === "{") {
14348
+ const close = source.indexOf("}", index + 1);
14349
+ if (close === -1) continue;
14350
+ const body = source.slice(index + 1, close);
14351
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
14352
+ if (match === null) {
14353
+ index = close;
14354
+ continue;
14355
+ }
14356
+ const max = match[2] === void 0 ? Number(match[1]) : match[2] === "" ? Infinity : Number(match[2]);
14357
+ if (max > MAX_QUANTIFIER_REPEAT) {
14358
+ return "a repetition bound is larger than the search budget can evaluate safely";
14359
+ }
14360
+ if (max === Infinity) unbounded += 1;
14361
+ const group = groups[groups.length - 1];
14362
+ if (group !== void 0) group.quantified = true;
14363
+ index = close;
14364
+ }
14365
+ }
14366
+ if (unbounded > 1) {
14367
+ return "the pattern has more than one unbounded repetition";
14368
+ }
14369
+ return null;
13791
14370
  }
13792
- function forgetManifest(file) {
13793
- manifestCache.delete(file);
14371
+ function isOptionalQuantifierAt(source, start) {
14372
+ if (source[start] === "?") return true;
14373
+ if (source[start] !== "{") return false;
14374
+ const close = source.indexOf("}", start + 1);
14375
+ if (close === -1) return false;
14376
+ const body = source.slice(start + 1, close);
14377
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
14378
+ if (match === null) return false;
14379
+ const minimum = Number(match[1]);
14380
+ if (match[2] === void 0) return minimum <= 1;
14381
+ const maximum = match[2] === "" ? Infinity : Number(match[2]);
14382
+ return maximum <= 1;
14383
+ }
14384
+ function isQuantifiedAt(source, start) {
14385
+ const char = source[start];
14386
+ if (char === "*" || char === "+") return true;
14387
+ if (char !== "{") return false;
14388
+ const close = source.indexOf("}", start + 1);
14389
+ if (close === -1) return false;
14390
+ const body = source.slice(start + 1, close);
14391
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
14392
+ if (match === null) return false;
14393
+ if (match[2] === void 0) return Number(match[1]) > 1;
14394
+ if (match[2] === "") return true;
14395
+ return Number(match[2]) > 1;
13794
14396
  }
13795
14397
 
13796
14398
  // src/mcp/tools.ts
@@ -13824,6 +14426,16 @@ var OUT_DIR_PROPERTY = {
13824
14426
  };
13825
14427
  var outDirOverride = (args) => ({ outDir: args.outDir });
13826
14428
  var SCOPE_PROPERTIES = {
14429
+ only: {
14430
+ type: "array",
14431
+ items: { type: "string" },
14432
+ description: "Globs to include: replaces the config allow-list for this run."
14433
+ },
14434
+ ignore: {
14435
+ type: "array",
14436
+ items: { type: "string" },
14437
+ description: "Globs to exclude, added to the config deny-list for this run."
14438
+ },
13827
14439
  maxPartTokens: {
13828
14440
  type: "string",
13829
14441
  description: 'Token ceiling per part, for example 32000 or "32k". Narrower than maxPartBytes; it converts at four bytes per token.'
@@ -13858,7 +14470,9 @@ function workspaceOverrides(args) {
13858
14470
  sarif: args.sarif,
13859
14471
  changedSince: args.changedSince,
13860
14472
  staged: args.staged,
13861
- withDependents: args.withDependents
14473
+ withDependents: args.withDependents,
14474
+ only: args.only,
14475
+ ignore: args.ignore
13862
14476
  };
13863
14477
  }
13864
14478
  function failure(message) {
@@ -13894,11 +14508,11 @@ function toRelativePath(root, value) {
13894
14508
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
13895
14509
  const resolvedRoot = path27__namespace.resolve(root);
13896
14510
  const absolute = path27__namespace.resolve(resolvedRoot, cleaned);
13897
- const relative16 = path27__namespace.relative(resolvedRoot, absolute);
13898
- if (relative16 === "" || relative16 === ".." || relative16.startsWith(`..${path27__namespace.sep}`) || path27__namespace.isAbsolute(relative16)) {
14511
+ const relative17 = path27__namespace.relative(resolvedRoot, absolute);
14512
+ if (relative17 === "" || relative17 === ".." || relative17.startsWith(`..${path27__namespace.sep}`) || path27__namespace.isAbsolute(relative17)) {
13899
14513
  return null;
13900
14514
  }
13901
- return relative16.split(path27__namespace.sep).join("/");
14515
+ return relative17.split(path27__namespace.sep).join("/");
13902
14516
  }
13903
14517
  function symbolsOf(entry) {
13904
14518
  const summary = entry.summary;
@@ -13991,16 +14605,15 @@ var historyTool = {
13991
14605
  async handler(args, context) {
13992
14606
  const prepared = await prepare(args, context, outDirOverride(args));
13993
14607
  if (!prepared.ok) return prepared.outcome;
13994
- const reportPath = path27__namespace.resolve(prepared.workspace.root, prepared.workspace.config.outDir, "reports", "log.md");
13995
- let text2;
13996
- try {
13997
- text2 = fs24__namespace.readFileSync(reportPath, "utf8");
13998
- } catch {
14608
+ const snapshotDir = path27__namespace.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
14609
+ const reportRead = readConfinedText(snapshotDir, path27__namespace.posix.join("reports", "log.md"));
14610
+ if (!reportRead.ok) {
13999
14611
  return {
14000
- 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.",
14612
+ 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.",
14001
14613
  isError: true
14002
14614
  };
14003
14615
  }
14616
+ const text2 = reportRead.text;
14004
14617
  const manifestRead = readManifest3(prepared.workspace);
14005
14618
  const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
14006
14619
  if (recordedLog !== void 0 && recordedLog !== null) {
@@ -14164,21 +14777,22 @@ var workspaceTool = {
14164
14777
  async handler(args, context) {
14165
14778
  const prepared = await prepare(args, context, outDirOverride(args));
14166
14779
  if (!prepared.ok) return prepared.outcome;
14167
- const index = path27__namespace.resolve(
14168
- prepared.workspace.root,
14169
- prepared.workspace.config.outDir,
14170
- "WORKSPACE.json"
14171
- );
14172
- let text2;
14173
- try {
14174
- text2 = fs24__namespace.readFileSync(index, "utf8");
14175
- } catch {
14780
+ const snapshotDir = path27__namespace.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
14781
+ const index = path27__namespace.join(snapshotDir, "WORKSPACE.json");
14782
+ const read = readConfinedText(snapshotDir, "WORKSPACE.json");
14783
+ if (!read.ok) {
14176
14784
  return {
14177
- text: "No workspace index at " + index + ". Generate one with `generate --workspace member-a,member-b`; a single snapshot has no members to list.",
14785
+ 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.",
14178
14786
  isError: true
14179
14787
  };
14180
14788
  }
14181
- const document = JSON.parse(text2);
14789
+ const text2 = read.text;
14790
+ let document;
14791
+ try {
14792
+ document = JSON.parse(text2);
14793
+ } catch (error) {
14794
+ return { text: "WORKSPACE.json is not valid JSON: " + error.message, isError: true };
14795
+ }
14182
14796
  const members = document.members ?? [];
14183
14797
  const links = document.links ?? [];
14184
14798
  const lines = [
@@ -14318,6 +14932,10 @@ var routesTool = {
14318
14932
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
14319
14933
  let filter = null;
14320
14934
  if (typeof args.pattern === "string") {
14935
+ const unsafe = unsafeRegExpReason(args.pattern);
14936
+ if (unsafe !== null) {
14937
+ return { text: "pattern is refused: " + unsafe + ".", isError: true };
14938
+ }
14321
14939
  try {
14322
14940
  filter = new RegExp(args.pattern, "i");
14323
14941
  } catch (error) {
@@ -14461,6 +15079,12 @@ var searchTool = {
14461
15079
  const cap = Math.max(1, Math.min(500, typeof args.maxMatches === "number" ? args.maxMatches : 50));
14462
15080
  const contextLines = Math.max(0, Math.min(10, typeof args.contextLines === "number" ? args.contextLines : 0));
14463
15081
  let pattern;
15082
+ if (args.regex === true) {
15083
+ const unsafe = unsafeRegExpReason(query);
15084
+ if (unsafe !== null) {
15085
+ return { text: "regex is refused: " + unsafe + ".", isError: true };
15086
+ }
15087
+ }
14464
15088
  try {
14465
15089
  pattern = args.regex === true ? new RegExp(query, "i") : new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
14466
15090
  } catch (error) {
@@ -14483,11 +15107,17 @@ var searchTool = {
14483
15107
  } catch {
14484
15108
  continue;
14485
15109
  }
14486
- if (Buffer.byteLength(text2, "utf8") > MAX_SEARCH_BYTES) {
15110
+ const partBytes = Buffer.byteLength(text2, "utf8");
15111
+ if (partBytes > MAX_SEARCH_BYTES) {
14487
15112
  skippedOversize.push(part.filename);
15113
+ truncated = true;
14488
15114
  continue;
14489
15115
  }
14490
- scanned += text2.length;
15116
+ if (scanned + partBytes > MAX_SEARCH_BYTES) {
15117
+ truncated = true;
15118
+ break;
15119
+ }
15120
+ scanned += partBytes;
14491
15121
  for (const section of parsePartSections(text2)) {
14492
15122
  if (matches.length >= cap) {
14493
15123
  truncated = true;
@@ -14853,28 +15483,39 @@ var symbolTool = {
14853
15483
  };
14854
15484
  }
14855
15485
  const callSites = [];
15486
+ let referencesTruncated = false;
14856
15487
  if (args.references !== false) {
14857
15488
  const limit = Math.max(1, typeof args.maxReferences === "number" ? args.maxReferences : 20);
14858
15489
  const definitionKeys = new Set(matches.map((match) => match.path + ":" + match.line));
14859
15490
  const word = new RegExp("\\b" + name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b");
14860
- const parts = /* @__PURE__ */ new Map();
15491
+ const sectionsByPart = /* @__PURE__ */ new Map();
14861
15492
  let scanned = 0;
14862
15493
  for (const file of read.manifest.files) {
14863
15494
  if (callSites.length >= limit) break;
14864
15495
  const partPath = partPathFor(workspace, file.part);
14865
15496
  if (partPath === null) continue;
14866
- let partText = parts.get(partPath);
14867
- if (partText === void 0) {
15497
+ let sections = sectionsByPart.get(partPath);
15498
+ if (sections === void 0) {
15499
+ if (scanned >= MAX_SEARCH_BYTES) {
15500
+ referencesTruncated = true;
15501
+ break;
15502
+ }
15503
+ let partText;
14868
15504
  try {
14869
15505
  partText = fs24__namespace.readFileSync(partPath, "utf8");
14870
15506
  } catch {
14871
15507
  continue;
14872
15508
  }
14873
- parts.set(partPath, partText);
15509
+ const bytes = Buffer.byteLength(partText, "utf8");
15510
+ if (scanned + bytes > MAX_SEARCH_BYTES) {
15511
+ referencesTruncated = true;
15512
+ break;
15513
+ }
15514
+ scanned += bytes;
15515
+ sections = parsePartSections(partText);
15516
+ sectionsByPart.set(partPath, sections);
14874
15517
  }
14875
- if (scanned > MAX_SEARCH_BYTES) break;
14876
- scanned += Buffer.byteLength(partText, "utf8");
14877
- const section = findSection(parsePartSections(partText), file.relativePath);
15518
+ const section = findSection(sections, file.relativePath);
14878
15519
  if (section === null) continue;
14879
15520
  const bodyLines = section.body.split("\n");
14880
15521
  for (let index = 0; index < bodyLines.length && callSites.length < limit; index += 1) {
@@ -14888,8 +15529,11 @@ var symbolTool = {
14888
15529
  }
14889
15530
  }
14890
15531
  }
14891
- 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")));
14892
- return { text: text2, structured: { found: matches.length, matches, references: callSites } };
15532
+ 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." : "");
15533
+ return {
15534
+ text: text2,
15535
+ structured: { found: matches.length, matches, references: callSites, truncated: referencesTruncated }
15536
+ };
14893
15537
  }
14894
15538
  };
14895
15539
  var contextTool = {
@@ -15047,6 +15691,10 @@ var queryTool = {
15047
15691
  const maxFiles = typeof args.maxFiles === "number" ? Math.min(200, Math.max(1, args.maxFiles)) : 40;
15048
15692
  let pattern = null;
15049
15693
  if (typeof args.pathPattern === "string") {
15694
+ const unsafe = unsafeRegExpReason(args.pathPattern);
15695
+ if (unsafe !== null) {
15696
+ return { text: "pathPattern is refused: " + unsafe + ".", isError: true };
15697
+ }
15050
15698
  try {
15051
15699
  pattern = new RegExp(args.pathPattern, "i");
15052
15700
  } catch (error) {
@@ -15432,7 +16080,12 @@ var planTool = {
15432
16080
  const prepared = await prepare(args, context, workspaceOverrides(args));
15433
16081
  if (!prepared.ok) return prepared.outcome;
15434
16082
  const workspace = prepared.workspace;
15435
- const result = await generateInWorker(workspace.root, workspace.cliOptions, { dryRun: true });
16083
+ const controller = new AbortController();
16084
+ context.onCancel?.(() => controller.abort());
16085
+ const result = await generateInWorker(workspace.root, workspace.cliOptions, {
16086
+ dryRun: true,
16087
+ signal: controller.signal
16088
+ });
15436
16089
  if (!result.ok) return failure(result.message);
15437
16090
  const summary = result.summary;
15438
16091
  const topReasons = summary.skipReasons;
@@ -15522,16 +16175,6 @@ var generateTool = {
15522
16175
  minimum: 500,
15523
16176
  description: "Fit the snapshot into this token budget, highest value first."
15524
16177
  },
15525
- only: {
15526
- type: "array",
15527
- items: { type: "string" },
15528
- description: "Globs to include: replaces the config allow-list for this run."
15529
- },
15530
- ignore: {
15531
- type: "array",
15532
- items: { type: "string" },
15533
- description: "Globs to exclude, added to the config deny-list for this run."
15534
- },
15535
16178
  ...SCOPE_PROPERTIES
15536
16179
  },
15537
16180
  additionalProperties: false
@@ -15650,7 +16293,12 @@ function configAsGenerated(workspace, manifest) {
15650
16293
  ...cli.includeLogs !== void 0 || configured("logCount") || recorded?.logCount !== void 0 ? { logCount: choose("logCount", recorded?.logCount, workspace.config.logCount, cli.includeLogs) } : {},
15651
16294
  ...cli.skeleton === true || configured("skeleton") || recorded?.skeleton !== void 0 ? { skeleton: choose("skeleton", recorded?.skeleton, workspace.config.skeleton, cli.skeleton === true ? true : void 0) } : {},
15652
16295
  ...cli.sarif === true || configured("sarif") || recorded?.sarif !== void 0 ? { sarif: choose("sarif", recorded?.sarif, workspace.config.sarif, cli.sarif === true ? true : void 0) } : {},
15653
- ...configured("maxParts") || recorded?.maxParts !== void 0 ? { maxParts: choose("maxParts", recorded?.maxParts, workspace.config.maxParts) } : {}
16296
+ ...configured("maxParts") || recorded?.maxParts !== void 0 ? { maxParts: choose("maxParts", recorded?.maxParts, workspace.config.maxParts) } : {},
16297
+ ...cli.maxPartTokens !== void 0 || configured("maxPartTokens") || recorded?.maxPartTokens !== void 0 ? { maxPartTokens: choose("maxPartTokens", recorded?.maxPartTokens, workspace.config.maxPartTokens, cli.maxPartTokens) } : {},
16298
+ ...cli.changedSince !== void 0 || configured("changedSince") || recorded?.changedSince !== void 0 ? { changedSince: choose("changedSince", recorded?.changedSince, workspace.config.changedSince, cli.changedSince) } : {},
16299
+ ...cli.staged === true || configured("staged") || recorded?.staged !== void 0 ? { staged: choose("staged", recorded?.staged, workspace.config.staged, cli.staged === true ? true : void 0) } : {},
16300
+ ...cli.withDependents === true || configured("withDependents") || recorded?.withDependents !== void 0 ? { withDependents: choose("withDependents", recorded?.withDependents, workspace.config.withDependents, cli.withDependents === true ? true : void 0) } : {},
16301
+ ...configured("promptTask") || recorded?.promptTask !== void 0 ? { promptTask: choose("promptTask", recorded?.promptTask, workspace.config.promptTask) } : {}
15654
16302
  };
15655
16303
  }
15656
16304
  var validateTool = {
@@ -16541,7 +17189,7 @@ var COMMAND_OPTION_SCOPE = {
16541
17189
  "version"
16542
17190
  ],
16543
17191
  diff: ["format", "mode", "no-config", "no-update-check", "help", "version"],
16544
- describe: ["format", "mode", "help", "version"],
17192
+ describe: ["format", "mode", "no-update-check", "help", "version"],
16545
17193
  init: [
16546
17194
  "install-hook",
16547
17195
  "cwd",
@@ -16562,7 +17210,7 @@ var COMMAND_OPTION_SCOPE = {
16562
17210
  "help",
16563
17211
  "version"
16564
17212
  ],
16565
- skill: ["cwd", "format", "mode", "install", "target", "help", "version"],
17213
+ skill: ["cwd", "format", "mode", "install", "target", "no-update-check", "help", "version"],
16566
17214
  // `mcp` reads the repository, so it takes --cwd. It has no --format: stdout carries JSON-RPC
16567
17215
  // messages, and there is no second shape to choose, so offering the flag would be a lie.
16568
17216
  serve: ["port", "host", "token", "no-auth", "allow-private", "cwd", "no-update-check", "help"],
@@ -16621,6 +17269,7 @@ var COMMAND_ORDER = [
16621
17269
  "health",
16622
17270
  "report",
16623
17271
  "explain",
17272
+ "update",
16624
17273
  "init",
16625
17274
  "setup",
16626
17275
  "diff",
@@ -17082,24 +17731,28 @@ function buildAgentContract() {
17082
17731
  {
17083
17732
  flag: "--only",
17084
17733
  type: "string",
17734
+ default: "unset",
17085
17735
  summary: "Comma-separated globs to include: overrides the config include list for this run.",
17086
17736
  appliesTo: optionAppliesTo("only")
17087
17737
  },
17088
17738
  {
17089
17739
  flag: "--ignore",
17090
17740
  type: "string",
17741
+ default: "unset",
17091
17742
  summary: "Comma-separated globs to exclude, added to the config exclude list for this run.",
17092
17743
  appliesTo: optionAppliesTo("ignore")
17093
17744
  },
17094
17745
  {
17095
17746
  flag: "--remove-empty-lines",
17096
17747
  type: "boolean",
17748
+ default: false,
17097
17749
  summary: "Drop blank and whitespace-only lines from emitted bodies; line numbers no longer match the source.",
17098
17750
  appliesTo: optionAppliesTo("remove-empty-lines")
17099
17751
  },
17100
17752
  {
17101
17753
  flag: "--all-members",
17102
17754
  type: "boolean",
17755
+ default: false,
17103
17756
  summary: "Audit every snapshot a --workspace run wrote, not only the one at outDir.",
17104
17757
  appliesTo: optionAppliesTo("all-members")
17105
17758
  },
@@ -17813,36 +18466,46 @@ function buildResourceProvider() {
17813
18466
  }
17814
18467
  const workspace = await workspaceFor(context);
17815
18468
  if ("error" in workspace) return null;
18469
+ const snapshotDir = path27__namespace.resolve(workspace.root, workspace.config.outDir);
17816
18470
  if (uri === PROMPT_URI) {
17817
- const text2 = readFileIfPresent(
17818
- path27__namespace.resolve(workspace.root, workspace.config.outDir, "PROMPT.md")
17819
- );
17820
- if (text2 === null) {
18471
+ const read = readConfinedText(snapshotDir, "PROMPT.md");
18472
+ if (!read.ok) {
17821
18473
  throw new ResourceNotFoundError(
17822
18474
  uri,
17823
- "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."
18475
+ "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."
17824
18476
  );
17825
18477
  }
17826
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, PROMPT_ADVICE) };
18478
+ return {
18479
+ uri,
18480
+ mimeType: "text/markdown",
18481
+ text: ensureSingleRead(uri, read.text, PROMPT_ADVICE)
18482
+ };
17827
18483
  }
17828
18484
  const report2 = REPORT_URIS.get(uri);
17829
18485
  if (report2) {
17830
- const text2 = readFileIfPresent(
17831
- path27__namespace.resolve(workspace.root, workspace.config.outDir, "reports", report2.file)
17832
- );
17833
- if (text2 === null) {
18486
+ const read = readConfinedText(snapshotDir, path27__namespace.posix.join("reports", report2.file));
18487
+ if (!read.ok) {
17834
18488
  throw new ResourceNotFoundError(
17835
18489
  uri,
17836
- "This snapshot contains no " + report2.file + ": that report was disabled, or nothing has been generated yet. Run snapshot_generate first."
18490
+ "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."
17837
18491
  );
17838
18492
  }
17839
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, REPORT_ADVICE) };
18493
+ return {
18494
+ uri,
18495
+ mimeType: "text/markdown",
18496
+ text: ensureSingleRead(uri, read.text, REPORT_ADVICE)
18497
+ };
17840
18498
  }
17841
18499
  if (uri === "snapshot://manifest") {
17842
18500
  const read = readManifest3(workspace);
17843
18501
  if (!read.ok) return null;
17844
- const text2 = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
17845
- return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text2, MANIFEST_ADVICE) };
18502
+ const confined = readConfinedText(path27__namespace.dirname(read.file), path27__namespace.basename(read.file));
18503
+ if (!confined.ok) return null;
18504
+ return {
18505
+ uri,
18506
+ mimeType: "application/json",
18507
+ text: ensureSingleRead(uri, confined.text, MANIFEST_ADVICE)
18508
+ };
17846
18509
  }
17847
18510
  const partMatch = PART_URI.exec(uri);
17848
18511
  if (partMatch) {
@@ -18302,11 +18965,11 @@ var MAX_LINE_BYTES = 32 * 1024 * 1024;
18302
18965
  function createWriter(output) {
18303
18966
  return {
18304
18967
  write(value) {
18305
- return new Promise((resolve15, reject) => {
18968
+ return new Promise((resolve16, reject) => {
18306
18969
  output.write(`${JSON.stringify(value)}
18307
18970
  `, (error) => {
18308
18971
  if (error) reject(error);
18309
- else resolve15();
18972
+ else resolve16();
18310
18973
  });
18311
18974
  });
18312
18975
  }
@@ -18445,12 +19108,12 @@ async function runStdioServer(options) {
18445
19108
  });
18446
19109
  return writeChain;
18447
19110
  };
18448
- const MAX_IN_FLIGHT = 4;
19111
+ const MAX_IN_FLIGHT2 = 4;
18449
19112
  let inFlight = 0;
18450
19113
  let inputEnded = false;
18451
19114
  let resolveDone = () => void 0;
18452
- const finished = new Promise((resolve15) => {
18453
- resolveDone = resolve15;
19115
+ const finished = new Promise((resolve16) => {
19116
+ resolveDone = resolve16;
18454
19117
  });
18455
19118
  const finishIfIdle = () => {
18456
19119
  if (inputEnded && inFlight === 0) resolveDone(0);
@@ -18480,14 +19143,26 @@ async function runStdioServer(options) {
18480
19143
  errorResponse(
18481
19144
  id,
18482
19145
  ERROR_CODES.overloaded,
18483
- `The server is already handling ${MAX_IN_FLIGHT} requests; retry this one when it is free.`
19146
+ `The server is already handling ${MAX_IN_FLIGHT2} requests; retry this one when it is free.`
18484
19147
  )
18485
19148
  );
18486
19149
  };
19150
+ const isCancellation = (line) => {
19151
+ try {
19152
+ const parsed = JSON.parse(line);
19153
+ return parsed !== null && typeof parsed === "object" && parsed.method === "notifications/cancelled";
19154
+ } catch {
19155
+ return false;
19156
+ }
19157
+ };
18487
19158
  const stopReading = createLineReader(process.stdin, {
18488
19159
  onOverflow: (bytes) => log(`mcp: discarded an oversized message (${bytes} bytes)`),
18489
19160
  onLine: (line) => {
18490
- if (inFlight >= MAX_IN_FLIGHT) {
19161
+ if (inFlight >= MAX_IN_FLIGHT2) {
19162
+ if (isCancellation(line)) {
19163
+ void handleLine(line);
19164
+ return;
19165
+ }
18491
19166
  rejectOverloaded(line);
18492
19167
  return;
18493
19168
  }
@@ -18533,30 +19208,44 @@ function crc32(data) {
18533
19208
  return (crc ^ 4294967295) >>> 0;
18534
19209
  }
18535
19210
  function dosDateTime(date) {
18536
- const year = Math.max(1980, date.getFullYear());
19211
+ const year = Math.max(1980, date.getUTCFullYear());
18537
19212
  return {
18538
- time: date.getHours() << 11 | date.getMinutes() << 5 | Math.floor(date.getSeconds() / 2),
18539
- date: year - 1980 << 9 | date.getMonth() + 1 << 5 | date.getDate()
19213
+ time: date.getUTCHours() << 11 | date.getUTCMinutes() << 5 | Math.floor(date.getUTCSeconds() / 2),
19214
+ date: year - 1980 << 9 | date.getUTCMonth() + 1 << 5 | date.getUTCDate()
18540
19215
  };
18541
19216
  }
18542
19217
  function walkFiles(root, prefix = "") {
18543
19218
  const files = [];
18544
- for (const entry of fs24__namespace.readdirSync(path27__namespace.join(root, prefix), { withFileTypes: true })) {
18545
- const relative16 = prefix === "" ? entry.name : prefix + "/" + entry.name;
18546
- if (entry.isDirectory()) files.push(...walkFiles(root, relative16));
18547
- else if (entry.isFile()) files.push(relative16);
19219
+ const stack = [prefix];
19220
+ while (stack.length > 0) {
19221
+ const current = stack.pop();
19222
+ for (const entry of fs24__namespace.readdirSync(path27__namespace.join(root, current), { withFileTypes: true })) {
19223
+ const relative17 = current === "" ? entry.name : current + "/" + entry.name;
19224
+ if (entry.isDirectory()) stack.push(relative17);
19225
+ else if (entry.isFile()) files.push(relative17);
19226
+ }
18548
19227
  }
18549
19228
  return files;
18550
19229
  }
18551
19230
  function writeZip(options) {
18552
19231
  const entries = [...options.entries ?? []];
19232
+ const maxTotalBytes = options.maxTotalBytes ?? 256 * 1024 * 1024;
19233
+ let totalBytes = entries.reduce((total, entry) => total + entry.content.length, 0);
19234
+ if (totalBytes > maxTotalBytes) {
19235
+ throw new Error("zip: uncompressed content exceeds " + maxTotalBytes + " bytes");
19236
+ }
18553
19237
  if (options.directory !== void 0) {
18554
19238
  const root = options.directory;
18555
- for (const relative16 of walkFiles(root)) {
18556
- if (options.skip !== void 0 && options.skip(relative16)) continue;
18557
- const full = path27__namespace.join(root, relative16);
19239
+ for (const relative17 of walkFiles(root)) {
19240
+ if (options.skip !== void 0 && options.skip(relative17)) continue;
19241
+ const full = path27__namespace.join(root, relative17);
18558
19242
  const stat = fs24__namespace.statSync(full);
18559
- entries.push({ name: relative16, content: fs24__namespace.readFileSync(full), mtime: stat.mtime });
19243
+ if (totalBytes + stat.size > maxTotalBytes) {
19244
+ throw new Error("zip: uncompressed content exceeds " + maxTotalBytes + " bytes");
19245
+ }
19246
+ const content = fs24__namespace.readFileSync(full);
19247
+ totalBytes += content.length;
19248
+ entries.push({ name: relative17, content, mtime: stat.mtime });
18560
19249
  }
18561
19250
  }
18562
19251
  if (entries.length > 65535) {
@@ -18776,6 +19465,7 @@ var SERVE_PAGE = `<!doctype html>
18776
19465
  var DEFAULT_PORT = 4788;
18777
19466
  var MAX_BODY = 64 * 1024;
18778
19467
  var MAX_PREVIEW = 64 * 1024;
19468
+ var MAX_MCP_IN_FLIGHT = 4;
18779
19469
  function isLoopback(origin) {
18780
19470
  try {
18781
19471
  const url = new URL(origin);
@@ -18793,6 +19483,23 @@ async function startWebServer(options) {
18793
19483
  throw new Error("Refusing to serve " + host + " without a token.");
18794
19484
  }
18795
19485
  const createMcp = () => createServer({ cwd: options.cwd, log });
19486
+ const toolCount = buildTools().length;
19487
+ const rateWindows = /* @__PURE__ */ new Map();
19488
+ const rateLimited = (request) => {
19489
+ const remote = request.socket.remoteAddress ?? "unknown";
19490
+ const now = Date.now();
19491
+ const window = rateWindows.get(remote);
19492
+ if (window === void 0 || window.resetAt <= now) {
19493
+ if (!rateWindows.has(remote) && rateWindows.size >= 1024) {
19494
+ for (const [key, value] of rateWindows) if (value.resetAt <= now) rateWindows.delete(key);
19495
+ }
19496
+ rateWindows.set(remote, { count: 1, resetAt: now + 1e4 });
19497
+ return false;
19498
+ }
19499
+ if (window.count >= 120) return true;
19500
+ window.count += 1;
19501
+ return false;
19502
+ };
18796
19503
  const mcpPerSocket = /* @__PURE__ */ new WeakMap();
18797
19504
  const mcpFor = (socket) => {
18798
19505
  let server2 = mcpPerSocket.get(socket);
@@ -18803,6 +19510,7 @@ async function startWebServer(options) {
18803
19510
  return server2;
18804
19511
  };
18805
19512
  const temporaryClones = /* @__PURE__ */ new Set();
19513
+ let mcpInFlight = 0;
18806
19514
  const allowedRoots = [path27__namespace.resolve(options.cwd)];
18807
19515
  const canonical = (candidate) => {
18808
19516
  try {
@@ -18811,21 +19519,22 @@ async function startWebServer(options) {
18811
19519
  return null;
18812
19520
  }
18813
19521
  };
19522
+ const fold = (value) => process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
18814
19523
  const inside = (resolved) => allowedRoots.some((root) => {
18815
19524
  const canonicalRoot = canonical(root);
18816
19525
  if (canonicalRoot === null) return false;
18817
- const relative16 = path27__namespace.relative(canonicalRoot, resolved);
18818
- return relative16 === "" || !relative16.startsWith(`..${path27__namespace.sep}`) && relative16 !== ".." && !path27__namespace.isAbsolute(relative16);
19526
+ const relative17 = path27__namespace.relative(fold(canonicalRoot), fold(resolved));
19527
+ return relative17 === "" || !relative17.startsWith(`..${path27__namespace.sep}`) && relative17 !== ".." && !path27__namespace.isAbsolute(relative17);
18819
19528
  });
18820
19529
  const insideAllowedRoots = (candidate) => {
18821
19530
  const resolved = canonical(candidate);
18822
19531
  return resolved === null ? false : inside(resolved);
18823
19532
  };
18824
19533
  const lexicallyInside = (candidate) => {
18825
- const resolved = path27__namespace.resolve(candidate);
19534
+ const resolved = fold(path27__namespace.resolve(candidate));
18826
19535
  return allowedRoots.some((root) => {
18827
- const prefix = path27__namespace.resolve(root) + path27__namespace.sep;
18828
- return resolved === path27__namespace.resolve(root) || resolved.startsWith(prefix);
19536
+ const resolvedRoot = fold(path27__namespace.resolve(root));
19537
+ return resolved === resolvedRoot || resolved.startsWith(resolvedRoot + path27__namespace.sep);
18829
19538
  });
18830
19539
  };
18831
19540
  const insideAllowedRootsForWrite = (candidate) => {
@@ -18883,8 +19592,12 @@ async function startWebServer(options) {
18883
19592
  response.end();
18884
19593
  return;
18885
19594
  }
19595
+ if (rateLimited(request)) {
19596
+ send(429, { error: "too many requests" }, { "retry-after": "10" });
19597
+ return;
19598
+ }
18886
19599
  if (request.method === "GET" && request.url === "/healthz") {
18887
- send(200, { ok: true, name: "codebase-snapshot", tools: 12 });
19600
+ send(200, { ok: true, name: "codebase-snapshot", tools: toolCount });
18888
19601
  return;
18889
19602
  }
18890
19603
  if (request.method === "GET" && (request.url === "/" || request.url === "/index.html")) {
@@ -18929,12 +19642,35 @@ async function startWebServer(options) {
18929
19642
  const server2 = mcpFor(request.socket);
18930
19643
  const answers = [];
18931
19644
  for (const item of batch) {
18932
- const answer = await server2.handle(item);
18933
- if (answer !== null) answers.push(answer);
19645
+ const gated = item !== null && typeof item === "object" && item.method === "tools/call";
19646
+ if (gated && mcpInFlight >= MAX_MCP_IN_FLIGHT) {
19647
+ answers.push({
19648
+ jsonrpc: "2.0",
19649
+ id: item.id ?? null,
19650
+ error: {
19651
+ code: -32001,
19652
+ message: "server busy: too many tool calls are already in flight"
19653
+ }
19654
+ });
19655
+ continue;
19656
+ }
19657
+ if (gated) mcpInFlight += 1;
19658
+ try {
19659
+ const answer = await server2.handle(item);
19660
+ if (answer !== null) answers.push(answer);
19661
+ } finally {
19662
+ if (gated) mcpInFlight -= 1;
19663
+ }
18934
19664
  }
18935
19665
  if (answers.length === 0) send(202, "");
18936
19666
  else send(200, Array.isArray(message) ? answers : answers[0]);
18937
- })();
19667
+ })().catch((error) => {
19668
+ log("serve: " + error.message);
19669
+ try {
19670
+ send(500, { error: "internal error" });
19671
+ } catch {
19672
+ }
19673
+ });
18938
19674
  });
18939
19675
  return;
18940
19676
  }
@@ -19027,13 +19763,12 @@ async function startWebServer(options) {
19027
19763
  send(400, { error: "not a directory: " + target });
19028
19764
  return;
19029
19765
  }
19030
- const loaded = await loadConfigFileDetailed(target, { allowExecutableConfig: false });
19766
+ const loaded = isRemote ? { config: null, errors: [] } : await loadConfigFileDetailed(target, { allowExecutableConfig: false });
19031
19767
  if (loaded.errors.length > 0) {
19032
19768
  send(400, { error: loaded.errors.join("; ") });
19033
19769
  return;
19034
19770
  }
19035
19771
  const runConfig = isRemote ? {
19036
- ...loaded.config ?? {},
19037
19772
  outDir: "snapshot",
19038
19773
  tmpDir: "snapshot.tmp",
19039
19774
  hooks: {}
@@ -19044,13 +19779,39 @@ async function startWebServer(options) {
19044
19779
  send(403, { error: "the configured outDir resolves outside the served directory" });
19045
19780
  return;
19046
19781
  }
19782
+ const configuredTmpDir = typeof runConfig.tmpDir === "string" && runConfig.tmpDir.trim() !== "" ? runConfig.tmpDir : "snapshot.tmp";
19783
+ const stagingDir = path27__namespace.resolve(target, configuredTmpDir);
19784
+ if (!insideAllowedRootsForWrite(stagingDir)) {
19785
+ send(403, { error: "the configured tmpDir resolves outside the served directory" });
19786
+ return;
19787
+ }
19047
19788
  const started = Date.now();
19048
19789
  try {
19049
- const manifest = generateSnapshot({ ...runConfig, cwd: target }, {
19050
- ...provenance === void 0 ? {} : { source: provenance },
19051
- ...mode === "slice" ? { slice: { question } } : {},
19052
- ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
19053
- });
19790
+ const generated = await generateInWorker(
19791
+ target,
19792
+ { cwd: target },
19793
+ {
19794
+ config: runConfig,
19795
+ ...provenance === void 0 ? {} : { source: provenance },
19796
+ ...mode === "slice" && question.length >= 3 ? { narrow: { slice: { question } } } : {},
19797
+ ...mode === "budget" && budgetTokens !== void 0 ? { narrow: { budgetTokens } } : {}
19798
+ }
19799
+ );
19800
+ if (!generated.ok) {
19801
+ send(500, { error: generated.message });
19802
+ return;
19803
+ }
19804
+ const manifestRead = readConfinedText(snapshotDir, "manifest.json");
19805
+ if (!manifestRead.ok) {
19806
+ send(500, { error: "the generate worker did not write manifest.json" });
19807
+ return;
19808
+ }
19809
+ const manifest = JSON.parse(manifestRead.text);
19810
+ const shape = describeManifestShapeProblem(manifest);
19811
+ if (shape !== null) {
19812
+ send(500, { error: "the generated manifest is not a snapshot manifest: " + shape });
19813
+ return;
19814
+ }
19054
19815
  const seconds = ((Date.now() - started) / 1e3).toFixed(2);
19055
19816
  const health = auditSnapshot({ snapshotDir, repoDir: target });
19056
19817
  send(200, {
@@ -19073,7 +19834,13 @@ async function startWebServer(options) {
19073
19834
  } catch (error) {
19074
19835
  send(500, { error: error.message });
19075
19836
  }
19076
- })();
19837
+ })().catch((error) => {
19838
+ log("serve: " + error.message);
19839
+ try {
19840
+ send(500, { error: "internal error" });
19841
+ } catch {
19842
+ }
19843
+ });
19077
19844
  });
19078
19845
  return;
19079
19846
  }
@@ -19083,15 +19850,24 @@ async function startWebServer(options) {
19083
19850
  send(403, { error: "outside the served directory: " + target });
19084
19851
  return;
19085
19852
  }
19086
- if (!fs24__namespace.existsSync(path27__namespace.join(target, "manifest.json"))) {
19087
- send(404, { error: "no manifest.json under " + target });
19853
+ if (!fs24__namespace.existsSync(target)) {
19854
+ send(404, { error: "no snapshot directory at " + target });
19088
19855
  return;
19089
19856
  }
19090
19857
  if (!insideAllowedRoots(target)) {
19091
19858
  send(403, { error: "outside the served directory: " + target });
19092
19859
  return;
19093
19860
  }
19094
- const report2 = auditSnapshot({ snapshotDir: target, repoDir: path27__namespace.dirname(target) });
19861
+ const repoDir = path27__namespace.dirname(target);
19862
+ if (!insideAllowedRoots(repoDir)) {
19863
+ send(403, { error: "the repository root for this snapshot is outside the served directory" });
19864
+ return;
19865
+ }
19866
+ if (!fs24__namespace.existsSync(path27__namespace.join(target, "manifest.json"))) {
19867
+ send(404, { error: "no manifest.json under " + target });
19868
+ return;
19869
+ }
19870
+ const report2 = auditSnapshot({ snapshotDir: target, repoDir });
19095
19871
  send(200, { score: report2.score, counts: report2.counts, checks: report2.checks });
19096
19872
  return;
19097
19873
  }
@@ -19101,7 +19877,7 @@ async function startWebServer(options) {
19101
19877
  send(403, { error: "outside the served directory: " + target });
19102
19878
  return;
19103
19879
  }
19104
- if (!fs24__namespace.existsSync(path27__namespace.join(target, "manifest.json"))) {
19880
+ if (!fs24__namespace.existsSync(target)) {
19105
19881
  send(404, { error: "no manifest.json under " + target });
19106
19882
  return;
19107
19883
  }
@@ -19109,10 +19885,18 @@ async function startWebServer(options) {
19109
19885
  send(403, { error: "outside the served directory: " + target });
19110
19886
  return;
19111
19887
  }
19112
- const manifestFile = path27__namespace.join(target, "manifest.json");
19888
+ const manifestRead = readConfinedText(target, "manifest.json");
19889
+ if (!manifestRead.ok) {
19890
+ if (manifestRead.reason === "outside") {
19891
+ send(403, { error: "manifest.json resolves outside the snapshot directory" });
19892
+ } else {
19893
+ send(404, { error: "no readable manifest.json under " + target });
19894
+ }
19895
+ return;
19896
+ }
19113
19897
  let manifest;
19114
19898
  try {
19115
- manifest = JSON.parse(fs24__namespace.readFileSync(manifestFile, "utf8"));
19899
+ manifest = JSON.parse(manifestRead.text);
19116
19900
  } catch {
19117
19901
  send(404, { error: "no manifest.json under " + target });
19118
19902
  return;
@@ -19122,12 +19906,8 @@ async function startWebServer(options) {
19122
19906
  send(400, { error: "manifest.json is not a snapshot manifest: " + shapeProblem });
19123
19907
  return;
19124
19908
  }
19125
- let prompt = "";
19126
- try {
19127
- prompt = fs24__namespace.readFileSync(path27__namespace.join(target, "PROMPT.md"), "utf8").slice(0, MAX_PREVIEW);
19128
- } catch {
19129
- prompt = "(this snapshot has no PROMPT.md)";
19130
- }
19909
+ const promptRead = readConfinedText(target, "PROMPT.md");
19910
+ const prompt = promptRead.ok ? promptRead.text.slice(0, MAX_PREVIEW) : "(this snapshot has no readable PROMPT.md)";
19131
19911
  send(200, {
19132
19912
  fingerprint: manifest.fingerprint ?? "",
19133
19913
  generatedAt: manifest.generatedAt ?? "",
@@ -19145,7 +19925,7 @@ async function startWebServer(options) {
19145
19925
  send(403, { error: "outside the served directory: " + target });
19146
19926
  return;
19147
19927
  }
19148
- if (!fs24__namespace.existsSync(path27__namespace.join(target, "manifest.json")) && !fs24__namespace.existsSync(path27__namespace.join(target, ".codebase-snapshot"))) {
19928
+ if (!fs24__namespace.existsSync(target)) {
19149
19929
  send(404, { error: "not a snapshot directory: " + target });
19150
19930
  return;
19151
19931
  }
@@ -19153,6 +19933,10 @@ async function startWebServer(options) {
19153
19933
  send(403, { error: "outside the served directory: " + target });
19154
19934
  return;
19155
19935
  }
19936
+ if (!fs24__namespace.existsSync(path27__namespace.join(target, "manifest.json")) && !fs24__namespace.existsSync(path27__namespace.join(target, ".codebase-snapshot"))) {
19937
+ send(404, { error: "not a snapshot directory: " + target });
19938
+ return;
19939
+ }
19156
19940
  try {
19157
19941
  const zip = writeZip({ directory: target });
19158
19942
  response.writeHead(200, {
@@ -19169,11 +19953,11 @@ async function startWebServer(options) {
19169
19953
  }
19170
19954
  send(404, { error: "not found" });
19171
19955
  });
19172
- await new Promise((resolve15, reject) => {
19956
+ await new Promise((resolve16, reject) => {
19173
19957
  server.once("error", reject);
19174
19958
  server.listen(port, host, () => {
19175
19959
  server.removeListener("error", reject);
19176
- resolve15();
19960
+ resolve16();
19177
19961
  });
19178
19962
  });
19179
19963
  const address = server.address();
@@ -19185,14 +19969,14 @@ async function startWebServer(options) {
19185
19969
  port: actualPort,
19186
19970
  host,
19187
19971
  token,
19188
- close: () => new Promise((resolve15) => {
19972
+ close: () => new Promise((resolve16) => {
19189
19973
  for (const directory of temporaryClones) {
19190
19974
  try {
19191
19975
  fs24__namespace.rmSync(directory, { recursive: true, force: true });
19192
19976
  } catch {
19193
19977
  }
19194
19978
  }
19195
- server.close(() => resolve15());
19979
+ server.close(() => resolve16());
19196
19980
  })
19197
19981
  };
19198
19982
  }
@@ -19308,14 +20092,14 @@ function writeCache(file, entry) {
19308
20092
  }
19309
20093
  }
19310
20094
  function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
19311
- return new Promise((resolve15) => {
20095
+ return new Promise((resolve16) => {
19312
20096
  let settled = false;
19313
20097
  let request = null;
19314
20098
  const finish = (value) => {
19315
20099
  if (settled) return;
19316
20100
  settled = true;
19317
20101
  clearTimeout(deadline);
19318
- resolve15(value);
20102
+ resolve16(value);
19319
20103
  };
19320
20104
  const deadline = setTimeout(() => {
19321
20105
  request?.destroy();
@@ -19430,7 +20214,7 @@ if [ ! -f "$SNAPSHOT_DIR/manifest.json" ]; then
19430
20214
  exit 1
19431
20215
  fi
19432
20216
 
19433
- if ! npx --no-install ${GENERATOR_NAME} validate >/dev/null 2>&1; then
20217
+ if ! npx --no-install ${GENERATOR_NAME} validate --out-dir "$SNAPSHOT_DIR" >/dev/null 2>&1; then
19434
20218
  echo "${GENERATOR_NAME}: the snapshot is out of date." >&2
19435
20219
  echo " Run \\"npx ${GENERATOR_NAME} generate\\", stage the change, and commit again." >&2
19436
20220
  echo " (npx --no-install is used on purpose: this hook must not install anything)" >&2
@@ -19454,16 +20238,36 @@ function gitDirectory(cwd) {
19454
20238
  if (!match) return null;
19455
20239
  const target = match[1];
19456
20240
  const resolved = path27__namespace.isAbsolute(target.trim()) ? target.trim() : path27__namespace.join(cwd, target.trim());
19457
- if (!fs24__namespace.statSync(resolved).isDirectory()) return null;
19458
- if (isInside3(path27__namespace.resolve(cwd), path27__namespace.resolve(resolved))) return resolved;
19459
- return isRegisteredWorktree(path27__namespace.resolve(resolved), cwd) ? resolved : null;
20241
+ const cwdReal = canonicalForWrite(cwd);
20242
+ const resolvedReal = canonicalForWrite(resolved);
20243
+ if (cwdReal === null || resolvedReal === null || !fs24__namespace.statSync(resolvedReal).isDirectory()) {
20244
+ return null;
20245
+ }
20246
+ if (isInside4(cwdReal, resolvedReal)) return resolvedReal;
20247
+ return isRegisteredWorktree(path27__namespace.resolve(resolved), cwd) ? resolvedReal : null;
19460
20248
  } catch {
19461
20249
  return null;
19462
20250
  }
19463
20251
  }
19464
- function isInside3(parent, child) {
19465
- const relative16 = path27__namespace.relative(parent, child);
19466
- return relative16 === "" || !relative16.startsWith("..") && !path27__namespace.isAbsolute(relative16);
20252
+ function isInside4(parent, child) {
20253
+ const relative17 = path27__namespace.relative(parent, child);
20254
+ return relative17 === "" || !relative17.startsWith("..") && !path27__namespace.isAbsolute(relative17);
20255
+ }
20256
+ function canonicalForWrite(target) {
20257
+ let existing = path27__namespace.resolve(target);
20258
+ const tail = [];
20259
+ while (!fs24__namespace.existsSync(existing)) {
20260
+ tail.unshift(path27__namespace.basename(existing));
20261
+ const parent = path27__namespace.dirname(existing);
20262
+ if (parent === existing) break;
20263
+ existing = parent;
20264
+ }
20265
+ try {
20266
+ const real = fs24__namespace.realpathSync(existing);
20267
+ return tail.length === 0 ? real : path27__namespace.join(real, ...tail);
20268
+ } catch {
20269
+ return null;
20270
+ }
19467
20271
  }
19468
20272
  function isRegisteredWorktree(gitDir, cwd) {
19469
20273
  try {
@@ -19491,9 +20295,16 @@ function configuredHooksDirectory(cwd) {
19491
20295
  if (hooks === null) return null;
19492
20296
  const resolved = path27__namespace.resolve(cwd, hooks);
19493
20297
  const common = gitOutput(cwd, ["rev-parse", "--git-common-dir"]);
19494
- const commonDir = common === null ? null : path27__namespace.resolve(cwd, common);
19495
- if (isInside3(path27__namespace.resolve(cwd), resolved)) return { dir: resolved };
19496
- if (commonDir !== null && isInside3(commonDir, resolved)) return { dir: resolved };
20298
+ const commonDir = common === null ? null : canonicalForWrite(path27__namespace.resolve(cwd, common));
20299
+ const cwdReal = canonicalForWrite(cwd);
20300
+ const hooksReal = canonicalForWrite(resolved);
20301
+ if (hooksReal === null || cwdReal === null) {
20302
+ return {
20303
+ refusal: `The hooks directory git reports (${resolved}) could not be resolved, so no hook was written.`
20304
+ };
20305
+ }
20306
+ if (isInside4(cwdReal, hooksReal)) return { dir: hooksReal };
20307
+ if (commonDir !== null && isInside4(commonDir, hooksReal)) return { dir: hooksReal };
19497
20308
  return {
19498
20309
  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.`
19499
20310
  };
@@ -19513,8 +20324,48 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
19513
20324
  ]
19514
20325
  };
19515
20326
  }
19516
- const hooksDir = configured === null ? path27__namespace.join(gitDir, "hooks") : configured.dir;
20327
+ const hooksDirRaw = configured === null ? path27__namespace.join(gitDir, "hooks") : configured.dir;
20328
+ const hooksDir = canonicalForWrite(hooksDirRaw);
20329
+ if (hooksDir === null) {
20330
+ return {
20331
+ path: null,
20332
+ written: false,
20333
+ notes: [`Refusing to write the hooks directory: ${hooksDirRaw} could not be resolved.`]
20334
+ };
20335
+ }
19517
20336
  const hookPath = path27__namespace.join(hooksDir, "pre-commit");
20337
+ try {
20338
+ const existingStats = fs24__namespace.lstatSync(hookPath);
20339
+ if (existingStats.isSymbolicLink()) {
20340
+ return {
20341
+ path: hookPath,
20342
+ written: false,
20343
+ notes: [`Refusing to write ${hookPath}: it is a symbolic link.`]
20344
+ };
20345
+ }
20346
+ if (existingStats.isFile() && existingStats.nlink > 1) {
20347
+ return {
20348
+ path: hookPath,
20349
+ written: false,
20350
+ notes: [`Refusing to write ${hookPath}: it has ${existingStats.nlink} hard links.`]
20351
+ };
20352
+ }
20353
+ if (!existingStats.isFile()) {
20354
+ return {
20355
+ path: hookPath,
20356
+ written: false,
20357
+ notes: [`Refusing to write ${hookPath}: it is not a regular file.`]
20358
+ };
20359
+ }
20360
+ } catch (error) {
20361
+ if (error.code !== "ENOENT") {
20362
+ return {
20363
+ path: hookPath,
20364
+ written: false,
20365
+ notes: [`Refusing to write ${hookPath}: ${error.message}`]
20366
+ };
20367
+ }
20368
+ }
19518
20369
  try {
19519
20370
  fs24__namespace.mkdirSync(hooksDir, { recursive: true });
19520
20371
  } catch (err) {
@@ -19564,23 +20415,23 @@ var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
19564
20415
  var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
19565
20416
  var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
19566
20417
  var fileDerivationBytes = 0;
19567
- function takeDerivation(path28, hash, settings) {
19568
- const cached = FILE_DERIVATIONS.get(path28);
20418
+ function takeDerivation(path28, relativePath, hash, settings) {
20419
+ const key = path28 + "\0" + relativePath;
20420
+ const cached = FILE_DERIVATIONS.get(key);
19569
20421
  if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
19570
- FILE_DERIVATIONS.delete(path28);
19571
- FILE_DERIVATIONS.set(path28, cached);
20422
+ FILE_DERIVATIONS.delete(key);
20423
+ FILE_DERIVATIONS.set(key, cached);
19572
20424
  return cached;
19573
20425
  }
19574
- function rememberDerivation(path28, hash, settings, derivation) {
20426
+ function rememberDerivation(path28, relativePath, hash, settings, derivation) {
20427
+ const key = path28 + "\0" + relativePath;
19575
20428
  const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
19576
20429
  const bytes = bodyBytes * 2 + 512;
19577
20430
  if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
19578
- const previous = FILE_DERIVATIONS.get(path28);
20431
+ const previous = FILE_DERIVATIONS.get(key);
19579
20432
  if (previous !== void 0) {
19580
- FILE_DERIVATIONS.delete(path28);
20433
+ FILE_DERIVATIONS.delete(key);
19581
20434
  fileDerivationBytes -= previous.bytes;
19582
- } else {
19583
- FILE_DERIVATIONS.delete(path28);
19584
20435
  }
19585
20436
  while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
19586
20437
  const oldest = FILE_DERIVATIONS.keys().next();
@@ -19589,7 +20440,7 @@ function rememberDerivation(path28, hash, settings, derivation) {
19589
20440
  FILE_DERIVATIONS.delete(oldest.value);
19590
20441
  if (evicted !== void 0) fileDerivationBytes -= evicted.bytes;
19591
20442
  }
19592
- FILE_DERIVATIONS.set(path28, { ...derivation, hash, settings, bytes });
20443
+ FILE_DERIVATIONS.set(key, { ...derivation, hash, settings, bytes });
19593
20444
  fileDerivationBytes += bytes;
19594
20445
  }
19595
20446
  function derivationSettings(config) {
@@ -19845,6 +20696,11 @@ function verifyInMemory(files, parts, unaccounted) {
19845
20696
  }
19846
20697
  }
19847
20698
  for (const part of parts) {
20699
+ if (part.metadata.hardClipped === true) {
20700
+ errors.push(
20701
+ `${part.filename} was hard-clipped by the part budget; its manifest entries cannot describe the surviving sections. Increase the budget or split the file instead of shipping a lie.`
20702
+ );
20703
+ }
19848
20704
  if (sha256Hex2(part.markdown) !== part.metadata.sha256) {
19849
20705
  errors.push(`${part.filename} content does not match its recorded sha256.`);
19850
20706
  }
@@ -19873,7 +20729,12 @@ function resolveSafeOutputDirs(config) {
19873
20729
  const outDir = path27__namespace.resolve(cwd, config.outDir);
19874
20730
  const tmpDir = path27__namespace.resolve(cwd, config.tmpDir);
19875
20731
  const root = path27__namespace.parse(cwd).root;
19876
- const contains = (parent, child) => child === parent || child.startsWith(`${parent}${path27__namespace.sep}`);
20732
+ const fold = (value) => process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
20733
+ const contains = (parent, child) => {
20734
+ const foldedParent = fold(parent);
20735
+ const foldedChild = fold(child);
20736
+ return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path27__namespace.sep}`);
20737
+ };
19877
20738
  const reject = (reason) => {
19878
20739
  throw new Error(
19879
20740
  `Refusing to generate: ${reason}. outDir=${outDir} tmpDir=${tmpDir} cwd=${cwd}`
@@ -19915,7 +20776,7 @@ function maskPathText(value, secretRules) {
19915
20776
  }
19916
20777
  function maskOwnerBrief(brief, secretRules) {
19917
20778
  if (brief === void 0) return void 0;
19918
- const mask = (value) => scanAndRedactSecrets(value, secretRules ?? [], "owner-brief").redacted;
20779
+ const mask = (value) => maskProse(value, secretRules, "owner-brief");
19919
20780
  return {
19920
20781
  ...brief,
19921
20782
  path: mask(brief.path),
@@ -19925,11 +20786,17 @@ function maskOwnerBrief(brief, secretRules) {
19925
20786
  ...brief.bar === void 0 ? {} : { bar: mask(brief.bar) },
19926
20787
  ...brief.calibration === void 0 ? {} : { calibration: mask(brief.calibration) },
19927
20788
  ...brief.preamble === void 0 ? {} : { preamble: mask(brief.preamble) },
19928
- notes: brief.notes.map((note) => ({ heading: note.heading, body: mask(note.body) }))
20789
+ // The heading is prose too. Masking only the body left `## Incident ghp_…` in PROMPT.md:
20790
+ // ownerNotesSection reproduced the heading as a Markdown title, where no line rule that
20791
+ // expects `key: value` can see it.
20792
+ notes: brief.notes.map((note) => ({ heading: mask(note.heading), body: mask(note.body) }))
19929
20793
  };
19930
20794
  }
20795
+ function maskProse(value, secretRules, scope) {
20796
+ return scanAndRedactSecrets(value, secretRules ?? [], scope).redacted;
20797
+ }
19931
20798
  function maskOverview(overview, secretRules) {
19932
- const mask = (value) => maskPathText(value, secretRules);
20799
+ const mask = (value) => maskProse(value, secretRules, "overview");
19933
20800
  return {
19934
20801
  ...overview.description === void 0 ? {} : { description: mask(overview.description) },
19935
20802
  ...overview.summary === void 0 ? {} : { summary: mask(overview.summary) },
@@ -19961,9 +20828,9 @@ function listEntries(dir) {
19961
20828
  return;
19962
20829
  }
19963
20830
  for (const child of children) {
19964
- const relative16 = prefix === "" ? child.name : `${prefix}/${child.name}`;
19965
- entries.push(relative16);
19966
- if (child.isDirectory()) walk2(path27__namespace.join(absolute, child.name), relative16);
20831
+ const relative17 = prefix === "" ? child.name : `${prefix}/${child.name}`;
20832
+ entries.push(relative17);
20833
+ if (child.isDirectory()) walk2(path27__namespace.join(absolute, child.name), relative17);
19967
20834
  }
19968
20835
  };
19969
20836
  walk2(dir, "");
@@ -20418,6 +21285,7 @@ function ensureParentDirectory(target, label) {
20418
21285
  }
20419
21286
  var LOCK_HEARTBEAT_MS = 5e3;
20420
21287
  var LOCK_STALE_HEARTBEAT_MS = 12e4;
21288
+ var LOCK_EMPTY_GRACE_MS = 5e3;
20421
21289
  var LOCK_HEARTBEAT_SOURCE = `
20422
21290
  const { parentPort, workerData } = require("node:worker_threads");
20423
21291
  const fs = require("node:fs");
@@ -20559,9 +21427,11 @@ function lockOwnerIsGone(lockPath) {
20559
21427
  try {
20560
21428
  pid = JSON.parse(raw).pid;
20561
21429
  } catch {
20562
- return lockFileIsAncient(lockPath);
21430
+ return lockFileIsAncient(lockPath, LOCK_EMPTY_GRACE_MS);
21431
+ }
21432
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) {
21433
+ return lockFileIsAncient(lockPath, LOCK_EMPTY_GRACE_MS);
20563
21434
  }
20564
- if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return lockFileIsAncient(lockPath);
20565
21435
  try {
20566
21436
  process.kill(pid, 0);
20567
21437
  return lockFileIsAncient(lockPath);
@@ -20588,8 +21458,8 @@ function reclaimStaleLock(lockPath) {
20588
21458
  return false;
20589
21459
  }
20590
21460
  }
20591
- function lockFileIsAncient(lockPath) {
20592
- return lockHeartbeatAgeMs(lockPath) > LOCK_STALE_HEARTBEAT_MS;
21461
+ function lockFileIsAncient(lockPath, thresholdMs = LOCK_STALE_HEARTBEAT_MS) {
21462
+ return lockHeartbeatAgeMs(lockPath) > thresholdMs;
20593
21463
  }
20594
21464
  function writeManifestAtomically(manifestPath, manifest) {
20595
21465
  const tempPath = `${manifestPath}.${process.pid}.tmp`;
@@ -20604,13 +21474,13 @@ function writeManifestAtomically(manifestPath, manifest) {
20604
21474
  throw err;
20605
21475
  }
20606
21476
  }
20607
- function swapIntoPlace(stagingDir, outDir, beforeSwap) {
21477
+ function swapIntoPlace(stagingDir, outDir, beforeSwap, onStagingPreserved) {
20608
21478
  ensureParentDirectory(outDir, "outDir");
20609
21479
  const deadline = Date.now() + 3e3;
20610
21480
  let delay = 25;
20611
21481
  for (; ; ) {
20612
21482
  try {
20613
- swapOnce(stagingDir, outDir, beforeSwap);
21483
+ swapOnce(stagingDir, outDir, beforeSwap, onStagingPreserved);
20614
21484
  return;
20615
21485
  } catch (err) {
20616
21486
  const code = err.code;
@@ -20645,7 +21515,7 @@ function recoverInterruptedPublish(outDir) {
20645
21515
  } catch {
20646
21516
  }
20647
21517
  }
20648
- function swapOnce(stagingDir, outDir, beforeSwap) {
21518
+ function swapOnce(stagingDir, outDir, beforeSwap, onStagingPreserved) {
20649
21519
  const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
20650
21520
  const hadPrevious = fs24__namespace.existsSync(outDir);
20651
21521
  if (hadPrevious) beforeSwap?.();
@@ -20656,6 +21526,7 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
20656
21526
  movedAside = true;
20657
21527
  } catch (err) {
20658
21528
  if (!isLockError(err)) throw err;
21529
+ onStagingPreserved?.();
20659
21530
  fs24__namespace.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
20660
21531
  process.stderr.write(
20661
21532
  `\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.
@@ -20686,6 +21557,7 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
20686
21557
  if (fs24__namespace.existsSync(outDir)) fs24__namespace.rmSync(outDir, { recursive: true, force: true });
20687
21558
  fs24__namespace.renameSync(backupDir, outDir);
20688
21559
  } else if (hadPrevious && !movedAside) {
21560
+ onStagingPreserved?.();
20689
21561
  process.stderr.write(
20690
21562
  `\u26A0 The previous snapshot at ${outDir} was removed and the new one could not be moved into place. It is complete at ${stagingDir}.
20691
21563
  `
@@ -20875,7 +21747,7 @@ function generateSnapshot(configInput, options) {
20875
21747
  // output — but only at these exact paths, not at every directory that shares the name.
20876
21748
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
20877
21749
  (directory) => path27__namespace.relative(config.cwd, path27__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
20878
- ).filter((relative16) => relative16.length > 0 && !relative16.startsWith("..")),
21750
+ ).filter((relative17) => relative17.length > 0 && !relative17.startsWith("..")),
20879
21751
  // A staged path can be absent from the working tree while its index blob exists. Discovery
20880
21752
  // lists the working tree, so those paths would never reach the scan at all.
20881
21753
  ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
@@ -21021,9 +21893,9 @@ function generateSnapshot(configInput, options) {
21021
21893
  const language = detectLanguage(relativePath);
21022
21894
  bump(layerCounts, layer2);
21023
21895
  bump(kindCounts, kind);
21024
- const derivation = takeDerivation(absolutePath, hashSha256, derivationKey) ?? (() => {
21896
+ const derivation = takeDerivation(absolutePath, relativePath, hashSha256, derivationKey) ?? (() => {
21025
21897
  const fresh = deriveFile(relativePath, rawContent, sizeBytes, config);
21026
- rememberDerivation(absolutePath, hashSha256, derivationKey, fresh);
21898
+ rememberDerivation(absolutePath, relativePath, hashSha256, derivationKey, fresh);
21027
21899
  return fresh;
21028
21900
  })();
21029
21901
  const { lineCount } = derivation;
@@ -21203,7 +22075,9 @@ function generateSnapshot(configInput, options) {
21203
22075
  const tokens = Math.max(1, Math.ceil(file.includedBytes / 4));
21204
22076
  const value = (entry(file.relativePath) ? 100 : 0) + layerWeight(file.layer) + Math.min(60, (importers.get(file.relativePath) ?? 0) * 6) - Math.min(40, tokens / 250);
21205
22077
  return { file, tokens, value };
21206
- }).sort((left, right) => right.value - left.value || left.tokens - right.tokens || left.file.relativePath.localeCompare(right.file.relativePath));
22078
+ }).sort(
22079
+ (left, right) => right.value - left.value || left.tokens - right.tokens || (left.file.relativePath < right.file.relativePath ? -1 : left.file.relativePath > right.file.relativePath ? 1 : 0)
22080
+ );
21207
22081
  const keep = /* @__PURE__ */ new Set();
21208
22082
  let used = 0;
21209
22083
  const selected = [];
@@ -21565,7 +22439,7 @@ function generateSnapshot(configInput, options) {
21565
22439
  const reportExcludes = [...config.excludePatterns, ...config.presetExclude];
21566
22440
  const diffReport = artifacts.diff ? generateDiffReport(config.cwd, {
21567
22441
  secretRules: config.secretRules,
21568
- excluded: (relativePath) => reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
22442
+ excluded: (relativePath) => isSensitivePath(relativePath) || defaultIgnoreReason(relativePath) !== null || config.include.length > 0 && !config.include.some((pattern) => matchesExclude(relativePath, pattern)) || reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
21569
22443
  }) : null;
21570
22444
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
21571
22445
  const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount, secretRules: config.secretRules }) : null;
@@ -21591,8 +22465,8 @@ function generateSnapshot(configInput, options) {
21591
22465
  task: config.promptTask,
21592
22466
  brief: maskOwnerBrief(config.brief, config.secretRules),
21593
22467
  history: recentCommits(config.cwd).map((commit) => ({
21594
- subject: maskPathText(commit.subject, config.secretRules),
21595
- body: maskPathText(commit.body, config.secretRules)
22468
+ subject: maskProse(commit.subject, config.secretRules, "git-log"),
22469
+ body: maskProse(commit.body, config.secretRules, "git-log")
21596
22470
  })),
21597
22471
  overview: maskOverview(readProjectOverview(config.cwd), config.secretRules)
21598
22472
  }) : null;
@@ -21612,8 +22486,11 @@ function generateSnapshot(configInput, options) {
21612
22486
  const entry = {
21613
22487
  ...file,
21614
22488
  content,
21615
- inclusionMode: file.inclusionMode === "comments-stripped" ? "comments-stripped" : "full",
21616
- ...file.emptyLinesRemoved === true ? { emptyLinesRemoved: true } : {},
22489
+ // `fullContents` is the pre-preview body but still carries comments and blank lines: the
22490
+ // monolith is the whole source, not the comments-stripped variant. Calling it
22491
+ // `comments-stripped` (or copying `emptyLinesRemoved`) described a transformation this
22492
+ // artifact did not perform.
22493
+ inclusionMode: "full",
21617
22494
  isPreviewTruncated: false,
21618
22495
  includedBytes: Buffer.byteLength(content, "utf8"),
21619
22496
  includedLines: countLines(content)
@@ -21692,6 +22569,7 @@ function generateSnapshot(configInput, options) {
21692
22569
  recoverInterruptedPublish(outDir);
21693
22570
  assertReplaceable(outDir, "outDir", config.secretRules);
21694
22571
  let stagingDir = null;
22572
+ let stagingPreserved = false;
21695
22573
  let releaseDeferred = false;
21696
22574
  try {
21697
22575
  ensureParentDirectory(outDir, "outDir");
@@ -21718,21 +22596,25 @@ function generateSnapshot(configInput, options) {
21718
22596
  fs24__namespace.mkdirSync(reportsDir, { recursive: true });
21719
22597
  }
21720
22598
  const writtenArtifacts = /* @__PURE__ */ new Map();
22599
+ const ledgerRoot = (targetDir) => stagingDir !== null && (targetDir === stagingDir || targetDir.startsWith(stagingDir + path27__namespace.sep)) ? stagingDir : outDir;
22600
+ const ledgerEntry = (targetDir, relativeEntry) => path27__namespace.relative(ledgerRoot(targetDir), path27__namespace.join(targetDir, ...relativeEntry.split("/"))).split(path27__namespace.sep).join("/");
21721
22601
  const writeArtifact = (targetDir, relativeEntry, data) => {
21722
22602
  const full = path27__namespace.join(targetDir, ...relativeEntry.split("/"));
21723
22603
  fs24__namespace.writeFileSync(full, data, "utf8");
21724
22604
  const stats = fs24__namespace.statSync(full);
21725
- writtenArtifacts.set(relativeEntry, {
21726
- digest: { path: relativeEntry, bytes: stats.size, sha256: sha256Hex2(data) },
22605
+ const entry = ledgerEntry(targetDir, relativeEntry);
22606
+ writtenArtifacts.set(entry, {
22607
+ digest: { path: entry, bytes: stats.size, sha256: sha256Hex2(data) },
21727
22608
  mtimeMs: stats.mtimeMs
21728
22609
  });
21729
22610
  };
21730
22611
  const recordArtifact = (targetDir, relativeEntry) => {
21731
22612
  const full = path27__namespace.join(targetDir, ...relativeEntry.split("/"));
21732
22613
  const stats = fs24__namespace.statSync(full);
21733
- writtenArtifacts.set(relativeEntry, {
22614
+ const entry = ledgerEntry(targetDir, relativeEntry);
22615
+ writtenArtifacts.set(entry, {
21734
22616
  digest: {
21735
- path: relativeEntry,
22617
+ path: entry,
21736
22618
  bytes: stats.size,
21737
22619
  sha256: sha256Hex2(fs24__namespace.readFileSync(full))
21738
22620
  },
@@ -21801,7 +22683,14 @@ function generateSnapshot(configInput, options) {
21801
22683
  stagingDir,
21802
22684
  markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21803
22685
  );
21804
- swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
22686
+ swapIntoPlace(
22687
+ stagingDir,
22688
+ outDir,
22689
+ () => assertReplaceable(outDir, "outDir", config.secretRules),
22690
+ () => {
22691
+ stagingPreserved = true;
22692
+ }
22693
+ );
21805
22694
  stagingDir = null;
21806
22695
  const warningsBeforeHook = manifest.warnings.length;
21807
22696
  const pendingHook = runAfterGenerate(config, manifest);
@@ -21855,7 +22744,7 @@ function generateSnapshot(configInput, options) {
21855
22744
  }
21856
22745
  return manifest;
21857
22746
  } catch (err) {
21858
- if (stagingDir !== null) {
22747
+ if (stagingDir !== null && !stagingPreserved) {
21859
22748
  try {
21860
22749
  fs24__namespace.rmSync(stagingDir, { recursive: true, force: true });
21861
22750
  } catch {
@@ -21960,6 +22849,10 @@ var DEFAULT_PORT2 = 4789;
21960
22849
  var DEFAULT_MAX_BODY = 2 * 1024 * 1024;
21961
22850
  var RATE_LIMIT = 60;
21962
22851
  var RATE_WINDOW_MS = 1e4;
22852
+ var MAX_IN_FLIGHT = 4;
22853
+ var MAX_SESSION_ENTRIES = 64;
22854
+ var MAX_SSE_SESSIONS = 64;
22855
+ var MAX_RATE_WINDOWS = 1024;
21963
22856
  function generateToken() {
21964
22857
  return crypto__namespace.randomBytes(24).toString("base64url");
21965
22858
  }
@@ -21995,6 +22888,10 @@ async function startHttpTransport(options) {
21995
22888
  const toolCount = buildTools().length;
21996
22889
  const mcpSessions = /* @__PURE__ */ new Map();
21997
22890
  const socketServers = /* @__PURE__ */ new WeakMap();
22891
+ const rememberSession = (id, server) => {
22892
+ if (!mcpSessions.has(id) && mcpSessions.size >= MAX_SESSION_ENTRIES) return;
22893
+ mcpSessions.set(id, server);
22894
+ };
21998
22895
  const anonymousServers = /* @__PURE__ */ new Map();
21999
22896
  const serverFor = (request) => {
22000
22897
  const header = request.headers["mcp-session-id"];
@@ -22003,11 +22900,7 @@ async function startHttpTransport(options) {
22003
22900
  let existing = mcpSessions.get(supplied);
22004
22901
  if (existing === void 0) {
22005
22902
  existing = createMcp();
22006
- if (mcpSessions.size >= 64) {
22007
- const oldest = mcpSessions.keys().next().value;
22008
- if (oldest !== void 0) mcpSessions.delete(oldest);
22009
- }
22010
- mcpSessions.set(supplied, existing);
22903
+ rememberSession(supplied, existing);
22011
22904
  }
22012
22905
  return existing;
22013
22906
  }
@@ -22038,6 +22931,35 @@ async function startHttpTransport(options) {
22038
22931
  return fromQuery !== null && timingSafeEqual3(fromQuery, token);
22039
22932
  };
22040
22933
  const sessions = /* @__PURE__ */ new Map();
22934
+ let inFlight = 0;
22935
+ const acquireToolSlot = () => {
22936
+ if (inFlight >= MAX_IN_FLIGHT) return false;
22937
+ inFlight += 1;
22938
+ return true;
22939
+ };
22940
+ const releaseToolSlot = () => {
22941
+ if (inFlight > 0) inFlight -= 1;
22942
+ };
22943
+ const busyResponse = (id) => ({
22944
+ jsonrpc: "2.0",
22945
+ id: typeof id === "string" || typeof id === "number" || id === null ? id : null,
22946
+ error: {
22947
+ code: -32001,
22948
+ message: "server busy: too many tool calls are already in flight"
22949
+ }
22950
+ });
22951
+ const isToolCall = (message) => message !== null && typeof message === "object" && message.method === "tools/call";
22952
+ const rememberRateWindow = (remote, now) => {
22953
+ if (!sessions.has(remote) && sessions.size >= MAX_RATE_WINDOWS) {
22954
+ for (const [key, value] of sessions) if (value.resetAt <= now) sessions.delete(key);
22955
+ while (sessions.size >= MAX_RATE_WINDOWS) {
22956
+ const oldest = sessions.keys().next().value;
22957
+ if (oldest === void 0) break;
22958
+ sessions.delete(oldest);
22959
+ }
22960
+ }
22961
+ sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
22962
+ };
22041
22963
  const metrics = {
22042
22964
  requests: 0,
22043
22965
  byMethod: /* @__PURE__ */ new Map(),
@@ -22053,7 +22975,7 @@ async function startHttpTransport(options) {
22053
22975
  const now = Date.now();
22054
22976
  const window = sessions.get(remote);
22055
22977
  if (window === void 0 || window.resetAt <= now) {
22056
- sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
22978
+ rememberRateWindow(remote, now);
22057
22979
  return false;
22058
22980
  }
22059
22981
  if (window.count >= RATE_LIMIT) return true;
@@ -22114,6 +23036,10 @@ async function startHttpTransport(options) {
22114
23036
  return;
22115
23037
  }
22116
23038
  if (request.method === "GET" && request.url === "/metrics") {
23039
+ if (token !== null && host !== "127.0.0.1" && host !== "localhost" && host !== "::1" && !tokenAccepted(request, new URL(request.url, "http://localhost"))) {
23040
+ send(401, { error: "unauthorized" }, { "www-authenticate": 'Bearer realm="codebase-snapshot"' });
23041
+ return;
23042
+ }
22117
23043
  const lines = [
22118
23044
  "# HELP snapshot_uptime_seconds Seconds since the process started.",
22119
23045
  "# TYPE snapshot_uptime_seconds gauge",
@@ -22151,6 +23077,10 @@ async function startHttpTransport(options) {
22151
23077
  send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
22152
23078
  return;
22153
23079
  }
23080
+ if (sseSessions.size >= MAX_SSE_SESSIONS) {
23081
+ send(503, { error: "too many open SSE sessions" }, { ...cors, "retry-after": "10" });
23082
+ return;
23083
+ }
22154
23084
  const id = crypto__namespace.randomBytes(12).toString("hex");
22155
23085
  response.writeHead(200, {
22156
23086
  ...cors,
@@ -22160,9 +23090,21 @@ async function startHttpTransport(options) {
22160
23090
  "x-accel-buffering": "no"
22161
23091
  });
22162
23092
  const write = (payload) => {
22163
- response.write(payload);
23093
+ try {
23094
+ response.write(payload);
23095
+ } catch {
23096
+ }
22164
23097
  };
22165
- sseSessions.set(id, { write, end: () => response.end(), server: createMcp() });
23098
+ sseSessions.set(id, {
23099
+ write,
23100
+ end: () => {
23101
+ try {
23102
+ response.end();
23103
+ } catch {
23104
+ }
23105
+ },
23106
+ server: createMcp()
23107
+ });
22166
23108
  const heartbeat = setInterval(() => write(": ping\n\n"), 15e3);
22167
23109
  const cleanup = () => {
22168
23110
  clearInterval(heartbeat);
@@ -22213,10 +23155,27 @@ async function startHttpTransport(options) {
22213
23155
  send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: String(error) } });
22214
23156
  return;
22215
23157
  }
22216
- const answer = await stream.server.handle(message);
22217
- if (answer !== null) stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
23158
+ const gated = isToolCall(message);
23159
+ if (gated && !acquireToolSlot()) {
23160
+ const answer = busyResponse(message.id);
23161
+ stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
23162
+ send(202, "", cors);
23163
+ return;
23164
+ }
23165
+ try {
23166
+ const answer = await stream.server.handle(message);
23167
+ if (answer !== null) stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
23168
+ } finally {
23169
+ if (gated) releaseToolSlot();
23170
+ }
22218
23171
  send(202, "", cors);
22219
- })();
23172
+ })().catch((error) => {
23173
+ log("mcp/http: " + error.message);
23174
+ try {
23175
+ send(500, { jsonrpc: "2.0", id: null, error: { code: -32603, message: "Internal error" } }, cors);
23176
+ } catch {
23177
+ }
23178
+ });
22220
23179
  });
22221
23180
  return;
22222
23181
  }
@@ -22279,13 +23238,22 @@ async function startHttpTransport(options) {
22279
23238
  }
22280
23239
  if (sessionId === "" && !Array.isArray(message) && message.method === "initialize") {
22281
23240
  sessionId = newSessionId();
22282
- mcpSessions.set(sessionId, activeServer);
23241
+ rememberSession(sessionId, activeServer);
22283
23242
  }
22284
23243
  const sessionHeaders = sessionId === "" ? cors : { ...cors, "mcp-session-id": sessionId };
22285
23244
  const answers = [];
22286
23245
  for (const item of batch) {
22287
- const answer = await activeServer.handle(item);
22288
- if (answer !== null) answers.push(answer);
23246
+ const gated = isToolCall(item);
23247
+ if (gated && !acquireToolSlot()) {
23248
+ answers.push(busyResponse(item.id));
23249
+ continue;
23250
+ }
23251
+ try {
23252
+ const answer = await activeServer.handle(item);
23253
+ if (answer !== null) answers.push(answer);
23254
+ } finally {
23255
+ if (gated) releaseToolSlot();
23256
+ }
22289
23257
  }
22290
23258
  if (answers.length === 0) {
22291
23259
  send(202, "", sessionHeaders);
@@ -22304,11 +23272,11 @@ async function startHttpTransport(options) {
22304
23272
  }
22305
23273
  });
22306
23274
  });
22307
- await new Promise((resolve15, reject) => {
23275
+ await new Promise((resolve16, reject) => {
22308
23276
  httpServer.once("error", reject);
22309
23277
  httpServer.listen(port, host, () => {
22310
23278
  httpServer.removeListener("error", reject);
22311
- resolve15();
23279
+ resolve16();
22312
23280
  });
22313
23281
  });
22314
23282
  const address = httpServer.address();
@@ -22319,7 +23287,7 @@ async function startHttpTransport(options) {
22319
23287
  port: actualPort,
22320
23288
  host,
22321
23289
  token,
22322
- close: () => new Promise((resolve15) => {
23290
+ close: () => new Promise((resolve16) => {
22323
23291
  for (const [, session] of sseSessions) {
22324
23292
  try {
22325
23293
  session.end();
@@ -22327,7 +23295,7 @@ async function startHttpTransport(options) {
22327
23295
  }
22328
23296
  }
22329
23297
  sseSessions.clear();
22330
- httpServer.close(() => resolve15());
23298
+ httpServer.close(() => resolve16());
22331
23299
  httpServer.closeAllConnections();
22332
23300
  })
22333
23301
  };
@@ -22581,6 +23549,13 @@ function parseByteOption(raw, optionName, minimum, unit = "byte count") {
22581
23549
  }
22582
23550
  return value;
22583
23551
  }
23552
+ function parsePort(raw) {
23553
+ const value = parsePositiveInteger(raw, "port", 0);
23554
+ if (value !== void 0 && value > 65535) {
23555
+ throw new UsageError(`--port must be at most 65535, received "${raw}".`);
23556
+ }
23557
+ return value;
23558
+ }
22584
23559
  function parseCountOption(raw, optionName, minimum = 0) {
22585
23560
  if (raw === void 0) return void 0;
22586
23561
  const trimmed = raw.trim();
@@ -22869,7 +23844,7 @@ function parseCliArgs(argv) {
22869
23844
  sarif: values.sarif === true ? true : void 0,
22870
23845
  strict: values.strict === true ? true : void 0,
22871
23846
  http: values.http === true ? true : void 0,
22872
- port: parsePositiveInteger(values.port, "port", 1),
23847
+ port: parsePort(values.port),
22873
23848
  host: values.host === void 0 ? void 0 : String(values.host),
22874
23849
  token: values.token === void 0 ? void 0 : String(values.token),
22875
23850
  noAuth: values["no-auth"] === true ? true : void 0,
@@ -22933,8 +23908,8 @@ function splitList(value) {
22933
23908
  }
22934
23909
  function displayOutPath(cwd, outDir, ...segments) {
22935
23910
  const absolute = path27__namespace.resolve(cwd, outDir, ...segments);
22936
- const relative16 = path27__namespace.relative(cwd, absolute);
22937
- if (relative16 && !relative16.startsWith("..") && !path27__namespace.isAbsolute(relative16)) return relative16;
23911
+ const relative17 = path27__namespace.relative(cwd, absolute);
23912
+ if (relative17 && !relative17.startsWith("..") && !path27__namespace.isAbsolute(relative17)) return relative17;
22938
23913
  return absolute;
22939
23914
  }
22940
23915
  function nextStepHint(cwd, scriptsAddedNow) {
@@ -23507,6 +24482,8 @@ ${USAGE}
23507
24482
  }
23508
24483
  throw err;
23509
24484
  }
24485
+ const environmentToken = process.env.SNAPSHOT_TOKEN?.trim();
24486
+ const tokenOption = invocation.noAuth === true ? { token: null } : invocation.token !== void 0 ? { token: invocation.token } : environmentToken !== void 0 && environmentToken !== "" ? { token: environmentToken } : {};
23510
24487
  if (invocation.command === "init") {
23511
24488
  return await runInitCommand(invocation);
23512
24489
  }
@@ -23526,8 +24503,7 @@ ${USAGE}
23526
24503
  cwd: path27__namespace.resolve(invocation.cwd),
23527
24504
  ...invocation.host === void 0 ? {} : { host: invocation.host },
23528
24505
  ...invocation.port === void 0 ? {} : { port: invocation.port },
23529
- ...invocation.noAuth === true ? { token: null } : {},
23530
- ...invocation.token === void 0 ? {} : { token: invocation.token },
24506
+ ...tokenOption,
23531
24507
  ...invocation.allowPrivate === true ? { allowPrivate: true } : {},
23532
24508
  log: (line) => warn(line)
23533
24509
  });
@@ -23539,9 +24515,9 @@ ${USAGE}
23539
24515
  } else {
23540
24516
  warn(" WARNING: --no-auth is on. Any page on this machine can read the repository.");
23541
24517
  }
23542
- await new Promise((resolve15) => {
24518
+ await new Promise((resolve16) => {
23543
24519
  const stop = () => {
23544
- void server.close().then(resolve15);
24520
+ void server.close().then(resolve16);
23545
24521
  };
23546
24522
  process.once("SIGINT", stop);
23547
24523
  process.once("SIGTERM", stop);
@@ -23554,22 +24530,21 @@ ${USAGE}
23554
24530
  cwd: path27__namespace.resolve(invocation.cwd),
23555
24531
  ...invocation.host === void 0 ? {} : { host: invocation.host },
23556
24532
  ...invocation.port === void 0 ? {} : { port: invocation.port },
23557
- ...invocation.noAuth === true ? { token: null } : {},
23558
- ...invocation.token === void 0 ? {} : { token: invocation.token },
24533
+ ...tokenOption,
23559
24534
  ...invocation.allowOrigins === void 0 ? {} : { allowedOrigins: invocation.allowOrigins },
23560
24535
  log: (line) => warn(line)
23561
24536
  });
23562
24537
  info("MCP over HTTP: " + transport.url);
23563
- info(" tools: 12 (see describe --format json)");
24538
+ info(" tools: " + buildTools().length + " (see describe --format json)");
23564
24539
  if (transport.token !== null) {
23565
24540
  info(" Authorization: Bearer " + transport.token);
23566
24541
  info(" (generated for this run; pass --token to choose one)");
23567
24542
  } else {
23568
24543
  warn(" WARNING: --no-auth is on. Any page on this machine can read the repository.");
23569
24544
  }
23570
- await new Promise((resolve15) => {
24545
+ await new Promise((resolve16) => {
23571
24546
  const stop = () => {
23572
- void transport.close().then(resolve15);
24547
+ void transport.close().then(resolve16);
23573
24548
  };
23574
24549
  process.once("SIGINT", stop);
23575
24550
  process.once("SIGTERM", stop);
@@ -23667,10 +24642,25 @@ ${USAGE}
23667
24642
  return fail(invocation.format, `Could not read ${indexPath}: ${error.message}`);
23668
24643
  }
23669
24644
  const rows = [];
24645
+ const insidePath = (parent, child) => {
24646
+ const relative17 = path27__namespace.relative(parent, child);
24647
+ return relative17 === "" || !relative17.startsWith("..") && !path27__namespace.isAbsolute(relative17);
24648
+ };
23670
24649
  for (const member of index.members ?? []) {
23671
24650
  const name = member.name ?? "?";
23672
- const snapshotDir2 = path27__namespace.join(outRoot, name);
23673
- const repoDir = path27__namespace.resolve(resolved.cwd, member.path ?? name);
24651
+ const snapshotDir2 = path27__namespace.resolve(outRoot, name);
24652
+ const repoPath = member.path ?? name;
24653
+ const repoDir = path27__namespace.resolve(resolved.cwd, repoPath);
24654
+ if (name.length === 0 || path27__namespace.isAbsolute(name) || name.split("/").includes("..") || !insidePath(outRoot, snapshotDir2) || path27__namespace.isAbsolute(repoPath) || repoPath.split(/[\\/]/).includes("..") || !insidePath(resolved.cwd, repoDir)) {
24655
+ rows.push({
24656
+ name,
24657
+ score: 0,
24658
+ counts: { pass: 0, warn: 0, fail: 1 },
24659
+ failed: [],
24660
+ error: "the workspace index names a path outside the workspace"
24661
+ });
24662
+ continue;
24663
+ }
23674
24664
  if (!fs24__namespace.existsSync(path27__namespace.join(snapshotDir2, "manifest.json"))) {
23675
24665
  rows.push({ name, score: 0, counts: { pass: 0, warn: 0, fail: 1 }, failed: [], error: "no snapshot at " + snapshotDir2 });
23676
24666
  continue;
@@ -23838,6 +24828,27 @@ ${USAGE}
23838
24828
  );
23839
24829
  }
23840
24830
  const outRoot = path27__namespace.resolve(invocation.cwd, invocation.outDir ?? "snapshot");
24831
+ const workspaceCwd = path27__namespace.resolve(invocation.cwd);
24832
+ const outRootRelative = path27__namespace.relative(outRoot, workspaceCwd);
24833
+ if (outRootRelative === "" || !outRootRelative.startsWith("..") && !path27__namespace.isAbsolute(outRootRelative)) {
24834
+ return fail(
24835
+ invocation.format,
24836
+ `--workspace refuses --out-dir ${outRoot}: it is the working directory or one of its ancestors.`
24837
+ );
24838
+ }
24839
+ const plannedNames = /* @__PURE__ */ new Map();
24840
+ for (const member of members) {
24841
+ const directory = path27__namespace.resolve(invocation.cwd, member);
24842
+ const name = path27__namespace.basename(directory);
24843
+ const previous = plannedNames.get(name);
24844
+ if (previous !== void 0) {
24845
+ return fail(
24846
+ invocation.format,
24847
+ `--workspace members "${previous}" and "${member}" share the basename "${name}"; each member needs a distinct directory name.`
24848
+ );
24849
+ }
24850
+ plannedNames.set(name, member);
24851
+ }
23841
24852
  const records = [];
23842
24853
  let failed = 0;
23843
24854
  for (const member of members) {
@@ -23857,7 +24868,10 @@ ${USAGE}
23857
24868
  continue;
23858
24869
  }
23859
24870
  try {
23860
- const manifest = generateSnapshot({ cwd: directory, outDir: path27__namespace.join(outRoot, name) });
24871
+ const manifest = generateSnapshot(
24872
+ { cwd: directory, outDir: path27__namespace.join(outRoot, name) },
24873
+ { dryRun: invocation.dryRun }
24874
+ );
23861
24875
  records.push({
23862
24876
  name,
23863
24877
  path: directory,
@@ -23873,7 +24887,7 @@ ${USAGE}
23873
24887
  failed += 1;
23874
24888
  }
23875
24889
  }
23876
- fs24__namespace.mkdirSync(outRoot, { recursive: true });
24890
+ if (!invocation.dryRun) fs24__namespace.mkdirSync(outRoot, { recursive: true });
23877
24891
  const links = [];
23878
24892
  for (const record of records) {
23879
24893
  const counts = /* @__PURE__ */ new Map();
@@ -23896,16 +24910,48 @@ ${USAGE}
23896
24910
  links.push({ from: record.name, to, specifiers: bucket.count, examples: bucket.examples });
23897
24911
  }
23898
24912
  }
23899
- links.sort((left, right) => (left.from + ">" + left.to).localeCompare(right.from + ">" + right.to));
24913
+ links.sort((left, right) => {
24914
+ const a = left.from + ">" + left.to;
24915
+ const b = right.from + ">" + right.to;
24916
+ return a < b ? -1 : a > b ? 1 : 0;
24917
+ });
23900
24918
  const document = {
23901
24919
  generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
23902
24920
  generator: GENERATOR_VERSION,
23903
- members: records.map(({ imports: _imports, ...rest }) => rest),
24921
+ // The index is published; an absolute host path in it names the author's home directory.
24922
+ // Store the member path relative to the workspace cwd, as manifest paths already are.
24923
+ members: records.map(({ imports: _imports, ...rest }) => ({
24924
+ ...rest,
24925
+ path: path27__namespace.relative(workspaceCwd, rest.path).split(path27__namespace.sep).join("/") || "."
24926
+ })),
23904
24927
  links
23905
24928
  };
23906
- fs24__namespace.writeFileSync(path27__namespace.join(outRoot, "WORKSPACE.json"), JSON.stringify(document, null, 2) + "\n", "utf8");
24929
+ if (!invocation.dryRun) {
24930
+ const workspacePath = path27__namespace.join(outRoot, "WORKSPACE.json");
24931
+ try {
24932
+ const stats = fs24__namespace.lstatSync(workspacePath);
24933
+ if (stats.isSymbolicLink() || !stats.isFile()) {
24934
+ return fail(invocation.format, `${workspacePath} is not a regular file; refusing to replace it.`);
24935
+ }
24936
+ } catch (error) {
24937
+ if (error.code !== "ENOENT") throw error;
24938
+ }
24939
+ const tempPath = `${workspacePath}.${process.pid}.${Date.now()}.tmp`;
24940
+ try {
24941
+ fs24__namespace.writeFileSync(tempPath, JSON.stringify(document, null, 2) + "\n", "utf8");
24942
+ fs24__namespace.renameSync(tempPath, workspacePath);
24943
+ } catch (error) {
24944
+ try {
24945
+ fs24__namespace.rmSync(tempPath, { force: true });
24946
+ } catch {
24947
+ }
24948
+ throw error;
24949
+ }
24950
+ }
23907
24951
  emit(invocation.format, document, () => {
23908
- info("\n\u{1F5C2} Workspace: " + records.length + " of " + members.length + " member(s) written under " + outRoot);
24952
+ info(
24953
+ "\n\u{1F5C2} Workspace: " + records.length + " of " + members.length + (invocation.dryRun ? " member(s) planned; nothing was written." : " member(s) written under " + outRoot)
24954
+ );
23909
24955
  for (const record of records) {
23910
24956
  info(" - " + record.name + " (" + record.fingerprint.slice(0, 12) + ")");
23911
24957
  }
@@ -23939,8 +24985,10 @@ ${USAGE}
23939
24985
  if (shape !== null) {
23940
24986
  return fail(invocation.format, manifestPath + " is not a snapshot manifest: " + shape);
23941
24987
  }
23942
- deltaBase = { manifest: base, path: manifestPath };
23943
- info(" Delta base: " + manifestPath + " (" + base.files.length + " files, fingerprint " + base.fingerprint.slice(0, 12) + ")");
24988
+ const relativeBase = path27__namespace.relative(invocation.cwd, manifestPath).split(path27__namespace.sep).join("/");
24989
+ const recordedBase = relativeBase === "" || relativeBase.startsWith("..") || path27__namespace.isAbsolute(relativeBase) ? path27__namespace.basename(manifestPath) : relativeBase;
24990
+ deltaBase = { manifest: base, path: recordedBase };
24991
+ info(" Delta base: " + recordedBase + " (" + base.files.length + " files, fingerprint " + base.fingerprint.slice(0, 12) + ")");
23944
24992
  }
23945
24993
  const manifest = generateSnapshot(resolved, {
23946
24994
  dryRun: invocation.dryRun,
@@ -24115,8 +25163,8 @@ function comparablePath(value) {
24115
25163
  return process.platform === "win32" ? absolute.toLowerCase() : absolute;
24116
25164
  }
24117
25165
  function isSameOrInside(parent, candidate) {
24118
- const relative16 = path27__namespace.relative(parent, candidate);
24119
- return relative16 === "" || relative16 !== ".." && !relative16.startsWith(`..${path27__namespace.sep}`) && !path27__namespace.isAbsolute(relative16);
25166
+ const relative17 = path27__namespace.relative(parent, candidate);
25167
+ return relative17 === "" || relative17 !== ".." && !relative17.startsWith(`..${path27__namespace.sep}`) && !path27__namespace.isAbsolute(relative17);
24120
25168
  }
24121
25169
  function isGeneratedWatchPath(candidate, paths) {
24122
25170
  const absolute = comparablePath(path27__namespace.resolve(paths.cwd, candidate));
@@ -24251,12 +25299,12 @@ async function runWatchLoop(invocation, resolved, options) {
24251
25299
  info(`\u26A0 Watch error: ${err.message}`);
24252
25300
  info(" The watcher may have missed changes. Restart with Ctrl+C if they stop arriving.");
24253
25301
  });
24254
- await new Promise((resolve15) => {
25302
+ await new Promise((resolve16) => {
24255
25303
  const stop = () => {
24256
25304
  stopped = true;
24257
25305
  if (timer) clearTimeout(timer);
24258
25306
  watcher.close();
24259
- resolve15();
25307
+ resolve16();
24260
25308
  };
24261
25309
  process.once("SIGINT", stop);
24262
25310
  process.once("SIGTERM", stop);
@@ -24295,6 +25343,7 @@ exports.main = main;
24295
25343
  exports.parseByteOption = parseByteOption;
24296
25344
  exports.parseCliArgs = parseCliArgs;
24297
25345
  exports.parseCountOption = parseCountOption;
25346
+ exports.parsePort = parsePort;
24298
25347
  exports.parsePositiveInteger = parsePositiveInteger;
24299
25348
  exports.watchPathsFor = watchPathsFor;
24300
25349
  exports.watchSupportProblem = watchSupportProblem;