codebase-snapshot 0.20.2 → 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/cli.cjs CHANGED
@@ -197,8 +197,8 @@ function workspacePackageDirs(cwd, patterns) {
197
197
  function scanWorkspacePackages(cwd, patterns) {
198
198
  const files = /* @__PURE__ */ new Set();
199
199
  const dependencies = /* @__PURE__ */ new Set();
200
- for (const relative15 of workspacePackageDirs(cwd, patterns)) {
201
- const full = path27__namespace.join(cwd, relative15);
200
+ for (const relative16 of workspacePackageDirs(cwd, patterns)) {
201
+ const full = path27__namespace.join(cwd, relative16);
202
202
  try {
203
203
  for (const entry of fs24__namespace.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
204
204
  } catch {
@@ -2226,10 +2226,68 @@ function applySpansKeepingQuotes(line, spans) {
2226
2226
  out += line.slice(cursor);
2227
2227
  return out;
2228
2228
  }
2229
+ var SIGNATURE_FILE = "signature.json";
2230
+ function loadSigningKey(environment = process.env) {
2231
+ const pem = environment.SNAPSHOT_SIGNING_KEY;
2232
+ if (pem === void 0 || pem.trim() === "") return null;
2233
+ return crypto__namespace.createPrivateKey({ key: pem, format: "pem" });
2234
+ }
2235
+ function signManifest(manifestPath, options = {}) {
2236
+ const bytes = fs24__namespace.readFileSync(manifestPath);
2237
+ const manifest = JSON.parse(bytes.toString("utf8"));
2238
+ if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
2239
+ throw new Error("refusing to sign: the manifest has no valid fingerprint");
2240
+ }
2241
+ const configured = options.key ?? null;
2242
+ const key = configured ?? crypto__namespace.generateKeyPairSync("ed25519").privateKey;
2243
+ const publicKey = crypto__namespace.createPublicKey(key).export({ type: "spki", format: "der" }).toString("base64");
2244
+ const signature = crypto__namespace.sign(null, bytes, key).toString("base64");
2245
+ return {
2246
+ algorithm: "ed25519",
2247
+ signedAt: options.signedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
2248
+ fingerprint: manifest.fingerprint,
2249
+ manifestSha256: crypto__namespace.createHash("sha256").update(bytes).digest("hex"),
2250
+ publicKey,
2251
+ signature,
2252
+ keyOrigin: configured === null ? "generated" : "configured"
2253
+ };
2254
+ }
2255
+ function verifySnapshotSignature(snapshotDir) {
2256
+ const signaturePath = path27__namespace.join(snapshotDir, SIGNATURE_FILE);
2257
+ const manifestPath = path27__namespace.join(snapshotDir, "manifest.json");
2258
+ if (!fs24__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
2259
+ let record;
2260
+ try {
2261
+ record = JSON.parse(fs24__namespace.readFileSync(signaturePath, "utf8"));
2262
+ } catch (error) {
2263
+ return { ok: false, reason: "signature.json is not JSON: " + error.message };
2264
+ }
2265
+ if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
2266
+ return { ok: false, reason: "signature.json is not an ed25519 record" };
2267
+ }
2268
+ let bytes;
2269
+ try {
2270
+ bytes = fs24__namespace.readFileSync(manifestPath);
2271
+ } catch {
2272
+ return { ok: false, reason: "the signed manifest is missing" };
2273
+ }
2274
+ const sha2562 = crypto__namespace.createHash("sha256").update(bytes).digest("hex");
2275
+ if (sha2562 !== record.manifestSha256) {
2276
+ return { ok: false, reason: "manifest.json changed after it was signed" };
2277
+ }
2278
+ let verified = false;
2279
+ try {
2280
+ const key = crypto__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
2281
+ verified = crypto__namespace.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
2282
+ } catch (error) {
2283
+ return { ok: false, reason: "the signature could not be checked: " + error.message };
2284
+ }
2285
+ return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
2286
+ }
2229
2287
 
2230
2288
  // src/version.ts
2231
2289
  var GENERATOR_NAME = "codebase-snapshot";
2232
- var GENERATOR_VERSION = "0.20.2";
2290
+ var GENERATOR_VERSION = "0.20.4";
2233
2291
  var SCHEMA_VERSION = "3.0.0";
2234
2292
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2235
2293
  function isOurGeneratorName(name) {
@@ -2261,8 +2319,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
2261
2319
  };
2262
2320
  }
2263
2321
  function isInside(root, candidate) {
2264
- const relative15 = path27__namespace.relative(root, candidate);
2265
- return relative15 === "" || !relative15.startsWith(`..${path27__namespace.sep}`) && relative15 !== ".." && !path27__namespace.isAbsolute(relative15);
2322
+ const relative16 = path27__namespace.relative(root, candidate);
2323
+ return relative16 === "" || !relative16.startsWith(`..${path27__namespace.sep}`) && relative16 !== ".." && !path27__namespace.isAbsolute(relative16);
2266
2324
  }
2267
2325
  var GIT_OUTPUT_LIMIT = 68157440;
2268
2326
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -2736,7 +2794,7 @@ function listIgnoredPaths(cwd) {
2736
2794
  }
2737
2795
  function hasSnapshotMarker(target) {
2738
2796
  try {
2739
- return fs24__namespace.statSync(target).isDirectory() && fs24__namespace.existsSync(path27__namespace.join(target, ".codebase-snapshot"));
2797
+ return fs24__namespace.statSync(target).isDirectory() && isToolOwnedDirectory2(target);
2740
2798
  } catch {
2741
2799
  return false;
2742
2800
  }
@@ -2777,7 +2835,9 @@ function isToolOwnedDirectory2(dir) {
2777
2835
  return false;
2778
2836
  }
2779
2837
  return entries.every(
2780
- (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || accounted.has(entry)
2838
+ (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || // A snapshot signed before signing moved into staging has a valid signature.json the old
2839
+ // marker could not record. It is our artifact when the signature verifies.
2840
+ entry === "signature.json" && verifySnapshotSignature(dir).ok || accounted.has(entry)
2781
2841
  );
2782
2842
  }
2783
2843
  function makeToolOwnedDecider(cwd, toolOwnedPaths) {
@@ -2887,6 +2947,15 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
2887
2947
  });
2888
2948
  continue;
2889
2949
  }
2950
+ const targetRelative = path27__namespace.relative(rootReal, targetReal).split(path27__namespace.sep).join("/");
2951
+ if (isSensitivePath(targetRelative)) {
2952
+ report2(linkedPath, {
2953
+ path: linkedPath,
2954
+ reason: "sensitive-file",
2955
+ detail: "link target is a credential-bearing file; not followed"
2956
+ });
2957
+ continue;
2958
+ }
2890
2959
  kept.push(candidate);
2891
2960
  }
2892
2961
  return kept;
@@ -3612,21 +3681,25 @@ var CONFIG_KEY_NAMES = [
3612
3681
  "kinds",
3613
3682
  "largeFileBytes",
3614
3683
  "layers",
3684
+ "logCount",
3615
3685
  "layersMode",
3616
3686
  "maxMonolithBytes",
3617
3687
  "maxPartBytes",
3618
3688
  "maxParts",
3619
3689
  "maxPartTokens",
3620
3690
  "outDir",
3691
+ "pack",
3621
3692
  "preset",
3622
3693
  "previewHeadLines",
3623
3694
  "promptTask",
3624
3695
  "staged",
3625
3696
  "previewTailLines",
3697
+ "removeEmptyLines",
3626
3698
  "secretRules",
3627
3699
  "secrets",
3628
3700
  "sarif",
3629
3701
  "skeleton",
3702
+ "stripComments",
3630
3703
  "tmpDir",
3631
3704
  "withDependents"
3632
3705
  ];
@@ -3934,7 +4007,34 @@ function readConfiguredBrief(cwd, value) {
3934
4007
  "brief must be a path to a markdown file (received " + describeValue2(value) + ")."
3935
4008
  );
3936
4009
  }
3937
- const filePath = path27__namespace.resolve(cwd, value);
4010
+ const rootReal = (() => {
4011
+ try {
4012
+ return fs24__namespace.realpathSync(cwd);
4013
+ } catch {
4014
+ return path27__namespace.resolve(cwd);
4015
+ }
4016
+ })();
4017
+ const requested = path27__namespace.resolve(cwd, value);
4018
+ let filePath;
4019
+ try {
4020
+ filePath = fs24__namespace.realpathSync(requested);
4021
+ } catch {
4022
+ throw new Error(
4023
+ 'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
4024
+ );
4025
+ }
4026
+ const relative16 = path27__namespace.relative(rootReal, filePath);
4027
+ if (relative16.length === 0 || relative16 === ".." || relative16.startsWith(`..${path27__namespace.sep}`) || path27__namespace.isAbsolute(relative16)) {
4028
+ throw new Error(
4029
+ 'brief "' + value + '" resolves outside the repository. A brief must be a file inside the repository being described; an absolute or parent path is refused.'
4030
+ );
4031
+ }
4032
+ const posixRelative = relative16.split(path27__namespace.sep).join("/");
4033
+ if (isSensitivePath(posixRelative) || isSensitivePath(value)) {
4034
+ throw new Error(
4035
+ 'brief "' + value + '" is a credential-bearing file. A snapshot must not reproduce secrets, so it cannot be used as the owner brief.'
4036
+ );
4037
+ }
3938
4038
  let text2;
3939
4039
  try {
3940
4040
  if (!fs24__namespace.statSync(filePath).isFile()) throw new Error("not a file");
@@ -4051,11 +4151,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
4051
4151
  const patterns = [];
4052
4152
  for (const dir of [outDir, tmpDir]) {
4053
4153
  const absolute = path27__namespace.resolve(cwd, dir);
4054
- const relative15 = path27__namespace.relative(cwd, absolute);
4055
- if (!relative15 || relative15 === ".." || relative15.startsWith(`..${path27__namespace.sep}`) || path27__namespace.isAbsolute(relative15)) {
4154
+ const relative16 = path27__namespace.relative(cwd, absolute);
4155
+ if (!relative16 || relative16 === ".." || relative16.startsWith(`..${path27__namespace.sep}`) || path27__namespace.isAbsolute(relative16)) {
4056
4156
  continue;
4057
4157
  }
4058
- patterns.push(`${relative15.replace(/\\/g, "/")}/**`);
4158
+ patterns.push(`${relative16.replace(/\\/g, "/")}/**`);
4059
4159
  }
4060
4160
  return patterns;
4061
4161
  }
@@ -4685,8 +4785,8 @@ function tsconfigPathsFor(cwd) {
4685
4785
  return value;
4686
4786
  }
4687
4787
  function repositoryRelative(cwd, target) {
4688
- const relative15 = path27__namespace.relative(cwd, target).replace(/\\/g, "/");
4689
- return relative15.length === 0 || !relative15.startsWith("..") && !path27__namespace.isAbsolute(relative15) ? relative15 : null;
4788
+ const relative16 = path27__namespace.relative(cwd, target).replace(/\\/g, "/");
4789
+ return relative16.length === 0 || !relative16.startsWith("..") && !path27__namespace.isAbsolute(relative16) ? relative16 : null;
4690
4790
  }
4691
4791
  function rememberFirst(map, key, value) {
4692
4792
  if (!map.has(key)) map.set(key, value);
@@ -5650,9 +5750,9 @@ var rubyProfile = {
5650
5750
  eachLine(content, (line) => {
5651
5751
  const trimmed = line.trim();
5652
5752
  if (!trimmed || trimmed.startsWith("#")) return;
5653
- const relative15 = REQUIRE_RELATIVE.exec(trimmed);
5654
- if (relative15) {
5655
- summary.imports.push(`./${relative15[1]}`);
5753
+ const relative16 = REQUIRE_RELATIVE.exec(trimmed);
5754
+ if (relative16) {
5755
+ summary.imports.push(`./${relative16[1]}`);
5656
5756
  return;
5657
5757
  }
5658
5758
  const required = REQUIRE.exec(trimmed);
@@ -6235,69 +6335,6 @@ function importsOfFile(relativePath, absolutePath) {
6235
6335
  if (decoded.binary) return [];
6236
6336
  return importsOfText(relativePath, decoded.text);
6237
6337
  }
6238
- var SIGNATURE_FILE = "signature.json";
6239
- function loadSigningKey(environment = process.env) {
6240
- const pem = environment.SNAPSHOT_SIGNING_KEY;
6241
- if (pem === void 0 || pem.trim() === "") return null;
6242
- return crypto__namespace.createPrivateKey({ key: pem, format: "pem" });
6243
- }
6244
- function signManifest(manifestPath, options = {}) {
6245
- const bytes = fs24__namespace.readFileSync(manifestPath);
6246
- const manifest = JSON.parse(bytes.toString("utf8"));
6247
- if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
6248
- throw new Error("refusing to sign: the manifest has no valid fingerprint");
6249
- }
6250
- const configured = options.key ?? null;
6251
- const key = configured ?? crypto__namespace.generateKeyPairSync("ed25519").privateKey;
6252
- const publicKey = crypto__namespace.createPublicKey(key).export({ type: "spki", format: "der" }).toString("base64");
6253
- const signature = crypto__namespace.sign(null, bytes, key).toString("base64");
6254
- return {
6255
- algorithm: "ed25519",
6256
- signedAt: options.signedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
6257
- fingerprint: manifest.fingerprint,
6258
- manifestSha256: crypto__namespace.createHash("sha256").update(bytes).digest("hex"),
6259
- publicKey,
6260
- signature,
6261
- keyOrigin: configured === null ? "generated" : "configured"
6262
- };
6263
- }
6264
- function writeSignature(snapshotDir, record) {
6265
- const target = path27__namespace.join(snapshotDir, SIGNATURE_FILE);
6266
- fs24__namespace.writeFileSync(target, JSON.stringify(record, null, 2) + "\n", "utf8");
6267
- return target;
6268
- }
6269
- function verifySnapshotSignature(snapshotDir) {
6270
- const signaturePath = path27__namespace.join(snapshotDir, SIGNATURE_FILE);
6271
- const manifestPath = path27__namespace.join(snapshotDir, "manifest.json");
6272
- if (!fs24__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
6273
- let record;
6274
- try {
6275
- record = JSON.parse(fs24__namespace.readFileSync(signaturePath, "utf8"));
6276
- } catch (error) {
6277
- return { ok: false, reason: "signature.json is not JSON: " + error.message };
6278
- }
6279
- if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
6280
- return { ok: false, reason: "signature.json is not an ed25519 record" };
6281
- }
6282
- let bytes;
6283
- try {
6284
- bytes = fs24__namespace.readFileSync(manifestPath);
6285
- } catch {
6286
- return { ok: false, reason: "the signed manifest is missing" };
6287
- }
6288
- const sha2562 = crypto__namespace.createHash("sha256").update(bytes).digest("hex");
6289
- if (sha2562 !== record.manifestSha256) {
6290
- return { ok: false, reason: "manifest.json changed after it was signed" };
6291
- }
6292
- let verified = false;
6293
- try {
6294
- const key = crypto__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
6295
- verified = crypto__namespace.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
6296
- } catch (error) {
6297
- return { ok: false, reason: "the signature could not be checked: " + error.message };
6298
- }
6299
- return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
6300
- }
6301
6338
 
6302
6339
  // src/validator/validate.ts
6303
6340
  function maskedPath(value, secretRules) {
@@ -6716,17 +6753,18 @@ function validateSnapshot(configInput) {
6716
6753
  return skippedReasons.get(maskedPath(diskFile, config.secretRules)) ?? null;
6717
6754
  };
6718
6755
  let unchangedScope = null;
6756
+ let stagedScope = null;
6719
6757
  const recordedChangedSince = manifest.config?.changedSince;
6720
6758
  const recordedStaged = manifest.config?.staged === true;
6721
6759
  const recordedWithDependents = manifest.config?.withDependents === true;
6722
6760
  if (recordedChangedSince !== void 0 || recordedStaged) {
6723
6761
  try {
6724
- unchangedScope = new Set(
6725
- resolveChangedScope(config.cwd, {
6726
- ...recordedChangedSince === void 0 ? {} : { changedSince: recordedChangedSince },
6727
- ...recordedStaged ? { staged: true } : {}
6728
- }).paths
6729
- );
6762
+ const scope = resolveChangedScope(config.cwd, {
6763
+ ...recordedChangedSince === void 0 ? {} : { changedSince: recordedChangedSince },
6764
+ ...recordedStaged ? { staged: true } : {}
6765
+ });
6766
+ unchangedScope = new Set(scope.paths);
6767
+ if (recordedStaged) stagedScope = new Set(scope.stagedPaths);
6730
6768
  } catch {
6731
6769
  warnings.push(
6732
6770
  "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."
@@ -6737,7 +6775,11 @@ function validateSnapshot(configInput) {
6737
6775
  function becameDependent(diskFile) {
6738
6776
  if (!recordedWithDependents || unchangedScope === null) return false;
6739
6777
  dependentResolver ??= buildImportResolver(
6740
- collection.files.map((file) => ({ relativePath: file }))
6778
+ collection.files.map((file) => ({ relativePath: file })),
6779
+ {
6780
+ tsconfig: tsconfigPathsFor(config.cwd),
6781
+ ...unchangedScope === null ? {} : { extraPaths: unchangedScope }
6782
+ }
6741
6783
  );
6742
6784
  return importsChangedFile(
6743
6785
  diskFile,
@@ -6760,7 +6802,7 @@ function validateSnapshot(configInput) {
6760
6802
  // snapshot was reported as drifting.
6761
6803
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
6762
6804
  (directory) => path27__namespace.relative(config.cwd, path27__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
6763
- ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
6805
+ ).filter((relative16) => relative16.length > 0 && !relative16.startsWith(".."))
6764
6806
  });
6765
6807
  for (const diskFile of collection.files) {
6766
6808
  const snapshotHash = manifestFileMap.get(diskFile);
@@ -6786,7 +6828,8 @@ function validateSnapshot(configInput) {
6786
6828
  }
6787
6829
  let diskHash;
6788
6830
  try {
6789
- diskHash = sha256Hex(fs24__namespace.readFileSync(path27__namespace.join(config.cwd, diskFile)));
6831
+ const stagedBlob = recordedStaged && stagedScope?.has(diskFile) === true ? readStagedBlob(config.cwd, diskFile) : null;
6832
+ diskHash = sha256Hex(stagedBlob ?? fs24__namespace.readFileSync(path27__namespace.join(config.cwd, diskFile)));
6790
6833
  } catch (err) {
6791
6834
  if (err.code === "ENOENT") {
6792
6835
  drift.missingOnDisk.push(diskFile);
@@ -7240,8 +7283,8 @@ function validateSnapshot(configInput) {
7240
7283
  const target = match[1].split("#")[0];
7241
7284
  if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
7242
7285
  const resolved = path27__namespace.resolve(snapshotDir, "reports", target);
7243
- const relative15 = path27__namespace.relative(snapshotDir, resolved);
7244
- if (relative15.startsWith("..") || path27__namespace.isAbsolute(relative15) || !fs24__namespace.existsSync(resolved)) {
7286
+ const relative16 = path27__namespace.relative(snapshotDir, resolved);
7287
+ if (relative16.startsWith("..") || path27__namespace.isAbsolute(relative16) || !fs24__namespace.existsSync(resolved)) {
7245
7288
  drift.partIssues.push({
7246
7289
  part: key,
7247
7290
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -7884,23 +7927,23 @@ function describeMatcher(matcher) {
7884
7927
  function normalizeTarget(cwd, target) {
7885
7928
  const resolvedCwd = path27__namespace.resolve(cwd);
7886
7929
  const absolute = path27__namespace.resolve(resolvedCwd, target);
7887
- const relative15 = path27__namespace.relative(resolvedCwd, absolute);
7888
- if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path27__namespace.sep}`) || path27__namespace.isAbsolute(relative15)) {
7930
+ const relative16 = path27__namespace.relative(resolvedCwd, absolute);
7931
+ if (relative16 === "" || relative16 === ".." || relative16.startsWith(`..${path27__namespace.sep}`) || path27__namespace.isAbsolute(relative16)) {
7889
7932
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
7890
7933
  }
7891
- return { relative: relative15.split(path27__namespace.sep).join("/"), outsideRoot: false };
7934
+ return { relative: relative16.split(path27__namespace.sep).join("/"), outsideRoot: false };
7892
7935
  }
7893
7936
  function findRuleMatch(rules, relativePath) {
7894
7937
  return rules.find(
7895
7938
  (rule) => matchRule(relativePath, rule.match)
7896
7939
  );
7897
7940
  }
7898
- function findRecordedAncestor(skipped, relative15, maskedPath2) {
7941
+ function findRecordedAncestor(skipped, relative16, maskedPath2) {
7899
7942
  let nearest;
7900
7943
  for (const record of skipped) {
7901
7944
  const ancestorPath = record.path;
7902
7945
  if (ancestorPath.length === 0) continue;
7903
- const isAncestor = relative15.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
7946
+ const isAncestor = relative16.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
7904
7947
  if (!isAncestor) continue;
7905
7948
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
7906
7949
  }
@@ -7916,8 +7959,8 @@ function readManifest2(config) {
7916
7959
  }
7917
7960
  function explainPath(config, target) {
7918
7961
  const normalized = normalizeTarget(config.cwd, target);
7919
- const relative15 = normalized.relative;
7920
- const maskedPath2 = findSecretInPath(relative15, config.secretRules)?.masked ?? relative15;
7962
+ const relative16 = normalized.relative;
7963
+ const maskedPath2 = findSecretInPath(relative16, config.secretRules)?.masked ?? relative16;
7921
7964
  if (normalized.outsideRoot) {
7922
7965
  return {
7923
7966
  path: maskedPath2,
@@ -7927,7 +7970,7 @@ function explainPath(config, target) {
7927
7970
  detail: "path resolves outside the configured repository root and was not inspected"
7928
7971
  };
7929
7972
  }
7930
- const absolute = path27__namespace.join(config.cwd, relative15);
7973
+ const absolute = path27__namespace.join(config.cwd, relative16);
7931
7974
  const result = {
7932
7975
  path: maskedPath2,
7933
7976
  exists: fs24__namespace.existsSync(absolute),
@@ -7945,11 +7988,11 @@ function explainPath(config, target) {
7945
7988
  // that is only missing because the walker dropped the tool's own output directory.
7946
7989
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
7947
7990
  (directory) => path27__namespace.relative(config.cwd, path27__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
7948
- ).filter((relative16) => relative16.length > 0 && !relative16.startsWith(".."))
7991
+ ).filter((relative17) => relative17.length > 0 && !relative17.startsWith(".."))
7949
7992
  });
7950
- if (!collection.files.includes(relative15)) {
7993
+ if (!collection.files.includes(relative16)) {
7951
7994
  const record = collection.skipped.find(
7952
- (entry2) => entry2.path === relative15 || entry2.path === maskedPath2
7995
+ (entry2) => entry2.path === relative16 || entry2.path === maskedPath2
7953
7996
  );
7954
7997
  if (record) {
7955
7998
  result.reason = record.reason;
@@ -7958,7 +8001,7 @@ function explainPath(config, target) {
7958
8001
  result.reason = "missing";
7959
8002
  result.detail = "no such file or directory, relative to the configured cwd";
7960
8003
  } else {
7961
- const ancestor = findRecordedAncestor(collection.skipped, relative15, maskedPath2);
8004
+ const ancestor = findRecordedAncestor(collection.skipped, relative16, maskedPath2);
7962
8005
  if (ancestor) {
7963
8006
  result.reason = ancestor.reason;
7964
8007
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -7978,13 +8021,15 @@ function explainPath(config, target) {
7978
8021
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
7979
8022
  ...config.staged === true ? { staged: true } : {}
7980
8023
  });
7981
- inScope = scope.paths.has(relative15);
8024
+ inScope = scope.paths.has(relative16);
7982
8025
  if (!inScope && config.withDependents === true) {
7983
8026
  inScope = importsChangedFile(
7984
- relative15,
7985
- importsOfFile(relative15, absolute),
8027
+ relative16,
8028
+ importsOfFile(relative16, absolute),
7986
8029
  scope.paths,
7987
- buildImportResolver(collection.files.map((file) => ({ relativePath: file })))
8030
+ buildImportResolver(collection.files.map((file) => ({ relativePath: file })), {
8031
+ tsconfig: tsconfigPathsFor(config.cwd)
8032
+ })
7988
8033
  );
7989
8034
  }
7990
8035
  scopeDetail = scope.detail;
@@ -8040,15 +8085,15 @@ function explainPath(config, target) {
8040
8085
  result.bytes = buffer.length;
8041
8086
  result.lines = countLines(text2);
8042
8087
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
8043
- const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative15);
8088
+ const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative16);
8044
8089
  result.secretCount = findings.length;
8045
8090
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
8046
8091
  let inclusionMode = "full";
8047
- if (config.skeleton === true && isSkeletonizable(relative15)) {
8048
- const skeleton = skeletonizeTypeScript(text2, relative15);
8092
+ if (config.skeleton === true && isSkeletonizable(relative16)) {
8093
+ const skeleton = skeletonizeTypeScript(text2, relative16);
8049
8094
  if (skeleton.collapsed > 0) inclusionMode = "signatures";
8050
8095
  }
8051
- if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative15) && stripComments2(text2, relative15).removed > 0) {
8096
+ if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative16) && stripComments2(text2, relative16).removed > 0) {
8052
8097
  inclusionMode = "comments-stripped";
8053
8098
  }
8054
8099
  if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
@@ -8057,18 +8102,18 @@ function explainPath(config, target) {
8057
8102
  }
8058
8103
  result.inclusionMode = inclusionMode;
8059
8104
  }
8060
- result.layer = classifyLayer(relative15, config.layers);
8061
- result.kind = classifyKind(relative15, config.kinds);
8062
- result.language = detectLanguage(relative15);
8063
- const layerRule = findRuleMatch(config.layers, relative15);
8105
+ result.layer = classifyLayer(relative16, config.layers);
8106
+ result.kind = classifyKind(relative16, config.kinds);
8107
+ result.language = detectLanguage(relative16);
8108
+ const layerRule = findRuleMatch(config.layers, relative16);
8064
8109
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
8065
- const kindRule = findRuleMatch(config.kinds, relative15);
8110
+ const kindRule = findRuleMatch(config.kinds, relative16);
8066
8111
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
8067
8112
  const manifest = readManifest2(config);
8068
- const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative15) : void 0;
8113
+ const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative16) : void 0;
8069
8114
  result.part = entry?.part ?? null;
8070
8115
  if (entry === void 0) {
8071
- const record = manifest?.skipped?.find((skip) => skip.path === relative15);
8116
+ const record = manifest?.skipped?.find((skip) => skip.path === relative16);
8072
8117
  if (record !== void 0 && (record.reason === "not-selected" || record.reason === "unchanged")) {
8073
8118
  result.included = false;
8074
8119
  result.reason = record.reason;
@@ -8333,9 +8378,17 @@ function renderConfig(answers) {
8333
8378
  // Replace function and method bodies with \`{ /* ... */ }\` in TypeScript files.
8334
8379
  // Signatures and comments stay, so the structure of the file survives.
8335
8380
  skeleton: ${answers.skeleton},
8381
+ // Remove comment text from JavaScript and TypeScript bodies.
8382
+ stripComments: false,
8383
+ // Drop blank lines from emitted bodies; line numbers in the part move.
8384
+ removeEmptyLines: false,
8336
8385
  // Also write reports/audit.sarif (SARIF 2.1.0) for a CI security gate. The
8337
8386
  // matched value is never included \u2014 only the path, the line and the rule.
8338
8387
  sarif: ${answers.sarif},
8388
+ // Commit lines in reports/log.md when the log artifact is enabled.
8389
+ logCount: 20,
8390
+ // Write one single-file pack: "single", "xml" or "json". null = no pack.
8391
+ pack: null,
8339
8392
  // Snapshot only the files that differ from a git ref (for example "main"),
8340
8393
  // plus untracked ones. null means "snapshot everything"; any other value must
8341
8394
  // be a git ref string, and anything else is a configuration error.
@@ -9009,11 +9062,11 @@ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
9009
9062
  const entries = [];
9010
9063
  for (const directory of [outDir, tmpDir]) {
9011
9064
  if (directory === null) continue;
9012
- const relative15 = path27__namespace.relative(cwd, path27__namespace.resolve(cwd, directory)).replace(/\\/g, "/");
9013
- if (relative15 === "" || relative15 === "." || relative15.startsWith("..") || path27__namespace.isAbsolute(relative15)) {
9065
+ const relative16 = path27__namespace.relative(cwd, path27__namespace.resolve(cwd, directory)).replace(/\\/g, "/");
9066
+ if (relative16 === "" || relative16 === "." || relative16.startsWith("..") || path27__namespace.isAbsolute(relative16)) {
9014
9067
  continue;
9015
9068
  }
9016
- entries.push(`/${relative15}/`);
9069
+ entries.push(`/${relative16}/`);
9017
9070
  }
9018
9071
  return [...new Set(entries)];
9019
9072
  }
@@ -9344,10 +9397,10 @@ async function runInit(options) {
9344
9397
  };
9345
9398
  }
9346
9399
  function describeTarget(cwd) {
9347
- const relative15 = path27__namespace.relative(process.cwd(), cwd);
9348
- if (relative15 === "") return "this directory";
9349
- if (relative15.startsWith("..") || path27__namespace.isAbsolute(relative15)) return cwd;
9350
- return relative15;
9400
+ const relative16 = path27__namespace.relative(process.cwd(), cwd);
9401
+ if (relative16 === "") return "this directory";
9402
+ if (relative16.startsWith("..") || path27__namespace.isAbsolute(relative16)) return cwd;
9403
+ return relative16;
9351
9404
  }
9352
9405
  function firstRunMessage(reason, cwd) {
9353
9406
  const where = describeTarget(cwd);
@@ -10570,12 +10623,27 @@ function runGit(cwd, args) {
10570
10623
  function isGitRepository(cwd) {
10571
10624
  return runGit(cwd, ["rev-parse", "--is-inside-work-tree"]).out.trim() === "true";
10572
10625
  }
10626
+ function diffSectionPaths(body) {
10627
+ const paths = /* @__PURE__ */ new Set();
10628
+ for (const line of body.split("\n")) {
10629
+ const plus = /^\+\+\+ b\/(.*)$/.exec(line);
10630
+ if (plus !== null) paths.add(plus[1]);
10631
+ const minus = /^--- a\/(.*)$/.exec(line);
10632
+ if (minus !== null) paths.add(minus[1]);
10633
+ const header = /^diff --git a\/(.*?) b\/(.*)$/.exec(line);
10634
+ if (header !== null) {
10635
+ paths.add(header[1]);
10636
+ paths.add(header[2]);
10637
+ }
10638
+ }
10639
+ return [...paths];
10640
+ }
10573
10641
  function generateDiffReport(cwd, options = {}) {
10574
10642
  if (!isGitRepository(cwd)) return null;
10575
10643
  const maxBytes = options.maxBytes ?? 200 * 1024;
10576
10644
  const sections = [];
10577
- let bytes = 0;
10578
10645
  let truncated = false;
10646
+ let omittedSensitive = 0;
10579
10647
  const commands = [
10580
10648
  ["Unstaged", ["diff", "--no-color"]],
10581
10649
  ["Staged", ["diff", "--cached", "--no-color"]]
@@ -10583,28 +10651,47 @@ function generateDiffReport(cwd, options = {}) {
10583
10651
  for (const [title, args] of commands) {
10584
10652
  const result = runGit(cwd, args);
10585
10653
  if (!result.ok || result.out.trim() === "") continue;
10586
- const body = result.out;
10587
- bytes += Buffer.byteLength(body, "utf8");
10588
- const used = Buffer.byteLength(sections.join(""), "utf8");
10589
- const remaining = Math.max(0, maxBytes - used);
10590
- const chunk = Buffer.byteLength(body, "utf8") > remaining ? body.slice(0, remaining) : body;
10591
- if (chunk.length < body.length) truncated = true;
10592
- sections.push("## " + title + " changes\n\nRun: git " + args.join(" ") + "\n\n```diff\n" + chunk + "\n```");
10654
+ const rawSections = result.out.split(/(?=^diff --git )/m).filter((section) => section.length > 0);
10655
+ for (const rawSection of rawSections) {
10656
+ const paths2 = diffSectionPaths(rawSection);
10657
+ const blocked = paths2.some((path28) => isSensitivePath(path28) || options.excluded?.(path28) === true);
10658
+ if (blocked) {
10659
+ omittedSensitive += 1;
10660
+ continue;
10661
+ }
10662
+ const used = Buffer.byteLength(sections.join(""), "utf8");
10663
+ const remaining = Math.max(0, maxBytes - used);
10664
+ if (remaining === 0) {
10665
+ truncated = true;
10666
+ break;
10667
+ }
10668
+ const chunk = truncateToBytes(rawSection, remaining);
10669
+ if (chunk.isTruncated) truncated = true;
10670
+ sections.push(
10671
+ "## " + title + " changes\n\nRun: git " + args.join(" ") + "\n\n```diff\n" + chunk.content + "\n```"
10672
+ );
10673
+ if (chunk.isTruncated) break;
10674
+ }
10593
10675
  }
10594
10676
  if (sections.length === 0) return null;
10595
10677
  const paths = /* @__PURE__ */ new Set();
10596
- for (const match of sections.join("\n").matchAll(/^\+\+\+ b\/(.+)$/gm)) paths.add(match[1]);
10597
- const text2 = [
10678
+ for (const section of sections) for (const path28 of diffSectionPaths(section)) paths.add(path28);
10679
+ const joined = [
10598
10680
  "# Uncommitted changes",
10599
10681
  "",
10600
10682
  "Generated from the repository at the moment the snapshot was written. Untracked files are not",
10601
10683
  "in a diff until they are added; this artifact says what git reports, not what git ignores.",
10602
10684
  "",
10685
+ ...omittedSensitive > 0 ? [
10686
+ "> " + omittedSensitive + " file section(s) omitted: their path is credential-bearing or excluded from the snapshot.",
10687
+ ""
10688
+ ] : [],
10603
10689
  ...sections,
10604
10690
  ...truncated ? ["", "> Truncated at " + maxBytes + " bytes. Run git diff for the rest."] : [],
10605
10691
  ""
10606
10692
  ].join("\n");
10607
- return { text: text2, bytes, truncated, paths: [...paths].sort() };
10693
+ const text2 = scanAndRedactSecrets(joined, options.secretRules ?? [], "reports/diff.md").redacted;
10694
+ return { text: text2, bytes: Buffer.byteLength(text2, "utf8"), truncated, paths: [...paths].sort() };
10608
10695
  }
10609
10696
  function generateLogReport(cwd, options = {}) {
10610
10697
  const count = Math.max(1, Math.min(500, options.count ?? 20));
@@ -10618,13 +10705,15 @@ function generateLogReport(cwd, options = {}) {
10618
10705
  const body = (result.stdout ?? "").trim();
10619
10706
  if (body === "") return null;
10620
10707
  const lines = body.split("\n");
10708
+ const redacted = scanAndRedactSecrets(body, options.secretRules ?? [], "reports/log.md").redacted;
10709
+ const joined = truncateToBytes(redacted, maxBytes).content;
10621
10710
  const text2 = [
10622
10711
  "# Recent commits",
10623
10712
  "",
10624
10713
  "The last " + count + " commits, newest first, one line each.",
10625
10714
  "",
10626
10715
  "```text",
10627
- lines.join("\n").slice(0, maxBytes),
10716
+ joined,
10628
10717
  "```",
10629
10718
  ""
10630
10719
  ].join("\n");
@@ -11487,24 +11576,93 @@ function readReleases(cwd) {
11487
11576
  return headings.slice(0, MAX_RELEASES);
11488
11577
  }
11489
11578
  var HOST_PATTERN = /^[a-z0-9.-]+$/i;
11579
+ function parseIPv4(value) {
11580
+ const parts = value.split(".");
11581
+ if (parts.length !== 4) return null;
11582
+ const octets = [];
11583
+ for (const part of parts) {
11584
+ if (!/^\d{1,3}$/.test(part)) return null;
11585
+ const octet = Number(part);
11586
+ if (octet > 255) return null;
11587
+ octets.push(octet);
11588
+ }
11589
+ return octets;
11590
+ }
11591
+ function isPrivateIPv4(octets) {
11592
+ const [a, b] = octets;
11593
+ 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;
11594
+ }
11595
+ function parseIPv6(value) {
11596
+ const withoutZone = value.split("%")[0] ?? value;
11597
+ if (!withoutZone.includes(":")) return null;
11598
+ const halves = withoutZone.split("::");
11599
+ if (halves.length > 2) return null;
11600
+ const left = halves[0] === "" ? [] : halves[0].split(":");
11601
+ const right = halves.length === 2 && halves[1] !== "" ? halves[1].split(":") : [];
11602
+ const groups = [...left, ...right];
11603
+ if (halves.length === 1 && groups.length !== 8) return null;
11604
+ if (halves.length === 2 && groups.length > 7) return null;
11605
+ const expand = (group) => {
11606
+ if (group.includes(".")) {
11607
+ const octets = parseIPv4(group);
11608
+ if (octets === null) return null;
11609
+ return [
11610
+ (octets[0] << 8 | octets[1]).toString(16),
11611
+ (octets[2] << 8 | octets[3]).toString(16)
11612
+ ];
11613
+ }
11614
+ return [group];
11615
+ };
11616
+ const expanded = [];
11617
+ for (const group of groups) {
11618
+ const next = expand(group);
11619
+ if (next === null) return null;
11620
+ expanded.push(...next);
11621
+ }
11622
+ if (halves.length === 1 && expanded.length !== 8) return null;
11623
+ if (halves.length === 2 && expanded.length > 8) return null;
11624
+ const missing = 8 - expanded.length;
11625
+ const full = halves.length === 2 ? [...expanded.slice(0, left.length), ...Array(missing).fill("0"), ...expanded.slice(left.length)] : expanded;
11626
+ if (full.length !== 8) return null;
11627
+ const numbers = [];
11628
+ for (const group of full) {
11629
+ if (!/^[0-9a-f]{1,4}$/i.test(group)) return null;
11630
+ numbers.push(Number.parseInt(group, 16));
11631
+ }
11632
+ return numbers;
11633
+ }
11634
+ function isPrivateIPv6(groups) {
11635
+ const [first, second, third, fourth, fifth, sixth, seventh, eighth] = groups;
11636
+ const allZeroThrough = (count) => groups.slice(0, count).every((group) => group === 0);
11637
+ if (groups.every((group) => group === 0)) return true;
11638
+ if (allZeroThrough(7) && eighth === 1) return true;
11639
+ if ((first & 65024) === 64512) return true;
11640
+ if ((first & 65472) === 65152) return true;
11641
+ if ((first & 65472) === 65216) return true;
11642
+ if ((first & 65280) === 65280) return true;
11643
+ if (first === 8193 && second === 3512) return true;
11644
+ const mapped = (offset) => isPrivateIPv4([
11645
+ groups[offset] >> 8,
11646
+ groups[offset] & 255,
11647
+ groups[offset + 1] >> 8,
11648
+ groups[offset + 1] & 255
11649
+ ]);
11650
+ if (allZeroThrough(5) && sixth === 65535) return mapped(6);
11651
+ if (allZeroThrough(6) && (seventh !== 0 || eighth !== 0)) return mapped(6);
11652
+ if (first === 100 && second === 65435 && third === 0 && fourth === 0 && fifth === 0 && sixth === 0) {
11653
+ return mapped(6);
11654
+ }
11655
+ if (first === 8194) return mapped(1);
11656
+ return false;
11657
+ }
11490
11658
  function isPrivateHost(host) {
11491
- const value = host.toLowerCase().replace(/^\[|\]$/g, "");
11659
+ const value = host.toLowerCase().replace(/^\[|\]$/g, "").split("%")[0] ?? "";
11492
11660
  if (value === "localhost" || value.endsWith(".localhost") || value.endsWith(".local")) return true;
11493
11661
  if (value === "::1" || value === "0.0.0.0" || value === "::") return true;
11494
- if (value.startsWith("fc") || value.startsWith("fd")) return true;
11495
- if (value.startsWith("fe80")) return true;
11496
- const parts = value.split(".");
11497
- if (parts.length === 4 && parts.every((part) => /^\d{1,3}$/.test(part))) {
11498
- const octets = parts.map(Number);
11499
- if (octets.some((octet) => octet > 255)) return true;
11500
- if (octets[0] === 127) return true;
11501
- if (octets[0] === 10) return true;
11502
- if (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) return true;
11503
- if (octets[0] === 192 && octets[1] === 168) return true;
11504
- if (octets[0] === 169 && octets[1] === 254) return true;
11505
- if (octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127) return true;
11506
- if (octets[0] === 0) return true;
11507
- }
11662
+ const ipv4 = parseIPv4(value);
11663
+ if (ipv4 !== null) return isPrivateIPv4(ipv4);
11664
+ const ipv6 = parseIPv6(value);
11665
+ if (ipv6 !== null) return isPrivateIPv6(ipv6);
11508
11666
  return false;
11509
11667
  }
11510
11668
  function parseRemoteSource(input, options = {}) {
@@ -11579,14 +11737,25 @@ async function assertPublicHost(host, allowPrivate) {
11579
11737
  }
11580
11738
  }
11581
11739
  }
11740
+ function tokenHosts() {
11741
+ const configured = process.env.CODEBASE_SNAPSHOT_GITHUB_HOSTS;
11742
+ if (configured === void 0 || configured.trim() === "") return ["github.com"];
11743
+ return configured.split(",").map((entry) => entry.trim().toLowerCase()).filter((entry) => entry.length > 0);
11744
+ }
11745
+ function tokenAllowedForHost(host) {
11746
+ return tokenHosts().includes(host.toLowerCase().replace(/^\[|\]$/g, ""));
11747
+ }
11582
11748
  function gitEnvironment(token, host) {
11583
11749
  const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_LFS_SKIP_SMUDGE: "1" };
11584
11750
  delete env.GIT_ASKPASS;
11585
11751
  delete env.SSH_ASKPASS;
11586
11752
  if (token !== void 0 && token !== null && token !== "") {
11587
- env.GIT_CONFIG_COUNT = "1";
11588
- env.GIT_CONFIG_KEY_0 = "http.https://" + host + "/.extraheader";
11589
- env.GIT_CONFIG_VALUE_0 = "Authorization: Basic " + Buffer.from("x-access-token:" + token).toString("base64");
11753
+ const normalizedHost = host.toLowerCase().replace(/^\[|\]$/g, "");
11754
+ if (tokenAllowedForHost(normalizedHost)) {
11755
+ env.GIT_CONFIG_COUNT = "1";
11756
+ env.GIT_CONFIG_KEY_0 = "http.https://" + normalizedHost + "/.extraheader";
11757
+ env.GIT_CONFIG_VALUE_0 = "Authorization: Basic " + Buffer.from("x-access-token:" + token).toString("base64");
11758
+ }
11590
11759
  }
11591
11760
  return env;
11592
11761
  }
@@ -11596,15 +11765,29 @@ async function cloneRepository(source, options) {
11596
11765
  const dest = path27__namespace.resolve(options.dest);
11597
11766
  fs24__namespace.rmSync(dest, { recursive: true, force: true });
11598
11767
  fs24__namespace.mkdirSync(dest, { recursive: true });
11599
- const args = ["clone", "--depth", "1", "--single-branch", "--no-tags", "--quiet"];
11600
- if (options.ref !== void 0 && options.ref !== null && options.ref !== "") {
11601
- args.push("--branch", options.ref);
11768
+ const ref = options.ref ?? source.ref;
11769
+ const args = [
11770
+ "-c",
11771
+ "http.followRedirects=false",
11772
+ ...source.kind === "https" ? ["-c", "protocol.file.allow=never", "-c", "protocol.ssh.allow=never"] : [],
11773
+ "clone",
11774
+ "--depth",
11775
+ "1",
11776
+ "--single-branch",
11777
+ "--no-tags",
11778
+ "--quiet"
11779
+ ];
11780
+ if (ref !== void 0 && ref !== null && ref !== "") {
11781
+ args.push("--branch", ref);
11602
11782
  }
11603
11783
  args.push(source.url, dest);
11604
- log("clone: " + source.url + (options.ref ? " (" + options.ref + ")" : ""));
11784
+ log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
11605
11785
  const started = Date.now();
11606
11786
  const result = childProcess.spawnSync("git", args, {
11607
- env: gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
11787
+ env: {
11788
+ ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
11789
+ ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
11790
+ },
11608
11791
  timeout: options.timeoutMs ?? 18e4,
11609
11792
  encoding: "utf8",
11610
11793
  windowsHide: true
@@ -11632,7 +11815,7 @@ async function cloneRepository(source, options) {
11632
11815
  host: source.host,
11633
11816
  owner: source.owner,
11634
11817
  repo: source.repo,
11635
- ref: options.ref !== void 0 && options.ref !== null && options.ref !== "" ? options.ref : source.ref,
11818
+ ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
11636
11819
  commit,
11637
11820
  fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
11638
11821
  }
@@ -12000,9 +12183,9 @@ function walk(dir, prefix = "") {
12000
12183
  }
12001
12184
  const files = [];
12002
12185
  for (const entry of entries) {
12003
- const relative15 = prefix === "" ? entry.name : prefix + "/" + entry.name;
12004
- if (entry.isDirectory()) files.push(...walk(path27__namespace.join(dir, entry.name), relative15));
12005
- else if (entry.isFile()) files.push(relative15);
12186
+ const relative16 = prefix === "" ? entry.name : prefix + "/" + entry.name;
12187
+ if (entry.isDirectory()) files.push(...walk(path27__namespace.join(dir, entry.name), relative16));
12188
+ else if (entry.isFile()) files.push(relative16);
12006
12189
  }
12007
12190
  return files;
12008
12191
  }
@@ -12040,13 +12223,14 @@ function secretTokens(text2) {
12040
12223
  }
12041
12224
  return [...tokens];
12042
12225
  }
12043
- function artifactTextContains(snapshotDir, token) {
12044
- for (const relative15 of walk(snapshotDir)) {
12045
- if (!TEXT_ARTIFACT.test(relative15)) continue;
12046
- const text2 = readText2(path27__namespace.join(snapshotDir, relative15));
12047
- if (text2 !== null && text2.includes(token)) return true;
12226
+ function readArtifactTexts(snapshotDir) {
12227
+ const texts = [];
12228
+ for (const relative16 of walk(snapshotDir)) {
12229
+ if (!TEXT_ARTIFACT.test(relative16)) continue;
12230
+ const text2 = readText2(path27__namespace.join(snapshotDir, relative16));
12231
+ if (text2 !== null) texts.push(text2);
12048
12232
  }
12049
- return false;
12233
+ return texts;
12050
12234
  }
12051
12235
  function findHostPaths(snapshotDir, repoDir) {
12052
12236
  const patterns = [
@@ -12059,15 +12243,15 @@ function findHostPaths(snapshotDir, repoDir) {
12059
12243
  ];
12060
12244
  const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
12061
12245
  const hits = /* @__PURE__ */ new Set();
12062
- for (const relative15 of walk(snapshotDir)) {
12063
- if (!TEXT_ARTIFACT.test(relative15)) continue;
12064
- const text2 = readText2(path27__namespace.join(snapshotDir, relative15));
12246
+ for (const relative16 of walk(snapshotDir)) {
12247
+ if (!TEXT_ARTIFACT.test(relative16)) continue;
12248
+ const text2 = readText2(path27__namespace.join(snapshotDir, relative16));
12065
12249
  if (text2 === null) continue;
12066
12250
  for (const pattern of patterns) {
12067
- for (const match of text2.match(pattern) ?? []) hits.add(relative15 + ": " + match);
12251
+ for (const match of text2.match(pattern) ?? []) hits.add(relative16 + ": " + match);
12068
12252
  }
12069
12253
  repoPattern.lastIndex = 0;
12070
- if (repoPattern.test(text2)) hits.add(relative15 + ": the repository absolute path");
12254
+ if (repoPattern.test(text2)) hits.add(relative16 + ": the repository absolute path");
12071
12255
  }
12072
12256
  return [...hits];
12073
12257
  }
@@ -12314,13 +12498,13 @@ function auditSnapshot(options) {
12314
12498
  let artifactCount = 0;
12315
12499
  for (const [key, value] of Object.entries(artifacts)) {
12316
12500
  if (value === null || value === void 0) continue;
12317
- const relative15 = ARTIFACT_FILES[key];
12318
- if (relative15 === void 0) continue;
12501
+ const relative16 = ARTIFACT_FILES[key];
12502
+ if (relative16 === void 0) continue;
12319
12503
  artifactCount += 1;
12320
- const bytes = readBytes(path27__namespace.join(snapshotDir, relative15));
12321
- if (bytes === null) artifactProblems.push(relative15 + " is missing");
12504
+ const bytes = readBytes(path27__namespace.join(snapshotDir, relative16));
12505
+ if (bytes === null) artifactProblems.push(relative16 + " is missing");
12322
12506
  else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
12323
- artifactProblems.push(relative15 + " changed");
12507
+ artifactProblems.push(relative16 + " changed");
12324
12508
  }
12325
12509
  }
12326
12510
  checks.push(
@@ -13050,25 +13234,25 @@ function auditSnapshot(options) {
13050
13234
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
13051
13235
  const leakHits = [];
13052
13236
  let scannedBytes = 0;
13053
- for (const relative15 of walk(snapshotDir)) {
13054
- if (!TEXT_ARTIFACT.test(relative15) || scannedBytes > scanBudget) continue;
13055
- if (relative15 === SIGNATURE_FILE) continue;
13056
- const text2 = readText2(path27__namespace.join(snapshotDir, relative15));
13237
+ for (const relative16 of walk(snapshotDir)) {
13238
+ if (!TEXT_ARTIFACT.test(relative16) || scannedBytes > scanBudget) continue;
13239
+ if (relative16 === SIGNATURE_FILE) continue;
13240
+ const text2 = readText2(path27__namespace.join(snapshotDir, relative16));
13057
13241
  if (text2 === null) continue;
13058
13242
  scannedBytes += Buffer.byteLength(text2, "utf8");
13059
13243
  let findingCount = 0;
13060
- if (/^parts[\\/].*\.md$/i.test(relative15)) {
13244
+ if (/^parts[\\/].*\.md$/i.test(relative16)) {
13061
13245
  let headerText = text2;
13062
13246
  for (const section of parsePartSections(text2)) {
13063
13247
  findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
13064
13248
  headerText = headerText.replace(section.body, "");
13065
13249
  }
13066
- findingCount += scanAndRedactSecrets(headerText, rules, relative15).findings.length;
13250
+ findingCount += scanAndRedactSecrets(headerText, rules, relative16).findings.length;
13067
13251
  } else {
13068
- findingCount = scanAndRedactSecrets(text2, rules, relative15).findings.length;
13252
+ findingCount = scanAndRedactSecrets(text2, rules, relative16).findings.length;
13069
13253
  }
13070
13254
  if (findingCount > 0) {
13071
- leakHits.push(relative15 + " (" + findingCount + " line(s))");
13255
+ leakHits.push(relative16 + " (" + findingCount + " line(s))");
13072
13256
  }
13073
13257
  }
13074
13258
  const signatureRecordPath = path27__namespace.join(snapshotDir, SIGNATURE_FILE);
@@ -13113,13 +13297,15 @@ function auditSnapshot(options) {
13113
13297
  );
13114
13298
  const leakedFrom = [];
13115
13299
  let compared = 0;
13300
+ const artifactTexts = readArtifactTexts(snapshotDir);
13301
+ const artifactContains = (token) => artifactTexts.some((text2) => text2.includes(token));
13116
13302
  for (const record of skippedSensitive.slice(0, 40)) {
13117
13303
  if (record.path.includes("[REDACTED") || compared > 400) continue;
13118
13304
  const text2 = readText2(path27__namespace.join(repoDir, record.path));
13119
13305
  if (text2 === null) continue;
13120
13306
  for (const token of secretTokens(text2)) {
13121
13307
  compared += 1;
13122
- if (artifactTextContains(snapshotDir, token)) leakedFrom.push(record.path);
13308
+ if (artifactContains(token)) leakedFrom.push(record.path);
13123
13309
  }
13124
13310
  }
13125
13311
  checks.push(
@@ -13280,6 +13466,7 @@ const { parentPort, workerData } = require("node:worker_threads");
13280
13466
  const manifest = mod.generateSnapshot(config, {
13281
13467
  dryRun: workerData.dryRun === true,
13282
13468
  ...(workerData.narrow ?? {}),
13469
+ ...(workerData.runId === undefined ? {} : { runId: workerData.runId }),
13283
13470
  });
13284
13471
  const skipCounts = new Map();
13285
13472
  for (const record of manifest.skipped) {
@@ -13325,8 +13512,13 @@ function generateInWorker(cwd, cliOptions, options = {}) {
13325
13512
  const finish = (result) => {
13326
13513
  if (settled) return;
13327
13514
  settled = true;
13328
- if (worker !== null) void worker.terminate();
13329
- resolve15(result);
13515
+ const terminated = worker === null ? Promise.resolve(void 0) : worker.terminate();
13516
+ void terminated.catch(() => void 0).then(() => {
13517
+ if (!result.ok && options.runId !== void 0 && options.lockRoots !== void 0) {
13518
+ releaseAbandonedRun(options.lockRoots, options.runId);
13519
+ }
13520
+ resolve15(result);
13521
+ });
13330
13522
  };
13331
13523
  const isCjs = typeof __dirname !== "undefined";
13332
13524
  const directory = isCjs ? __dirname : path27__namespace.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href))));
@@ -13338,7 +13530,8 @@ function generateInWorker(cwd, cliOptions, options = {}) {
13338
13530
  cwd,
13339
13531
  cliOptions,
13340
13532
  dryRun: options.dryRun === true,
13341
- narrow: options.narrow ?? {}
13533
+ narrow: options.narrow ?? {},
13534
+ ...options.runId === void 0 ? {} : { runId: options.runId }
13342
13535
  }
13343
13536
  });
13344
13537
  } catch (error) {
@@ -13503,7 +13696,16 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
13503
13696
  if (overrides.withDependents === true) cliOptions.withDependents = true;
13504
13697
  try {
13505
13698
  const config = resolveConfig(loaded.config, cliOptions, root);
13506
- return { ok: true, workspace: { root, config, configFile: loaded.file, cliOptions } };
13699
+ return {
13700
+ ok: true,
13701
+ workspace: {
13702
+ root,
13703
+ config,
13704
+ configFile: loaded.file,
13705
+ sourceConfig: loaded.config ?? null,
13706
+ cliOptions
13707
+ }
13708
+ };
13507
13709
  } catch (error) {
13508
13710
  return { ok: false, message: error instanceof Error ? error.message : String(error) };
13509
13711
  }
@@ -13517,8 +13719,8 @@ function partPathFor(workspace, filename) {
13517
13719
  if (filename.length === 0 || filename.includes("\0")) return null;
13518
13720
  const partsDir = path27__namespace.resolve(workspace.root, workspace.config.outDir, "parts");
13519
13721
  const resolved = path27__namespace.resolve(partsDir, filename);
13520
- const relative15 = path27__namespace.relative(partsDir, resolved);
13521
- if (relative15.length === 0 || relative15.includes(path27__namespace.sep) || relative15.includes("/") || relative15.includes("\\") || path27__namespace.isAbsolute(relative15)) {
13722
+ const relative16 = path27__namespace.relative(partsDir, resolved);
13723
+ if (relative16.length === 0 || relative16.includes(path27__namespace.sep) || relative16.includes("/") || relative16.includes("\\") || path27__namespace.isAbsolute(relative16)) {
13522
13724
  return null;
13523
13725
  }
13524
13726
  let stats;
@@ -13692,11 +13894,11 @@ function toRelativePath(root, value) {
13692
13894
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
13693
13895
  const resolvedRoot = path27__namespace.resolve(root);
13694
13896
  const absolute = path27__namespace.resolve(resolvedRoot, cleaned);
13695
- const relative15 = path27__namespace.relative(resolvedRoot, absolute);
13696
- if (relative15 === "" || relative15 === ".." || relative15.startsWith(`..${path27__namespace.sep}`) || path27__namespace.isAbsolute(relative15)) {
13897
+ const relative16 = path27__namespace.relative(resolvedRoot, absolute);
13898
+ if (relative16 === "" || relative16 === ".." || relative16.startsWith(`..${path27__namespace.sep}`) || path27__namespace.isAbsolute(relative16)) {
13697
13899
  return null;
13698
13900
  }
13699
- return relative15.split(path27__namespace.sep).join("/");
13901
+ return relative16.split(path27__namespace.sep).join("/");
13700
13902
  }
13701
13903
  function symbolsOf(entry) {
13702
13904
  const summary = entry.summary;
@@ -13910,7 +14112,9 @@ var testsTool = {
13910
14112
  const cap = Math.max(1, typeof args.maxFiles === "number" ? args.maxFiles : 50);
13911
14113
  const isTest2 = (filePath) => /(^|\/)(tests?|__tests__|spec)\//.test(filePath) || /\.(test|spec)\.[a-z0-9]+$/i.test(filePath);
13912
14114
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath, file]));
13913
- const resolver = buildImportResolver(read.manifest.files, {});
14115
+ const resolver = buildImportResolver(read.manifest.files, {
14116
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
14117
+ });
13914
14118
  const testFiles = read.manifest.files.filter((file) => isTest2(file.relativePath));
13915
14119
  const importsOf = (filePath) => {
13916
14120
  const entry = read.manifest.indexes.imports.byFile.find((candidate) => candidate.path === filePath);
@@ -13958,9 +14162,13 @@ var workspaceTool = {
13958
14162
  },
13959
14163
  annotations: READ_ONLY,
13960
14164
  async handler(args, context) {
13961
- const root = path27__namespace.resolve(context.cwd, typeof args.root === "string" ? args.root : ".");
13962
- const outDir = typeof args.outDir === "string" ? args.outDir : "snapshot";
13963
- const index = path27__namespace.resolve(root, outDir, "WORKSPACE.json");
14165
+ const prepared = await prepare(args, context, outDirOverride(args));
14166
+ if (!prepared.ok) return prepared.outcome;
14167
+ const index = path27__namespace.resolve(
14168
+ prepared.workspace.root,
14169
+ prepared.workspace.config.outDir,
14170
+ "WORKSPACE.json"
14171
+ );
13964
14172
  let text2;
13965
14173
  try {
13966
14174
  text2 = fs24__namespace.readFileSync(index, "utf8");
@@ -14017,7 +14225,9 @@ var neighborsTool = {
14017
14225
  const file = read.manifest.files.find((candidate) => candidate.relativePath === wanted) ?? read.manifest.files.find((candidate) => candidate.relativePath.toLowerCase() === wanted.toLowerCase());
14018
14226
  if (file === void 0) return { text: wanted + " is not in the snapshot; snapshot_explain says why.", isError: true };
14019
14227
  const byPath = new Map(read.manifest.files.map((candidate) => [candidate.relativePath, candidate]));
14020
- const resolver = buildImportResolver(read.manifest.files, {});
14228
+ const resolver = buildImportResolver(read.manifest.files, {
14229
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
14230
+ });
14021
14231
  const entry = read.manifest.indexes.imports.byFile.find((candidate) => candidate.path === file.relativePath);
14022
14232
  const imports = [];
14023
14233
  for (const specifier of entry?.imports ?? []) {
@@ -14159,7 +14369,9 @@ var cyclesTool = {
14159
14369
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
14160
14370
  const cap = Math.max(1, typeof args.maxComponents === "number" ? args.maxComponents : 20);
14161
14371
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath, file]));
14162
- const resolver = buildImportResolver(read.manifest.files, {});
14372
+ const resolver = buildImportResolver(read.manifest.files, {
14373
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
14374
+ });
14163
14375
  const edges = /* @__PURE__ */ new Map();
14164
14376
  for (const path28 of byPath.keys()) edges.set(path28, []);
14165
14377
  for (const entry of read.manifest.indexes.imports.byFile) {
@@ -15359,10 +15571,17 @@ var generateTool = {
15359
15571
  ...typeof args.slice === "string" ? { slice: { question: args.slice, ...typeof args.sliceTokens === "number" ? { maxTokens: args.sliceTokens } : {} } } : {},
15360
15572
  ...typeof args.budgetTokens === "number" ? { budgetTokens: args.budgetTokens } : {}
15361
15573
  };
15574
+ let lockRoots;
15575
+ try {
15576
+ const safe = resolveSafeOutputDirs(workspace.config);
15577
+ lockRoots = [safe.outDir, safe.tmpDir];
15578
+ } catch (error) {
15579
+ return failure(error instanceof Error ? error.message : String(error));
15580
+ }
15362
15581
  const result = await generateInWorker(
15363
15582
  workspace.root,
15364
15583
  { ...workspace.cliOptions, ...reportOptions },
15365
- { signal: controller.signal, narrow }
15584
+ { signal: controller.signal, narrow, runId: crypto.randomUUID(), lockRoots }
15366
15585
  );
15367
15586
  if (!result.ok) return failure(result.message);
15368
15587
  context.notify?.({ message: "writing the snapshot", progress: 2, total: 2 });
@@ -15396,16 +15615,42 @@ var generateTool = {
15396
15615
  };
15397
15616
  function configAsGenerated(workspace, manifest) {
15398
15617
  const recorded = manifest.config;
15618
+ const cli = workspace.cliOptions;
15619
+ const source = workspace.sourceConfig;
15620
+ const configured = (key) => source !== null && Object.prototype.hasOwnProperty.call(source, key);
15621
+ const sourceArtifacts = source !== null && source.artifacts !== null && typeof source.artifacts === "object" ? source.artifacts : null;
15622
+ const artifacts = { ...workspace.config.artifacts };
15623
+ if (recorded?.artifacts !== void 0) {
15624
+ for (const [key, value] of Object.entries(recorded.artifacts)) {
15625
+ if (sourceArtifacts === null || !Object.prototype.hasOwnProperty.call(sourceArtifacts, key)) {
15626
+ artifacts[key] = value;
15627
+ }
15628
+ }
15629
+ }
15630
+ let artifactOverride = recorded?.artifacts !== void 0;
15631
+ if (cli.includeDiffs === true) {
15632
+ artifacts.diff = true;
15633
+ artifactOverride = true;
15634
+ }
15635
+ if (cli.includeLogs !== void 0) {
15636
+ artifacts.log = true;
15637
+ artifactOverride = true;
15638
+ }
15639
+ if (cli.tokenTree === true) {
15640
+ artifacts.tokenTree = true;
15641
+ artifactOverride = true;
15642
+ }
15643
+ const choose = (key, recordedValue, current, cliValue) => cliValue !== void 0 ? cliValue : configured(key) ? current : recordedValue ?? current;
15399
15644
  return {
15400
15645
  ...workspace.config,
15401
- ...recorded?.artifacts === void 0 ? {} : { artifacts: recorded.artifacts },
15402
- ...recorded?.stripComments === void 0 ? {} : { stripComments: recorded.stripComments },
15403
- ...recorded?.removeEmptyLines === void 0 ? {} : { removeEmptyLines: recorded.removeEmptyLines },
15404
- ...recorded?.pack === void 0 ? {} : { pack: recorded.pack },
15405
- ...recorded?.logCount === void 0 ? {} : { logCount: recorded.logCount },
15406
- ...recorded?.skeleton === void 0 ? {} : { skeleton: recorded.skeleton },
15407
- ...recorded?.sarif === void 0 ? {} : { sarif: recorded.sarif },
15408
- ...recorded?.maxParts === void 0 ? {} : { maxParts: recorded.maxParts }
15646
+ ...artifactOverride ? { artifacts } : {},
15647
+ ...cli.stripComments === true || configured("stripComments") || recorded?.stripComments !== void 0 ? { stripComments: choose("stripComments", recorded?.stripComments, workspace.config.stripComments, cli.stripComments === true ? true : void 0) } : {},
15648
+ ...cli.removeEmptyLines === true || configured("removeEmptyLines") || recorded?.removeEmptyLines !== void 0 ? { removeEmptyLines: choose("removeEmptyLines", recorded?.removeEmptyLines, workspace.config.removeEmptyLines, cli.removeEmptyLines === true ? true : void 0) } : {},
15649
+ ...cli.pack !== void 0 || configured("pack") || recorded?.pack !== void 0 ? { pack: choose("pack", recorded?.pack ?? void 0, workspace.config.pack, cli.pack) } : {},
15650
+ ...cli.includeLogs !== void 0 || configured("logCount") || recorded?.logCount !== void 0 ? { logCount: choose("logCount", recorded?.logCount, workspace.config.logCount, cli.includeLogs) } : {},
15651
+ ...cli.skeleton === true || configured("skeleton") || recorded?.skeleton !== void 0 ? { skeleton: choose("skeleton", recorded?.skeleton, workspace.config.skeleton, cli.skeleton === true ? true : void 0) } : {},
15652
+ ...cli.sarif === true || configured("sarif") || recorded?.sarif !== void 0 ? { sarif: choose("sarif", recorded?.sarif, workspace.config.sarif, cli.sarif === true ? true : void 0) } : {},
15653
+ ...configured("maxParts") || recorded?.maxParts !== void 0 ? { maxParts: choose("maxParts", recorded?.maxParts, workspace.config.maxParts) } : {}
15409
15654
  };
15410
15655
  }
15411
15656
  var validateTool = {
@@ -15642,7 +15887,9 @@ var dependentsTool = {
15642
15887
  }
15643
15888
  const direction = args.direction === "imports" || args.direction === "imported-by" ? String(args.direction) : "both";
15644
15889
  const limit = typeof args.limit === "number" && args.limit > 0 ? Math.floor(args.limit) : 50;
15645
- const resolver = buildImportResolver(manifest.files);
15890
+ const resolver = buildImportResolver(manifest.files, {
15891
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
15892
+ });
15646
15893
  const imports = [];
15647
15894
  const unresolved = [];
15648
15895
  if (direction !== "imported-by") {
@@ -17120,6 +17367,10 @@ function buildAgentContract() {
17120
17367
  { key: "maxPartBytes", type: "number | string", default: 307200, summary: "Per-part byte budget." },
17121
17368
  { key: "maxPartTokens", type: "number | string | null", default: null, summary: "Per-part token ceiling; narrows maxPartBytes. Minimum 1024." },
17122
17369
  { key: "skeleton", type: "boolean", default: false, summary: "Collapse function bodies to `{ /* ... */ }` in TS, JS, TSX and JSX files." },
17370
+ { key: "stripComments", type: "boolean", default: false, summary: "Remove comment text from JS/TS bodies." },
17371
+ { key: "removeEmptyLines", type: "boolean", default: false, summary: "Drop blank lines from emitted bodies; the part's line numbers move, and files[] records emptyLinesRemoved." },
17372
+ { key: "pack", type: '"single" | "xml" | "json" | null', default: null, summary: "Write one single-file pack in this format." },
17373
+ { key: "logCount", type: "number", default: 20, summary: "Commit lines in reports/log.md (also set by --include-logs <n>)." },
17123
17374
  { key: "sarif", type: "boolean", default: false, summary: "Also write reports/audit.sarif." },
17124
17375
  { key: "changedSince", type: "string | null", default: null, summary: "Snapshot only files that differ from this git ref." },
17125
17376
  { key: "staged", type: "boolean", default: false, summary: "Snapshot only files staged in the index." },
@@ -18291,9 +18542,9 @@ function dosDateTime(date) {
18291
18542
  function walkFiles(root, prefix = "") {
18292
18543
  const files = [];
18293
18544
  for (const entry of fs24__namespace.readdirSync(path27__namespace.join(root, prefix), { withFileTypes: true })) {
18294
- const relative15 = prefix === "" ? entry.name : prefix + "/" + entry.name;
18295
- if (entry.isDirectory()) files.push(...walkFiles(root, relative15));
18296
- else if (entry.isFile()) files.push(relative15);
18545
+ const relative16 = prefix === "" ? entry.name : prefix + "/" + entry.name;
18546
+ if (entry.isDirectory()) files.push(...walkFiles(root, relative16));
18547
+ else if (entry.isFile()) files.push(relative16);
18297
18548
  }
18298
18549
  return files;
18299
18550
  }
@@ -18301,11 +18552,11 @@ function writeZip(options) {
18301
18552
  const entries = [...options.entries ?? []];
18302
18553
  if (options.directory !== void 0) {
18303
18554
  const root = options.directory;
18304
- for (const relative15 of walkFiles(root)) {
18305
- if (options.skip !== void 0 && options.skip(relative15)) continue;
18306
- const full = path27__namespace.join(root, relative15);
18555
+ for (const relative16 of walkFiles(root)) {
18556
+ if (options.skip !== void 0 && options.skip(relative16)) continue;
18557
+ const full = path27__namespace.join(root, relative16);
18307
18558
  const stat = fs24__namespace.statSync(full);
18308
- entries.push({ name: relative15, content: fs24__namespace.readFileSync(full), mtime: stat.mtime });
18559
+ entries.push({ name: relative16, content: fs24__namespace.readFileSync(full), mtime: stat.mtime });
18309
18560
  }
18310
18561
  }
18311
18562
  if (entries.length > 65535) {
@@ -18498,8 +18749,13 @@ var SERVE_PAGE = `<!doctype html>
18498
18749
  $("counts").textContent = info.included + " included / " + info.skipped + " skipped";
18499
18750
  $("files").innerHTML = "";
18500
18751
  for (const file of info.files.slice(0, 400)) {
18752
+ // A manifest is untrusted input. Interpolating file.part (or a path) into innerHTML let a
18753
+ // crafted manifest run script in the serve origin and read the token from localStorage.
18501
18754
  const li = document.createElement("li");
18502
- li.innerHTML = "<b>" + file.path.replace(/[<>&]/g, "") + "</b> " + file.part;
18755
+ const name = document.createElement("b");
18756
+ name.textContent = file.path;
18757
+ li.appendChild(name);
18758
+ li.appendChild(document.createTextNode(" " + file.part));
18503
18759
  $("files").appendChild(li);
18504
18760
  }
18505
18761
  }
@@ -18536,16 +18792,55 @@ async function startWebServer(options) {
18536
18792
  if (token === null && !["127.0.0.1", "localhost", "::1"].includes(host)) {
18537
18793
  throw new Error("Refusing to serve " + host + " without a token.");
18538
18794
  }
18539
- const mcp = createServer({ cwd: options.cwd, log });
18795
+ const createMcp = () => createServer({ cwd: options.cwd, log });
18796
+ const mcpPerSocket = /* @__PURE__ */ new WeakMap();
18797
+ const mcpFor = (socket) => {
18798
+ let server2 = mcpPerSocket.get(socket);
18799
+ if (server2 === void 0) {
18800
+ server2 = createMcp();
18801
+ mcpPerSocket.set(socket, server2);
18802
+ }
18803
+ return server2;
18804
+ };
18540
18805
  const temporaryClones = /* @__PURE__ */ new Set();
18541
18806
  const allowedRoots = [path27__namespace.resolve(options.cwd)];
18807
+ const canonical = (candidate) => {
18808
+ try {
18809
+ return fs24__namespace.realpathSync(candidate);
18810
+ } catch {
18811
+ return null;
18812
+ }
18813
+ };
18814
+ const inside = (resolved) => allowedRoots.some((root) => {
18815
+ const canonicalRoot = canonical(root);
18816
+ if (canonicalRoot === null) return false;
18817
+ const relative16 = path27__namespace.relative(canonicalRoot, resolved);
18818
+ return relative16 === "" || !relative16.startsWith(`..${path27__namespace.sep}`) && relative16 !== ".." && !path27__namespace.isAbsolute(relative16);
18819
+ });
18542
18820
  const insideAllowedRoots = (candidate) => {
18821
+ const resolved = canonical(candidate);
18822
+ return resolved === null ? false : inside(resolved);
18823
+ };
18824
+ const lexicallyInside = (candidate) => {
18543
18825
  const resolved = path27__namespace.resolve(candidate);
18544
18826
  return allowedRoots.some((root) => {
18545
- const prefix = root.endsWith(path27__namespace.sep) ? root : root + path27__namespace.sep;
18546
- return resolved === root || resolved.startsWith(prefix);
18827
+ const prefix = path27__namespace.resolve(root) + path27__namespace.sep;
18828
+ return resolved === path27__namespace.resolve(root) || resolved.startsWith(prefix);
18547
18829
  });
18548
18830
  };
18831
+ const insideAllowedRootsForWrite = (candidate) => {
18832
+ let existing = path27__namespace.resolve(candidate);
18833
+ const tail = [];
18834
+ while (!fs24__namespace.existsSync(existing)) {
18835
+ tail.unshift(path27__namespace.basename(existing));
18836
+ const parent = path27__namespace.dirname(existing);
18837
+ if (parent === existing) break;
18838
+ existing = parent;
18839
+ }
18840
+ const resolved = canonical(existing);
18841
+ if (resolved === null) return false;
18842
+ return inside(tail.length === 0 ? resolved : path27__namespace.join(resolved, ...tail));
18843
+ };
18549
18844
  const authorized = (request) => {
18550
18845
  if (token === null) return true;
18551
18846
  const header = request.headers.authorization ?? "";
@@ -18569,7 +18864,10 @@ async function startWebServer(options) {
18569
18864
  cors["access-control-allow-headers"] = "authorization, content-type";
18570
18865
  cors["access-control-allow-methods"] = "GET, POST, OPTIONS";
18571
18866
  }
18867
+ let responseSent = false;
18572
18868
  const send = (status, body, extra = {}) => {
18869
+ if (responseSent) return;
18870
+ responseSent = true;
18573
18871
  const text2 = typeof body === "string" ? body : JSON.stringify(body);
18574
18872
  response.writeHead(status, {
18575
18873
  ...cors,
@@ -18600,10 +18898,13 @@ async function startWebServer(options) {
18600
18898
  const url = new URL(request.url ?? "/", "http://localhost");
18601
18899
  if (request.method === "POST" && (request.url === "/mcp" || (request.url ?? "").startsWith("/mcp?"))) {
18602
18900
  let received = 0;
18901
+ let tooLarge = false;
18603
18902
  const chunks = [];
18604
18903
  request.on("data", (chunk) => {
18904
+ if (tooLarge) return;
18605
18905
  received += chunk.length;
18606
18906
  if (received > 2 * 1024 * 1024) {
18907
+ tooLarge = true;
18607
18908
  request.destroy();
18608
18909
  send(413, { error: "request body too large" });
18609
18910
  return;
@@ -18611,6 +18912,7 @@ async function startWebServer(options) {
18611
18912
  chunks.push(chunk);
18612
18913
  });
18613
18914
  request.on("end", () => {
18915
+ if (tooLarge) return;
18614
18916
  void (async () => {
18615
18917
  let message;
18616
18918
  try {
@@ -18620,9 +18922,14 @@ async function startWebServer(options) {
18620
18922
  return;
18621
18923
  }
18622
18924
  const batch = Array.isArray(message) ? message : [message];
18925
+ if (batch.length > 100) {
18926
+ send(400, { error: "JSON-RPC batch is limited to 100 messages" });
18927
+ return;
18928
+ }
18929
+ const server2 = mcpFor(request.socket);
18623
18930
  const answers = [];
18624
18931
  for (const item of batch) {
18625
- const answer = await mcp.handle(item);
18932
+ const answer = await server2.handle(item);
18626
18933
  if (answer !== null) answers.push(answer);
18627
18934
  }
18628
18935
  if (answers.length === 0) send(202, "");
@@ -18633,10 +18940,13 @@ async function startWebServer(options) {
18633
18940
  }
18634
18941
  if (request.method === "POST" && request.url === "/api/generate") {
18635
18942
  let received = 0;
18943
+ let tooLarge = false;
18636
18944
  const chunks = [];
18637
18945
  request.on("data", (chunk) => {
18946
+ if (tooLarge) return;
18638
18947
  received += chunk.length;
18639
18948
  if (received > MAX_BODY) {
18949
+ tooLarge = true;
18640
18950
  request.destroy();
18641
18951
  send(413, { error: "request body too large" });
18642
18952
  return;
@@ -18644,6 +18954,7 @@ async function startWebServer(options) {
18644
18954
  chunks.push(chunk);
18645
18955
  });
18646
18956
  request.on("end", () => {
18957
+ if (tooLarge) return;
18647
18958
  void (async () => {
18648
18959
  let source = "";
18649
18960
  let mode = "full";
@@ -18700,6 +19011,10 @@ async function startWebServer(options) {
18700
19011
  }
18701
19012
  } else {
18702
19013
  target = path27__namespace.resolve(options.cwd, source);
19014
+ if (!insideAllowedRoots(target)) {
19015
+ send(403, { error: "outside the served directory: " + target });
19016
+ return;
19017
+ }
18703
19018
  }
18704
19019
  let stat;
18705
19020
  try {
@@ -18717,15 +19032,26 @@ async function startWebServer(options) {
18717
19032
  send(400, { error: loaded.errors.join("; ") });
18718
19033
  return;
18719
19034
  }
19035
+ const runConfig = isRemote ? {
19036
+ ...loaded.config ?? {},
19037
+ outDir: "snapshot",
19038
+ tmpDir: "snapshot.tmp",
19039
+ hooks: {}
19040
+ } : loaded.config ?? {};
19041
+ const configuredOutDir = typeof runConfig.outDir === "string" && runConfig.outDir.trim() !== "" ? runConfig.outDir : "snapshot";
19042
+ const snapshotDir = path27__namespace.resolve(target, configuredOutDir);
19043
+ if (!insideAllowedRootsForWrite(snapshotDir)) {
19044
+ send(403, { error: "the configured outDir resolves outside the served directory" });
19045
+ return;
19046
+ }
18720
19047
  const started = Date.now();
18721
19048
  try {
18722
- const manifest = generateSnapshot({ ...loaded.config ?? {}, cwd: target }, {
19049
+ const manifest = generateSnapshot({ ...runConfig, cwd: target }, {
18723
19050
  ...provenance === void 0 ? {} : { source: provenance },
18724
19051
  ...mode === "slice" ? { slice: { question } } : {},
18725
19052
  ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
18726
19053
  });
18727
19054
  const seconds = ((Date.now() - started) / 1e3).toFixed(2);
18728
- const snapshotDir = path27__namespace.join(target, "snapshot");
18729
19055
  const health = auditSnapshot({ snapshotDir, repoDir: target });
18730
19056
  send(200, {
18731
19057
  path: snapshotDir,
@@ -18753,7 +19079,7 @@ async function startWebServer(options) {
18753
19079
  }
18754
19080
  if (request.method === "GET" && request.url?.startsWith("/api/health?") === true) {
18755
19081
  const target = path27__namespace.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
18756
- if (!insideAllowedRoots(target)) {
19082
+ if (!lexicallyInside(target)) {
18757
19083
  send(403, { error: "outside the served directory: " + target });
18758
19084
  return;
18759
19085
  }
@@ -18761,12 +19087,24 @@ async function startWebServer(options) {
18761
19087
  send(404, { error: "no manifest.json under " + target });
18762
19088
  return;
18763
19089
  }
19090
+ if (!insideAllowedRoots(target)) {
19091
+ send(403, { error: "outside the served directory: " + target });
19092
+ return;
19093
+ }
18764
19094
  const report2 = auditSnapshot({ snapshotDir: target, repoDir: path27__namespace.dirname(target) });
18765
19095
  send(200, { score: report2.score, counts: report2.counts, checks: report2.checks });
18766
19096
  return;
18767
19097
  }
18768
19098
  if (request.method === "GET" && (request.url?.startsWith("/api/snapshot?") === true || request.url === "/api/snapshot")) {
18769
19099
  const target = path27__namespace.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
19100
+ if (!lexicallyInside(target)) {
19101
+ send(403, { error: "outside the served directory: " + target });
19102
+ return;
19103
+ }
19104
+ if (!fs24__namespace.existsSync(path27__namespace.join(target, "manifest.json"))) {
19105
+ send(404, { error: "no manifest.json under " + target });
19106
+ return;
19107
+ }
18770
19108
  if (!insideAllowedRoots(target)) {
18771
19109
  send(403, { error: "outside the served directory: " + target });
18772
19110
  return;
@@ -18779,6 +19117,11 @@ async function startWebServer(options) {
18779
19117
  send(404, { error: "no manifest.json under " + target });
18780
19118
  return;
18781
19119
  }
19120
+ const shapeProblem = describeManifestShapeProblem(manifest);
19121
+ if (shapeProblem !== null) {
19122
+ send(400, { error: "manifest.json is not a snapshot manifest: " + shapeProblem });
19123
+ return;
19124
+ }
18782
19125
  let prompt = "";
18783
19126
  try {
18784
19127
  prompt = fs24__namespace.readFileSync(path27__namespace.join(target, "PROMPT.md"), "utf8").slice(0, MAX_PREVIEW);
@@ -18798,7 +19141,7 @@ async function startWebServer(options) {
18798
19141
  }
18799
19142
  if (request.method === "GET" && request.url?.startsWith("/api/snapshot.zip") === true) {
18800
19143
  const target = path27__namespace.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
18801
- if (!insideAllowedRoots(target)) {
19144
+ if (!lexicallyInside(target)) {
18802
19145
  send(403, { error: "outside the served directory: " + target });
18803
19146
  return;
18804
19147
  }
@@ -18806,6 +19149,10 @@ async function startWebServer(options) {
18806
19149
  send(404, { error: "not a snapshot directory: " + target });
18807
19150
  return;
18808
19151
  }
19152
+ if (!insideAllowedRoots(target)) {
19153
+ send(403, { error: "outside the served directory: " + target });
19154
+ return;
19155
+ }
18809
19156
  try {
18810
19157
  const zip = writeZip({ directory: target });
18811
19158
  response.writeHead(200, {
@@ -19115,8 +19462,8 @@ function gitDirectory(cwd) {
19115
19462
  }
19116
19463
  }
19117
19464
  function isInside3(parent, child) {
19118
- const relative15 = path27__namespace.relative(parent, child);
19119
- return relative15 === "" || !relative15.startsWith("..") && !path27__namespace.isAbsolute(relative15);
19465
+ const relative16 = path27__namespace.relative(parent, child);
19466
+ return relative16 === "" || !relative16.startsWith("..") && !path27__namespace.isAbsolute(relative16);
19120
19467
  }
19121
19468
  function isRegisteredWorktree(gitDir, cwd) {
19122
19469
  try {
@@ -19568,7 +19915,7 @@ function maskPathText(value, secretRules) {
19568
19915
  }
19569
19916
  function maskOwnerBrief(brief, secretRules) {
19570
19917
  if (brief === void 0) return void 0;
19571
- const mask = (value) => maskPathText(value, secretRules);
19918
+ const mask = (value) => scanAndRedactSecrets(value, secretRules ?? [], "owner-brief").redacted;
19572
19919
  return {
19573
19920
  ...brief,
19574
19921
  path: mask(brief.path),
@@ -19614,9 +19961,9 @@ function listEntries(dir) {
19614
19961
  return;
19615
19962
  }
19616
19963
  for (const child of children) {
19617
- const relative15 = prefix === "" ? child.name : `${prefix}/${child.name}`;
19618
- entries.push(relative15);
19619
- if (child.isDirectory()) walk2(path27__namespace.join(absolute, child.name), relative15);
19964
+ const relative16 = prefix === "" ? child.name : `${prefix}/${child.name}`;
19965
+ entries.push(relative16);
19966
+ if (child.isDirectory()) walk2(path27__namespace.join(absolute, child.name), relative16);
19620
19967
  }
19621
19968
  };
19622
19969
  walk2(dir, "");
@@ -19651,7 +19998,7 @@ function markerInventory(dir, written) {
19651
19998
  }
19652
19999
  return { entries, files };
19653
20000
  }
19654
- function markerPayload(dir, state, id, createdAt, written) {
20001
+ function markerPayload(dir, state, id, createdAt, written, runId) {
19655
20002
  const { entries, files } = markerInventory(dir, written);
19656
20003
  const marker2 = {
19657
20004
  generator: GENERATOR_NAME,
@@ -19660,6 +20007,7 @@ function markerPayload(dir, state, id, createdAt, written) {
19660
20007
  createdAt,
19661
20008
  state,
19662
20009
  id,
20010
+ ...runId === void 0 ? {} : { runId },
19663
20011
  pid: process.pid,
19664
20012
  entries,
19665
20013
  files
@@ -19757,6 +20105,7 @@ function readOwnershipMarker(dir) {
19757
20105
  createdAt: typeof candidate.createdAt === "string" ? candidate.createdAt : "unknown",
19758
20106
  state: candidate.state,
19759
20107
  id: candidate.id,
20108
+ runId: typeof candidate.runId === "string" ? candidate.runId : void 0,
19760
20109
  pid: typeof candidate.pid === "number" ? candidate.pid : void 0,
19761
20110
  manifestSha256: typeof candidate.manifestSha256 === "string" ? candidate.manifestSha256 : void 0,
19762
20111
  entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0,
@@ -19915,13 +20264,19 @@ function assessSnapshotDirectory(dir) {
19915
20264
  };
19916
20265
  }
19917
20266
  const entries = listEntries(dir);
19918
- const foreignEntries = entries.filter(
20267
+ let foreignEntries = entries.filter(
19919
20268
  (entry) => !recorded.has(entry) && !isIgnorableEntry(entry)
19920
20269
  );
20270
+ const legacySignatureOnly = foreignEntries.length === 1 && foreignEntries[0] === SIGNATURE_FILE && verifySnapshotSignature(dir).ok;
20271
+ if (legacySignatureOnly) foreignEntries = [];
19921
20272
  if (foreignEntries.length > 0) {
19922
20273
  return { owned: false, problem: null, foreignEntries, marker: marker2 };
19923
20274
  }
19924
- const inventoryProblem = marker2.files === void 0 ? null : verifyMarkerInventory(dir, entries, marker2.files);
20275
+ const inventoryProblem = marker2.files === void 0 ? null : verifyMarkerInventory(
20276
+ dir,
20277
+ legacySignatureOnly ? entries.filter((entry) => entry !== SIGNATURE_FILE) : entries,
20278
+ marker2.files
20279
+ );
19925
20280
  return {
19926
20281
  owned: inventoryProblem === null,
19927
20282
  problem: inventoryProblem,
@@ -20099,13 +20454,13 @@ function startLockHeartbeat(lockPath) {
20099
20454
  return () => void 0;
20100
20455
  }
20101
20456
  }
20102
- function acquireRunLock(stagingRoot) {
20457
+ function acquireRunLock(stagingRoot, runId) {
20103
20458
  const lockPath = lockPathFor(stagingRoot);
20104
20459
  const payload = `${JSON.stringify({
20105
20460
  pid: process.pid,
20106
20461
  stagingRoot,
20107
20462
  host: os2__namespace.hostname(),
20108
- runId: crypto__namespace.randomUUID(),
20463
+ runId,
20109
20464
  heartbeatMs: LOCK_HEARTBEAT_MS,
20110
20465
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
20111
20466
  })}
@@ -20159,6 +20514,33 @@ function canonicalLockTarget(targetPath2) {
20159
20514
  function lockPathFor(stagingRoot) {
20160
20515
  return path27__namespace.join(os2__namespace.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
20161
20516
  }
20517
+ function releaseAbandonedRun(stagingRoots, runId) {
20518
+ if (runId.length === 0) return;
20519
+ for (const root of new Set(stagingRoots)) {
20520
+ const lockPath = lockPathFor(root);
20521
+ try {
20522
+ const payload = JSON.parse(fs24__namespace.readFileSync(lockPath, "utf8"));
20523
+ if (payload.runId === runId) fs24__namespace.rmSync(lockPath, { force: true });
20524
+ } catch {
20525
+ }
20526
+ let entries;
20527
+ try {
20528
+ entries = fs24__namespace.readdirSync(root);
20529
+ } catch {
20530
+ continue;
20531
+ }
20532
+ for (const name of entries) {
20533
+ if (!name.startsWith(RUN_DIR_PREFIX)) continue;
20534
+ const directory = path27__namespace.join(root, name);
20535
+ const { marker: marker2 } = readOwnershipMarker(directory);
20536
+ if (marker2?.runId !== runId) continue;
20537
+ try {
20538
+ fs24__namespace.rmSync(directory, { recursive: true, force: true });
20539
+ } catch {
20540
+ }
20541
+ }
20542
+ }
20543
+ }
20162
20544
  function lockHeartbeatAgeMs(lockPath) {
20163
20545
  try {
20164
20546
  return Date.now() - fs24__namespace.statSync(lockPath).mtimeMs;
@@ -20473,6 +20855,7 @@ function generateSnapshot(configInput, options) {
20473
20855
  assertUsableConfigInput(configInput);
20474
20856
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
20475
20857
  const dryRun = options?.dryRun ?? false;
20858
+ const runId = options?.runId ?? crypto__namespace.randomUUID();
20476
20859
  const gitInfo = getGitInfo(config.cwd, config.branch);
20477
20860
  const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
20478
20861
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
@@ -20492,7 +20875,7 @@ function generateSnapshot(configInput, options) {
20492
20875
  // output — but only at these exact paths, not at every directory that shares the name.
20493
20876
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
20494
20877
  (directory) => path27__namespace.relative(config.cwd, path27__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
20495
- ).filter((relative15) => relative15.length > 0 && !relative15.startsWith("..")),
20878
+ ).filter((relative16) => relative16.length > 0 && !relative16.startsWith("..")),
20496
20879
  // A staged path can be absent from the working tree while its index blob exists. Discovery
20497
20880
  // lists the working tree, so those paths would never reach the scan at all.
20498
20881
  ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
@@ -21179,9 +21562,13 @@ function generateSnapshot(configInput, options) {
21179
21562
  if (navigationText !== null) manifest.artifacts.navigation = artifactRecord(navigationText);
21180
21563
  const auditText = artifacts.audit ? generateAuditReport(manifest, secretFindings, config.secretRules) : null;
21181
21564
  if (auditText !== null) manifest.artifacts.audit = artifactRecord(auditText);
21182
- const diffReport = artifacts.diff ? generateDiffReport(config.cwd) : null;
21565
+ const reportExcludes = [...config.excludePatterns, ...config.presetExclude];
21566
+ const diffReport = artifacts.diff ? generateDiffReport(config.cwd, {
21567
+ secretRules: config.secretRules,
21568
+ excluded: (relativePath) => reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
21569
+ }) : null;
21183
21570
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
21184
- const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount }) : null;
21571
+ const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount, secretRules: config.secretRules }) : null;
21185
21572
  if (artifacts.diff && diffReport === null && !isGitRepository(config.cwd)) {
21186
21573
  manifest.warnings.push(
21187
21574
  "--include-diffs was requested, but the generated directory is not a git repository; reports/diff.md was not written."
@@ -21225,7 +21612,8 @@ function generateSnapshot(configInput, options) {
21225
21612
  const entry = {
21226
21613
  ...file,
21227
21614
  content,
21228
- inclusionMode: "full",
21615
+ inclusionMode: file.inclusionMode === "comments-stripped" ? "comments-stripped" : "full",
21616
+ ...file.emptyLinesRemoved === true ? { emptyLinesRemoved: true } : {},
21229
21617
  isPreviewTruncated: false,
21230
21618
  includedBytes: Buffer.byteLength(content, "utf8"),
21231
21619
  includedLines: countLines(content)
@@ -21293,7 +21681,7 @@ function generateSnapshot(configInput, options) {
21293
21681
  const lockKeys = Array.from(/* @__PURE__ */ new Set([tmpDir, outDir])).sort();
21294
21682
  const releases = [];
21295
21683
  try {
21296
- for (const key of lockKeys) releases.push(acquireRunLock(key));
21684
+ for (const key of lockKeys) releases.push(acquireRunLock(key, runId));
21297
21685
  } catch (error) {
21298
21686
  for (const release of [...releases].reverse()) release();
21299
21687
  throw error;
@@ -21320,6 +21708,7 @@ function generateSnapshot(configInput, options) {
21320
21708
  createdAt,
21321
21709
  state: "staging",
21322
21710
  id: snapshotId,
21711
+ runId,
21323
21712
  pid: process.pid
21324
21713
  });
21325
21714
  const partsDir = path27__namespace.join(stagingDir, "parts");
@@ -21388,6 +21777,17 @@ function generateSnapshot(configInput, options) {
21388
21777
  if (artifacts.manifest) {
21389
21778
  writeArtifact(stagingDir, "manifest.json", JSON.stringify(manifest, null, 2));
21390
21779
  }
21780
+ if (options?.sign !== void 0) {
21781
+ if (!artifacts.manifest) {
21782
+ throw new Error(
21783
+ "Refusing to sign: manifest.json is disabled for this run. Signing covers the manifest, so enable the manifest artifact or drop --sign."
21784
+ );
21785
+ }
21786
+ const record = signManifest(path27__namespace.join(stagingDir, "manifest.json"), {
21787
+ key: options.sign.key ?? null
21788
+ });
21789
+ writeArtifact(stagingDir, SIGNATURE_FILE, JSON.stringify(record, null, 2) + "\n");
21790
+ }
21391
21791
  if (monolithJson !== null) {
21392
21792
  writeArtifact(stagingDir, "full-codebase.json", monolithJson);
21393
21793
  }
@@ -21399,7 +21799,7 @@ function generateSnapshot(configInput, options) {
21399
21799
  }
21400
21800
  writeOwnershipMarker(
21401
21801
  stagingDir,
21402
- markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts)
21802
+ markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21403
21803
  );
21404
21804
  swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
21405
21805
  stagingDir = null;
@@ -21410,10 +21810,16 @@ function generateSnapshot(configInput, options) {
21410
21810
  if (artifacts.manifest && manifest.warnings.length !== warningsBeforeHook) {
21411
21811
  writeManifestAtomically(path27__namespace.join(outDir, "manifest.json"), manifest);
21412
21812
  recordArtifact(outDir, "manifest.json");
21813
+ if (options?.sign !== void 0) {
21814
+ const record = signManifest(path27__namespace.join(outDir, "manifest.json"), {
21815
+ key: options.sign.key ?? null
21816
+ });
21817
+ writeArtifact(outDir, SIGNATURE_FILE, JSON.stringify(record, null, 2) + "\n");
21818
+ }
21413
21819
  }
21414
21820
  writeOwnershipMarker(
21415
21821
  outDir,
21416
- markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts)
21822
+ markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21417
21823
  );
21418
21824
  };
21419
21825
  if (config.hooks.afterGenerate) shipHookState();
@@ -21585,8 +21991,43 @@ async function startHttpTransport(options) {
21585
21991
  "Refusing to serve " + host + " without a token: a repository reachable from the network must require Authorization. Drop --no-auth, or bind the loopback address."
21586
21992
  );
21587
21993
  }
21588
- const server = createServer({ cwd: options.cwd, log });
21994
+ const createMcp = () => createServer({ cwd: options.cwd, log });
21589
21995
  const toolCount = buildTools().length;
21996
+ const mcpSessions = /* @__PURE__ */ new Map();
21997
+ const socketServers = /* @__PURE__ */ new WeakMap();
21998
+ const anonymousServers = /* @__PURE__ */ new Map();
21999
+ const serverFor = (request) => {
22000
+ const header = request.headers["mcp-session-id"];
22001
+ const supplied = typeof header === "string" ? header.trim() : "";
22002
+ if (supplied !== "") {
22003
+ let existing = mcpSessions.get(supplied);
22004
+ if (existing === void 0) {
22005
+ existing = createMcp();
22006
+ if (mcpSessions.size >= 64) {
22007
+ const oldest = mcpSessions.keys().next().value;
22008
+ if (oldest !== void 0) mcpSessions.delete(oldest);
22009
+ }
22010
+ mcpSessions.set(supplied, existing);
22011
+ }
22012
+ return existing;
22013
+ }
22014
+ const onSocket = socketServers.get(request.socket);
22015
+ if (onSocket !== void 0) return onSocket;
22016
+ const userAgent = typeof request.headers["user-agent"] === "string" ? request.headers["user-agent"] : "";
22017
+ const fallbackKey = (request.socket.remoteAddress ?? "unknown") + "\0" + userAgent;
22018
+ let fallback = anonymousServers.get(fallbackKey);
22019
+ if (fallback === void 0) {
22020
+ fallback = createMcp();
22021
+ if (anonymousServers.size >= 64) {
22022
+ const oldest = anonymousServers.keys().next().value;
22023
+ if (oldest !== void 0) anonymousServers.delete(oldest);
22024
+ }
22025
+ anonymousServers.set(fallbackKey, fallback);
22026
+ }
22027
+ socketServers.set(request.socket, fallback);
22028
+ return fallback;
22029
+ };
22030
+ const newSessionId = () => crypto__namespace.randomBytes(12).toString("hex");
21590
22031
  const sseSessions = /* @__PURE__ */ new Map();
21591
22032
  const tokenAccepted = (request, url) => {
21592
22033
  if (token === null) return true;
@@ -21607,6 +22048,18 @@ async function startHttpTransport(options) {
21607
22048
  const method = request.method ?? "UNKNOWN";
21608
22049
  metrics.byMethod.set(method, (metrics.byMethod.get(method) ?? 0) + 1);
21609
22050
  };
22051
+ const rateLimited = (request) => {
22052
+ const remote = request.socket.remoteAddress ?? "unknown";
22053
+ const now = Date.now();
22054
+ const window = sessions.get(remote);
22055
+ if (window === void 0 || window.resetAt <= now) {
22056
+ sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
22057
+ return false;
22058
+ }
22059
+ if (window.count >= RATE_LIMIT) return true;
22060
+ window.count += 1;
22061
+ return false;
22062
+ };
21610
22063
  const allowedOrigin = (origin) => {
21611
22064
  if (origin === void 0) return null;
21612
22065
  if (isLoopbackOrigin(origin)) return origin;
@@ -21614,7 +22067,10 @@ async function startHttpTransport(options) {
21614
22067
  };
21615
22068
  const httpServer = http__namespace.createServer((request, response) => {
21616
22069
  noteRequest(request);
22070
+ let responseSent = false;
21617
22071
  const send = (status, body, extra = {}) => {
22072
+ if (responseSent) return;
22073
+ responseSent = true;
21618
22074
  const text2 = typeof body === "string" ? body : JSON.stringify(body);
21619
22075
  if (status >= 400 && status < 500 && status !== 429) metrics.refused += 1;
21620
22076
  response.writeHead(status, {
@@ -21690,6 +22146,11 @@ async function startHttpTransport(options) {
21690
22146
  send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
21691
22147
  return;
21692
22148
  }
22149
+ if (rateLimited(request)) {
22150
+ metrics.rateLimited += 1;
22151
+ send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
22152
+ return;
22153
+ }
21693
22154
  const id = crypto__namespace.randomBytes(12).toString("hex");
21694
22155
  response.writeHead(200, {
21695
22156
  ...cors,
@@ -21701,7 +22162,7 @@ async function startHttpTransport(options) {
21701
22162
  const write = (payload) => {
21702
22163
  response.write(payload);
21703
22164
  };
21704
- sseSessions.set(id, { write, end: () => response.end() });
22165
+ sseSessions.set(id, { write, end: () => response.end(), server: createMcp() });
21705
22166
  const heartbeat = setInterval(() => write(": ping\n\n"), 15e3);
21706
22167
  const cleanup = () => {
21707
22168
  clearInterval(heartbeat);
@@ -21717,6 +22178,11 @@ async function startHttpTransport(options) {
21717
22178
  send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
21718
22179
  return;
21719
22180
  }
22181
+ if (rateLimited(request)) {
22182
+ metrics.rateLimited += 1;
22183
+ send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
22184
+ return;
22185
+ }
21720
22186
  const id = url.searchParams.get("sessionId") ?? "";
21721
22187
  const stream = sseSessions.get(id);
21722
22188
  if (stream === void 0) {
@@ -21725,9 +22191,12 @@ async function startHttpTransport(options) {
21725
22191
  }
21726
22192
  const chunks2 = [];
21727
22193
  let received2 = 0;
22194
+ let tooLarge2 = false;
21728
22195
  request.on("data", (chunk) => {
22196
+ if (tooLarge2) return;
21729
22197
  received2 += chunk.length;
21730
22198
  if (received2 > maxBody) {
22199
+ tooLarge2 = true;
21731
22200
  request.destroy();
21732
22201
  send(413, { error: "request body too large", limit: maxBody });
21733
22202
  return;
@@ -21735,6 +22204,7 @@ async function startHttpTransport(options) {
21735
22204
  chunks2.push(chunk);
21736
22205
  });
21737
22206
  request.on("end", () => {
22207
+ if (tooLarge2) return;
21738
22208
  void (async () => {
21739
22209
  let message;
21740
22210
  try {
@@ -21743,7 +22213,7 @@ async function startHttpTransport(options) {
21743
22213
  send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: String(error) } });
21744
22214
  return;
21745
22215
  }
21746
- const answer = await server.handle(message);
22216
+ const answer = await stream.server.handle(message);
21747
22217
  if (answer !== null) stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
21748
22218
  send(202, "", cors);
21749
22219
  })();
@@ -21770,20 +22240,22 @@ async function startHttpTransport(options) {
21770
22240
  return;
21771
22241
  }
21772
22242
  }
21773
- const remote = request.socket.remoteAddress ?? "unknown";
21774
- const now = Date.now();
21775
- const window = sessions.get(remote);
21776
- if (window === void 0 || window.resetAt <= now) sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
21777
- else if (window.count >= RATE_LIMIT) {
22243
+ if (rateLimited(request)) {
21778
22244
  metrics.rateLimited += 1;
21779
22245
  send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
21780
22246
  return;
21781
- } else window.count += 1;
22247
+ }
22248
+ const activeServer = serverFor(request);
22249
+ const sessionHeader = request.headers["mcp-session-id"];
22250
+ let sessionId = typeof sessionHeader === "string" ? sessionHeader.trim() : "";
21782
22251
  let received = 0;
22252
+ let tooLarge = false;
21783
22253
  const chunks = [];
21784
22254
  request.on("data", (chunk) => {
22255
+ if (tooLarge) return;
21785
22256
  received += chunk.length;
21786
22257
  if (received > maxBody) {
22258
+ tooLarge = true;
21787
22259
  request.destroy();
21788
22260
  send(413, { error: "request body too large", limit: maxBody }, cors);
21789
22261
  return;
@@ -21791,6 +22263,7 @@ async function startHttpTransport(options) {
21791
22263
  chunks.push(chunk);
21792
22264
  });
21793
22265
  request.on("end", () => {
22266
+ if (tooLarge) return;
21794
22267
  void (async () => {
21795
22268
  let message;
21796
22269
  try {
@@ -21799,17 +22272,26 @@ async function startHttpTransport(options) {
21799
22272
  send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error: " + error.message } }, cors);
21800
22273
  return;
21801
22274
  }
21802
- const answers = [];
21803
22275
  const batch = Array.isArray(message) ? message : [message];
22276
+ if (batch.length > 100) {
22277
+ send(400, { error: "JSON-RPC batch is limited to 100 messages" }, cors);
22278
+ return;
22279
+ }
22280
+ if (sessionId === "" && !Array.isArray(message) && message.method === "initialize") {
22281
+ sessionId = newSessionId();
22282
+ mcpSessions.set(sessionId, activeServer);
22283
+ }
22284
+ const sessionHeaders = sessionId === "" ? cors : { ...cors, "mcp-session-id": sessionId };
22285
+ const answers = [];
21804
22286
  for (const item of batch) {
21805
- const answer = await server.handle(item);
22287
+ const answer = await activeServer.handle(item);
21806
22288
  if (answer !== null) answers.push(answer);
21807
22289
  }
21808
22290
  if (answers.length === 0) {
21809
- send(202, "", cors);
22291
+ send(202, "", sessionHeaders);
21810
22292
  return;
21811
22293
  }
21812
- send(200, Array.isArray(message) ? answers : answers[0], cors);
22294
+ send(200, Array.isArray(message) ? answers : answers[0], sessionHeaders);
21813
22295
  })().catch((error) => {
21814
22296
  log("mcp/http: " + error.message);
21815
22297
  send(500, { jsonrpc: "2.0", id: null, error: { code: -32603, message: "Internal error" } }, cors);
@@ -22451,8 +22933,8 @@ function splitList(value) {
22451
22933
  }
22452
22934
  function displayOutPath(cwd, outDir, ...segments) {
22453
22935
  const absolute = path27__namespace.resolve(cwd, outDir, ...segments);
22454
- const relative15 = path27__namespace.relative(cwd, absolute);
22455
- if (relative15 && !relative15.startsWith("..") && !path27__namespace.isAbsolute(relative15)) return relative15;
22936
+ const relative16 = path27__namespace.relative(cwd, absolute);
22937
+ if (relative16 && !relative16.startsWith("..") && !path27__namespace.isAbsolute(relative16)) return relative16;
22456
22938
  return absolute;
22457
22939
  }
22458
22940
  function nextStepHint(cwd, scriptsAddedNow) {
@@ -22968,6 +23450,42 @@ ${formatUpdateNotice(notice, installKind())}
22968
23450
  }
22969
23451
  return code;
22970
23452
  }
23453
+ function generateCliOptions(invocation) {
23454
+ return {
23455
+ mode: invocation.command,
23456
+ format: invocation.format,
23457
+ dryRun: invocation.dryRun,
23458
+ cwd: invocation.cwd,
23459
+ outDir: invocation.outDir,
23460
+ includeMonolith: invocation.includeMonolith,
23461
+ includeSensitiveFiles: invocation.includeSensitiveFiles,
23462
+ maxPartBytes: invocation.maxPartBytes,
23463
+ maxPartTokens: invocation.maxPartTokens,
23464
+ largeFileBytes: invocation.largeFileBytes,
23465
+ maxMonolithBytes: invocation.maxMonolithBytes,
23466
+ attachmentSlots: invocation.attachmentSlots,
23467
+ maxParts: invocation.maxParts,
23468
+ ...invocation.includeDiffs === true ? { includeDiffs: true } : {},
23469
+ ...invocation.includeLogs === void 0 ? {} : { includeLogs: invocation.includeLogs },
23470
+ ...invocation.tokenTree === true ? { tokenTree: true } : {},
23471
+ ...invocation.stripComments === true ? { stripComments: true } : {},
23472
+ ...invocation.removeEmptyLines === true ? { removeEmptyLines: true } : {},
23473
+ ...invocation.only === void 0 ? {} : { only: invocation.only },
23474
+ ...invocation.ignore === void 0 ? {} : { ignore: invocation.ignore },
23475
+ ...invocation.pack === void 0 ? {} : { pack: invocation.pack },
23476
+ ...invocation.sign === true ? { sign: true } : {},
23477
+ brief: invocation.brief,
23478
+ promptTask: invocation.promptTask,
23479
+ skipArtifacts: invocation.skipArtifacts,
23480
+ onlyArtifacts: invocation.onlyArtifacts,
23481
+ discovery: invocation.discovery,
23482
+ changedSince: invocation.changedSince,
23483
+ staged: invocation.staged,
23484
+ withDependents: invocation.withDependents,
23485
+ skeleton: invocation.skeleton,
23486
+ sarif: invocation.sarif
23487
+ };
23488
+ }
22971
23489
  async function runCommand(argv) {
22972
23490
  let invocation;
22973
23491
  try {
@@ -23121,42 +23639,7 @@ ${USAGE}
23121
23639
  try {
23122
23640
  resolved = resolveConfig(
23123
23641
  loaded.config,
23124
- {
23125
- mode: invocation.command,
23126
- format: invocation.format,
23127
- dryRun: invocation.dryRun,
23128
- cwd: invocation.cwd,
23129
- outDir: invocation.outDir,
23130
- includeMonolith: invocation.includeMonolith,
23131
- includeSensitiveFiles: invocation.includeSensitiveFiles,
23132
- maxPartBytes: invocation.maxPartBytes,
23133
- maxPartTokens: invocation.maxPartTokens,
23134
- largeFileBytes: invocation.largeFileBytes,
23135
- maxMonolithBytes: invocation.maxMonolithBytes,
23136
- attachmentSlots: invocation.attachmentSlots,
23137
- maxParts: invocation.maxParts,
23138
- ...invocation.includeDiffs === true ? { includeDiffs: true } : {},
23139
- ...invocation.includeLogs === void 0 ? {} : { includeLogs: invocation.includeLogs },
23140
- ...invocation.tokenTree === true ? { tokenTree: true } : {},
23141
- ...invocation.stripComments === true ? { stripComments: true } : {},
23142
- ...invocation.removeEmptyLines === true ? { removeEmptyLines: true } : {},
23143
- ...invocation.only === void 0 ? {} : { only: invocation.only },
23144
- ...invocation.ignore === void 0 ? {} : { ignore: invocation.ignore },
23145
- ...invocation.pack === void 0 ? {} : { pack: invocation.pack },
23146
- brief: invocation.brief,
23147
- promptTask: invocation.promptTask,
23148
- skipArtifacts: invocation.skipArtifacts,
23149
- // `--only-artifacts` is forwarded as itself, not only as the derived suppression list:
23150
- // suppression cannot switch an artifact *on*, so a config that had turned one of the
23151
- // requested artifacts off left the run with nothing to write.
23152
- onlyArtifacts: invocation.onlyArtifacts,
23153
- discovery: invocation.discovery,
23154
- changedSince: invocation.changedSince,
23155
- staged: invocation.staged,
23156
- withDependents: invocation.withDependents,
23157
- skeleton: invocation.skeleton,
23158
- sarif: invocation.sarif
23159
- },
23642
+ generateCliOptions(invocation),
23160
23643
  invocation.cwd
23161
23644
  );
23162
23645
  } catch (err) {
@@ -23192,7 +23675,11 @@ ${USAGE}
23192
23675
  rows.push({ name, score: 0, counts: { pass: 0, warn: 0, fail: 1 }, failed: [], error: "no snapshot at " + snapshotDir2 });
23193
23676
  continue;
23194
23677
  }
23195
- const report3 = auditSnapshot({ snapshotDir: snapshotDir2, repoDir });
23678
+ const report3 = auditSnapshot({
23679
+ snapshotDir: snapshotDir2,
23680
+ repoDir,
23681
+ ...invocation.deep === true ? { deep: true } : {}
23682
+ });
23196
23683
  rows.push({
23197
23684
  name,
23198
23685
  score: report3.score,
@@ -23334,6 +23821,12 @@ ${USAGE}
23334
23821
  if (invocation.watch) {
23335
23822
  const problem = watchSupportProblem();
23336
23823
  if (problem !== null) return fail(invocation.format, problem);
23824
+ if (invocation.delta !== void 0) {
23825
+ return fail(
23826
+ invocation.format,
23827
+ "--watch cannot track a fixed --delta base; run a one-shot generate --delta, or watch without it."
23828
+ );
23829
+ }
23337
23830
  }
23338
23831
  if (invocation.workspace !== void 0) {
23339
23832
  const members = invocation.workspace.split(",").map((member) => member.trim()).filter((member) => member.length > 0);
@@ -23459,16 +23952,18 @@ ${USAGE}
23459
23952
  question: invocation.slice,
23460
23953
  ...invocation.sliceTokens === void 0 ? {} : { maxTokens: invocation.sliceTokens }
23461
23954
  }
23462
- }
23955
+ },
23956
+ ...invocation.sign === true && !invocation.dryRun ? { sign: { key: loadSigningKey() } } : {}
23463
23957
  });
23464
23958
  if (invocation.sign === true && !invocation.dryRun) {
23465
- const manifestPath = path27__namespace.resolve(resolved.cwd, resolved.outDir, "manifest.json");
23959
+ const signaturePath = path27__namespace.resolve(resolved.cwd, resolved.outDir, SIGNATURE_FILE);
23466
23960
  try {
23467
- const record = signManifest(manifestPath, { key: loadSigningKey() });
23468
- writeSignature(path27__namespace.dirname(manifestPath), record);
23469
- info(" Signature: ed25519, " + record.keyOrigin + " key, " + record.fingerprint.slice(0, 12));
23961
+ const record = JSON.parse(fs24__namespace.readFileSync(signaturePath, "utf8"));
23962
+ info(
23963
+ " Signature: ed25519, " + (record.keyOrigin ?? "unknown") + " key, " + (record.fingerprint ?? manifest.fingerprint).slice(0, 12)
23964
+ );
23470
23965
  } catch (error) {
23471
- return fail(invocation.format, "Signing failed: " + error.message);
23966
+ return fail(invocation.format, "The snapshot was written but its signature could not be read: " + error.message);
23472
23967
  }
23473
23968
  }
23474
23969
  const elapsed = ((performance.now() - started) / 1e3).toFixed(2);
@@ -23620,8 +24115,8 @@ function comparablePath(value) {
23620
24115
  return process.platform === "win32" ? absolute.toLowerCase() : absolute;
23621
24116
  }
23622
24117
  function isSameOrInside(parent, candidate) {
23623
- const relative15 = path27__namespace.relative(parent, candidate);
23624
- return relative15 === "" || relative15 !== ".." && !relative15.startsWith(`..${path27__namespace.sep}`) && !path27__namespace.isAbsolute(relative15);
24118
+ const relative16 = path27__namespace.relative(parent, candidate);
24119
+ return relative16 === "" || relative16 !== ".." && !relative16.startsWith(`..${path27__namespace.sep}`) && !path27__namespace.isAbsolute(relative16);
23625
24120
  }
23626
24121
  function isGeneratedWatchPath(candidate, paths) {
23627
24122
  const absolute = comparablePath(path27__namespace.resolve(paths.cwd, candidate));
@@ -23696,34 +24191,20 @@ async function runWatchLoop(invocation, resolved, options) {
23696
24191
  for (const warning of loaded.warnings) warn(`\u26A0 Config: ${warning}`);
23697
24192
  const next = resolveConfig(
23698
24193
  loaded.config,
23699
- {
23700
- mode: invocation.command,
23701
- format: invocation.format,
23702
- dryRun: invocation.dryRun,
23703
- cwd: invocation.cwd,
23704
- outDir: invocation.outDir,
23705
- includeMonolith: invocation.includeMonolith,
23706
- includeSensitiveFiles: invocation.includeSensitiveFiles,
23707
- maxPartBytes: invocation.maxPartBytes,
23708
- maxPartTokens: invocation.maxPartTokens,
23709
- largeFileBytes: invocation.largeFileBytes,
23710
- maxMonolithBytes: invocation.maxMonolithBytes,
23711
- attachmentSlots: invocation.attachmentSlots,
23712
- maxParts: invocation.maxParts,
23713
- brief: invocation.brief,
23714
- promptTask: invocation.promptTask,
23715
- skipArtifacts: invocation.skipArtifacts,
23716
- onlyArtifacts: invocation.onlyArtifacts,
23717
- discovery: invocation.discovery,
23718
- changedSince: invocation.changedSince,
23719
- staged: invocation.staged,
23720
- withDependents: invocation.withDependents,
23721
- skeleton: invocation.skeleton,
23722
- sarif: invocation.sarif
23723
- },
24194
+ generateCliOptions(invocation),
23724
24195
  invocation.cwd
23725
24196
  );
23726
- const manifest = generateSnapshot(next, { dryRun: invocation.dryRun });
24197
+ const manifest = generateSnapshot(next, {
24198
+ dryRun: invocation.dryRun,
24199
+ ...invocation.budgetTokens === void 0 ? {} : { budgetTokens: invocation.budgetTokens },
24200
+ ...invocation.slice === void 0 ? {} : {
24201
+ slice: {
24202
+ question: invocation.slice,
24203
+ ...invocation.sliceTokens === void 0 ? {} : { maxTokens: invocation.sliceTokens }
24204
+ }
24205
+ },
24206
+ ...invocation.sign === true && !invocation.dryRun ? { sign: { key: loadSigningKey() } } : {}
24207
+ });
23727
24208
  paths = watchPathsFor(next);
23728
24209
  const elapsed = ((performance.now() - started) / 1e3).toFixed(2);
23729
24210
  info(
@@ -23807,6 +24288,7 @@ exports.buildAgentContract = buildAgentContract;
23807
24288
  exports.cleanInstallEnv = cleanInstallEnv;
23808
24289
  exports.decideWatchEvent = decideWatchEvent;
23809
24290
  exports.finishWatchRun = finishWatchRun;
24291
+ exports.generateCliOptions = generateCliOptions;
23810
24292
  exports.initialWatchState = initialWatchState;
23811
24293
  exports.isGeneratedWatchPath = isGeneratedWatchPath;
23812
24294
  exports.main = main;