codebase-snapshot 0.20.3 → 0.20.4

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
@@ -12,8 +12,8 @@ import * as path8 from "path";
12
12
 
13
13
  // src/scanner/files.ts
14
14
  import * as childProcess from "child_process";
15
- import * as fs2 from "fs";
16
- import * as path2 from "path";
15
+ import * as fs3 from "fs";
16
+ import * as path3 from "path";
17
17
 
18
18
  // src/presets/context.ts
19
19
  import * as fs from "fs";
@@ -167,8 +167,8 @@ function workspacePackageDirs(cwd, patterns) {
167
167
  function scanWorkspacePackages(cwd, patterns) {
168
168
  const files = /* @__PURE__ */ new Set();
169
169
  const dependencies = /* @__PURE__ */ new Set();
170
- for (const relative15 of workspacePackageDirs(cwd, patterns)) {
171
- const full = path.join(cwd, relative15);
170
+ for (const relative16 of workspacePackageDirs(cwd, patterns)) {
171
+ const full = path.join(cwd, relative16);
172
172
  try {
173
173
  for (const entry of fs.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
174
174
  } catch {
@@ -2197,9 +2197,72 @@ function applySpansKeepingQuotes(line, spans) {
2197
2197
  return out;
2198
2198
  }
2199
2199
 
2200
+ // src/signing.ts
2201
+ import * as crypto from "crypto";
2202
+ import * as fs2 from "fs";
2203
+ import * as path2 from "path";
2204
+ var SIGNATURE_FILE = "signature.json";
2205
+ function loadSigningKey(environment = process.env) {
2206
+ const pem = environment.SNAPSHOT_SIGNING_KEY;
2207
+ if (pem === void 0 || pem.trim() === "") return null;
2208
+ return crypto.createPrivateKey({ key: pem, format: "pem" });
2209
+ }
2210
+ function signManifest(manifestPath, options = {}) {
2211
+ const bytes = fs2.readFileSync(manifestPath);
2212
+ const manifest = JSON.parse(bytes.toString("utf8"));
2213
+ if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
2214
+ throw new Error("refusing to sign: the manifest has no valid fingerprint");
2215
+ }
2216
+ const configured = options.key ?? null;
2217
+ const key = configured ?? crypto.generateKeyPairSync("ed25519").privateKey;
2218
+ const publicKey = crypto.createPublicKey(key).export({ type: "spki", format: "der" }).toString("base64");
2219
+ const signature = crypto.sign(null, bytes, key).toString("base64");
2220
+ return {
2221
+ algorithm: "ed25519",
2222
+ signedAt: options.signedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
2223
+ fingerprint: manifest.fingerprint,
2224
+ manifestSha256: crypto.createHash("sha256").update(bytes).digest("hex"),
2225
+ publicKey,
2226
+ signature,
2227
+ keyOrigin: configured === null ? "generated" : "configured"
2228
+ };
2229
+ }
2230
+ function verifySnapshotSignature(snapshotDir) {
2231
+ const signaturePath = path2.join(snapshotDir, SIGNATURE_FILE);
2232
+ const manifestPath = path2.join(snapshotDir, "manifest.json");
2233
+ if (!fs2.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
2234
+ let record;
2235
+ try {
2236
+ record = JSON.parse(fs2.readFileSync(signaturePath, "utf8"));
2237
+ } catch (error) {
2238
+ return { ok: false, reason: "signature.json is not JSON: " + error.message };
2239
+ }
2240
+ if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
2241
+ return { ok: false, reason: "signature.json is not an ed25519 record" };
2242
+ }
2243
+ let bytes;
2244
+ try {
2245
+ bytes = fs2.readFileSync(manifestPath);
2246
+ } catch {
2247
+ return { ok: false, reason: "the signed manifest is missing" };
2248
+ }
2249
+ const sha2562 = crypto.createHash("sha256").update(bytes).digest("hex");
2250
+ if (sha2562 !== record.manifestSha256) {
2251
+ return { ok: false, reason: "manifest.json changed after it was signed" };
2252
+ }
2253
+ let verified = false;
2254
+ try {
2255
+ const key = crypto.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
2256
+ verified = crypto.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
2257
+ } catch (error) {
2258
+ return { ok: false, reason: "the signature could not be checked: " + error.message };
2259
+ }
2260
+ return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
2261
+ }
2262
+
2200
2263
  // src/version.ts
2201
2264
  var GENERATOR_NAME = "codebase-snapshot";
2202
- var GENERATOR_VERSION = "0.20.3";
2265
+ var GENERATOR_VERSION = "0.20.4";
2203
2266
  var SCHEMA_VERSION = "3.0.0";
2204
2267
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2205
2268
  function isOurGeneratorName(name) {
@@ -2216,14 +2279,14 @@ var PRESET_IGNORES = new Set(
2216
2279
  );
2217
2280
  function readLinkTarget(linkPath, fallback) {
2218
2281
  try {
2219
- return fs2.readlinkSync(linkPath);
2282
+ return fs3.readlinkSync(linkPath);
2220
2283
  } catch {
2221
2284
  return fallback;
2222
2285
  }
2223
2286
  }
2224
2287
  function brokenLinkRecord(linkPath, relativePath, rootReal) {
2225
2288
  const rawTarget = readLinkTarget(linkPath, linkPath);
2226
- const resolvedFallback = path2.resolve(path2.dirname(linkPath), rawTarget);
2289
+ const resolvedFallback = path3.resolve(path3.dirname(linkPath), rawTarget);
2227
2290
  return isInside(rootReal, resolvedFallback) ? { path: relativePath, reason: "read-error", detail: "broken symlink" } : {
2228
2291
  path: relativePath,
2229
2292
  reason: "outside-root",
@@ -2231,8 +2294,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
2231
2294
  };
2232
2295
  }
2233
2296
  function isInside(root, candidate) {
2234
- const relative15 = path2.relative(root, candidate);
2235
- return relative15 === "" || !relative15.startsWith(`..${path2.sep}`) && relative15 !== ".." && !path2.isAbsolute(relative15);
2297
+ const relative16 = path3.relative(root, candidate);
2298
+ return relative16 === "" || !relative16.startsWith(`..${path3.sep}`) && relative16 !== ".." && !path3.isAbsolute(relative16);
2236
2299
  }
2237
2300
  var GIT_OUTPUT_LIMIT = 68157440;
2238
2301
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -2492,10 +2555,10 @@ function trimUnescapedTrailingSpaces(line) {
2492
2555
  return line.slice(0, end);
2493
2556
  }
2494
2557
  function readGitignoreRules(dir) {
2495
- const gitignorePath2 = path2.join(dir, ".gitignore");
2558
+ const gitignorePath2 = path3.join(dir, ".gitignore");
2496
2559
  let raw;
2497
2560
  try {
2498
- raw = fs2.readFileSync(gitignorePath2, "utf8");
2561
+ raw = fs3.readFileSync(gitignorePath2, "utf8");
2499
2562
  } catch {
2500
2563
  return [];
2501
2564
  }
@@ -2706,7 +2769,7 @@ function listIgnoredPaths(cwd) {
2706
2769
  }
2707
2770
  function hasSnapshotMarker(target) {
2708
2771
  try {
2709
- return fs2.statSync(target).isDirectory() && fs2.existsSync(path2.join(target, ".codebase-snapshot"));
2772
+ return fs3.statSync(target).isDirectory() && isToolOwnedDirectory2(target);
2710
2773
  } catch {
2711
2774
  return false;
2712
2775
  }
@@ -2715,7 +2778,7 @@ var IGNORABLE_DIRECTORY_ENTRIES = /* @__PURE__ */ new Set([".DS_Store"]);
2715
2778
  function isToolOwnedDirectory2(dir) {
2716
2779
  let raw;
2717
2780
  try {
2718
- raw = fs2.readFileSync(path2.join(dir, ".codebase-snapshot"), "utf8");
2781
+ raw = fs3.readFileSync(path3.join(dir, ".codebase-snapshot"), "utf8");
2719
2782
  } catch {
2720
2783
  return false;
2721
2784
  }
@@ -2742,12 +2805,14 @@ function isToolOwnedDirectory2(dir) {
2742
2805
  }
2743
2806
  let entries;
2744
2807
  try {
2745
- entries = fs2.readdirSync(dir);
2808
+ entries = fs3.readdirSync(dir);
2746
2809
  } catch {
2747
2810
  return false;
2748
2811
  }
2749
2812
  return entries.every(
2750
- (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || accounted.has(entry)
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)
2751
2816
  );
2752
2817
  }
2753
2818
  function makeToolOwnedDecider(cwd, toolOwnedPaths) {
@@ -2759,7 +2824,7 @@ function makeToolOwnedDecider(cwd, toolOwnedPaths) {
2759
2824
  const prefix = parts.slice(0, depth).join("/");
2760
2825
  let hasMarker = markers.get(prefix);
2761
2826
  if (hasMarker === void 0) {
2762
- hasMarker = isToolOwnedDirectory2(path2.join(cwd, prefix));
2827
+ hasMarker = isToolOwnedDirectory2(path3.join(cwd, prefix));
2763
2828
  markers.set(prefix, hasMarker);
2764
2829
  }
2765
2830
  if (hasMarker) return true;
@@ -2774,7 +2839,7 @@ function makeLinkProbe() {
2774
2839
  let known = cache.get(absolutePath);
2775
2840
  if (known === void 0) {
2776
2841
  try {
2777
- known = fs2.lstatSync(absolutePath).isSymbolicLink();
2842
+ known = fs3.lstatSync(absolutePath).isSymbolicLink();
2778
2843
  } catch {
2779
2844
  known = false;
2780
2845
  }
@@ -2787,7 +2852,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
2787
2852
  const isLink = makeLinkProbe();
2788
2853
  let rootReal = cwd;
2789
2854
  try {
2790
- rootReal = fs2.realpathSync(cwd);
2855
+ rootReal = fs3.realpathSync(cwd);
2791
2856
  } catch {
2792
2857
  }
2793
2858
  const reported = /* @__PURE__ */ new Set();
@@ -2802,7 +2867,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
2802
2867
  let linkedPath = null;
2803
2868
  for (let depth = 1; depth <= parts.length; depth += 1) {
2804
2869
  const prefix = parts.slice(0, depth).join("/");
2805
- if (isLink(path2.join(cwd, prefix))) {
2870
+ if (isLink(path3.join(cwd, prefix))) {
2806
2871
  linkedPath = prefix;
2807
2872
  break;
2808
2873
  }
@@ -2811,11 +2876,11 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
2811
2876
  kept.push(candidate);
2812
2877
  continue;
2813
2878
  }
2814
- const absolute = path2.join(cwd, linkedPath);
2879
+ const absolute = path3.join(cwd, linkedPath);
2815
2880
  const rawTarget = readLinkTarget(absolute, absolute);
2816
2881
  let targetReal = null;
2817
2882
  try {
2818
- targetReal = fs2.realpathSync(absolute);
2883
+ targetReal = fs3.realpathSync(absolute);
2819
2884
  } catch {
2820
2885
  targetReal = null;
2821
2886
  }
@@ -2833,7 +2898,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
2833
2898
  }
2834
2899
  let stats = null;
2835
2900
  try {
2836
- stats = fs2.statSync(absolute);
2901
+ stats = fs3.statSync(absolute);
2837
2902
  } catch {
2838
2903
  stats = null;
2839
2904
  }
@@ -2857,6 +2922,15 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
2857
2922
  });
2858
2923
  continue;
2859
2924
  }
2925
+ const targetRelative = path3.relative(rootReal, targetReal).split(path3.sep).join("/");
2926
+ if (isSensitivePath(targetRelative)) {
2927
+ report2(linkedPath, {
2928
+ path: linkedPath,
2929
+ reason: "sensitive-file",
2930
+ detail: "link target is a credential-bearing file; not followed"
2931
+ });
2932
+ continue;
2933
+ }
2860
2934
  kept.push(candidate);
2861
2935
  }
2862
2936
  return kept;
@@ -2921,7 +2995,7 @@ function collectFiles(cwd, options = {}) {
2921
2995
  "Discovery mode is `git`, but git could not list this directory's files. Run inside a working repository, or pass --discovery walk (or auto) to scan the tree directly."
2922
2996
  );
2923
2997
  }
2924
- if (fs2.existsSync(path2.join(cwd, ".git"))) {
2998
+ if (fs3.existsSync(path3.join(cwd, ".git"))) {
2925
2999
  throw new Error(
2926
3000
  "This directory is a git repository, but git could not list its files. A plain walk honours .gitignore files, but git also applies .git/info/exclude and your global excludes file, includes files that are tracked although a .gitignore now matches them, and treats a submodule as a single entry. Fix the repository (git status should work), run outside git, or pass --discovery walk to accept those differences."
2927
3001
  );
@@ -2989,7 +3063,7 @@ function collectFiles(cwd, options = {}) {
2989
3063
  }
2990
3064
  function rootRealFor(root) {
2991
3065
  try {
2992
- return fs2.realpathSync(root);
3066
+ return fs3.realpathSync(root);
2993
3067
  } catch {
2994
3068
  return root;
2995
3069
  }
@@ -2998,18 +3072,18 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
2998
3072
  const results = { files: [], skipped: [] };
2999
3073
  const stack = [];
3000
3074
  const toolDirNames = toolDirNamesFor(reservedPaths);
3001
- const relativeToBase = (target) => path2.relative(baseDir, target).replace(/\\/g, "/") || ".";
3075
+ const relativeToBase = (target) => path3.relative(baseDir, target).replace(/\\/g, "/") || ".";
3002
3076
  const enter = (current, layers) => {
3003
3077
  if (visited.has(current)) return false;
3004
3078
  visited.add(current);
3005
3079
  const localRules = readGitignoreRules(current);
3006
3080
  const gitignoreLayers = localRules.length === 0 ? layers : [
3007
3081
  ...layers,
3008
- { prefix: path2.relative(baseDir, current).replace(/\\/g, "/"), rules: localRules }
3082
+ { prefix: path3.relative(baseDir, current).replace(/\\/g, "/"), rules: localRules }
3009
3083
  ];
3010
3084
  let entries;
3011
3085
  try {
3012
- entries = fs2.readdirSync(current, { withFileTypes: true });
3086
+ entries = fs3.readdirSync(current, { withFileTypes: true });
3013
3087
  } catch {
3014
3088
  results.skipped.push({
3015
3089
  path: relativeToBase(current),
@@ -3031,8 +3105,8 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3031
3105
  }
3032
3106
  const entry = frame.entries[frame.index];
3033
3107
  frame.index += 1;
3034
- const fullPath = path2.join(frame.dir, entry.name);
3035
- const relPath = path2.relative(baseDir, fullPath).replace(/\\/g, "/");
3108
+ const fullPath = path3.join(frame.dir, entry.name);
3109
+ const relPath = path3.relative(baseDir, fullPath).replace(/\\/g, "/");
3036
3110
  if (reservedPaths.has(relPath)) continue;
3037
3111
  if (entry.isDirectory() && DEFAULT_IGNORED_DIRS.includes(entry.name)) {
3038
3112
  results.skipped.push({
@@ -3065,14 +3139,14 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3065
3139
  if (entry.isSymbolicLink()) {
3066
3140
  let targetReal;
3067
3141
  try {
3068
- targetReal = fs2.realpathSync(fullPath);
3142
+ targetReal = fs3.realpathSync(fullPath);
3069
3143
  } catch {
3070
3144
  results.skipped.push(brokenLinkRecord(fullPath, relPath, rootReal));
3071
3145
  continue;
3072
3146
  }
3073
3147
  let stats;
3074
3148
  try {
3075
- stats = fs2.statSync(fullPath);
3149
+ stats = fs3.statSync(fullPath);
3076
3150
  } catch {
3077
3151
  results.skipped.push({ path: relPath, reason: "read-error", detail: "unreadable symlink" });
3078
3152
  continue;
@@ -3102,7 +3176,7 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3102
3176
  });
3103
3177
  continue;
3104
3178
  }
3105
- const targetRelative = path2.relative(rootReal, targetReal).split(path2.sep).join("/");
3179
+ const targetRelative = path3.relative(rootReal, targetReal).split(path3.sep).join("/");
3106
3180
  if (isSensitivePath(targetRelative)) {
3107
3181
  results.skipped.push({
3108
3182
  path: relPath,
@@ -3129,10 +3203,10 @@ import * as fs8 from "fs";
3129
3203
  import * as path7 from "path";
3130
3204
 
3131
3205
  // src/config.ts
3132
- import * as fs3 from "fs";
3133
- import { createHash as createHash2 } from "crypto";
3206
+ import * as fs4 from "fs";
3207
+ import { createHash as createHash3 } from "crypto";
3134
3208
  import { createRequire } from "module";
3135
- import * as path3 from "path";
3209
+ import * as path4 from "path";
3136
3210
  import { pathToFileURL } from "url";
3137
3211
 
3138
3212
  // src/ast/structured.ts
@@ -3308,7 +3382,7 @@ function summarizeMarkdown(content) {
3308
3382
  }
3309
3383
 
3310
3384
  // src/generator/brief.ts
3311
- import { createHash } from "crypto";
3385
+ import { createHash as createHash2 } from "crypto";
3312
3386
  var OWNER_SECTIONS = ["Stakes", "The system", "What came before", "The bar", "Calibration"];
3313
3387
  var RESERVED_SECTIONS = [
3314
3388
  "The job",
@@ -3384,7 +3458,7 @@ function parseOwnerBrief(filePath, text2) {
3384
3458
  return {
3385
3459
  brief: {
3386
3460
  path: filePath,
3387
- digest: createHash("sha256").update(text2, "utf8").digest("hex"),
3461
+ digest: createHash2("sha256").update(text2, "utf8").digest("hex"),
3388
3462
  ...recognised["Stakes"] ? { stakes: recognised["Stakes"] } : {},
3389
3463
  ...recognised["The system"] ? { system: recognised["The system"] } : {},
3390
3464
  ...recognised["What came before"] ? { history: recognised["What came before"] } : {},
@@ -3432,20 +3506,20 @@ var CONFIG_FILENAMES = [
3432
3506
  ];
3433
3507
  function findConfigFile(cwd) {
3434
3508
  for (const filename of CONFIG_FILENAMES) {
3435
- const fullPath = path3.join(cwd, filename);
3509
+ const fullPath = path4.join(cwd, filename);
3436
3510
  let stats = null;
3437
3511
  try {
3438
- stats = fs3.statSync(fullPath);
3512
+ stats = fs4.statSync(fullPath);
3439
3513
  } catch {
3440
- if (fs3.existsSync(fullPath)) return fullPath;
3514
+ if (fs4.existsSync(fullPath)) return fullPath;
3441
3515
  continue;
3442
3516
  }
3443
3517
  if (stats.isFile()) return fullPath;
3444
3518
  }
3445
- const pkgJsonPath = path3.join(cwd, "package.json");
3446
- if (!fs3.existsSync(pkgJsonPath)) return null;
3519
+ const pkgJsonPath = path4.join(cwd, "package.json");
3520
+ if (!fs4.existsSync(pkgJsonPath)) return null;
3447
3521
  try {
3448
- const parsed = JSON.parse(stripJsonComments(fs3.readFileSync(pkgJsonPath, "utf8")));
3522
+ const parsed = JSON.parse(stripJsonComments(fs4.readFileSync(pkgJsonPath, "utf8")));
3449
3523
  const snapshot = parsed?.snapshot;
3450
3524
  return typeof snapshot === "object" && snapshot !== null && !Array.isArray(snapshot) ? pkgJsonPath : null;
3451
3525
  } catch {
@@ -3597,21 +3671,25 @@ var CONFIG_KEY_NAMES = [
3597
3671
  "kinds",
3598
3672
  "largeFileBytes",
3599
3673
  "layers",
3674
+ "logCount",
3600
3675
  "layersMode",
3601
3676
  "maxMonolithBytes",
3602
3677
  "maxPartBytes",
3603
3678
  "maxParts",
3604
3679
  "maxPartTokens",
3605
3680
  "outDir",
3681
+ "pack",
3606
3682
  "preset",
3607
3683
  "previewHeadLines",
3608
3684
  "promptTask",
3609
3685
  "staged",
3610
3686
  "previewTailLines",
3687
+ "removeEmptyLines",
3611
3688
  "secretRules",
3612
3689
  "secrets",
3613
3690
  "sarif",
3614
3691
  "skeleton",
3692
+ "stripComments",
3615
3693
  "tmpDir",
3616
3694
  "withDependents"
3617
3695
  ];
@@ -3656,10 +3734,10 @@ function readConfigExport(exported, file) {
3656
3734
  var lastModuleConfig = null;
3657
3735
  function moduleConfigKey(fullPath) {
3658
3736
  try {
3659
- return createHash2("sha256").update(fs3.readFileSync(fullPath)).digest("hex").slice(0, 24);
3737
+ return createHash3("sha256").update(fs4.readFileSync(fullPath)).digest("hex").slice(0, 24);
3660
3738
  } catch {
3661
3739
  try {
3662
- const stats = fs3.statSync(fullPath);
3740
+ const stats = fs4.statSync(fullPath);
3663
3741
  return `stat-${stats.mtimeMs}-${stats.size}`;
3664
3742
  } catch {
3665
3743
  return "unreadable";
@@ -3685,7 +3763,7 @@ async function importConfigModule(fullPath) {
3685
3763
  function attachConfigDir(config, filePath) {
3686
3764
  if (typeof config === "object" && config !== null) {
3687
3765
  Object.defineProperty(config, CONFIG_DIR_SYMBOL, {
3688
- value: path3.dirname(filePath),
3766
+ value: path4.dirname(filePath),
3689
3767
  enumerable: false,
3690
3768
  configurable: true
3691
3769
  });
@@ -3697,12 +3775,12 @@ async function loadConfigFileDetailed(cwd, options = {}) {
3697
3775
  const errors = [];
3698
3776
  const configDirectories = [];
3699
3777
  for (const filename of CONFIG_FILENAMES) {
3700
- const fullPath = path3.join(cwd, filename);
3778
+ const fullPath = path4.join(cwd, filename);
3701
3779
  let candidateStats = null;
3702
3780
  try {
3703
- candidateStats = fs3.statSync(fullPath);
3781
+ candidateStats = fs4.statSync(fullPath);
3704
3782
  } catch {
3705
- if (!fs3.existsSync(fullPath)) continue;
3783
+ if (!fs4.existsSync(fullPath)) continue;
3706
3784
  }
3707
3785
  if (candidateStats !== null && !candidateStats.isFile()) {
3708
3786
  configDirectories.push(fullPath);
@@ -3710,7 +3788,7 @@ async function loadConfigFileDetailed(cwd, options = {}) {
3710
3788
  }
3711
3789
  if (filename.endsWith(".json") || filename === ".snapshotrc") {
3712
3790
  try {
3713
- const config = parseJsonish(fs3.readFileSync(fullPath, "utf8"), fullPath);
3791
+ const config = parseJsonish(fs4.readFileSync(fullPath, "utf8"), fullPath);
3714
3792
  if (config === null || typeof config !== "object" || Array.isArray(config)) {
3715
3793
  throw new Error(
3716
3794
  `${fullPath} does not hold a configuration object (received ${describeValue2(config)}).`
@@ -3750,10 +3828,10 @@ async function loadConfigFileDetailed(cwd, options = {}) {
3750
3828
  continue;
3751
3829
  }
3752
3830
  }
3753
- const pkgJsonPath = path3.join(cwd, "package.json");
3754
- if (fs3.existsSync(pkgJsonPath)) {
3831
+ const pkgJsonPath = path4.join(cwd, "package.json");
3832
+ if (fs4.existsSync(pkgJsonPath)) {
3755
3833
  try {
3756
- const parsed = parseJsonish(fs3.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
3834
+ const parsed = parseJsonish(fs4.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
3757
3835
  const snapshotKey = parsed.snapshot;
3758
3836
  if (snapshotKey && typeof snapshotKey === "object" && !Array.isArray(snapshotKey)) {
3759
3837
  assertKnownConfigKeys(
@@ -3919,11 +3997,38 @@ function readConfiguredBrief(cwd, value) {
3919
3997
  "brief must be a path to a markdown file (received " + describeValue2(value) + ")."
3920
3998
  );
3921
3999
  }
3922
- const filePath = path3.resolve(cwd, value);
4000
+ const rootReal = (() => {
4001
+ try {
4002
+ return fs4.realpathSync(cwd);
4003
+ } catch {
4004
+ return path4.resolve(cwd);
4005
+ }
4006
+ })();
4007
+ const requested = path4.resolve(cwd, value);
4008
+ let filePath;
4009
+ try {
4010
+ filePath = fs4.realpathSync(requested);
4011
+ } catch {
4012
+ throw new Error(
4013
+ 'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
4014
+ );
4015
+ }
4016
+ const relative16 = path4.relative(rootReal, filePath);
4017
+ if (relative16.length === 0 || relative16 === ".." || relative16.startsWith(`..${path4.sep}`) || path4.isAbsolute(relative16)) {
4018
+ throw new Error(
4019
+ '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
+ );
4021
+ }
4022
+ const posixRelative = relative16.split(path4.sep).join("/");
4023
+ if (isSensitivePath(posixRelative) || isSensitivePath(value)) {
4024
+ throw new Error(
4025
+ 'brief "' + value + '" is a credential-bearing file. A snapshot must not reproduce secrets, so it cannot be used as the owner brief.'
4026
+ );
4027
+ }
3923
4028
  let text2;
3924
4029
  try {
3925
- if (!fs3.statSync(filePath).isFile()) throw new Error("not a file");
3926
- text2 = fs3.readFileSync(filePath, "utf8");
4030
+ if (!fs4.statSync(filePath).isFile()) throw new Error("not a file");
4031
+ text2 = fs4.readFileSync(filePath, "utf8");
3927
4032
  } catch {
3928
4033
  throw new Error(
3929
4034
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
@@ -4035,12 +4140,12 @@ function resolveKindRules(value) {
4035
4140
  function outputExcludePatterns(cwd, outDir, tmpDir) {
4036
4141
  const patterns = [];
4037
4142
  for (const dir of [outDir, tmpDir]) {
4038
- const absolute = path3.resolve(cwd, dir);
4039
- const relative15 = path3.relative(cwd, absolute);
4040
- if (!relative15 || relative15 === ".." || relative15.startsWith(`..${path3.sep}`) || path3.isAbsolute(relative15)) {
4143
+ const absolute = path4.resolve(cwd, dir);
4144
+ const relative16 = path4.relative(cwd, absolute);
4145
+ if (!relative16 || relative16 === ".." || relative16.startsWith(`..${path4.sep}`) || path4.isAbsolute(relative16)) {
4041
4146
  continue;
4042
4147
  }
4043
- patterns.push(`${relative15.replace(/\\/g, "/")}/**`);
4148
+ patterns.push(`${relative16.replace(/\\/g, "/")}/**`);
4044
4149
  }
4045
4150
  return patterns;
4046
4151
  }
@@ -4170,11 +4275,11 @@ function resolveCandidateCwd(userConfig, cliOptions, baseDir) {
4170
4275
  );
4171
4276
  }
4172
4277
  const candidate = cliOptions?.cwd || userConfig?.cwd || baseDir || process.cwd();
4173
- const resolved = path3.resolve(candidate);
4174
- if (!fs3.existsSync(resolved)) {
4278
+ const resolved = path4.resolve(candidate);
4279
+ if (!fs4.existsSync(resolved)) {
4175
4280
  throw new Error(`Working directory does not exist: ${resolved}`);
4176
4281
  }
4177
- if (!fs3.statSync(resolved).isDirectory()) {
4282
+ if (!fs4.statSync(resolved).isDirectory()) {
4178
4283
  throw new Error(`Working directory is not a directory: ${resolved}`);
4179
4284
  }
4180
4285
  return resolved;
@@ -4504,7 +4609,7 @@ function configDigest(config) {
4504
4609
  (rule) => `${rule.rule}:${rule.pattern.source}/${rule.pattern.flags}:${rule.valueGroup ?? ""}`
4505
4610
  ).sort()
4506
4611
  };
4507
- return createHash2("sha256").update(JSON.stringify(material)).digest("hex");
4612
+ return createHash3("sha256").update(JSON.stringify(material)).digest("hex");
4508
4613
  }
4509
4614
 
4510
4615
  // src/scanner/changed.ts
@@ -4606,8 +4711,8 @@ function resolveChangedScope(cwd, request) {
4606
4711
  }
4607
4712
 
4608
4713
  // src/scanner/dependents.ts
4609
- import * as fs4 from "fs";
4610
- import * as path4 from "path";
4714
+ import * as fs5 from "fs";
4715
+ import * as path5 from "path";
4611
4716
  import ts from "typescript";
4612
4717
  var RELATIVE_SPECIFIER = /^\.{1,2}\//;
4613
4718
  var IMPORT_CANDIDATE_SUFFIXES = [
@@ -4641,10 +4746,10 @@ var PYTHON_SUFFIXES = [".py", ".pyi", "/__init__.py", "/__init__.pyi"];
4641
4746
  var CASE_INSENSITIVE_FILESYSTEM = process.platform === "win32" || process.platform === "darwin";
4642
4747
  var TSCONFIG_CACHE = /* @__PURE__ */ new Map();
4643
4748
  function tsconfigPathsFor(cwd) {
4644
- const configPath = path4.join(cwd, "tsconfig.json");
4749
+ const configPath = path5.join(cwd, "tsconfig.json");
4645
4750
  let stats;
4646
4751
  try {
4647
- stats = fs4.statSync(configPath);
4752
+ stats = fs5.statSync(configPath);
4648
4753
  } catch (err) {
4649
4754
  if (err.code === "ENOENT") return null;
4650
4755
  return null;
@@ -4678,8 +4783,8 @@ function tsconfigPathsFor(cwd) {
4678
4783
  return value;
4679
4784
  }
4680
4785
  function repositoryRelative(cwd, target) {
4681
- const relative15 = path4.relative(cwd, target).replace(/\\/g, "/");
4682
- return relative15.length === 0 || !relative15.startsWith("..") && !path4.isAbsolute(relative15) ? relative15 : null;
4786
+ const relative16 = path5.relative(cwd, target).replace(/\\/g, "/");
4787
+ return relative16.length === 0 || !relative16.startsWith("..") && !path5.isAbsolute(relative16) ? relative16 : null;
4683
4788
  }
4684
4789
  function rememberFirst(map, key, value) {
4685
4790
  if (!map.has(key)) map.set(key, value);
@@ -4694,15 +4799,15 @@ function buildImportResolver(files, options = {}) {
4694
4799
  if (CASE_INSENSITIVE_FILESYSTEM) {
4695
4800
  rememberFirst(byPathFolded, relativePath.toLowerCase(), relativePath);
4696
4801
  }
4697
- const extension = path4.posix.extname(relativePath);
4802
+ const extension = path5.posix.extname(relativePath);
4698
4803
  if (!SOURCE_EXTENSIONS.has(extension)) return;
4699
4804
  const stem = relativePath.slice(0, -extension.length);
4700
4805
  rememberFirst(byStem, stem, relativePath);
4701
4806
  if (CASE_INSENSITIVE_FILESYSTEM) {
4702
4807
  rememberFirst(byStemFolded, stem.toLowerCase(), relativePath);
4703
4808
  }
4704
- if (path4.posix.basename(stem) === "index") {
4705
- const directory = path4.posix.dirname(stem);
4809
+ if (path5.posix.basename(stem) === "index") {
4810
+ const directory = path5.posix.dirname(stem);
4706
4811
  rememberFirst(byStem, directory, relativePath);
4707
4812
  if (CASE_INSENSITIVE_FILESYSTEM) {
4708
4813
  rememberFirst(byStemFolded, directory.toLowerCase(), relativePath);
@@ -4718,7 +4823,7 @@ function buildImportResolver(files, options = {}) {
4718
4823
  return { byPath, byPathFolded, byStem, byStemFolded, tsconfig: options.tsconfig ?? null };
4719
4824
  }
4720
4825
  function resolveSpecifier(fromFile, specifier, resolver) {
4721
- const extension = path4.posix.extname(fromFile).toLowerCase();
4826
+ const extension = path5.posix.extname(fromFile).toLowerCase();
4722
4827
  const exact = (key) => resolver.byPath.get(key) ?? (CASE_INSENSITIVE_FILESYSTEM ? resolver.byPathFolded.get(key.toLowerCase()) : void 0) ?? null;
4723
4828
  const firstOf = (candidates) => {
4724
4829
  for (const candidate of candidates) {
@@ -4741,34 +4846,34 @@ function resolveSpecifier(fromFile, specifier, resolver) {
4741
4846
  if (PYTHON_EXTENSIONS.has(extension) && specifier.startsWith(".")) {
4742
4847
  const dots = /^\.+/.exec(specifier)?.[0].length ?? 0;
4743
4848
  const rest = specifier.slice(dots).replace(/\./g, "/");
4744
- let base = path4.posix.dirname(fromFile);
4745
- for (let up = 1; up < dots; up += 1) base = path4.posix.dirname(base);
4746
- const joined2 = rest ? path4.posix.normalize(path4.posix.join(base, rest)) : base;
4849
+ let base = path5.posix.dirname(fromFile);
4850
+ for (let up = 1; up < dots; up += 1) base = path5.posix.dirname(base);
4851
+ const joined2 = rest ? path5.posix.normalize(path5.posix.join(base, rest)) : base;
4747
4852
  return firstOf([joined2, ...PYTHON_SUFFIXES.map((suffix) => `${joined2}${suffix}`)]);
4748
4853
  }
4749
4854
  if (RUBY_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
4750
- const joined2 = path4.posix.normalize(
4751
- path4.posix.join(path4.posix.dirname(fromFile), specifier)
4855
+ const joined2 = path5.posix.normalize(
4856
+ path5.posix.join(path5.posix.dirname(fromFile), specifier)
4752
4857
  );
4753
4858
  return firstOf([`${joined2}.rb`, joined2]);
4754
4859
  }
4755
4860
  if (C_EXTENSIONS.has(extension) && specifier.startsWith("./")) {
4756
- const joined2 = path4.posix.normalize(
4757
- path4.posix.join(path4.posix.dirname(fromFile), specifier)
4861
+ const joined2 = path5.posix.normalize(
4862
+ path5.posix.join(path5.posix.dirname(fromFile), specifier)
4758
4863
  );
4759
4864
  return exact(joined2);
4760
4865
  }
4761
4866
  if (extension === ".dart" && !specifier.includes(":")) {
4762
- const joined2 = path4.posix.normalize(
4763
- path4.posix.join(path4.posix.dirname(fromFile), specifier)
4867
+ const joined2 = path5.posix.normalize(
4868
+ path5.posix.join(path5.posix.dirname(fromFile), specifier)
4764
4869
  );
4765
4870
  return firstOf([joined2, `${joined2}.dart`]);
4766
4871
  }
4767
4872
  if (!RELATIVE_SPECIFIER.test(specifier)) {
4768
4873
  return resolveTsconfigSpecifier(specifier, resolver, lookupPath);
4769
4874
  }
4770
- const joined = path4.posix.normalize(
4771
- path4.posix.join(path4.posix.dirname(fromFile), specifier)
4875
+ const joined = path5.posix.normalize(
4876
+ path5.posix.join(path5.posix.dirname(fromFile), specifier)
4772
4877
  );
4773
4878
  return lookupPath(joined);
4774
4879
  }
@@ -4792,13 +4897,13 @@ function resolveTsconfigSpecifier(specifier, resolver, lookupPath) {
4792
4897
  if (captured === null) continue;
4793
4898
  for (const target of rule.targets) {
4794
4899
  const substituted = target.split("*").join(captured);
4795
- const base = config.baseUrl === null ? substituted : path4.posix.join(config.baseUrl, substituted);
4796
- const hit = lookupPath(path4.posix.normalize(base));
4900
+ const base = config.baseUrl === null ? substituted : path5.posix.join(config.baseUrl, substituted);
4901
+ const hit = lookupPath(path5.posix.normalize(base));
4797
4902
  if (hit) return hit;
4798
4903
  }
4799
4904
  }
4800
4905
  if (config.baseUrl !== null) {
4801
- return lookupPath(path4.posix.normalize(path4.posix.join(config.baseUrl, specifier)));
4906
+ return lookupPath(path5.posix.normalize(path5.posix.join(config.baseUrl, specifier)));
4802
4907
  }
4803
4908
  return null;
4804
4909
  }
@@ -4811,7 +4916,7 @@ function importsChangedFile(importerPath, imports, changedPaths, resolver) {
4811
4916
  }
4812
4917
 
4813
4918
  // src/ast/imports.ts
4814
- import * as fs6 from "fs";
4919
+ import * as fs7 from "fs";
4815
4920
 
4816
4921
  // src/ast/ts-parser.ts
4817
4922
  import ts2 from "typescript";
@@ -5649,9 +5754,9 @@ var rubyProfile = {
5649
5754
  eachLine(content, (line) => {
5650
5755
  const trimmed = line.trim();
5651
5756
  if (!trimmed || trimmed.startsWith("#")) return;
5652
- const relative15 = REQUIRE_RELATIVE.exec(trimmed);
5653
- if (relative15) {
5654
- summary.imports.push(`./${relative15[1]}`);
5757
+ const relative16 = REQUIRE_RELATIVE.exec(trimmed);
5758
+ if (relative16) {
5759
+ summary.imports.push(`./${relative16[1]}`);
5655
5760
  return;
5656
5761
  }
5657
5762
  const required = REQUIRE.exec(trimmed);
@@ -5970,8 +6075,8 @@ function summarizeWithProfile(path28, content) {
5970
6075
  }
5971
6076
 
5972
6077
  // src/scanner/binary.ts
5973
- import * as fs5 from "fs";
5974
- import * as path5 from "path";
6078
+ import * as fs6 from "fs";
6079
+ import * as path6 from "path";
5975
6080
  var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
5976
6081
  ".png",
5977
6082
  ".jpg",
@@ -6015,7 +6120,7 @@ var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
6015
6120
  ".so"
6016
6121
  ]);
6017
6122
  function isBinaryExtension(filePath) {
6018
- const ext = path5.extname(filePath).toLowerCase();
6123
+ const ext = path6.extname(filePath).toLowerCase();
6019
6124
  return BINARY_EXTENSIONS.has(ext);
6020
6125
  }
6021
6126
  function countControlBytes(buffer) {
@@ -6182,13 +6287,13 @@ function isBinaryFile(absolutePath) {
6182
6287
  if (isBinaryExtension(absolutePath)) return true;
6183
6288
  let fd;
6184
6289
  try {
6185
- fd = fs5.openSync(absolutePath, "r");
6290
+ fd = fs6.openSync(absolutePath, "r");
6186
6291
  const buffer = Buffer.alloc(CHUNK);
6187
6292
  let sample2;
6188
6293
  let position = 0;
6189
6294
  while (position < BINARY_SCAN_BYTES) {
6190
6295
  const wanted = Math.min(CHUNK, BINARY_SCAN_BYTES - position);
6191
- const bytesRead = fs5.readSync(fd, buffer, 0, wanted, position);
6296
+ const bytesRead = fs6.readSync(fd, buffer, 0, wanted, position);
6192
6297
  if (bytesRead === 0) return false;
6193
6298
  const chunk = buffer.subarray(0, bytesRead);
6194
6299
  if (sample2 === void 0) {
@@ -6206,7 +6311,7 @@ function isBinaryFile(absolutePath) {
6206
6311
  } finally {
6207
6312
  if (fd !== void 0) {
6208
6313
  try {
6209
- fs5.closeSync(fd);
6314
+ fs6.closeSync(fd);
6210
6315
  } catch {
6211
6316
  }
6212
6317
  }
@@ -6228,9 +6333,9 @@ function importsOfText(relativePath, text2) {
6228
6333
  function importsOfFile(relativePath, absolutePath) {
6229
6334
  let buffer;
6230
6335
  try {
6231
- const stats = fs6.statSync(absolutePath);
6336
+ const stats = fs7.statSync(absolutePath);
6232
6337
  if (!stats.isFile() || stats.size > SUMMARY_MAX_SOURCE_BYTES) return [];
6233
- buffer = fs6.readFileSync(absolutePath);
6338
+ buffer = fs7.readFileSync(absolutePath);
6234
6339
  } catch {
6235
6340
  return [];
6236
6341
  }
@@ -6239,74 +6344,6 @@ function importsOfFile(relativePath, absolutePath) {
6239
6344
  return importsOfText(relativePath, decoded.text);
6240
6345
  }
6241
6346
 
6242
- // src/signing.ts
6243
- import * as crypto from "crypto";
6244
- import * as fs7 from "fs";
6245
- import * as path6 from "path";
6246
- var SIGNATURE_FILE = "signature.json";
6247
- function loadSigningKey(environment = process.env) {
6248
- const pem = environment.SNAPSHOT_SIGNING_KEY;
6249
- if (pem === void 0 || pem.trim() === "") return null;
6250
- return crypto.createPrivateKey({ key: pem, format: "pem" });
6251
- }
6252
- function signManifest(manifestPath, options = {}) {
6253
- const bytes = fs7.readFileSync(manifestPath);
6254
- const manifest = JSON.parse(bytes.toString("utf8"));
6255
- if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
6256
- throw new Error("refusing to sign: the manifest has no valid fingerprint");
6257
- }
6258
- const configured = options.key ?? null;
6259
- const key = configured ?? crypto.generateKeyPairSync("ed25519").privateKey;
6260
- const publicKey = crypto.createPublicKey(key).export({ type: "spki", format: "der" }).toString("base64");
6261
- const signature = crypto.sign(null, bytes, key).toString("base64");
6262
- return {
6263
- algorithm: "ed25519",
6264
- signedAt: options.signedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
6265
- fingerprint: manifest.fingerprint,
6266
- manifestSha256: crypto.createHash("sha256").update(bytes).digest("hex"),
6267
- publicKey,
6268
- signature,
6269
- keyOrigin: configured === null ? "generated" : "configured"
6270
- };
6271
- }
6272
- function writeSignature(snapshotDir, record) {
6273
- const target = path6.join(snapshotDir, SIGNATURE_FILE);
6274
- fs7.writeFileSync(target, JSON.stringify(record, null, 2) + "\n", "utf8");
6275
- return target;
6276
- }
6277
- function verifySnapshotSignature(snapshotDir) {
6278
- const signaturePath = path6.join(snapshotDir, SIGNATURE_FILE);
6279
- const manifestPath = path6.join(snapshotDir, "manifest.json");
6280
- if (!fs7.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
6281
- let record;
6282
- try {
6283
- record = JSON.parse(fs7.readFileSync(signaturePath, "utf8"));
6284
- } catch (error) {
6285
- return { ok: false, reason: "signature.json is not JSON: " + error.message };
6286
- }
6287
- if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
6288
- return { ok: false, reason: "signature.json is not an ed25519 record" };
6289
- }
6290
- let bytes;
6291
- try {
6292
- bytes = fs7.readFileSync(manifestPath);
6293
- } catch {
6294
- return { ok: false, reason: "the signed manifest is missing" };
6295
- }
6296
- const sha2562 = crypto.createHash("sha256").update(bytes).digest("hex");
6297
- if (sha2562 !== record.manifestSha256) {
6298
- return { ok: false, reason: "manifest.json changed after it was signed" };
6299
- }
6300
- let verified = false;
6301
- try {
6302
- const key = crypto.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
6303
- verified = crypto.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
6304
- } catch (error) {
6305
- return { ok: false, reason: "the signature could not be checked: " + error.message };
6306
- }
6307
- return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
6308
- }
6309
-
6310
6347
  // src/validator/validate.ts
6311
6348
  function maskedPath(value, secretRules) {
6312
6349
  return findSecretInPath(value, secretRules)?.masked ?? value;
@@ -6724,17 +6761,18 @@ function validateSnapshot(configInput) {
6724
6761
  return skippedReasons.get(maskedPath(diskFile, config.secretRules)) ?? null;
6725
6762
  };
6726
6763
  let unchangedScope = null;
6764
+ let stagedScope = null;
6727
6765
  const recordedChangedSince = manifest.config?.changedSince;
6728
6766
  const recordedStaged = manifest.config?.staged === true;
6729
6767
  const recordedWithDependents = manifest.config?.withDependents === true;
6730
6768
  if (recordedChangedSince !== void 0 || recordedStaged) {
6731
6769
  try {
6732
- unchangedScope = new Set(
6733
- resolveChangedScope(config.cwd, {
6734
- ...recordedChangedSince === void 0 ? {} : { changedSince: recordedChangedSince },
6735
- ...recordedStaged ? { staged: true } : {}
6736
- }).paths
6737
- );
6770
+ const scope = resolveChangedScope(config.cwd, {
6771
+ ...recordedChangedSince === void 0 ? {} : { changedSince: recordedChangedSince },
6772
+ ...recordedStaged ? { staged: true } : {}
6773
+ });
6774
+ unchangedScope = new Set(scope.paths);
6775
+ if (recordedStaged) stagedScope = new Set(scope.stagedPaths);
6738
6776
  } catch {
6739
6777
  warnings.push(
6740
6778
  "The snapshot was generated with a changed-files scope, but that scope could not be re-resolved; files it recorded as `unchanged` were trusted rather than re-checked."
@@ -6745,7 +6783,11 @@ function validateSnapshot(configInput) {
6745
6783
  function becameDependent(diskFile) {
6746
6784
  if (!recordedWithDependents || unchangedScope === null) return false;
6747
6785
  dependentResolver ??= buildImportResolver(
6748
- collection.files.map((file) => ({ relativePath: file }))
6786
+ collection.files.map((file) => ({ relativePath: file })),
6787
+ {
6788
+ tsconfig: tsconfigPathsFor(config.cwd),
6789
+ ...unchangedScope === null ? {} : { extraPaths: unchangedScope }
6790
+ }
6749
6791
  );
6750
6792
  return importsChangedFile(
6751
6793
  diskFile,
@@ -6768,7 +6810,7 @@ function validateSnapshot(configInput) {
6768
6810
  // snapshot was reported as drifting.
6769
6811
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
6770
6812
  (directory) => path7.relative(config.cwd, path7.resolve(config.cwd, directory)).replace(/\\/g, "/")
6771
- ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
6813
+ ).filter((relative16) => relative16.length > 0 && !relative16.startsWith(".."))
6772
6814
  });
6773
6815
  for (const diskFile of collection.files) {
6774
6816
  const snapshotHash = manifestFileMap.get(diskFile);
@@ -6794,7 +6836,8 @@ function validateSnapshot(configInput) {
6794
6836
  }
6795
6837
  let diskHash;
6796
6838
  try {
6797
- diskHash = sha256Hex(fs8.readFileSync(path7.join(config.cwd, diskFile)));
6839
+ const stagedBlob = recordedStaged && stagedScope?.has(diskFile) === true ? readStagedBlob(config.cwd, diskFile) : null;
6840
+ diskHash = sha256Hex(stagedBlob ?? fs8.readFileSync(path7.join(config.cwd, diskFile)));
6798
6841
  } catch (err) {
6799
6842
  if (err.code === "ENOENT") {
6800
6843
  drift.missingOnDisk.push(diskFile);
@@ -7248,8 +7291,8 @@ function validateSnapshot(configInput) {
7248
7291
  const target = match[1].split("#")[0];
7249
7292
  if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
7250
7293
  const resolved = path7.resolve(snapshotDir, "reports", target);
7251
- const relative15 = path7.relative(snapshotDir, resolved);
7252
- if (relative15.startsWith("..") || path7.isAbsolute(relative15) || !fs8.existsSync(resolved)) {
7294
+ const relative16 = path7.relative(snapshotDir, resolved);
7295
+ if (relative16.startsWith("..") || path7.isAbsolute(relative16) || !fs8.existsSync(resolved)) {
7253
7296
  drift.partIssues.push({
7254
7297
  part: key,
7255
7298
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -7905,23 +7948,23 @@ function describeMatcher(matcher) {
7905
7948
  function normalizeTarget(cwd, target) {
7906
7949
  const resolvedCwd = path10.resolve(cwd);
7907
7950
  const absolute = path10.resolve(resolvedCwd, target);
7908
- const relative15 = path10.relative(resolvedCwd, absolute);
7909
- if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path10.sep}`) || path10.isAbsolute(relative15)) {
7951
+ const relative16 = path10.relative(resolvedCwd, absolute);
7952
+ if (relative16 === "" || relative16 === ".." || relative16.startsWith(`..${path10.sep}`) || path10.isAbsolute(relative16)) {
7910
7953
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
7911
7954
  }
7912
- return { relative: relative15.split(path10.sep).join("/"), outsideRoot: false };
7955
+ return { relative: relative16.split(path10.sep).join("/"), outsideRoot: false };
7913
7956
  }
7914
7957
  function findRuleMatch(rules, relativePath) {
7915
7958
  return rules.find(
7916
7959
  (rule) => matchRule(relativePath, rule.match)
7917
7960
  );
7918
7961
  }
7919
- function findRecordedAncestor(skipped, relative15, maskedPath2) {
7962
+ function findRecordedAncestor(skipped, relative16, maskedPath2) {
7920
7963
  let nearest;
7921
7964
  for (const record of skipped) {
7922
7965
  const ancestorPath = record.path;
7923
7966
  if (ancestorPath.length === 0) continue;
7924
- const isAncestor = relative15.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
7967
+ const isAncestor = relative16.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
7925
7968
  if (!isAncestor) continue;
7926
7969
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
7927
7970
  }
@@ -7937,8 +7980,8 @@ function readManifest2(config) {
7937
7980
  }
7938
7981
  function explainPath(config, target) {
7939
7982
  const normalized = normalizeTarget(config.cwd, target);
7940
- const relative15 = normalized.relative;
7941
- const maskedPath2 = findSecretInPath(relative15, config.secretRules)?.masked ?? relative15;
7983
+ const relative16 = normalized.relative;
7984
+ const maskedPath2 = findSecretInPath(relative16, config.secretRules)?.masked ?? relative16;
7942
7985
  if (normalized.outsideRoot) {
7943
7986
  return {
7944
7987
  path: maskedPath2,
@@ -7948,7 +7991,7 @@ function explainPath(config, target) {
7948
7991
  detail: "path resolves outside the configured repository root and was not inspected"
7949
7992
  };
7950
7993
  }
7951
- const absolute = path10.join(config.cwd, relative15);
7994
+ const absolute = path10.join(config.cwd, relative16);
7952
7995
  const result = {
7953
7996
  path: maskedPath2,
7954
7997
  exists: fs10.existsSync(absolute),
@@ -7966,11 +8009,11 @@ function explainPath(config, target) {
7966
8009
  // that is only missing because the walker dropped the tool's own output directory.
7967
8010
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
7968
8011
  (directory) => path10.relative(config.cwd, path10.resolve(config.cwd, directory)).replace(/\\/g, "/")
7969
- ).filter((relative16) => relative16.length > 0 && !relative16.startsWith(".."))
8012
+ ).filter((relative17) => relative17.length > 0 && !relative17.startsWith(".."))
7970
8013
  });
7971
- if (!collection.files.includes(relative15)) {
8014
+ if (!collection.files.includes(relative16)) {
7972
8015
  const record = collection.skipped.find(
7973
- (entry2) => entry2.path === relative15 || entry2.path === maskedPath2
8016
+ (entry2) => entry2.path === relative16 || entry2.path === maskedPath2
7974
8017
  );
7975
8018
  if (record) {
7976
8019
  result.reason = record.reason;
@@ -7979,7 +8022,7 @@ function explainPath(config, target) {
7979
8022
  result.reason = "missing";
7980
8023
  result.detail = "no such file or directory, relative to the configured cwd";
7981
8024
  } else {
7982
- const ancestor = findRecordedAncestor(collection.skipped, relative15, maskedPath2);
8025
+ const ancestor = findRecordedAncestor(collection.skipped, relative16, maskedPath2);
7983
8026
  if (ancestor) {
7984
8027
  result.reason = ancestor.reason;
7985
8028
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -7999,13 +8042,15 @@ function explainPath(config, target) {
7999
8042
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
8000
8043
  ...config.staged === true ? { staged: true } : {}
8001
8044
  });
8002
- inScope = scope.paths.has(relative15);
8045
+ inScope = scope.paths.has(relative16);
8003
8046
  if (!inScope && config.withDependents === true) {
8004
8047
  inScope = importsChangedFile(
8005
- relative15,
8006
- importsOfFile(relative15, absolute),
8048
+ relative16,
8049
+ importsOfFile(relative16, absolute),
8007
8050
  scope.paths,
8008
- buildImportResolver(collection.files.map((file) => ({ relativePath: file })))
8051
+ buildImportResolver(collection.files.map((file) => ({ relativePath: file })), {
8052
+ tsconfig: tsconfigPathsFor(config.cwd)
8053
+ })
8009
8054
  );
8010
8055
  }
8011
8056
  scopeDetail = scope.detail;
@@ -8061,15 +8106,15 @@ function explainPath(config, target) {
8061
8106
  result.bytes = buffer.length;
8062
8107
  result.lines = countLines(text2);
8063
8108
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
8064
- const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative15);
8109
+ const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative16);
8065
8110
  result.secretCount = findings.length;
8066
8111
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
8067
8112
  let inclusionMode = "full";
8068
- if (config.skeleton === true && isSkeletonizable(relative15)) {
8069
- const skeleton = skeletonizeTypeScript(text2, relative15);
8113
+ if (config.skeleton === true && isSkeletonizable(relative16)) {
8114
+ const skeleton = skeletonizeTypeScript(text2, relative16);
8070
8115
  if (skeleton.collapsed > 0) inclusionMode = "signatures";
8071
8116
  }
8072
- if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative15) && stripComments2(text2, relative15).removed > 0) {
8117
+ if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative16) && stripComments2(text2, relative16).removed > 0) {
8073
8118
  inclusionMode = "comments-stripped";
8074
8119
  }
8075
8120
  if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
@@ -8078,18 +8123,18 @@ function explainPath(config, target) {
8078
8123
  }
8079
8124
  result.inclusionMode = inclusionMode;
8080
8125
  }
8081
- result.layer = classifyLayer(relative15, config.layers);
8082
- result.kind = classifyKind(relative15, config.kinds);
8083
- result.language = detectLanguage(relative15);
8084
- const layerRule = findRuleMatch(config.layers, relative15);
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);
8085
8130
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
8086
- const kindRule = findRuleMatch(config.kinds, relative15);
8131
+ const kindRule = findRuleMatch(config.kinds, relative16);
8087
8132
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
8088
8133
  const manifest = readManifest2(config);
8089
- const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative15) : void 0;
8134
+ const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative16) : void 0;
8090
8135
  result.part = entry?.part ?? null;
8091
8136
  if (entry === void 0) {
8092
- const record = manifest?.skipped?.find((skip) => skip.path === relative15);
8137
+ const record = manifest?.skipped?.find((skip) => skip.path === relative16);
8093
8138
  if (record !== void 0 && (record.reason === "not-selected" || record.reason === "unchanged")) {
8094
8139
  result.included = false;
8095
8140
  result.reason = record.reason;
@@ -8367,9 +8412,17 @@ function renderConfig(answers) {
8367
8412
  // Replace function and method bodies with \`{ /* ... */ }\` in TypeScript files.
8368
8413
  // Signatures and comments stay, so the structure of the file survives.
8369
8414
  skeleton: ${answers.skeleton},
8415
+ // Remove comment text from JavaScript and TypeScript bodies.
8416
+ stripComments: false,
8417
+ // Drop blank lines from emitted bodies; line numbers in the part move.
8418
+ removeEmptyLines: false,
8370
8419
  // Also write reports/audit.sarif (SARIF 2.1.0) for a CI security gate. The
8371
8420
  // matched value is never included \u2014 only the path, the line and the rule.
8372
8421
  sarif: ${answers.sarif},
8422
+ // Commit lines in reports/log.md when the log artifact is enabled.
8423
+ logCount: 20,
8424
+ // Write one single-file pack: "single", "xml" or "json". null = no pack.
8425
+ pack: null,
8373
8426
  // Snapshot only the files that differ from a git ref (for example "main"),
8374
8427
  // plus untracked ones. null means "snapshot everything"; any other value must
8375
8428
  // be a git ref string, and anything else is a configuration error.
@@ -9046,11 +9099,11 @@ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
9046
9099
  const entries = [];
9047
9100
  for (const directory of [outDir, tmpDir]) {
9048
9101
  if (directory === null) continue;
9049
- const relative15 = path12.relative(cwd, path12.resolve(cwd, directory)).replace(/\\/g, "/");
9050
- if (relative15 === "" || relative15 === "." || relative15.startsWith("..") || path12.isAbsolute(relative15)) {
9102
+ const relative16 = path12.relative(cwd, path12.resolve(cwd, directory)).replace(/\\/g, "/");
9103
+ if (relative16 === "" || relative16 === "." || relative16.startsWith("..") || path12.isAbsolute(relative16)) {
9051
9104
  continue;
9052
9105
  }
9053
- entries.push(`/${relative15}/`);
9106
+ entries.push(`/${relative16}/`);
9054
9107
  }
9055
9108
  return [...new Set(entries)];
9056
9109
  }
@@ -9385,10 +9438,10 @@ async function runInit(options) {
9385
9438
  import * as fs13 from "fs";
9386
9439
  import * as path13 from "path";
9387
9440
  function describeTarget(cwd) {
9388
- const relative15 = path13.relative(process.cwd(), cwd);
9389
- if (relative15 === "") return "this directory";
9390
- if (relative15.startsWith("..") || path13.isAbsolute(relative15)) return cwd;
9391
- return relative15;
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;
9392
9445
  }
9393
9446
  function firstRunMessage(reason, cwd) {
9394
9447
  const where = describeTarget(cwd);
@@ -10632,12 +10685,27 @@ function runGit(cwd, args) {
10632
10685
  function isGitRepository(cwd) {
10633
10686
  return runGit(cwd, ["rev-parse", "--is-inside-work-tree"]).out.trim() === "true";
10634
10687
  }
10688
+ function diffSectionPaths(body) {
10689
+ const paths = /* @__PURE__ */ new Set();
10690
+ 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]);
10699
+ }
10700
+ }
10701
+ return [...paths];
10702
+ }
10635
10703
  function generateDiffReport(cwd, options = {}) {
10636
10704
  if (!isGitRepository(cwd)) return null;
10637
10705
  const maxBytes = options.maxBytes ?? 200 * 1024;
10638
10706
  const sections = [];
10639
- let bytes = 0;
10640
10707
  let truncated = false;
10708
+ let omittedSensitive = 0;
10641
10709
  const commands = [
10642
10710
  ["Unstaged", ["diff", "--no-color"]],
10643
10711
  ["Staged", ["diff", "--cached", "--no-color"]]
@@ -10645,28 +10713,47 @@ function generateDiffReport(cwd, options = {}) {
10645
10713
  for (const [title, args] of commands) {
10646
10714
  const result = runGit(cwd, args);
10647
10715
  if (!result.ok || result.out.trim() === "") continue;
10648
- const body = result.out;
10649
- bytes += Buffer.byteLength(body, "utf8");
10650
- const used = Buffer.byteLength(sections.join(""), "utf8");
10651
- const remaining = Math.max(0, maxBytes - used);
10652
- const chunk = Buffer.byteLength(body, "utf8") > remaining ? body.slice(0, remaining) : body;
10653
- if (chunk.length < body.length) truncated = true;
10654
- sections.push("## " + title + " changes\n\nRun: git " + args.join(" ") + "\n\n```diff\n" + chunk + "\n```");
10716
+ const rawSections = result.out.split(/(?=^diff --git )/m).filter((section) => section.length > 0);
10717
+ for (const rawSection of rawSections) {
10718
+ const paths2 = diffSectionPaths(rawSection);
10719
+ const blocked = paths2.some((path28) => isSensitivePath(path28) || options.excluded?.(path28) === true);
10720
+ if (blocked) {
10721
+ omittedSensitive += 1;
10722
+ continue;
10723
+ }
10724
+ const used = Buffer.byteLength(sections.join(""), "utf8");
10725
+ const remaining = Math.max(0, maxBytes - used);
10726
+ if (remaining === 0) {
10727
+ truncated = true;
10728
+ break;
10729
+ }
10730
+ const chunk = truncateToBytes(rawSection, remaining);
10731
+ if (chunk.isTruncated) truncated = true;
10732
+ sections.push(
10733
+ "## " + title + " changes\n\nRun: git " + args.join(" ") + "\n\n```diff\n" + chunk.content + "\n```"
10734
+ );
10735
+ if (chunk.isTruncated) break;
10736
+ }
10655
10737
  }
10656
10738
  if (sections.length === 0) return null;
10657
10739
  const paths = /* @__PURE__ */ new Set();
10658
- for (const match of sections.join("\n").matchAll(/^\+\+\+ b\/(.+)$/gm)) paths.add(match[1]);
10659
- const text2 = [
10740
+ for (const section of sections) for (const path28 of diffSectionPaths(section)) paths.add(path28);
10741
+ const joined = [
10660
10742
  "# Uncommitted changes",
10661
10743
  "",
10662
10744
  "Generated from the repository at the moment the snapshot was written. Untracked files are not",
10663
10745
  "in a diff until they are added; this artifact says what git reports, not what git ignores.",
10664
10746
  "",
10747
+ ...omittedSensitive > 0 ? [
10748
+ "> " + omittedSensitive + " file section(s) omitted: their path is credential-bearing or excluded from the snapshot.",
10749
+ ""
10750
+ ] : [],
10665
10751
  ...sections,
10666
10752
  ...truncated ? ["", "> Truncated at " + maxBytes + " bytes. Run git diff for the rest."] : [],
10667
10753
  ""
10668
10754
  ].join("\n");
10669
- return { text: text2, bytes, truncated, paths: [...paths].sort() };
10755
+ const text2 = scanAndRedactSecrets(joined, options.secretRules ?? [], "reports/diff.md").redacted;
10756
+ return { text: text2, bytes: Buffer.byteLength(text2, "utf8"), truncated, paths: [...paths].sort() };
10670
10757
  }
10671
10758
 
10672
10759
  // src/generator/log.ts
@@ -10683,13 +10770,15 @@ function generateLogReport(cwd, options = {}) {
10683
10770
  const body = (result.stdout ?? "").trim();
10684
10771
  if (body === "") return null;
10685
10772
  const lines = body.split("\n");
10773
+ const redacted = scanAndRedactSecrets(body, options.secretRules ?? [], "reports/log.md").redacted;
10774
+ const joined = truncateToBytes(redacted, maxBytes).content;
10686
10775
  const text2 = [
10687
10776
  "# Recent commits",
10688
10777
  "",
10689
10778
  "The last " + count + " commits, newest first, one line each.",
10690
10779
  "",
10691
10780
  "```text",
10692
- lines.join("\n").slice(0, maxBytes),
10781
+ joined,
10693
10782
  "```",
10694
10783
  ""
10695
10784
  ].join("\n");
@@ -11564,24 +11653,93 @@ import { spawnSync as spawnSync3 } from "child_process";
11564
11653
  import { lookup } from "dns/promises";
11565
11654
  import { fileURLToPath } from "url";
11566
11655
  var HOST_PATTERN = /^[a-z0-9.-]+$/i;
11656
+ function parseIPv4(value) {
11657
+ const parts = value.split(".");
11658
+ if (parts.length !== 4) return null;
11659
+ const octets = [];
11660
+ for (const part of parts) {
11661
+ if (!/^\d{1,3}$/.test(part)) return null;
11662
+ const octet = Number(part);
11663
+ if (octet > 255) return null;
11664
+ octets.push(octet);
11665
+ }
11666
+ return octets;
11667
+ }
11668
+ function isPrivateIPv4(octets) {
11669
+ const [a, b] = octets;
11670
+ return a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 192 && b === 0 && octets[2] === 0 || a === 192 && b === 0 && octets[2] === 2 || a === 198 && (b === 18 || b === 19) || a === 198 && b === 51 && octets[2] === 100 || a === 203 && b === 0 && octets[2] === 113 || a >= 224;
11671
+ }
11672
+ function parseIPv6(value) {
11673
+ const withoutZone = value.split("%")[0] ?? value;
11674
+ if (!withoutZone.includes(":")) return null;
11675
+ const halves = withoutZone.split("::");
11676
+ if (halves.length > 2) return null;
11677
+ const left = halves[0] === "" ? [] : halves[0].split(":");
11678
+ const right = halves.length === 2 && halves[1] !== "" ? halves[1].split(":") : [];
11679
+ const groups = [...left, ...right];
11680
+ if (halves.length === 1 && groups.length !== 8) return null;
11681
+ if (halves.length === 2 && groups.length > 7) return null;
11682
+ const expand = (group) => {
11683
+ if (group.includes(".")) {
11684
+ const octets = parseIPv4(group);
11685
+ if (octets === null) return null;
11686
+ return [
11687
+ (octets[0] << 8 | octets[1]).toString(16),
11688
+ (octets[2] << 8 | octets[3]).toString(16)
11689
+ ];
11690
+ }
11691
+ return [group];
11692
+ };
11693
+ const expanded = [];
11694
+ for (const group of groups) {
11695
+ const next = expand(group);
11696
+ if (next === null) return null;
11697
+ expanded.push(...next);
11698
+ }
11699
+ if (halves.length === 1 && expanded.length !== 8) return null;
11700
+ if (halves.length === 2 && expanded.length > 8) return null;
11701
+ const missing = 8 - expanded.length;
11702
+ const full = halves.length === 2 ? [...expanded.slice(0, left.length), ...Array(missing).fill("0"), ...expanded.slice(left.length)] : expanded;
11703
+ if (full.length !== 8) return null;
11704
+ const numbers = [];
11705
+ for (const group of full) {
11706
+ if (!/^[0-9a-f]{1,4}$/i.test(group)) return null;
11707
+ numbers.push(Number.parseInt(group, 16));
11708
+ }
11709
+ return numbers;
11710
+ }
11711
+ function isPrivateIPv6(groups) {
11712
+ const [first, second, third, fourth, fifth, sixth, seventh, eighth] = groups;
11713
+ const allZeroThrough = (count) => groups.slice(0, count).every((group) => group === 0);
11714
+ if (groups.every((group) => group === 0)) return true;
11715
+ if (allZeroThrough(7) && eighth === 1) return true;
11716
+ if ((first & 65024) === 64512) return true;
11717
+ if ((first & 65472) === 65152) return true;
11718
+ if ((first & 65472) === 65216) return true;
11719
+ if ((first & 65280) === 65280) return true;
11720
+ if (first === 8193 && second === 3512) return true;
11721
+ const mapped = (offset) => isPrivateIPv4([
11722
+ groups[offset] >> 8,
11723
+ groups[offset] & 255,
11724
+ groups[offset + 1] >> 8,
11725
+ groups[offset + 1] & 255
11726
+ ]);
11727
+ if (allZeroThrough(5) && sixth === 65535) return mapped(6);
11728
+ if (allZeroThrough(6) && (seventh !== 0 || eighth !== 0)) return mapped(6);
11729
+ if (first === 100 && second === 65435 && third === 0 && fourth === 0 && fifth === 0 && sixth === 0) {
11730
+ return mapped(6);
11731
+ }
11732
+ if (first === 8194) return mapped(1);
11733
+ return false;
11734
+ }
11567
11735
  function isPrivateHost(host) {
11568
- const value = host.toLowerCase().replace(/^\[|\]$/g, "");
11736
+ const value = host.toLowerCase().replace(/^\[|\]$/g, "").split("%")[0] ?? "";
11569
11737
  if (value === "localhost" || value.endsWith(".localhost") || value.endsWith(".local")) return true;
11570
11738
  if (value === "::1" || value === "0.0.0.0" || value === "::") return true;
11571
- if (value.startsWith("fc") || value.startsWith("fd")) return true;
11572
- if (value.startsWith("fe80")) return true;
11573
- const parts = value.split(".");
11574
- if (parts.length === 4 && parts.every((part) => /^\d{1,3}$/.test(part))) {
11575
- const octets = parts.map(Number);
11576
- if (octets.some((octet) => octet > 255)) return true;
11577
- if (octets[0] === 127) return true;
11578
- if (octets[0] === 10) return true;
11579
- if (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) return true;
11580
- if (octets[0] === 192 && octets[1] === 168) return true;
11581
- if (octets[0] === 169 && octets[1] === 254) return true;
11582
- if (octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127) return true;
11583
- if (octets[0] === 0) return true;
11584
- }
11739
+ const ipv4 = parseIPv4(value);
11740
+ if (ipv4 !== null) return isPrivateIPv4(ipv4);
11741
+ const ipv6 = parseIPv6(value);
11742
+ if (ipv6 !== null) return isPrivateIPv6(ipv6);
11585
11743
  return false;
11586
11744
  }
11587
11745
  function parseRemoteSource(input, options = {}) {
@@ -11656,14 +11814,25 @@ async function assertPublicHost(host, allowPrivate) {
11656
11814
  }
11657
11815
  }
11658
11816
  }
11817
+ function tokenHosts() {
11818
+ const configured = process.env.CODEBASE_SNAPSHOT_GITHUB_HOSTS;
11819
+ if (configured === void 0 || configured.trim() === "") return ["github.com"];
11820
+ return configured.split(",").map((entry) => entry.trim().toLowerCase()).filter((entry) => entry.length > 0);
11821
+ }
11822
+ function tokenAllowedForHost(host) {
11823
+ return tokenHosts().includes(host.toLowerCase().replace(/^\[|\]$/g, ""));
11824
+ }
11659
11825
  function gitEnvironment(token, host) {
11660
11826
  const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_LFS_SKIP_SMUDGE: "1" };
11661
11827
  delete env.GIT_ASKPASS;
11662
11828
  delete env.SSH_ASKPASS;
11663
11829
  if (token !== void 0 && token !== null && token !== "") {
11664
- env.GIT_CONFIG_COUNT = "1";
11665
- env.GIT_CONFIG_KEY_0 = "http.https://" + host + "/.extraheader";
11666
- env.GIT_CONFIG_VALUE_0 = "Authorization: Basic " + Buffer.from("x-access-token:" + token).toString("base64");
11830
+ const normalizedHost = host.toLowerCase().replace(/^\[|\]$/g, "");
11831
+ if (tokenAllowedForHost(normalizedHost)) {
11832
+ env.GIT_CONFIG_COUNT = "1";
11833
+ env.GIT_CONFIG_KEY_0 = "http.https://" + normalizedHost + "/.extraheader";
11834
+ env.GIT_CONFIG_VALUE_0 = "Authorization: Basic " + Buffer.from("x-access-token:" + token).toString("base64");
11835
+ }
11667
11836
  }
11668
11837
  return env;
11669
11838
  }
@@ -11673,15 +11842,29 @@ async function cloneRepository(source, options) {
11673
11842
  const dest = path15.resolve(options.dest);
11674
11843
  fs15.rmSync(dest, { recursive: true, force: true });
11675
11844
  fs15.mkdirSync(dest, { recursive: true });
11676
- const args = ["clone", "--depth", "1", "--single-branch", "--no-tags", "--quiet"];
11677
- if (options.ref !== void 0 && options.ref !== null && options.ref !== "") {
11678
- args.push("--branch", options.ref);
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);
11679
11859
  }
11680
11860
  args.push(source.url, dest);
11681
- log("clone: " + source.url + (options.ref ? " (" + options.ref + ")" : ""));
11861
+ log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
11682
11862
  const started = Date.now();
11683
11863
  const result = spawnSync3("git", args, {
11684
- env: gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
11864
+ env: {
11865
+ ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
11866
+ ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
11867
+ },
11685
11868
  timeout: options.timeoutMs ?? 18e4,
11686
11869
  encoding: "utf8",
11687
11870
  windowsHide: true
@@ -11709,7 +11892,7 @@ async function cloneRepository(source, options) {
11709
11892
  host: source.host,
11710
11893
  owner: source.owner,
11711
11894
  repo: source.repo,
11712
- ref: options.ref !== void 0 && options.ref !== null && options.ref !== "" ? options.ref : source.ref,
11895
+ ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
11713
11896
  commit,
11714
11897
  fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
11715
11898
  }
@@ -12101,9 +12284,9 @@ function walk(dir, prefix = "") {
12101
12284
  }
12102
12285
  const files = [];
12103
12286
  for (const entry of entries) {
12104
- const relative15 = prefix === "" ? entry.name : prefix + "/" + entry.name;
12105
- if (entry.isDirectory()) files.push(...walk(path16.join(dir, entry.name), relative15));
12106
- else if (entry.isFile()) files.push(relative15);
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);
12107
12290
  }
12108
12291
  return files;
12109
12292
  }
@@ -12143,9 +12326,9 @@ function secretTokens(text2) {
12143
12326
  }
12144
12327
  function readArtifactTexts(snapshotDir) {
12145
12328
  const texts = [];
12146
- for (const relative15 of walk(snapshotDir)) {
12147
- if (!TEXT_ARTIFACT.test(relative15)) continue;
12148
- const text2 = readText2(path16.join(snapshotDir, relative15));
12329
+ for (const relative16 of walk(snapshotDir)) {
12330
+ if (!TEXT_ARTIFACT.test(relative16)) continue;
12331
+ const text2 = readText2(path16.join(snapshotDir, relative16));
12149
12332
  if (text2 !== null) texts.push(text2);
12150
12333
  }
12151
12334
  return texts;
@@ -12161,15 +12344,15 @@ function findHostPaths(snapshotDir, repoDir) {
12161
12344
  ];
12162
12345
  const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
12163
12346
  const hits = /* @__PURE__ */ new Set();
12164
- for (const relative15 of walk(snapshotDir)) {
12165
- if (!TEXT_ARTIFACT.test(relative15)) continue;
12166
- const text2 = readText2(path16.join(snapshotDir, relative15));
12347
+ for (const relative16 of walk(snapshotDir)) {
12348
+ if (!TEXT_ARTIFACT.test(relative16)) continue;
12349
+ const text2 = readText2(path16.join(snapshotDir, relative16));
12167
12350
  if (text2 === null) continue;
12168
12351
  for (const pattern of patterns) {
12169
- for (const match of text2.match(pattern) ?? []) hits.add(relative15 + ": " + match);
12352
+ for (const match of text2.match(pattern) ?? []) hits.add(relative16 + ": " + match);
12170
12353
  }
12171
12354
  repoPattern.lastIndex = 0;
12172
- if (repoPattern.test(text2)) hits.add(relative15 + ": the repository absolute path");
12355
+ if (repoPattern.test(text2)) hits.add(relative16 + ": the repository absolute path");
12173
12356
  }
12174
12357
  return [...hits];
12175
12358
  }
@@ -12416,13 +12599,13 @@ function auditSnapshot(options) {
12416
12599
  let artifactCount = 0;
12417
12600
  for (const [key, value] of Object.entries(artifacts)) {
12418
12601
  if (value === null || value === void 0) continue;
12419
- const relative15 = ARTIFACT_FILES[key];
12420
- if (relative15 === void 0) continue;
12602
+ const relative16 = ARTIFACT_FILES[key];
12603
+ if (relative16 === void 0) continue;
12421
12604
  artifactCount += 1;
12422
- const bytes = readBytes(path16.join(snapshotDir, relative15));
12423
- if (bytes === null) artifactProblems.push(relative15 + " is missing");
12605
+ const bytes = readBytes(path16.join(snapshotDir, relative16));
12606
+ if (bytes === null) artifactProblems.push(relative16 + " is missing");
12424
12607
  else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
12425
- artifactProblems.push(relative15 + " changed");
12608
+ artifactProblems.push(relative16 + " changed");
12426
12609
  }
12427
12610
  }
12428
12611
  checks.push(
@@ -13152,25 +13335,25 @@ function auditSnapshot(options) {
13152
13335
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
13153
13336
  const leakHits = [];
13154
13337
  let scannedBytes = 0;
13155
- for (const relative15 of walk(snapshotDir)) {
13156
- if (!TEXT_ARTIFACT.test(relative15) || scannedBytes > scanBudget) continue;
13157
- if (relative15 === SIGNATURE_FILE) continue;
13158
- const text2 = readText2(path16.join(snapshotDir, relative15));
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));
13159
13342
  if (text2 === null) continue;
13160
13343
  scannedBytes += Buffer.byteLength(text2, "utf8");
13161
13344
  let findingCount = 0;
13162
- if (/^parts[\\/].*\.md$/i.test(relative15)) {
13345
+ if (/^parts[\\/].*\.md$/i.test(relative16)) {
13163
13346
  let headerText = text2;
13164
13347
  for (const section of parsePartSections(text2)) {
13165
13348
  findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
13166
13349
  headerText = headerText.replace(section.body, "");
13167
13350
  }
13168
- findingCount += scanAndRedactSecrets(headerText, rules, relative15).findings.length;
13351
+ findingCount += scanAndRedactSecrets(headerText, rules, relative16).findings.length;
13169
13352
  } else {
13170
- findingCount = scanAndRedactSecrets(text2, rules, relative15).findings.length;
13353
+ findingCount = scanAndRedactSecrets(text2, rules, relative16).findings.length;
13171
13354
  }
13172
13355
  if (findingCount > 0) {
13173
- leakHits.push(relative15 + " (" + findingCount + " line(s))");
13356
+ leakHits.push(relative16 + " (" + findingCount + " line(s))");
13174
13357
  }
13175
13358
  }
13176
13359
  const signatureRecordPath = path16.join(snapshotDir, SIGNATURE_FILE);
@@ -13389,6 +13572,7 @@ const { parentPort, workerData } = require("node:worker_threads");
13389
13572
  const manifest = mod.generateSnapshot(config, {
13390
13573
  dryRun: workerData.dryRun === true,
13391
13574
  ...(workerData.narrow ?? {}),
13575
+ ...(workerData.runId === undefined ? {} : { runId: workerData.runId }),
13392
13576
  });
13393
13577
  const skipCounts = new Map();
13394
13578
  for (const record of manifest.skipped) {
@@ -13434,8 +13618,13 @@ function generateInWorker(cwd, cliOptions, options = {}) {
13434
13618
  const finish = (result) => {
13435
13619
  if (settled) return;
13436
13620
  settled = true;
13437
- if (worker !== null) void worker.terminate();
13438
- resolve15(result);
13621
+ const terminated = worker === null ? Promise.resolve(void 0) : worker.terminate();
13622
+ void terminated.catch(() => void 0).then(() => {
13623
+ if (!result.ok && options.runId !== void 0 && options.lockRoots !== void 0) {
13624
+ releaseAbandonedRun(options.lockRoots, options.runId);
13625
+ }
13626
+ resolve15(result);
13627
+ });
13439
13628
  };
13440
13629
  const isCjs = typeof __dirname !== "undefined";
13441
13630
  const directory = isCjs ? __dirname : path17.dirname(fileURLToPath2(import.meta.url));
@@ -13447,7 +13636,8 @@ function generateInWorker(cwd, cliOptions, options = {}) {
13447
13636
  cwd,
13448
13637
  cliOptions,
13449
13638
  dryRun: options.dryRun === true,
13450
- narrow: options.narrow ?? {}
13639
+ narrow: options.narrow ?? {},
13640
+ ...options.runId === void 0 ? {} : { runId: options.runId }
13451
13641
  }
13452
13642
  });
13453
13643
  } catch (error) {
@@ -13501,7 +13691,7 @@ function windowText(body, fromLine, lineCount) {
13501
13691
  }
13502
13692
 
13503
13693
  // src/mcp/tools.ts
13504
- import { createHash as createHash8 } from "crypto";
13694
+ import { createHash as createHash8, randomUUID } from "crypto";
13505
13695
 
13506
13696
  // src/mcp/workspace.ts
13507
13697
  import * as fs17 from "fs";
@@ -13619,7 +13809,16 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
13619
13809
  if (overrides.withDependents === true) cliOptions.withDependents = true;
13620
13810
  try {
13621
13811
  const config = resolveConfig(loaded.config, cliOptions, root);
13622
- return { ok: true, workspace: { root, config, configFile: loaded.file, cliOptions } };
13812
+ return {
13813
+ ok: true,
13814
+ workspace: {
13815
+ root,
13816
+ config,
13817
+ configFile: loaded.file,
13818
+ sourceConfig: loaded.config ?? null,
13819
+ cliOptions
13820
+ }
13821
+ };
13623
13822
  } catch (error) {
13624
13823
  return { ok: false, message: error instanceof Error ? error.message : String(error) };
13625
13824
  }
@@ -13633,8 +13832,8 @@ function partPathFor(workspace, filename) {
13633
13832
  if (filename.length === 0 || filename.includes("\0")) return null;
13634
13833
  const partsDir = path18.resolve(workspace.root, workspace.config.outDir, "parts");
13635
13834
  const resolved = path18.resolve(partsDir, filename);
13636
- const relative15 = path18.relative(partsDir, resolved);
13637
- if (relative15.length === 0 || relative15.includes(path18.sep) || relative15.includes("/") || relative15.includes("\\") || path18.isAbsolute(relative15)) {
13835
+ const relative16 = path18.relative(partsDir, resolved);
13836
+ if (relative16.length === 0 || relative16.includes(path18.sep) || relative16.includes("/") || relative16.includes("\\") || path18.isAbsolute(relative16)) {
13638
13837
  return null;
13639
13838
  }
13640
13839
  let stats;
@@ -13808,11 +14007,11 @@ function toRelativePath(root, value) {
13808
14007
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
13809
14008
  const resolvedRoot = path19.resolve(root);
13810
14009
  const absolute = path19.resolve(resolvedRoot, cleaned);
13811
- const relative15 = path19.relative(resolvedRoot, absolute);
13812
- if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path19.sep}`) || path19.isAbsolute(relative15)) {
14010
+ const relative16 = path19.relative(resolvedRoot, absolute);
14011
+ if (relative16 === "" || relative16 === ".." || relative16.startsWith(`..${path19.sep}`) || path19.isAbsolute(relative16)) {
13813
14012
  return null;
13814
14013
  }
13815
- return relative15.split(path19.sep).join("/");
14014
+ return relative16.split(path19.sep).join("/");
13816
14015
  }
13817
14016
  function symbolsOf(entry) {
13818
14017
  const summary = entry.summary;
@@ -14026,7 +14225,9 @@ var testsTool = {
14026
14225
  const cap = Math.max(1, typeof args.maxFiles === "number" ? args.maxFiles : 50);
14027
14226
  const isTest2 = (filePath) => /(^|\/)(tests?|__tests__|spec)\//.test(filePath) || /\.(test|spec)\.[a-z0-9]+$/i.test(filePath);
14028
14227
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath, file]));
14029
- const resolver = buildImportResolver(read.manifest.files, {});
14228
+ const resolver = buildImportResolver(read.manifest.files, {
14229
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
14230
+ });
14030
14231
  const testFiles = read.manifest.files.filter((file) => isTest2(file.relativePath));
14031
14232
  const importsOf = (filePath) => {
14032
14233
  const entry = read.manifest.indexes.imports.byFile.find((candidate) => candidate.path === filePath);
@@ -14074,9 +14275,13 @@ var workspaceTool = {
14074
14275
  },
14075
14276
  annotations: READ_ONLY,
14076
14277
  async handler(args, context) {
14077
- const root = path19.resolve(context.cwd, typeof args.root === "string" ? args.root : ".");
14078
- const outDir = typeof args.outDir === "string" ? args.outDir : "snapshot";
14079
- const index = path19.resolve(root, outDir, "WORKSPACE.json");
14278
+ const prepared = await prepare(args, context, outDirOverride(args));
14279
+ if (!prepared.ok) return prepared.outcome;
14280
+ const index = path19.resolve(
14281
+ prepared.workspace.root,
14282
+ prepared.workspace.config.outDir,
14283
+ "WORKSPACE.json"
14284
+ );
14080
14285
  let text2;
14081
14286
  try {
14082
14287
  text2 = fs18.readFileSync(index, "utf8");
@@ -14133,7 +14338,9 @@ var neighborsTool = {
14133
14338
  const file = read.manifest.files.find((candidate) => candidate.relativePath === wanted) ?? read.manifest.files.find((candidate) => candidate.relativePath.toLowerCase() === wanted.toLowerCase());
14134
14339
  if (file === void 0) return { text: wanted + " is not in the snapshot; snapshot_explain says why.", isError: true };
14135
14340
  const byPath = new Map(read.manifest.files.map((candidate) => [candidate.relativePath, candidate]));
14136
- const resolver = buildImportResolver(read.manifest.files, {});
14341
+ const resolver = buildImportResolver(read.manifest.files, {
14342
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
14343
+ });
14137
14344
  const entry = read.manifest.indexes.imports.byFile.find((candidate) => candidate.path === file.relativePath);
14138
14345
  const imports = [];
14139
14346
  for (const specifier of entry?.imports ?? []) {
@@ -14275,7 +14482,9 @@ var cyclesTool = {
14275
14482
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
14276
14483
  const cap = Math.max(1, typeof args.maxComponents === "number" ? args.maxComponents : 20);
14277
14484
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath, file]));
14278
- const resolver = buildImportResolver(read.manifest.files, {});
14485
+ const resolver = buildImportResolver(read.manifest.files, {
14486
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
14487
+ });
14279
14488
  const edges = /* @__PURE__ */ new Map();
14280
14489
  for (const path28 of byPath.keys()) edges.set(path28, []);
14281
14490
  for (const entry of read.manifest.indexes.imports.byFile) {
@@ -15475,10 +15684,17 @@ var generateTool = {
15475
15684
  ...typeof args.slice === "string" ? { slice: { question: args.slice, ...typeof args.sliceTokens === "number" ? { maxTokens: args.sliceTokens } : {} } } : {},
15476
15685
  ...typeof args.budgetTokens === "number" ? { budgetTokens: args.budgetTokens } : {}
15477
15686
  };
15687
+ let lockRoots;
15688
+ try {
15689
+ const safe = resolveSafeOutputDirs(workspace.config);
15690
+ lockRoots = [safe.outDir, safe.tmpDir];
15691
+ } catch (error) {
15692
+ return failure(error instanceof Error ? error.message : String(error));
15693
+ }
15478
15694
  const result = await generateInWorker(
15479
15695
  workspace.root,
15480
15696
  { ...workspace.cliOptions, ...reportOptions },
15481
- { signal: controller.signal, narrow }
15697
+ { signal: controller.signal, narrow, runId: randomUUID(), lockRoots }
15482
15698
  );
15483
15699
  if (!result.ok) return failure(result.message);
15484
15700
  context.notify?.({ message: "writing the snapshot", progress: 2, total: 2 });
@@ -15512,16 +15728,42 @@ var generateTool = {
15512
15728
  };
15513
15729
  function configAsGenerated(workspace, manifest) {
15514
15730
  const recorded = manifest.config;
15731
+ const cli = workspace.cliOptions;
15732
+ const source = workspace.sourceConfig;
15733
+ const configured = (key) => source !== null && Object.prototype.hasOwnProperty.call(source, key);
15734
+ const sourceArtifacts = source !== null && source.artifacts !== null && typeof source.artifacts === "object" ? source.artifacts : null;
15735
+ const artifacts = { ...workspace.config.artifacts };
15736
+ if (recorded?.artifacts !== void 0) {
15737
+ for (const [key, value] of Object.entries(recorded.artifacts)) {
15738
+ if (sourceArtifacts === null || !Object.prototype.hasOwnProperty.call(sourceArtifacts, key)) {
15739
+ artifacts[key] = value;
15740
+ }
15741
+ }
15742
+ }
15743
+ let artifactOverride = recorded?.artifacts !== void 0;
15744
+ if (cli.includeDiffs === true) {
15745
+ artifacts.diff = true;
15746
+ artifactOverride = true;
15747
+ }
15748
+ if (cli.includeLogs !== void 0) {
15749
+ artifacts.log = true;
15750
+ artifactOverride = true;
15751
+ }
15752
+ if (cli.tokenTree === true) {
15753
+ artifacts.tokenTree = true;
15754
+ artifactOverride = true;
15755
+ }
15756
+ const choose = (key, recordedValue, current, cliValue) => cliValue !== void 0 ? cliValue : configured(key) ? current : recordedValue ?? current;
15515
15757
  return {
15516
15758
  ...workspace.config,
15517
- ...recorded?.artifacts === void 0 ? {} : { artifacts: recorded.artifacts },
15518
- ...recorded?.stripComments === void 0 ? {} : { stripComments: recorded.stripComments },
15519
- ...recorded?.removeEmptyLines === void 0 ? {} : { removeEmptyLines: recorded.removeEmptyLines },
15520
- ...recorded?.pack === void 0 ? {} : { pack: recorded.pack },
15521
- ...recorded?.logCount === void 0 ? {} : { logCount: recorded.logCount },
15522
- ...recorded?.skeleton === void 0 ? {} : { skeleton: recorded.skeleton },
15523
- ...recorded?.sarif === void 0 ? {} : { sarif: recorded.sarif },
15524
- ...recorded?.maxParts === void 0 ? {} : { maxParts: recorded.maxParts }
15759
+ ...artifactOverride ? { artifacts } : {},
15760
+ ...cli.stripComments === true || configured("stripComments") || recorded?.stripComments !== void 0 ? { stripComments: choose("stripComments", recorded?.stripComments, workspace.config.stripComments, cli.stripComments === true ? true : void 0) } : {},
15761
+ ...cli.removeEmptyLines === true || configured("removeEmptyLines") || recorded?.removeEmptyLines !== void 0 ? { removeEmptyLines: choose("removeEmptyLines", recorded?.removeEmptyLines, workspace.config.removeEmptyLines, cli.removeEmptyLines === true ? true : void 0) } : {},
15762
+ ...cli.pack !== void 0 || configured("pack") || recorded?.pack !== void 0 ? { pack: choose("pack", recorded?.pack ?? void 0, workspace.config.pack, cli.pack) } : {},
15763
+ ...cli.includeLogs !== void 0 || configured("logCount") || recorded?.logCount !== void 0 ? { logCount: choose("logCount", recorded?.logCount, workspace.config.logCount, cli.includeLogs) } : {},
15764
+ ...cli.skeleton === true || configured("skeleton") || recorded?.skeleton !== void 0 ? { skeleton: choose("skeleton", recorded?.skeleton, workspace.config.skeleton, cli.skeleton === true ? true : void 0) } : {},
15765
+ ...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) } : {}
15525
15767
  };
15526
15768
  }
15527
15769
  var validateTool = {
@@ -15758,7 +16000,9 @@ var dependentsTool = {
15758
16000
  }
15759
16001
  const direction = args.direction === "imports" || args.direction === "imported-by" ? String(args.direction) : "both";
15760
16002
  const limit = typeof args.limit === "number" && args.limit > 0 ? Math.floor(args.limit) : 50;
15761
- const resolver = buildImportResolver(manifest.files);
16003
+ const resolver = buildImportResolver(manifest.files, {
16004
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
16005
+ });
15762
16006
  const imports = [];
15763
16007
  const unresolved = [];
15764
16008
  if (direction !== "imported-by") {
@@ -17236,6 +17480,10 @@ function buildAgentContract() {
17236
17480
  { key: "maxPartBytes", type: "number | string", default: 307200, summary: "Per-part byte budget." },
17237
17481
  { key: "maxPartTokens", type: "number | string | null", default: null, summary: "Per-part token ceiling; narrows maxPartBytes. Minimum 1024." },
17238
17482
  { key: "skeleton", type: "boolean", default: false, summary: "Collapse function bodies to `{ /* ... */ }` in TS, JS, TSX and JSX files." },
17483
+ { key: "stripComments", type: "boolean", default: false, summary: "Remove comment text from JS/TS bodies." },
17484
+ { key: "removeEmptyLines", type: "boolean", default: false, summary: "Drop blank lines from emitted bodies; the part's line numbers move, and files[] records emptyLinesRemoved." },
17485
+ { key: "pack", type: '"single" | "xml" | "json" | null', default: null, summary: "Write one single-file pack in this format." },
17486
+ { key: "logCount", type: "number", default: 20, summary: "Commit lines in reports/log.md (also set by --include-logs <n>)." },
17239
17487
  { key: "sarif", type: "boolean", default: false, summary: "Also write reports/audit.sarif." },
17240
17488
  { key: "changedSince", type: "string | null", default: null, summary: "Snapshot only files that differ from this git ref." },
17241
17489
  { key: "staged", type: "boolean", default: false, summary: "Snapshot only files staged in the index." },
@@ -18413,9 +18661,9 @@ function dosDateTime(date) {
18413
18661
  function walkFiles(root, prefix = "") {
18414
18662
  const files = [];
18415
18663
  for (const entry of fs20.readdirSync(path21.join(root, prefix), { withFileTypes: true })) {
18416
- const relative15 = prefix === "" ? entry.name : prefix + "/" + entry.name;
18417
- if (entry.isDirectory()) files.push(...walkFiles(root, relative15));
18418
- else if (entry.isFile()) files.push(relative15);
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);
18419
18667
  }
18420
18668
  return files;
18421
18669
  }
@@ -18423,11 +18671,11 @@ function writeZip(options) {
18423
18671
  const entries = [...options.entries ?? []];
18424
18672
  if (options.directory !== void 0) {
18425
18673
  const root = options.directory;
18426
- for (const relative15 of walkFiles(root)) {
18427
- if (options.skip !== void 0 && options.skip(relative15)) continue;
18428
- const full = path21.join(root, relative15);
18674
+ for (const relative16 of walkFiles(root)) {
18675
+ if (options.skip !== void 0 && options.skip(relative16)) continue;
18676
+ const full = path21.join(root, relative16);
18429
18677
  const stat = fs20.statSync(full);
18430
- entries.push({ name: relative15, content: fs20.readFileSync(full), mtime: stat.mtime });
18678
+ entries.push({ name: relative16, content: fs20.readFileSync(full), mtime: stat.mtime });
18431
18679
  }
18432
18680
  }
18433
18681
  if (entries.length > 65535) {
@@ -18620,8 +18868,13 @@ var SERVE_PAGE = `<!doctype html>
18620
18868
  $("counts").textContent = info.included + " included / " + info.skipped + " skipped";
18621
18869
  $("files").innerHTML = "";
18622
18870
  for (const file of info.files.slice(0, 400)) {
18871
+ // A manifest is untrusted input. Interpolating file.part (or a path) into innerHTML let a
18872
+ // crafted manifest run script in the serve origin and read the token from localStorage.
18623
18873
  const li = document.createElement("li");
18624
- li.innerHTML = "<b>" + file.path.replace(/[<>&]/g, "") + "</b> " + file.part;
18874
+ const name = document.createElement("b");
18875
+ name.textContent = file.path;
18876
+ li.appendChild(name);
18877
+ li.appendChild(document.createTextNode(" " + file.part));
18625
18878
  $("files").appendChild(li);
18626
18879
  }
18627
18880
  }
@@ -18658,16 +18911,55 @@ async function startWebServer(options) {
18658
18911
  if (token === null && !["127.0.0.1", "localhost", "::1"].includes(host)) {
18659
18912
  throw new Error("Refusing to serve " + host + " without a token.");
18660
18913
  }
18661
- const mcp = createServer({ cwd: options.cwd, log });
18914
+ const createMcp = () => createServer({ cwd: options.cwd, log });
18915
+ const mcpPerSocket = /* @__PURE__ */ new WeakMap();
18916
+ const mcpFor = (socket) => {
18917
+ let server2 = mcpPerSocket.get(socket);
18918
+ if (server2 === void 0) {
18919
+ server2 = createMcp();
18920
+ mcpPerSocket.set(socket, server2);
18921
+ }
18922
+ return server2;
18923
+ };
18662
18924
  const temporaryClones = /* @__PURE__ */ new Set();
18663
18925
  const allowedRoots = [path22.resolve(options.cwd)];
18926
+ const canonical = (candidate) => {
18927
+ try {
18928
+ return fs21.realpathSync(candidate);
18929
+ } catch {
18930
+ return null;
18931
+ }
18932
+ };
18933
+ const inside = (resolved) => allowedRoots.some((root) => {
18934
+ const canonicalRoot = canonical(root);
18935
+ if (canonicalRoot === null) return false;
18936
+ const relative16 = path22.relative(canonicalRoot, resolved);
18937
+ return relative16 === "" || !relative16.startsWith(`..${path22.sep}`) && relative16 !== ".." && !path22.isAbsolute(relative16);
18938
+ });
18664
18939
  const insideAllowedRoots = (candidate) => {
18940
+ const resolved = canonical(candidate);
18941
+ return resolved === null ? false : inside(resolved);
18942
+ };
18943
+ const lexicallyInside = (candidate) => {
18665
18944
  const resolved = path22.resolve(candidate);
18666
18945
  return allowedRoots.some((root) => {
18667
- const prefix = root.endsWith(path22.sep) ? root : root + path22.sep;
18668
- return resolved === root || resolved.startsWith(prefix);
18946
+ const prefix = path22.resolve(root) + path22.sep;
18947
+ return resolved === path22.resolve(root) || resolved.startsWith(prefix);
18669
18948
  });
18670
18949
  };
18950
+ const insideAllowedRootsForWrite = (candidate) => {
18951
+ let existing = path22.resolve(candidate);
18952
+ const tail = [];
18953
+ while (!fs21.existsSync(existing)) {
18954
+ tail.unshift(path22.basename(existing));
18955
+ const parent = path22.dirname(existing);
18956
+ if (parent === existing) break;
18957
+ existing = parent;
18958
+ }
18959
+ const resolved = canonical(existing);
18960
+ if (resolved === null) return false;
18961
+ return inside(tail.length === 0 ? resolved : path22.join(resolved, ...tail));
18962
+ };
18671
18963
  const authorized = (request) => {
18672
18964
  if (token === null) return true;
18673
18965
  const header = request.headers.authorization ?? "";
@@ -18691,7 +18983,10 @@ async function startWebServer(options) {
18691
18983
  cors["access-control-allow-headers"] = "authorization, content-type";
18692
18984
  cors["access-control-allow-methods"] = "GET, POST, OPTIONS";
18693
18985
  }
18986
+ let responseSent = false;
18694
18987
  const send = (status, body, extra = {}) => {
18988
+ if (responseSent) return;
18989
+ responseSent = true;
18695
18990
  const text2 = typeof body === "string" ? body : JSON.stringify(body);
18696
18991
  response.writeHead(status, {
18697
18992
  ...cors,
@@ -18722,10 +19017,13 @@ async function startWebServer(options) {
18722
19017
  const url = new URL(request.url ?? "/", "http://localhost");
18723
19018
  if (request.method === "POST" && (request.url === "/mcp" || (request.url ?? "").startsWith("/mcp?"))) {
18724
19019
  let received = 0;
19020
+ let tooLarge = false;
18725
19021
  const chunks = [];
18726
19022
  request.on("data", (chunk) => {
19023
+ if (tooLarge) return;
18727
19024
  received += chunk.length;
18728
19025
  if (received > 2 * 1024 * 1024) {
19026
+ tooLarge = true;
18729
19027
  request.destroy();
18730
19028
  send(413, { error: "request body too large" });
18731
19029
  return;
@@ -18733,6 +19031,7 @@ async function startWebServer(options) {
18733
19031
  chunks.push(chunk);
18734
19032
  });
18735
19033
  request.on("end", () => {
19034
+ if (tooLarge) return;
18736
19035
  void (async () => {
18737
19036
  let message;
18738
19037
  try {
@@ -18742,9 +19041,14 @@ async function startWebServer(options) {
18742
19041
  return;
18743
19042
  }
18744
19043
  const batch = Array.isArray(message) ? message : [message];
19044
+ if (batch.length > 100) {
19045
+ send(400, { error: "JSON-RPC batch is limited to 100 messages" });
19046
+ return;
19047
+ }
19048
+ const server2 = mcpFor(request.socket);
18745
19049
  const answers = [];
18746
19050
  for (const item of batch) {
18747
- const answer = await mcp.handle(item);
19051
+ const answer = await server2.handle(item);
18748
19052
  if (answer !== null) answers.push(answer);
18749
19053
  }
18750
19054
  if (answers.length === 0) send(202, "");
@@ -18755,10 +19059,13 @@ async function startWebServer(options) {
18755
19059
  }
18756
19060
  if (request.method === "POST" && request.url === "/api/generate") {
18757
19061
  let received = 0;
19062
+ let tooLarge = false;
18758
19063
  const chunks = [];
18759
19064
  request.on("data", (chunk) => {
19065
+ if (tooLarge) return;
18760
19066
  received += chunk.length;
18761
19067
  if (received > MAX_BODY) {
19068
+ tooLarge = true;
18762
19069
  request.destroy();
18763
19070
  send(413, { error: "request body too large" });
18764
19071
  return;
@@ -18766,6 +19073,7 @@ async function startWebServer(options) {
18766
19073
  chunks.push(chunk);
18767
19074
  });
18768
19075
  request.on("end", () => {
19076
+ if (tooLarge) return;
18769
19077
  void (async () => {
18770
19078
  let source = "";
18771
19079
  let mode = "full";
@@ -18822,6 +19130,10 @@ async function startWebServer(options) {
18822
19130
  }
18823
19131
  } else {
18824
19132
  target = path22.resolve(options.cwd, source);
19133
+ if (!insideAllowedRoots(target)) {
19134
+ send(403, { error: "outside the served directory: " + target });
19135
+ return;
19136
+ }
18825
19137
  }
18826
19138
  let stat;
18827
19139
  try {
@@ -18839,15 +19151,26 @@ async function startWebServer(options) {
18839
19151
  send(400, { error: loaded.errors.join("; ") });
18840
19152
  return;
18841
19153
  }
19154
+ const runConfig = isRemote ? {
19155
+ ...loaded.config ?? {},
19156
+ outDir: "snapshot",
19157
+ tmpDir: "snapshot.tmp",
19158
+ hooks: {}
19159
+ } : loaded.config ?? {};
19160
+ const configuredOutDir = typeof runConfig.outDir === "string" && runConfig.outDir.trim() !== "" ? runConfig.outDir : "snapshot";
19161
+ const snapshotDir = path22.resolve(target, configuredOutDir);
19162
+ if (!insideAllowedRootsForWrite(snapshotDir)) {
19163
+ send(403, { error: "the configured outDir resolves outside the served directory" });
19164
+ return;
19165
+ }
18842
19166
  const started = Date.now();
18843
19167
  try {
18844
- const manifest = generateSnapshot({ ...loaded.config ?? {}, cwd: target }, {
19168
+ const manifest = generateSnapshot({ ...runConfig, cwd: target }, {
18845
19169
  ...provenance === void 0 ? {} : { source: provenance },
18846
19170
  ...mode === "slice" ? { slice: { question } } : {},
18847
19171
  ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
18848
19172
  });
18849
19173
  const seconds = ((Date.now() - started) / 1e3).toFixed(2);
18850
- const snapshotDir = path22.join(target, "snapshot");
18851
19174
  const health = auditSnapshot({ snapshotDir, repoDir: target });
18852
19175
  send(200, {
18853
19176
  path: snapshotDir,
@@ -18875,7 +19198,7 @@ async function startWebServer(options) {
18875
19198
  }
18876
19199
  if (request.method === "GET" && request.url?.startsWith("/api/health?") === true) {
18877
19200
  const target = path22.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
18878
- if (!insideAllowedRoots(target)) {
19201
+ if (!lexicallyInside(target)) {
18879
19202
  send(403, { error: "outside the served directory: " + target });
18880
19203
  return;
18881
19204
  }
@@ -18883,12 +19206,24 @@ async function startWebServer(options) {
18883
19206
  send(404, { error: "no manifest.json under " + target });
18884
19207
  return;
18885
19208
  }
19209
+ if (!insideAllowedRoots(target)) {
19210
+ send(403, { error: "outside the served directory: " + target });
19211
+ return;
19212
+ }
18886
19213
  const report2 = auditSnapshot({ snapshotDir: target, repoDir: path22.dirname(target) });
18887
19214
  send(200, { score: report2.score, counts: report2.counts, checks: report2.checks });
18888
19215
  return;
18889
19216
  }
18890
19217
  if (request.method === "GET" && (request.url?.startsWith("/api/snapshot?") === true || request.url === "/api/snapshot")) {
18891
19218
  const target = path22.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
19219
+ if (!lexicallyInside(target)) {
19220
+ send(403, { error: "outside the served directory: " + target });
19221
+ return;
19222
+ }
19223
+ if (!fs21.existsSync(path22.join(target, "manifest.json"))) {
19224
+ send(404, { error: "no manifest.json under " + target });
19225
+ return;
19226
+ }
18892
19227
  if (!insideAllowedRoots(target)) {
18893
19228
  send(403, { error: "outside the served directory: " + target });
18894
19229
  return;
@@ -18901,6 +19236,11 @@ async function startWebServer(options) {
18901
19236
  send(404, { error: "no manifest.json under " + target });
18902
19237
  return;
18903
19238
  }
19239
+ const shapeProblem = describeManifestShapeProblem(manifest);
19240
+ if (shapeProblem !== null) {
19241
+ send(400, { error: "manifest.json is not a snapshot manifest: " + shapeProblem });
19242
+ return;
19243
+ }
18904
19244
  let prompt = "";
18905
19245
  try {
18906
19246
  prompt = fs21.readFileSync(path22.join(target, "PROMPT.md"), "utf8").slice(0, MAX_PREVIEW);
@@ -18920,7 +19260,7 @@ async function startWebServer(options) {
18920
19260
  }
18921
19261
  if (request.method === "GET" && request.url?.startsWith("/api/snapshot.zip") === true) {
18922
19262
  const target = path22.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
18923
- if (!insideAllowedRoots(target)) {
19263
+ if (!lexicallyInside(target)) {
18924
19264
  send(403, { error: "outside the served directory: " + target });
18925
19265
  return;
18926
19266
  }
@@ -18928,6 +19268,10 @@ async function startWebServer(options) {
18928
19268
  send(404, { error: "not a snapshot directory: " + target });
18929
19269
  return;
18930
19270
  }
19271
+ if (!insideAllowedRoots(target)) {
19272
+ send(403, { error: "outside the served directory: " + target });
19273
+ return;
19274
+ }
18931
19275
  try {
18932
19276
  const zip = writeZip({ directory: target });
18933
19277
  response.writeHead(200, {
@@ -19249,8 +19593,8 @@ function gitDirectory(cwd) {
19249
19593
  }
19250
19594
  }
19251
19595
  function isInside3(parent, child) {
19252
- const relative15 = path24.relative(parent, child);
19253
- return relative15 === "" || !relative15.startsWith("..") && !path24.isAbsolute(relative15);
19596
+ const relative16 = path24.relative(parent, child);
19597
+ return relative16 === "" || !relative16.startsWith("..") && !path24.isAbsolute(relative16);
19254
19598
  }
19255
19599
  function isRegisteredWorktree(gitDir, cwd) {
19256
19600
  try {
@@ -19703,7 +20047,7 @@ function maskPathText(value, secretRules) {
19703
20047
  }
19704
20048
  function maskOwnerBrief(brief, secretRules) {
19705
20049
  if (brief === void 0) return void 0;
19706
- const mask = (value) => maskPathText(value, secretRules);
20050
+ const mask = (value) => scanAndRedactSecrets(value, secretRules ?? [], "owner-brief").redacted;
19707
20051
  return {
19708
20052
  ...brief,
19709
20053
  path: mask(brief.path),
@@ -19749,9 +20093,9 @@ function listEntries(dir) {
19749
20093
  return;
19750
20094
  }
19751
20095
  for (const child of children) {
19752
- const relative15 = prefix === "" ? child.name : `${prefix}/${child.name}`;
19753
- entries.push(relative15);
19754
- if (child.isDirectory()) walk2(path25.join(absolute, child.name), relative15);
20096
+ const relative16 = prefix === "" ? child.name : `${prefix}/${child.name}`;
20097
+ entries.push(relative16);
20098
+ if (child.isDirectory()) walk2(path25.join(absolute, child.name), relative16);
19755
20099
  }
19756
20100
  };
19757
20101
  walk2(dir, "");
@@ -19786,7 +20130,7 @@ function markerInventory(dir, written) {
19786
20130
  }
19787
20131
  return { entries, files };
19788
20132
  }
19789
- function markerPayload(dir, state, id, createdAt, written) {
20133
+ function markerPayload(dir, state, id, createdAt, written, runId) {
19790
20134
  const { entries, files } = markerInventory(dir, written);
19791
20135
  const marker2 = {
19792
20136
  generator: GENERATOR_NAME,
@@ -19795,6 +20139,7 @@ function markerPayload(dir, state, id, createdAt, written) {
19795
20139
  createdAt,
19796
20140
  state,
19797
20141
  id,
20142
+ ...runId === void 0 ? {} : { runId },
19798
20143
  pid: process.pid,
19799
20144
  entries,
19800
20145
  files
@@ -19892,6 +20237,7 @@ function readOwnershipMarker(dir) {
19892
20237
  createdAt: typeof candidate.createdAt === "string" ? candidate.createdAt : "unknown",
19893
20238
  state: candidate.state,
19894
20239
  id: candidate.id,
20240
+ runId: typeof candidate.runId === "string" ? candidate.runId : void 0,
19895
20241
  pid: typeof candidate.pid === "number" ? candidate.pid : void 0,
19896
20242
  manifestSha256: typeof candidate.manifestSha256 === "string" ? candidate.manifestSha256 : void 0,
19897
20243
  entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0,
@@ -20050,13 +20396,19 @@ function assessSnapshotDirectory(dir) {
20050
20396
  };
20051
20397
  }
20052
20398
  const entries = listEntries(dir);
20053
- const foreignEntries = entries.filter(
20399
+ let foreignEntries = entries.filter(
20054
20400
  (entry) => !recorded.has(entry) && !isIgnorableEntry(entry)
20055
20401
  );
20402
+ const legacySignatureOnly = foreignEntries.length === 1 && foreignEntries[0] === SIGNATURE_FILE && verifySnapshotSignature(dir).ok;
20403
+ if (legacySignatureOnly) foreignEntries = [];
20056
20404
  if (foreignEntries.length > 0) {
20057
20405
  return { owned: false, problem: null, foreignEntries, marker: marker2 };
20058
20406
  }
20059
- const inventoryProblem = marker2.files === void 0 ? null : verifyMarkerInventory(dir, entries, marker2.files);
20407
+ const inventoryProblem = marker2.files === void 0 ? null : verifyMarkerInventory(
20408
+ dir,
20409
+ legacySignatureOnly ? entries.filter((entry) => entry !== SIGNATURE_FILE) : entries,
20410
+ marker2.files
20411
+ );
20060
20412
  return {
20061
20413
  owned: inventoryProblem === null,
20062
20414
  problem: inventoryProblem,
@@ -20234,13 +20586,13 @@ function startLockHeartbeat(lockPath) {
20234
20586
  return () => void 0;
20235
20587
  }
20236
20588
  }
20237
- function acquireRunLock(stagingRoot) {
20589
+ function acquireRunLock(stagingRoot, runId) {
20238
20590
  const lockPath = lockPathFor(stagingRoot);
20239
20591
  const payload = `${JSON.stringify({
20240
20592
  pid: process.pid,
20241
20593
  stagingRoot,
20242
20594
  host: os3.hostname(),
20243
- runId: crypto5.randomUUID(),
20595
+ runId,
20244
20596
  heartbeatMs: LOCK_HEARTBEAT_MS,
20245
20597
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
20246
20598
  })}
@@ -20294,6 +20646,33 @@ function canonicalLockTarget(targetPath2) {
20294
20646
  function lockPathFor(stagingRoot) {
20295
20647
  return path25.join(os3.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
20296
20648
  }
20649
+ function releaseAbandonedRun(stagingRoots, runId) {
20650
+ if (runId.length === 0) return;
20651
+ for (const root of new Set(stagingRoots)) {
20652
+ const lockPath = lockPathFor(root);
20653
+ try {
20654
+ const payload = JSON.parse(fs24.readFileSync(lockPath, "utf8"));
20655
+ if (payload.runId === runId) fs24.rmSync(lockPath, { force: true });
20656
+ } catch {
20657
+ }
20658
+ let entries;
20659
+ try {
20660
+ entries = fs24.readdirSync(root);
20661
+ } catch {
20662
+ continue;
20663
+ }
20664
+ for (const name of entries) {
20665
+ if (!name.startsWith(RUN_DIR_PREFIX)) continue;
20666
+ const directory = path25.join(root, name);
20667
+ const { marker: marker2 } = readOwnershipMarker(directory);
20668
+ if (marker2?.runId !== runId) continue;
20669
+ try {
20670
+ fs24.rmSync(directory, { recursive: true, force: true });
20671
+ } catch {
20672
+ }
20673
+ }
20674
+ }
20675
+ }
20297
20676
  function lockHeartbeatAgeMs(lockPath) {
20298
20677
  try {
20299
20678
  return Date.now() - fs24.statSync(lockPath).mtimeMs;
@@ -20608,6 +20987,7 @@ function generateSnapshot(configInput, options) {
20608
20987
  assertUsableConfigInput(configInput);
20609
20988
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
20610
20989
  const dryRun = options?.dryRun ?? false;
20990
+ const runId = options?.runId ?? crypto5.randomUUID();
20611
20991
  const gitInfo = getGitInfo(config.cwd, config.branch);
20612
20992
  const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
20613
20993
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
@@ -20627,7 +21007,7 @@ function generateSnapshot(configInput, options) {
20627
21007
  // output — but only at these exact paths, not at every directory that shares the name.
20628
21008
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
20629
21009
  (directory) => path25.relative(config.cwd, path25.resolve(config.cwd, directory)).replace(/\\/g, "/")
20630
- ).filter((relative15) => relative15.length > 0 && !relative15.startsWith("..")),
21010
+ ).filter((relative16) => relative16.length > 0 && !relative16.startsWith("..")),
20631
21011
  // A staged path can be absent from the working tree while its index blob exists. Discovery
20632
21012
  // lists the working tree, so those paths would never reach the scan at all.
20633
21013
  ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
@@ -21314,9 +21694,13 @@ function generateSnapshot(configInput, options) {
21314
21694
  if (navigationText !== null) manifest.artifacts.navigation = artifactRecord(navigationText);
21315
21695
  const auditText = artifacts.audit ? generateAuditReport(manifest, secretFindings, config.secretRules) : null;
21316
21696
  if (auditText !== null) manifest.artifacts.audit = artifactRecord(auditText);
21317
- const diffReport = artifacts.diff ? generateDiffReport(config.cwd) : null;
21697
+ const reportExcludes = [...config.excludePatterns, ...config.presetExclude];
21698
+ const diffReport = artifacts.diff ? generateDiffReport(config.cwd, {
21699
+ secretRules: config.secretRules,
21700
+ excluded: (relativePath) => reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
21701
+ }) : null;
21318
21702
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
21319
- const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount }) : null;
21703
+ const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount, secretRules: config.secretRules }) : null;
21320
21704
  if (artifacts.diff && diffReport === null && !isGitRepository(config.cwd)) {
21321
21705
  manifest.warnings.push(
21322
21706
  "--include-diffs was requested, but the generated directory is not a git repository; reports/diff.md was not written."
@@ -21360,7 +21744,8 @@ function generateSnapshot(configInput, options) {
21360
21744
  const entry = {
21361
21745
  ...file,
21362
21746
  content,
21363
- inclusionMode: "full",
21747
+ inclusionMode: file.inclusionMode === "comments-stripped" ? "comments-stripped" : "full",
21748
+ ...file.emptyLinesRemoved === true ? { emptyLinesRemoved: true } : {},
21364
21749
  isPreviewTruncated: false,
21365
21750
  includedBytes: Buffer.byteLength(content, "utf8"),
21366
21751
  includedLines: countLines(content)
@@ -21428,7 +21813,7 @@ function generateSnapshot(configInput, options) {
21428
21813
  const lockKeys = Array.from(/* @__PURE__ */ new Set([tmpDir, outDir])).sort();
21429
21814
  const releases = [];
21430
21815
  try {
21431
- for (const key of lockKeys) releases.push(acquireRunLock(key));
21816
+ for (const key of lockKeys) releases.push(acquireRunLock(key, runId));
21432
21817
  } catch (error) {
21433
21818
  for (const release of [...releases].reverse()) release();
21434
21819
  throw error;
@@ -21455,6 +21840,7 @@ function generateSnapshot(configInput, options) {
21455
21840
  createdAt,
21456
21841
  state: "staging",
21457
21842
  id: snapshotId,
21843
+ runId,
21458
21844
  pid: process.pid
21459
21845
  });
21460
21846
  const partsDir = path25.join(stagingDir, "parts");
@@ -21523,6 +21909,17 @@ function generateSnapshot(configInput, options) {
21523
21909
  if (artifacts.manifest) {
21524
21910
  writeArtifact(stagingDir, "manifest.json", JSON.stringify(manifest, null, 2));
21525
21911
  }
21912
+ if (options?.sign !== void 0) {
21913
+ if (!artifacts.manifest) {
21914
+ throw new Error(
21915
+ "Refusing to sign: manifest.json is disabled for this run. Signing covers the manifest, so enable the manifest artifact or drop --sign."
21916
+ );
21917
+ }
21918
+ const record = signManifest(path25.join(stagingDir, "manifest.json"), {
21919
+ key: options.sign.key ?? null
21920
+ });
21921
+ writeArtifact(stagingDir, SIGNATURE_FILE, JSON.stringify(record, null, 2) + "\n");
21922
+ }
21526
21923
  if (monolithJson !== null) {
21527
21924
  writeArtifact(stagingDir, "full-codebase.json", monolithJson);
21528
21925
  }
@@ -21534,7 +21931,7 @@ function generateSnapshot(configInput, options) {
21534
21931
  }
21535
21932
  writeOwnershipMarker(
21536
21933
  stagingDir,
21537
- markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts)
21934
+ markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21538
21935
  );
21539
21936
  swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
21540
21937
  stagingDir = null;
@@ -21545,10 +21942,16 @@ function generateSnapshot(configInput, options) {
21545
21942
  if (artifacts.manifest && manifest.warnings.length !== warningsBeforeHook) {
21546
21943
  writeManifestAtomically(path25.join(outDir, "manifest.json"), manifest);
21547
21944
  recordArtifact(outDir, "manifest.json");
21945
+ if (options?.sign !== void 0) {
21946
+ const record = signManifest(path25.join(outDir, "manifest.json"), {
21947
+ key: options.sign.key ?? null
21948
+ });
21949
+ writeArtifact(outDir, SIGNATURE_FILE, JSON.stringify(record, null, 2) + "\n");
21950
+ }
21548
21951
  }
21549
21952
  writeOwnershipMarker(
21550
21953
  outDir,
21551
- markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts)
21954
+ markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21552
21955
  );
21553
21956
  };
21554
21957
  if (config.hooks.afterGenerate) shipHookState();
@@ -21728,8 +22131,43 @@ async function startHttpTransport(options) {
21728
22131
  "Refusing to serve " + host + " without a token: a repository reachable from the network must require Authorization. Drop --no-auth, or bind the loopback address."
21729
22132
  );
21730
22133
  }
21731
- const server = createServer({ cwd: options.cwd, log });
22134
+ const createMcp = () => createServer({ cwd: options.cwd, log });
21732
22135
  const toolCount = buildTools().length;
22136
+ const mcpSessions = /* @__PURE__ */ new Map();
22137
+ const socketServers = /* @__PURE__ */ new WeakMap();
22138
+ const anonymousServers = /* @__PURE__ */ new Map();
22139
+ const serverFor = (request) => {
22140
+ const header = request.headers["mcp-session-id"];
22141
+ const supplied = typeof header === "string" ? header.trim() : "";
22142
+ if (supplied !== "") {
22143
+ let existing = mcpSessions.get(supplied);
22144
+ if (existing === void 0) {
22145
+ 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);
22151
+ }
22152
+ return existing;
22153
+ }
22154
+ const onSocket = socketServers.get(request.socket);
22155
+ if (onSocket !== void 0) return onSocket;
22156
+ const userAgent = typeof request.headers["user-agent"] === "string" ? request.headers["user-agent"] : "";
22157
+ const fallbackKey = (request.socket.remoteAddress ?? "unknown") + "\0" + userAgent;
22158
+ let fallback = anonymousServers.get(fallbackKey);
22159
+ if (fallback === void 0) {
22160
+ fallback = createMcp();
22161
+ if (anonymousServers.size >= 64) {
22162
+ const oldest = anonymousServers.keys().next().value;
22163
+ if (oldest !== void 0) anonymousServers.delete(oldest);
22164
+ }
22165
+ anonymousServers.set(fallbackKey, fallback);
22166
+ }
22167
+ socketServers.set(request.socket, fallback);
22168
+ return fallback;
22169
+ };
22170
+ const newSessionId = () => crypto6.randomBytes(12).toString("hex");
21733
22171
  const sseSessions = /* @__PURE__ */ new Map();
21734
22172
  const tokenAccepted = (request, url) => {
21735
22173
  if (token === null) return true;
@@ -21752,6 +22190,18 @@ async function startHttpTransport(options) {
21752
22190
  const method = request.method ?? "UNKNOWN";
21753
22191
  metrics.byMethod.set(method, (metrics.byMethod.get(method) ?? 0) + 1);
21754
22192
  };
22193
+ const rateLimited = (request) => {
22194
+ const remote = request.socket.remoteAddress ?? "unknown";
22195
+ const now = Date.now();
22196
+ const window = sessions.get(remote);
22197
+ if (window === void 0 || window.resetAt <= now) {
22198
+ sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
22199
+ return false;
22200
+ }
22201
+ if (window.count >= RATE_LIMIT) return true;
22202
+ window.count += 1;
22203
+ return false;
22204
+ };
21755
22205
  const allowedOrigin = (origin) => {
21756
22206
  if (origin === void 0) return null;
21757
22207
  if (isLoopbackOrigin(origin)) return origin;
@@ -21759,7 +22209,10 @@ async function startHttpTransport(options) {
21759
22209
  };
21760
22210
  const httpServer = http3.createServer((request, response) => {
21761
22211
  noteRequest(request);
22212
+ let responseSent = false;
21762
22213
  const send = (status, body, extra = {}) => {
22214
+ if (responseSent) return;
22215
+ responseSent = true;
21763
22216
  const text2 = typeof body === "string" ? body : JSON.stringify(body);
21764
22217
  if (status >= 400 && status < 500 && status !== 429) metrics.refused += 1;
21765
22218
  response.writeHead(status, {
@@ -21835,6 +22288,11 @@ async function startHttpTransport(options) {
21835
22288
  send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
21836
22289
  return;
21837
22290
  }
22291
+ if (rateLimited(request)) {
22292
+ metrics.rateLimited += 1;
22293
+ send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
22294
+ return;
22295
+ }
21838
22296
  const id = crypto6.randomBytes(12).toString("hex");
21839
22297
  response.writeHead(200, {
21840
22298
  ...cors,
@@ -21846,7 +22304,7 @@ async function startHttpTransport(options) {
21846
22304
  const write = (payload) => {
21847
22305
  response.write(payload);
21848
22306
  };
21849
- sseSessions.set(id, { write, end: () => response.end() });
22307
+ sseSessions.set(id, { write, end: () => response.end(), server: createMcp() });
21850
22308
  const heartbeat = setInterval(() => write(": ping\n\n"), 15e3);
21851
22309
  const cleanup = () => {
21852
22310
  clearInterval(heartbeat);
@@ -21862,6 +22320,11 @@ async function startHttpTransport(options) {
21862
22320
  send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
21863
22321
  return;
21864
22322
  }
22323
+ if (rateLimited(request)) {
22324
+ metrics.rateLimited += 1;
22325
+ send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
22326
+ return;
22327
+ }
21865
22328
  const id = url.searchParams.get("sessionId") ?? "";
21866
22329
  const stream = sseSessions.get(id);
21867
22330
  if (stream === void 0) {
@@ -21870,9 +22333,12 @@ async function startHttpTransport(options) {
21870
22333
  }
21871
22334
  const chunks2 = [];
21872
22335
  let received2 = 0;
22336
+ let tooLarge2 = false;
21873
22337
  request.on("data", (chunk) => {
22338
+ if (tooLarge2) return;
21874
22339
  received2 += chunk.length;
21875
22340
  if (received2 > maxBody) {
22341
+ tooLarge2 = true;
21876
22342
  request.destroy();
21877
22343
  send(413, { error: "request body too large", limit: maxBody });
21878
22344
  return;
@@ -21880,6 +22346,7 @@ async function startHttpTransport(options) {
21880
22346
  chunks2.push(chunk);
21881
22347
  });
21882
22348
  request.on("end", () => {
22349
+ if (tooLarge2) return;
21883
22350
  void (async () => {
21884
22351
  let message;
21885
22352
  try {
@@ -21888,7 +22355,7 @@ async function startHttpTransport(options) {
21888
22355
  send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: String(error) } });
21889
22356
  return;
21890
22357
  }
21891
- const answer = await server.handle(message);
22358
+ const answer = await stream.server.handle(message);
21892
22359
  if (answer !== null) stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
21893
22360
  send(202, "", cors);
21894
22361
  })();
@@ -21915,20 +22382,22 @@ async function startHttpTransport(options) {
21915
22382
  return;
21916
22383
  }
21917
22384
  }
21918
- const remote = request.socket.remoteAddress ?? "unknown";
21919
- const now = Date.now();
21920
- const window = sessions.get(remote);
21921
- if (window === void 0 || window.resetAt <= now) sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
21922
- else if (window.count >= RATE_LIMIT) {
22385
+ if (rateLimited(request)) {
21923
22386
  metrics.rateLimited += 1;
21924
22387
  send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
21925
22388
  return;
21926
- } else window.count += 1;
22389
+ }
22390
+ const activeServer = serverFor(request);
22391
+ const sessionHeader = request.headers["mcp-session-id"];
22392
+ let sessionId = typeof sessionHeader === "string" ? sessionHeader.trim() : "";
21927
22393
  let received = 0;
22394
+ let tooLarge = false;
21928
22395
  const chunks = [];
21929
22396
  request.on("data", (chunk) => {
22397
+ if (tooLarge) return;
21930
22398
  received += chunk.length;
21931
22399
  if (received > maxBody) {
22400
+ tooLarge = true;
21932
22401
  request.destroy();
21933
22402
  send(413, { error: "request body too large", limit: maxBody }, cors);
21934
22403
  return;
@@ -21936,6 +22405,7 @@ async function startHttpTransport(options) {
21936
22405
  chunks.push(chunk);
21937
22406
  });
21938
22407
  request.on("end", () => {
22408
+ if (tooLarge) return;
21939
22409
  void (async () => {
21940
22410
  let message;
21941
22411
  try {
@@ -21944,17 +22414,26 @@ async function startHttpTransport(options) {
21944
22414
  send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error: " + error.message } }, cors);
21945
22415
  return;
21946
22416
  }
21947
- const answers = [];
21948
22417
  const batch = Array.isArray(message) ? message : [message];
22418
+ if (batch.length > 100) {
22419
+ send(400, { error: "JSON-RPC batch is limited to 100 messages" }, cors);
22420
+ return;
22421
+ }
22422
+ if (sessionId === "" && !Array.isArray(message) && message.method === "initialize") {
22423
+ sessionId = newSessionId();
22424
+ mcpSessions.set(sessionId, activeServer);
22425
+ }
22426
+ const sessionHeaders = sessionId === "" ? cors : { ...cors, "mcp-session-id": sessionId };
22427
+ const answers = [];
21949
22428
  for (const item of batch) {
21950
- const answer = await server.handle(item);
22429
+ const answer = await activeServer.handle(item);
21951
22430
  if (answer !== null) answers.push(answer);
21952
22431
  }
21953
22432
  if (answers.length === 0) {
21954
- send(202, "", cors);
22433
+ send(202, "", sessionHeaders);
21955
22434
  return;
21956
22435
  }
21957
- send(200, Array.isArray(message) ? answers : answers[0], cors);
22436
+ send(200, Array.isArray(message) ? answers : answers[0], sessionHeaders);
21958
22437
  })().catch((error) => {
21959
22438
  log("mcp/http: " + error.message);
21960
22439
  send(500, { jsonrpc: "2.0", id: null, error: { code: -32603, message: "Internal error" } }, cors);
@@ -22596,8 +23075,8 @@ function splitList(value) {
22596
23075
  }
22597
23076
  function displayOutPath(cwd, outDir, ...segments) {
22598
23077
  const absolute = path27.resolve(cwd, outDir, ...segments);
22599
- const relative15 = path27.relative(cwd, absolute);
22600
- if (relative15 && !relative15.startsWith("..") && !path27.isAbsolute(relative15)) return relative15;
23078
+ const relative16 = path27.relative(cwd, absolute);
23079
+ if (relative16 && !relative16.startsWith("..") && !path27.isAbsolute(relative16)) return relative16;
22601
23080
  return absolute;
22602
23081
  }
22603
23082
  function nextStepHint(cwd, scriptsAddedNow) {
@@ -23113,6 +23592,42 @@ ${formatUpdateNotice(notice, installKind())}
23113
23592
  }
23114
23593
  return code;
23115
23594
  }
23595
+ function generateCliOptions(invocation) {
23596
+ return {
23597
+ mode: invocation.command,
23598
+ format: invocation.format,
23599
+ dryRun: invocation.dryRun,
23600
+ cwd: invocation.cwd,
23601
+ outDir: invocation.outDir,
23602
+ includeMonolith: invocation.includeMonolith,
23603
+ includeSensitiveFiles: invocation.includeSensitiveFiles,
23604
+ maxPartBytes: invocation.maxPartBytes,
23605
+ maxPartTokens: invocation.maxPartTokens,
23606
+ largeFileBytes: invocation.largeFileBytes,
23607
+ maxMonolithBytes: invocation.maxMonolithBytes,
23608
+ attachmentSlots: invocation.attachmentSlots,
23609
+ maxParts: invocation.maxParts,
23610
+ ...invocation.includeDiffs === true ? { includeDiffs: true } : {},
23611
+ ...invocation.includeLogs === void 0 ? {} : { includeLogs: invocation.includeLogs },
23612
+ ...invocation.tokenTree === true ? { tokenTree: true } : {},
23613
+ ...invocation.stripComments === true ? { stripComments: true } : {},
23614
+ ...invocation.removeEmptyLines === true ? { removeEmptyLines: true } : {},
23615
+ ...invocation.only === void 0 ? {} : { only: invocation.only },
23616
+ ...invocation.ignore === void 0 ? {} : { ignore: invocation.ignore },
23617
+ ...invocation.pack === void 0 ? {} : { pack: invocation.pack },
23618
+ ...invocation.sign === true ? { sign: true } : {},
23619
+ brief: invocation.brief,
23620
+ promptTask: invocation.promptTask,
23621
+ skipArtifacts: invocation.skipArtifacts,
23622
+ onlyArtifacts: invocation.onlyArtifacts,
23623
+ discovery: invocation.discovery,
23624
+ changedSince: invocation.changedSince,
23625
+ staged: invocation.staged,
23626
+ withDependents: invocation.withDependents,
23627
+ skeleton: invocation.skeleton,
23628
+ sarif: invocation.sarif
23629
+ };
23630
+ }
23116
23631
  async function runCommand(argv) {
23117
23632
  let invocation;
23118
23633
  try {
@@ -23266,42 +23781,7 @@ ${USAGE}
23266
23781
  try {
23267
23782
  resolved = resolveConfig(
23268
23783
  loaded.config,
23269
- {
23270
- mode: invocation.command,
23271
- format: invocation.format,
23272
- dryRun: invocation.dryRun,
23273
- cwd: invocation.cwd,
23274
- outDir: invocation.outDir,
23275
- includeMonolith: invocation.includeMonolith,
23276
- includeSensitiveFiles: invocation.includeSensitiveFiles,
23277
- maxPartBytes: invocation.maxPartBytes,
23278
- maxPartTokens: invocation.maxPartTokens,
23279
- largeFileBytes: invocation.largeFileBytes,
23280
- maxMonolithBytes: invocation.maxMonolithBytes,
23281
- attachmentSlots: invocation.attachmentSlots,
23282
- maxParts: invocation.maxParts,
23283
- ...invocation.includeDiffs === true ? { includeDiffs: true } : {},
23284
- ...invocation.includeLogs === void 0 ? {} : { includeLogs: invocation.includeLogs },
23285
- ...invocation.tokenTree === true ? { tokenTree: true } : {},
23286
- ...invocation.stripComments === true ? { stripComments: true } : {},
23287
- ...invocation.removeEmptyLines === true ? { removeEmptyLines: true } : {},
23288
- ...invocation.only === void 0 ? {} : { only: invocation.only },
23289
- ...invocation.ignore === void 0 ? {} : { ignore: invocation.ignore },
23290
- ...invocation.pack === void 0 ? {} : { pack: invocation.pack },
23291
- brief: invocation.brief,
23292
- promptTask: invocation.promptTask,
23293
- skipArtifacts: invocation.skipArtifacts,
23294
- // `--only-artifacts` is forwarded as itself, not only as the derived suppression list:
23295
- // suppression cannot switch an artifact *on*, so a config that had turned one of the
23296
- // requested artifacts off left the run with nothing to write.
23297
- onlyArtifacts: invocation.onlyArtifacts,
23298
- discovery: invocation.discovery,
23299
- changedSince: invocation.changedSince,
23300
- staged: invocation.staged,
23301
- withDependents: invocation.withDependents,
23302
- skeleton: invocation.skeleton,
23303
- sarif: invocation.sarif
23304
- },
23784
+ generateCliOptions(invocation),
23305
23785
  invocation.cwd
23306
23786
  );
23307
23787
  } catch (err) {
@@ -23337,7 +23817,11 @@ ${USAGE}
23337
23817
  rows.push({ name, score: 0, counts: { pass: 0, warn: 0, fail: 1 }, failed: [], error: "no snapshot at " + snapshotDir2 });
23338
23818
  continue;
23339
23819
  }
23340
- const report3 = auditSnapshot({ snapshotDir: snapshotDir2, repoDir });
23820
+ const report3 = auditSnapshot({
23821
+ snapshotDir: snapshotDir2,
23822
+ repoDir,
23823
+ ...invocation.deep === true ? { deep: true } : {}
23824
+ });
23341
23825
  rows.push({
23342
23826
  name,
23343
23827
  score: report3.score,
@@ -23479,6 +23963,12 @@ ${USAGE}
23479
23963
  if (invocation.watch) {
23480
23964
  const problem = watchSupportProblem();
23481
23965
  if (problem !== null) return fail(invocation.format, problem);
23966
+ if (invocation.delta !== void 0) {
23967
+ return fail(
23968
+ invocation.format,
23969
+ "--watch cannot track a fixed --delta base; run a one-shot generate --delta, or watch without it."
23970
+ );
23971
+ }
23482
23972
  }
23483
23973
  if (invocation.workspace !== void 0) {
23484
23974
  const members = invocation.workspace.split(",").map((member) => member.trim()).filter((member) => member.length > 0);
@@ -23604,16 +24094,18 @@ ${USAGE}
23604
24094
  question: invocation.slice,
23605
24095
  ...invocation.sliceTokens === void 0 ? {} : { maxTokens: invocation.sliceTokens }
23606
24096
  }
23607
- }
24097
+ },
24098
+ ...invocation.sign === true && !invocation.dryRun ? { sign: { key: loadSigningKey() } } : {}
23608
24099
  });
23609
24100
  if (invocation.sign === true && !invocation.dryRun) {
23610
- const manifestPath = path27.resolve(resolved.cwd, resolved.outDir, "manifest.json");
24101
+ const signaturePath = path27.resolve(resolved.cwd, resolved.outDir, SIGNATURE_FILE);
23611
24102
  try {
23612
- const record = signManifest(manifestPath, { key: loadSigningKey() });
23613
- writeSignature(path27.dirname(manifestPath), record);
23614
- info(" Signature: ed25519, " + record.keyOrigin + " key, " + record.fingerprint.slice(0, 12));
24103
+ const record = JSON.parse(fs26.readFileSync(signaturePath, "utf8"));
24104
+ info(
24105
+ " Signature: ed25519, " + (record.keyOrigin ?? "unknown") + " key, " + (record.fingerprint ?? manifest.fingerprint).slice(0, 12)
24106
+ );
23615
24107
  } catch (error) {
23616
- return fail(invocation.format, "Signing failed: " + error.message);
24108
+ return fail(invocation.format, "The snapshot was written but its signature could not be read: " + error.message);
23617
24109
  }
23618
24110
  }
23619
24111
  const elapsed = ((performance.now() - started) / 1e3).toFixed(2);
@@ -23765,8 +24257,8 @@ function comparablePath(value) {
23765
24257
  return process.platform === "win32" ? absolute.toLowerCase() : absolute;
23766
24258
  }
23767
24259
  function isSameOrInside(parent, candidate) {
23768
- const relative15 = path27.relative(parent, candidate);
23769
- return relative15 === "" || relative15 !== ".." && !relative15.startsWith(`..${path27.sep}`) && !path27.isAbsolute(relative15);
24260
+ const relative16 = path27.relative(parent, candidate);
24261
+ return relative16 === "" || relative16 !== ".." && !relative16.startsWith(`..${path27.sep}`) && !path27.isAbsolute(relative16);
23770
24262
  }
23771
24263
  function isGeneratedWatchPath(candidate, paths) {
23772
24264
  const absolute = comparablePath(path27.resolve(paths.cwd, candidate));
@@ -23841,34 +24333,20 @@ async function runWatchLoop(invocation, resolved, options) {
23841
24333
  for (const warning of loaded.warnings) warn(`\u26A0 Config: ${warning}`);
23842
24334
  const next = resolveConfig(
23843
24335
  loaded.config,
23844
- {
23845
- mode: invocation.command,
23846
- format: invocation.format,
23847
- dryRun: invocation.dryRun,
23848
- cwd: invocation.cwd,
23849
- outDir: invocation.outDir,
23850
- includeMonolith: invocation.includeMonolith,
23851
- includeSensitiveFiles: invocation.includeSensitiveFiles,
23852
- maxPartBytes: invocation.maxPartBytes,
23853
- maxPartTokens: invocation.maxPartTokens,
23854
- largeFileBytes: invocation.largeFileBytes,
23855
- maxMonolithBytes: invocation.maxMonolithBytes,
23856
- attachmentSlots: invocation.attachmentSlots,
23857
- maxParts: invocation.maxParts,
23858
- brief: invocation.brief,
23859
- promptTask: invocation.promptTask,
23860
- skipArtifacts: invocation.skipArtifacts,
23861
- onlyArtifacts: invocation.onlyArtifacts,
23862
- discovery: invocation.discovery,
23863
- changedSince: invocation.changedSince,
23864
- staged: invocation.staged,
23865
- withDependents: invocation.withDependents,
23866
- skeleton: invocation.skeleton,
23867
- sarif: invocation.sarif
23868
- },
24336
+ generateCliOptions(invocation),
23869
24337
  invocation.cwd
23870
24338
  );
23871
- const manifest = generateSnapshot(next, { dryRun: invocation.dryRun });
24339
+ const manifest = generateSnapshot(next, {
24340
+ dryRun: invocation.dryRun,
24341
+ ...invocation.budgetTokens === void 0 ? {} : { budgetTokens: invocation.budgetTokens },
24342
+ ...invocation.slice === void 0 ? {} : {
24343
+ slice: {
24344
+ question: invocation.slice,
24345
+ ...invocation.sliceTokens === void 0 ? {} : { maxTokens: invocation.sliceTokens }
24346
+ }
24347
+ },
24348
+ ...invocation.sign === true && !invocation.dryRun ? { sign: { key: loadSigningKey() } } : {}
24349
+ });
23872
24350
  paths = watchPathsFor(next);
23873
24351
  const elapsed = ((performance.now() - started) / 1e3).toFixed(2);
23874
24352
  info(