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/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var crypto2 = require('crypto');
3
+ var crypto = require('crypto');
4
4
  var worker_threads = require('worker_threads');
5
5
  var async_hooks = require('async_hooks');
6
6
  var fs24 = require('fs');
@@ -36,7 +36,7 @@ function _interopNamespace(e) {
36
36
  return Object.freeze(n);
37
37
  }
38
38
 
39
- var crypto2__namespace = /*#__PURE__*/_interopNamespace(crypto2);
39
+ var crypto__namespace = /*#__PURE__*/_interopNamespace(crypto);
40
40
  var fs24__namespace = /*#__PURE__*/_interopNamespace(fs24);
41
41
  var os2__namespace = /*#__PURE__*/_interopNamespace(os2);
42
42
  var path25__namespace = /*#__PURE__*/_interopNamespace(path25);
@@ -639,9 +639,9 @@ var rubyProfile = {
639
639
  eachLine(content, (line) => {
640
640
  const trimmed = line.trim();
641
641
  if (!trimmed || trimmed.startsWith("#")) return;
642
- const relative13 = REQUIRE_RELATIVE.exec(trimmed);
643
- if (relative13) {
644
- summary.imports.push(`./${relative13[1]}`);
642
+ const relative14 = REQUIRE_RELATIVE.exec(trimmed);
643
+ if (relative14) {
644
+ summary.imports.push(`./${relative14[1]}`);
645
645
  return;
646
646
  }
647
647
  const required = REQUIRE.exec(trimmed);
@@ -1827,7 +1827,7 @@ function parseOwnerBrief(filePath, text2) {
1827
1827
  return {
1828
1828
  brief: {
1829
1829
  path: filePath,
1830
- digest: crypto2.createHash("sha256").update(text2, "utf8").digest("hex"),
1830
+ digest: crypto.createHash("sha256").update(text2, "utf8").digest("hex"),
1831
1831
  ...recognised["Stakes"] ? { stakes: recognised["Stakes"] } : {},
1832
1832
  ...recognised["The system"] ? { system: recognised["The system"] } : {},
1833
1833
  ...recognised["What came before"] ? { history: recognised["What came before"] } : {},
@@ -1988,8 +1988,8 @@ function workspacePackageDirs(cwd, patterns) {
1988
1988
  function scanWorkspacePackages(cwd, patterns) {
1989
1989
  const files = /* @__PURE__ */ new Set();
1990
1990
  const dependencies = /* @__PURE__ */ new Set();
1991
- for (const relative13 of workspacePackageDirs(cwd, patterns)) {
1992
- const full = path25__namespace.join(cwd, relative13);
1991
+ for (const relative14 of workspacePackageDirs(cwd, patterns)) {
1992
+ const full = path25__namespace.join(cwd, relative14);
1993
1993
  try {
1994
1994
  for (const entry of fs24__namespace.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
1995
1995
  } catch {
@@ -4017,10 +4017,63 @@ function applySpansKeepingQuotes(line, spans) {
4017
4017
  out += line.slice(cursor);
4018
4018
  return out;
4019
4019
  }
4020
+ var SIGNATURE_FILE = "signature.json";
4021
+ function signManifest(manifestPath, options = {}) {
4022
+ const bytes = fs24__namespace.readFileSync(manifestPath);
4023
+ const manifest = JSON.parse(bytes.toString("utf8"));
4024
+ if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
4025
+ throw new Error("refusing to sign: the manifest has no valid fingerprint");
4026
+ }
4027
+ const configured = options.key ?? null;
4028
+ const key = configured ?? crypto__namespace.generateKeyPairSync("ed25519").privateKey;
4029
+ const publicKey = crypto__namespace.createPublicKey(key).export({ type: "spki", format: "der" }).toString("base64");
4030
+ const signature = crypto__namespace.sign(null, bytes, key).toString("base64");
4031
+ return {
4032
+ algorithm: "ed25519",
4033
+ signedAt: options.signedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
4034
+ fingerprint: manifest.fingerprint,
4035
+ manifestSha256: crypto__namespace.createHash("sha256").update(bytes).digest("hex"),
4036
+ publicKey,
4037
+ signature,
4038
+ keyOrigin: configured === null ? "generated" : "configured"
4039
+ };
4040
+ }
4041
+ function verifySnapshotSignature(snapshotDir) {
4042
+ const signaturePath = path25__namespace.join(snapshotDir, SIGNATURE_FILE);
4043
+ const manifestPath = path25__namespace.join(snapshotDir, "manifest.json");
4044
+ if (!fs24__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
4045
+ let record;
4046
+ try {
4047
+ record = JSON.parse(fs24__namespace.readFileSync(signaturePath, "utf8"));
4048
+ } catch (error) {
4049
+ return { ok: false, reason: "signature.json is not JSON: " + error.message };
4050
+ }
4051
+ if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
4052
+ return { ok: false, reason: "signature.json is not an ed25519 record" };
4053
+ }
4054
+ let bytes;
4055
+ try {
4056
+ bytes = fs24__namespace.readFileSync(manifestPath);
4057
+ } catch {
4058
+ return { ok: false, reason: "the signed manifest is missing" };
4059
+ }
4060
+ const sha2562 = crypto__namespace.createHash("sha256").update(bytes).digest("hex");
4061
+ if (sha2562 !== record.manifestSha256) {
4062
+ return { ok: false, reason: "manifest.json changed after it was signed" };
4063
+ }
4064
+ let verified = false;
4065
+ try {
4066
+ const key = crypto__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
4067
+ verified = crypto__namespace.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
4068
+ } catch (error) {
4069
+ return { ok: false, reason: "the signature could not be checked: " + error.message };
4070
+ }
4071
+ return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
4072
+ }
4020
4073
 
4021
4074
  // src/version.ts
4022
4075
  var GENERATOR_NAME = "codebase-snapshot";
4023
- var GENERATOR_VERSION = "0.20.2";
4076
+ var GENERATOR_VERSION = "0.20.4";
4024
4077
  var SCHEMA_VERSION = "3.0.0";
4025
4078
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
4026
4079
  function isOurGeneratorName(name) {
@@ -4052,8 +4105,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
4052
4105
  };
4053
4106
  }
4054
4107
  function isInside(root, candidate) {
4055
- const relative13 = path25__namespace.relative(root, candidate);
4056
- return relative13 === "" || !relative13.startsWith(`..${path25__namespace.sep}`) && relative13 !== ".." && !path25__namespace.isAbsolute(relative13);
4108
+ const relative14 = path25__namespace.relative(root, candidate);
4109
+ return relative14 === "" || !relative14.startsWith(`..${path25__namespace.sep}`) && relative14 !== ".." && !path25__namespace.isAbsolute(relative14);
4057
4110
  }
4058
4111
  var GIT_OUTPUT_LIMIT = 68157440;
4059
4112
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -4527,7 +4580,7 @@ function listIgnoredPaths(cwd) {
4527
4580
  }
4528
4581
  function hasSnapshotMarker(target) {
4529
4582
  try {
4530
- return fs24__namespace.statSync(target).isDirectory() && fs24__namespace.existsSync(path25__namespace.join(target, ".codebase-snapshot"));
4583
+ return fs24__namespace.statSync(target).isDirectory() && isToolOwnedDirectory2(target);
4531
4584
  } catch {
4532
4585
  return false;
4533
4586
  }
@@ -4568,7 +4621,9 @@ function isToolOwnedDirectory2(dir) {
4568
4621
  return false;
4569
4622
  }
4570
4623
  return entries.every(
4571
- (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || accounted.has(entry)
4624
+ (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || // A snapshot signed before signing moved into staging has a valid signature.json the old
4625
+ // marker could not record. It is our artifact when the signature verifies.
4626
+ entry === "signature.json" && verifySnapshotSignature(dir).ok || accounted.has(entry)
4572
4627
  );
4573
4628
  }
4574
4629
  function makeToolOwnedDecider(cwd, toolOwnedPaths) {
@@ -4678,6 +4733,15 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
4678
4733
  });
4679
4734
  continue;
4680
4735
  }
4736
+ const targetRelative = path25__namespace.relative(rootReal, targetReal).split(path25__namespace.sep).join("/");
4737
+ if (isSensitivePath(targetRelative)) {
4738
+ report2(linkedPath, {
4739
+ path: linkedPath,
4740
+ reason: "sensitive-file",
4741
+ detail: "link target is a credential-bearing file; not followed"
4742
+ });
4743
+ continue;
4744
+ }
4681
4745
  kept.push(candidate);
4682
4746
  }
4683
4747
  return kept;
@@ -5122,21 +5186,25 @@ var CONFIG_KEY_NAMES = [
5122
5186
  "kinds",
5123
5187
  "largeFileBytes",
5124
5188
  "layers",
5189
+ "logCount",
5125
5190
  "layersMode",
5126
5191
  "maxMonolithBytes",
5127
5192
  "maxPartBytes",
5128
5193
  "maxParts",
5129
5194
  "maxPartTokens",
5130
5195
  "outDir",
5196
+ "pack",
5131
5197
  "preset",
5132
5198
  "previewHeadLines",
5133
5199
  "promptTask",
5134
5200
  "staged",
5135
5201
  "previewTailLines",
5202
+ "removeEmptyLines",
5136
5203
  "secretRules",
5137
5204
  "secrets",
5138
5205
  "sarif",
5139
5206
  "skeleton",
5207
+ "stripComments",
5140
5208
  "tmpDir",
5141
5209
  "withDependents"
5142
5210
  ];
@@ -5181,7 +5249,7 @@ function readConfigExport(exported, file) {
5181
5249
  var lastModuleConfig = null;
5182
5250
  function moduleConfigKey(fullPath) {
5183
5251
  try {
5184
- return crypto2.createHash("sha256").update(fs24__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
5252
+ return crypto.createHash("sha256").update(fs24__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
5185
5253
  } catch {
5186
5254
  try {
5187
5255
  const stats = fs24__namespace.statSync(fullPath);
@@ -5451,7 +5519,34 @@ function readConfiguredBrief(cwd, value) {
5451
5519
  "brief must be a path to a markdown file (received " + describeValue2(value) + ")."
5452
5520
  );
5453
5521
  }
5454
- const filePath = path25__namespace.resolve(cwd, value);
5522
+ const rootReal = (() => {
5523
+ try {
5524
+ return fs24__namespace.realpathSync(cwd);
5525
+ } catch {
5526
+ return path25__namespace.resolve(cwd);
5527
+ }
5528
+ })();
5529
+ const requested = path25__namespace.resolve(cwd, value);
5530
+ let filePath;
5531
+ try {
5532
+ filePath = fs24__namespace.realpathSync(requested);
5533
+ } catch {
5534
+ throw new Error(
5535
+ 'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
5536
+ );
5537
+ }
5538
+ const relative14 = path25__namespace.relative(rootReal, filePath);
5539
+ if (relative14.length === 0 || relative14 === ".." || relative14.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative14)) {
5540
+ throw new Error(
5541
+ 'brief "' + value + '" resolves outside the repository. A brief must be a file inside the repository being described; an absolute or parent path is refused.'
5542
+ );
5543
+ }
5544
+ const posixRelative = relative14.split(path25__namespace.sep).join("/");
5545
+ if (isSensitivePath(posixRelative) || isSensitivePath(value)) {
5546
+ throw new Error(
5547
+ 'brief "' + value + '" is a credential-bearing file. A snapshot must not reproduce secrets, so it cannot be used as the owner brief.'
5548
+ );
5549
+ }
5455
5550
  let text2;
5456
5551
  try {
5457
5552
  if (!fs24__namespace.statSync(filePath).isFile()) throw new Error("not a file");
@@ -5568,11 +5663,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
5568
5663
  const patterns = [];
5569
5664
  for (const dir of [outDir, tmpDir]) {
5570
5665
  const absolute = path25__namespace.resolve(cwd, dir);
5571
- const relative13 = path25__namespace.relative(cwd, absolute);
5572
- if (!relative13 || relative13 === ".." || relative13.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative13)) {
5666
+ const relative14 = path25__namespace.relative(cwd, absolute);
5667
+ if (!relative14 || relative14 === ".." || relative14.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative14)) {
5573
5668
  continue;
5574
5669
  }
5575
- patterns.push(`${relative13.replace(/\\/g, "/")}/**`);
5670
+ patterns.push(`${relative14.replace(/\\/g, "/")}/**`);
5576
5671
  }
5577
5672
  return patterns;
5578
5673
  }
@@ -6036,7 +6131,7 @@ function configDigest(config) {
6036
6131
  (rule) => `${rule.rule}:${rule.pattern.source}/${rule.pattern.flags}:${rule.valueGroup ?? ""}`
6037
6132
  ).sort()
6038
6133
  };
6039
- return crypto2.createHash("sha256").update(JSON.stringify(material)).digest("hex");
6134
+ return crypto.createHash("sha256").update(JSON.stringify(material)).digest("hex");
6040
6135
  }
6041
6136
 
6042
6137
  // src/define-config.ts
@@ -6237,7 +6332,7 @@ var BUILTIN_RULE_IDS = new Map(
6237
6332
  function ruleIdFor(name) {
6238
6333
  const builtin = BUILTIN_RULE_IDS.get(name);
6239
6334
  if (builtin !== void 0) return builtin;
6240
- const digest = crypto2__namespace.createHash("sha256").update(name).digest("hex").slice(0, 8);
6335
+ const digest = crypto__namespace.createHash("sha256").update(name).digest("hex").slice(0, 8);
6241
6336
  return `CS${digest.toUpperCase()}`;
6242
6337
  }
6243
6338
  function generateSarifReport(manifest, findings, rules, toolVersion) {
@@ -6575,7 +6670,7 @@ function renumberParts(parts, contentFingerprint) {
6575
6670
  filename: nameFor(index + 1),
6576
6671
  byteSize: Buffer.byteLength(markdown, "utf8"),
6577
6672
  estimatedTokens,
6578
- sha256: crypto2__namespace.createHash("sha256").update(markdown).digest("hex"),
6673
+ sha256: crypto__namespace.createHash("sha256").update(markdown).digest("hex"),
6579
6674
  lines: countLines(markdown),
6580
6675
  fileCount: included.length,
6581
6676
  layersCovered: Object.keys(layerCounts).sort()
@@ -6701,7 +6796,7 @@ function rehashPart(part, markdown) {
6701
6796
  metadata: {
6702
6797
  ...part.metadata,
6703
6798
  byteSize: Buffer.byteLength(redistributed, "utf8"),
6704
- sha256: crypto2__namespace.createHash("sha256").update(redistributed).digest("hex"),
6799
+ sha256: crypto__namespace.createHash("sha256").update(redistributed).digest("hex"),
6705
6800
  lines: countLines(redistributed),
6706
6801
  estimatedTokens
6707
6802
  }
@@ -6782,7 +6877,7 @@ function renderGroups(groups, contentFingerprint, assemble = (group, index, tota
6782
6877
  return groups.map((group, index) => {
6783
6878
  const { filename, content, estimatedTokens } = assemble(group, index, total);
6784
6879
  const byteSize = Buffer.byteLength(content, "utf8");
6785
- const sha2562 = crypto2__namespace.createHash("sha256").update(content).digest("hex");
6880
+ const sha2562 = crypto__namespace.createHash("sha256").update(content).digest("hex");
6786
6881
  const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
6787
6882
  const includedFiles = group.sections.map(({ file }) => ({
6788
6883
  relativePath: file.relativePath,
@@ -6864,7 +6959,7 @@ function renderSummary(summary, inclusionMode) {
6864
6959
  }
6865
6960
  function anchorForPath(filePath) {
6866
6961
  const slug = filePath.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
6867
- const digest = crypto2__namespace.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
6962
+ const digest = crypto__namespace.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
6868
6963
  return `${slug || "file"}-${digest}`;
6869
6964
  }
6870
6965
 
@@ -7371,12 +7466,27 @@ function runGit(cwd, args) {
7371
7466
  function isGitRepository(cwd) {
7372
7467
  return runGit(cwd, ["rev-parse", "--is-inside-work-tree"]).out.trim() === "true";
7373
7468
  }
7469
+ function diffSectionPaths(body) {
7470
+ const paths = /* @__PURE__ */ new Set();
7471
+ for (const line of body.split("\n")) {
7472
+ const plus = /^\+\+\+ b\/(.*)$/.exec(line);
7473
+ if (plus !== null) paths.add(plus[1]);
7474
+ const minus = /^--- a\/(.*)$/.exec(line);
7475
+ if (minus !== null) paths.add(minus[1]);
7476
+ const header = /^diff --git a\/(.*?) b\/(.*)$/.exec(line);
7477
+ if (header !== null) {
7478
+ paths.add(header[1]);
7479
+ paths.add(header[2]);
7480
+ }
7481
+ }
7482
+ return [...paths];
7483
+ }
7374
7484
  function generateDiffReport(cwd, options = {}) {
7375
7485
  if (!isGitRepository(cwd)) return null;
7376
7486
  const maxBytes = options.maxBytes ?? 200 * 1024;
7377
7487
  const sections = [];
7378
- let bytes = 0;
7379
7488
  let truncated = false;
7489
+ let omittedSensitive = 0;
7380
7490
  const commands = [
7381
7491
  ["Unstaged", ["diff", "--no-color"]],
7382
7492
  ["Staged", ["diff", "--cached", "--no-color"]]
@@ -7384,28 +7494,47 @@ function generateDiffReport(cwd, options = {}) {
7384
7494
  for (const [title, args] of commands) {
7385
7495
  const result = runGit(cwd, args);
7386
7496
  if (!result.ok || result.out.trim() === "") continue;
7387
- const body = result.out;
7388
- bytes += Buffer.byteLength(body, "utf8");
7389
- const used = Buffer.byteLength(sections.join(""), "utf8");
7390
- const remaining = Math.max(0, maxBytes - used);
7391
- const chunk = Buffer.byteLength(body, "utf8") > remaining ? body.slice(0, remaining) : body;
7392
- if (chunk.length < body.length) truncated = true;
7393
- sections.push("## " + title + " changes\n\nRun: git " + args.join(" ") + "\n\n```diff\n" + chunk + "\n```");
7497
+ const rawSections = result.out.split(/(?=^diff --git )/m).filter((section) => section.length > 0);
7498
+ for (const rawSection of rawSections) {
7499
+ const paths2 = diffSectionPaths(rawSection);
7500
+ const blocked = paths2.some((path26) => isSensitivePath(path26) || options.excluded?.(path26) === true);
7501
+ if (blocked) {
7502
+ omittedSensitive += 1;
7503
+ continue;
7504
+ }
7505
+ const used = Buffer.byteLength(sections.join(""), "utf8");
7506
+ const remaining = Math.max(0, maxBytes - used);
7507
+ if (remaining === 0) {
7508
+ truncated = true;
7509
+ break;
7510
+ }
7511
+ const chunk = truncateToBytes(rawSection, remaining);
7512
+ if (chunk.isTruncated) truncated = true;
7513
+ sections.push(
7514
+ "## " + title + " changes\n\nRun: git " + args.join(" ") + "\n\n```diff\n" + chunk.content + "\n```"
7515
+ );
7516
+ if (chunk.isTruncated) break;
7517
+ }
7394
7518
  }
7395
7519
  if (sections.length === 0) return null;
7396
7520
  const paths = /* @__PURE__ */ new Set();
7397
- for (const match of sections.join("\n").matchAll(/^\+\+\+ b\/(.+)$/gm)) paths.add(match[1]);
7398
- const text2 = [
7521
+ for (const section of sections) for (const path26 of diffSectionPaths(section)) paths.add(path26);
7522
+ const joined = [
7399
7523
  "# Uncommitted changes",
7400
7524
  "",
7401
7525
  "Generated from the repository at the moment the snapshot was written. Untracked files are not",
7402
7526
  "in a diff until they are added; this artifact says what git reports, not what git ignores.",
7403
7527
  "",
7528
+ ...omittedSensitive > 0 ? [
7529
+ "> " + omittedSensitive + " file section(s) omitted: their path is credential-bearing or excluded from the snapshot.",
7530
+ ""
7531
+ ] : [],
7404
7532
  ...sections,
7405
7533
  ...truncated ? ["", "> Truncated at " + maxBytes + " bytes. Run git diff for the rest."] : [],
7406
7534
  ""
7407
7535
  ].join("\n");
7408
- return { text: text2, bytes, truncated, paths: [...paths].sort() };
7536
+ const text2 = scanAndRedactSecrets(joined, options.secretRules ?? [], "reports/diff.md").redacted;
7537
+ return { text: text2, bytes: Buffer.byteLength(text2, "utf8"), truncated, paths: [...paths].sort() };
7409
7538
  }
7410
7539
  function generateLogReport(cwd, options = {}) {
7411
7540
  const count = Math.max(1, Math.min(500, options.count ?? 20));
@@ -7419,13 +7548,15 @@ function generateLogReport(cwd, options = {}) {
7419
7548
  const body = (result.stdout ?? "").trim();
7420
7549
  if (body === "") return null;
7421
7550
  const lines = body.split("\n");
7551
+ const redacted = scanAndRedactSecrets(body, options.secretRules ?? [], "reports/log.md").redacted;
7552
+ const joined = truncateToBytes(redacted, maxBytes).content;
7422
7553
  const text2 = [
7423
7554
  "# Recent commits",
7424
7555
  "",
7425
7556
  "The last " + count + " commits, newest first, one line each.",
7426
7557
  "",
7427
7558
  "```text",
7428
- lines.join("\n").slice(0, maxBytes),
7559
+ joined,
7429
7560
  "```",
7430
7561
  ""
7431
7562
  ].join("\n");
@@ -8393,8 +8524,8 @@ function tsconfigPathsFor(cwd) {
8393
8524
  return value;
8394
8525
  }
8395
8526
  function repositoryRelative(cwd, target) {
8396
- const relative13 = path25__namespace.relative(cwd, target).replace(/\\/g, "/");
8397
- return relative13.length === 0 || !relative13.startsWith("..") && !path25__namespace.isAbsolute(relative13) ? relative13 : null;
8527
+ const relative14 = path25__namespace.relative(cwd, target).replace(/\\/g, "/");
8528
+ return relative14.length === 0 || !relative14.startsWith("..") && !path25__namespace.isAbsolute(relative14) ? relative14 : null;
8398
8529
  }
8399
8530
  function rememberFirst(map, key, value) {
8400
8531
  if (!map.has(key)) map.set(key, value);
@@ -8645,41 +8776,6 @@ function detectLanguage(filePath) {
8645
8776
  const ext = path25__namespace.posix.extname(base).toLowerCase();
8646
8777
  return LANGUAGE_BY_EXTENSION[ext] ?? "text";
8647
8778
  }
8648
- var SIGNATURE_FILE = "signature.json";
8649
- function verifySnapshotSignature(snapshotDir) {
8650
- const signaturePath = path25__namespace.join(snapshotDir, SIGNATURE_FILE);
8651
- const manifestPath = path25__namespace.join(snapshotDir, "manifest.json");
8652
- if (!fs24__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
8653
- let record;
8654
- try {
8655
- record = JSON.parse(fs24__namespace.readFileSync(signaturePath, "utf8"));
8656
- } catch (error) {
8657
- return { ok: false, reason: "signature.json is not JSON: " + error.message };
8658
- }
8659
- if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
8660
- return { ok: false, reason: "signature.json is not an ed25519 record" };
8661
- }
8662
- let bytes;
8663
- try {
8664
- bytes = fs24__namespace.readFileSync(manifestPath);
8665
- } catch {
8666
- return { ok: false, reason: "the signed manifest is missing" };
8667
- }
8668
- const sha2562 = crypto2__namespace.createHash("sha256").update(bytes).digest("hex");
8669
- if (sha2562 !== record.manifestSha256) {
8670
- return { ok: false, reason: "manifest.json changed after it was signed" };
8671
- }
8672
- let verified = false;
8673
- try {
8674
- const key = crypto2__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
8675
- verified = crypto2__namespace.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
8676
- } catch (error) {
8677
- return { ok: false, reason: "the signature could not be checked: " + error.message };
8678
- }
8679
- return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
8680
- }
8681
-
8682
- // src/validator/validate.ts
8683
8779
  function maskedPath(value, secretRules) {
8684
8780
  return findSecretInPath(value, secretRules)?.masked ?? value;
8685
8781
  }
@@ -8743,7 +8839,7 @@ function emptyDrift() {
8743
8839
  };
8744
8840
  }
8745
8841
  function sha256Hex(buffer) {
8746
- return crypto2__namespace.createHash("sha256").update(buffer).digest("hex");
8842
+ return crypto__namespace.createHash("sha256").update(buffer).digest("hex");
8747
8843
  }
8748
8844
  function wouldNowBeIncluded(cwd, relativePath) {
8749
8845
  const absolutePath = path25__namespace.join(cwd, relativePath);
@@ -9096,17 +9192,18 @@ function validateSnapshot(configInput) {
9096
9192
  return skippedReasons.get(maskedPath(diskFile, config.secretRules)) ?? null;
9097
9193
  };
9098
9194
  let unchangedScope = null;
9195
+ let stagedScope = null;
9099
9196
  const recordedChangedSince = manifest.config?.changedSince;
9100
9197
  const recordedStaged = manifest.config?.staged === true;
9101
9198
  const recordedWithDependents = manifest.config?.withDependents === true;
9102
9199
  if (recordedChangedSince !== void 0 || recordedStaged) {
9103
9200
  try {
9104
- unchangedScope = new Set(
9105
- resolveChangedScope(config.cwd, {
9106
- ...recordedChangedSince === void 0 ? {} : { changedSince: recordedChangedSince },
9107
- ...recordedStaged ? { staged: true } : {}
9108
- }).paths
9109
- );
9201
+ const scope = resolveChangedScope(config.cwd, {
9202
+ ...recordedChangedSince === void 0 ? {} : { changedSince: recordedChangedSince },
9203
+ ...recordedStaged ? { staged: true } : {}
9204
+ });
9205
+ unchangedScope = new Set(scope.paths);
9206
+ if (recordedStaged) stagedScope = new Set(scope.stagedPaths);
9110
9207
  } catch {
9111
9208
  warnings.push(
9112
9209
  "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."
@@ -9117,7 +9214,11 @@ function validateSnapshot(configInput) {
9117
9214
  function becameDependent(diskFile) {
9118
9215
  if (!recordedWithDependents || unchangedScope === null) return false;
9119
9216
  dependentResolver ??= buildImportResolver(
9120
- collection.files.map((file) => ({ relativePath: file }))
9217
+ collection.files.map((file) => ({ relativePath: file })),
9218
+ {
9219
+ tsconfig: tsconfigPathsFor(config.cwd),
9220
+ ...unchangedScope === null ? {} : { extraPaths: unchangedScope }
9221
+ }
9121
9222
  );
9122
9223
  return importsChangedFile(
9123
9224
  diskFile,
@@ -9140,7 +9241,7 @@ function validateSnapshot(configInput) {
9140
9241
  // snapshot was reported as drifting.
9141
9242
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
9142
9243
  (directory) => path25__namespace.relative(config.cwd, path25__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
9143
- ).filter((relative13) => relative13.length > 0 && !relative13.startsWith(".."))
9244
+ ).filter((relative14) => relative14.length > 0 && !relative14.startsWith(".."))
9144
9245
  });
9145
9246
  for (const diskFile of collection.files) {
9146
9247
  const snapshotHash = manifestFileMap.get(diskFile);
@@ -9166,7 +9267,8 @@ function validateSnapshot(configInput) {
9166
9267
  }
9167
9268
  let diskHash;
9168
9269
  try {
9169
- diskHash = sha256Hex(fs24__namespace.readFileSync(path25__namespace.join(config.cwd, diskFile)));
9270
+ const stagedBlob = recordedStaged && stagedScope?.has(diskFile) === true ? readStagedBlob(config.cwd, diskFile) : null;
9271
+ diskHash = sha256Hex(stagedBlob ?? fs24__namespace.readFileSync(path25__namespace.join(config.cwd, diskFile)));
9170
9272
  } catch (err) {
9171
9273
  if (err.code === "ENOENT") {
9172
9274
  drift.missingOnDisk.push(diskFile);
@@ -9620,8 +9722,8 @@ function validateSnapshot(configInput) {
9620
9722
  const target = match[1].split("#")[0];
9621
9723
  if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
9622
9724
  const resolved = path25__namespace.resolve(snapshotDir, "reports", target);
9623
- const relative13 = path25__namespace.relative(snapshotDir, resolved);
9624
- if (relative13.startsWith("..") || path25__namespace.isAbsolute(relative13) || !fs24__namespace.existsSync(resolved)) {
9725
+ const relative14 = path25__namespace.relative(snapshotDir, resolved);
9726
+ if (relative14.startsWith("..") || path25__namespace.isAbsolute(relative14) || !fs24__namespace.existsSync(resolved)) {
9625
9727
  drift.partIssues.push({
9626
9728
  part: key,
9627
9729
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -9715,24 +9817,93 @@ function validateSnapshot(configInput) {
9715
9817
  };
9716
9818
  }
9717
9819
  var HOST_PATTERN = /^[a-z0-9.-]+$/i;
9820
+ function parseIPv4(value) {
9821
+ const parts = value.split(".");
9822
+ if (parts.length !== 4) return null;
9823
+ const octets = [];
9824
+ for (const part of parts) {
9825
+ if (!/^\d{1,3}$/.test(part)) return null;
9826
+ const octet = Number(part);
9827
+ if (octet > 255) return null;
9828
+ octets.push(octet);
9829
+ }
9830
+ return octets;
9831
+ }
9832
+ function isPrivateIPv4(octets) {
9833
+ const [a, b] = octets;
9834
+ 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;
9835
+ }
9836
+ function parseIPv6(value) {
9837
+ const withoutZone = value.split("%")[0] ?? value;
9838
+ if (!withoutZone.includes(":")) return null;
9839
+ const halves = withoutZone.split("::");
9840
+ if (halves.length > 2) return null;
9841
+ const left = halves[0] === "" ? [] : halves[0].split(":");
9842
+ const right = halves.length === 2 && halves[1] !== "" ? halves[1].split(":") : [];
9843
+ const groups = [...left, ...right];
9844
+ if (halves.length === 1 && groups.length !== 8) return null;
9845
+ if (halves.length === 2 && groups.length > 7) return null;
9846
+ const expand = (group) => {
9847
+ if (group.includes(".")) {
9848
+ const octets = parseIPv4(group);
9849
+ if (octets === null) return null;
9850
+ return [
9851
+ (octets[0] << 8 | octets[1]).toString(16),
9852
+ (octets[2] << 8 | octets[3]).toString(16)
9853
+ ];
9854
+ }
9855
+ return [group];
9856
+ };
9857
+ const expanded = [];
9858
+ for (const group of groups) {
9859
+ const next = expand(group);
9860
+ if (next === null) return null;
9861
+ expanded.push(...next);
9862
+ }
9863
+ if (halves.length === 1 && expanded.length !== 8) return null;
9864
+ if (halves.length === 2 && expanded.length > 8) return null;
9865
+ const missing = 8 - expanded.length;
9866
+ const full = halves.length === 2 ? [...expanded.slice(0, left.length), ...Array(missing).fill("0"), ...expanded.slice(left.length)] : expanded;
9867
+ if (full.length !== 8) return null;
9868
+ const numbers = [];
9869
+ for (const group of full) {
9870
+ if (!/^[0-9a-f]{1,4}$/i.test(group)) return null;
9871
+ numbers.push(Number.parseInt(group, 16));
9872
+ }
9873
+ return numbers;
9874
+ }
9875
+ function isPrivateIPv6(groups) {
9876
+ const [first, second, third, fourth, fifth, sixth, seventh, eighth] = groups;
9877
+ const allZeroThrough = (count) => groups.slice(0, count).every((group) => group === 0);
9878
+ if (groups.every((group) => group === 0)) return true;
9879
+ if (allZeroThrough(7) && eighth === 1) return true;
9880
+ if ((first & 65024) === 64512) return true;
9881
+ if ((first & 65472) === 65152) return true;
9882
+ if ((first & 65472) === 65216) return true;
9883
+ if ((first & 65280) === 65280) return true;
9884
+ if (first === 8193 && second === 3512) return true;
9885
+ const mapped = (offset) => isPrivateIPv4([
9886
+ groups[offset] >> 8,
9887
+ groups[offset] & 255,
9888
+ groups[offset + 1] >> 8,
9889
+ groups[offset + 1] & 255
9890
+ ]);
9891
+ if (allZeroThrough(5) && sixth === 65535) return mapped(6);
9892
+ if (allZeroThrough(6) && (seventh !== 0 || eighth !== 0)) return mapped(6);
9893
+ if (first === 100 && second === 65435 && third === 0 && fourth === 0 && fifth === 0 && sixth === 0) {
9894
+ return mapped(6);
9895
+ }
9896
+ if (first === 8194) return mapped(1);
9897
+ return false;
9898
+ }
9718
9899
  function isPrivateHost(host) {
9719
- const value = host.toLowerCase().replace(/^\[|\]$/g, "");
9900
+ const value = host.toLowerCase().replace(/^\[|\]$/g, "").split("%")[0] ?? "";
9720
9901
  if (value === "localhost" || value.endsWith(".localhost") || value.endsWith(".local")) return true;
9721
9902
  if (value === "::1" || value === "0.0.0.0" || value === "::") return true;
9722
- if (value.startsWith("fc") || value.startsWith("fd")) return true;
9723
- if (value.startsWith("fe80")) return true;
9724
- const parts = value.split(".");
9725
- if (parts.length === 4 && parts.every((part) => /^\d{1,3}$/.test(part))) {
9726
- const octets = parts.map(Number);
9727
- if (octets.some((octet) => octet > 255)) return true;
9728
- if (octets[0] === 127) return true;
9729
- if (octets[0] === 10) return true;
9730
- if (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) return true;
9731
- if (octets[0] === 192 && octets[1] === 168) return true;
9732
- if (octets[0] === 169 && octets[1] === 254) return true;
9733
- if (octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127) return true;
9734
- if (octets[0] === 0) return true;
9735
- }
9903
+ const ipv4 = parseIPv4(value);
9904
+ if (ipv4 !== null) return isPrivateIPv4(ipv4);
9905
+ const ipv6 = parseIPv6(value);
9906
+ if (ipv6 !== null) return isPrivateIPv6(ipv6);
9736
9907
  return false;
9737
9908
  }
9738
9909
  function parseRemoteSource(input, options = {}) {
@@ -9807,14 +9978,25 @@ async function assertPublicHost(host, allowPrivate) {
9807
9978
  }
9808
9979
  }
9809
9980
  }
9981
+ function tokenHosts() {
9982
+ const configured = process.env.CODEBASE_SNAPSHOT_GITHUB_HOSTS;
9983
+ if (configured === void 0 || configured.trim() === "") return ["github.com"];
9984
+ return configured.split(",").map((entry) => entry.trim().toLowerCase()).filter((entry) => entry.length > 0);
9985
+ }
9986
+ function tokenAllowedForHost(host) {
9987
+ return tokenHosts().includes(host.toLowerCase().replace(/^\[|\]$/g, ""));
9988
+ }
9810
9989
  function gitEnvironment(token, host) {
9811
9990
  const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_LFS_SKIP_SMUDGE: "1" };
9812
9991
  delete env.GIT_ASKPASS;
9813
9992
  delete env.SSH_ASKPASS;
9814
9993
  if (token !== void 0 && token !== null && token !== "") {
9815
- env.GIT_CONFIG_COUNT = "1";
9816
- env.GIT_CONFIG_KEY_0 = "http.https://" + host + "/.extraheader";
9817
- env.GIT_CONFIG_VALUE_0 = "Authorization: Basic " + Buffer.from("x-access-token:" + token).toString("base64");
9994
+ const normalizedHost = host.toLowerCase().replace(/^\[|\]$/g, "");
9995
+ if (tokenAllowedForHost(normalizedHost)) {
9996
+ env.GIT_CONFIG_COUNT = "1";
9997
+ env.GIT_CONFIG_KEY_0 = "http.https://" + normalizedHost + "/.extraheader";
9998
+ env.GIT_CONFIG_VALUE_0 = "Authorization: Basic " + Buffer.from("x-access-token:" + token).toString("base64");
9999
+ }
9818
10000
  }
9819
10001
  return env;
9820
10002
  }
@@ -9824,15 +10006,29 @@ async function cloneRepository(source, options) {
9824
10006
  const dest = path25__namespace.resolve(options.dest);
9825
10007
  fs24__namespace.rmSync(dest, { recursive: true, force: true });
9826
10008
  fs24__namespace.mkdirSync(dest, { recursive: true });
9827
- const args = ["clone", "--depth", "1", "--single-branch", "--no-tags", "--quiet"];
9828
- if (options.ref !== void 0 && options.ref !== null && options.ref !== "") {
9829
- args.push("--branch", options.ref);
10009
+ const ref = options.ref ?? source.ref;
10010
+ const args = [
10011
+ "-c",
10012
+ "http.followRedirects=false",
10013
+ ...source.kind === "https" ? ["-c", "protocol.file.allow=never", "-c", "protocol.ssh.allow=never"] : [],
10014
+ "clone",
10015
+ "--depth",
10016
+ "1",
10017
+ "--single-branch",
10018
+ "--no-tags",
10019
+ "--quiet"
10020
+ ];
10021
+ if (ref !== void 0 && ref !== null && ref !== "") {
10022
+ args.push("--branch", ref);
9830
10023
  }
9831
10024
  args.push(source.url, dest);
9832
- log("clone: " + source.url + (options.ref ? " (" + options.ref + ")" : ""));
10025
+ log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
9833
10026
  const started = Date.now();
9834
10027
  const result = childProcess.spawnSync("git", args, {
9835
- env: gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
10028
+ env: {
10029
+ ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
10030
+ ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
10031
+ },
9836
10032
  timeout: options.timeoutMs ?? 18e4,
9837
10033
  encoding: "utf8",
9838
10034
  windowsHide: true
@@ -9860,7 +10056,7 @@ async function cloneRepository(source, options) {
9860
10056
  host: source.host,
9861
10057
  owner: source.owner,
9862
10058
  repo: source.repo,
9863
- ref: options.ref !== void 0 && options.ref !== null && options.ref !== "" ? options.ref : source.ref,
10059
+ ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
9864
10060
  commit,
9865
10061
  fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
9866
10062
  }
@@ -10186,7 +10382,7 @@ var ARTIFACT_FILES = {
10186
10382
  };
10187
10383
  var TEXT_ARTIFACT = /\.(md|json|txt|sarif)$/i;
10188
10384
  function sha256(buffer) {
10189
- return crypto2.createHash("sha256").update(buffer).digest("hex");
10385
+ return crypto.createHash("sha256").update(buffer).digest("hex");
10190
10386
  }
10191
10387
  function readBytes(file) {
10192
10388
  try {
@@ -10220,9 +10416,9 @@ function walk(dir, prefix = "") {
10220
10416
  }
10221
10417
  const files = [];
10222
10418
  for (const entry of entries) {
10223
- const relative13 = prefix === "" ? entry.name : prefix + "/" + entry.name;
10224
- if (entry.isDirectory()) files.push(...walk(path25__namespace.join(dir, entry.name), relative13));
10225
- else if (entry.isFile()) files.push(relative13);
10419
+ const relative14 = prefix === "" ? entry.name : prefix + "/" + entry.name;
10420
+ if (entry.isDirectory()) files.push(...walk(path25__namespace.join(dir, entry.name), relative14));
10421
+ else if (entry.isFile()) files.push(relative14);
10226
10422
  }
10227
10423
  return files;
10228
10424
  }
@@ -10260,13 +10456,14 @@ function secretTokens(text2) {
10260
10456
  }
10261
10457
  return [...tokens];
10262
10458
  }
10263
- function artifactTextContains(snapshotDir, token) {
10264
- for (const relative13 of walk(snapshotDir)) {
10265
- if (!TEXT_ARTIFACT.test(relative13)) continue;
10266
- const text2 = readText2(path25__namespace.join(snapshotDir, relative13));
10267
- if (text2 !== null && text2.includes(token)) return true;
10459
+ function readArtifactTexts(snapshotDir) {
10460
+ const texts = [];
10461
+ for (const relative14 of walk(snapshotDir)) {
10462
+ if (!TEXT_ARTIFACT.test(relative14)) continue;
10463
+ const text2 = readText2(path25__namespace.join(snapshotDir, relative14));
10464
+ if (text2 !== null) texts.push(text2);
10268
10465
  }
10269
- return false;
10466
+ return texts;
10270
10467
  }
10271
10468
  function findHostPaths(snapshotDir, repoDir) {
10272
10469
  const patterns = [
@@ -10279,15 +10476,15 @@ function findHostPaths(snapshotDir, repoDir) {
10279
10476
  ];
10280
10477
  const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
10281
10478
  const hits = /* @__PURE__ */ new Set();
10282
- for (const relative13 of walk(snapshotDir)) {
10283
- if (!TEXT_ARTIFACT.test(relative13)) continue;
10284
- const text2 = readText2(path25__namespace.join(snapshotDir, relative13));
10479
+ for (const relative14 of walk(snapshotDir)) {
10480
+ if (!TEXT_ARTIFACT.test(relative14)) continue;
10481
+ const text2 = readText2(path25__namespace.join(snapshotDir, relative14));
10285
10482
  if (text2 === null) continue;
10286
10483
  for (const pattern of patterns) {
10287
- for (const match of text2.match(pattern) ?? []) hits.add(relative13 + ": " + match);
10484
+ for (const match of text2.match(pattern) ?? []) hits.add(relative14 + ": " + match);
10288
10485
  }
10289
10486
  repoPattern.lastIndex = 0;
10290
- if (repoPattern.test(text2)) hits.add(relative13 + ": the repository absolute path");
10487
+ if (repoPattern.test(text2)) hits.add(relative14 + ": the repository absolute path");
10291
10488
  }
10292
10489
  return [...hits];
10293
10490
  }
@@ -10534,13 +10731,13 @@ function auditSnapshot(options) {
10534
10731
  let artifactCount = 0;
10535
10732
  for (const [key, value] of Object.entries(artifacts)) {
10536
10733
  if (value === null || value === void 0) continue;
10537
- const relative13 = ARTIFACT_FILES[key];
10538
- if (relative13 === void 0) continue;
10734
+ const relative14 = ARTIFACT_FILES[key];
10735
+ if (relative14 === void 0) continue;
10539
10736
  artifactCount += 1;
10540
- const bytes = readBytes(path25__namespace.join(snapshotDir, relative13));
10541
- if (bytes === null) artifactProblems.push(relative13 + " is missing");
10737
+ const bytes = readBytes(path25__namespace.join(snapshotDir, relative14));
10738
+ if (bytes === null) artifactProblems.push(relative14 + " is missing");
10542
10739
  else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
10543
- artifactProblems.push(relative13 + " changed");
10740
+ artifactProblems.push(relative14 + " changed");
10544
10741
  }
10545
10742
  }
10546
10743
  checks.push(
@@ -11270,25 +11467,25 @@ function auditSnapshot(options) {
11270
11467
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
11271
11468
  const leakHits = [];
11272
11469
  let scannedBytes = 0;
11273
- for (const relative13 of walk(snapshotDir)) {
11274
- if (!TEXT_ARTIFACT.test(relative13) || scannedBytes > scanBudget) continue;
11275
- if (relative13 === SIGNATURE_FILE) continue;
11276
- const text2 = readText2(path25__namespace.join(snapshotDir, relative13));
11470
+ for (const relative14 of walk(snapshotDir)) {
11471
+ if (!TEXT_ARTIFACT.test(relative14) || scannedBytes > scanBudget) continue;
11472
+ if (relative14 === SIGNATURE_FILE) continue;
11473
+ const text2 = readText2(path25__namespace.join(snapshotDir, relative14));
11277
11474
  if (text2 === null) continue;
11278
11475
  scannedBytes += Buffer.byteLength(text2, "utf8");
11279
11476
  let findingCount = 0;
11280
- if (/^parts[\\/].*\.md$/i.test(relative13)) {
11477
+ if (/^parts[\\/].*\.md$/i.test(relative14)) {
11281
11478
  let headerText = text2;
11282
11479
  for (const section of parsePartSections(text2)) {
11283
11480
  findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
11284
11481
  headerText = headerText.replace(section.body, "");
11285
11482
  }
11286
- findingCount += scanAndRedactSecrets(headerText, rules, relative13).findings.length;
11483
+ findingCount += scanAndRedactSecrets(headerText, rules, relative14).findings.length;
11287
11484
  } else {
11288
- findingCount = scanAndRedactSecrets(text2, rules, relative13).findings.length;
11485
+ findingCount = scanAndRedactSecrets(text2, rules, relative14).findings.length;
11289
11486
  }
11290
11487
  if (findingCount > 0) {
11291
- leakHits.push(relative13 + " (" + findingCount + " line(s))");
11488
+ leakHits.push(relative14 + " (" + findingCount + " line(s))");
11292
11489
  }
11293
11490
  }
11294
11491
  const signatureRecordPath = path25__namespace.join(snapshotDir, SIGNATURE_FILE);
@@ -11333,13 +11530,15 @@ function auditSnapshot(options) {
11333
11530
  );
11334
11531
  const leakedFrom = [];
11335
11532
  let compared = 0;
11533
+ const artifactTexts = readArtifactTexts(snapshotDir);
11534
+ const artifactContains = (token) => artifactTexts.some((text2) => text2.includes(token));
11336
11535
  for (const record of skippedSensitive.slice(0, 40)) {
11337
11536
  if (record.path.includes("[REDACTED") || compared > 400) continue;
11338
11537
  const text2 = readText2(path25__namespace.join(repoDir, record.path));
11339
11538
  if (text2 === null) continue;
11340
11539
  for (const token of secretTokens(text2)) {
11341
11540
  compared += 1;
11342
- if (artifactTextContains(snapshotDir, token)) leakedFrom.push(record.path);
11541
+ if (artifactContains(token)) leakedFrom.push(record.path);
11343
11542
  }
11344
11543
  }
11345
11544
  checks.push(
@@ -11489,23 +11688,23 @@ function describeMatcher(matcher) {
11489
11688
  function normalizeTarget(cwd, target) {
11490
11689
  const resolvedCwd = path25__namespace.resolve(cwd);
11491
11690
  const absolute = path25__namespace.resolve(resolvedCwd, target);
11492
- const relative13 = path25__namespace.relative(resolvedCwd, absolute);
11493
- if (relative13 === "" || relative13 === ".." || relative13.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative13)) {
11691
+ const relative14 = path25__namespace.relative(resolvedCwd, absolute);
11692
+ if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative14)) {
11494
11693
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
11495
11694
  }
11496
- return { relative: relative13.split(path25__namespace.sep).join("/"), outsideRoot: false };
11695
+ return { relative: relative14.split(path25__namespace.sep).join("/"), outsideRoot: false };
11497
11696
  }
11498
11697
  function findRuleMatch(rules, relativePath) {
11499
11698
  return rules.find(
11500
11699
  (rule) => matchRule(relativePath, rule.match)
11501
11700
  );
11502
11701
  }
11503
- function findRecordedAncestor(skipped, relative13, maskedPath2) {
11702
+ function findRecordedAncestor(skipped, relative14, maskedPath2) {
11504
11703
  let nearest;
11505
11704
  for (const record of skipped) {
11506
11705
  const ancestorPath = record.path;
11507
11706
  if (ancestorPath.length === 0) continue;
11508
- const isAncestor = relative13.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
11707
+ const isAncestor = relative14.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
11509
11708
  if (!isAncestor) continue;
11510
11709
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
11511
11710
  }
@@ -11521,8 +11720,8 @@ function readManifest2(config) {
11521
11720
  }
11522
11721
  function explainPath(config, target) {
11523
11722
  const normalized = normalizeTarget(config.cwd, target);
11524
- const relative13 = normalized.relative;
11525
- const maskedPath2 = findSecretInPath(relative13, config.secretRules)?.masked ?? relative13;
11723
+ const relative14 = normalized.relative;
11724
+ const maskedPath2 = findSecretInPath(relative14, config.secretRules)?.masked ?? relative14;
11526
11725
  if (normalized.outsideRoot) {
11527
11726
  return {
11528
11727
  path: maskedPath2,
@@ -11532,7 +11731,7 @@ function explainPath(config, target) {
11532
11731
  detail: "path resolves outside the configured repository root and was not inspected"
11533
11732
  };
11534
11733
  }
11535
- const absolute = path25__namespace.join(config.cwd, relative13);
11734
+ const absolute = path25__namespace.join(config.cwd, relative14);
11536
11735
  const result = {
11537
11736
  path: maskedPath2,
11538
11737
  exists: fs24__namespace.existsSync(absolute),
@@ -11550,11 +11749,11 @@ function explainPath(config, target) {
11550
11749
  // that is only missing because the walker dropped the tool's own output directory.
11551
11750
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
11552
11751
  (directory) => path25__namespace.relative(config.cwd, path25__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
11553
- ).filter((relative14) => relative14.length > 0 && !relative14.startsWith(".."))
11752
+ ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
11554
11753
  });
11555
- if (!collection.files.includes(relative13)) {
11754
+ if (!collection.files.includes(relative14)) {
11556
11755
  const record = collection.skipped.find(
11557
- (entry2) => entry2.path === relative13 || entry2.path === maskedPath2
11756
+ (entry2) => entry2.path === relative14 || entry2.path === maskedPath2
11558
11757
  );
11559
11758
  if (record) {
11560
11759
  result.reason = record.reason;
@@ -11563,7 +11762,7 @@ function explainPath(config, target) {
11563
11762
  result.reason = "missing";
11564
11763
  result.detail = "no such file or directory, relative to the configured cwd";
11565
11764
  } else {
11566
- const ancestor = findRecordedAncestor(collection.skipped, relative13, maskedPath2);
11765
+ const ancestor = findRecordedAncestor(collection.skipped, relative14, maskedPath2);
11567
11766
  if (ancestor) {
11568
11767
  result.reason = ancestor.reason;
11569
11768
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -11583,13 +11782,15 @@ function explainPath(config, target) {
11583
11782
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
11584
11783
  ...config.staged === true ? { staged: true } : {}
11585
11784
  });
11586
- inScope = scope.paths.has(relative13);
11785
+ inScope = scope.paths.has(relative14);
11587
11786
  if (!inScope && config.withDependents === true) {
11588
11787
  inScope = importsChangedFile(
11589
- relative13,
11590
- importsOfFile(relative13, absolute),
11788
+ relative14,
11789
+ importsOfFile(relative14, absolute),
11591
11790
  scope.paths,
11592
- buildImportResolver(collection.files.map((file) => ({ relativePath: file })))
11791
+ buildImportResolver(collection.files.map((file) => ({ relativePath: file })), {
11792
+ tsconfig: tsconfigPathsFor(config.cwd)
11793
+ })
11593
11794
  );
11594
11795
  }
11595
11796
  scopeDetail = scope.detail;
@@ -11645,15 +11846,15 @@ function explainPath(config, target) {
11645
11846
  result.bytes = buffer.length;
11646
11847
  result.lines = countLines(text2);
11647
11848
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
11648
- const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative13);
11849
+ const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative14);
11649
11850
  result.secretCount = findings.length;
11650
11851
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
11651
11852
  let inclusionMode = "full";
11652
- if (config.skeleton === true && isSkeletonizable(relative13)) {
11653
- const skeleton = skeletonizeTypeScript(text2, relative13);
11853
+ if (config.skeleton === true && isSkeletonizable(relative14)) {
11854
+ const skeleton = skeletonizeTypeScript(text2, relative14);
11654
11855
  if (skeleton.collapsed > 0) inclusionMode = "signatures";
11655
11856
  }
11656
- if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative13) && stripComments2(text2, relative13).removed > 0) {
11857
+ if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative14) && stripComments2(text2, relative14).removed > 0) {
11657
11858
  inclusionMode = "comments-stripped";
11658
11859
  }
11659
11860
  if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
@@ -11662,18 +11863,18 @@ function explainPath(config, target) {
11662
11863
  }
11663
11864
  result.inclusionMode = inclusionMode;
11664
11865
  }
11665
- result.layer = classifyLayer(relative13, config.layers);
11666
- result.kind = classifyKind(relative13, config.kinds);
11667
- result.language = detectLanguage(relative13);
11668
- const layerRule = findRuleMatch(config.layers, relative13);
11866
+ result.layer = classifyLayer(relative14, config.layers);
11867
+ result.kind = classifyKind(relative14, config.kinds);
11868
+ result.language = detectLanguage(relative14);
11869
+ const layerRule = findRuleMatch(config.layers, relative14);
11669
11870
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
11670
- const kindRule = findRuleMatch(config.kinds, relative13);
11871
+ const kindRule = findRuleMatch(config.kinds, relative14);
11671
11872
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
11672
11873
  const manifest = readManifest2(config);
11673
- const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative13) : void 0;
11874
+ const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative14) : void 0;
11674
11875
  result.part = entry?.part ?? null;
11675
11876
  if (entry === void 0) {
11676
- const record = manifest?.skipped?.find((skip) => skip.path === relative13);
11877
+ const record = manifest?.skipped?.find((skip) => skip.path === relative14);
11677
11878
  if (record !== void 0 && (record.reason === "not-selected" || record.reason === "unchanged")) {
11678
11879
  result.included = false;
11679
11880
  result.reason = record.reason;
@@ -11738,6 +11939,7 @@ const { parentPort, workerData } = require("node:worker_threads");
11738
11939
  const manifest = mod.generateSnapshot(config, {
11739
11940
  dryRun: workerData.dryRun === true,
11740
11941
  ...(workerData.narrow ?? {}),
11942
+ ...(workerData.runId === undefined ? {} : { runId: workerData.runId }),
11741
11943
  });
11742
11944
  const skipCounts = new Map();
11743
11945
  for (const record of manifest.skipped) {
@@ -11783,8 +11985,13 @@ function generateInWorker(cwd, cliOptions, options = {}) {
11783
11985
  const finish = (result) => {
11784
11986
  if (settled) return;
11785
11987
  settled = true;
11786
- if (worker !== null) void worker.terminate();
11787
- resolve14(result);
11988
+ const terminated = worker === null ? Promise.resolve(void 0) : worker.terminate();
11989
+ void terminated.catch(() => void 0).then(() => {
11990
+ if (!result.ok && options.runId !== void 0 && options.lockRoots !== void 0) {
11991
+ releaseAbandonedRun(options.lockRoots, options.runId);
11992
+ }
11993
+ resolve14(result);
11994
+ });
11788
11995
  };
11789
11996
  const isCjs = typeof __dirname !== "undefined";
11790
11997
  const directory = isCjs ? __dirname : path25__namespace.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
@@ -11796,7 +12003,8 @@ function generateInWorker(cwd, cliOptions, options = {}) {
11796
12003
  cwd,
11797
12004
  cliOptions,
11798
12005
  dryRun: options.dryRun === true,
11799
- narrow: options.narrow ?? {}
12006
+ narrow: options.narrow ?? {},
12007
+ ...options.runId === void 0 ? {} : { runId: options.runId }
11800
12008
  }
11801
12009
  });
11802
12010
  } catch (error) {
@@ -11961,7 +12169,16 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
11961
12169
  if (overrides.withDependents === true) cliOptions.withDependents = true;
11962
12170
  try {
11963
12171
  const config = resolveConfig(loaded.config, cliOptions, root);
11964
- return { ok: true, workspace: { root, config, configFile: loaded.file, cliOptions } };
12172
+ return {
12173
+ ok: true,
12174
+ workspace: {
12175
+ root,
12176
+ config,
12177
+ configFile: loaded.file,
12178
+ sourceConfig: loaded.config ?? null,
12179
+ cliOptions
12180
+ }
12181
+ };
11965
12182
  } catch (error) {
11966
12183
  return { ok: false, message: error instanceof Error ? error.message : String(error) };
11967
12184
  }
@@ -11975,8 +12192,8 @@ function partPathFor(workspace, filename) {
11975
12192
  if (filename.length === 0 || filename.includes("\0")) return null;
11976
12193
  const partsDir = path25__namespace.resolve(workspace.root, workspace.config.outDir, "parts");
11977
12194
  const resolved = path25__namespace.resolve(partsDir, filename);
11978
- const relative13 = path25__namespace.relative(partsDir, resolved);
11979
- if (relative13.length === 0 || relative13.includes(path25__namespace.sep) || relative13.includes("/") || relative13.includes("\\") || path25__namespace.isAbsolute(relative13)) {
12195
+ const relative14 = path25__namespace.relative(partsDir, resolved);
12196
+ if (relative14.length === 0 || relative14.includes(path25__namespace.sep) || relative14.includes("/") || relative14.includes("\\") || path25__namespace.isAbsolute(relative14)) {
11980
12197
  return null;
11981
12198
  }
11982
12199
  let stats;
@@ -12150,11 +12367,11 @@ function toRelativePath(root, value) {
12150
12367
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
12151
12368
  const resolvedRoot = path25__namespace.resolve(root);
12152
12369
  const absolute = path25__namespace.resolve(resolvedRoot, cleaned);
12153
- const relative13 = path25__namespace.relative(resolvedRoot, absolute);
12154
- if (relative13 === "" || relative13 === ".." || relative13.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative13)) {
12370
+ const relative14 = path25__namespace.relative(resolvedRoot, absolute);
12371
+ if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path25__namespace.sep}`) || path25__namespace.isAbsolute(relative14)) {
12155
12372
  return null;
12156
12373
  }
12157
- return relative13.split(path25__namespace.sep).join("/");
12374
+ return relative14.split(path25__namespace.sep).join("/");
12158
12375
  }
12159
12376
  function symbolsOf(entry) {
12160
12377
  const summary = entry.summary;
@@ -12260,7 +12477,7 @@ var historyTool = {
12260
12477
  const manifestRead = readManifest3(prepared.workspace);
12261
12478
  const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
12262
12479
  if (recordedLog !== void 0 && recordedLog !== null) {
12263
- const digest = crypto2.createHash("sha256").update(text2, "utf8").digest("hex");
12480
+ const digest = crypto.createHash("sha256").update(text2, "utf8").digest("hex");
12264
12481
  if (digest !== recordedLog.sha256) {
12265
12482
  return {
12266
12483
  text: "reports/log.md changed after the snapshot was generated (its digest no longer matches the manifest). Regenerate the snapshot rather than trusting this history.",
@@ -12368,7 +12585,9 @@ var testsTool = {
12368
12585
  const cap = Math.max(1, typeof args.maxFiles === "number" ? args.maxFiles : 50);
12369
12586
  const isTest2 = (filePath) => /(^|\/)(tests?|__tests__|spec)\//.test(filePath) || /\.(test|spec)\.[a-z0-9]+$/i.test(filePath);
12370
12587
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath, file]));
12371
- const resolver = buildImportResolver(read.manifest.files, {});
12588
+ const resolver = buildImportResolver(read.manifest.files, {
12589
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
12590
+ });
12372
12591
  const testFiles = read.manifest.files.filter((file) => isTest2(file.relativePath));
12373
12592
  const importsOf = (filePath) => {
12374
12593
  const entry = read.manifest.indexes.imports.byFile.find((candidate) => candidate.path === filePath);
@@ -12416,9 +12635,13 @@ var workspaceTool = {
12416
12635
  },
12417
12636
  annotations: READ_ONLY,
12418
12637
  async handler(args, context) {
12419
- const root = path25__namespace.resolve(context.cwd, typeof args.root === "string" ? args.root : ".");
12420
- const outDir = typeof args.outDir === "string" ? args.outDir : "snapshot";
12421
- const index = path25__namespace.resolve(root, outDir, "WORKSPACE.json");
12638
+ const prepared = await prepare(args, context, outDirOverride(args));
12639
+ if (!prepared.ok) return prepared.outcome;
12640
+ const index = path25__namespace.resolve(
12641
+ prepared.workspace.root,
12642
+ prepared.workspace.config.outDir,
12643
+ "WORKSPACE.json"
12644
+ );
12422
12645
  let text2;
12423
12646
  try {
12424
12647
  text2 = fs24__namespace.readFileSync(index, "utf8");
@@ -12475,7 +12698,9 @@ var neighborsTool = {
12475
12698
  const file = read.manifest.files.find((candidate) => candidate.relativePath === wanted) ?? read.manifest.files.find((candidate) => candidate.relativePath.toLowerCase() === wanted.toLowerCase());
12476
12699
  if (file === void 0) return { text: wanted + " is not in the snapshot; snapshot_explain says why.", isError: true };
12477
12700
  const byPath = new Map(read.manifest.files.map((candidate) => [candidate.relativePath, candidate]));
12478
- const resolver = buildImportResolver(read.manifest.files, {});
12701
+ const resolver = buildImportResolver(read.manifest.files, {
12702
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
12703
+ });
12479
12704
  const entry = read.manifest.indexes.imports.byFile.find((candidate) => candidate.path === file.relativePath);
12480
12705
  const imports = [];
12481
12706
  for (const specifier of entry?.imports ?? []) {
@@ -12617,7 +12842,9 @@ var cyclesTool = {
12617
12842
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
12618
12843
  const cap = Math.max(1, typeof args.maxComponents === "number" ? args.maxComponents : 20);
12619
12844
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath, file]));
12620
- const resolver = buildImportResolver(read.manifest.files, {});
12845
+ const resolver = buildImportResolver(read.manifest.files, {
12846
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
12847
+ });
12621
12848
  const edges = /* @__PURE__ */ new Map();
12622
12849
  for (const path26 of byPath.keys()) edges.set(path26, []);
12623
12850
  for (const entry of read.manifest.indexes.imports.byFile) {
@@ -13817,10 +14044,17 @@ var generateTool = {
13817
14044
  ...typeof args.slice === "string" ? { slice: { question: args.slice, ...typeof args.sliceTokens === "number" ? { maxTokens: args.sliceTokens } : {} } } : {},
13818
14045
  ...typeof args.budgetTokens === "number" ? { budgetTokens: args.budgetTokens } : {}
13819
14046
  };
14047
+ let lockRoots;
14048
+ try {
14049
+ const safe = resolveSafeOutputDirs(workspace.config);
14050
+ lockRoots = [safe.outDir, safe.tmpDir];
14051
+ } catch (error) {
14052
+ return failure(error instanceof Error ? error.message : String(error));
14053
+ }
13820
14054
  const result = await generateInWorker(
13821
14055
  workspace.root,
13822
14056
  { ...workspace.cliOptions, ...reportOptions },
13823
- { signal: controller.signal, narrow }
14057
+ { signal: controller.signal, narrow, runId: crypto.randomUUID(), lockRoots }
13824
14058
  );
13825
14059
  if (!result.ok) return failure(result.message);
13826
14060
  context.notify?.({ message: "writing the snapshot", progress: 2, total: 2 });
@@ -13854,16 +14088,42 @@ var generateTool = {
13854
14088
  };
13855
14089
  function configAsGenerated(workspace, manifest) {
13856
14090
  const recorded = manifest.config;
14091
+ const cli = workspace.cliOptions;
14092
+ const source = workspace.sourceConfig;
14093
+ const configured = (key) => source !== null && Object.prototype.hasOwnProperty.call(source, key);
14094
+ const sourceArtifacts = source !== null && source.artifacts !== null && typeof source.artifacts === "object" ? source.artifacts : null;
14095
+ const artifacts = { ...workspace.config.artifacts };
14096
+ if (recorded?.artifacts !== void 0) {
14097
+ for (const [key, value] of Object.entries(recorded.artifacts)) {
14098
+ if (sourceArtifacts === null || !Object.prototype.hasOwnProperty.call(sourceArtifacts, key)) {
14099
+ artifacts[key] = value;
14100
+ }
14101
+ }
14102
+ }
14103
+ let artifactOverride = recorded?.artifacts !== void 0;
14104
+ if (cli.includeDiffs === true) {
14105
+ artifacts.diff = true;
14106
+ artifactOverride = true;
14107
+ }
14108
+ if (cli.includeLogs !== void 0) {
14109
+ artifacts.log = true;
14110
+ artifactOverride = true;
14111
+ }
14112
+ if (cli.tokenTree === true) {
14113
+ artifacts.tokenTree = true;
14114
+ artifactOverride = true;
14115
+ }
14116
+ const choose = (key, recordedValue, current, cliValue) => cliValue !== void 0 ? cliValue : configured(key) ? current : recordedValue ?? current;
13857
14117
  return {
13858
14118
  ...workspace.config,
13859
- ...recorded?.artifacts === void 0 ? {} : { artifacts: recorded.artifacts },
13860
- ...recorded?.stripComments === void 0 ? {} : { stripComments: recorded.stripComments },
13861
- ...recorded?.removeEmptyLines === void 0 ? {} : { removeEmptyLines: recorded.removeEmptyLines },
13862
- ...recorded?.pack === void 0 ? {} : { pack: recorded.pack },
13863
- ...recorded?.logCount === void 0 ? {} : { logCount: recorded.logCount },
13864
- ...recorded?.skeleton === void 0 ? {} : { skeleton: recorded.skeleton },
13865
- ...recorded?.sarif === void 0 ? {} : { sarif: recorded.sarif },
13866
- ...recorded?.maxParts === void 0 ? {} : { maxParts: recorded.maxParts }
14119
+ ...artifactOverride ? { artifacts } : {},
14120
+ ...cli.stripComments === true || configured("stripComments") || recorded?.stripComments !== void 0 ? { stripComments: choose("stripComments", recorded?.stripComments, workspace.config.stripComments, cli.stripComments === true ? true : void 0) } : {},
14121
+ ...cli.removeEmptyLines === true || configured("removeEmptyLines") || recorded?.removeEmptyLines !== void 0 ? { removeEmptyLines: choose("removeEmptyLines", recorded?.removeEmptyLines, workspace.config.removeEmptyLines, cli.removeEmptyLines === true ? true : void 0) } : {},
14122
+ ...cli.pack !== void 0 || configured("pack") || recorded?.pack !== void 0 ? { pack: choose("pack", recorded?.pack ?? void 0, workspace.config.pack, cli.pack) } : {},
14123
+ ...cli.includeLogs !== void 0 || configured("logCount") || recorded?.logCount !== void 0 ? { logCount: choose("logCount", recorded?.logCount, workspace.config.logCount, cli.includeLogs) } : {},
14124
+ ...cli.skeleton === true || configured("skeleton") || recorded?.skeleton !== void 0 ? { skeleton: choose("skeleton", recorded?.skeleton, workspace.config.skeleton, cli.skeleton === true ? true : void 0) } : {},
14125
+ ...cli.sarif === true || configured("sarif") || recorded?.sarif !== void 0 ? { sarif: choose("sarif", recorded?.sarif, workspace.config.sarif, cli.sarif === true ? true : void 0) } : {},
14126
+ ...configured("maxParts") || recorded?.maxParts !== void 0 ? { maxParts: choose("maxParts", recorded?.maxParts, workspace.config.maxParts) } : {}
13867
14127
  };
13868
14128
  }
13869
14129
  var validateTool = {
@@ -14100,7 +14360,9 @@ var dependentsTool = {
14100
14360
  }
14101
14361
  const direction = args.direction === "imports" || args.direction === "imported-by" ? String(args.direction) : "both";
14102
14362
  const limit = typeof args.limit === "number" && args.limit > 0 ? Math.floor(args.limit) : 50;
14103
- const resolver = buildImportResolver(manifest.files);
14363
+ const resolver = buildImportResolver(manifest.files, {
14364
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
14365
+ });
14104
14366
  const imports = [];
14105
14367
  const unresolved = [];
14106
14368
  if (direction !== "imported-by") {
@@ -15509,6 +15771,10 @@ function buildAgentContract() {
15509
15771
  { key: "maxPartBytes", type: "number | string", default: 307200, summary: "Per-part byte budget." },
15510
15772
  { key: "maxPartTokens", type: "number | string | null", default: null, summary: "Per-part token ceiling; narrows maxPartBytes. Minimum 1024." },
15511
15773
  { key: "skeleton", type: "boolean", default: false, summary: "Collapse function bodies to `{ /* ... */ }` in TS, JS, TSX and JSX files." },
15774
+ { key: "stripComments", type: "boolean", default: false, summary: "Remove comment text from JS/TS bodies." },
15775
+ { key: "removeEmptyLines", type: "boolean", default: false, summary: "Drop blank lines from emitted bodies; the part's line numbers move, and files[] records emptyLinesRemoved." },
15776
+ { key: "pack", type: '"single" | "xml" | "json" | null', default: null, summary: "Write one single-file pack in this format." },
15777
+ { key: "logCount", type: "number", default: 20, summary: "Commit lines in reports/log.md (also set by --include-logs <n>)." },
15512
15778
  { key: "sarif", type: "boolean", default: false, summary: "Also write reports/audit.sarif." },
15513
15779
  { key: "changedSince", type: "string | null", default: null, summary: "Snapshot only files that differ from this git ref." },
15514
15780
  { key: "staged", type: "boolean", default: false, summary: "Snapshot only files staged in the index." },
@@ -16491,9 +16757,9 @@ function dosDateTime(date) {
16491
16757
  function walkFiles(root, prefix = "") {
16492
16758
  const files = [];
16493
16759
  for (const entry of fs24__namespace.readdirSync(path25__namespace.join(root, prefix), { withFileTypes: true })) {
16494
- const relative13 = prefix === "" ? entry.name : prefix + "/" + entry.name;
16495
- if (entry.isDirectory()) files.push(...walkFiles(root, relative13));
16496
- else if (entry.isFile()) files.push(relative13);
16760
+ const relative14 = prefix === "" ? entry.name : prefix + "/" + entry.name;
16761
+ if (entry.isDirectory()) files.push(...walkFiles(root, relative14));
16762
+ else if (entry.isFile()) files.push(relative14);
16497
16763
  }
16498
16764
  return files;
16499
16765
  }
@@ -16501,11 +16767,11 @@ function writeZip(options) {
16501
16767
  const entries = [...options.entries ?? []];
16502
16768
  if (options.directory !== void 0) {
16503
16769
  const root = options.directory;
16504
- for (const relative13 of walkFiles(root)) {
16505
- if (options.skip !== void 0 && options.skip(relative13)) continue;
16506
- const full = path25__namespace.join(root, relative13);
16770
+ for (const relative14 of walkFiles(root)) {
16771
+ if (options.skip !== void 0 && options.skip(relative14)) continue;
16772
+ const full = path25__namespace.join(root, relative14);
16507
16773
  const stat = fs24__namespace.statSync(full);
16508
- entries.push({ name: relative13, content: fs24__namespace.readFileSync(full), mtime: stat.mtime });
16774
+ entries.push({ name: relative14, content: fs24__namespace.readFileSync(full), mtime: stat.mtime });
16509
16775
  }
16510
16776
  }
16511
16777
  if (entries.length > 65535) {
@@ -16698,8 +16964,13 @@ var SERVE_PAGE = `<!doctype html>
16698
16964
  $("counts").textContent = info.included + " included / " + info.skipped + " skipped";
16699
16965
  $("files").innerHTML = "";
16700
16966
  for (const file of info.files.slice(0, 400)) {
16967
+ // A manifest is untrusted input. Interpolating file.part (or a path) into innerHTML let a
16968
+ // crafted manifest run script in the serve origin and read the token from localStorage.
16701
16969
  const li = document.createElement("li");
16702
- li.innerHTML = "<b>" + file.path.replace(/[<>&]/g, "") + "</b> " + file.part;
16970
+ const name = document.createElement("b");
16971
+ name.textContent = file.path;
16972
+ li.appendChild(name);
16973
+ li.appendChild(document.createTextNode(" " + file.part));
16703
16974
  $("files").appendChild(li);
16704
16975
  }
16705
16976
  }
@@ -16732,20 +17003,59 @@ async function startWebServer(options) {
16732
17003
  const host = options.host ?? "127.0.0.1";
16733
17004
  const port = options.port ?? DEFAULT_PORT;
16734
17005
  const log = options.log ?? ((line) => process.stderr.write(line + "\n"));
16735
- const token = options.token === void 0 ? crypto2.randomBytes(18).toString("base64url") : options.token;
17006
+ const token = options.token === void 0 ? crypto.randomBytes(18).toString("base64url") : options.token;
16736
17007
  if (token === null && !["127.0.0.1", "localhost", "::1"].includes(host)) {
16737
17008
  throw new Error("Refusing to serve " + host + " without a token.");
16738
17009
  }
16739
- const mcp = createServer({ cwd: options.cwd, log });
17010
+ const createMcp = () => createServer({ cwd: options.cwd, log });
17011
+ const mcpPerSocket = /* @__PURE__ */ new WeakMap();
17012
+ const mcpFor = (socket) => {
17013
+ let server2 = mcpPerSocket.get(socket);
17014
+ if (server2 === void 0) {
17015
+ server2 = createMcp();
17016
+ mcpPerSocket.set(socket, server2);
17017
+ }
17018
+ return server2;
17019
+ };
16740
17020
  const temporaryClones = /* @__PURE__ */ new Set();
16741
17021
  const allowedRoots = [path25__namespace.resolve(options.cwd)];
17022
+ const canonical = (candidate) => {
17023
+ try {
17024
+ return fs24__namespace.realpathSync(candidate);
17025
+ } catch {
17026
+ return null;
17027
+ }
17028
+ };
17029
+ const inside = (resolved) => allowedRoots.some((root) => {
17030
+ const canonicalRoot = canonical(root);
17031
+ if (canonicalRoot === null) return false;
17032
+ const relative14 = path25__namespace.relative(canonicalRoot, resolved);
17033
+ return relative14 === "" || !relative14.startsWith(`..${path25__namespace.sep}`) && relative14 !== ".." && !path25__namespace.isAbsolute(relative14);
17034
+ });
16742
17035
  const insideAllowedRoots = (candidate) => {
17036
+ const resolved = canonical(candidate);
17037
+ return resolved === null ? false : inside(resolved);
17038
+ };
17039
+ const lexicallyInside = (candidate) => {
16743
17040
  const resolved = path25__namespace.resolve(candidate);
16744
17041
  return allowedRoots.some((root) => {
16745
- const prefix = root.endsWith(path25__namespace.sep) ? root : root + path25__namespace.sep;
16746
- return resolved === root || resolved.startsWith(prefix);
17042
+ const prefix = path25__namespace.resolve(root) + path25__namespace.sep;
17043
+ return resolved === path25__namespace.resolve(root) || resolved.startsWith(prefix);
16747
17044
  });
16748
17045
  };
17046
+ const insideAllowedRootsForWrite = (candidate) => {
17047
+ let existing = path25__namespace.resolve(candidate);
17048
+ const tail = [];
17049
+ while (!fs24__namespace.existsSync(existing)) {
17050
+ tail.unshift(path25__namespace.basename(existing));
17051
+ const parent = path25__namespace.dirname(existing);
17052
+ if (parent === existing) break;
17053
+ existing = parent;
17054
+ }
17055
+ const resolved = canonical(existing);
17056
+ if (resolved === null) return false;
17057
+ return inside(tail.length === 0 ? resolved : path25__namespace.join(resolved, ...tail));
17058
+ };
16749
17059
  const authorized = (request) => {
16750
17060
  if (token === null) return true;
16751
17061
  const header = request.headers.authorization ?? "";
@@ -16753,7 +17063,7 @@ async function startWebServer(options) {
16753
17063
  if (match === null) return false;
16754
17064
  const given = Buffer.from(match[1].trim(), "utf8");
16755
17065
  const expected = Buffer.from(token, "utf8");
16756
- return given.length === expected.length && crypto2.timingSafeEqual(given, expected);
17066
+ return given.length === expected.length && crypto.timingSafeEqual(given, expected);
16757
17067
  };
16758
17068
  const server = http__namespace.createServer((request, response) => {
16759
17069
  const origin = typeof request.headers.origin === "string" ? request.headers.origin : void 0;
@@ -16769,7 +17079,10 @@ async function startWebServer(options) {
16769
17079
  cors["access-control-allow-headers"] = "authorization, content-type";
16770
17080
  cors["access-control-allow-methods"] = "GET, POST, OPTIONS";
16771
17081
  }
17082
+ let responseSent = false;
16772
17083
  const send = (status, body, extra = {}) => {
17084
+ if (responseSent) return;
17085
+ responseSent = true;
16773
17086
  const text2 = typeof body === "string" ? body : JSON.stringify(body);
16774
17087
  response.writeHead(status, {
16775
17088
  ...cors,
@@ -16800,10 +17113,13 @@ async function startWebServer(options) {
16800
17113
  const url = new URL(request.url ?? "/", "http://localhost");
16801
17114
  if (request.method === "POST" && (request.url === "/mcp" || (request.url ?? "").startsWith("/mcp?"))) {
16802
17115
  let received = 0;
17116
+ let tooLarge = false;
16803
17117
  const chunks = [];
16804
17118
  request.on("data", (chunk) => {
17119
+ if (tooLarge) return;
16805
17120
  received += chunk.length;
16806
17121
  if (received > 2 * 1024 * 1024) {
17122
+ tooLarge = true;
16807
17123
  request.destroy();
16808
17124
  send(413, { error: "request body too large" });
16809
17125
  return;
@@ -16811,6 +17127,7 @@ async function startWebServer(options) {
16811
17127
  chunks.push(chunk);
16812
17128
  });
16813
17129
  request.on("end", () => {
17130
+ if (tooLarge) return;
16814
17131
  void (async () => {
16815
17132
  let message;
16816
17133
  try {
@@ -16820,9 +17137,14 @@ async function startWebServer(options) {
16820
17137
  return;
16821
17138
  }
16822
17139
  const batch = Array.isArray(message) ? message : [message];
17140
+ if (batch.length > 100) {
17141
+ send(400, { error: "JSON-RPC batch is limited to 100 messages" });
17142
+ return;
17143
+ }
17144
+ const server2 = mcpFor(request.socket);
16823
17145
  const answers = [];
16824
17146
  for (const item of batch) {
16825
- const answer = await mcp.handle(item);
17147
+ const answer = await server2.handle(item);
16826
17148
  if (answer !== null) answers.push(answer);
16827
17149
  }
16828
17150
  if (answers.length === 0) send(202, "");
@@ -16833,10 +17155,13 @@ async function startWebServer(options) {
16833
17155
  }
16834
17156
  if (request.method === "POST" && request.url === "/api/generate") {
16835
17157
  let received = 0;
17158
+ let tooLarge = false;
16836
17159
  const chunks = [];
16837
17160
  request.on("data", (chunk) => {
17161
+ if (tooLarge) return;
16838
17162
  received += chunk.length;
16839
17163
  if (received > MAX_BODY) {
17164
+ tooLarge = true;
16840
17165
  request.destroy();
16841
17166
  send(413, { error: "request body too large" });
16842
17167
  return;
@@ -16844,6 +17169,7 @@ async function startWebServer(options) {
16844
17169
  chunks.push(chunk);
16845
17170
  });
16846
17171
  request.on("end", () => {
17172
+ if (tooLarge) return;
16847
17173
  void (async () => {
16848
17174
  let source = "";
16849
17175
  let mode = "full";
@@ -16900,6 +17226,10 @@ async function startWebServer(options) {
16900
17226
  }
16901
17227
  } else {
16902
17228
  target = path25__namespace.resolve(options.cwd, source);
17229
+ if (!insideAllowedRoots(target)) {
17230
+ send(403, { error: "outside the served directory: " + target });
17231
+ return;
17232
+ }
16903
17233
  }
16904
17234
  let stat;
16905
17235
  try {
@@ -16917,15 +17247,26 @@ async function startWebServer(options) {
16917
17247
  send(400, { error: loaded.errors.join("; ") });
16918
17248
  return;
16919
17249
  }
17250
+ const runConfig = isRemote ? {
17251
+ ...loaded.config ?? {},
17252
+ outDir: "snapshot",
17253
+ tmpDir: "snapshot.tmp",
17254
+ hooks: {}
17255
+ } : loaded.config ?? {};
17256
+ const configuredOutDir = typeof runConfig.outDir === "string" && runConfig.outDir.trim() !== "" ? runConfig.outDir : "snapshot";
17257
+ const snapshotDir = path25__namespace.resolve(target, configuredOutDir);
17258
+ if (!insideAllowedRootsForWrite(snapshotDir)) {
17259
+ send(403, { error: "the configured outDir resolves outside the served directory" });
17260
+ return;
17261
+ }
16920
17262
  const started = Date.now();
16921
17263
  try {
16922
- const manifest = generateSnapshot({ ...loaded.config ?? {}, cwd: target }, {
17264
+ const manifest = generateSnapshot({ ...runConfig, cwd: target }, {
16923
17265
  ...provenance === void 0 ? {} : { source: provenance },
16924
17266
  ...mode === "slice" ? { slice: { question } } : {},
16925
17267
  ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
16926
17268
  });
16927
17269
  const seconds = ((Date.now() - started) / 1e3).toFixed(2);
16928
- const snapshotDir = path25__namespace.join(target, "snapshot");
16929
17270
  const health = auditSnapshot({ snapshotDir, repoDir: target });
16930
17271
  send(200, {
16931
17272
  path: snapshotDir,
@@ -16953,7 +17294,7 @@ async function startWebServer(options) {
16953
17294
  }
16954
17295
  if (request.method === "GET" && request.url?.startsWith("/api/health?") === true) {
16955
17296
  const target = path25__namespace.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
16956
- if (!insideAllowedRoots(target)) {
17297
+ if (!lexicallyInside(target)) {
16957
17298
  send(403, { error: "outside the served directory: " + target });
16958
17299
  return;
16959
17300
  }
@@ -16961,12 +17302,24 @@ async function startWebServer(options) {
16961
17302
  send(404, { error: "no manifest.json under " + target });
16962
17303
  return;
16963
17304
  }
17305
+ if (!insideAllowedRoots(target)) {
17306
+ send(403, { error: "outside the served directory: " + target });
17307
+ return;
17308
+ }
16964
17309
  const report2 = auditSnapshot({ snapshotDir: target, repoDir: path25__namespace.dirname(target) });
16965
17310
  send(200, { score: report2.score, counts: report2.counts, checks: report2.checks });
16966
17311
  return;
16967
17312
  }
16968
17313
  if (request.method === "GET" && (request.url?.startsWith("/api/snapshot?") === true || request.url === "/api/snapshot")) {
16969
17314
  const target = path25__namespace.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17315
+ if (!lexicallyInside(target)) {
17316
+ send(403, { error: "outside the served directory: " + target });
17317
+ return;
17318
+ }
17319
+ if (!fs24__namespace.existsSync(path25__namespace.join(target, "manifest.json"))) {
17320
+ send(404, { error: "no manifest.json under " + target });
17321
+ return;
17322
+ }
16970
17323
  if (!insideAllowedRoots(target)) {
16971
17324
  send(403, { error: "outside the served directory: " + target });
16972
17325
  return;
@@ -16979,6 +17332,11 @@ async function startWebServer(options) {
16979
17332
  send(404, { error: "no manifest.json under " + target });
16980
17333
  return;
16981
17334
  }
17335
+ const shapeProblem = describeManifestShapeProblem(manifest);
17336
+ if (shapeProblem !== null) {
17337
+ send(400, { error: "manifest.json is not a snapshot manifest: " + shapeProblem });
17338
+ return;
17339
+ }
16982
17340
  let prompt = "";
16983
17341
  try {
16984
17342
  prompt = fs24__namespace.readFileSync(path25__namespace.join(target, "PROMPT.md"), "utf8").slice(0, MAX_PREVIEW);
@@ -16998,7 +17356,7 @@ async function startWebServer(options) {
16998
17356
  }
16999
17357
  if (request.method === "GET" && request.url?.startsWith("/api/snapshot.zip") === true) {
17000
17358
  const target = path25__namespace.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17001
- if (!insideAllowedRoots(target)) {
17359
+ if (!lexicallyInside(target)) {
17002
17360
  send(403, { error: "outside the served directory: " + target });
17003
17361
  return;
17004
17362
  }
@@ -17006,6 +17364,10 @@ async function startWebServer(options) {
17006
17364
  send(404, { error: "not a snapshot directory: " + target });
17007
17365
  return;
17008
17366
  }
17367
+ if (!insideAllowedRoots(target)) {
17368
+ send(403, { error: "outside the served directory: " + target });
17369
+ return;
17370
+ }
17009
17371
  try {
17010
17372
  const zip = writeZip({ directory: target });
17011
17373
  response.writeHead(200, {
@@ -17751,9 +18113,17 @@ function renderConfig(answers) {
17751
18113
  // Replace function and method bodies with \`{ /* ... */ }\` in TypeScript files.
17752
18114
  // Signatures and comments stay, so the structure of the file survives.
17753
18115
  skeleton: ${answers.skeleton},
18116
+ // Remove comment text from JavaScript and TypeScript bodies.
18117
+ stripComments: false,
18118
+ // Drop blank lines from emitted bodies; line numbers in the part move.
18119
+ removeEmptyLines: false,
17754
18120
  // Also write reports/audit.sarif (SARIF 2.1.0) for a CI security gate. The
17755
18121
  // matched value is never included \u2014 only the path, the line and the rule.
17756
18122
  sarif: ${answers.sarif},
18123
+ // Commit lines in reports/log.md when the log artifact is enabled.
18124
+ logCount: 20,
18125
+ // Write one single-file pack: "single", "xml" or "json". null = no pack.
18126
+ pack: null,
17757
18127
  // Snapshot only the files that differ from a git ref (for example "main"),
17758
18128
  // plus untracked ones. null means "snapshot everything"; any other value must
17759
18129
  // be a git ref string, and anything else is a configuration error.
@@ -18427,11 +18797,11 @@ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
18427
18797
  const entries = [];
18428
18798
  for (const directory of [outDir, tmpDir]) {
18429
18799
  if (directory === null) continue;
18430
- const relative13 = path25__namespace.relative(cwd, path25__namespace.resolve(cwd, directory)).replace(/\\/g, "/");
18431
- if (relative13 === "" || relative13 === "." || relative13.startsWith("..") || path25__namespace.isAbsolute(relative13)) {
18800
+ const relative14 = path25__namespace.relative(cwd, path25__namespace.resolve(cwd, directory)).replace(/\\/g, "/");
18801
+ if (relative14 === "" || relative14 === "." || relative14.startsWith("..") || path25__namespace.isAbsolute(relative14)) {
18432
18802
  continue;
18433
18803
  }
18434
- entries.push(`/${relative13}/`);
18804
+ entries.push(`/${relative14}/`);
18435
18805
  }
18436
18806
  return [...new Set(entries)];
18437
18807
  }
@@ -18762,10 +19132,10 @@ async function runInit(options) {
18762
19132
  };
18763
19133
  }
18764
19134
  function describeTarget(cwd) {
18765
- const relative13 = path25__namespace.relative(process.cwd(), cwd);
18766
- if (relative13 === "") return "this directory";
18767
- if (relative13.startsWith("..") || path25__namespace.isAbsolute(relative13)) return cwd;
18768
- return relative13;
19135
+ const relative14 = path25__namespace.relative(process.cwd(), cwd);
19136
+ if (relative14 === "") return "this directory";
19137
+ if (relative14.startsWith("..") || path25__namespace.isAbsolute(relative14)) return cwd;
19138
+ return relative14;
18769
19139
  }
18770
19140
  function firstRunMessage(reason, cwd) {
18771
19141
  const where = describeTarget(cwd);
@@ -18867,8 +19237,8 @@ function gitDirectory(cwd) {
18867
19237
  }
18868
19238
  }
18869
19239
  function isInside3(parent, child) {
18870
- const relative13 = path25__namespace.relative(parent, child);
18871
- return relative13 === "" || !relative13.startsWith("..") && !path25__namespace.isAbsolute(relative13);
19240
+ const relative14 = path25__namespace.relative(parent, child);
19241
+ return relative14 === "" || !relative14.startsWith("..") && !path25__namespace.isAbsolute(relative14);
18872
19242
  }
18873
19243
  function isRegisteredWorktree(gitDir, cwd) {
18874
19244
  try {
@@ -19107,7 +19477,7 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
19107
19477
  };
19108
19478
  }
19109
19479
  function sha256Hex2(input) {
19110
- return crypto2__namespace.createHash("sha256").update(input).digest("hex");
19480
+ return crypto__namespace.createHash("sha256").update(input).digest("hex");
19111
19481
  }
19112
19482
  var TS_EXTENSIONS = [
19113
19483
  ".ts",
@@ -19320,7 +19690,7 @@ function maskPathText(value, secretRules) {
19320
19690
  }
19321
19691
  function maskOwnerBrief(brief, secretRules) {
19322
19692
  if (brief === void 0) return void 0;
19323
- const mask = (value) => maskPathText(value, secretRules);
19693
+ const mask = (value) => scanAndRedactSecrets(value, secretRules ?? [], "owner-brief").redacted;
19324
19694
  return {
19325
19695
  ...brief,
19326
19696
  path: mask(brief.path),
@@ -19366,9 +19736,9 @@ function listEntries(dir) {
19366
19736
  return;
19367
19737
  }
19368
19738
  for (const child of children) {
19369
- const relative13 = prefix === "" ? child.name : `${prefix}/${child.name}`;
19370
- entries.push(relative13);
19371
- if (child.isDirectory()) walk2(path25__namespace.join(absolute, child.name), relative13);
19739
+ const relative14 = prefix === "" ? child.name : `${prefix}/${child.name}`;
19740
+ entries.push(relative14);
19741
+ if (child.isDirectory()) walk2(path25__namespace.join(absolute, child.name), relative14);
19372
19742
  }
19373
19743
  };
19374
19744
  walk2(dir, "");
@@ -19403,7 +19773,7 @@ function markerInventory(dir, written) {
19403
19773
  }
19404
19774
  return { entries, files };
19405
19775
  }
19406
- function markerPayload(dir, state, id, createdAt, written) {
19776
+ function markerPayload(dir, state, id, createdAt, written, runId) {
19407
19777
  const { entries, files } = markerInventory(dir, written);
19408
19778
  const marker2 = {
19409
19779
  generator: GENERATOR_NAME,
@@ -19412,6 +19782,7 @@ function markerPayload(dir, state, id, createdAt, written) {
19412
19782
  createdAt,
19413
19783
  state,
19414
19784
  id,
19785
+ ...runId === void 0 ? {} : { runId },
19415
19786
  pid: process.pid,
19416
19787
  entries,
19417
19788
  files
@@ -19509,6 +19880,7 @@ function readOwnershipMarker(dir) {
19509
19880
  createdAt: typeof candidate.createdAt === "string" ? candidate.createdAt : "unknown",
19510
19881
  state: candidate.state,
19511
19882
  id: candidate.id,
19883
+ runId: typeof candidate.runId === "string" ? candidate.runId : void 0,
19512
19884
  pid: typeof candidate.pid === "number" ? candidate.pid : void 0,
19513
19885
  manifestSha256: typeof candidate.manifestSha256 === "string" ? candidate.manifestSha256 : void 0,
19514
19886
  entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0,
@@ -19667,13 +20039,19 @@ function assessSnapshotDirectory(dir) {
19667
20039
  };
19668
20040
  }
19669
20041
  const entries = listEntries(dir);
19670
- const foreignEntries = entries.filter(
20042
+ let foreignEntries = entries.filter(
19671
20043
  (entry) => !recorded.has(entry) && !isIgnorableEntry(entry)
19672
20044
  );
20045
+ const legacySignatureOnly = foreignEntries.length === 1 && foreignEntries[0] === SIGNATURE_FILE && verifySnapshotSignature(dir).ok;
20046
+ if (legacySignatureOnly) foreignEntries = [];
19673
20047
  if (foreignEntries.length > 0) {
19674
20048
  return { owned: false, problem: null, foreignEntries, marker: marker2 };
19675
20049
  }
19676
- const inventoryProblem = marker2.files === void 0 ? null : verifyMarkerInventory(dir, entries, marker2.files);
20050
+ const inventoryProblem = marker2.files === void 0 ? null : verifyMarkerInventory(
20051
+ dir,
20052
+ legacySignatureOnly ? entries.filter((entry) => entry !== SIGNATURE_FILE) : entries,
20053
+ marker2.files
20054
+ );
19677
20055
  return {
19678
20056
  owned: inventoryProblem === null,
19679
20057
  problem: inventoryProblem,
@@ -19851,13 +20229,13 @@ function startLockHeartbeat(lockPath) {
19851
20229
  return () => void 0;
19852
20230
  }
19853
20231
  }
19854
- function acquireRunLock(stagingRoot) {
20232
+ function acquireRunLock(stagingRoot, runId) {
19855
20233
  const lockPath = lockPathFor(stagingRoot);
19856
20234
  const payload = `${JSON.stringify({
19857
20235
  pid: process.pid,
19858
20236
  stagingRoot,
19859
20237
  host: os2__namespace.hostname(),
19860
- runId: crypto2__namespace.randomUUID(),
20238
+ runId,
19861
20239
  heartbeatMs: LOCK_HEARTBEAT_MS,
19862
20240
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
19863
20241
  })}
@@ -19911,6 +20289,33 @@ function canonicalLockTarget(targetPath) {
19911
20289
  function lockPathFor(stagingRoot) {
19912
20290
  return path25__namespace.join(os2__namespace.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
19913
20291
  }
20292
+ function releaseAbandonedRun(stagingRoots, runId) {
20293
+ if (runId.length === 0) return;
20294
+ for (const root of new Set(stagingRoots)) {
20295
+ const lockPath = lockPathFor(root);
20296
+ try {
20297
+ const payload = JSON.parse(fs24__namespace.readFileSync(lockPath, "utf8"));
20298
+ if (payload.runId === runId) fs24__namespace.rmSync(lockPath, { force: true });
20299
+ } catch {
20300
+ }
20301
+ let entries;
20302
+ try {
20303
+ entries = fs24__namespace.readdirSync(root);
20304
+ } catch {
20305
+ continue;
20306
+ }
20307
+ for (const name of entries) {
20308
+ if (!name.startsWith(RUN_DIR_PREFIX)) continue;
20309
+ const directory = path25__namespace.join(root, name);
20310
+ const { marker: marker2 } = readOwnershipMarker(directory);
20311
+ if (marker2?.runId !== runId) continue;
20312
+ try {
20313
+ fs24__namespace.rmSync(directory, { recursive: true, force: true });
20314
+ } catch {
20315
+ }
20316
+ }
20317
+ }
20318
+ }
19914
20319
  function lockHeartbeatAgeMs(lockPath) {
19915
20320
  try {
19916
20321
  return Date.now() - fs24__namespace.statSync(lockPath).mtimeMs;
@@ -20225,6 +20630,7 @@ function generateSnapshot(configInput, options) {
20225
20630
  assertUsableConfigInput(configInput);
20226
20631
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
20227
20632
  const dryRun = options?.dryRun ?? false;
20633
+ const runId = options?.runId ?? crypto__namespace.randomUUID();
20228
20634
  const gitInfo = getGitInfo(config.cwd, config.branch);
20229
20635
  const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
20230
20636
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
@@ -20244,7 +20650,7 @@ function generateSnapshot(configInput, options) {
20244
20650
  // output — but only at these exact paths, not at every directory that shares the name.
20245
20651
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
20246
20652
  (directory) => path25__namespace.relative(config.cwd, path25__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
20247
- ).filter((relative13) => relative13.length > 0 && !relative13.startsWith("..")),
20653
+ ).filter((relative14) => relative14.length > 0 && !relative14.startsWith("..")),
20248
20654
  // A staged path can be absent from the working tree while its index blob exists. Discovery
20249
20655
  // lists the working tree, so those paths would never reach the scan at all.
20250
20656
  ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
@@ -20931,9 +21337,13 @@ function generateSnapshot(configInput, options) {
20931
21337
  if (navigationText !== null) manifest.artifacts.navigation = artifactRecord(navigationText);
20932
21338
  const auditText = artifacts.audit ? generateAuditReport(manifest, secretFindings, config.secretRules) : null;
20933
21339
  if (auditText !== null) manifest.artifacts.audit = artifactRecord(auditText);
20934
- const diffReport = artifacts.diff ? generateDiffReport(config.cwd) : null;
21340
+ const reportExcludes = [...config.excludePatterns, ...config.presetExclude];
21341
+ const diffReport = artifacts.diff ? generateDiffReport(config.cwd, {
21342
+ secretRules: config.secretRules,
21343
+ excluded: (relativePath) => reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
21344
+ }) : null;
20935
21345
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
20936
- const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount }) : null;
21346
+ const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount, secretRules: config.secretRules }) : null;
20937
21347
  if (artifacts.diff && diffReport === null && !isGitRepository(config.cwd)) {
20938
21348
  manifest.warnings.push(
20939
21349
  "--include-diffs was requested, but the generated directory is not a git repository; reports/diff.md was not written."
@@ -20977,7 +21387,8 @@ function generateSnapshot(configInput, options) {
20977
21387
  const entry = {
20978
21388
  ...file,
20979
21389
  content,
20980
- inclusionMode: "full",
21390
+ inclusionMode: file.inclusionMode === "comments-stripped" ? "comments-stripped" : "full",
21391
+ ...file.emptyLinesRemoved === true ? { emptyLinesRemoved: true } : {},
20981
21392
  isPreviewTruncated: false,
20982
21393
  includedBytes: Buffer.byteLength(content, "utf8"),
20983
21394
  includedLines: countLines(content)
@@ -21045,7 +21456,7 @@ function generateSnapshot(configInput, options) {
21045
21456
  const lockKeys = Array.from(/* @__PURE__ */ new Set([tmpDir, outDir])).sort();
21046
21457
  const releases = [];
21047
21458
  try {
21048
- for (const key of lockKeys) releases.push(acquireRunLock(key));
21459
+ for (const key of lockKeys) releases.push(acquireRunLock(key, runId));
21049
21460
  } catch (error) {
21050
21461
  for (const release of [...releases].reverse()) release();
21051
21462
  throw error;
@@ -21061,7 +21472,7 @@ function generateSnapshot(configInput, options) {
21061
21472
  ensureParentDirectory(outDir, "outDir");
21062
21473
  fs24__namespace.mkdirSync(tmpDir, { recursive: true });
21063
21474
  cleanStaleRunDirs(tmpDir);
21064
- const snapshotId = crypto2__namespace.randomUUID();
21475
+ const snapshotId = crypto__namespace.randomUUID();
21065
21476
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
21066
21477
  stagingDir = path25__namespace.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
21067
21478
  fs24__namespace.mkdirSync(stagingDir);
@@ -21072,6 +21483,7 @@ function generateSnapshot(configInput, options) {
21072
21483
  createdAt,
21073
21484
  state: "staging",
21074
21485
  id: snapshotId,
21486
+ runId,
21075
21487
  pid: process.pid
21076
21488
  });
21077
21489
  const partsDir = path25__namespace.join(stagingDir, "parts");
@@ -21140,6 +21552,17 @@ function generateSnapshot(configInput, options) {
21140
21552
  if (artifacts.manifest) {
21141
21553
  writeArtifact(stagingDir, "manifest.json", JSON.stringify(manifest, null, 2));
21142
21554
  }
21555
+ if (options?.sign !== void 0) {
21556
+ if (!artifacts.manifest) {
21557
+ throw new Error(
21558
+ "Refusing to sign: manifest.json is disabled for this run. Signing covers the manifest, so enable the manifest artifact or drop --sign."
21559
+ );
21560
+ }
21561
+ const record = signManifest(path25__namespace.join(stagingDir, "manifest.json"), {
21562
+ key: options.sign.key ?? null
21563
+ });
21564
+ writeArtifact(stagingDir, SIGNATURE_FILE, JSON.stringify(record, null, 2) + "\n");
21565
+ }
21143
21566
  if (monolithJson !== null) {
21144
21567
  writeArtifact(stagingDir, "full-codebase.json", monolithJson);
21145
21568
  }
@@ -21151,7 +21574,7 @@ function generateSnapshot(configInput, options) {
21151
21574
  }
21152
21575
  writeOwnershipMarker(
21153
21576
  stagingDir,
21154
- markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts)
21577
+ markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21155
21578
  );
21156
21579
  swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
21157
21580
  stagingDir = null;
@@ -21162,10 +21585,16 @@ function generateSnapshot(configInput, options) {
21162
21585
  if (artifacts.manifest && manifest.warnings.length !== warningsBeforeHook) {
21163
21586
  writeManifestAtomically(path25__namespace.join(outDir, "manifest.json"), manifest);
21164
21587
  recordArtifact(outDir, "manifest.json");
21588
+ if (options?.sign !== void 0) {
21589
+ const record = signManifest(path25__namespace.join(outDir, "manifest.json"), {
21590
+ key: options.sign.key ?? null
21591
+ });
21592
+ writeArtifact(outDir, SIGNATURE_FILE, JSON.stringify(record, null, 2) + "\n");
21593
+ }
21165
21594
  }
21166
21595
  writeOwnershipMarker(
21167
21596
  outDir,
21168
- markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts)
21597
+ markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21169
21598
  );
21170
21599
  };
21171
21600
  if (config.hooks.afterGenerate) shipHookState();
@@ -21322,6 +21751,7 @@ exports.parseRemoteSource = parseRemoteSource;
21322
21751
  exports.partitionFiles = partitionFiles;
21323
21752
  exports.planFirstRun = planFirstRun;
21324
21753
  exports.profileForPath = profileForPath;
21754
+ exports.releaseAbandonedRun = releaseAbandonedRun;
21325
21755
  exports.renderConfig = renderConfig;
21326
21756
  exports.renderDiffText = renderDiffText;
21327
21757
  exports.renderExplainText = renderExplainText;
@@ -21342,6 +21772,7 @@ exports.summarizeMarkdown = summarizeMarkdown;
21342
21772
  exports.summarizeTypeScriptSource = summarizeTypeScriptSource;
21343
21773
  exports.summarizeWithProfile = summarizeWithProfile;
21344
21774
  exports.supportsTypeScriptImports = supportsTypeScriptImports;
21775
+ exports.tokenAllowedForHost = tokenAllowedForHost;
21345
21776
  exports.treeTruncationWarnings = treeTruncationWarnings;
21346
21777
  exports.truncatePreview = truncatePreview;
21347
21778
  exports.truncateToBytes = truncateToBytes;