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/bin.js CHANGED
@@ -7,17 +7,192 @@ import * as path27 from "path";
7
7
  import { parseArgs } from "util";
8
8
 
9
9
  // src/diff.ts
10
- import * as fs9 from "fs";
11
- import * as path8 from "path";
10
+ import * as fs10 from "fs";
11
+ import * as path9 from "path";
12
12
 
13
13
  // src/scanner/files.ts
14
14
  import * as childProcess from "child_process";
15
+ import { createHash as createHash2 } from "crypto";
15
16
  import * as fs3 from "fs";
16
17
  import * as path3 from "path";
17
18
 
18
19
  // src/presets/context.ts
19
20
  import * as fs from "fs";
20
21
  import * as path from "path";
22
+
23
+ // src/ast/structured.ts
24
+ function stripJsonComments(content) {
25
+ const text2 = content.replace(/^\uFEFF/, "");
26
+ const withoutComments = stripComments(text2);
27
+ return stripTrailingCommas(withoutComments);
28
+ }
29
+ function stripComments(text2) {
30
+ let out = "";
31
+ let inString = false;
32
+ let escaped = false;
33
+ for (let index = 0; index < text2.length; index += 1) {
34
+ const char = text2[index];
35
+ if (inString) {
36
+ out += char;
37
+ if (escaped) escaped = false;
38
+ else if (char === "\\") escaped = true;
39
+ else if (char === '"') inString = false;
40
+ continue;
41
+ }
42
+ if (char === '"') {
43
+ inString = true;
44
+ out += char;
45
+ continue;
46
+ }
47
+ if (char === "/" && text2[index + 1] === "/") {
48
+ while (index < text2.length && text2[index] !== "\n" && text2[index] !== "\r") index += 1;
49
+ index -= 1;
50
+ continue;
51
+ }
52
+ if (char === "/" && text2[index + 1] === "*") {
53
+ index += 2;
54
+ while (index < text2.length && !(text2[index] === "*" && text2[index + 1] === "/")) {
55
+ if (text2[index] === "\n" || text2[index] === "\r") out += text2[index];
56
+ index += 1;
57
+ }
58
+ index += 1;
59
+ continue;
60
+ }
61
+ out += char;
62
+ }
63
+ return out;
64
+ }
65
+ function stripTrailingCommas(text2) {
66
+ let out = "";
67
+ let inString = false;
68
+ let escaped = false;
69
+ for (let index = 0; index < text2.length; index += 1) {
70
+ const char = text2[index];
71
+ if (inString) {
72
+ out += char;
73
+ if (escaped) escaped = false;
74
+ else if (char === "\\") escaped = true;
75
+ else if (char === '"') inString = false;
76
+ continue;
77
+ }
78
+ if (char === '"') {
79
+ inString = true;
80
+ out += char;
81
+ continue;
82
+ }
83
+ if (char === ",") {
84
+ let next = index + 1;
85
+ while (next < text2.length && /\s/.test(text2[next])) next += 1;
86
+ if (text2[next] === "}" || text2[next] === "]") continue;
87
+ }
88
+ out += char;
89
+ }
90
+ return out;
91
+ }
92
+ function summarizeJson(content) {
93
+ try {
94
+ const parsed = JSON.parse(stripJsonComments(content));
95
+ if (Array.isArray(parsed)) {
96
+ const sample2 = parsed[0];
97
+ const sampleKeys = sample2 && typeof sample2 === "object" && !Array.isArray(sample2) ? Object.keys(sample2).slice(0, 10).sort() : [];
98
+ return {
99
+ shape: "array",
100
+ itemCount: parsed.length,
101
+ keys: [],
102
+ sampleKeys
103
+ };
104
+ }
105
+ if (parsed && typeof parsed === "object") {
106
+ const keys = Object.keys(parsed).sort();
107
+ return {
108
+ shape: "object",
109
+ itemCount: keys.length,
110
+ keys: keys.slice(0, 30),
111
+ sampleKeys: []
112
+ };
113
+ }
114
+ return {
115
+ shape: typeof parsed,
116
+ itemCount: null,
117
+ keys: [],
118
+ sampleKeys: []
119
+ };
120
+ } catch {
121
+ return {
122
+ shape: "invalid-json",
123
+ itemCount: null,
124
+ keys: [],
125
+ sampleKeys: []
126
+ };
127
+ }
128
+ }
129
+ function frontMatterEnd(lines) {
130
+ if (lines.length < 3 || lines[0].trim() !== "---") return 0;
131
+ for (let index = 1; index < lines.length; index += 1) {
132
+ const line = lines[index];
133
+ const candidate = line.trim();
134
+ if (candidate === "---" || candidate === "...") {
135
+ return index > 1 ? index : 0;
136
+ }
137
+ if (candidate === "") continue;
138
+ if (/^#(\s|$)/.test(candidate)) continue;
139
+ if (/^(`{3,}|~{3,})/.test(candidate)) return 0;
140
+ if (/^#{1,6}\s+\S/.test(candidate)) return 0;
141
+ const isYamlMapping = /^[A-Za-z0-9_.-]+\s*:(\s|$)/.test(candidate);
142
+ const isListItem = /^-(?:(\s|$))/.test(candidate);
143
+ const isIndented = /^[ \t]/.test(line);
144
+ if (!isYamlMapping && !isListItem && !isIndented) return 0;
145
+ }
146
+ return 0;
147
+ }
148
+ function summarizeMarkdown(content) {
149
+ const headings = [];
150
+ const frontmatterKeys = [];
151
+ const lines = content.replace(/^\uFEFF/, "").split(/\r\n|\n|\r/);
152
+ let inFrontmatter = false;
153
+ let fence = null;
154
+ const frontMatterEndLine = frontMatterEnd(lines);
155
+ for (let index = 0; index < lines.length; index++) {
156
+ const line = lines[index];
157
+ if (index === 0 && frontMatterEndLine > 0) {
158
+ inFrontmatter = true;
159
+ continue;
160
+ }
161
+ if (inFrontmatter) {
162
+ const trimmedFrontmatter = line.trim();
163
+ if (trimmedFrontmatter === "---" || trimmedFrontmatter === "...") {
164
+ inFrontmatter = false;
165
+ continue;
166
+ }
167
+ const match = /^([A-Za-z0-9_.-]+)\s*:/.exec(line);
168
+ if (match) frontmatterKeys.push(match[1]);
169
+ continue;
170
+ }
171
+ const trimmed = line.trim();
172
+ const fenceMatch = /^(`{3,}|~{3,})(.*)$/.exec(trimmed);
173
+ if (fenceMatch) {
174
+ const run = fenceMatch[1];
175
+ const rest = fenceMatch[2].trim();
176
+ if (fence === null) {
177
+ fence = { marker: run[0], length: run.length };
178
+ } else if (run[0] === fence.marker && run.length >= fence.length && rest === "") {
179
+ fence = null;
180
+ }
181
+ continue;
182
+ }
183
+ if (fence !== null) continue;
184
+ const headingMatch = /^(#{1,6})\s+(.+)$/.exec(trimmed);
185
+ if (headingMatch) {
186
+ headings.push(`${headingMatch[1]} ${headingMatch[2].trim()}`);
187
+ }
188
+ }
189
+ return {
190
+ headings: headings.slice(0, 40),
191
+ frontmatterKeys: Array.from(new Set(frontmatterKeys)).sort()
192
+ };
193
+ }
194
+
195
+ // src/presets/context.ts
21
196
  var MANIFEST_FILES = [
22
197
  "package.json",
23
198
  "pyproject.toml",
@@ -77,7 +252,7 @@ function readManifest(cwd, name) {
77
252
  function dependenciesFromPackageJson(raw) {
78
253
  const names = /* @__PURE__ */ new Set();
79
254
  try {
80
- const parsed = JSON.parse(raw);
255
+ const parsed = JSON.parse(stripJsonComments(raw.replace(/^\uFEFF/, "")));
81
256
  for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
82
257
  const block = parsed[section];
83
258
  if (block && typeof block === "object") {
@@ -167,8 +342,8 @@ function workspacePackageDirs(cwd, patterns) {
167
342
  function scanWorkspacePackages(cwd, patterns) {
168
343
  const files = /* @__PURE__ */ new Set();
169
344
  const dependencies = /* @__PURE__ */ new Set();
170
- for (const relative16 of workspacePackageDirs(cwd, patterns)) {
171
- const full = path.join(cwd, relative16);
345
+ for (const relative17 of workspacePackageDirs(cwd, patterns)) {
346
+ const full = path.join(cwd, relative17);
172
347
  try {
173
348
  for (const entry of fs.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
174
349
  } catch {
@@ -1382,7 +1557,7 @@ var DEFAULT_SECRET_PATTERNS = [
1382
1557
  // rendering of textual userinfo mixes cases, while the prose the earlier rules were
1383
1558
  // protecting (`Bearer authentication`) is a lowercase word.
1384
1559
  rule: "authorization-header",
1385
- pattern: /(?<=[Aa]uthorization["']?\s*[:=]\s*["']?[A-Za-z][A-Za-z0-9._~+/-]{0,31}\s{1,8})(?:[A-Za-z0-9_.+/-]{0,31}[0-9][A-Za-z0-9_.+/-]{0,1024}|[A-Za-z0-9_.+/-]{32,1024}|[A-Za-z0-9_.+/-]{8,1024}={1,2}|(?=[A-Za-z0-9_.+/-]{0,1023}[A-Z])(?=[A-Za-z0-9_.+/-]{0,1023}[a-z])[A-Za-z0-9_.+/-]{12,1024})(?![A-Za-z0-9_.+/=-])/
1560
+ pattern: /(?<=[Aa][Uu][Tt][Hh][Oo][Rr][Ii][Zz][Aa][Tt][Ii][Oo][Nn]["']?\s*[:=]\s*["']?[A-Za-z][A-Za-z0-9._~+/-]{0,31}\s{1,8})(?:[A-Za-z0-9_.+/-]{0,31}[0-9][A-Za-z0-9_.+/-]{0,1024}|[A-Za-z0-9_.+/-]{32,1024}|[A-Za-z0-9_.+/-]{8,1024}={1,2}|(?=[A-Za-z0-9_.+/-]{0,1023}[A-Z])(?=[A-Za-z0-9_.+/-]{0,1023}[a-z])[A-Za-z0-9_.+/-]{12,1024})(?![A-Za-z0-9_.+/=-])/
1386
1561
  },
1387
1562
  {
1388
1563
  // Broader names than before (`apiKey`, `clientSecret`, `privateKey` were
@@ -1960,6 +2135,7 @@ function redactStructuredValues(text2, filePath, recordFinding) {
1960
2135
  if (firstValue === void 0) continue;
1961
2136
  const valueIndent = (/^[ \t]*/.exec(firstValue)?.[0] ?? "").length;
1962
2137
  if (valueIndent <= baseIndent) continue;
2138
+ if (STRUCTURED_KEY.test(firstValue) || /^[ \t]*-[ \t]/.test(firstValue)) continue;
1963
2139
  let masked = false;
1964
2140
  while (cursor < segments.length) {
1965
2141
  const body = segments[cursor] ?? "";
@@ -1975,7 +2151,7 @@ function redactStructuredValues(text2, filePath, recordFinding) {
1975
2151
  }
1976
2152
  return segments.join("");
1977
2153
  }
1978
- var DOCKERFILE_ENV = /^([ \t]*ENV[ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]+)(\S.*)$/;
2154
+ var DOCKERFILE_ENV = /^([ \t]*)(ENV|ARG)([ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]*=[ \t]*|[ \t]+)(\S.*)$/i;
1979
2155
  function redactDockerfileEnv(text2, filePath, recordFinding) {
1980
2156
  if (!isDockerfile(filePath)) return text2;
1981
2157
  const segments = text2.split(LINE_BREAK);
@@ -1984,10 +2160,9 @@ function redactDockerfileEnv(text2, filePath, recordFinding) {
1984
2160
  if (line === void 0) continue;
1985
2161
  const match = DOCKERFILE_ENV.exec(line);
1986
2162
  if (match === null) continue;
1987
- if (!CREDENTIAL_KEY_TAIL.test(match[2] ?? "")) continue;
1988
- const value = match[4] ?? "";
1989
- if (value.startsWith("=")) continue;
1990
- segments[index] = `${match[1]}${match[2]}${match[3]}${REDACTION_MARKER}`;
2163
+ if (!CREDENTIAL_KEY_TAIL.test(match[4] ?? "")) continue;
2164
+ const separator = match[5] ?? "";
2165
+ segments[index] = `${match[1]}${match[2]}${match[3]}${match[4]}${separator}${REDACTION_MARKER}`;
1991
2166
  recordFinding(index / 2 + 1, ["dockerfile-env-secret"]);
1992
2167
  }
1993
2168
  return segments.join("");
@@ -2072,6 +2247,7 @@ function isSourceCodeFile(filePath) {
2072
2247
  var PLACEHOLDER_PATTERNS = [
2073
2248
  /^<[^>]*>?$/,
2074
2249
  /^\.{3,}$/,
2250
+ /^(?:[A-Za-z0-9_-]{1,8}-)?\.{3,}$/,
2075
2251
  /^(?:x{4,}|X{4,}|\*{3,})$/,
2076
2252
  /^(?:replace|change)[-_ ]?me(?:[-_ ].*)?$/i,
2077
2253
  /^your[-_ ].*$/i,
@@ -2085,7 +2261,7 @@ function isPlaceholderValue(value) {
2085
2261
  if (trimmed.length === 0) return false;
2086
2262
  if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
2087
2263
  if (trimmed.includes(REDACTION_MARKER) || trimmed.includes(PEM_REDACTION_MARKER)) return true;
2088
- return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
2264
+ return false;
2089
2265
  }
2090
2266
  function quotesAreBalanced(text2) {
2091
2267
  let single = 0;
@@ -2137,6 +2313,7 @@ var ASSIGNMENT_FILE = /\.(?:sh|bash|zsh|ksh|fish|env|ya?ml|toml|ini|conf|cfg|pro
2137
2313
  var ASSIGNMENT_BASENAME = /^(?:\.env(?:\.[^/]*)?|\.envrc|\.profile|\.bashrc|\.zshrc|\.bash_profile)$/i;
2138
2314
  function isAssignmentFile(filePath) {
2139
2315
  if (filePath === void 0) return false;
2316
+ if (isDockerfile(filePath)) return true;
2140
2317
  const normalised = filePath.replace(/\\/g, "/");
2141
2318
  if (ASSIGNMENT_FILE.test(normalised)) return true;
2142
2319
  const base = normalised.slice(normalised.lastIndexOf("/") + 1);
@@ -2250,6 +2427,15 @@ function verifySnapshotSignature(snapshotDir) {
2250
2427
  if (sha2562 !== record.manifestSha256) {
2251
2428
  return { ok: false, reason: "manifest.json changed after it was signed" };
2252
2429
  }
2430
+ let signedFingerprint;
2431
+ try {
2432
+ signedFingerprint = JSON.parse(bytes.toString("utf8")).fingerprint;
2433
+ } catch {
2434
+ return { ok: false, reason: "the signed manifest is not JSON" };
2435
+ }
2436
+ if (typeof record.fingerprint !== "string" || record.fingerprint !== signedFingerprint) {
2437
+ return { ok: false, reason: "signature.json names a different fingerprint than the manifest" };
2438
+ }
2253
2439
  let verified = false;
2254
2440
  try {
2255
2441
  const key = crypto.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
@@ -2262,7 +2448,7 @@ function verifySnapshotSignature(snapshotDir) {
2262
2448
 
2263
2449
  // src/version.ts
2264
2450
  var GENERATOR_NAME = "codebase-snapshot";
2265
- var GENERATOR_VERSION = "0.20.4";
2451
+ var GENERATOR_VERSION = "0.20.6";
2266
2452
  var SCHEMA_VERSION = "3.0.0";
2267
2453
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2268
2454
  function isOurGeneratorName(name) {
@@ -2294,8 +2480,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
2294
2480
  };
2295
2481
  }
2296
2482
  function isInside(root, candidate) {
2297
- const relative16 = path3.relative(root, candidate);
2298
- return relative16 === "" || !relative16.startsWith(`..${path3.sep}`) && relative16 !== ".." && !path3.isAbsolute(relative16);
2483
+ const relative17 = path3.relative(root, candidate);
2484
+ return relative17 === "" || !relative17.startsWith(`..${path3.sep}`) && relative17 !== ".." && !path3.isAbsolute(relative17);
2299
2485
  }
2300
2486
  var GIT_OUTPUT_LIMIT = 68157440;
2301
2487
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -2361,7 +2547,7 @@ var DEFAULT_IGNORED_FILES = [
2361
2547
  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;
2362
2548
  var SENSITIVE_PATH = /(?:^|\/)\.(?:aws|ssh|gnupg)\/|(?:^|\/)\.docker\/config\.json$|(?:^|\/)\.kube\/config$|(?:^|\/)\.config\/gcloud\/|(?:^|\/)\.composer\/|(?:^|\/)\.terraform\/credentials\.tfrc\.json$/i;
2363
2549
  var SENSITIVE_EXT = /\.(?:pem|key|p12|pfx|jks|keystore|ppk|asc|kdbx|tfstate|tfvars)$/i;
2364
- var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.[A-Za-z0-9_-]+)?$/i;
2550
+ var TEMPLATE_SUFFIX = /^(.*)\.(?:example|sample|template|dist)(\.(?:json|ya?ml|toml|ini|txt|md|properties|conf|cfg))?$/i;
2365
2551
  var BACKUP_SUFFIX = /(?:~|\.(?:bak|backup|old|orig|save|copy|swp|swo|tmp|part))$/i;
2366
2552
  function normaliseName(name) {
2367
2553
  let normalised = name.trim().replace(/[. ]+$/, "");
@@ -2790,30 +2976,67 @@ function isToolOwnedDirectory2(dir) {
2790
2976
  }
2791
2977
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
2792
2978
  const marker2 = parsed;
2793
- if (marker2.generator !== GENERATOR_NAME || marker2.state !== "complete" || typeof marker2.id !== "string" || !Array.isArray(marker2.files)) {
2979
+ 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)) {
2794
2980
  return false;
2795
2981
  }
2796
- const accounted = /* @__PURE__ */ new Set();
2982
+ let manifestBytes;
2983
+ try {
2984
+ manifestBytes = fs3.readFileSync(path3.join(dir, "manifest.json"));
2985
+ } catch {
2986
+ return false;
2987
+ }
2988
+ if (createHash2("sha256").update(manifestBytes).digest("hex") !== marker2.manifestSha256) {
2989
+ return false;
2990
+ }
2991
+ const recordedFiles = /* @__PURE__ */ new Set();
2797
2992
  for (const item of marker2.files) {
2798
2993
  if (!item || typeof item !== "object" || Array.isArray(item)) return false;
2799
- const entry = item.path;
2800
- if (typeof entry !== "string" || entry.length === 0) return false;
2801
- const parts = entry.split("/");
2802
- for (let depth = 1; depth <= parts.length; depth += 1) {
2803
- accounted.add(parts.slice(0, depth).join("/"));
2994
+ const record = item;
2995
+ const entry = record.path;
2996
+ if (typeof entry !== "string" || entry.length === 0 || entry.includes(String.fromCharCode(92)) || entry.includes("\0") || path3.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)) {
2997
+ return false;
2804
2998
  }
2999
+ const full = path3.join(dir, ...entry.split("/"));
3000
+ let stats;
3001
+ try {
3002
+ stats = fs3.lstatSync(full);
3003
+ } catch {
3004
+ return false;
3005
+ }
3006
+ if (!stats.isFile() || stats.size !== record.bytes) return false;
3007
+ let digest;
3008
+ try {
3009
+ digest = createHash2("sha256").update(fs3.readFileSync(full)).digest("hex");
3010
+ } catch {
3011
+ return false;
3012
+ }
3013
+ if (digest !== record.sha256) return false;
3014
+ recordedFiles.add(entry);
2805
3015
  }
2806
- let entries;
2807
- try {
2808
- entries = fs3.readdirSync(dir);
2809
- } catch {
2810
- return false;
3016
+ const stack = [""];
3017
+ while (stack.length > 0) {
3018
+ const current = stack.pop();
3019
+ let entries;
3020
+ try {
3021
+ entries = fs3.readdirSync(path3.join(dir, current), { withFileTypes: true });
3022
+ } catch {
3023
+ return false;
3024
+ }
3025
+ for (const entry of entries) {
3026
+ const relative17 = current === "" ? entry.name : current + "/" + entry.name;
3027
+ if (relative17 === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry.name)) continue;
3028
+ if (entry.isDirectory()) {
3029
+ stack.push(relative17);
3030
+ continue;
3031
+ }
3032
+ if (!entry.isFile()) return false;
3033
+ if (relative17 === "signature.json" && !recordedFiles.has(relative17) && verifySnapshotSignature(dir).ok) {
3034
+ continue;
3035
+ }
3036
+ if (!recordedFiles.has(relative17)) return false;
3037
+ }
2811
3038
  }
2812
- return entries.every(
2813
- (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || // A snapshot signed before signing moved into staging has a valid signature.json the old
2814
- // marker could not record. It is our artifact when the signature verifies.
2815
- entry === "signature.json" && verifySnapshotSignature(dir).ok || accounted.has(entry)
2816
- );
3039
+ return true;
2817
3040
  }
2818
3041
  function makeToolOwnedDecider(cwd, toolOwnedPaths) {
2819
3042
  const markers = /* @__PURE__ */ new Map();
@@ -3014,7 +3237,7 @@ function collectFiles(cwd, options = {}) {
3014
3237
  candidates.push(extra);
3015
3238
  }
3016
3239
  }
3017
- const files = candidates.filter((file) => {
3240
+ let files = candidates.filter((file) => {
3018
3241
  if (isToolOwned(file)) return false;
3019
3242
  const ignored = defaultIgnoreReason(file, toolDirNames);
3020
3243
  if (ignored) {
@@ -3059,8 +3282,51 @@ function collectFiles(cwd, options = {}) {
3059
3282
  }
3060
3283
  return true;
3061
3284
  }).sort();
3285
+ files = dropSymlinksToUnincludedTargets(cwd, files, skipped);
3062
3286
  return { files, skipped: maskSkipPaths(skipped, pathRules) };
3063
3287
  }
3288
+ function dropSymlinksToUnincludedTargets(cwd, files, skipped) {
3289
+ const aliases = /* @__PURE__ */ new Set();
3290
+ for (const file of files) {
3291
+ try {
3292
+ if (fs3.lstatSync(path3.join(cwd, file)).isSymbolicLink()) aliases.add(file);
3293
+ } catch {
3294
+ }
3295
+ }
3296
+ if (aliases.size === 0) return [...files];
3297
+ const includedTargets = /* @__PURE__ */ new Set();
3298
+ for (const file of files) {
3299
+ if (aliases.has(file)) continue;
3300
+ try {
3301
+ includedTargets.add(fs3.realpathSync(path3.join(cwd, file)));
3302
+ } catch {
3303
+ }
3304
+ }
3305
+ const kept = [];
3306
+ for (const file of files) {
3307
+ if (!aliases.has(file)) {
3308
+ kept.push(file);
3309
+ continue;
3310
+ }
3311
+ let target;
3312
+ try {
3313
+ target = fs3.realpathSync(path3.join(cwd, file));
3314
+ } catch {
3315
+ skipped.push({ path: file, reason: "read-error", detail: "symlink target could not be resolved" });
3316
+ continue;
3317
+ }
3318
+ if (includedTargets.has(target)) {
3319
+ kept.push(file);
3320
+ continue;
3321
+ }
3322
+ skipped.push({
3323
+ path: file,
3324
+ reason: "symlink",
3325
+ detail: "link target was excluded from the snapshot; not followed"
3326
+ });
3327
+ }
3328
+ return kept;
3329
+ }
3064
3330
  function rootRealFor(root) {
3065
3331
  try {
3066
3332
  return fs3.realpathSync(root);
@@ -3199,190 +3465,18 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3199
3465
 
3200
3466
  // src/validator/validate.ts
3201
3467
  import * as crypto2 from "crypto";
3202
- import * as fs8 from "fs";
3203
- import * as path7 from "path";
3468
+ import * as fs9 from "fs";
3469
+ import * as path8 from "path";
3204
3470
 
3205
3471
  // src/config.ts
3206
3472
  import * as fs4 from "fs";
3207
- import { createHash as createHash3 } from "crypto";
3473
+ import { createHash as createHash4 } from "crypto";
3208
3474
  import { createRequire } from "module";
3209
3475
  import * as path4 from "path";
3210
3476
  import { pathToFileURL } from "url";
3211
3477
 
3212
- // src/ast/structured.ts
3213
- function stripJsonComments(content) {
3214
- const text2 = content.replace(/^\uFEFF/, "");
3215
- const withoutComments = stripComments(text2);
3216
- return stripTrailingCommas(withoutComments);
3217
- }
3218
- function stripComments(text2) {
3219
- let out = "";
3220
- let inString = false;
3221
- let escaped = false;
3222
- for (let index = 0; index < text2.length; index += 1) {
3223
- const char = text2[index];
3224
- if (inString) {
3225
- out += char;
3226
- if (escaped) escaped = false;
3227
- else if (char === "\\") escaped = true;
3228
- else if (char === '"') inString = false;
3229
- continue;
3230
- }
3231
- if (char === '"') {
3232
- inString = true;
3233
- out += char;
3234
- continue;
3235
- }
3236
- if (char === "/" && text2[index + 1] === "/") {
3237
- while (index < text2.length && text2[index] !== "\n" && text2[index] !== "\r") index += 1;
3238
- index -= 1;
3239
- continue;
3240
- }
3241
- if (char === "/" && text2[index + 1] === "*") {
3242
- index += 2;
3243
- while (index < text2.length && !(text2[index] === "*" && text2[index + 1] === "/")) {
3244
- if (text2[index] === "\n" || text2[index] === "\r") out += text2[index];
3245
- index += 1;
3246
- }
3247
- index += 1;
3248
- continue;
3249
- }
3250
- out += char;
3251
- }
3252
- return out;
3253
- }
3254
- function stripTrailingCommas(text2) {
3255
- let out = "";
3256
- let inString = false;
3257
- let escaped = false;
3258
- for (let index = 0; index < text2.length; index += 1) {
3259
- const char = text2[index];
3260
- if (inString) {
3261
- out += char;
3262
- if (escaped) escaped = false;
3263
- else if (char === "\\") escaped = true;
3264
- else if (char === '"') inString = false;
3265
- continue;
3266
- }
3267
- if (char === '"') {
3268
- inString = true;
3269
- out += char;
3270
- continue;
3271
- }
3272
- if (char === ",") {
3273
- let next = index + 1;
3274
- while (next < text2.length && /\s/.test(text2[next])) next += 1;
3275
- if (text2[next] === "}" || text2[next] === "]") continue;
3276
- }
3277
- out += char;
3278
- }
3279
- return out;
3280
- }
3281
- function summarizeJson(content) {
3282
- try {
3283
- const parsed = JSON.parse(stripJsonComments(content));
3284
- if (Array.isArray(parsed)) {
3285
- const sample2 = parsed[0];
3286
- const sampleKeys = sample2 && typeof sample2 === "object" && !Array.isArray(sample2) ? Object.keys(sample2).slice(0, 10).sort() : [];
3287
- return {
3288
- shape: "array",
3289
- itemCount: parsed.length,
3290
- keys: [],
3291
- sampleKeys
3292
- };
3293
- }
3294
- if (parsed && typeof parsed === "object") {
3295
- const keys = Object.keys(parsed).sort();
3296
- return {
3297
- shape: "object",
3298
- itemCount: keys.length,
3299
- keys: keys.slice(0, 30),
3300
- sampleKeys: []
3301
- };
3302
- }
3303
- return {
3304
- shape: typeof parsed,
3305
- itemCount: null,
3306
- keys: [],
3307
- sampleKeys: []
3308
- };
3309
- } catch {
3310
- return {
3311
- shape: "invalid-json",
3312
- itemCount: null,
3313
- keys: [],
3314
- sampleKeys: []
3315
- };
3316
- }
3317
- }
3318
- function frontMatterEnd(lines) {
3319
- if (lines.length < 3 || lines[0].trim() !== "---") return 0;
3320
- for (let index = 1; index < lines.length; index += 1) {
3321
- const line = lines[index];
3322
- const candidate = line.trim();
3323
- if (candidate === "---" || candidate === "...") {
3324
- return index > 1 ? index : 0;
3325
- }
3326
- if (candidate === "") continue;
3327
- if (/^#(\s|$)/.test(candidate)) continue;
3328
- if (/^(`{3,}|~{3,})/.test(candidate)) return 0;
3329
- if (/^#{1,6}\s+\S/.test(candidate)) return 0;
3330
- const isYamlMapping = /^[A-Za-z0-9_.-]+\s*:(\s|$)/.test(candidate);
3331
- const isListItem = /^-(?:(\s|$))/.test(candidate);
3332
- const isIndented = /^[ \t]/.test(line);
3333
- if (!isYamlMapping && !isListItem && !isIndented) return 0;
3334
- }
3335
- return 0;
3336
- }
3337
- function summarizeMarkdown(content) {
3338
- const headings = [];
3339
- const frontmatterKeys = [];
3340
- const lines = content.replace(/^\uFEFF/, "").split(/\r\n|\n|\r/);
3341
- let inFrontmatter = false;
3342
- let fence = null;
3343
- const frontMatterEndLine = frontMatterEnd(lines);
3344
- for (let index = 0; index < lines.length; index++) {
3345
- const line = lines[index];
3346
- if (index === 0 && frontMatterEndLine > 0) {
3347
- inFrontmatter = true;
3348
- continue;
3349
- }
3350
- if (inFrontmatter) {
3351
- const trimmedFrontmatter = line.trim();
3352
- if (trimmedFrontmatter === "---" || trimmedFrontmatter === "...") {
3353
- inFrontmatter = false;
3354
- continue;
3355
- }
3356
- const match = /^([A-Za-z0-9_.-]+)\s*:/.exec(line);
3357
- if (match) frontmatterKeys.push(match[1]);
3358
- continue;
3359
- }
3360
- const trimmed = line.trim();
3361
- const fenceMatch = /^(`{3,}|~{3,})(.*)$/.exec(trimmed);
3362
- if (fenceMatch) {
3363
- const run = fenceMatch[1];
3364
- const rest = fenceMatch[2].trim();
3365
- if (fence === null) {
3366
- fence = { marker: run[0], length: run.length };
3367
- } else if (run[0] === fence.marker && run.length >= fence.length && rest === "") {
3368
- fence = null;
3369
- }
3370
- continue;
3371
- }
3372
- if (fence !== null) continue;
3373
- const headingMatch = /^(#{1,6})\s+(.+)$/.exec(trimmed);
3374
- if (headingMatch) {
3375
- headings.push(`${headingMatch[1]} ${headingMatch[2].trim()}`);
3376
- }
3377
- }
3378
- return {
3379
- headings: headings.slice(0, 40),
3380
- frontmatterKeys: Array.from(new Set(frontmatterKeys)).sort()
3381
- };
3382
- }
3383
-
3384
3478
  // src/generator/brief.ts
3385
- import { createHash as createHash2 } from "crypto";
3479
+ import { createHash as createHash3 } from "crypto";
3386
3480
  var OWNER_SECTIONS = ["Stakes", "The system", "What came before", "The bar", "Calibration"];
3387
3481
  var RESERVED_SECTIONS = [
3388
3482
  "The job",
@@ -3458,7 +3552,7 @@ function parseOwnerBrief(filePath, text2) {
3458
3552
  return {
3459
3553
  brief: {
3460
3554
  path: filePath,
3461
- digest: createHash2("sha256").update(text2, "utf8").digest("hex"),
3555
+ digest: createHash3("sha256").update(text2, "utf8").digest("hex"),
3462
3556
  ...recognised["Stakes"] ? { stakes: recognised["Stakes"] } : {},
3463
3557
  ...recognised["The system"] ? { system: recognised["The system"] } : {},
3464
3558
  ...recognised["What came before"] ? { history: recognised["What came before"] } : {},
@@ -3578,8 +3672,25 @@ function normalizeResolvedConfig(config) {
3578
3672
  monolithWanted,
3579
3673
  monolithWanted
3580
3674
  );
3675
+ if (!Number.isSafeInteger(config.maxPartBytes) || config.maxPartBytes < MIN_MAX_PART_BYTES) {
3676
+ throw new Error(
3677
+ `maxPartBytes must be at least ${MIN_MAX_PART_BYTES} bytes (received ${String(config.maxPartBytes)}).`
3678
+ );
3679
+ }
3680
+ if (!Number.isSafeInteger(config.largeFileBytes) || config.largeFileBytes < 0) {
3681
+ throw new Error(
3682
+ `largeFileBytes must be a non-negative integer; received ${String(config.largeFileBytes)}.`
3683
+ );
3684
+ }
3685
+ const maxPartTokens = config.maxPartTokens ?? Math.floor(config.maxPartBytes / 4);
3686
+ if (!Number.isSafeInteger(maxPartTokens) || maxPartTokens < MIN_MAX_PART_TOKENS) {
3687
+ throw new Error(
3688
+ `maxPartTokens must be at least ${MIN_MAX_PART_TOKENS} tokens; received ${String(maxPartTokens)}.`
3689
+ );
3690
+ }
3581
3691
  return markResolvedConfig({
3582
3692
  ...config,
3693
+ maxPartTokens,
3583
3694
  discovery,
3584
3695
  // A spread copy built before the field existed carries no value; the default applies, and it
3585
3696
  // is re-validated because the number reaches a rendered artifact.
@@ -3734,7 +3845,7 @@ function readConfigExport(exported, file) {
3734
3845
  var lastModuleConfig = null;
3735
3846
  function moduleConfigKey(fullPath) {
3736
3847
  try {
3737
- return createHash3("sha256").update(fs4.readFileSync(fullPath)).digest("hex").slice(0, 24);
3848
+ return createHash4("sha256").update(fs4.readFileSync(fullPath)).digest("hex").slice(0, 24);
3738
3849
  } catch {
3739
3850
  try {
3740
3851
  const stats = fs4.statSync(fullPath);
@@ -4013,13 +4124,13 @@ function readConfiguredBrief(cwd, value) {
4013
4124
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
4014
4125
  );
4015
4126
  }
4016
- const relative16 = path4.relative(rootReal, filePath);
4017
- if (relative16.length === 0 || relative16 === ".." || relative16.startsWith(`..${path4.sep}`) || path4.isAbsolute(relative16)) {
4127
+ const relative17 = path4.relative(rootReal, filePath);
4128
+ if (relative17.length === 0 || relative17 === ".." || relative17.startsWith(`..${path4.sep}`) || path4.isAbsolute(relative17)) {
4018
4129
  throw new Error(
4019
4130
  'brief "' + value + '" resolves outside the repository. A brief must be a file inside the repository being described; an absolute or parent path is refused.'
4020
4131
  );
4021
4132
  }
4022
- const posixRelative = relative16.split(path4.sep).join("/");
4133
+ const posixRelative = relative17.split(path4.sep).join("/");
4023
4134
  if (isSensitivePath(posixRelative) || isSensitivePath(value)) {
4024
4135
  throw new Error(
4025
4136
  'brief "' + value + '" is a credential-bearing file. A snapshot must not reproduce secrets, so it cannot be used as the owner brief.'
@@ -4027,9 +4138,16 @@ function readConfiguredBrief(cwd, value) {
4027
4138
  }
4028
4139
  let text2;
4029
4140
  try {
4030
- if (!fs4.statSync(filePath).isFile()) throw new Error("not a file");
4141
+ const stats = fs4.statSync(filePath);
4142
+ if (!stats.isFile()) throw new Error("not a file");
4143
+ if (stats.size > MAX_BRIEF_BYTES) {
4144
+ throw new Error(
4145
+ '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."
4146
+ );
4147
+ }
4031
4148
  text2 = fs4.readFileSync(filePath, "utf8");
4032
- } catch {
4149
+ } catch (error) {
4150
+ if (error instanceof Error && error.message.startsWith('brief "')) throw error;
4033
4151
  throw new Error(
4034
4152
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
4035
4153
  );
@@ -4141,11 +4259,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
4141
4259
  const patterns = [];
4142
4260
  for (const dir of [outDir, tmpDir]) {
4143
4261
  const absolute = path4.resolve(cwd, dir);
4144
- const relative16 = path4.relative(cwd, absolute);
4145
- if (!relative16 || relative16 === ".." || relative16.startsWith(`..${path4.sep}`) || path4.isAbsolute(relative16)) {
4262
+ const relative17 = path4.relative(cwd, absolute);
4263
+ if (!relative17 || relative17 === ".." || relative17.startsWith(`..${path4.sep}`) || path4.isAbsolute(relative17)) {
4146
4264
  continue;
4147
4265
  }
4148
- patterns.push(`${relative16.replace(/\\/g, "/")}/**`);
4266
+ patterns.push(`${relative17.replace(/\\/g, "/")}/**`);
4149
4267
  }
4150
4268
  return patterns;
4151
4269
  }
@@ -4432,7 +4550,10 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
4432
4550
  outDir,
4433
4551
  tmpDir,
4434
4552
  maxPartBytes: resolvedMaxPartBytes,
4435
- ...maxPartTokens === void 0 ? {} : { maxPartTokens },
4553
+ // Record the effective value even when the user did not set it. normalizeResolvedConfig
4554
+ // derives it for the manifest; leaving validate's fresh resolution unset made a clean
4555
+ // snapshot report a configuration mismatch.
4556
+ maxPartTokens: maxPartTokens ?? Math.floor(resolvedMaxPartBytes / 4),
4436
4557
  largeFileBytes: largeFileBytesFor(resolvedMaxPartBytes, cliOptions, userConfig),
4437
4558
  previewHeadLines: strictPositiveInteger(userConfig?.previewHeadLines, 80, "`previewHeadLines`"),
4438
4559
  previewTailLines: strictPositiveInteger(userConfig?.previewTailLines, 40, "`previewTailLines`"),
@@ -4609,7 +4730,7 @@ function configDigest(config) {
4609
4730
  (rule) => `${rule.rule}:${rule.pattern.source}/${rule.pattern.flags}:${rule.valueGroup ?? ""}`
4610
4731
  ).sort()
4611
4732
  };
4612
- return createHash3("sha256").update(JSON.stringify(material)).digest("hex");
4733
+ return createHash4("sha256").update(JSON.stringify(material)).digest("hex");
4613
4734
  }
4614
4735
 
4615
4736
  // src/scanner/changed.ts
@@ -4755,6 +4876,10 @@ function tsconfigPathsFor(cwd) {
4755
4876
  return null;
4756
4877
  }
4757
4878
  const key = `${stats.mtimeMs}:${stats.size}`;
4879
+ if (!TSCONFIG_CACHE.has(configPath) && TSCONFIG_CACHE.size >= 64) {
4880
+ const oldest = TSCONFIG_CACHE.keys().next().value;
4881
+ if (oldest !== void 0) TSCONFIG_CACHE.delete(oldest);
4882
+ }
4758
4883
  const cached = TSCONFIG_CACHE.get(configPath);
4759
4884
  if (cached !== void 0 && cached.key === key) return cached.value;
4760
4885
  let value = null;
@@ -4783,8 +4908,8 @@ function tsconfigPathsFor(cwd) {
4783
4908
  return value;
4784
4909
  }
4785
4910
  function repositoryRelative(cwd, target) {
4786
- const relative16 = path5.relative(cwd, target).replace(/\\/g, "/");
4787
- return relative16.length === 0 || !relative16.startsWith("..") && !path5.isAbsolute(relative16) ? relative16 : null;
4911
+ const relative17 = path5.relative(cwd, target).replace(/\\/g, "/");
4912
+ return relative17.length === 0 || !relative17.startsWith("..") && !path5.isAbsolute(relative17) ? relative17 : null;
4788
4913
  }
4789
4914
  function rememberFirst(map, key, value) {
4790
4915
  if (!map.has(key)) map.set(key, value);
@@ -5013,7 +5138,7 @@ function summarizeTypeScriptSource(relativePath, content) {
5013
5138
  routeHandlers: []
5014
5139
  };
5015
5140
  const lowerPath = relativePath.toLowerCase();
5016
- const scriptKind2 = /.tsx$/.test(lowerPath) ? ts2.ScriptKind.TSX : /.jsx$/.test(lowerPath) ? ts2.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts2.ScriptKind.JS : ts2.ScriptKind.TS;
5141
+ const scriptKind2 = /\.tsx$/.test(lowerPath) ? ts2.ScriptKind.TSX : /\.jsx$/.test(lowerPath) ? ts2.ScriptKind.JSX : /.(?:js|mjs|cjs)$/.test(lowerPath) ? ts2.ScriptKind.JS : ts2.ScriptKind.TS;
5017
5142
  const sourceFile = ts2.createSourceFile(
5018
5143
  relativePath,
5019
5144
  content,
@@ -5249,7 +5374,7 @@ function finalizeSummary(summary) {
5249
5374
  }
5250
5375
  function eachLine(content, visit) {
5251
5376
  const text2 = content.length > MAX_SUMMARY_CHARS ? content.slice(0, MAX_SUMMARY_CHARS) : content;
5252
- for (const line of text2.split(/\r?\n/)) visit(line);
5377
+ for (const line of text2.split(/\r\n|\n|\r/)) visit(line);
5253
5378
  }
5254
5379
  function isTopLevel(line) {
5255
5380
  return !/^[\s]/.test(line);
@@ -5754,9 +5879,9 @@ var rubyProfile = {
5754
5879
  eachLine(content, (line) => {
5755
5880
  const trimmed = line.trim();
5756
5881
  if (!trimmed || trimmed.startsWith("#")) return;
5757
- const relative16 = REQUIRE_RELATIVE.exec(trimmed);
5758
- if (relative16) {
5759
- summary.imports.push(`./${relative16[1]}`);
5882
+ const relative17 = REQUIRE_RELATIVE.exec(trimmed);
5883
+ if (relative17) {
5884
+ summary.imports.push(`./${relative17[1]}`);
5760
5885
  return;
5761
5886
  }
5762
5887
  const required = REQUIRE.exec(trimmed);
@@ -6246,17 +6371,17 @@ function decodeText(buffer) {
6246
6371
  };
6247
6372
  }
6248
6373
  const invalidBytes = countInvalidUtf8Bytes(buffer);
6374
+ const controlBytes = countControlBytes(buffer);
6375
+ if (controlBytes > CONTROL_BYTES_FLOOR && controlBytes * 100 > buffer.length) {
6376
+ return {
6377
+ text: "",
6378
+ encoding: "utf-8",
6379
+ invalidBytes,
6380
+ binary: true,
6381
+ binaryReason: `${controlBytes} control byte(s) in ${buffer.length} B; not text`
6382
+ };
6383
+ }
6249
6384
  if (invalidBytes === 0) {
6250
- const controlBytes = countControlBytes(buffer);
6251
- if (controlBytes > CONTROL_BYTES_FLOOR && controlBytes * 100 > buffer.length) {
6252
- return {
6253
- text: "",
6254
- encoding: "utf-8",
6255
- invalidBytes: 0,
6256
- binary: true,
6257
- binaryReason: `${controlBytes} control byte(s) in ${buffer.length} B; valid UTF-8 but not text`
6258
- };
6259
- }
6260
6385
  return {
6261
6386
  text: new TextDecoder("utf-8").decode(buffer),
6262
6387
  encoding: "utf-8",
@@ -6344,39 +6469,112 @@ function importsOfFile(relativePath, absolutePath) {
6344
6469
  return importsOfText(relativePath, decoded.text);
6345
6470
  }
6346
6471
 
6472
+ // src/security/confine.ts
6473
+ import * as fs8 from "fs";
6474
+ import * as path7 from "path";
6475
+ function isInside2(parent, child) {
6476
+ const relative17 = path7.relative(parent, child);
6477
+ return relative17 === "" || !relative17.startsWith("..") && !path7.isAbsolute(relative17);
6478
+ }
6479
+ function resolveConfined(baseDir, relativePath) {
6480
+ if (relativePath.length === 0 || relativePath.includes("\0")) {
6481
+ return { ok: false, reason: "not-file", message: "the file name is empty or contains a NUL byte" };
6482
+ }
6483
+ if (path7.isAbsolute(relativePath)) {
6484
+ return { ok: false, reason: "outside", message: "an absolute path is not a snapshot-relative file" };
6485
+ }
6486
+ let baseReal;
6487
+ try {
6488
+ baseReal = fs8.realpathSync(path7.resolve(baseDir));
6489
+ } catch {
6490
+ return { ok: false, reason: "missing", message: "the snapshot directory does not exist" };
6491
+ }
6492
+ const candidate = path7.resolve(baseReal, relativePath);
6493
+ if (!isInside2(baseReal, candidate)) {
6494
+ return { ok: false, reason: "outside", message: "the path resolves outside the snapshot directory" };
6495
+ }
6496
+ let stats;
6497
+ try {
6498
+ stats = fs8.lstatSync(candidate);
6499
+ } catch (error) {
6500
+ const code = error.code;
6501
+ return {
6502
+ ok: false,
6503
+ reason: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unreadable",
6504
+ message: code === "ENOENT" || code === "ENOTDIR" ? "the file does not exist" : "the file could not be inspected"
6505
+ };
6506
+ }
6507
+ if (stats.isSymbolicLink()) {
6508
+ return { ok: false, reason: "not-file", message: "the file is a symbolic link" };
6509
+ }
6510
+ if (!stats.isFile()) {
6511
+ return { ok: false, reason: "not-file", message: "the path is not a regular file" };
6512
+ }
6513
+ let real;
6514
+ try {
6515
+ real = fs8.realpathSync(candidate);
6516
+ } catch {
6517
+ return { ok: false, reason: "unreadable", message: "the file could not be resolved" };
6518
+ }
6519
+ if (!isInside2(baseReal, real)) {
6520
+ return { ok: false, reason: "outside", message: "the file resolves outside the snapshot directory" };
6521
+ }
6522
+ return { ok: true, path: real, stats };
6523
+ }
6524
+ function readConfinedBytes(baseDir, relativePath) {
6525
+ const resolved = resolveConfined(baseDir, relativePath);
6526
+ if (!resolved.ok) return resolved;
6527
+ try {
6528
+ const bytes = fs8.readFileSync(resolved.path);
6529
+ return { ok: true, bytes, path: resolved.path, stats: fs8.statSync(resolved.path) };
6530
+ } catch {
6531
+ return { ok: false, reason: "unreadable", message: "the file could not be read" };
6532
+ }
6533
+ }
6534
+ function readConfinedText(baseDir, relativePath) {
6535
+ const resolved = resolveConfined(baseDir, relativePath);
6536
+ if (!resolved.ok) return resolved;
6537
+ try {
6538
+ const text2 = fs8.readFileSync(resolved.path, "utf8");
6539
+ return { ok: true, text: text2, path: resolved.path, stats: fs8.statSync(resolved.path) };
6540
+ } catch {
6541
+ return { ok: false, reason: "unreadable", message: "the file could not be read" };
6542
+ }
6543
+ }
6544
+
6347
6545
  // src/validator/validate.ts
6348
6546
  function maskedPath(value, secretRules) {
6349
6547
  return findSecretInPath(value, secretRules)?.masked ?? value;
6350
6548
  }
6351
6549
  function confineToDirectory(directory, filename) {
6352
6550
  if (filename.includes("\0")) return null;
6353
- if (path7.isAbsolute(filename)) return null;
6354
- const base = path7.resolve(directory);
6355
- const resolved = path7.resolve(base, filename);
6551
+ if (path8.isAbsolute(filename)) return null;
6552
+ const base = path8.resolve(directory);
6553
+ const resolved = path8.resolve(base, filename);
6356
6554
  const caseInsensitive = process.platform === "win32" || process.platform === "darwin";
6357
- const prefix = caseInsensitive ? `${base}${path7.sep}`.toLowerCase() : `${base}${path7.sep}`;
6555
+ const prefix = caseInsensitive ? `${base}${path8.sep}`.toLowerCase() : `${base}${path8.sep}`;
6358
6556
  const candidate = caseInsensitive ? resolved.toLowerCase() : resolved;
6359
6557
  return candidate.startsWith(prefix) ? resolved : null;
6360
6558
  }
6361
6559
  function findStagingDirectory(config) {
6362
- const tmpDir = path7.resolve(config.cwd, config.tmpDir);
6560
+ const tmpDir = path8.resolve(config.cwd, config.tmpDir);
6363
6561
  let entries;
6364
6562
  try {
6365
- entries = fs8.readdirSync(tmpDir);
6563
+ entries = fs9.readdirSync(tmpDir);
6366
6564
  } catch {
6367
6565
  return null;
6368
6566
  }
6369
6567
  const runs = entries.filter((name) => name.startsWith("run-")).sort();
6370
6568
  const newest = runs[runs.length - 1];
6371
- return newest ? path7.join(tmpDir, newest) : null;
6569
+ return newest ? path8.join(tmpDir, newest) : null;
6372
6570
  }
6373
6571
  function describeMissingManifest(config, manifestPath) {
6374
- const outDir = path7.resolve(config.cwd, config.outDir);
6375
- const markerPath = path7.join(outDir, ".codebase-snapshot");
6572
+ const outDir = path8.resolve(config.cwd, config.outDir);
6573
+ const markerPath = path8.join(outDir, ".codebase-snapshot");
6376
6574
  let marker2 = null;
6377
6575
  try {
6378
- if (fs8.existsSync(markerPath)) {
6379
- const parsed = JSON.parse(fs8.readFileSync(markerPath, "utf8"));
6576
+ if (fs9.existsSync(markerPath)) {
6577
+ const parsed = JSON.parse(fs9.readFileSync(markerPath, "utf8"));
6380
6578
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
6381
6579
  marker2 = parsed;
6382
6580
  }
@@ -6411,13 +6609,13 @@ function sha256Hex(buffer) {
6411
6609
  return crypto2.createHash("sha256").update(buffer).digest("hex");
6412
6610
  }
6413
6611
  function wouldNowBeIncluded(cwd, relativePath) {
6414
- const absolutePath = path7.join(cwd, relativePath);
6612
+ const absolutePath = path8.join(cwd, relativePath);
6415
6613
  try {
6416
- const stats = fs8.statSync(absolutePath);
6614
+ const stats = fs9.statSync(absolutePath);
6417
6615
  if (!stats.isFile()) return false;
6418
6616
  if (isBinaryExtension(absolutePath)) return false;
6419
6617
  if (stats.size > BINARY_SCAN_BYTES && isBinaryFile(absolutePath)) return false;
6420
- return !decodeText(fs8.readFileSync(absolutePath)).binary;
6618
+ return !decodeText(fs9.readFileSync(absolutePath)).binary;
6421
6619
  } catch {
6422
6620
  return false;
6423
6621
  }
@@ -6429,7 +6627,7 @@ var TRUNCATION_REASONS = /* @__PURE__ */ new Set([
6429
6627
  ]);
6430
6628
  function isConfinedRelative(value) {
6431
6629
  if (value.length === 0 || value.includes("\0") || value.includes("\\")) return false;
6432
- if (path7.isAbsolute(value)) return false;
6630
+ if (path8.isAbsolute(value)) return false;
6433
6631
  return !value.split("/").includes("..");
6434
6632
  }
6435
6633
  function describeManifestShapeProblem(value) {
@@ -6595,6 +6793,9 @@ function describeManifestShapeProblem(value) {
6595
6793
  if (typeof fields.relativePath !== "string") {
6596
6794
  return 'a "files" entry has no "relativePath"';
6597
6795
  }
6796
+ if (!isConfinedRelative(fields.relativePath)) {
6797
+ return 'a "files" entry "relativePath" resolves outside the repository and was not inspected';
6798
+ }
6598
6799
  if (!currentSchema) continue;
6599
6800
  if (typeof fields.part !== "string" || fields.part.length === 0) {
6600
6801
  return 'a "files" entry records no "part"';
@@ -6608,11 +6809,23 @@ function describeManifestShapeProblem(value) {
6608
6809
  return `a "files" entry "${key}" must be a non-negative integer`;
6609
6810
  }
6610
6811
  }
6611
- if (!["full", "preview", "signatures", "comments-stripped"].includes(String(fields.inclusionMode))) {
6612
- return 'a "files" entry has an unknown "inclusionMode"';
6812
+ if (!["full", "preview", "signatures", "comments-stripped"].includes(String(fields.inclusionMode))) {
6813
+ return 'a "files" entry has an unknown "inclusionMode"';
6814
+ }
6815
+ }
6816
+ if (!Array.isArray(candidate.skipped)) return 'missing "skipped" array';
6817
+ for (const entry of candidate.skipped) {
6818
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
6819
+ return 'a "skipped" entry is not an object';
6820
+ }
6821
+ const fields = entry;
6822
+ if (typeof fields.path !== "string" || !isConfinedRelative(fields.path)) {
6823
+ return 'a "skipped" entry "path" resolves outside the repository and was not inspected';
6824
+ }
6825
+ if (typeof fields.reason !== "string" || fields.reason.length === 0) {
6826
+ return 'a "skipped" entry has no "reason"';
6613
6827
  }
6614
6828
  }
6615
- if (!Array.isArray(candidate.skipped)) return 'missing "skipped" array';
6616
6829
  if (!Array.isArray(candidate.parts)) return 'missing "parts" array';
6617
6830
  for (const entry of candidate.parts) {
6618
6831
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
@@ -6623,7 +6836,7 @@ function describeManifestShapeProblem(value) {
6623
6836
  if (typeof filename !== "string" || filename.trim() === "") {
6624
6837
  return 'a "parts" entry has no "filename"';
6625
6838
  }
6626
- if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path7.isAbsolute(filename)) {
6839
+ if (filename.includes("/") || filename.includes("\\") || filename.includes("\0") || filename === "." || filename === ".." || path8.isAbsolute(filename)) {
6627
6840
  return 'a "parts" entry "filename" must be a bare filename inside parts/';
6628
6841
  }
6629
6842
  if (currentSchema) {
@@ -6649,8 +6862,8 @@ function describeManifestShapeProblem(value) {
6649
6862
  function validateSnapshot(configInput) {
6650
6863
  assertUsableConfigInput(configInput);
6651
6864
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput);
6652
- const manifestPath = path7.resolve(config.cwd, config.outDir, "manifest.json");
6653
- if (!fs8.existsSync(manifestPath)) {
6865
+ const manifestPath = path8.resolve(config.cwd, config.outDir, "manifest.json");
6866
+ if (!fs9.existsSync(manifestPath)) {
6654
6867
  return {
6655
6868
  valid: false,
6656
6869
  manifestPresent: false,
@@ -6661,7 +6874,7 @@ function validateSnapshot(configInput) {
6661
6874
  }
6662
6875
  let manifest;
6663
6876
  try {
6664
- manifest = JSON.parse(fs8.readFileSync(manifestPath, "utf8"));
6877
+ manifest = JSON.parse(fs9.readFileSync(manifestPath, "utf8"));
6665
6878
  } catch (err) {
6666
6879
  return {
6667
6880
  valid: false,
@@ -6673,17 +6886,19 @@ function validateSnapshot(configInput) {
6673
6886
  }
6674
6887
  const shapeProblem = describeManifestShapeProblem(manifest);
6675
6888
  if (shapeProblem) {
6889
+ const drift2 = emptyDrift();
6890
+ drift2.partIssues.push({ part: "manifest.json", issue: shapeProblem });
6676
6891
  return {
6677
6892
  valid: false,
6678
6893
  manifestPresent: true,
6679
- drift: emptyDrift(),
6894
+ drift: drift2,
6680
6895
  errors: [`${manifestPath} is not a snapshot manifest: ${shapeProblem}`],
6681
6896
  warnings: []
6682
6897
  };
6683
6898
  }
6684
6899
  const drift = emptyDrift();
6685
6900
  const warnings = [];
6686
- const snapshotDir = path7.resolve(config.cwd, config.outDir);
6901
+ const snapshotDir = path8.resolve(config.cwd, config.outDir);
6687
6902
  const unreadableSkips = manifest.skipped.filter(
6688
6903
  (entry) => entry.reason === "missing" || entry.reason === "read-error"
6689
6904
  );
@@ -6791,7 +7006,7 @@ function validateSnapshot(configInput) {
6791
7006
  );
6792
7007
  return importsChangedFile(
6793
7008
  diskFile,
6794
- importsOfFile(diskFile, path7.join(config.cwd, diskFile)),
7009
+ importsOfFile(diskFile, path8.join(config.cwd, diskFile)),
6795
7010
  unchangedScope,
6796
7011
  dependentResolver
6797
7012
  );
@@ -6805,12 +7020,16 @@ function validateSnapshot(configInput) {
6805
7020
  // discovery mode" meant `validate` could enumerate files one way while the snapshot
6806
7021
  // had been generated another way, and then blame the difference on drift.
6807
7022
  discovery: config.discovery,
7023
+ // `generate --staged` adds index-only paths to the candidate list. Without the same
7024
+ // extra paths, a staged file that is absent from the working tree was invisible to
7025
+ // this scan and then reported as deleted, although the snapshot matched the index.
7026
+ ...stagedScope === null ? {} : { extraPaths: [...stagedScope] },
6808
7027
  // The same exclusion `generate` applies: without it, `validate` recounted the tool's
6809
7028
  // own output directory as a set of files missing from the snapshot, so a correct
6810
7029
  // snapshot was reported as drifting.
6811
7030
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
6812
- (directory) => path7.relative(config.cwd, path7.resolve(config.cwd, directory)).replace(/\\/g, "/")
6813
- ).filter((relative16) => relative16.length > 0 && !relative16.startsWith(".."))
7031
+ (directory) => path8.relative(config.cwd, path8.resolve(config.cwd, directory)).replace(/\\/g, "/")
7032
+ ).filter((relative17) => relative17.length > 0 && !relative17.startsWith(".."))
6814
7033
  });
6815
7034
  for (const diskFile of collection.files) {
6816
7035
  const snapshotHash = manifestFileMap.get(diskFile);
@@ -6837,7 +7056,7 @@ function validateSnapshot(configInput) {
6837
7056
  let diskHash;
6838
7057
  try {
6839
7058
  const stagedBlob = recordedStaged && stagedScope?.has(diskFile) === true ? readStagedBlob(config.cwd, diskFile) : null;
6840
- diskHash = sha256Hex(stagedBlob ?? fs8.readFileSync(path7.join(config.cwd, diskFile)));
7059
+ diskHash = sha256Hex(stagedBlob ?? fs9.readFileSync(path8.join(config.cwd, diskFile)));
6841
7060
  } catch (err) {
6842
7061
  if (err.code === "ENOENT") {
6843
7062
  drift.missingOnDisk.push(diskFile);
@@ -6851,6 +7070,12 @@ function validateSnapshot(configInput) {
6851
7070
  }
6852
7071
  }
6853
7072
  for (const snapshotFile of manifestFileMap.keys()) {
7073
+ if (recordedStaged && stagedScope?.has(snapshotFile)) {
7074
+ if (readStagedBlob(config.cwd, snapshotFile) === null) {
7075
+ drift.missingOnDisk.push(snapshotFile);
7076
+ }
7077
+ continue;
7078
+ }
6854
7079
  const confined = confineToDirectory(config.cwd, snapshotFile);
6855
7080
  if (confined === null) {
6856
7081
  drift.partIssues.push({
@@ -6861,7 +7086,7 @@ function validateSnapshot(configInput) {
6861
7086
  }
6862
7087
  let statFailure = null;
6863
7088
  try {
6864
- fs8.statSync(confined);
7089
+ fs9.statSync(confined);
6865
7090
  } catch (err) {
6866
7091
  statFailure = err;
6867
7092
  }
@@ -6881,7 +7106,7 @@ function validateSnapshot(configInput) {
6881
7106
  ...Object.values(config.budgets.byLayer)
6882
7107
  );
6883
7108
  const partNames = /* @__PURE__ */ new Set();
6884
- const partsDir = path7.join(snapshotDir, "parts");
7109
+ const partsDir = path8.join(snapshotDir, "parts");
6885
7110
  for (const part of manifest.parts) {
6886
7111
  if (!part || typeof part.filename !== "string") continue;
6887
7112
  partNames.add(part.filename);
@@ -6894,13 +7119,15 @@ function validateSnapshot(configInput) {
6894
7119
  });
6895
7120
  continue;
6896
7121
  }
6897
- let buffer;
6898
- try {
6899
- buffer = fs8.readFileSync(partPath);
6900
- } catch {
6901
- drift.partIssues.push({ part: part.filename, issue: "missing from snapshot/parts" });
7122
+ const partRead = readConfinedBytes(partsDir, part.filename);
7123
+ if (!partRead.ok) {
7124
+ drift.partIssues.push({
7125
+ part: part.filename,
7126
+ issue: `missing or not a regular file in snapshot/parts (${partRead.reason})`
7127
+ });
6902
7128
  continue;
6903
7129
  }
7130
+ const buffer = partRead.bytes;
6904
7131
  if (buffer.length !== part.byteSize) {
6905
7132
  drift.partIssues.push({
6906
7133
  part: part.filename,
@@ -7273,15 +7500,15 @@ function validateSnapshot(configInput) {
7273
7500
  ];
7274
7501
  for (const [key, artifact] of declaredArtifacts) {
7275
7502
  if (!artifact) continue;
7276
- const artifactPath = path7.join(snapshotDir, ...key.split("/"));
7277
- let buffer;
7278
- try {
7279
- if (!fs8.statSync(artifactPath).isFile()) throw new Error("not a regular file");
7280
- buffer = fs8.readFileSync(artifactPath);
7281
- } catch {
7282
- drift.partIssues.push({ part: key, issue: "declared artifact is missing" });
7503
+ const artifactRead = readConfinedBytes(snapshotDir, key);
7504
+ if (!artifactRead.ok) {
7505
+ drift.partIssues.push({
7506
+ part: key,
7507
+ issue: `declared artifact is missing or not a regular file (${artifactRead.reason})`
7508
+ });
7283
7509
  continue;
7284
7510
  }
7511
+ const buffer = artifactRead.bytes;
7285
7512
  if (sha256Hex(buffer) !== artifact.sha256 || buffer.length !== artifact.byteSize) {
7286
7513
  drift.partIssues.push({ part: key, issue: "artifact does not match its recorded digest" });
7287
7514
  continue;
@@ -7290,9 +7517,9 @@ function validateSnapshot(configInput) {
7290
7517
  for (const match of buffer.toString("utf8").matchAll(/\]\(([^)\s]+)\)/g)) {
7291
7518
  const target = match[1].split("#")[0];
7292
7519
  if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
7293
- const resolved = path7.resolve(snapshotDir, "reports", target);
7294
- const relative16 = path7.relative(snapshotDir, resolved);
7295
- if (relative16.startsWith("..") || path7.isAbsolute(relative16) || !fs8.existsSync(resolved)) {
7520
+ const resolved = path8.resolve(snapshotDir, "reports", target);
7521
+ const relative17 = path8.relative(snapshotDir, resolved);
7522
+ if (relative17.startsWith("..") || path8.isAbsolute(relative17) || !fs9.existsSync(resolved)) {
7296
7523
  drift.partIssues.push({
7297
7524
  part: key,
7298
7525
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -7304,13 +7531,11 @@ function validateSnapshot(configInput) {
7304
7531
  const sarifArtifact = manifest.artifacts?.sarif;
7305
7532
  if (sarifArtifact) {
7306
7533
  const sarifKey = "reports/audit.sarif";
7307
- try {
7308
- const buffer = fs8.readFileSync(path7.join(snapshotDir, "reports", "audit.sarif"));
7309
- if (sha256Hex(buffer) !== sarifArtifact.sha256 || buffer.length !== sarifArtifact.byteSize) {
7310
- drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
7311
- }
7312
- } catch {
7313
- drift.partIssues.push({ part: sarifKey, issue: "declared artifact is missing" });
7534
+ const sarifRead = readConfinedBytes(snapshotDir, "reports/audit.sarif");
7535
+ if (!sarifRead.ok) {
7536
+ drift.partIssues.push({ part: sarifKey, issue: "declared artifact is missing or not a regular file" });
7537
+ } else if (sha256Hex(sarifRead.bytes) !== sarifArtifact.sha256 || sarifRead.bytes.length !== sarifArtifact.byteSize) {
7538
+ drift.partIssues.push({ part: sarifKey, issue: "artifact does not match its recorded digest" });
7314
7539
  }
7315
7540
  }
7316
7541
  if (manifest.git && manifest.git.branch && manifest.git.branch !== config.branch) {
@@ -7351,9 +7576,9 @@ function validateSnapshot(configInput) {
7351
7576
  `${drift.configMismatches.length} configuration mismatch(es) between the manifest and this run.`
7352
7577
  );
7353
7578
  }
7354
- const signaturePath = path7.join(path7.dirname(manifestPath), "signature.json");
7355
- if (fs8.existsSync(signaturePath)) {
7356
- const outcome = verifySnapshotSignature(path7.dirname(manifestPath));
7579
+ const signaturePath = path8.join(path8.dirname(manifestPath), "signature.json");
7580
+ if (fs9.existsSync(signaturePath)) {
7581
+ const outcome = verifySnapshotSignature(path8.dirname(manifestPath));
7357
7582
  if (!outcome.ok) errors.push("signature: " + outcome.reason + ".");
7358
7583
  }
7359
7584
  if (manifest.slice !== void 0 || manifest.budget !== void 0) {
@@ -7599,14 +7824,14 @@ function compareManifests(before, after, secretRules) {
7599
7824
  function loadManifest(target) {
7600
7825
  let isDirectory;
7601
7826
  try {
7602
- isDirectory = fs9.statSync(target).isDirectory();
7827
+ isDirectory = fs10.statSync(target).isDirectory();
7603
7828
  } catch {
7604
7829
  throw new Error(`No snapshot found at ${target}: the path does not exist.`);
7605
7830
  }
7606
- const manifestPath = isDirectory ? path8.join(target, "manifest.json") : target;
7831
+ const manifestPath = isDirectory ? path9.join(target, "manifest.json") : target;
7607
7832
  let raw;
7608
7833
  try {
7609
- raw = fs9.readFileSync(manifestPath, "utf8");
7834
+ raw = fs10.readFileSync(manifestPath, "utf8");
7610
7835
  } catch {
7611
7836
  throw new Error(`Could not read a manifest at ${manifestPath}.`);
7612
7837
  }
@@ -7662,8 +7887,8 @@ function renderDiffText(diff) {
7662
7887
  }
7663
7888
 
7664
7889
  // src/explain.ts
7665
- import * as fs10 from "fs";
7666
- import * as path10 from "path";
7890
+ import * as fs11 from "fs";
7891
+ import * as path11 from "path";
7667
7892
 
7668
7893
  // src/ast/skeleton.ts
7669
7894
  import ts3 from "typescript";
@@ -7703,9 +7928,15 @@ function skeletonizeTypeScript(source, fileName = "file.ts") {
7703
7928
  if (end > start) spans.push({ start, end });
7704
7929
  }
7705
7930
  }
7706
- ts3.forEachChild(node, visit);
7707
7931
  };
7708
- visit(sourceFile);
7932
+ const stack = [sourceFile];
7933
+ while (stack.length > 0) {
7934
+ const node = stack.pop();
7935
+ visit(node);
7936
+ ts3.forEachChild(node, (child) => {
7937
+ stack.push(child);
7938
+ });
7939
+ }
7709
7940
  if (spans.length === 0) return { text: source, collapsed: 0 };
7710
7941
  const outermost = [];
7711
7942
  for (const span of spans.sort((a, b) => a.start - b.start || b.end - a.end)) {
@@ -7754,12 +7985,15 @@ function stripComments2(text2, relativePath) {
7754
7985
  if (ranges_ === void 0) return;
7755
7986
  for (const range of ranges_) ranges.push([range.pos, range.end]);
7756
7987
  };
7757
- const visit = (node) => {
7988
+ const stack = [source];
7989
+ while (stack.length > 0) {
7990
+ const node = stack.pop();
7758
7991
  collect(ts4.getLeadingCommentRanges(text2, node.getFullStart()));
7759
7992
  collect(ts4.getTrailingCommentRanges(text2, node.getEnd()));
7760
- ts4.forEachChild(node, visit);
7761
- };
7762
- visit(source);
7993
+ ts4.forEachChild(node, (child) => {
7994
+ stack.push(child);
7995
+ });
7996
+ }
7763
7997
  collect(ts4.getLeadingCommentRanges(text2, source.endOfFileToken.getFullStart()));
7764
7998
  if (ranges.length === 0) return { text: text2, removed: 0 };
7765
7999
  ranges.sort((left, right) => left[0] - right[0]);
@@ -7799,6 +8033,9 @@ function countLines(content) {
7799
8033
  const last = content.charCodeAt(content.length - 1);
7800
8034
  return last === 10 || last === 13 ? breaks : breaks + 1;
7801
8035
  }
8036
+ function countBodyLines(content) {
8037
+ return content.length === 0 ? 0 : content.split("\n").length;
8038
+ }
7802
8039
  function truncateToBytes(content, maxBytes) {
7803
8040
  if (maxBytes <= 0) return { content: "", isTruncated: content.length > 0 };
7804
8041
  const buffer = Buffer.from(content, "utf8");
@@ -7843,7 +8080,7 @@ function truncatePreview(content, headLines, tailLines) {
7843
8080
  }
7844
8081
 
7845
8082
  // src/scanner/language.ts
7846
- import * as path9 from "path";
8083
+ import * as path10 from "path";
7847
8084
  var LANGUAGE_BY_EXTENSION = {
7848
8085
  ".ts": "typescript",
7849
8086
  ".mts": "typescript",
@@ -7901,10 +8138,10 @@ var LANGUAGE_BY_BASENAME = {
7901
8138
  };
7902
8139
  function detectLanguage(filePath) {
7903
8140
  const normalized = filePath.replace(/\\/g, "/");
7904
- const base = path9.posix.basename(normalized);
8141
+ const base = path10.posix.basename(normalized);
7905
8142
  if (LANGUAGE_BY_BASENAME[base]) return LANGUAGE_BY_BASENAME[base];
7906
8143
  if (base === ".env" || base.startsWith(".env.")) return "dotenv";
7907
- const ext = path9.posix.extname(base).toLowerCase();
8144
+ const ext = path10.posix.extname(base).toLowerCase();
7908
8145
  return LANGUAGE_BY_EXTENSION[ext] ?? "text";
7909
8146
  }
7910
8147
 
@@ -7937,6 +8174,17 @@ function formatNumber(value) {
7937
8174
  }
7938
8175
 
7939
8176
  // src/explain.ts
8177
+ function safeRegularFile(cwd, absolute) {
8178
+ try {
8179
+ if (!fs11.lstatSync(absolute).isFile()) return false;
8180
+ const root = fs11.realpathSync(cwd);
8181
+ const real = fs11.realpathSync(absolute);
8182
+ const relative17 = path11.relative(root, real);
8183
+ return relative17 !== ".." && !relative17.startsWith(".." + path11.sep) && !path11.isAbsolute(relative17);
8184
+ } catch {
8185
+ return false;
8186
+ }
8187
+ }
7940
8188
  function describeMatcher(matcher) {
7941
8189
  if (typeof matcher === "string") return matcher;
7942
8190
  if (matcher instanceof RegExp) return String(matcher);
@@ -7946,42 +8194,42 @@ function describeMatcher(matcher) {
7946
8194
  return String(matcher);
7947
8195
  }
7948
8196
  function normalizeTarget(cwd, target) {
7949
- const resolvedCwd = path10.resolve(cwd);
7950
- const absolute = path10.resolve(resolvedCwd, target);
7951
- const relative16 = path10.relative(resolvedCwd, absolute);
7952
- if (relative16 === "" || relative16 === ".." || relative16.startsWith(`..${path10.sep}`) || path10.isAbsolute(relative16)) {
8197
+ const resolvedCwd = path11.resolve(cwd);
8198
+ const absolute = path11.resolve(resolvedCwd, target);
8199
+ const relative17 = path11.relative(resolvedCwd, absolute);
8200
+ if (relative17 === "" || relative17 === ".." || relative17.startsWith(`..${path11.sep}`) || path11.isAbsolute(relative17)) {
7953
8201
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
7954
8202
  }
7955
- return { relative: relative16.split(path10.sep).join("/"), outsideRoot: false };
8203
+ return { relative: relative17.split(path11.sep).join("/"), outsideRoot: false };
7956
8204
  }
7957
8205
  function findRuleMatch(rules, relativePath) {
7958
8206
  return rules.find(
7959
8207
  (rule) => matchRule(relativePath, rule.match)
7960
8208
  );
7961
8209
  }
7962
- function findRecordedAncestor(skipped, relative16, maskedPath2) {
8210
+ function findRecordedAncestor(skipped, relative17, maskedPath2) {
7963
8211
  let nearest;
7964
8212
  for (const record of skipped) {
7965
8213
  const ancestorPath = record.path;
7966
8214
  if (ancestorPath.length === 0) continue;
7967
- const isAncestor = relative16.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
8215
+ const isAncestor = relative17.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
7968
8216
  if (!isAncestor) continue;
7969
8217
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
7970
8218
  }
7971
8219
  return nearest;
7972
8220
  }
7973
8221
  function readManifest2(config) {
7974
- const manifestPath = path10.resolve(config.cwd, config.outDir, "manifest.json");
8222
+ const manifestPath = path11.resolve(config.cwd, config.outDir, "manifest.json");
7975
8223
  try {
7976
- return JSON.parse(fs10.readFileSync(manifestPath, "utf8"));
8224
+ return JSON.parse(fs11.readFileSync(manifestPath, "utf8"));
7977
8225
  } catch {
7978
8226
  return null;
7979
8227
  }
7980
8228
  }
7981
8229
  function explainPath(config, target) {
7982
8230
  const normalized = normalizeTarget(config.cwd, target);
7983
- const relative16 = normalized.relative;
7984
- const maskedPath2 = findSecretInPath(relative16, config.secretRules)?.masked ?? relative16;
8231
+ const relative17 = normalized.relative;
8232
+ const maskedPath2 = findSecretInPath(relative17, config.secretRules)?.masked ?? relative17;
7985
8233
  if (normalized.outsideRoot) {
7986
8234
  return {
7987
8235
  path: maskedPath2,
@@ -7991,10 +8239,14 @@ function explainPath(config, target) {
7991
8239
  detail: "path resolves outside the configured repository root and was not inspected"
7992
8240
  };
7993
8241
  }
7994
- const absolute = path10.join(config.cwd, relative16);
8242
+ const absolute = path11.join(config.cwd, relative17);
8243
+ const stagedBlob = config.staged === true ? readStagedBlob(config.cwd, relative17) : null;
7995
8244
  const result = {
7996
8245
  path: maskedPath2,
7997
- exists: fs10.existsSync(absolute),
8246
+ // `existsSync` follows a symlink, so an in-repo link to /etc/passwd answered "exists" for a
8247
+ // file the scanner refuses. `lstat` plus a canonical containment check keeps the answer about
8248
+ // a regular file the repository actually contains; a staged blob is the index's answer.
8249
+ exists: stagedBlob !== null || safeRegularFile(config.cwd, absolute),
7998
8250
  included: false
7999
8251
  };
8000
8252
  const collection = collectFiles(config.cwd, {
@@ -8008,12 +8260,12 @@ function explainPath(config, target) {
8008
8260
  // Same exclusion `generate` applies, so `explain` never says "not-discovered" about a file
8009
8261
  // that is only missing because the walker dropped the tool's own output directory.
8010
8262
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
8011
- (directory) => path10.relative(config.cwd, path10.resolve(config.cwd, directory)).replace(/\\/g, "/")
8012
- ).filter((relative17) => relative17.length > 0 && !relative17.startsWith(".."))
8263
+ (directory) => path11.relative(config.cwd, path11.resolve(config.cwd, directory)).replace(/\\/g, "/")
8264
+ ).filter((relative18) => relative18.length > 0 && !relative18.startsWith(".."))
8013
8265
  });
8014
- if (!collection.files.includes(relative16)) {
8266
+ if (!collection.files.includes(relative17)) {
8015
8267
  const record = collection.skipped.find(
8016
- (entry2) => entry2.path === relative16 || entry2.path === maskedPath2
8268
+ (entry2) => entry2.path === relative17 || entry2.path === maskedPath2
8017
8269
  );
8018
8270
  if (record) {
8019
8271
  result.reason = record.reason;
@@ -8022,7 +8274,7 @@ function explainPath(config, target) {
8022
8274
  result.reason = "missing";
8023
8275
  result.detail = "no such file or directory, relative to the configured cwd";
8024
8276
  } else {
8025
- const ancestor = findRecordedAncestor(collection.skipped, relative16, maskedPath2);
8277
+ const ancestor = findRecordedAncestor(collection.skipped, relative17, maskedPath2);
8026
8278
  if (ancestor) {
8027
8279
  result.reason = ancestor.reason;
8028
8280
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -8042,11 +8294,11 @@ function explainPath(config, target) {
8042
8294
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
8043
8295
  ...config.staged === true ? { staged: true } : {}
8044
8296
  });
8045
- inScope = scope.paths.has(relative16);
8297
+ inScope = scope.paths.has(relative17);
8046
8298
  if (!inScope && config.withDependents === true) {
8047
8299
  inScope = importsChangedFile(
8048
- relative16,
8049
- importsOfFile(relative16, absolute),
8300
+ relative17,
8301
+ importsOfFile(relative17, absolute),
8050
8302
  scope.paths,
8051
8303
  buildImportResolver(collection.files.map((file) => ({ relativePath: file })), {
8052
8304
  tsconfig: tsconfigPathsFor(config.cwd)
@@ -8073,11 +8325,13 @@ function explainPath(config, target) {
8073
8325
  result.detail = "binary extension; generate skips it without reading and records `binary` in manifest.skipped[]";
8074
8326
  return result;
8075
8327
  }
8076
- let sizeOnDisk = null;
8077
- try {
8078
- sizeOnDisk = fs10.statSync(absolute).size;
8079
- } catch {
8080
- sizeOnDisk = null;
8328
+ let sizeOnDisk = stagedBlob?.length ?? null;
8329
+ if (sizeOnDisk === null) {
8330
+ try {
8331
+ sizeOnDisk = fs11.statSync(absolute).size;
8332
+ } catch {
8333
+ sizeOnDisk = null;
8334
+ }
8081
8335
  }
8082
8336
  if (sizeOnDisk !== null && sizeOnDisk > BINARY_SCAN_BYTES && isBinaryFile(absolute)) {
8083
8337
  result.included = false;
@@ -8085,10 +8339,10 @@ function explainPath(config, target) {
8085
8339
  result.detail = "binary content; generate skips it and records `binary` in manifest.skipped[]";
8086
8340
  return result;
8087
8341
  }
8088
- if (fs10.existsSync(absolute) && fs10.statSync(absolute).isFile()) {
8342
+ if (stagedBlob !== null || safeRegularFile(config.cwd, absolute)) {
8089
8343
  let buffer;
8090
8344
  try {
8091
- buffer = fs10.readFileSync(absolute);
8345
+ buffer = stagedBlob ?? fs11.readFileSync(absolute);
8092
8346
  } catch (err) {
8093
8347
  result.included = false;
8094
8348
  result.reason = "read-error";
@@ -8106,15 +8360,15 @@ function explainPath(config, target) {
8106
8360
  result.bytes = buffer.length;
8107
8361
  result.lines = countLines(text2);
8108
8362
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
8109
- const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative16);
8363
+ const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative17);
8110
8364
  result.secretCount = findings.length;
8111
8365
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
8112
8366
  let inclusionMode = "full";
8113
- if (config.skeleton === true && isSkeletonizable(relative16)) {
8114
- const skeleton = skeletonizeTypeScript(text2, relative16);
8367
+ if (config.skeleton === true && isSkeletonizable(relative17)) {
8368
+ const skeleton = skeletonizeTypeScript(text2, relative17);
8115
8369
  if (skeleton.collapsed > 0) inclusionMode = "signatures";
8116
8370
  }
8117
- if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative16) && stripComments2(text2, relative16).removed > 0) {
8371
+ if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative17) && stripComments2(text2, relative17).removed > 0) {
8118
8372
  inclusionMode = "comments-stripped";
8119
8373
  }
8120
8374
  if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
@@ -8123,20 +8377,36 @@ function explainPath(config, target) {
8123
8377
  }
8124
8378
  result.inclusionMode = inclusionMode;
8125
8379
  }
8126
- result.layer = classifyLayer(relative16, config.layers);
8127
- result.kind = classifyKind(relative16, config.kinds);
8128
- result.language = detectLanguage(relative16);
8129
- const layerRule = findRuleMatch(config.layers, relative16);
8380
+ result.layer = classifyLayer(relative17, config.layers);
8381
+ result.kind = classifyKind(relative17, config.kinds);
8382
+ result.language = detectLanguage(relative17);
8383
+ const layerRule = findRuleMatch(config.layers, relative17);
8130
8384
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
8131
- const kindRule = findRuleMatch(config.kinds, relative16);
8385
+ const kindRule = findRuleMatch(config.kinds, relative17);
8132
8386
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
8133
8387
  const manifest = readManifest2(config);
8134
- const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative16) : void 0;
8388
+ const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative17) : void 0;
8135
8389
  result.part = entry?.part ?? null;
8136
8390
  if (entry === void 0) {
8137
- const record = manifest?.skipped?.find((skip) => skip.path === relative16);
8391
+ const record = manifest?.skipped?.find((skip) => skip.path === relative17);
8138
8392
  if (record !== void 0 && (record.reason === "not-selected" || record.reason === "unchanged")) {
8139
8393
  result.included = false;
8394
+ for (const key of [
8395
+ "layer",
8396
+ "layerMatch",
8397
+ "kind",
8398
+ "kindMatch",
8399
+ "language",
8400
+ "inclusionMode",
8401
+ "lines",
8402
+ "bytes",
8403
+ "encoding",
8404
+ "secretCount",
8405
+ "secrets"
8406
+ ]) {
8407
+ delete result[key];
8408
+ }
8409
+ result.part = null;
8140
8410
  result.reason = record.reason;
8141
8411
  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");
8142
8412
  }
@@ -8179,12 +8449,12 @@ function renderExplainText(result) {
8179
8449
  }
8180
8450
 
8181
8451
  // src/wizard/init.ts
8182
- import * as fs12 from "fs";
8183
- import * as path12 from "path";
8452
+ import * as fs13 from "fs";
8453
+ import * as path13 from "path";
8184
8454
 
8185
8455
  // src/gitignore.ts
8186
- import * as fs11 from "fs";
8187
- import * as path11 from "path";
8456
+ import * as fs12 from "fs";
8457
+ import * as path12 from "path";
8188
8458
  function decodeGitignore(buffer) {
8189
8459
  const startsWith = (...bytes) => buffer.length >= bytes.length && bytes.every((byte, index) => buffer[index] === byte);
8190
8460
  if (startsWith(239, 187, 191)) {
@@ -8233,15 +8503,31 @@ function canonicalIgnorePattern(line) {
8233
8503
  function appendGitignoreEntries(cwd, entries) {
8234
8504
  const wanted = [...new Set(entries)].filter((entry) => entry.trim().length > 0);
8235
8505
  if (wanted.length === 0) return { added: [], note: null };
8236
- const ignorePath = path11.join(cwd, ".gitignore");
8506
+ const ignorePath = path12.join(cwd, ".gitignore");
8237
8507
  const manual = `Add ${wanted.map((entry) => `"${entry}"`).join(" and ")} to your .gitignore yourself.`;
8238
8508
  let decoded = { text: "", bom: Buffer.alloc(0), encoding: "utf8" };
8239
8509
  try {
8240
- if (fs11.existsSync(ignorePath)) {
8241
- if (fs11.statSync(ignorePath).isDirectory()) {
8510
+ if (fs12.existsSync(ignorePath)) {
8511
+ const stats = fs12.lstatSync(ignorePath);
8512
+ if (stats.isDirectory()) {
8242
8513
  return { added: [], note: `${ignorePath} is a directory, so it was not updated. ${manual}` };
8243
8514
  }
8244
- const read = decodeGitignore(fs11.readFileSync(ignorePath));
8515
+ if (stats.isSymbolicLink() || !stats.isFile() || stats.nlink > 1) {
8516
+ return {
8517
+ added: [],
8518
+ note: `${ignorePath} is a symbolic link, a hard link, or not a regular file, so it was not updated. ` + manual
8519
+ };
8520
+ }
8521
+ const rootReal = fs12.realpathSync(cwd);
8522
+ const fileReal = fs12.realpathSync(ignorePath);
8523
+ const relative17 = path12.relative(rootReal, fileReal);
8524
+ if (relative17 === ".." || relative17.startsWith(`..${path12.sep}`) || path12.isAbsolute(relative17)) {
8525
+ return {
8526
+ added: [],
8527
+ note: `${ignorePath} resolves outside the repository, so it was not updated. ${manual}`
8528
+ };
8529
+ }
8530
+ const read = decodeGitignore(fs12.readFileSync(ignorePath));
8245
8531
  if (read === null) {
8246
8532
  return {
8247
8533
  added: [],
@@ -8262,18 +8548,25 @@ function appendGitignoreEntries(cwd, entries) {
8262
8548
  if (added.length === 0) return { added: [], note: null };
8263
8549
  const newline = existing.includes("\r\n") ? "\r\n" : "\n";
8264
8550
  const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : newline;
8551
+ const tempPath = `${ignorePath}.${process.pid}.${Date.now()}.tmp`;
8265
8552
  try {
8266
- fs11.writeFileSync(
8267
- ignorePath,
8268
- encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`)
8553
+ fs12.writeFileSync(
8554
+ tempPath,
8555
+ encodeGitignore(decoded, `${existing}${prefix}${added.join(newline)}${newline}`),
8556
+ { flag: "wx" }
8269
8557
  );
8558
+ fs12.renameSync(tempPath, ignorePath);
8270
8559
  } catch (err) {
8560
+ try {
8561
+ fs12.rmSync(tempPath, { force: true });
8562
+ } catch {
8563
+ }
8271
8564
  return { added: [], note: `${err.message}. ${manual}` };
8272
8565
  }
8273
8566
  return { added, note: null };
8274
8567
  }
8275
8568
  function gitignorePath(cwd, filePath) {
8276
- return path11.relative(cwd, filePath).split(path11.sep).join("/");
8569
+ return path12.relative(cwd, filePath).split(path12.sep).join("/");
8277
8570
  }
8278
8571
 
8279
8572
  // src/wizard/brief-template.ts
@@ -8666,7 +8959,7 @@ function keyReader(input) {
8666
8959
  next() {
8667
8960
  const queued = queue.shift();
8668
8961
  if (queued) return Promise.resolve(queued);
8669
- return new Promise((resolve15) => waiters.push(resolve15));
8962
+ return new Promise((resolve16) => waiters.push(resolve16));
8670
8963
  },
8671
8964
  close() {
8672
8965
  input.off("keypress", onKey);
@@ -8892,7 +9185,7 @@ function parsePackageJson(raw) {
8892
9185
  }
8893
9186
  function readPackageJson(cwd) {
8894
9187
  try {
8895
- return parsePackageJson(fs12.readFileSync(path12.join(cwd, "package.json"), "utf8"));
9188
+ return parsePackageJson(fs13.readFileSync(path13.join(cwd, "package.json"), "utf8"));
8896
9189
  } catch {
8897
9190
  return null;
8898
9191
  }
@@ -8929,7 +9222,7 @@ function artifactAnswers(options) {
8929
9222
  }
8930
9223
  function topLevelDirs(cwd) {
8931
9224
  try {
8932
- return fs12.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
9225
+ return fs13.readdirSync(cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules").map((entry) => entry.name).sort();
8933
9226
  } catch {
8934
9227
  return [];
8935
9228
  }
@@ -8944,7 +9237,7 @@ function writeFileOrExplain(target, content) {
8944
9237
  try {
8945
9238
  let stats = null;
8946
9239
  try {
8947
- stats = fs12.lstatSync(target);
9240
+ stats = fs13.lstatSync(target);
8948
9241
  } catch {
8949
9242
  stats = null;
8950
9243
  }
@@ -8959,12 +9252,12 @@ function writeFileOrExplain(target, content) {
8959
9252
  );
8960
9253
  }
8961
9254
  const temporary = `${target}.tmp-${process.pid}-${Date.now()}`;
8962
- fs12.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
9255
+ fs13.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
8963
9256
  try {
8964
- fs12.renameSync(temporary, target);
9257
+ fs13.renameSync(temporary, target);
8965
9258
  } catch (err) {
8966
9259
  try {
8967
- fs12.unlinkSync(temporary);
9260
+ fs13.unlinkSync(temporary);
8968
9261
  } catch {
8969
9262
  }
8970
9263
  throw err;
@@ -9012,19 +9305,19 @@ function serializePackageJson(raw, value) {
9012
9305
  return `${bom}${text2}${raw.endsWith("\n") ? crlf ? "\r\n" : "\n" : ""}`;
9013
9306
  }
9014
9307
  function updatePackageJson(cwd, notes) {
9015
- const packagePath = path12.join(cwd, "package.json");
9308
+ const packagePath = path13.join(cwd, "package.json");
9016
9309
  const unchanged = {
9017
9310
  scripts: [],
9018
9311
  dependency: { name: GENERATOR_NAME, range: null, added: false }
9019
9312
  };
9020
- if (!fs12.existsSync(packagePath)) {
9313
+ if (!fs13.existsSync(packagePath)) {
9021
9314
  notes.push("No package.json found, so npm scripts and the devDependency were not added.");
9022
9315
  return unchanged;
9023
9316
  }
9024
9317
  let raw;
9025
9318
  let parsed;
9026
9319
  try {
9027
- raw = fs12.readFileSync(packagePath, "utf8");
9320
+ raw = fs13.readFileSync(packagePath, "utf8");
9028
9321
  parsed = parsePackageJson(raw);
9029
9322
  } catch {
9030
9323
  notes.push("Could not parse package.json; npm scripts and the devDependency were not added.");
@@ -9099,11 +9392,11 @@ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
9099
9392
  const entries = [];
9100
9393
  for (const directory of [outDir, tmpDir]) {
9101
9394
  if (directory === null) continue;
9102
- const relative16 = path12.relative(cwd, path12.resolve(cwd, directory)).replace(/\\/g, "/");
9103
- if (relative16 === "" || relative16 === "." || relative16.startsWith("..") || path12.isAbsolute(relative16)) {
9395
+ const relative17 = path13.relative(cwd, path13.resolve(cwd, directory)).replace(/\\/g, "/");
9396
+ if (relative17 === "" || relative17 === "." || relative17.startsWith("..") || path13.isAbsolute(relative17)) {
9104
9397
  continue;
9105
9398
  }
9106
- entries.push(`/${relative16}/`);
9399
+ entries.push(`/${relative17}/`);
9107
9400
  }
9108
9401
  return [...new Set(entries)];
9109
9402
  }
@@ -9259,7 +9552,14 @@ async function runInit(options) {
9259
9552
  try {
9260
9553
  const raw = await text(io, "Part size (e.g. 150k, 1.5mb, 900000)", {
9261
9554
  defaultValue: currentBudget,
9262
- validate: (value) => parseByteSize(value) === void 0 ? "Not a valid size." : null,
9555
+ validate: (value) => {
9556
+ const parsed = parseByteSize(value);
9557
+ if (parsed === void 0) return "Not a valid size.";
9558
+ if (parsed < MIN_MAX_PART_BYTES) {
9559
+ return `A part budget below ${MIN_MAX_PART_BYTES} bytes cannot hold the truncation notice.`;
9560
+ }
9561
+ return null;
9562
+ },
9263
9563
  allowBack: true
9264
9564
  });
9265
9565
  answers.maxPartBytes = parseByteSize(raw) ?? answers.maxPartBytes;
@@ -9355,7 +9655,7 @@ async function runInit(options) {
9355
9655
  const configText = renderConfig(answers);
9356
9656
  const preferredName = chooseConfigFileName(options.cwd);
9357
9657
  const presentConfigs = CONFIG_CANDIDATES.filter(
9358
- (name) => fs12.existsSync(path12.join(options.cwd, name))
9658
+ (name) => fs13.existsSync(path13.join(options.cwd, name))
9359
9659
  );
9360
9660
  const present = presentConfigs[0] ?? null;
9361
9661
  if (presentConfigs.length > 1) {
@@ -9364,7 +9664,7 @@ async function runInit(options) {
9364
9664
  );
9365
9665
  }
9366
9666
  const configName = present !== null && options.force ? present : preferredName;
9367
- const configPath = path12.join(options.cwd, configName);
9667
+ const configPath = path13.join(options.cwd, configName);
9368
9668
  const reused = present !== null && options.force !== true && options.reuseConfig === true;
9369
9669
  if (reused) notes.push(`Kept the existing ${present} instead of writing a new one.`);
9370
9670
  if (options.dryRun) {
@@ -9381,7 +9681,7 @@ async function runInit(options) {
9381
9681
  dependency: { name: GENERATOR_NAME, range: `^${GENERATOR_VERSION}`, added: false },
9382
9682
  notes,
9383
9683
  outDir: answers.outDir,
9384
- briefPath: path12.join(options.cwd, BRIEF_SCAFFOLD_FILE),
9684
+ briefPath: path13.join(options.cwd, BRIEF_SCAFFOLD_FILE),
9385
9685
  briefWritten: false
9386
9686
  };
9387
9687
  }
@@ -9400,13 +9700,13 @@ async function runInit(options) {
9400
9700
  'package.json already defines a "snapshot" config. Remove that key, or re-run with --force to write a config file that takes precedence over it.'
9401
9701
  );
9402
9702
  }
9403
- if (fs12.existsSync(configPath) && !options.force && !reused) {
9703
+ if (fs13.existsSync(configPath) && !options.force && !reused) {
9404
9704
  throw new Error(`${configName} already exists. Re-run with --force to replace it.`);
9405
9705
  }
9406
9706
  if (!reused) writeFileOrExplain(configPath, configText);
9407
- const briefPath = path12.join(options.cwd, BRIEF_SCAFFOLD_FILE);
9707
+ const briefPath = path13.join(options.cwd, BRIEF_SCAFFOLD_FILE);
9408
9708
  let briefWritten = false;
9409
- if (!fs12.existsSync(briefPath)) {
9709
+ if (!fs13.existsSync(briefPath)) {
9410
9710
  writeFileOrExplain(briefPath, BRIEF_SCAFFOLD);
9411
9711
  briefWritten = true;
9412
9712
  }
@@ -9435,13 +9735,13 @@ async function runInit(options) {
9435
9735
  }
9436
9736
 
9437
9737
  // src/wizard/autopilot.ts
9438
- import * as fs13 from "fs";
9439
- import * as path13 from "path";
9738
+ import * as fs14 from "fs";
9739
+ import * as path14 from "path";
9440
9740
  function describeTarget(cwd) {
9441
- const relative16 = path13.relative(process.cwd(), cwd);
9442
- if (relative16 === "") return "this directory";
9443
- if (relative16.startsWith("..") || path13.isAbsolute(relative16)) return cwd;
9444
- return relative16;
9741
+ const relative17 = path14.relative(process.cwd(), cwd);
9742
+ if (relative17 === "") return "this directory";
9743
+ if (relative17.startsWith("..") || path14.isAbsolute(relative17)) return cwd;
9744
+ return relative17;
9445
9745
  }
9446
9746
  function firstRunMessage(reason, cwd) {
9447
9747
  const where = describeTarget(cwd);
@@ -9464,7 +9764,7 @@ function planFirstRun(facts) {
9464
9764
  var NOT_CONTENT = /* @__PURE__ */ new Set([".git", ".hg", ".svn", ".bzr", ".DS_Store", "Thumbs.db"]);
9465
9765
  function isEffectivelyEmpty(cwd) {
9466
9766
  try {
9467
- return fs13.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
9767
+ return fs14.readdirSync(cwd).every((entry) => NOT_CONTENT.has(entry));
9468
9768
  } catch {
9469
9769
  return false;
9470
9770
  }
@@ -9472,7 +9772,7 @@ function isEffectivelyEmpty(cwd) {
9472
9772
  function hasPriorSnapshot(cwd, outDir) {
9473
9773
  let parsed;
9474
9774
  try {
9475
- parsed = JSON.parse(fs13.readFileSync(path13.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
9775
+ parsed = JSON.parse(fs14.readFileSync(path14.join(cwd, outDir, ".codebase-snapshot"), "utf8"));
9476
9776
  } catch {
9477
9777
  return false;
9478
9778
  }
@@ -9742,7 +10042,8 @@ function generateSarifReport(manifest, findings, rules, toolVersion) {
9742
10042
  const results = findings.filter((finding) => typeof finding.path === "string" && finding.path.length > 0).map((finding) => {
9743
10043
  const primary = finding.rules[0] ?? "unknown";
9744
10044
  const line = Math.max(1, finding.line);
9745
- const findingPath = String(finding.path).replace(/\\/g, "/");
10045
+ const rawPath = findSecretInPath(String(finding.path), rules)?.masked ?? String(finding.path);
10046
+ const findingPath = rawPath.replace(/\\/g, "/").split("/").map((segment) => encodeURIComponent(segment)).join("/");
9746
10047
  return {
9747
10048
  ruleId: ruleIdFor(primary),
9748
10049
  ruleIndex: ruleIndex.get(primary) ?? 0,
@@ -10043,14 +10344,16 @@ function fenceIsOpen(text2, fence) {
10043
10344
  }
10044
10345
  var OMISSION_NOTICE_LINE = /^\.\.\. \[\d+ lines omitted: [^\]]*\] \.\.\.$/;
10045
10346
  function applyTruncatedContent(file, content, reason) {
10046
- const keptLines = content.split("\n").filter((line) => !OMISSION_NOTICE_LINE.test(line)).length;
10347
+ const keptLines = content.split("\n").filter(
10348
+ (line) => !OMISSION_NOTICE_LINE.test(line) && line.trim() !== SECTION_TRUNCATION_NOTICE
10349
+ ).length;
10047
10350
  file.content = content;
10048
10351
  file.isPreviewTruncated = true;
10049
10352
  file.inclusionMode = "preview";
10050
10353
  file.truncationReason = reason;
10051
10354
  file.omittedRanges = keptLines >= file.originalLines ? file.originalLines > 0 ? [[file.originalLines, file.originalLines]] : [] : [[keptLines + 1, file.originalLines]];
10052
10355
  file.includedBytes = Buffer.byteLength(content, "utf8");
10053
- file.includedLines = countLines(content);
10356
+ file.includedLines = countBodyLines(content);
10054
10357
  }
10055
10358
  function rehashPart(part, markdown) {
10056
10359
  const estimatedTokens = estimateTokens(markdown.replace(TOKEN_LINE, ""));
@@ -10063,7 +10366,8 @@ function rehashPart(part, markdown) {
10063
10366
  byteSize: Buffer.byteLength(redistributed, "utf8"),
10064
10367
  sha256: crypto4.createHash("sha256").update(redistributed).digest("hex"),
10065
10368
  lines: countLines(redistributed),
10066
- estimatedTokens
10369
+ estimatedTokens,
10370
+ hardClipped: true
10067
10371
  }
10068
10372
  };
10069
10373
  }
@@ -10185,7 +10489,7 @@ function renderFileSection(file) {
10185
10489
  const content = file.content ?? "";
10186
10490
  const body = emittedBody(content);
10187
10491
  file.includedBytes = Buffer.byteLength(body, "utf8");
10188
- file.includedLines = countLines(body);
10492
+ file.includedLines = countBodyLines(body);
10189
10493
  const fence = fenceForContent(content);
10190
10494
  const anchor = anchorForPath(file.relativePath);
10191
10495
  return [
@@ -10239,11 +10543,14 @@ function generateMonolithJson(manifest, filesWithContent) {
10239
10543
  );
10240
10544
  return JSON.stringify({ manifest: embedded, files }, null, 2);
10241
10545
  }
10546
+ function xmlSafe(value) {
10547
+ return value.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]/g, "\uFFFD");
10548
+ }
10242
10549
  function xmlAttribute(value) {
10243
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
10550
+ return xmlSafe(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
10244
10551
  }
10245
10552
  function cdata(value) {
10246
- return "<![CDATA[" + value.replace(/\]\]>/g, "]]]]><![CDATA[>") + "]]>";
10553
+ return "<![CDATA[" + xmlSafe(value).replace(/\]\]>/g, "]]]]><![CDATA[>") + "]]>";
10247
10554
  }
10248
10555
  function generateMonolithXml(manifest, filesWithContent) {
10249
10556
  const files = filesWithContent.map((file) => {
@@ -10344,14 +10651,19 @@ function generateNavigation(manifest) {
10344
10651
  }
10345
10652
 
10346
10653
  // src/generator/selection.ts
10654
+ function cell(value) {
10655
+ return escapeControls(value).replace(/\r?\n/g, " ").replace(/\|/g, "\\|");
10656
+ }
10347
10657
  function generateSelectionReport(manifest, selection) {
10348
10658
  const lines = [];
10349
10659
  lines.push("# Selection");
10350
10660
  lines.push("");
10351
10661
  lines.push("**Kind:** `" + selection.kind + "` ");
10352
- for (const detailLine of selection.detail.split("\n")) {
10353
- lines.push("**" + detailLine.slice(0, detailLine.indexOf(":")) + ":**" + detailLine.slice(detailLine.indexOf(":") + 1) + " ");
10354
- }
10662
+ const detail = selection.detail.replace(/\r?\n/g, " ");
10663
+ const colon = detail.indexOf(":");
10664
+ lines.push(
10665
+ "**" + (colon === -1 ? "Selection" : detail.slice(0, colon)) + ":**" + (colon === -1 ? " " + detail : detail.slice(colon + 1)) + " "
10666
+ );
10355
10667
  lines.push("**Selected files:** " + selection.files.length + " ");
10356
10668
  const spent = manifest.budget?.usedTokens ?? manifest.slice?.usedTokens ?? 0;
10357
10669
  lines.push("**Tokens spent:** " + spent.toLocaleString("en-US"));
@@ -10361,7 +10673,7 @@ function generateSelectionReport(manifest, selection) {
10361
10673
  lines.push("| File | Tokens | Reason |");
10362
10674
  lines.push("| :-- | --: | :-- |");
10363
10675
  for (const file of selection.files) {
10364
- lines.push("| `" + file.path + "` | " + file.tokens.toLocaleString("en-US") + " | " + file.why + " |");
10676
+ lines.push("| `" + cell(file.path) + "` | " + file.tokens.toLocaleString("en-US") + " | " + cell(file.why) + " |");
10365
10677
  }
10366
10678
  lines.push("");
10367
10679
  const dropped = selection.kind === "slice" ? manifest.slice?.dropped : manifest.budget?.dropped;
@@ -10381,7 +10693,7 @@ function generateSelectionReport(manifest, selection) {
10381
10693
  lines.push("| File | Tokens |");
10382
10694
  lines.push("| :-- | --: |");
10383
10695
  for (const item of next) {
10384
- lines.push("| `" + item.path + "` | " + item.tokens.toLocaleString("en-US") + " |");
10696
+ lines.push("| `" + cell(item.path) + "` | " + item.tokens.toLocaleString("en-US") + " |");
10385
10697
  }
10386
10698
  lines.push("");
10387
10699
  }
@@ -10588,7 +10900,9 @@ function planForQuestion(manifest, question, options = {}) {
10588
10900
  notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
10589
10901
  }
10590
10902
  }
10591
- scored.sort((left, right) => right.score - left.score || left.file.relativePath.localeCompare(right.file.relativePath));
10903
+ scored.sort(
10904
+ (left, right) => right.score - left.score || (left.file.relativePath < right.file.relativePath ? -1 : left.file.relativePath > right.file.relativePath ? 1 : 0)
10905
+ );
10592
10906
  const chosen = /* @__PURE__ */ new Map();
10593
10907
  const skipped = [];
10594
10908
  let used = 0;
@@ -10678,25 +10992,112 @@ function formatNumber2(value) {
10678
10992
  // src/generator/diff.ts
10679
10993
  import { spawnSync } from "child_process";
10680
10994
  function runGit(cwd, args) {
10681
- const result = spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true, maxBuffer: 64 * 1024 * 1024 });
10995
+ const result = spawnSync(
10996
+ "git",
10997
+ [
10998
+ "-c",
10999
+ "core.quotepath=false",
11000
+ "-c",
11001
+ "diff.noprefix=false",
11002
+ "-c",
11003
+ "diff.mnemonicPrefix=false",
11004
+ ...args
11005
+ ],
11006
+ { cwd, encoding: "utf8", windowsHide: true, maxBuffer: 64 * 1024 * 1024 }
11007
+ );
10682
11008
  if (result.status !== 0) return { ok: false, out: (result.stderr ?? "").trim() };
10683
11009
  return { ok: true, out: result.stdout ?? "" };
10684
11010
  }
10685
11011
  function isGitRepository(cwd) {
10686
11012
  return runGit(cwd, ["rev-parse", "--is-inside-work-tree"]).out.trim() === "true";
10687
11013
  }
11014
+ function unquoteGitPath(value) {
11015
+ if (!value.startsWith('"') || !value.endsWith('"')) return value;
11016
+ const body = value.slice(1, -1);
11017
+ let out = "";
11018
+ let bytes = [];
11019
+ const flushBytes = () => {
11020
+ if (bytes.length === 0) return;
11021
+ out += Buffer.from(bytes).toString("utf8");
11022
+ bytes = [];
11023
+ };
11024
+ const escapes = {
11025
+ a: "\x07",
11026
+ b: "\b",
11027
+ f: "\f",
11028
+ n: "\n",
11029
+ r: "\r",
11030
+ t: " ",
11031
+ v: "\v",
11032
+ "\\": "\\",
11033
+ '"': '"'
11034
+ };
11035
+ for (let index = 0; index < body.length; index += 1) {
11036
+ const char = body[index];
11037
+ if (char !== "\\") {
11038
+ flushBytes();
11039
+ out += char;
11040
+ continue;
11041
+ }
11042
+ const next = body[index + 1];
11043
+ if (next === void 0) {
11044
+ flushBytes();
11045
+ out += "\\";
11046
+ break;
11047
+ }
11048
+ index += 1;
11049
+ if (/[0-7]/.test(next)) {
11050
+ let octal = next;
11051
+ while (octal.length < 3 && /[0-7]/.test(body[index + 1] ?? "")) {
11052
+ index += 1;
11053
+ octal += body[index];
11054
+ }
11055
+ bytes.push(Number.parseInt(octal, 8) & 255);
11056
+ continue;
11057
+ }
11058
+ flushBytes();
11059
+ out += escapes[next] ?? next;
11060
+ }
11061
+ flushBytes();
11062
+ return out;
11063
+ }
11064
+ function wholeLinePath(value, prefix) {
11065
+ const withoutTimestamp = value.endsWith(" ") ? value.slice(0, -1) : value;
11066
+ const unquoted = unquoteGitPath(withoutTimestamp);
11067
+ if (unquoted === "/dev/null") return null;
11068
+ if (!unquoted.startsWith(prefix)) return null;
11069
+ return unquoted.slice(prefix.length);
11070
+ }
11071
+ function headerPaths(value) {
11072
+ const separator = value.lastIndexOf(" b/");
11073
+ if (separator <= 0) return [];
11074
+ const left = unquoteGitPath(value.slice(0, separator));
11075
+ const right = unquoteGitPath(value.slice(separator + 1));
11076
+ const paths = [];
11077
+ if (left.startsWith("a/")) paths.push(left.slice(2));
11078
+ if (right.startsWith("b/")) paths.push(right.slice(2));
11079
+ return paths;
11080
+ }
10688
11081
  function diffSectionPaths(body) {
10689
11082
  const paths = /* @__PURE__ */ new Set();
11083
+ let header = null;
10690
11084
  for (const line of body.split("\n")) {
10691
- const plus = /^\+\+\+ b\/(.*)$/.exec(line);
10692
- if (plus !== null) paths.add(plus[1]);
10693
- const minus = /^--- a\/(.*)$/.exec(line);
10694
- if (minus !== null) paths.add(minus[1]);
10695
- const header = /^diff --git a\/(.*?) b\/(.*)$/.exec(line);
10696
- if (header !== null) {
10697
- paths.add(header[1]);
10698
- paths.add(header[2]);
11085
+ if (line.startsWith("diff --git ")) {
11086
+ header = line.slice("diff --git ".length);
11087
+ continue;
11088
+ }
11089
+ if (line.startsWith("+++ ")) {
11090
+ const path28 = wholeLinePath(line.slice(4), "b/");
11091
+ if (path28 !== null) paths.add(path28);
11092
+ continue;
10699
11093
  }
11094
+ if (line.startsWith("--- ")) {
11095
+ const path28 = wholeLinePath(line.slice(4), "a/");
11096
+ if (path28 !== null) paths.add(path28);
11097
+ }
11098
+ }
11099
+ if (paths.size === 0 && header !== null) {
11100
+ for (const path28 of headerPaths(header)) paths.add(path28);
10700
11101
  }
10701
11102
  return [...paths];
10702
11103
  }
@@ -10706,6 +11107,7 @@ function generateDiffReport(cwd, options = {}) {
10706
11107
  const sections = [];
10707
11108
  let truncated = false;
10708
11109
  let omittedSensitive = 0;
11110
+ let omittedUnparseable = 0;
10709
11111
  const commands = [
10710
11112
  ["Unstaged", ["diff", "--no-color"]],
10711
11113
  ["Staged", ["diff", "--cached", "--no-color"]]
@@ -10716,6 +11118,10 @@ function generateDiffReport(cwd, options = {}) {
10716
11118
  const rawSections = result.out.split(/(?=^diff --git )/m).filter((section) => section.length > 0);
10717
11119
  for (const rawSection of rawSections) {
10718
11120
  const paths2 = diffSectionPaths(rawSection);
11121
+ if (paths2.length === 0) {
11122
+ omittedUnparseable += 1;
11123
+ continue;
11124
+ }
10719
11125
  const blocked = paths2.some((path28) => isSensitivePath(path28) || options.excluded?.(path28) === true);
10720
11126
  if (blocked) {
10721
11127
  omittedSensitive += 1;
@@ -10727,7 +11133,13 @@ function generateDiffReport(cwd, options = {}) {
10727
11133
  truncated = true;
10728
11134
  break;
10729
11135
  }
10730
- const chunk = truncateToBytes(rawSection, remaining);
11136
+ const sourcePath = paths2[0] ?? "reports/diff.md";
11137
+ const redactedSection = scanAndRedactSecrets(
11138
+ rawSection,
11139
+ options.secretRules ?? [],
11140
+ sourcePath
11141
+ ).redacted;
11142
+ const chunk = truncateToBytes(redactedSection, remaining);
10731
11143
  if (chunk.isTruncated) truncated = true;
10732
11144
  sections.push(
10733
11145
  "## " + title + " changes\n\nRun: git " + args.join(" ") + "\n\n```diff\n" + chunk.content + "\n```"
@@ -10748,6 +11160,10 @@ function generateDiffReport(cwd, options = {}) {
10748
11160
  "> " + omittedSensitive + " file section(s) omitted: their path is credential-bearing or excluded from the snapshot.",
10749
11161
  ""
10750
11162
  ] : [],
11163
+ ...omittedUnparseable > 0 ? [
11164
+ "> " + omittedUnparseable + " file section(s) omitted: their diff header could not be attributed to a path, so the sensitive-path filter could not run.",
11165
+ ""
11166
+ ] : [],
10751
11167
  ...sections,
10752
11168
  ...truncated ? ["", "> Truncated at " + maxBytes + " bytes. Run git diff for the rest."] : [],
10753
11169
  ""
@@ -10786,28 +11202,39 @@ function generateLogReport(cwd, options = {}) {
10786
11202
  }
10787
11203
 
10788
11204
  // src/generator/tokens.ts
11205
+ function cell2(value) {
11206
+ return escapeControls(value).replace(/\r?\n/g, " ").replace(/\|/g, "\\|");
11207
+ }
11208
+ function byCodeUnit(left, right) {
11209
+ return left < right ? -1 : left > right ? 1 : 0;
11210
+ }
10789
11211
  function tokensOf2(bytes) {
10790
11212
  return Math.max(1, Math.ceil(bytes * 0.25));
10791
11213
  }
10792
11214
  function generateTokenTree(manifest) {
10793
11215
  if (manifest.files.length === 0) return null;
10794
- 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));
11216
+ 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));
10795
11217
  const byDirectory = /* @__PURE__ */ new Map();
10796
11218
  for (const row of rows) {
10797
11219
  const directory = row.path.includes("/") ? row.path.slice(0, row.path.lastIndexOf("/")) : ".";
10798
11220
  byDirectory.set(directory, (byDirectory.get(directory) ?? 0) + row.tokens);
10799
11221
  }
10800
- const directories = [...byDirectory.entries()].sort((left, right) => right[1] - left[1]);
11222
+ const directories = [...byDirectory.entries()].sort(
11223
+ (left, right) => right[1] - left[1] || byCodeUnit(left[0], right[0])
11224
+ );
10801
11225
  const total = rows.reduce((sum, row) => sum + row.tokens, 0);
10802
- const rowsTable = rows.map((row) => "| " + row.path + " | " + row.layer + " | " + row.part + " | " + row.tokens + " |");
11226
+ const rowsTable = rows.map(
11227
+ (row) => "| " + cell2(row.path) + " | " + cell2(row.layer) + " | " + cell2(row.part) + " | " + row.tokens + " |"
11228
+ );
10803
11229
  const directoryTable = directories.map(
10804
- (entry) => "| " + entry[0] + " | " + entry[1] + " | " + (entry[1] / total * 100).toFixed(1) + "% |"
11230
+ (entry) => "| " + cell2(entry[0]) + " | " + entry[1] + " | " + (entry[1] / total * 100).toFixed(1) + "% |"
10805
11231
  );
10806
11232
  const text2 = [
10807
11233
  "# Token tree",
10808
11234
  "",
10809
- "Estimated tokens per file (one token per four bytes of emitted body), sorted by cost. The total",
10810
- "is the same estimate the manifest carries: an estimate, not a count.",
11235
+ "Estimated tokens per file (one token per four bytes of emitted body), sorted by cost. Each",
11236
+ "row is an estimate; the manifest total is estimated from the assembled parts, so the two can",
11237
+ "differ slightly and neither is a tokenizer count.",
10811
11238
  "",
10812
11239
  "## Directories",
10813
11240
  "",
@@ -11009,7 +11436,9 @@ function systemSection(manifest, code, brief, escape, sawManifest) {
11009
11436
  if (brief?.system !== void 0) {
11010
11437
  out.push(...ownerBlock(brief.system, brief.path, code, escape), "", "What the index records:", "");
11011
11438
  }
11012
- const layers = Object.entries(manifest.layers).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
11439
+ const layers = Object.entries(manifest.layers).sort(
11440
+ (a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)
11441
+ );
11013
11442
  if (layers.length > 0) {
11014
11443
  const shown = layers.slice(0, MAX_LAYER_ROWS).map(([name, count]) => code(name) + " " + formatNumber(count));
11015
11444
  const rest = layers.length > MAX_LAYER_ROWS ? ", and " + formatNumber(layers.length - MAX_LAYER_ROWS) + " more" : "";
@@ -11127,7 +11556,7 @@ function coverageSection(manifest, code, auditWritten, partsWritten, sawManifest
11127
11556
  for (const record of manifest.skipped) {
11128
11557
  reasons.set(record.reason, (reasons.get(record.reason) ?? 0) + 1);
11129
11558
  }
11130
- const tally = [...reasons.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([reason, count]) => code(reason) + " " + formatNumber(count)).join(", ");
11559
+ 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(", ");
11131
11560
  const found = manifest.totals.candidateFiles;
11132
11561
  const included = manifest.totals.includedFiles;
11133
11562
  const skipped = manifest.counts.skippedCount;
@@ -11254,7 +11683,7 @@ function ownerNotesSection(brief, code, text2) {
11254
11683
  if (brief === void 0 || brief.notes.length === 0) return [];
11255
11684
  const out = ["## Owner notes", ""];
11256
11685
  for (const note of brief.notes) {
11257
- out.push("### " + note.heading, "", ...ownerBlock(note.body, brief.path, code, text2), "");
11686
+ out.push("### " + text2(note.heading), "", ...ownerBlock(note.body, brief.path, code, text2), "");
11258
11687
  }
11259
11688
  return out;
11260
11689
  }
@@ -11475,27 +11904,31 @@ function generateReadme(manifest, artifacts) {
11475
11904
  const readOrder = [];
11476
11905
  if (wrote("prompt")) {
11477
11906
  readOrder.push(
11478
- "1. Hand `PROMPT.md` to the model that receives this snapshot: it names the parts, the partial files and the fingerprint of this run."
11907
+ "Hand `PROMPT.md` to the model that receives this snapshot: it names the parts, the partial files and the fingerprint of this run."
11479
11908
  );
11480
11909
  }
11481
11910
  if (wrote("navigation") || wrote("projectTree")) {
11482
11911
  const first = [wrote("navigation") ? "`reports/navigation.md`" : null, wrote("projectTree") ? "`reports/project-tree.md`" : null].filter(Boolean).join(" or ");
11483
- readOrder.push(`1. Read ${first} first to locate target features or files.`);
11912
+ readOrder.push(`Read ${first} first to locate target features or files.`);
11484
11913
  }
11485
11914
  if (wrote("parts")) {
11486
11915
  readOrder.push(
11487
- `${readOrder.length + 1}. Open only the specific \`parts/part-XXX.md\` file holding the target modules.`
11916
+ "Open only the specific `parts/part-XXX.md` file holding the target modules."
11488
11917
  );
11489
11918
  }
11490
11919
  if (wrote("manifest")) {
11491
- readOrder.push(
11492
- `${readOrder.length + 1}. Inspect \`manifest.json\` for precise dependency and AST symbol maps.`
11493
- );
11920
+ readOrder.push("Inspect `manifest.json` for precise dependency and AST symbol maps.");
11494
11921
  }
11495
11922
  readOrder.push(
11496
- wrote("manifest") ? `${readOrder.length + 1}. Check \`manifest.validation.status\` before trusting the snapshot; \`snapshot validate\` re-checks it against disk.` : `${readOrder.length + 1}. No manifest was written, so this snapshot cannot be re-checked; regenerate with the manifest artifact enabled before trusting it.`
11923
+ 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."
11924
+ );
11925
+ lines.push(
11926
+ "",
11927
+ "## AI Agent Ingestion Guide",
11928
+ "",
11929
+ ...readOrder.map((step, index) => `${index + 1}. ${step}`),
11930
+ ""
11497
11931
  );
11498
- lines.push("", "## AI Agent Ingestion Guide", "", ...readOrder, "");
11499
11932
  return lines.join("\n");
11500
11933
  }
11501
11934
 
@@ -11584,8 +12017,6 @@ function treeTruncationWarnings(treeText) {
11584
12017
  }
11585
12018
 
11586
12019
  // src/generator/overview.ts
11587
- import * as fs14 from "fs";
11588
- import * as path14 from "path";
11589
12020
  var SUMMARY_LIMIT = 400;
11590
12021
  var MAX_RELEASES = 2;
11591
12022
  function readProjectOverview(cwd) {
@@ -11595,15 +12026,12 @@ function readProjectOverview(cwd) {
11595
12026
  releases: readReleases(cwd)
11596
12027
  };
11597
12028
  }
11598
- function readText(file) {
11599
- try {
11600
- return fs14.readFileSync(file, "utf8");
11601
- } catch {
11602
- return null;
11603
- }
12029
+ function readText(cwd, relative17) {
12030
+ const read = readConfinedText(cwd, relative17);
12031
+ return read.ok ? read.text : null;
11604
12032
  }
11605
12033
  function readDescription(cwd) {
11606
- const raw = readText(path14.join(cwd, "package.json"));
12034
+ const raw = readText(cwd, "package.json");
11607
12035
  if (raw === null) return {};
11608
12036
  try {
11609
12037
  const parsed = JSON.parse(stripJsonComments(raw));
@@ -11613,7 +12041,7 @@ function readDescription(cwd) {
11613
12041
  }
11614
12042
  }
11615
12043
  function readSummary(cwd) {
11616
- const raw = readText(path14.join(cwd, "README.md"));
12044
+ const raw = readText(cwd, "README.md");
11617
12045
  if (raw === null) return {};
11618
12046
  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, "'");
11619
12047
  const paragraph = [];
@@ -11639,7 +12067,7 @@ function truncate(text2, limit) {
11639
12067
  return (space > limit / 2 ? window.slice(0, space) : window).trim() + "\u2026";
11640
12068
  }
11641
12069
  function readReleases(cwd) {
11642
- const raw = readText(path14.join(cwd, "CHANGELOG.md"));
12070
+ const raw = readText(cwd, "CHANGELOG.md");
11643
12071
  if (raw === null) return [];
11644
12072
  const headings = raw.split(/\r?\n/).map((line) => /^##\s+(.+?)\s*$/.exec(line)?.[1]?.trim()).filter((heading) => heading !== void 0 && /^v?\d+\.\d+/.test(heading));
11645
12073
  return headings.slice(0, MAX_RELEASES);
@@ -11726,9 +12154,11 @@ function isPrivateIPv6(groups) {
11726
12154
  ]);
11727
12155
  if (allZeroThrough(5) && sixth === 65535) return mapped(6);
11728
12156
  if (allZeroThrough(6) && (seventh !== 0 || eighth !== 0)) return mapped(6);
12157
+ if (allZeroThrough(4) && fifth === 65535 && sixth === 0) return mapped(6);
11729
12158
  if (first === 100 && second === 65435 && third === 0 && fourth === 0 && fifth === 0 && sixth === 0) {
11730
12159
  return mapped(6);
11731
12160
  }
12161
+ if (first === 100 && second === 65435 && third === 1) return mapped(6);
11732
12162
  if (first === 8194) return mapped(1);
11733
12163
  return false;
11734
12164
  }
@@ -11842,61 +12272,69 @@ async function cloneRepository(source, options) {
11842
12272
  const dest = path15.resolve(options.dest);
11843
12273
  fs15.rmSync(dest, { recursive: true, force: true });
11844
12274
  fs15.mkdirSync(dest, { recursive: true });
11845
- const ref = options.ref ?? source.ref;
11846
- const args = [
11847
- "-c",
11848
- "http.followRedirects=false",
11849
- ...source.kind === "https" ? ["-c", "protocol.file.allow=never", "-c", "protocol.ssh.allow=never"] : [],
11850
- "clone",
11851
- "--depth",
11852
- "1",
11853
- "--single-branch",
11854
- "--no-tags",
11855
- "--quiet"
11856
- ];
11857
- if (ref !== void 0 && ref !== null && ref !== "") {
11858
- args.push("--branch", ref);
11859
- }
11860
- args.push(source.url, dest);
11861
- log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
11862
- const started = Date.now();
11863
- const result = spawnSync3("git", args, {
11864
- env: {
11865
- ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
11866
- ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
11867
- },
11868
- timeout: options.timeoutMs ?? 18e4,
11869
- encoding: "utf8",
11870
- windowsHide: true
11871
- });
11872
- if (result.error !== void 0 && result.error !== null) {
11873
- throw new Error("git clone could not run: " + result.error.message);
11874
- }
11875
- if (result.status !== 0) {
11876
- const detail = (result.stderr ?? "").trim().split("\n").slice(-3).join(" ");
11877
- throw new Error("git clone failed (exit " + result.status + "): " + (detail || "no output"));
11878
- }
11879
- const head = spawnSync3("git", ["-C", dest, "rev-parse", "HEAD"], { encoding: "utf8", windowsHide: true });
11880
- const commit = head.status === 0 ? (head.stdout ?? "").trim() : "";
11881
- if (commit === "") throw new Error("the clone has no HEAD; refusing to describe it");
11882
- const bytes = directorySize(dest);
11883
- log("clone: " + (bytes / 1024 / 1024).toFixed(1) + " MB in " + ((Date.now() - started) / 1e3).toFixed(1) + "s");
11884
- if (bytes > 1e9) {
11885
- throw new Error("the clone is larger than 1 GB (" + Math.round(bytes / 1024 / 1024) + " MB); refusing to scan it");
11886
- }
11887
- return {
11888
- directory: dest,
11889
- commit,
11890
- provenance: {
11891
- url: source.url,
11892
- host: source.host,
11893
- owner: source.owner,
11894
- repo: source.repo,
11895
- ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
12275
+ try {
12276
+ const ref = options.ref ?? source.ref;
12277
+ const args = [
12278
+ "-c",
12279
+ "http.followRedirects=false",
12280
+ ...source.kind === "https" ? ["-c", "protocol.file.allow=never", "-c", "protocol.ssh.allow=never"] : [],
12281
+ "clone",
12282
+ "--depth",
12283
+ "1",
12284
+ "--single-branch",
12285
+ "--no-tags",
12286
+ "--quiet"
12287
+ ];
12288
+ if (ref !== void 0 && ref !== null && ref !== "") {
12289
+ args.push("--branch", ref);
12290
+ }
12291
+ args.push(source.url, dest);
12292
+ log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
12293
+ const started = Date.now();
12294
+ const result = spawnSync3("git", args, {
12295
+ env: {
12296
+ ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
12297
+ ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
12298
+ },
12299
+ timeout: options.timeoutMs ?? 18e4,
12300
+ encoding: "utf8",
12301
+ windowsHide: true
12302
+ });
12303
+ if (result.error !== void 0 && result.error !== null) {
12304
+ throw new Error("git clone could not run: " + result.error.message);
12305
+ }
12306
+ if (result.status !== 0) {
12307
+ const detail = (result.stderr ?? "").trim().split("\n").slice(-3).join(" ");
12308
+ throw new Error("git clone failed (exit " + result.status + "): " + (detail || "no output"));
12309
+ }
12310
+ const head = spawnSync3("git", ["-C", dest, "rev-parse", "HEAD"], { encoding: "utf8", windowsHide: true });
12311
+ const commit = head.status === 0 ? (head.stdout ?? "").trim() : "";
12312
+ if (commit === "") throw new Error("the clone has no HEAD; refusing to describe it");
12313
+ const bytes = directorySize(dest);
12314
+ log("clone: " + (bytes / 1024 / 1024).toFixed(1) + " MB in " + ((Date.now() - started) / 1e3).toFixed(1) + "s");
12315
+ if (bytes > 1e9) {
12316
+ throw new Error("the clone is larger than 1 GB (" + Math.round(bytes / 1024 / 1024) + " MB); refusing to scan it");
12317
+ }
12318
+ return {
12319
+ directory: dest,
11896
12320
  commit,
11897
- fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
12321
+ provenance: {
12322
+ url: source.url,
12323
+ host: source.host,
12324
+ owner: source.owner,
12325
+ repo: source.repo,
12326
+ ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
12327
+ commit,
12328
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
12329
+ }
12330
+ };
12331
+ } catch (error) {
12332
+ try {
12333
+ fs15.rmSync(dest, { recursive: true, force: true });
12334
+ } catch {
11898
12335
  }
11899
- };
12336
+ throw error;
12337
+ }
11900
12338
  }
11901
12339
  function directorySize(root) {
11902
12340
  let total = 0;
@@ -12144,7 +12582,7 @@ import * as path19 from "path";
12144
12582
  import * as fs16 from "fs";
12145
12583
  import * as path16 from "path";
12146
12584
  import { execFileSync as execFileSync3 } from "child_process";
12147
- import { createHash as createHash7 } from "crypto";
12585
+ import { createHash as createHash8 } from "crypto";
12148
12586
 
12149
12587
  // src/partitioner/part-format.ts
12150
12588
  var FILE_HEADING = "### FILE: ";
@@ -12153,7 +12591,7 @@ var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
12153
12591
  var META_PREFIX = "- Meta: ";
12154
12592
  var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
12155
12593
  var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
12156
- var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
12594
+ var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures", "comments-stripped"]);
12157
12595
  var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
12158
12596
  function readIncludedLines(fields) {
12159
12597
  const last = fields[fields.length - 1];
@@ -12248,16 +12686,9 @@ var ARTIFACT_FILES = {
12248
12686
  fullXml: "full-codebase.xml",
12249
12687
  sarif: "reports/audit.sarif"
12250
12688
  };
12251
- var TEXT_ARTIFACT = /\.(md|json|txt|sarif)$/i;
12689
+ var TEXT_ARTIFACT = /\.(md|json|txt|sarif|xml)$/i;
12252
12690
  function sha256(buffer) {
12253
- return createHash7("sha256").update(buffer).digest("hex");
12254
- }
12255
- function readBytes(file) {
12256
- try {
12257
- return fs16.readFileSync(file);
12258
- } catch {
12259
- return null;
12260
- }
12691
+ return createHash8("sha256").update(buffer).digest("hex");
12261
12692
  }
12262
12693
  function readText2(file) {
12263
12694
  try {
@@ -12266,8 +12697,17 @@ function readText2(file) {
12266
12697
  return null;
12267
12698
  }
12268
12699
  }
12700
+ function snapshotText(snapshotDir, relative17) {
12701
+ const read = readConfinedText(snapshotDir, relative17);
12702
+ return read.ok ? read.text : null;
12703
+ }
12704
+ function snapshotBytes(snapshotDir, relative17) {
12705
+ const read = readConfinedBytes(snapshotDir, relative17);
12706
+ return read.ok ? read.bytes : null;
12707
+ }
12269
12708
  function readJson(file) {
12270
- const text2 = readText2(file);
12709
+ const confined = readConfinedText(path16.dirname(file), path16.basename(file));
12710
+ const text2 = confined.ok ? confined.text : null;
12271
12711
  if (text2 === null) return null;
12272
12712
  try {
12273
12713
  return JSON.parse(text2);
@@ -12284,9 +12724,9 @@ function walk(dir, prefix = "") {
12284
12724
  }
12285
12725
  const files = [];
12286
12726
  for (const entry of entries) {
12287
- const relative16 = prefix === "" ? entry.name : prefix + "/" + entry.name;
12288
- if (entry.isDirectory()) files.push(...walk(path16.join(dir, entry.name), relative16));
12289
- else if (entry.isFile()) files.push(relative16);
12727
+ const relative17 = prefix === "" ? entry.name : prefix + "/" + entry.name;
12728
+ if (entry.isDirectory()) files.push(...walk(path16.join(dir, entry.name), relative17));
12729
+ else if (entry.isFile()) files.push(relative17);
12290
12730
  }
12291
12731
  return files;
12292
12732
  }
@@ -12324,16 +12764,28 @@ function secretTokens(text2) {
12324
12764
  }
12325
12765
  return [...tokens];
12326
12766
  }
12327
- function readArtifactTexts(snapshotDir) {
12767
+ function readArtifactTexts(snapshotDir, maxBytes = 32 * 1024 * 1024) {
12328
12768
  const texts = [];
12329
- for (const relative16 of walk(snapshotDir)) {
12330
- if (!TEXT_ARTIFACT.test(relative16)) continue;
12331
- const text2 = readText2(path16.join(snapshotDir, relative16));
12332
- if (text2 !== null) texts.push(text2);
12769
+ let bytes = 0;
12770
+ for (const relative17 of walk(snapshotDir)) {
12771
+ if (!TEXT_ARTIFACT.test(relative17)) continue;
12772
+ const full = path16.join(snapshotDir, relative17);
12773
+ let size2;
12774
+ try {
12775
+ size2 = fs16.statSync(full).size;
12776
+ } catch {
12777
+ continue;
12778
+ }
12779
+ if (bytes + size2 > maxBytes) break;
12780
+ const text2 = snapshotText(snapshotDir, relative17);
12781
+ if (text2 !== null) {
12782
+ texts.push(text2);
12783
+ bytes += Buffer.byteLength(text2, "utf8");
12784
+ }
12333
12785
  }
12334
12786
  return texts;
12335
12787
  }
12336
- function findHostPaths(snapshotDir, repoDir) {
12788
+ function findHostPaths(snapshotDir, repoDir, maxBytes = 32 * 1024 * 1024) {
12337
12789
  const patterns = [
12338
12790
  /\/home\/[A-Za-z0-9._-]+/g,
12339
12791
  /\/Users\/[A-Za-z0-9._-]+/g,
@@ -12344,15 +12796,24 @@ function findHostPaths(snapshotDir, repoDir) {
12344
12796
  ];
12345
12797
  const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
12346
12798
  const hits = /* @__PURE__ */ new Set();
12347
- for (const relative16 of walk(snapshotDir)) {
12348
- if (!TEXT_ARTIFACT.test(relative16)) continue;
12349
- const text2 = readText2(path16.join(snapshotDir, relative16));
12799
+ let scanned = 0;
12800
+ for (const relative17 of walk(snapshotDir)) {
12801
+ if (!TEXT_ARTIFACT.test(relative17)) continue;
12802
+ let size2;
12803
+ try {
12804
+ size2 = fs16.statSync(path16.join(snapshotDir, relative17)).size;
12805
+ } catch {
12806
+ continue;
12807
+ }
12808
+ if (scanned + size2 > maxBytes) break;
12809
+ const text2 = snapshotText(snapshotDir, relative17);
12350
12810
  if (text2 === null) continue;
12811
+ scanned += Buffer.byteLength(text2, "utf8");
12351
12812
  for (const pattern of patterns) {
12352
- for (const match of text2.match(pattern) ?? []) hits.add(relative16 + ": " + match);
12813
+ for (const match of text2.match(pattern) ?? []) hits.add(relative17 + ": " + match);
12353
12814
  }
12354
12815
  repoPattern.lastIndex = 0;
12355
- if (repoPattern.test(text2)) hits.add(relative16 + ": the repository absolute path");
12816
+ if (repoPattern.test(text2)) hits.add(relative17 + ": the repository absolute path");
12356
12817
  }
12357
12818
  return [...hits];
12358
12819
  }
@@ -12534,7 +12995,7 @@ function auditSnapshot(options) {
12534
12995
  const missingParts = [];
12535
12996
  const mismatched = [];
12536
12997
  for (const part of manifest.parts) {
12537
- const bytes = readBytes(path16.join(snapshotDir, "parts", part.filename));
12998
+ const bytes = snapshotBytes(snapshotDir, "parts/" + part.filename);
12538
12999
  if (bytes === null) {
12539
13000
  missingParts.push(part.filename);
12540
13001
  continue;
@@ -12599,13 +13060,13 @@ function auditSnapshot(options) {
12599
13060
  let artifactCount = 0;
12600
13061
  for (const [key, value] of Object.entries(artifacts)) {
12601
13062
  if (value === null || value === void 0) continue;
12602
- const relative16 = ARTIFACT_FILES[key];
12603
- if (relative16 === void 0) continue;
13063
+ const relative17 = ARTIFACT_FILES[key];
13064
+ if (relative17 === void 0) continue;
12604
13065
  artifactCount += 1;
12605
- const bytes = readBytes(path16.join(snapshotDir, relative16));
12606
- if (bytes === null) artifactProblems.push(relative16 + " is missing");
13066
+ const bytes = snapshotBytes(snapshotDir, relative17);
13067
+ if (bytes === null) artifactProblems.push(relative17 + " is missing");
12607
13068
  else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
12608
- artifactProblems.push(relative16 + " changed");
13069
+ artifactProblems.push(relative17 + " changed");
12609
13070
  }
12610
13071
  }
12611
13072
  checks.push(
@@ -12715,7 +13176,7 @@ function auditSnapshot(options) {
12715
13176
  manifest.files.map((file) => [anchorForPath(file.relativePath), file.relativePath])
12716
13177
  );
12717
13178
  for (const part of manifest.parts) {
12718
- const partText = readText2(path16.join(snapshotDir, "parts", part.filename));
13179
+ const partText = snapshotText(snapshotDir, "parts/" + part.filename);
12719
13180
  if (partText === null) continue;
12720
13181
  const sections = parsePartSections(partText);
12721
13182
  partTexts.set(part.filename, partText);
@@ -12782,7 +13243,7 @@ function auditSnapshot(options) {
12782
13243
  }
12783
13244
  };
12784
13245
  if (manifest.artifacts?.readme != null) {
12785
- const text2 = readText2(path16.join(snapshotDir, "README.md"));
13246
+ const text2 = snapshotText(snapshotDir, "README.md");
12786
13247
  if (text2 === null) {
12787
13248
  reportProblems.push("README.md is recorded but unreadable");
12788
13249
  } else {
@@ -12822,7 +13283,7 @@ function auditSnapshot(options) {
12822
13283
  }
12823
13284
  }
12824
13285
  if (manifest.artifacts?.prompt != null) {
12825
- const text2 = readText2(path16.join(snapshotDir, "PROMPT.md"));
13286
+ const text2 = snapshotText(snapshotDir, "PROMPT.md");
12826
13287
  if (text2 === null) {
12827
13288
  reportProblems.push("PROMPT.md is recorded but unreadable");
12828
13289
  } else {
@@ -13011,7 +13472,7 @@ function auditSnapshot(options) {
13011
13472
  ];
13012
13473
  for (const reader of packReaders) {
13013
13474
  if (manifest.artifacts?.[reader.key] == null) continue;
13014
- const packText = readText2(path16.join(snapshotDir, reader.file));
13475
+ const packText = snapshotText(snapshotDir, reader.file);
13015
13476
  const problems = [];
13016
13477
  if (packText === null) {
13017
13478
  problems.push(reader.file + " is recorded but unreadable");
@@ -13061,7 +13522,7 @@ function auditSnapshot(options) {
13061
13522
  bodyByPath.set(file.relativePath, section.body);
13062
13523
  bodiesChecked += 1;
13063
13524
  const bytes = Buffer.byteLength(section.body, "utf8");
13064
- const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
13525
+ const bodyLines = countBodyLines(section.body);
13065
13526
  if (bytes !== file.includedBytes) {
13066
13527
  bodyProblems.push(file.relativePath + ": manifest says " + file.includedBytes + " B, part holds " + bytes + " B");
13067
13528
  } else if (bodyLines !== file.includedLines) {
@@ -13174,7 +13635,7 @@ function auditSnapshot(options) {
13174
13635
  let packBodies = 0;
13175
13636
  let packSkipped = 0;
13176
13637
  for (const pack of packsWanted) {
13177
- const text2 = readText2(path16.join(snapshotDir, pack.file));
13638
+ const text2 = snapshotText(snapshotDir, pack.file);
13178
13639
  if (text2 === null) continue;
13179
13640
  const bodies = pack.read(text2);
13180
13641
  if (bodies === null) {
@@ -13238,7 +13699,8 @@ function auditSnapshot(options) {
13238
13699
  unreplayable += 1;
13239
13700
  continue;
13240
13701
  }
13241
- const bytes = readBytes(path16.join(repoDir, file.relativePath));
13702
+ const repoBytes = readConfinedBytes(repoDir, file.relativePath);
13703
+ const bytes = repoBytes.ok ? repoBytes.bytes : null;
13242
13704
  if (bytes === null || sha256(bytes) !== file.hashSha256) {
13243
13705
  unreplayable += 1;
13244
13706
  continue;
@@ -13335,30 +13797,37 @@ function auditSnapshot(options) {
13335
13797
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
13336
13798
  const leakHits = [];
13337
13799
  let scannedBytes = 0;
13338
- for (const relative16 of walk(snapshotDir)) {
13339
- if (!TEXT_ARTIFACT.test(relative16) || scannedBytes > scanBudget) continue;
13340
- if (relative16 === SIGNATURE_FILE) continue;
13341
- const text2 = readText2(path16.join(snapshotDir, relative16));
13800
+ for (const relative17 of walk(snapshotDir)) {
13801
+ if (!TEXT_ARTIFACT.test(relative17) || scannedBytes > scanBudget) continue;
13802
+ if (relative17 === SIGNATURE_FILE) continue;
13803
+ let size2;
13804
+ try {
13805
+ size2 = fs16.statSync(path16.join(snapshotDir, relative17)).size;
13806
+ } catch {
13807
+ continue;
13808
+ }
13809
+ if (scannedBytes + size2 > scanBudget) break;
13810
+ const text2 = snapshotText(snapshotDir, relative17);
13342
13811
  if (text2 === null) continue;
13343
13812
  scannedBytes += Buffer.byteLength(text2, "utf8");
13344
13813
  let findingCount = 0;
13345
- if (/^parts[\\/].*\.md$/i.test(relative16)) {
13814
+ if (/^parts[\\/].*\.md$/i.test(relative17)) {
13346
13815
  let headerText = text2;
13347
13816
  for (const section of parsePartSections(text2)) {
13348
13817
  findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
13349
13818
  headerText = headerText.replace(section.body, "");
13350
13819
  }
13351
- findingCount += scanAndRedactSecrets(headerText, rules, relative16).findings.length;
13820
+ findingCount += scanAndRedactSecrets(headerText, rules, relative17).findings.length;
13352
13821
  } else {
13353
- findingCount = scanAndRedactSecrets(text2, rules, relative16).findings.length;
13822
+ findingCount = scanAndRedactSecrets(text2, rules, relative17).findings.length;
13354
13823
  }
13355
13824
  if (findingCount > 0) {
13356
- leakHits.push(relative16 + " (" + findingCount + " line(s))");
13825
+ leakHits.push(relative17 + " (" + findingCount + " line(s))");
13357
13826
  }
13358
13827
  }
13359
13828
  const signatureRecordPath = path16.join(snapshotDir, SIGNATURE_FILE);
13360
13829
  if (fs16.existsSync(signatureRecordPath)) {
13361
- const recordText = readText2(signatureRecordPath);
13830
+ const recordText = snapshotText(snapshotDir, SIGNATURE_FILE);
13362
13831
  if (recordText !== null) {
13363
13832
  scannedBytes += Buffer.byteLength(recordText, "utf8");
13364
13833
  let scanText = recordText;
@@ -13398,11 +13867,17 @@ function auditSnapshot(options) {
13398
13867
  );
13399
13868
  const leakedFrom = [];
13400
13869
  let compared = 0;
13401
- const artifactTexts = readArtifactTexts(snapshotDir);
13870
+ const artifactTexts = readArtifactTexts(snapshotDir, scanBudget);
13402
13871
  const artifactContains = (token) => artifactTexts.some((text2) => text2.includes(token));
13403
13872
  for (const record of skippedSensitive.slice(0, 40)) {
13404
13873
  if (record.path.includes("[REDACTED") || compared > 400) continue;
13405
- const text2 = readText2(path16.join(repoDir, record.path));
13874
+ try {
13875
+ if (fs16.statSync(path16.join(repoDir, record.path)).size > scanBudget) continue;
13876
+ } catch {
13877
+ continue;
13878
+ }
13879
+ const repoRead = readConfinedText(repoDir, record.path);
13880
+ const text2 = repoRead.ok ? repoRead.text : null;
13406
13881
  if (text2 === null) continue;
13407
13882
  for (const token of secretTokens(text2)) {
13408
13883
  compared += 1;
@@ -13424,7 +13899,7 @@ function auditSnapshot(options) {
13424
13899
  "A value from " + sample([...new Set(leakedFrom)]) + " appears in the snapshot."
13425
13900
  )
13426
13901
  );
13427
- const pii = findHostPaths(snapshotDir, repoDir);
13902
+ const pii = findHostPaths(snapshotDir, repoDir, scanBudget);
13428
13903
  checks.push(
13429
13904
  pii.length === 0 ? check(
13430
13905
  "pii.paths",
@@ -13560,7 +14035,10 @@ const { parentPort, workerData } = require("node:worker_threads");
13560
14035
  (async () => {
13561
14036
  try {
13562
14037
  const mod = await import(workerData.entryUrl);
13563
- const loaded = await mod.loadConfigFileDetailed(workerData.cwd);
14038
+ const loaded =
14039
+ workerData.config === null || workerData.config === undefined
14040
+ ? await mod.loadConfigFileDetailed(workerData.cwd, { allowExecutableConfig: false })
14041
+ : { config: workerData.config, errors: [] };
13564
14042
  if (loaded.errors.length > 0) {
13565
14043
  parentPort.postMessage({ ok: false, message: loaded.errors.join("; ") });
13566
14044
  return;
@@ -13572,6 +14050,7 @@ const { parentPort, workerData } = require("node:worker_threads");
13572
14050
  const manifest = mod.generateSnapshot(config, {
13573
14051
  dryRun: workerData.dryRun === true,
13574
14052
  ...(workerData.narrow ?? {}),
14053
+ ...(workerData.source === undefined ? {} : { source: workerData.source }),
13575
14054
  ...(workerData.runId === undefined ? {} : { runId: workerData.runId }),
13576
14055
  });
13577
14056
  const skipCounts = new Map();
@@ -13612,7 +14091,7 @@ const { parentPort, workerData } = require("node:worker_threads");
13612
14091
  })();
13613
14092
  `;
13614
14093
  function generateInWorker(cwd, cliOptions, options = {}) {
13615
- return new Promise((resolve15) => {
14094
+ return new Promise((resolve16) => {
13616
14095
  let settled = false;
13617
14096
  let worker = null;
13618
14097
  const finish = (result) => {
@@ -13623,7 +14102,7 @@ function generateInWorker(cwd, cliOptions, options = {}) {
13623
14102
  if (!result.ok && options.runId !== void 0 && options.lockRoots !== void 0) {
13624
14103
  releaseAbandonedRun(options.lockRoots, options.runId);
13625
14104
  }
13626
- resolve15(result);
14105
+ resolve16(result);
13627
14106
  });
13628
14107
  };
13629
14108
  const isCjs = typeof __dirname !== "undefined";
@@ -13637,6 +14116,8 @@ function generateInWorker(cwd, cliOptions, options = {}) {
13637
14116
  cliOptions,
13638
14117
  dryRun: options.dryRun === true,
13639
14118
  narrow: options.narrow ?? {},
14119
+ ...options.config === void 0 ? {} : { config: options.config },
14120
+ ...options.source === void 0 ? {} : { source: options.source },
13640
14121
  ...options.runId === void 0 ? {} : { runId: options.runId }
13641
14122
  }
13642
14123
  });
@@ -13691,7 +14172,7 @@ function windowText(body, fromLine, lineCount) {
13691
14172
  }
13692
14173
 
13693
14174
  // src/mcp/tools.ts
13694
- import { createHash as createHash8, randomUUID } from "crypto";
14175
+ import { createHash as createHash9, randomUUID } from "crypto";
13695
14176
 
13696
14177
  // src/mcp/workspace.ts
13697
14178
  import * as fs17 from "fs";
@@ -13707,7 +14188,7 @@ function canonicalPath(value) {
13707
14188
  return absolute;
13708
14189
  }
13709
14190
  }
13710
- function isInside2(parent, child) {
14191
+ function isInside3(parent, child) {
13711
14192
  const foldedParent = foldForComparison(parent);
13712
14193
  const foldedChild = foldForComparison(child);
13713
14194
  return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path18.sep}`);
@@ -13741,7 +14222,7 @@ function resolveRoot(requested, context) {
13741
14222
  }
13742
14223
  const resolved = canonicalPath(absolute);
13743
14224
  for (const allowed of context.roots) {
13744
- if (isInside2(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
14225
+ if (isInside3(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
13745
14226
  }
13746
14227
  const shown = context.roots.join(", ");
13747
14228
  return {
@@ -13785,7 +14266,7 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
13785
14266
  const requested = overrides.outDir.trim();
13786
14267
  const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
13787
14268
  const resolved = resolveThroughExistingAncestor(path18.resolve(root, requested));
13788
- if (!permitted.some((allowed) => isInside2(canonicalPath(allowed), resolved))) {
14269
+ if (!permitted.some((allowed) => isInside3(canonicalPath(allowed), resolved))) {
13789
14270
  const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
13790
14271
  return {
13791
14272
  ok: false,
@@ -13807,6 +14288,14 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
13807
14288
  if (overrides.sarif === true) cliOptions.sarif = true;
13808
14289
  if (overrides.staged === true) cliOptions.staged = true;
13809
14290
  if (overrides.withDependents === true) cliOptions.withDependents = true;
14291
+ for (const key of ["only", "ignore"]) {
14292
+ const value = overrides[key];
14293
+ if (value === void 0) continue;
14294
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
14295
+ return { ok: false, message: `"${key}" must be an array of glob strings.` };
14296
+ }
14297
+ cliOptions[key] = value;
14298
+ }
13810
14299
  try {
13811
14300
  const config = resolveConfig(loaded.config, cliOptions, root);
13812
14301
  return {
@@ -13832,8 +14321,8 @@ function partPathFor(workspace, filename) {
13832
14321
  if (filename.length === 0 || filename.includes("\0")) return null;
13833
14322
  const partsDir = path18.resolve(workspace.root, workspace.config.outDir, "parts");
13834
14323
  const resolved = path18.resolve(partsDir, filename);
13835
- const relative16 = path18.relative(partsDir, resolved);
13836
- if (relative16.length === 0 || relative16.includes(path18.sep) || relative16.includes("/") || relative16.includes("\\") || path18.isAbsolute(relative16)) {
14324
+ const relative17 = path18.relative(partsDir, resolved);
14325
+ if (relative17.length === 0 || relative17.includes(path18.sep) || relative17.includes("/") || relative17.includes("\\") || path18.isAbsolute(relative17)) {
13837
14326
  return null;
13838
14327
  }
13839
14328
  let stats;
@@ -13853,30 +14342,27 @@ function partPathFor(workspace, filename) {
13853
14342
  function readManifest3(workspace) {
13854
14343
  const file = manifestPathFor(workspace);
13855
14344
  const shown = path18.relative(workspace.root, file).split(path18.sep).join("/") || file;
13856
- let stats;
13857
- try {
13858
- stats = fs17.statSync(file);
13859
- } catch {
14345
+ const confined = readConfinedText(path18.dirname(file), path18.basename(file));
14346
+ if (!confined.ok) {
14347
+ if (confined.reason === "missing") {
14348
+ return {
14349
+ ok: false,
14350
+ missing: true,
14351
+ message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
14352
+ };
14353
+ }
13860
14354
  return {
13861
14355
  ok: false,
13862
- missing: true,
13863
- message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
14356
+ missing: false,
14357
+ message: `${shown} could not be read as a snapshot manifest: ${confined.message}.`
13864
14358
  };
13865
14359
  }
14360
+ const stats = confined.stats;
14361
+ const raw = confined.text;
13866
14362
  const cached = manifestCache.get(file);
13867
14363
  if (cached && cached.mtimeMs === stats.mtimeMs && cached.ctimeMs === stats.ctimeMs && cached.size === stats.size) {
13868
14364
  return { ok: true, manifest: cached.manifest, file };
13869
14365
  }
13870
- let raw;
13871
- try {
13872
- raw = fs17.readFileSync(file, "utf8");
13873
- } catch (error) {
13874
- return {
13875
- ok: false,
13876
- missing: false,
13877
- message: `${shown} exists but could not be read: ${error instanceof Error ? error.message : String(error)}`
13878
- };
13879
- }
13880
14366
  let parsed;
13881
14367
  try {
13882
14368
  parsed = JSON.parse(raw);
@@ -13887,23 +14373,140 @@ function readManifest3(workspace) {
13887
14373
  if (problem) {
13888
14374
  return { ok: false, missing: false, message: `${shown} is not a snapshot manifest: ${problem}` };
13889
14375
  }
13890
- const manifest = parsed;
13891
- manifestCache.delete(file);
13892
- manifestCache.set(file, {
13893
- mtimeMs: stats.mtimeMs,
13894
- ctimeMs: stats.ctimeMs,
13895
- size: stats.size,
13896
- manifest
13897
- });
13898
- while (manifestCache.size > MANIFEST_CACHE_LIMIT) {
13899
- const oldest = manifestCache.keys().next().value;
13900
- if (oldest === void 0) break;
13901
- manifestCache.delete(oldest);
14376
+ const manifest = parsed;
14377
+ manifestCache.delete(file);
14378
+ manifestCache.set(file, {
14379
+ mtimeMs: stats.mtimeMs,
14380
+ ctimeMs: stats.ctimeMs,
14381
+ size: stats.size,
14382
+ manifest
14383
+ });
14384
+ while (manifestCache.size > MANIFEST_CACHE_LIMIT) {
14385
+ const oldest = manifestCache.keys().next().value;
14386
+ if (oldest === void 0) break;
14387
+ manifestCache.delete(oldest);
14388
+ }
14389
+ return { ok: true, manifest, file };
14390
+ }
14391
+ function forgetManifest(file) {
14392
+ manifestCache.delete(file);
14393
+ }
14394
+
14395
+ // src/security/regex.ts
14396
+ var MAX_PATTERN_LENGTH = 256;
14397
+ var MAX_QUANTIFIER_REPEAT = 1e4;
14398
+ function unsafeRegExpReason(source) {
14399
+ if (source.length === 0) return null;
14400
+ if (source.length > MAX_PATTERN_LENGTH) {
14401
+ return `the pattern is longer than ${MAX_PATTERN_LENGTH} characters`;
14402
+ }
14403
+ let inClass = false;
14404
+ let unbounded = 0;
14405
+ const groups = [];
14406
+ for (let index = 0; index < source.length; index += 1) {
14407
+ const char = source[index];
14408
+ if (char === "\\") {
14409
+ index += 1;
14410
+ continue;
14411
+ }
14412
+ if (inClass) {
14413
+ if (char === "]") inClass = false;
14414
+ continue;
14415
+ }
14416
+ if (char === "[") {
14417
+ inClass = true;
14418
+ continue;
14419
+ }
14420
+ if (char === "(") {
14421
+ groups.push({ quantified: false, alternation: false });
14422
+ continue;
14423
+ }
14424
+ if (char === ")") {
14425
+ const group = groups.pop();
14426
+ if (group === void 0) continue;
14427
+ if (isQuantifiedAt(source, index + 1)) {
14428
+ if (group.quantified || group.alternation) {
14429
+ return "a quantified group contains another quantifier or an alternation";
14430
+ }
14431
+ group.quantified = true;
14432
+ } else if (isOptionalQuantifierAt(source, index + 1)) {
14433
+ group.quantified = true;
14434
+ }
14435
+ const parent = groups[groups.length - 1];
14436
+ if (parent !== void 0) {
14437
+ parent.quantified = parent.quantified || group.quantified;
14438
+ parent.alternation = parent.alternation || group.alternation;
14439
+ }
14440
+ continue;
14441
+ }
14442
+ if (char === "|") {
14443
+ const group = groups[groups.length - 1];
14444
+ if (group !== void 0) group.alternation = true;
14445
+ continue;
14446
+ }
14447
+ if (char === "?") {
14448
+ const previous = source[index - 1];
14449
+ if (previous !== "(" && previous !== "?" && previous !== "*" && previous !== "+" && previous !== "}") {
14450
+ const group = groups[groups.length - 1];
14451
+ if (group !== void 0) group.quantified = true;
14452
+ }
14453
+ continue;
14454
+ }
14455
+ if (char === "*" || char === "+") {
14456
+ unbounded += 1;
14457
+ const group = groups[groups.length - 1];
14458
+ if (group !== void 0) group.quantified = true;
14459
+ continue;
14460
+ }
14461
+ if (char === "{") {
14462
+ const close = source.indexOf("}", index + 1);
14463
+ if (close === -1) continue;
14464
+ const body = source.slice(index + 1, close);
14465
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
14466
+ if (match === null) {
14467
+ index = close;
14468
+ continue;
14469
+ }
14470
+ const max = match[2] === void 0 ? Number(match[1]) : match[2] === "" ? Infinity : Number(match[2]);
14471
+ if (max > MAX_QUANTIFIER_REPEAT) {
14472
+ return "a repetition bound is larger than the search budget can evaluate safely";
14473
+ }
14474
+ if (max === Infinity) unbounded += 1;
14475
+ const group = groups[groups.length - 1];
14476
+ if (group !== void 0) group.quantified = true;
14477
+ index = close;
14478
+ }
14479
+ }
14480
+ if (unbounded > 1) {
14481
+ return "the pattern has more than one unbounded repetition";
13902
14482
  }
13903
- return { ok: true, manifest, file };
14483
+ return null;
13904
14484
  }
13905
- function forgetManifest(file) {
13906
- manifestCache.delete(file);
14485
+ function isOptionalQuantifierAt(source, start) {
14486
+ if (source[start] === "?") return true;
14487
+ if (source[start] !== "{") return false;
14488
+ const close = source.indexOf("}", start + 1);
14489
+ if (close === -1) return false;
14490
+ const body = source.slice(start + 1, close);
14491
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
14492
+ if (match === null) return false;
14493
+ const minimum = Number(match[1]);
14494
+ if (match[2] === void 0) return minimum <= 1;
14495
+ const maximum = match[2] === "" ? Infinity : Number(match[2]);
14496
+ return maximum <= 1;
14497
+ }
14498
+ function isQuantifiedAt(source, start) {
14499
+ const char = source[start];
14500
+ if (char === "*" || char === "+") return true;
14501
+ if (char !== "{") return false;
14502
+ const close = source.indexOf("}", start + 1);
14503
+ if (close === -1) return false;
14504
+ const body = source.slice(start + 1, close);
14505
+ const match = /^(\d+)(?:,(\d*))?$/.exec(body);
14506
+ if (match === null) return false;
14507
+ if (match[2] === void 0) return Number(match[1]) > 1;
14508
+ if (match[2] === "") return true;
14509
+ return Number(match[2]) > 1;
13907
14510
  }
13908
14511
 
13909
14512
  // src/mcp/tools.ts
@@ -13937,6 +14540,16 @@ var OUT_DIR_PROPERTY = {
13937
14540
  };
13938
14541
  var outDirOverride = (args) => ({ outDir: args.outDir });
13939
14542
  var SCOPE_PROPERTIES = {
14543
+ only: {
14544
+ type: "array",
14545
+ items: { type: "string" },
14546
+ description: "Globs to include: replaces the config allow-list for this run."
14547
+ },
14548
+ ignore: {
14549
+ type: "array",
14550
+ items: { type: "string" },
14551
+ description: "Globs to exclude, added to the config deny-list for this run."
14552
+ },
13940
14553
  maxPartTokens: {
13941
14554
  type: "string",
13942
14555
  description: 'Token ceiling per part, for example 32000 or "32k". Narrower than maxPartBytes; it converts at four bytes per token.'
@@ -13971,7 +14584,9 @@ function workspaceOverrides(args) {
13971
14584
  sarif: args.sarif,
13972
14585
  changedSince: args.changedSince,
13973
14586
  staged: args.staged,
13974
- withDependents: args.withDependents
14587
+ withDependents: args.withDependents,
14588
+ only: args.only,
14589
+ ignore: args.ignore
13975
14590
  };
13976
14591
  }
13977
14592
  function failure(message) {
@@ -14007,11 +14622,11 @@ function toRelativePath(root, value) {
14007
14622
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
14008
14623
  const resolvedRoot = path19.resolve(root);
14009
14624
  const absolute = path19.resolve(resolvedRoot, cleaned);
14010
- const relative16 = path19.relative(resolvedRoot, absolute);
14011
- if (relative16 === "" || relative16 === ".." || relative16.startsWith(`..${path19.sep}`) || path19.isAbsolute(relative16)) {
14625
+ const relative17 = path19.relative(resolvedRoot, absolute);
14626
+ if (relative17 === "" || relative17 === ".." || relative17.startsWith(`..${path19.sep}`) || path19.isAbsolute(relative17)) {
14012
14627
  return null;
14013
14628
  }
14014
- return relative16.split(path19.sep).join("/");
14629
+ return relative17.split(path19.sep).join("/");
14015
14630
  }
14016
14631
  function symbolsOf(entry) {
14017
14632
  const summary = entry.summary;
@@ -14104,20 +14719,19 @@ var historyTool = {
14104
14719
  async handler(args, context) {
14105
14720
  const prepared = await prepare(args, context, outDirOverride(args));
14106
14721
  if (!prepared.ok) return prepared.outcome;
14107
- const reportPath = path19.resolve(prepared.workspace.root, prepared.workspace.config.outDir, "reports", "log.md");
14108
- let text2;
14109
- try {
14110
- text2 = fs18.readFileSync(reportPath, "utf8");
14111
- } catch {
14722
+ const snapshotDir = path19.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
14723
+ const reportRead = readConfinedText(snapshotDir, path19.posix.join("reports", "log.md"));
14724
+ if (!reportRead.ok) {
14112
14725
  return {
14113
- text: "This snapshot has no reports/log.md. Generate it with `snapshot_generate { includeLogs: 20 }`, or `generate --include-logs 20` on the command line; the report is opt-in because the commit subjects are repository content.",
14726
+ text: "This snapshot has no readable reports/log.md. Generate it with `snapshot_generate { includeLogs: 20 }`, or `generate --include-logs 20` on the command line; the report is opt-in because the commit subjects are repository content, and it must be a regular file inside the snapshot.",
14114
14727
  isError: true
14115
14728
  };
14116
14729
  }
14730
+ const text2 = reportRead.text;
14117
14731
  const manifestRead = readManifest3(prepared.workspace);
14118
14732
  const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
14119
14733
  if (recordedLog !== void 0 && recordedLog !== null) {
14120
- const digest = createHash8("sha256").update(text2, "utf8").digest("hex");
14734
+ const digest = createHash9("sha256").update(text2, "utf8").digest("hex");
14121
14735
  if (digest !== recordedLog.sha256) {
14122
14736
  return {
14123
14737
  text: "reports/log.md changed after the snapshot was generated (its digest no longer matches the manifest). Regenerate the snapshot rather than trusting this history.",
@@ -14277,21 +14891,22 @@ var workspaceTool = {
14277
14891
  async handler(args, context) {
14278
14892
  const prepared = await prepare(args, context, outDirOverride(args));
14279
14893
  if (!prepared.ok) return prepared.outcome;
14280
- const index = path19.resolve(
14281
- prepared.workspace.root,
14282
- prepared.workspace.config.outDir,
14283
- "WORKSPACE.json"
14284
- );
14285
- let text2;
14286
- try {
14287
- text2 = fs18.readFileSync(index, "utf8");
14288
- } catch {
14894
+ const snapshotDir = path19.resolve(prepared.workspace.root, prepared.workspace.config.outDir);
14895
+ const index = path19.join(snapshotDir, "WORKSPACE.json");
14896
+ const read = readConfinedText(snapshotDir, "WORKSPACE.json");
14897
+ if (!read.ok) {
14289
14898
  return {
14290
- text: "No workspace index at " + index + ". Generate one with `generate --workspace member-a,member-b`; a single snapshot has no members to list.",
14899
+ text: "No workspace index at " + index + " (the file is absent, or it is not a regular file inside the snapshot). Generate one with `generate --workspace member-a,member-b`; a single snapshot has no members to list.",
14291
14900
  isError: true
14292
14901
  };
14293
14902
  }
14294
- const document = JSON.parse(text2);
14903
+ const text2 = read.text;
14904
+ let document;
14905
+ try {
14906
+ document = JSON.parse(text2);
14907
+ } catch (error) {
14908
+ return { text: "WORKSPACE.json is not valid JSON: " + error.message, isError: true };
14909
+ }
14295
14910
  const members = document.members ?? [];
14296
14911
  const links = document.links ?? [];
14297
14912
  const lines = [
@@ -14431,6 +15046,10 @@ var routesTool = {
14431
15046
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
14432
15047
  let filter = null;
14433
15048
  if (typeof args.pattern === "string") {
15049
+ const unsafe = unsafeRegExpReason(args.pattern);
15050
+ if (unsafe !== null) {
15051
+ return { text: "pattern is refused: " + unsafe + ".", isError: true };
15052
+ }
14434
15053
  try {
14435
15054
  filter = new RegExp(args.pattern, "i");
14436
15055
  } catch (error) {
@@ -14574,6 +15193,12 @@ var searchTool = {
14574
15193
  const cap = Math.max(1, Math.min(500, typeof args.maxMatches === "number" ? args.maxMatches : 50));
14575
15194
  const contextLines = Math.max(0, Math.min(10, typeof args.contextLines === "number" ? args.contextLines : 0));
14576
15195
  let pattern;
15196
+ if (args.regex === true) {
15197
+ const unsafe = unsafeRegExpReason(query);
15198
+ if (unsafe !== null) {
15199
+ return { text: "regex is refused: " + unsafe + ".", isError: true };
15200
+ }
15201
+ }
14577
15202
  try {
14578
15203
  pattern = args.regex === true ? new RegExp(query, "i") : new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
14579
15204
  } catch (error) {
@@ -14596,11 +15221,17 @@ var searchTool = {
14596
15221
  } catch {
14597
15222
  continue;
14598
15223
  }
14599
- if (Buffer.byteLength(text2, "utf8") > MAX_SEARCH_BYTES) {
15224
+ const partBytes = Buffer.byteLength(text2, "utf8");
15225
+ if (partBytes > MAX_SEARCH_BYTES) {
14600
15226
  skippedOversize.push(part.filename);
15227
+ truncated = true;
14601
15228
  continue;
14602
15229
  }
14603
- scanned += text2.length;
15230
+ if (scanned + partBytes > MAX_SEARCH_BYTES) {
15231
+ truncated = true;
15232
+ break;
15233
+ }
15234
+ scanned += partBytes;
14604
15235
  for (const section of parsePartSections(text2)) {
14605
15236
  if (matches.length >= cap) {
14606
15237
  truncated = true;
@@ -14966,28 +15597,39 @@ var symbolTool = {
14966
15597
  };
14967
15598
  }
14968
15599
  const callSites = [];
15600
+ let referencesTruncated = false;
14969
15601
  if (args.references !== false) {
14970
15602
  const limit = Math.max(1, typeof args.maxReferences === "number" ? args.maxReferences : 20);
14971
15603
  const definitionKeys = new Set(matches.map((match) => match.path + ":" + match.line));
14972
15604
  const word = new RegExp("\\b" + name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b");
14973
- const parts = /* @__PURE__ */ new Map();
15605
+ const sectionsByPart = /* @__PURE__ */ new Map();
14974
15606
  let scanned = 0;
14975
15607
  for (const file of read.manifest.files) {
14976
15608
  if (callSites.length >= limit) break;
14977
15609
  const partPath = partPathFor(workspace, file.part);
14978
15610
  if (partPath === null) continue;
14979
- let partText = parts.get(partPath);
14980
- if (partText === void 0) {
15611
+ let sections = sectionsByPart.get(partPath);
15612
+ if (sections === void 0) {
15613
+ if (scanned >= MAX_SEARCH_BYTES) {
15614
+ referencesTruncated = true;
15615
+ break;
15616
+ }
15617
+ let partText;
14981
15618
  try {
14982
15619
  partText = fs18.readFileSync(partPath, "utf8");
14983
15620
  } catch {
14984
15621
  continue;
14985
15622
  }
14986
- parts.set(partPath, partText);
15623
+ const bytes = Buffer.byteLength(partText, "utf8");
15624
+ if (scanned + bytes > MAX_SEARCH_BYTES) {
15625
+ referencesTruncated = true;
15626
+ break;
15627
+ }
15628
+ scanned += bytes;
15629
+ sections = parsePartSections(partText);
15630
+ sectionsByPart.set(partPath, sections);
14987
15631
  }
14988
- if (scanned > MAX_SEARCH_BYTES) break;
14989
- scanned += Buffer.byteLength(partText, "utf8");
14990
- const section = findSection(parsePartSections(partText), file.relativePath);
15632
+ const section = findSection(sections, file.relativePath);
14991
15633
  if (section === null) continue;
14992
15634
  const bodyLines = section.body.split("\n");
14993
15635
  for (let index = 0; index < bodyLines.length && callSites.length < limit; index += 1) {
@@ -15001,8 +15643,11 @@ var symbolTool = {
15001
15643
  }
15002
15644
  }
15003
15645
  }
15004
- const text2 = matches.map((match) => "### " + match.path + " (" + match.part + ", line " + match.line + ")\n" + match.text).join("\n\n") + (args.references === false ? "" : "\n\n" + (callSites.length === 0 ? "No call site was found in the snapshot." : "Call sites (" + callSites.length + "):\n" + callSites.map((site) => " " + site.path + ":" + site.line + " " + site.text).join("\n")));
15005
- return { text: text2, structured: { found: matches.length, matches, references: callSites } };
15646
+ 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." : "");
15647
+ return {
15648
+ text: text2,
15649
+ structured: { found: matches.length, matches, references: callSites, truncated: referencesTruncated }
15650
+ };
15006
15651
  }
15007
15652
  };
15008
15653
  var contextTool = {
@@ -15160,6 +15805,10 @@ var queryTool = {
15160
15805
  const maxFiles = typeof args.maxFiles === "number" ? Math.min(200, Math.max(1, args.maxFiles)) : 40;
15161
15806
  let pattern = null;
15162
15807
  if (typeof args.pathPattern === "string") {
15808
+ const unsafe = unsafeRegExpReason(args.pathPattern);
15809
+ if (unsafe !== null) {
15810
+ return { text: "pathPattern is refused: " + unsafe + ".", isError: true };
15811
+ }
15163
15812
  try {
15164
15813
  pattern = new RegExp(args.pathPattern, "i");
15165
15814
  } catch (error) {
@@ -15545,7 +16194,12 @@ var planTool = {
15545
16194
  const prepared = await prepare(args, context, workspaceOverrides(args));
15546
16195
  if (!prepared.ok) return prepared.outcome;
15547
16196
  const workspace = prepared.workspace;
15548
- const result = await generateInWorker(workspace.root, workspace.cliOptions, { dryRun: true });
16197
+ const controller = new AbortController();
16198
+ context.onCancel?.(() => controller.abort());
16199
+ const result = await generateInWorker(workspace.root, workspace.cliOptions, {
16200
+ dryRun: true,
16201
+ signal: controller.signal
16202
+ });
15549
16203
  if (!result.ok) return failure(result.message);
15550
16204
  const summary = result.summary;
15551
16205
  const topReasons = summary.skipReasons;
@@ -15635,16 +16289,6 @@ var generateTool = {
15635
16289
  minimum: 500,
15636
16290
  description: "Fit the snapshot into this token budget, highest value first."
15637
16291
  },
15638
- only: {
15639
- type: "array",
15640
- items: { type: "string" },
15641
- description: "Globs to include: replaces the config allow-list for this run."
15642
- },
15643
- ignore: {
15644
- type: "array",
15645
- items: { type: "string" },
15646
- description: "Globs to exclude, added to the config deny-list for this run."
15647
- },
15648
16292
  ...SCOPE_PROPERTIES
15649
16293
  },
15650
16294
  additionalProperties: false
@@ -15763,7 +16407,12 @@ function configAsGenerated(workspace, manifest) {
15763
16407
  ...cli.includeLogs !== void 0 || configured("logCount") || recorded?.logCount !== void 0 ? { logCount: choose("logCount", recorded?.logCount, workspace.config.logCount, cli.includeLogs) } : {},
15764
16408
  ...cli.skeleton === true || configured("skeleton") || recorded?.skeleton !== void 0 ? { skeleton: choose("skeleton", recorded?.skeleton, workspace.config.skeleton, cli.skeleton === true ? true : void 0) } : {},
15765
16409
  ...cli.sarif === true || configured("sarif") || recorded?.sarif !== void 0 ? { sarif: choose("sarif", recorded?.sarif, workspace.config.sarif, cli.sarif === true ? true : void 0) } : {},
15766
- ...configured("maxParts") || recorded?.maxParts !== void 0 ? { maxParts: choose("maxParts", recorded?.maxParts, workspace.config.maxParts) } : {}
16410
+ ...configured("maxParts") || recorded?.maxParts !== void 0 ? { maxParts: choose("maxParts", recorded?.maxParts, workspace.config.maxParts) } : {},
16411
+ ...cli.maxPartTokens !== void 0 || configured("maxPartTokens") || recorded?.maxPartTokens !== void 0 ? { maxPartTokens: choose("maxPartTokens", recorded?.maxPartTokens, workspace.config.maxPartTokens, cli.maxPartTokens) } : {},
16412
+ ...cli.changedSince !== void 0 || configured("changedSince") || recorded?.changedSince !== void 0 ? { changedSince: choose("changedSince", recorded?.changedSince, workspace.config.changedSince, cli.changedSince) } : {},
16413
+ ...cli.staged === true || configured("staged") || recorded?.staged !== void 0 ? { staged: choose("staged", recorded?.staged, workspace.config.staged, cli.staged === true ? true : void 0) } : {},
16414
+ ...cli.withDependents === true || configured("withDependents") || recorded?.withDependents !== void 0 ? { withDependents: choose("withDependents", recorded?.withDependents, workspace.config.withDependents, cli.withDependents === true ? true : void 0) } : {},
16415
+ ...configured("promptTask") || recorded?.promptTask !== void 0 ? { promptTask: choose("promptTask", recorded?.promptTask, workspace.config.promptTask) } : {}
15767
16416
  };
15768
16417
  }
15769
16418
  var validateTool = {
@@ -16654,7 +17303,7 @@ var COMMAND_OPTION_SCOPE = {
16654
17303
  "version"
16655
17304
  ],
16656
17305
  diff: ["format", "mode", "no-config", "no-update-check", "help", "version"],
16657
- describe: ["format", "mode", "help", "version"],
17306
+ describe: ["format", "mode", "no-update-check", "help", "version"],
16658
17307
  init: [
16659
17308
  "install-hook",
16660
17309
  "cwd",
@@ -16675,7 +17324,7 @@ var COMMAND_OPTION_SCOPE = {
16675
17324
  "help",
16676
17325
  "version"
16677
17326
  ],
16678
- skill: ["cwd", "format", "mode", "install", "target", "help", "version"],
17327
+ skill: ["cwd", "format", "mode", "install", "target", "no-update-check", "help", "version"],
16679
17328
  // `mcp` reads the repository, so it takes --cwd. It has no --format: stdout carries JSON-RPC
16680
17329
  // messages, and there is no second shape to choose, so offering the flag would be a lie.
16681
17330
  serve: ["port", "host", "token", "no-auth", "allow-private", "cwd", "no-update-check", "help"],
@@ -16734,6 +17383,7 @@ var COMMAND_ORDER = [
16734
17383
  "health",
16735
17384
  "report",
16736
17385
  "explain",
17386
+ "update",
16737
17387
  "init",
16738
17388
  "setup",
16739
17389
  "diff",
@@ -17195,24 +17845,28 @@ function buildAgentContract() {
17195
17845
  {
17196
17846
  flag: "--only",
17197
17847
  type: "string",
17848
+ default: "unset",
17198
17849
  summary: "Comma-separated globs to include: overrides the config include list for this run.",
17199
17850
  appliesTo: optionAppliesTo("only")
17200
17851
  },
17201
17852
  {
17202
17853
  flag: "--ignore",
17203
17854
  type: "string",
17855
+ default: "unset",
17204
17856
  summary: "Comma-separated globs to exclude, added to the config exclude list for this run.",
17205
17857
  appliesTo: optionAppliesTo("ignore")
17206
17858
  },
17207
17859
  {
17208
17860
  flag: "--remove-empty-lines",
17209
17861
  type: "boolean",
17862
+ default: false,
17210
17863
  summary: "Drop blank and whitespace-only lines from emitted bodies; line numbers no longer match the source.",
17211
17864
  appliesTo: optionAppliesTo("remove-empty-lines")
17212
17865
  },
17213
17866
  {
17214
17867
  flag: "--all-members",
17215
17868
  type: "boolean",
17869
+ default: false,
17216
17870
  summary: "Audit every snapshot a --workspace run wrote, not only the one at outDir.",
17217
17871
  appliesTo: optionAppliesTo("all-members")
17218
17872
  },
@@ -17926,36 +18580,46 @@ function buildResourceProvider() {
17926
18580
  }
17927
18581
  const workspace = await workspaceFor(context);
17928
18582
  if ("error" in workspace) return null;
18583
+ const snapshotDir = path20.resolve(workspace.root, workspace.config.outDir);
17929
18584
  if (uri === PROMPT_URI) {
17930
- const text2 = readFileIfPresent(
17931
- path20.resolve(workspace.root, workspace.config.outDir, "PROMPT.md")
17932
- );
17933
- if (text2 === null) {
18585
+ const read = readConfinedText(snapshotDir, "PROMPT.md");
18586
+ if (!read.ok) {
17934
18587
  throw new ResourceNotFoundError(
17935
18588
  uri,
17936
- "This snapshot contains no PROMPT.md: the prompt artifact was disabled (artifacts.prompt = false or --skip-artifacts prompt), or nothing has been generated yet. Run snapshot_generate first."
18589
+ "This snapshot contains no readable PROMPT.md: the prompt artifact was disabled (artifacts.prompt = false or --skip-artifacts prompt), nothing has been generated yet, or the file is not a regular file inside the snapshot. Run snapshot_generate first."
17937
18590
  );
17938
18591
  }
17939
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, PROMPT_ADVICE) };
18592
+ return {
18593
+ uri,
18594
+ mimeType: "text/markdown",
18595
+ text: ensureSingleRead(uri, read.text, PROMPT_ADVICE)
18596
+ };
17940
18597
  }
17941
18598
  const report2 = REPORT_URIS.get(uri);
17942
18599
  if (report2) {
17943
- const text2 = readFileIfPresent(
17944
- path20.resolve(workspace.root, workspace.config.outDir, "reports", report2.file)
17945
- );
17946
- if (text2 === null) {
18600
+ const read = readConfinedText(snapshotDir, path20.posix.join("reports", report2.file));
18601
+ if (!read.ok) {
17947
18602
  throw new ResourceNotFoundError(
17948
18603
  uri,
17949
- "This snapshot contains no " + report2.file + ": that report was disabled, or nothing has been generated yet. Run snapshot_generate first."
18604
+ "This snapshot contains no readable " + report2.file + ": that report was disabled, nothing has been generated yet, or the file is not a regular file inside the snapshot. Run snapshot_generate first."
17950
18605
  );
17951
18606
  }
17952
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text2, REPORT_ADVICE) };
18607
+ return {
18608
+ uri,
18609
+ mimeType: "text/markdown",
18610
+ text: ensureSingleRead(uri, read.text, REPORT_ADVICE)
18611
+ };
17953
18612
  }
17954
18613
  if (uri === "snapshot://manifest") {
17955
18614
  const read = readManifest3(workspace);
17956
18615
  if (!read.ok) return null;
17957
- const text2 = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
17958
- return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text2, MANIFEST_ADVICE) };
18616
+ const confined = readConfinedText(path20.dirname(read.file), path20.basename(read.file));
18617
+ if (!confined.ok) return null;
18618
+ return {
18619
+ uri,
18620
+ mimeType: "application/json",
18621
+ text: ensureSingleRead(uri, confined.text, MANIFEST_ADVICE)
18622
+ };
17959
18623
  }
17960
18624
  const partMatch = PART_URI.exec(uri);
17961
18625
  if (partMatch) {
@@ -18417,11 +19081,11 @@ var MAX_LINE_BYTES = 32 * 1024 * 1024;
18417
19081
  function createWriter(output) {
18418
19082
  return {
18419
19083
  write(value) {
18420
- return new Promise((resolve15, reject) => {
19084
+ return new Promise((resolve16, reject) => {
18421
19085
  output.write(`${JSON.stringify(value)}
18422
19086
  `, (error) => {
18423
19087
  if (error) reject(error);
18424
- else resolve15();
19088
+ else resolve16();
18425
19089
  });
18426
19090
  });
18427
19091
  }
@@ -18560,12 +19224,12 @@ async function runStdioServer(options) {
18560
19224
  });
18561
19225
  return writeChain;
18562
19226
  };
18563
- const MAX_IN_FLIGHT = 4;
19227
+ const MAX_IN_FLIGHT2 = 4;
18564
19228
  let inFlight = 0;
18565
19229
  let inputEnded = false;
18566
19230
  let resolveDone = () => void 0;
18567
- const finished = new Promise((resolve15) => {
18568
- resolveDone = resolve15;
19231
+ const finished = new Promise((resolve16) => {
19232
+ resolveDone = resolve16;
18569
19233
  });
18570
19234
  const finishIfIdle = () => {
18571
19235
  if (inputEnded && inFlight === 0) resolveDone(0);
@@ -18595,14 +19259,26 @@ async function runStdioServer(options) {
18595
19259
  errorResponse(
18596
19260
  id,
18597
19261
  ERROR_CODES.overloaded,
18598
- `The server is already handling ${MAX_IN_FLIGHT} requests; retry this one when it is free.`
19262
+ `The server is already handling ${MAX_IN_FLIGHT2} requests; retry this one when it is free.`
18599
19263
  )
18600
19264
  );
18601
19265
  };
19266
+ const isCancellation = (line) => {
19267
+ try {
19268
+ const parsed = JSON.parse(line);
19269
+ return parsed !== null && typeof parsed === "object" && parsed.method === "notifications/cancelled";
19270
+ } catch {
19271
+ return false;
19272
+ }
19273
+ };
18602
19274
  const stopReading = createLineReader(process.stdin, {
18603
19275
  onOverflow: (bytes) => log(`mcp: discarded an oversized message (${bytes} bytes)`),
18604
19276
  onLine: (line) => {
18605
- if (inFlight >= MAX_IN_FLIGHT) {
19277
+ if (inFlight >= MAX_IN_FLIGHT2) {
19278
+ if (isCancellation(line)) {
19279
+ void handleLine(line);
19280
+ return;
19281
+ }
18606
19282
  rejectOverloaded(line);
18607
19283
  return;
18608
19284
  }
@@ -18652,30 +19328,44 @@ function crc32(data) {
18652
19328
  return (crc ^ 4294967295) >>> 0;
18653
19329
  }
18654
19330
  function dosDateTime(date) {
18655
- const year = Math.max(1980, date.getFullYear());
19331
+ const year = Math.max(1980, date.getUTCFullYear());
18656
19332
  return {
18657
- time: date.getHours() << 11 | date.getMinutes() << 5 | Math.floor(date.getSeconds() / 2),
18658
- date: year - 1980 << 9 | date.getMonth() + 1 << 5 | date.getDate()
19333
+ time: date.getUTCHours() << 11 | date.getUTCMinutes() << 5 | Math.floor(date.getUTCSeconds() / 2),
19334
+ date: year - 1980 << 9 | date.getUTCMonth() + 1 << 5 | date.getUTCDate()
18659
19335
  };
18660
19336
  }
18661
19337
  function walkFiles(root, prefix = "") {
18662
19338
  const files = [];
18663
- for (const entry of fs20.readdirSync(path21.join(root, prefix), { withFileTypes: true })) {
18664
- const relative16 = prefix === "" ? entry.name : prefix + "/" + entry.name;
18665
- if (entry.isDirectory()) files.push(...walkFiles(root, relative16));
18666
- else if (entry.isFile()) files.push(relative16);
19339
+ const stack = [prefix];
19340
+ while (stack.length > 0) {
19341
+ const current = stack.pop();
19342
+ for (const entry of fs20.readdirSync(path21.join(root, current), { withFileTypes: true })) {
19343
+ const relative17 = current === "" ? entry.name : current + "/" + entry.name;
19344
+ if (entry.isDirectory()) stack.push(relative17);
19345
+ else if (entry.isFile()) files.push(relative17);
19346
+ }
18667
19347
  }
18668
19348
  return files;
18669
19349
  }
18670
19350
  function writeZip(options) {
18671
19351
  const entries = [...options.entries ?? []];
19352
+ const maxTotalBytes = options.maxTotalBytes ?? 256 * 1024 * 1024;
19353
+ let totalBytes = entries.reduce((total, entry) => total + entry.content.length, 0);
19354
+ if (totalBytes > maxTotalBytes) {
19355
+ throw new Error("zip: uncompressed content exceeds " + maxTotalBytes + " bytes");
19356
+ }
18672
19357
  if (options.directory !== void 0) {
18673
19358
  const root = options.directory;
18674
- for (const relative16 of walkFiles(root)) {
18675
- if (options.skip !== void 0 && options.skip(relative16)) continue;
18676
- const full = path21.join(root, relative16);
19359
+ for (const relative17 of walkFiles(root)) {
19360
+ if (options.skip !== void 0 && options.skip(relative17)) continue;
19361
+ const full = path21.join(root, relative17);
18677
19362
  const stat = fs20.statSync(full);
18678
- entries.push({ name: relative16, content: fs20.readFileSync(full), mtime: stat.mtime });
19363
+ if (totalBytes + stat.size > maxTotalBytes) {
19364
+ throw new Error("zip: uncompressed content exceeds " + maxTotalBytes + " bytes");
19365
+ }
19366
+ const content = fs20.readFileSync(full);
19367
+ totalBytes += content.length;
19368
+ entries.push({ name: relative17, content, mtime: stat.mtime });
18679
19369
  }
18680
19370
  }
18681
19371
  if (entries.length > 65535) {
@@ -18895,6 +19585,7 @@ var SERVE_PAGE = `<!doctype html>
18895
19585
  var DEFAULT_PORT = 4788;
18896
19586
  var MAX_BODY = 64 * 1024;
18897
19587
  var MAX_PREVIEW = 64 * 1024;
19588
+ var MAX_MCP_IN_FLIGHT = 4;
18898
19589
  function isLoopback(origin) {
18899
19590
  try {
18900
19591
  const url = new URL(origin);
@@ -18912,6 +19603,23 @@ async function startWebServer(options) {
18912
19603
  throw new Error("Refusing to serve " + host + " without a token.");
18913
19604
  }
18914
19605
  const createMcp = () => createServer({ cwd: options.cwd, log });
19606
+ const toolCount = buildTools().length;
19607
+ const rateWindows = /* @__PURE__ */ new Map();
19608
+ const rateLimited = (request) => {
19609
+ const remote = request.socket.remoteAddress ?? "unknown";
19610
+ const now = Date.now();
19611
+ const window = rateWindows.get(remote);
19612
+ if (window === void 0 || window.resetAt <= now) {
19613
+ if (!rateWindows.has(remote) && rateWindows.size >= 1024) {
19614
+ for (const [key, value] of rateWindows) if (value.resetAt <= now) rateWindows.delete(key);
19615
+ }
19616
+ rateWindows.set(remote, { count: 1, resetAt: now + 1e4 });
19617
+ return false;
19618
+ }
19619
+ if (window.count >= 120) return true;
19620
+ window.count += 1;
19621
+ return false;
19622
+ };
18915
19623
  const mcpPerSocket = /* @__PURE__ */ new WeakMap();
18916
19624
  const mcpFor = (socket) => {
18917
19625
  let server2 = mcpPerSocket.get(socket);
@@ -18922,6 +19630,7 @@ async function startWebServer(options) {
18922
19630
  return server2;
18923
19631
  };
18924
19632
  const temporaryClones = /* @__PURE__ */ new Set();
19633
+ let mcpInFlight = 0;
18925
19634
  const allowedRoots = [path22.resolve(options.cwd)];
18926
19635
  const canonical = (candidate) => {
18927
19636
  try {
@@ -18930,21 +19639,22 @@ async function startWebServer(options) {
18930
19639
  return null;
18931
19640
  }
18932
19641
  };
19642
+ const fold = (value) => process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
18933
19643
  const inside = (resolved) => allowedRoots.some((root) => {
18934
19644
  const canonicalRoot = canonical(root);
18935
19645
  if (canonicalRoot === null) return false;
18936
- const relative16 = path22.relative(canonicalRoot, resolved);
18937
- return relative16 === "" || !relative16.startsWith(`..${path22.sep}`) && relative16 !== ".." && !path22.isAbsolute(relative16);
19646
+ const relative17 = path22.relative(fold(canonicalRoot), fold(resolved));
19647
+ return relative17 === "" || !relative17.startsWith(`..${path22.sep}`) && relative17 !== ".." && !path22.isAbsolute(relative17);
18938
19648
  });
18939
19649
  const insideAllowedRoots = (candidate) => {
18940
19650
  const resolved = canonical(candidate);
18941
19651
  return resolved === null ? false : inside(resolved);
18942
19652
  };
18943
19653
  const lexicallyInside = (candidate) => {
18944
- const resolved = path22.resolve(candidate);
19654
+ const resolved = fold(path22.resolve(candidate));
18945
19655
  return allowedRoots.some((root) => {
18946
- const prefix = path22.resolve(root) + path22.sep;
18947
- return resolved === path22.resolve(root) || resolved.startsWith(prefix);
19656
+ const resolvedRoot = fold(path22.resolve(root));
19657
+ return resolved === resolvedRoot || resolved.startsWith(resolvedRoot + path22.sep);
18948
19658
  });
18949
19659
  };
18950
19660
  const insideAllowedRootsForWrite = (candidate) => {
@@ -19002,8 +19712,12 @@ async function startWebServer(options) {
19002
19712
  response.end();
19003
19713
  return;
19004
19714
  }
19715
+ if (rateLimited(request)) {
19716
+ send(429, { error: "too many requests" }, { "retry-after": "10" });
19717
+ return;
19718
+ }
19005
19719
  if (request.method === "GET" && request.url === "/healthz") {
19006
- send(200, { ok: true, name: "codebase-snapshot", tools: 12 });
19720
+ send(200, { ok: true, name: "codebase-snapshot", tools: toolCount });
19007
19721
  return;
19008
19722
  }
19009
19723
  if (request.method === "GET" && (request.url === "/" || request.url === "/index.html")) {
@@ -19048,12 +19762,35 @@ async function startWebServer(options) {
19048
19762
  const server2 = mcpFor(request.socket);
19049
19763
  const answers = [];
19050
19764
  for (const item of batch) {
19051
- const answer = await server2.handle(item);
19052
- if (answer !== null) answers.push(answer);
19765
+ const gated = item !== null && typeof item === "object" && item.method === "tools/call";
19766
+ if (gated && mcpInFlight >= MAX_MCP_IN_FLIGHT) {
19767
+ answers.push({
19768
+ jsonrpc: "2.0",
19769
+ id: item.id ?? null,
19770
+ error: {
19771
+ code: -32001,
19772
+ message: "server busy: too many tool calls are already in flight"
19773
+ }
19774
+ });
19775
+ continue;
19776
+ }
19777
+ if (gated) mcpInFlight += 1;
19778
+ try {
19779
+ const answer = await server2.handle(item);
19780
+ if (answer !== null) answers.push(answer);
19781
+ } finally {
19782
+ if (gated) mcpInFlight -= 1;
19783
+ }
19053
19784
  }
19054
19785
  if (answers.length === 0) send(202, "");
19055
19786
  else send(200, Array.isArray(message) ? answers : answers[0]);
19056
- })();
19787
+ })().catch((error) => {
19788
+ log("serve: " + error.message);
19789
+ try {
19790
+ send(500, { error: "internal error" });
19791
+ } catch {
19792
+ }
19793
+ });
19057
19794
  });
19058
19795
  return;
19059
19796
  }
@@ -19146,13 +19883,12 @@ async function startWebServer(options) {
19146
19883
  send(400, { error: "not a directory: " + target });
19147
19884
  return;
19148
19885
  }
19149
- const loaded = await loadConfigFileDetailed(target, { allowExecutableConfig: false });
19886
+ const loaded = isRemote ? { config: null, errors: [] } : await loadConfigFileDetailed(target, { allowExecutableConfig: false });
19150
19887
  if (loaded.errors.length > 0) {
19151
19888
  send(400, { error: loaded.errors.join("; ") });
19152
19889
  return;
19153
19890
  }
19154
19891
  const runConfig = isRemote ? {
19155
- ...loaded.config ?? {},
19156
19892
  outDir: "snapshot",
19157
19893
  tmpDir: "snapshot.tmp",
19158
19894
  hooks: {}
@@ -19163,13 +19899,39 @@ async function startWebServer(options) {
19163
19899
  send(403, { error: "the configured outDir resolves outside the served directory" });
19164
19900
  return;
19165
19901
  }
19902
+ const configuredTmpDir = typeof runConfig.tmpDir === "string" && runConfig.tmpDir.trim() !== "" ? runConfig.tmpDir : "snapshot.tmp";
19903
+ const stagingDir = path22.resolve(target, configuredTmpDir);
19904
+ if (!insideAllowedRootsForWrite(stagingDir)) {
19905
+ send(403, { error: "the configured tmpDir resolves outside the served directory" });
19906
+ return;
19907
+ }
19166
19908
  const started = Date.now();
19167
19909
  try {
19168
- const manifest = generateSnapshot({ ...runConfig, cwd: target }, {
19169
- ...provenance === void 0 ? {} : { source: provenance },
19170
- ...mode === "slice" ? { slice: { question } } : {},
19171
- ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
19172
- });
19910
+ const generated = await generateInWorker(
19911
+ target,
19912
+ { cwd: target },
19913
+ {
19914
+ config: runConfig,
19915
+ ...provenance === void 0 ? {} : { source: provenance },
19916
+ ...mode === "slice" && question.length >= 3 ? { narrow: { slice: { question } } } : {},
19917
+ ...mode === "budget" && budgetTokens !== void 0 ? { narrow: { budgetTokens } } : {}
19918
+ }
19919
+ );
19920
+ if (!generated.ok) {
19921
+ send(500, { error: generated.message });
19922
+ return;
19923
+ }
19924
+ const manifestRead = readConfinedText(snapshotDir, "manifest.json");
19925
+ if (!manifestRead.ok) {
19926
+ send(500, { error: "the generate worker did not write manifest.json" });
19927
+ return;
19928
+ }
19929
+ const manifest = JSON.parse(manifestRead.text);
19930
+ const shape = describeManifestShapeProblem(manifest);
19931
+ if (shape !== null) {
19932
+ send(500, { error: "the generated manifest is not a snapshot manifest: " + shape });
19933
+ return;
19934
+ }
19173
19935
  const seconds = ((Date.now() - started) / 1e3).toFixed(2);
19174
19936
  const health = auditSnapshot({ snapshotDir, repoDir: target });
19175
19937
  send(200, {
@@ -19192,7 +19954,13 @@ async function startWebServer(options) {
19192
19954
  } catch (error) {
19193
19955
  send(500, { error: error.message });
19194
19956
  }
19195
- })();
19957
+ })().catch((error) => {
19958
+ log("serve: " + error.message);
19959
+ try {
19960
+ send(500, { error: "internal error" });
19961
+ } catch {
19962
+ }
19963
+ });
19196
19964
  });
19197
19965
  return;
19198
19966
  }
@@ -19202,15 +19970,24 @@ async function startWebServer(options) {
19202
19970
  send(403, { error: "outside the served directory: " + target });
19203
19971
  return;
19204
19972
  }
19205
- if (!fs21.existsSync(path22.join(target, "manifest.json"))) {
19206
- send(404, { error: "no manifest.json under " + target });
19973
+ if (!fs21.existsSync(target)) {
19974
+ send(404, { error: "no snapshot directory at " + target });
19207
19975
  return;
19208
19976
  }
19209
19977
  if (!insideAllowedRoots(target)) {
19210
19978
  send(403, { error: "outside the served directory: " + target });
19211
19979
  return;
19212
19980
  }
19213
- const report2 = auditSnapshot({ snapshotDir: target, repoDir: path22.dirname(target) });
19981
+ const repoDir = path22.dirname(target);
19982
+ if (!insideAllowedRoots(repoDir)) {
19983
+ send(403, { error: "the repository root for this snapshot is outside the served directory" });
19984
+ return;
19985
+ }
19986
+ if (!fs21.existsSync(path22.join(target, "manifest.json"))) {
19987
+ send(404, { error: "no manifest.json under " + target });
19988
+ return;
19989
+ }
19990
+ const report2 = auditSnapshot({ snapshotDir: target, repoDir });
19214
19991
  send(200, { score: report2.score, counts: report2.counts, checks: report2.checks });
19215
19992
  return;
19216
19993
  }
@@ -19220,7 +19997,7 @@ async function startWebServer(options) {
19220
19997
  send(403, { error: "outside the served directory: " + target });
19221
19998
  return;
19222
19999
  }
19223
- if (!fs21.existsSync(path22.join(target, "manifest.json"))) {
20000
+ if (!fs21.existsSync(target)) {
19224
20001
  send(404, { error: "no manifest.json under " + target });
19225
20002
  return;
19226
20003
  }
@@ -19228,10 +20005,18 @@ async function startWebServer(options) {
19228
20005
  send(403, { error: "outside the served directory: " + target });
19229
20006
  return;
19230
20007
  }
19231
- const manifestFile = path22.join(target, "manifest.json");
20008
+ const manifestRead = readConfinedText(target, "manifest.json");
20009
+ if (!manifestRead.ok) {
20010
+ if (manifestRead.reason === "outside") {
20011
+ send(403, { error: "manifest.json resolves outside the snapshot directory" });
20012
+ } else {
20013
+ send(404, { error: "no readable manifest.json under " + target });
20014
+ }
20015
+ return;
20016
+ }
19232
20017
  let manifest;
19233
20018
  try {
19234
- manifest = JSON.parse(fs21.readFileSync(manifestFile, "utf8"));
20019
+ manifest = JSON.parse(manifestRead.text);
19235
20020
  } catch {
19236
20021
  send(404, { error: "no manifest.json under " + target });
19237
20022
  return;
@@ -19241,12 +20026,8 @@ async function startWebServer(options) {
19241
20026
  send(400, { error: "manifest.json is not a snapshot manifest: " + shapeProblem });
19242
20027
  return;
19243
20028
  }
19244
- let prompt = "";
19245
- try {
19246
- prompt = fs21.readFileSync(path22.join(target, "PROMPT.md"), "utf8").slice(0, MAX_PREVIEW);
19247
- } catch {
19248
- prompt = "(this snapshot has no PROMPT.md)";
19249
- }
20029
+ const promptRead = readConfinedText(target, "PROMPT.md");
20030
+ const prompt = promptRead.ok ? promptRead.text.slice(0, MAX_PREVIEW) : "(this snapshot has no readable PROMPT.md)";
19250
20031
  send(200, {
19251
20032
  fingerprint: manifest.fingerprint ?? "",
19252
20033
  generatedAt: manifest.generatedAt ?? "",
@@ -19264,7 +20045,7 @@ async function startWebServer(options) {
19264
20045
  send(403, { error: "outside the served directory: " + target });
19265
20046
  return;
19266
20047
  }
19267
- if (!fs21.existsSync(path22.join(target, "manifest.json")) && !fs21.existsSync(path22.join(target, ".codebase-snapshot"))) {
20048
+ if (!fs21.existsSync(target)) {
19268
20049
  send(404, { error: "not a snapshot directory: " + target });
19269
20050
  return;
19270
20051
  }
@@ -19272,6 +20053,10 @@ async function startWebServer(options) {
19272
20053
  send(403, { error: "outside the served directory: " + target });
19273
20054
  return;
19274
20055
  }
20056
+ if (!fs21.existsSync(path22.join(target, "manifest.json")) && !fs21.existsSync(path22.join(target, ".codebase-snapshot"))) {
20057
+ send(404, { error: "not a snapshot directory: " + target });
20058
+ return;
20059
+ }
19275
20060
  try {
19276
20061
  const zip = writeZip({ directory: target });
19277
20062
  response.writeHead(200, {
@@ -19288,11 +20073,11 @@ async function startWebServer(options) {
19288
20073
  }
19289
20074
  send(404, { error: "not found" });
19290
20075
  });
19291
- await new Promise((resolve15, reject) => {
20076
+ await new Promise((resolve16, reject) => {
19292
20077
  server.once("error", reject);
19293
20078
  server.listen(port, host, () => {
19294
20079
  server.removeListener("error", reject);
19295
- resolve15();
20080
+ resolve16();
19296
20081
  });
19297
20082
  });
19298
20083
  const address = server.address();
@@ -19304,14 +20089,14 @@ async function startWebServer(options) {
19304
20089
  port: actualPort,
19305
20090
  host,
19306
20091
  token,
19307
- close: () => new Promise((resolve15) => {
20092
+ close: () => new Promise((resolve16) => {
19308
20093
  for (const directory of temporaryClones) {
19309
20094
  try {
19310
20095
  fs21.rmSync(directory, { recursive: true, force: true });
19311
20096
  } catch {
19312
20097
  }
19313
20098
  }
19314
- server.close(() => resolve15());
20099
+ server.close(() => resolve16());
19315
20100
  })
19316
20101
  };
19317
20102
  }
@@ -19434,14 +20219,14 @@ function writeCache(file, entry) {
19434
20219
  }
19435
20220
  }
19436
20221
  function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOUT_MS) {
19437
- return new Promise((resolve15) => {
20222
+ return new Promise((resolve16) => {
19438
20223
  let settled = false;
19439
20224
  let request = null;
19440
20225
  const finish = (value) => {
19441
20226
  if (settled) return;
19442
20227
  settled = true;
19443
20228
  clearTimeout(deadline);
19444
- resolve15(value);
20229
+ resolve16(value);
19445
20230
  };
19446
20231
  const deadline = setTimeout(() => {
19447
20232
  request?.destroy();
@@ -19561,7 +20346,7 @@ if [ ! -f "$SNAPSHOT_DIR/manifest.json" ]; then
19561
20346
  exit 1
19562
20347
  fi
19563
20348
 
19564
- if ! npx --no-install ${GENERATOR_NAME} validate >/dev/null 2>&1; then
20349
+ if ! npx --no-install ${GENERATOR_NAME} validate --out-dir "$SNAPSHOT_DIR" >/dev/null 2>&1; then
19565
20350
  echo "${GENERATOR_NAME}: the snapshot is out of date." >&2
19566
20351
  echo " Run \\"npx ${GENERATOR_NAME} generate\\", stage the change, and commit again." >&2
19567
20352
  echo " (npx --no-install is used on purpose: this hook must not install anything)" >&2
@@ -19585,16 +20370,36 @@ function gitDirectory(cwd) {
19585
20370
  if (!match) return null;
19586
20371
  const target = match[1];
19587
20372
  const resolved = path24.isAbsolute(target.trim()) ? target.trim() : path24.join(cwd, target.trim());
19588
- if (!fs23.statSync(resolved).isDirectory()) return null;
19589
- if (isInside3(path24.resolve(cwd), path24.resolve(resolved))) return resolved;
19590
- return isRegisteredWorktree(path24.resolve(resolved), cwd) ? resolved : null;
20373
+ const cwdReal = canonicalForWrite(cwd);
20374
+ const resolvedReal = canonicalForWrite(resolved);
20375
+ if (cwdReal === null || resolvedReal === null || !fs23.statSync(resolvedReal).isDirectory()) {
20376
+ return null;
20377
+ }
20378
+ if (isInside4(cwdReal, resolvedReal)) return resolvedReal;
20379
+ return isRegisteredWorktree(path24.resolve(resolved), cwd) ? resolvedReal : null;
19591
20380
  } catch {
19592
20381
  return null;
19593
20382
  }
19594
20383
  }
19595
- function isInside3(parent, child) {
19596
- const relative16 = path24.relative(parent, child);
19597
- return relative16 === "" || !relative16.startsWith("..") && !path24.isAbsolute(relative16);
20384
+ function isInside4(parent, child) {
20385
+ const relative17 = path24.relative(parent, child);
20386
+ return relative17 === "" || !relative17.startsWith("..") && !path24.isAbsolute(relative17);
20387
+ }
20388
+ function canonicalForWrite(target) {
20389
+ let existing = path24.resolve(target);
20390
+ const tail = [];
20391
+ while (!fs23.existsSync(existing)) {
20392
+ tail.unshift(path24.basename(existing));
20393
+ const parent = path24.dirname(existing);
20394
+ if (parent === existing) break;
20395
+ existing = parent;
20396
+ }
20397
+ try {
20398
+ const real = fs23.realpathSync(existing);
20399
+ return tail.length === 0 ? real : path24.join(real, ...tail);
20400
+ } catch {
20401
+ return null;
20402
+ }
19598
20403
  }
19599
20404
  function isRegisteredWorktree(gitDir, cwd) {
19600
20405
  try {
@@ -19622,9 +20427,16 @@ function configuredHooksDirectory(cwd) {
19622
20427
  if (hooks === null) return null;
19623
20428
  const resolved = path24.resolve(cwd, hooks);
19624
20429
  const common = gitOutput(cwd, ["rev-parse", "--git-common-dir"]);
19625
- const commonDir = common === null ? null : path24.resolve(cwd, common);
19626
- if (isInside3(path24.resolve(cwd), resolved)) return { dir: resolved };
19627
- if (commonDir !== null && isInside3(commonDir, resolved)) return { dir: resolved };
20430
+ const commonDir = common === null ? null : canonicalForWrite(path24.resolve(cwd, common));
20431
+ const cwdReal = canonicalForWrite(cwd);
20432
+ const hooksReal = canonicalForWrite(resolved);
20433
+ if (hooksReal === null || cwdReal === null) {
20434
+ return {
20435
+ refusal: `The hooks directory git reports (${resolved}) could not be resolved, so no hook was written.`
20436
+ };
20437
+ }
20438
+ if (isInside4(cwdReal, hooksReal)) return { dir: hooksReal };
20439
+ if (commonDir !== null && isInside4(commonDir, hooksReal)) return { dir: hooksReal };
19628
20440
  return {
19629
20441
  refusal: `The hooks directory git reports (${resolved}) is outside this repository, so no hook was written. Add \`npx ${GENERATOR_NAME} validate\` to the hook manager that owns it instead.`
19630
20442
  };
@@ -19644,8 +20456,48 @@ function installPreCommitHook(cwd, outDir = "snapshot") {
19644
20456
  ]
19645
20457
  };
19646
20458
  }
19647
- const hooksDir = configured === null ? path24.join(gitDir, "hooks") : configured.dir;
20459
+ const hooksDirRaw = configured === null ? path24.join(gitDir, "hooks") : configured.dir;
20460
+ const hooksDir = canonicalForWrite(hooksDirRaw);
20461
+ if (hooksDir === null) {
20462
+ return {
20463
+ path: null,
20464
+ written: false,
20465
+ notes: [`Refusing to write the hooks directory: ${hooksDirRaw} could not be resolved.`]
20466
+ };
20467
+ }
19648
20468
  const hookPath = path24.join(hooksDir, "pre-commit");
20469
+ try {
20470
+ const existingStats = fs23.lstatSync(hookPath);
20471
+ if (existingStats.isSymbolicLink()) {
20472
+ return {
20473
+ path: hookPath,
20474
+ written: false,
20475
+ notes: [`Refusing to write ${hookPath}: it is a symbolic link.`]
20476
+ };
20477
+ }
20478
+ if (existingStats.isFile() && existingStats.nlink > 1) {
20479
+ return {
20480
+ path: hookPath,
20481
+ written: false,
20482
+ notes: [`Refusing to write ${hookPath}: it has ${existingStats.nlink} hard links.`]
20483
+ };
20484
+ }
20485
+ if (!existingStats.isFile()) {
20486
+ return {
20487
+ path: hookPath,
20488
+ written: false,
20489
+ notes: [`Refusing to write ${hookPath}: it is not a regular file.`]
20490
+ };
20491
+ }
20492
+ } catch (error) {
20493
+ if (error.code !== "ENOENT") {
20494
+ return {
20495
+ path: hookPath,
20496
+ written: false,
20497
+ notes: [`Refusing to write ${hookPath}: ${error.message}`]
20498
+ };
20499
+ }
20500
+ }
19649
20501
  try {
19650
20502
  fs23.mkdirSync(hooksDir, { recursive: true });
19651
20503
  } catch (err) {
@@ -19695,23 +20547,23 @@ var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
19695
20547
  var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
19696
20548
  var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
19697
20549
  var fileDerivationBytes = 0;
19698
- function takeDerivation(path28, hash, settings) {
19699
- const cached = FILE_DERIVATIONS.get(path28);
20550
+ function takeDerivation(path28, relativePath, hash, settings) {
20551
+ const key = path28 + "\0" + relativePath;
20552
+ const cached = FILE_DERIVATIONS.get(key);
19700
20553
  if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
19701
- FILE_DERIVATIONS.delete(path28);
19702
- FILE_DERIVATIONS.set(path28, cached);
20554
+ FILE_DERIVATIONS.delete(key);
20555
+ FILE_DERIVATIONS.set(key, cached);
19703
20556
  return cached;
19704
20557
  }
19705
- function rememberDerivation(path28, hash, settings, derivation) {
20558
+ function rememberDerivation(path28, relativePath, hash, settings, derivation) {
20559
+ const key = path28 + "\0" + relativePath;
19706
20560
  const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
19707
20561
  const bytes = bodyBytes * 2 + 512;
19708
20562
  if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
19709
- const previous = FILE_DERIVATIONS.get(path28);
20563
+ const previous = FILE_DERIVATIONS.get(key);
19710
20564
  if (previous !== void 0) {
19711
- FILE_DERIVATIONS.delete(path28);
20565
+ FILE_DERIVATIONS.delete(key);
19712
20566
  fileDerivationBytes -= previous.bytes;
19713
- } else {
19714
- FILE_DERIVATIONS.delete(path28);
19715
20567
  }
19716
20568
  while (fileDerivationBytes + bytes > FILE_DERIVATION_LIMIT_BYTES) {
19717
20569
  const oldest = FILE_DERIVATIONS.keys().next();
@@ -19720,7 +20572,7 @@ function rememberDerivation(path28, hash, settings, derivation) {
19720
20572
  FILE_DERIVATIONS.delete(oldest.value);
19721
20573
  if (evicted !== void 0) fileDerivationBytes -= evicted.bytes;
19722
20574
  }
19723
- FILE_DERIVATIONS.set(path28, { ...derivation, hash, settings, bytes });
20575
+ FILE_DERIVATIONS.set(key, { ...derivation, hash, settings, bytes });
19724
20576
  fileDerivationBytes += bytes;
19725
20577
  }
19726
20578
  function derivationSettings(config) {
@@ -19977,6 +20829,11 @@ function verifyInMemory(files, parts, unaccounted) {
19977
20829
  }
19978
20830
  }
19979
20831
  for (const part of parts) {
20832
+ if (part.metadata.hardClipped === true) {
20833
+ errors.push(
20834
+ `${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.`
20835
+ );
20836
+ }
19980
20837
  if (sha256Hex2(part.markdown) !== part.metadata.sha256) {
19981
20838
  errors.push(`${part.filename} content does not match its recorded sha256.`);
19982
20839
  }
@@ -20005,7 +20862,12 @@ function resolveSafeOutputDirs(config) {
20005
20862
  const outDir = path25.resolve(cwd, config.outDir);
20006
20863
  const tmpDir = path25.resolve(cwd, config.tmpDir);
20007
20864
  const root = path25.parse(cwd).root;
20008
- const contains = (parent, child) => child === parent || child.startsWith(`${parent}${path25.sep}`);
20865
+ const fold = (value) => process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
20866
+ const contains = (parent, child) => {
20867
+ const foldedParent = fold(parent);
20868
+ const foldedChild = fold(child);
20869
+ return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path25.sep}`);
20870
+ };
20009
20871
  const reject = (reason) => {
20010
20872
  throw new Error(
20011
20873
  `Refusing to generate: ${reason}. outDir=${outDir} tmpDir=${tmpDir} cwd=${cwd}`
@@ -20047,7 +20909,7 @@ function maskPathText(value, secretRules) {
20047
20909
  }
20048
20910
  function maskOwnerBrief(brief, secretRules) {
20049
20911
  if (brief === void 0) return void 0;
20050
- const mask = (value) => scanAndRedactSecrets(value, secretRules ?? [], "owner-brief").redacted;
20912
+ const mask = (value) => maskProse(value, secretRules, "owner-brief");
20051
20913
  return {
20052
20914
  ...brief,
20053
20915
  path: mask(brief.path),
@@ -20057,11 +20919,17 @@ function maskOwnerBrief(brief, secretRules) {
20057
20919
  ...brief.bar === void 0 ? {} : { bar: mask(brief.bar) },
20058
20920
  ...brief.calibration === void 0 ? {} : { calibration: mask(brief.calibration) },
20059
20921
  ...brief.preamble === void 0 ? {} : { preamble: mask(brief.preamble) },
20060
- notes: brief.notes.map((note) => ({ heading: note.heading, body: mask(note.body) }))
20922
+ // The heading is prose too. Masking only the body left `## Incident ghp_…` in PROMPT.md:
20923
+ // ownerNotesSection reproduced the heading as a Markdown title, where no line rule that
20924
+ // expects `key: value` can see it.
20925
+ notes: brief.notes.map((note) => ({ heading: mask(note.heading), body: mask(note.body) }))
20061
20926
  };
20062
20927
  }
20928
+ function maskProse(value, secretRules, scope) {
20929
+ return scanAndRedactSecrets(value, secretRules ?? [], scope).redacted;
20930
+ }
20063
20931
  function maskOverview(overview, secretRules) {
20064
- const mask = (value) => maskPathText(value, secretRules);
20932
+ const mask = (value) => maskProse(value, secretRules, "overview");
20065
20933
  return {
20066
20934
  ...overview.description === void 0 ? {} : { description: mask(overview.description) },
20067
20935
  ...overview.summary === void 0 ? {} : { summary: mask(overview.summary) },
@@ -20093,9 +20961,9 @@ function listEntries(dir) {
20093
20961
  return;
20094
20962
  }
20095
20963
  for (const child of children) {
20096
- const relative16 = prefix === "" ? child.name : `${prefix}/${child.name}`;
20097
- entries.push(relative16);
20098
- if (child.isDirectory()) walk2(path25.join(absolute, child.name), relative16);
20964
+ const relative17 = prefix === "" ? child.name : `${prefix}/${child.name}`;
20965
+ entries.push(relative17);
20966
+ if (child.isDirectory()) walk2(path25.join(absolute, child.name), relative17);
20099
20967
  }
20100
20968
  };
20101
20969
  walk2(dir, "");
@@ -20550,6 +21418,7 @@ function ensureParentDirectory(target, label) {
20550
21418
  }
20551
21419
  var LOCK_HEARTBEAT_MS = 5e3;
20552
21420
  var LOCK_STALE_HEARTBEAT_MS = 12e4;
21421
+ var LOCK_EMPTY_GRACE_MS = 5e3;
20553
21422
  var LOCK_HEARTBEAT_SOURCE = `
20554
21423
  const { parentPort, workerData } = require("node:worker_threads");
20555
21424
  const fs = require("node:fs");
@@ -20691,9 +21560,11 @@ function lockOwnerIsGone(lockPath) {
20691
21560
  try {
20692
21561
  pid = JSON.parse(raw).pid;
20693
21562
  } catch {
20694
- return lockFileIsAncient(lockPath);
21563
+ return lockFileIsAncient(lockPath, LOCK_EMPTY_GRACE_MS);
21564
+ }
21565
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) {
21566
+ return lockFileIsAncient(lockPath, LOCK_EMPTY_GRACE_MS);
20695
21567
  }
20696
- if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return lockFileIsAncient(lockPath);
20697
21568
  try {
20698
21569
  process.kill(pid, 0);
20699
21570
  return lockFileIsAncient(lockPath);
@@ -20720,8 +21591,8 @@ function reclaimStaleLock(lockPath) {
20720
21591
  return false;
20721
21592
  }
20722
21593
  }
20723
- function lockFileIsAncient(lockPath) {
20724
- return lockHeartbeatAgeMs(lockPath) > LOCK_STALE_HEARTBEAT_MS;
21594
+ function lockFileIsAncient(lockPath, thresholdMs = LOCK_STALE_HEARTBEAT_MS) {
21595
+ return lockHeartbeatAgeMs(lockPath) > thresholdMs;
20725
21596
  }
20726
21597
  function writeManifestAtomically(manifestPath, manifest) {
20727
21598
  const tempPath = `${manifestPath}.${process.pid}.tmp`;
@@ -20736,13 +21607,13 @@ function writeManifestAtomically(manifestPath, manifest) {
20736
21607
  throw err;
20737
21608
  }
20738
21609
  }
20739
- function swapIntoPlace(stagingDir, outDir, beforeSwap) {
21610
+ function swapIntoPlace(stagingDir, outDir, beforeSwap, onStagingPreserved) {
20740
21611
  ensureParentDirectory(outDir, "outDir");
20741
21612
  const deadline = Date.now() + 3e3;
20742
21613
  let delay = 25;
20743
21614
  for (; ; ) {
20744
21615
  try {
20745
- swapOnce(stagingDir, outDir, beforeSwap);
21616
+ swapOnce(stagingDir, outDir, beforeSwap, onStagingPreserved);
20746
21617
  return;
20747
21618
  } catch (err) {
20748
21619
  const code = err.code;
@@ -20777,7 +21648,7 @@ function recoverInterruptedPublish(outDir) {
20777
21648
  } catch {
20778
21649
  }
20779
21650
  }
20780
- function swapOnce(stagingDir, outDir, beforeSwap) {
21651
+ function swapOnce(stagingDir, outDir, beforeSwap, onStagingPreserved) {
20781
21652
  const backupDir = `${outDir}.backup-${process.pid}-${Date.now()}`;
20782
21653
  const hadPrevious = fs24.existsSync(outDir);
20783
21654
  if (hadPrevious) beforeSwap?.();
@@ -20788,6 +21659,7 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
20788
21659
  movedAside = true;
20789
21660
  } catch (err) {
20790
21661
  if (!isLockError(err)) throw err;
21662
+ onStagingPreserved?.();
20791
21663
  fs24.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
20792
21664
  process.stderr.write(
20793
21665
  `\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.
@@ -20818,6 +21690,7 @@ function swapOnce(stagingDir, outDir, beforeSwap) {
20818
21690
  if (fs24.existsSync(outDir)) fs24.rmSync(outDir, { recursive: true, force: true });
20819
21691
  fs24.renameSync(backupDir, outDir);
20820
21692
  } else if (hadPrevious && !movedAside) {
21693
+ onStagingPreserved?.();
20821
21694
  process.stderr.write(
20822
21695
  `\u26A0 The previous snapshot at ${outDir} was removed and the new one could not be moved into place. It is complete at ${stagingDir}.
20823
21696
  `
@@ -21007,7 +21880,7 @@ function generateSnapshot(configInput, options) {
21007
21880
  // output — but only at these exact paths, not at every directory that shares the name.
21008
21881
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
21009
21882
  (directory) => path25.relative(config.cwd, path25.resolve(config.cwd, directory)).replace(/\\/g, "/")
21010
- ).filter((relative16) => relative16.length > 0 && !relative16.startsWith("..")),
21883
+ ).filter((relative17) => relative17.length > 0 && !relative17.startsWith("..")),
21011
21884
  // A staged path can be absent from the working tree while its index blob exists. Discovery
21012
21885
  // lists the working tree, so those paths would never reach the scan at all.
21013
21886
  ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
@@ -21153,9 +22026,9 @@ function generateSnapshot(configInput, options) {
21153
22026
  const language = detectLanguage(relativePath);
21154
22027
  bump(layerCounts, layer2);
21155
22028
  bump(kindCounts, kind);
21156
- const derivation = takeDerivation(absolutePath, hashSha256, derivationKey) ?? (() => {
22029
+ const derivation = takeDerivation(absolutePath, relativePath, hashSha256, derivationKey) ?? (() => {
21157
22030
  const fresh = deriveFile(relativePath, rawContent, sizeBytes, config);
21158
- rememberDerivation(absolutePath, hashSha256, derivationKey, fresh);
22031
+ rememberDerivation(absolutePath, relativePath, hashSha256, derivationKey, fresh);
21159
22032
  return fresh;
21160
22033
  })();
21161
22034
  const { lineCount } = derivation;
@@ -21335,7 +22208,9 @@ function generateSnapshot(configInput, options) {
21335
22208
  const tokens = Math.max(1, Math.ceil(file.includedBytes / 4));
21336
22209
  const value = (entry(file.relativePath) ? 100 : 0) + layerWeight(file.layer) + Math.min(60, (importers.get(file.relativePath) ?? 0) * 6) - Math.min(40, tokens / 250);
21337
22210
  return { file, tokens, value };
21338
- }).sort((left, right) => right.value - left.value || left.tokens - right.tokens || left.file.relativePath.localeCompare(right.file.relativePath));
22211
+ }).sort(
22212
+ (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)
22213
+ );
21339
22214
  const keep = /* @__PURE__ */ new Set();
21340
22215
  let used = 0;
21341
22216
  const selected = [];
@@ -21697,7 +22572,7 @@ function generateSnapshot(configInput, options) {
21697
22572
  const reportExcludes = [...config.excludePatterns, ...config.presetExclude];
21698
22573
  const diffReport = artifacts.diff ? generateDiffReport(config.cwd, {
21699
22574
  secretRules: config.secretRules,
21700
- excluded: (relativePath) => reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
22575
+ excluded: (relativePath) => isSensitivePath(relativePath) || defaultIgnoreReason(relativePath) !== null || config.include.length > 0 && !config.include.some((pattern) => matchesExclude(relativePath, pattern)) || reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
21701
22576
  }) : null;
21702
22577
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
21703
22578
  const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount, secretRules: config.secretRules }) : null;
@@ -21723,8 +22598,8 @@ function generateSnapshot(configInput, options) {
21723
22598
  task: config.promptTask,
21724
22599
  brief: maskOwnerBrief(config.brief, config.secretRules),
21725
22600
  history: recentCommits(config.cwd).map((commit) => ({
21726
- subject: maskPathText(commit.subject, config.secretRules),
21727
- body: maskPathText(commit.body, config.secretRules)
22601
+ subject: maskProse(commit.subject, config.secretRules, "git-log"),
22602
+ body: maskProse(commit.body, config.secretRules, "git-log")
21728
22603
  })),
21729
22604
  overview: maskOverview(readProjectOverview(config.cwd), config.secretRules)
21730
22605
  }) : null;
@@ -21744,8 +22619,11 @@ function generateSnapshot(configInput, options) {
21744
22619
  const entry = {
21745
22620
  ...file,
21746
22621
  content,
21747
- inclusionMode: file.inclusionMode === "comments-stripped" ? "comments-stripped" : "full",
21748
- ...file.emptyLinesRemoved === true ? { emptyLinesRemoved: true } : {},
22622
+ // `fullContents` is the pre-preview body but still carries comments and blank lines: the
22623
+ // monolith is the whole source, not the comments-stripped variant. Calling it
22624
+ // `comments-stripped` (or copying `emptyLinesRemoved`) described a transformation this
22625
+ // artifact did not perform.
22626
+ inclusionMode: "full",
21749
22627
  isPreviewTruncated: false,
21750
22628
  includedBytes: Buffer.byteLength(content, "utf8"),
21751
22629
  includedLines: countLines(content)
@@ -21824,6 +22702,7 @@ function generateSnapshot(configInput, options) {
21824
22702
  recoverInterruptedPublish(outDir);
21825
22703
  assertReplaceable(outDir, "outDir", config.secretRules);
21826
22704
  let stagingDir = null;
22705
+ let stagingPreserved = false;
21827
22706
  let releaseDeferred = false;
21828
22707
  try {
21829
22708
  ensureParentDirectory(outDir, "outDir");
@@ -21850,21 +22729,25 @@ function generateSnapshot(configInput, options) {
21850
22729
  fs24.mkdirSync(reportsDir, { recursive: true });
21851
22730
  }
21852
22731
  const writtenArtifacts = /* @__PURE__ */ new Map();
22732
+ const ledgerRoot = (targetDir) => stagingDir !== null && (targetDir === stagingDir || targetDir.startsWith(stagingDir + path25.sep)) ? stagingDir : outDir;
22733
+ const ledgerEntry = (targetDir, relativeEntry) => path25.relative(ledgerRoot(targetDir), path25.join(targetDir, ...relativeEntry.split("/"))).split(path25.sep).join("/");
21853
22734
  const writeArtifact = (targetDir, relativeEntry, data) => {
21854
22735
  const full = path25.join(targetDir, ...relativeEntry.split("/"));
21855
22736
  fs24.writeFileSync(full, data, "utf8");
21856
22737
  const stats = fs24.statSync(full);
21857
- writtenArtifacts.set(relativeEntry, {
21858
- digest: { path: relativeEntry, bytes: stats.size, sha256: sha256Hex2(data) },
22738
+ const entry = ledgerEntry(targetDir, relativeEntry);
22739
+ writtenArtifacts.set(entry, {
22740
+ digest: { path: entry, bytes: stats.size, sha256: sha256Hex2(data) },
21859
22741
  mtimeMs: stats.mtimeMs
21860
22742
  });
21861
22743
  };
21862
22744
  const recordArtifact = (targetDir, relativeEntry) => {
21863
22745
  const full = path25.join(targetDir, ...relativeEntry.split("/"));
21864
22746
  const stats = fs24.statSync(full);
21865
- writtenArtifacts.set(relativeEntry, {
22747
+ const entry = ledgerEntry(targetDir, relativeEntry);
22748
+ writtenArtifacts.set(entry, {
21866
22749
  digest: {
21867
- path: relativeEntry,
22750
+ path: entry,
21868
22751
  bytes: stats.size,
21869
22752
  sha256: sha256Hex2(fs24.readFileSync(full))
21870
22753
  },
@@ -21933,7 +22816,14 @@ function generateSnapshot(configInput, options) {
21933
22816
  stagingDir,
21934
22817
  markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21935
22818
  );
21936
- swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
22819
+ swapIntoPlace(
22820
+ stagingDir,
22821
+ outDir,
22822
+ () => assertReplaceable(outDir, "outDir", config.secretRules),
22823
+ () => {
22824
+ stagingPreserved = true;
22825
+ }
22826
+ );
21937
22827
  stagingDir = null;
21938
22828
  const warningsBeforeHook = manifest.warnings.length;
21939
22829
  const pendingHook = runAfterGenerate(config, manifest);
@@ -21987,7 +22877,7 @@ function generateSnapshot(configInput, options) {
21987
22877
  }
21988
22878
  return manifest;
21989
22879
  } catch (err) {
21990
- if (stagingDir !== null) {
22880
+ if (stagingDir !== null && !stagingPreserved) {
21991
22881
  try {
21992
22882
  fs24.rmSync(stagingDir, { recursive: true, force: true });
21993
22883
  } catch {
@@ -22100,6 +22990,10 @@ var DEFAULT_PORT2 = 4789;
22100
22990
  var DEFAULT_MAX_BODY = 2 * 1024 * 1024;
22101
22991
  var RATE_LIMIT = 60;
22102
22992
  var RATE_WINDOW_MS = 1e4;
22993
+ var MAX_IN_FLIGHT = 4;
22994
+ var MAX_SESSION_ENTRIES = 64;
22995
+ var MAX_SSE_SESSIONS = 64;
22996
+ var MAX_RATE_WINDOWS = 1024;
22103
22997
  function generateToken() {
22104
22998
  return crypto6.randomBytes(24).toString("base64url");
22105
22999
  }
@@ -22135,6 +23029,10 @@ async function startHttpTransport(options) {
22135
23029
  const toolCount = buildTools().length;
22136
23030
  const mcpSessions = /* @__PURE__ */ new Map();
22137
23031
  const socketServers = /* @__PURE__ */ new WeakMap();
23032
+ const rememberSession = (id, server) => {
23033
+ if (!mcpSessions.has(id) && mcpSessions.size >= MAX_SESSION_ENTRIES) return;
23034
+ mcpSessions.set(id, server);
23035
+ };
22138
23036
  const anonymousServers = /* @__PURE__ */ new Map();
22139
23037
  const serverFor = (request) => {
22140
23038
  const header = request.headers["mcp-session-id"];
@@ -22143,11 +23041,7 @@ async function startHttpTransport(options) {
22143
23041
  let existing = mcpSessions.get(supplied);
22144
23042
  if (existing === void 0) {
22145
23043
  existing = createMcp();
22146
- if (mcpSessions.size >= 64) {
22147
- const oldest = mcpSessions.keys().next().value;
22148
- if (oldest !== void 0) mcpSessions.delete(oldest);
22149
- }
22150
- mcpSessions.set(supplied, existing);
23044
+ rememberSession(supplied, existing);
22151
23045
  }
22152
23046
  return existing;
22153
23047
  }
@@ -22178,6 +23072,35 @@ async function startHttpTransport(options) {
22178
23072
  return fromQuery !== null && timingSafeEqual3(fromQuery, token);
22179
23073
  };
22180
23074
  const sessions = /* @__PURE__ */ new Map();
23075
+ let inFlight = 0;
23076
+ const acquireToolSlot = () => {
23077
+ if (inFlight >= MAX_IN_FLIGHT) return false;
23078
+ inFlight += 1;
23079
+ return true;
23080
+ };
23081
+ const releaseToolSlot = () => {
23082
+ if (inFlight > 0) inFlight -= 1;
23083
+ };
23084
+ const busyResponse = (id) => ({
23085
+ jsonrpc: "2.0",
23086
+ id: typeof id === "string" || typeof id === "number" || id === null ? id : null,
23087
+ error: {
23088
+ code: -32001,
23089
+ message: "server busy: too many tool calls are already in flight"
23090
+ }
23091
+ });
23092
+ const isToolCall = (message) => message !== null && typeof message === "object" && message.method === "tools/call";
23093
+ const rememberRateWindow = (remote, now) => {
23094
+ if (!sessions.has(remote) && sessions.size >= MAX_RATE_WINDOWS) {
23095
+ for (const [key, value] of sessions) if (value.resetAt <= now) sessions.delete(key);
23096
+ while (sessions.size >= MAX_RATE_WINDOWS) {
23097
+ const oldest = sessions.keys().next().value;
23098
+ if (oldest === void 0) break;
23099
+ sessions.delete(oldest);
23100
+ }
23101
+ }
23102
+ sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
23103
+ };
22181
23104
  const metrics = {
22182
23105
  requests: 0,
22183
23106
  byMethod: /* @__PURE__ */ new Map(),
@@ -22195,7 +23118,7 @@ async function startHttpTransport(options) {
22195
23118
  const now = Date.now();
22196
23119
  const window = sessions.get(remote);
22197
23120
  if (window === void 0 || window.resetAt <= now) {
22198
- sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
23121
+ rememberRateWindow(remote, now);
22199
23122
  return false;
22200
23123
  }
22201
23124
  if (window.count >= RATE_LIMIT) return true;
@@ -22256,6 +23179,10 @@ async function startHttpTransport(options) {
22256
23179
  return;
22257
23180
  }
22258
23181
  if (request.method === "GET" && request.url === "/metrics") {
23182
+ if (token !== null && host !== "127.0.0.1" && host !== "localhost" && host !== "::1" && !tokenAccepted(request, new URL(request.url, "http://localhost"))) {
23183
+ send(401, { error: "unauthorized" }, { "www-authenticate": 'Bearer realm="codebase-snapshot"' });
23184
+ return;
23185
+ }
22259
23186
  const lines = [
22260
23187
  "# HELP snapshot_uptime_seconds Seconds since the process started.",
22261
23188
  "# TYPE snapshot_uptime_seconds gauge",
@@ -22293,6 +23220,10 @@ async function startHttpTransport(options) {
22293
23220
  send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
22294
23221
  return;
22295
23222
  }
23223
+ if (sseSessions.size >= MAX_SSE_SESSIONS) {
23224
+ send(503, { error: "too many open SSE sessions" }, { ...cors, "retry-after": "10" });
23225
+ return;
23226
+ }
22296
23227
  const id = crypto6.randomBytes(12).toString("hex");
22297
23228
  response.writeHead(200, {
22298
23229
  ...cors,
@@ -22302,9 +23233,21 @@ async function startHttpTransport(options) {
22302
23233
  "x-accel-buffering": "no"
22303
23234
  });
22304
23235
  const write = (payload) => {
22305
- response.write(payload);
23236
+ try {
23237
+ response.write(payload);
23238
+ } catch {
23239
+ }
22306
23240
  };
22307
- sseSessions.set(id, { write, end: () => response.end(), server: createMcp() });
23241
+ sseSessions.set(id, {
23242
+ write,
23243
+ end: () => {
23244
+ try {
23245
+ response.end();
23246
+ } catch {
23247
+ }
23248
+ },
23249
+ server: createMcp()
23250
+ });
22308
23251
  const heartbeat = setInterval(() => write(": ping\n\n"), 15e3);
22309
23252
  const cleanup = () => {
22310
23253
  clearInterval(heartbeat);
@@ -22355,10 +23298,27 @@ async function startHttpTransport(options) {
22355
23298
  send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: String(error) } });
22356
23299
  return;
22357
23300
  }
22358
- const answer = await stream.server.handle(message);
22359
- if (answer !== null) stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
23301
+ const gated = isToolCall(message);
23302
+ if (gated && !acquireToolSlot()) {
23303
+ const answer = busyResponse(message.id);
23304
+ stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
23305
+ send(202, "", cors);
23306
+ return;
23307
+ }
23308
+ try {
23309
+ const answer = await stream.server.handle(message);
23310
+ if (answer !== null) stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
23311
+ } finally {
23312
+ if (gated) releaseToolSlot();
23313
+ }
22360
23314
  send(202, "", cors);
22361
- })();
23315
+ })().catch((error) => {
23316
+ log("mcp/http: " + error.message);
23317
+ try {
23318
+ send(500, { jsonrpc: "2.0", id: null, error: { code: -32603, message: "Internal error" } }, cors);
23319
+ } catch {
23320
+ }
23321
+ });
22362
23322
  });
22363
23323
  return;
22364
23324
  }
@@ -22421,13 +23381,22 @@ async function startHttpTransport(options) {
22421
23381
  }
22422
23382
  if (sessionId === "" && !Array.isArray(message) && message.method === "initialize") {
22423
23383
  sessionId = newSessionId();
22424
- mcpSessions.set(sessionId, activeServer);
23384
+ rememberSession(sessionId, activeServer);
22425
23385
  }
22426
23386
  const sessionHeaders = sessionId === "" ? cors : { ...cors, "mcp-session-id": sessionId };
22427
23387
  const answers = [];
22428
23388
  for (const item of batch) {
22429
- const answer = await activeServer.handle(item);
22430
- if (answer !== null) answers.push(answer);
23389
+ const gated = isToolCall(item);
23390
+ if (gated && !acquireToolSlot()) {
23391
+ answers.push(busyResponse(item.id));
23392
+ continue;
23393
+ }
23394
+ try {
23395
+ const answer = await activeServer.handle(item);
23396
+ if (answer !== null) answers.push(answer);
23397
+ } finally {
23398
+ if (gated) releaseToolSlot();
23399
+ }
22431
23400
  }
22432
23401
  if (answers.length === 0) {
22433
23402
  send(202, "", sessionHeaders);
@@ -22446,11 +23415,11 @@ async function startHttpTransport(options) {
22446
23415
  }
22447
23416
  });
22448
23417
  });
22449
- await new Promise((resolve15, reject) => {
23418
+ await new Promise((resolve16, reject) => {
22450
23419
  httpServer.once("error", reject);
22451
23420
  httpServer.listen(port, host, () => {
22452
23421
  httpServer.removeListener("error", reject);
22453
- resolve15();
23422
+ resolve16();
22454
23423
  });
22455
23424
  });
22456
23425
  const address = httpServer.address();
@@ -22461,7 +23430,7 @@ async function startHttpTransport(options) {
22461
23430
  port: actualPort,
22462
23431
  host,
22463
23432
  token,
22464
- close: () => new Promise((resolve15) => {
23433
+ close: () => new Promise((resolve16) => {
22465
23434
  for (const [, session] of sseSessions) {
22466
23435
  try {
22467
23436
  session.end();
@@ -22469,7 +23438,7 @@ async function startHttpTransport(options) {
22469
23438
  }
22470
23439
  }
22471
23440
  sseSessions.clear();
22472
- httpServer.close(() => resolve15());
23441
+ httpServer.close(() => resolve16());
22473
23442
  httpServer.closeAllConnections();
22474
23443
  })
22475
23444
  };
@@ -22723,6 +23692,13 @@ function parseByteOption(raw, optionName, minimum, unit = "byte count") {
22723
23692
  }
22724
23693
  return value;
22725
23694
  }
23695
+ function parsePort(raw) {
23696
+ const value = parsePositiveInteger(raw, "port", 0);
23697
+ if (value !== void 0 && value > 65535) {
23698
+ throw new UsageError(`--port must be at most 65535, received "${raw}".`);
23699
+ }
23700
+ return value;
23701
+ }
22726
23702
  function parseCountOption(raw, optionName, minimum = 0) {
22727
23703
  if (raw === void 0) return void 0;
22728
23704
  const trimmed = raw.trim();
@@ -23011,7 +23987,7 @@ function parseCliArgs(argv) {
23011
23987
  sarif: values.sarif === true ? true : void 0,
23012
23988
  strict: values.strict === true ? true : void 0,
23013
23989
  http: values.http === true ? true : void 0,
23014
- port: parsePositiveInteger(values.port, "port", 1),
23990
+ port: parsePort(values.port),
23015
23991
  host: values.host === void 0 ? void 0 : String(values.host),
23016
23992
  token: values.token === void 0 ? void 0 : String(values.token),
23017
23993
  noAuth: values["no-auth"] === true ? true : void 0,
@@ -23075,8 +24051,8 @@ function splitList(value) {
23075
24051
  }
23076
24052
  function displayOutPath(cwd, outDir, ...segments) {
23077
24053
  const absolute = path27.resolve(cwd, outDir, ...segments);
23078
- const relative16 = path27.relative(cwd, absolute);
23079
- if (relative16 && !relative16.startsWith("..") && !path27.isAbsolute(relative16)) return relative16;
24054
+ const relative17 = path27.relative(cwd, absolute);
24055
+ if (relative17 && !relative17.startsWith("..") && !path27.isAbsolute(relative17)) return relative17;
23080
24056
  return absolute;
23081
24057
  }
23082
24058
  function nextStepHint(cwd, scriptsAddedNow) {
@@ -23649,6 +24625,8 @@ ${USAGE}
23649
24625
  }
23650
24626
  throw err;
23651
24627
  }
24628
+ const environmentToken = process.env.SNAPSHOT_TOKEN?.trim();
24629
+ const tokenOption = invocation.noAuth === true ? { token: null } : invocation.token !== void 0 ? { token: invocation.token } : environmentToken !== void 0 && environmentToken !== "" ? { token: environmentToken } : {};
23652
24630
  if (invocation.command === "init") {
23653
24631
  return await runInitCommand(invocation);
23654
24632
  }
@@ -23668,8 +24646,7 @@ ${USAGE}
23668
24646
  cwd: path27.resolve(invocation.cwd),
23669
24647
  ...invocation.host === void 0 ? {} : { host: invocation.host },
23670
24648
  ...invocation.port === void 0 ? {} : { port: invocation.port },
23671
- ...invocation.noAuth === true ? { token: null } : {},
23672
- ...invocation.token === void 0 ? {} : { token: invocation.token },
24649
+ ...tokenOption,
23673
24650
  ...invocation.allowPrivate === true ? { allowPrivate: true } : {},
23674
24651
  log: (line) => warn(line)
23675
24652
  });
@@ -23681,9 +24658,9 @@ ${USAGE}
23681
24658
  } else {
23682
24659
  warn(" WARNING: --no-auth is on. Any page on this machine can read the repository.");
23683
24660
  }
23684
- await new Promise((resolve15) => {
24661
+ await new Promise((resolve16) => {
23685
24662
  const stop = () => {
23686
- void server.close().then(resolve15);
24663
+ void server.close().then(resolve16);
23687
24664
  };
23688
24665
  process.once("SIGINT", stop);
23689
24666
  process.once("SIGTERM", stop);
@@ -23696,22 +24673,21 @@ ${USAGE}
23696
24673
  cwd: path27.resolve(invocation.cwd),
23697
24674
  ...invocation.host === void 0 ? {} : { host: invocation.host },
23698
24675
  ...invocation.port === void 0 ? {} : { port: invocation.port },
23699
- ...invocation.noAuth === true ? { token: null } : {},
23700
- ...invocation.token === void 0 ? {} : { token: invocation.token },
24676
+ ...tokenOption,
23701
24677
  ...invocation.allowOrigins === void 0 ? {} : { allowedOrigins: invocation.allowOrigins },
23702
24678
  log: (line) => warn(line)
23703
24679
  });
23704
24680
  info("MCP over HTTP: " + transport.url);
23705
- info(" tools: 12 (see describe --format json)");
24681
+ info(" tools: " + buildTools().length + " (see describe --format json)");
23706
24682
  if (transport.token !== null) {
23707
24683
  info(" Authorization: Bearer " + transport.token);
23708
24684
  info(" (generated for this run; pass --token to choose one)");
23709
24685
  } else {
23710
24686
  warn(" WARNING: --no-auth is on. Any page on this machine can read the repository.");
23711
24687
  }
23712
- await new Promise((resolve15) => {
24688
+ await new Promise((resolve16) => {
23713
24689
  const stop = () => {
23714
- void transport.close().then(resolve15);
24690
+ void transport.close().then(resolve16);
23715
24691
  };
23716
24692
  process.once("SIGINT", stop);
23717
24693
  process.once("SIGTERM", stop);
@@ -23809,10 +24785,25 @@ ${USAGE}
23809
24785
  return fail(invocation.format, `Could not read ${indexPath}: ${error.message}`);
23810
24786
  }
23811
24787
  const rows = [];
24788
+ const insidePath = (parent, child) => {
24789
+ const relative17 = path27.relative(parent, child);
24790
+ return relative17 === "" || !relative17.startsWith("..") && !path27.isAbsolute(relative17);
24791
+ };
23812
24792
  for (const member of index.members ?? []) {
23813
24793
  const name = member.name ?? "?";
23814
- const snapshotDir2 = path27.join(outRoot, name);
23815
- const repoDir = path27.resolve(resolved.cwd, member.path ?? name);
24794
+ const snapshotDir2 = path27.resolve(outRoot, name);
24795
+ const repoPath = member.path ?? name;
24796
+ const repoDir = path27.resolve(resolved.cwd, repoPath);
24797
+ if (name.length === 0 || path27.isAbsolute(name) || name.split("/").includes("..") || !insidePath(outRoot, snapshotDir2) || path27.isAbsolute(repoPath) || repoPath.split(/[\\/]/).includes("..") || !insidePath(resolved.cwd, repoDir)) {
24798
+ rows.push({
24799
+ name,
24800
+ score: 0,
24801
+ counts: { pass: 0, warn: 0, fail: 1 },
24802
+ failed: [],
24803
+ error: "the workspace index names a path outside the workspace"
24804
+ });
24805
+ continue;
24806
+ }
23816
24807
  if (!fs26.existsSync(path27.join(snapshotDir2, "manifest.json"))) {
23817
24808
  rows.push({ name, score: 0, counts: { pass: 0, warn: 0, fail: 1 }, failed: [], error: "no snapshot at " + snapshotDir2 });
23818
24809
  continue;
@@ -23980,6 +24971,27 @@ ${USAGE}
23980
24971
  );
23981
24972
  }
23982
24973
  const outRoot = path27.resolve(invocation.cwd, invocation.outDir ?? "snapshot");
24974
+ const workspaceCwd = path27.resolve(invocation.cwd);
24975
+ const outRootRelative = path27.relative(outRoot, workspaceCwd);
24976
+ if (outRootRelative === "" || !outRootRelative.startsWith("..") && !path27.isAbsolute(outRootRelative)) {
24977
+ return fail(
24978
+ invocation.format,
24979
+ `--workspace refuses --out-dir ${outRoot}: it is the working directory or one of its ancestors.`
24980
+ );
24981
+ }
24982
+ const plannedNames = /* @__PURE__ */ new Map();
24983
+ for (const member of members) {
24984
+ const directory = path27.resolve(invocation.cwd, member);
24985
+ const name = path27.basename(directory);
24986
+ const previous = plannedNames.get(name);
24987
+ if (previous !== void 0) {
24988
+ return fail(
24989
+ invocation.format,
24990
+ `--workspace members "${previous}" and "${member}" share the basename "${name}"; each member needs a distinct directory name.`
24991
+ );
24992
+ }
24993
+ plannedNames.set(name, member);
24994
+ }
23983
24995
  const records = [];
23984
24996
  let failed = 0;
23985
24997
  for (const member of members) {
@@ -23999,7 +25011,10 @@ ${USAGE}
23999
25011
  continue;
24000
25012
  }
24001
25013
  try {
24002
- const manifest = generateSnapshot({ cwd: directory, outDir: path27.join(outRoot, name) });
25014
+ const manifest = generateSnapshot(
25015
+ { cwd: directory, outDir: path27.join(outRoot, name) },
25016
+ { dryRun: invocation.dryRun }
25017
+ );
24003
25018
  records.push({
24004
25019
  name,
24005
25020
  path: directory,
@@ -24015,7 +25030,7 @@ ${USAGE}
24015
25030
  failed += 1;
24016
25031
  }
24017
25032
  }
24018
- fs26.mkdirSync(outRoot, { recursive: true });
25033
+ if (!invocation.dryRun) fs26.mkdirSync(outRoot, { recursive: true });
24019
25034
  const links = [];
24020
25035
  for (const record of records) {
24021
25036
  const counts = /* @__PURE__ */ new Map();
@@ -24038,16 +25053,48 @@ ${USAGE}
24038
25053
  links.push({ from: record.name, to, specifiers: bucket.count, examples: bucket.examples });
24039
25054
  }
24040
25055
  }
24041
- links.sort((left, right) => (left.from + ">" + left.to).localeCompare(right.from + ">" + right.to));
25056
+ links.sort((left, right) => {
25057
+ const a = left.from + ">" + left.to;
25058
+ const b = right.from + ">" + right.to;
25059
+ return a < b ? -1 : a > b ? 1 : 0;
25060
+ });
24042
25061
  const document = {
24043
25062
  generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
24044
25063
  generator: GENERATOR_VERSION,
24045
- members: records.map(({ imports: _imports, ...rest }) => rest),
25064
+ // The index is published; an absolute host path in it names the author's home directory.
25065
+ // Store the member path relative to the workspace cwd, as manifest paths already are.
25066
+ members: records.map(({ imports: _imports, ...rest }) => ({
25067
+ ...rest,
25068
+ path: path27.relative(workspaceCwd, rest.path).split(path27.sep).join("/") || "."
25069
+ })),
24046
25070
  links
24047
25071
  };
24048
- fs26.writeFileSync(path27.join(outRoot, "WORKSPACE.json"), JSON.stringify(document, null, 2) + "\n", "utf8");
25072
+ if (!invocation.dryRun) {
25073
+ const workspacePath = path27.join(outRoot, "WORKSPACE.json");
25074
+ try {
25075
+ const stats = fs26.lstatSync(workspacePath);
25076
+ if (stats.isSymbolicLink() || !stats.isFile()) {
25077
+ return fail(invocation.format, `${workspacePath} is not a regular file; refusing to replace it.`);
25078
+ }
25079
+ } catch (error) {
25080
+ if (error.code !== "ENOENT") throw error;
25081
+ }
25082
+ const tempPath = `${workspacePath}.${process.pid}.${Date.now()}.tmp`;
25083
+ try {
25084
+ fs26.writeFileSync(tempPath, JSON.stringify(document, null, 2) + "\n", "utf8");
25085
+ fs26.renameSync(tempPath, workspacePath);
25086
+ } catch (error) {
25087
+ try {
25088
+ fs26.rmSync(tempPath, { force: true });
25089
+ } catch {
25090
+ }
25091
+ throw error;
25092
+ }
25093
+ }
24049
25094
  emit(invocation.format, document, () => {
24050
- info("\n\u{1F5C2} Workspace: " + records.length + " of " + members.length + " member(s) written under " + outRoot);
25095
+ info(
25096
+ "\n\u{1F5C2} Workspace: " + records.length + " of " + members.length + (invocation.dryRun ? " member(s) planned; nothing was written." : " member(s) written under " + outRoot)
25097
+ );
24051
25098
  for (const record of records) {
24052
25099
  info(" - " + record.name + " (" + record.fingerprint.slice(0, 12) + ")");
24053
25100
  }
@@ -24081,8 +25128,10 @@ ${USAGE}
24081
25128
  if (shape !== null) {
24082
25129
  return fail(invocation.format, manifestPath + " is not a snapshot manifest: " + shape);
24083
25130
  }
24084
- deltaBase = { manifest: base, path: manifestPath };
24085
- info(" Delta base: " + manifestPath + " (" + base.files.length + " files, fingerprint " + base.fingerprint.slice(0, 12) + ")");
25131
+ const relativeBase = path27.relative(invocation.cwd, manifestPath).split(path27.sep).join("/");
25132
+ const recordedBase = relativeBase === "" || relativeBase.startsWith("..") || path27.isAbsolute(relativeBase) ? path27.basename(manifestPath) : relativeBase;
25133
+ deltaBase = { manifest: base, path: recordedBase };
25134
+ info(" Delta base: " + recordedBase + " (" + base.files.length + " files, fingerprint " + base.fingerprint.slice(0, 12) + ")");
24086
25135
  }
24087
25136
  const manifest = generateSnapshot(resolved, {
24088
25137
  dryRun: invocation.dryRun,
@@ -24257,8 +25306,8 @@ function comparablePath(value) {
24257
25306
  return process.platform === "win32" ? absolute.toLowerCase() : absolute;
24258
25307
  }
24259
25308
  function isSameOrInside(parent, candidate) {
24260
- const relative16 = path27.relative(parent, candidate);
24261
- return relative16 === "" || relative16 !== ".." && !relative16.startsWith(`..${path27.sep}`) && !path27.isAbsolute(relative16);
25309
+ const relative17 = path27.relative(parent, candidate);
25310
+ return relative17 === "" || relative17 !== ".." && !relative17.startsWith(`..${path27.sep}`) && !path27.isAbsolute(relative17);
24262
25311
  }
24263
25312
  function isGeneratedWatchPath(candidate, paths) {
24264
25313
  const absolute = comparablePath(path27.resolve(paths.cwd, candidate));
@@ -24394,12 +25443,12 @@ async function runWatchLoop(invocation, resolved, options) {
24394
25443
  info(`\u26A0 Watch error: ${err.message}`);
24395
25444
  info(" The watcher may have missed changes. Restart with Ctrl+C if they stop arriving.");
24396
25445
  });
24397
- await new Promise((resolve15) => {
25446
+ await new Promise((resolve16) => {
24398
25447
  const stop = () => {
24399
25448
  stopped = true;
24400
25449
  if (timer) clearTimeout(timer);
24401
25450
  watcher.close();
24402
- resolve15();
25451
+ resolve16();
24403
25452
  };
24404
25453
  process.once("SIGINT", stop);
24405
25454
  process.once("SIGTERM", stop);