codebase-snapshot 0.20.3 → 0.20.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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.3";
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
  }
@@ -10262,9 +10458,9 @@ function secretTokens(text2) {
10262
10458
  }
10263
10459
  function readArtifactTexts(snapshotDir) {
10264
10460
  const texts = [];
10265
- for (const relative13 of walk(snapshotDir)) {
10266
- if (!TEXT_ARTIFACT.test(relative13)) continue;
10267
- const text2 = readText2(path25__namespace.join(snapshotDir, relative13));
10461
+ for (const relative14 of walk(snapshotDir)) {
10462
+ if (!TEXT_ARTIFACT.test(relative14)) continue;
10463
+ const text2 = readText2(path25__namespace.join(snapshotDir, relative14));
10268
10464
  if (text2 !== null) texts.push(text2);
10269
10465
  }
10270
10466
  return texts;
@@ -10280,15 +10476,15 @@ function findHostPaths(snapshotDir, repoDir) {
10280
10476
  ];
10281
10477
  const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
10282
10478
  const hits = /* @__PURE__ */ new Set();
10283
- for (const relative13 of walk(snapshotDir)) {
10284
- if (!TEXT_ARTIFACT.test(relative13)) continue;
10285
- 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));
10286
10482
  if (text2 === null) continue;
10287
10483
  for (const pattern of patterns) {
10288
- for (const match of text2.match(pattern) ?? []) hits.add(relative13 + ": " + match);
10484
+ for (const match of text2.match(pattern) ?? []) hits.add(relative14 + ": " + match);
10289
10485
  }
10290
10486
  repoPattern.lastIndex = 0;
10291
- if (repoPattern.test(text2)) hits.add(relative13 + ": the repository absolute path");
10487
+ if (repoPattern.test(text2)) hits.add(relative14 + ": the repository absolute path");
10292
10488
  }
10293
10489
  return [...hits];
10294
10490
  }
@@ -10535,13 +10731,13 @@ function auditSnapshot(options) {
10535
10731
  let artifactCount = 0;
10536
10732
  for (const [key, value] of Object.entries(artifacts)) {
10537
10733
  if (value === null || value === void 0) continue;
10538
- const relative13 = ARTIFACT_FILES[key];
10539
- if (relative13 === void 0) continue;
10734
+ const relative14 = ARTIFACT_FILES[key];
10735
+ if (relative14 === void 0) continue;
10540
10736
  artifactCount += 1;
10541
- const bytes = readBytes(path25__namespace.join(snapshotDir, relative13));
10542
- 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");
10543
10739
  else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
10544
- artifactProblems.push(relative13 + " changed");
10740
+ artifactProblems.push(relative14 + " changed");
10545
10741
  }
10546
10742
  }
10547
10743
  checks.push(
@@ -11271,25 +11467,25 @@ function auditSnapshot(options) {
11271
11467
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
11272
11468
  const leakHits = [];
11273
11469
  let scannedBytes = 0;
11274
- for (const relative13 of walk(snapshotDir)) {
11275
- if (!TEXT_ARTIFACT.test(relative13) || scannedBytes > scanBudget) continue;
11276
- if (relative13 === SIGNATURE_FILE) continue;
11277
- 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));
11278
11474
  if (text2 === null) continue;
11279
11475
  scannedBytes += Buffer.byteLength(text2, "utf8");
11280
11476
  let findingCount = 0;
11281
- if (/^parts[\\/].*\.md$/i.test(relative13)) {
11477
+ if (/^parts[\\/].*\.md$/i.test(relative14)) {
11282
11478
  let headerText = text2;
11283
11479
  for (const section of parsePartSections(text2)) {
11284
11480
  findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
11285
11481
  headerText = headerText.replace(section.body, "");
11286
11482
  }
11287
- findingCount += scanAndRedactSecrets(headerText, rules, relative13).findings.length;
11483
+ findingCount += scanAndRedactSecrets(headerText, rules, relative14).findings.length;
11288
11484
  } else {
11289
- findingCount = scanAndRedactSecrets(text2, rules, relative13).findings.length;
11485
+ findingCount = scanAndRedactSecrets(text2, rules, relative14).findings.length;
11290
11486
  }
11291
11487
  if (findingCount > 0) {
11292
- leakHits.push(relative13 + " (" + findingCount + " line(s))");
11488
+ leakHits.push(relative14 + " (" + findingCount + " line(s))");
11293
11489
  }
11294
11490
  }
11295
11491
  const signatureRecordPath = path25__namespace.join(snapshotDir, SIGNATURE_FILE);
@@ -11492,23 +11688,23 @@ function describeMatcher(matcher) {
11492
11688
  function normalizeTarget(cwd, target) {
11493
11689
  const resolvedCwd = path25__namespace.resolve(cwd);
11494
11690
  const absolute = path25__namespace.resolve(resolvedCwd, target);
11495
- const relative13 = path25__namespace.relative(resolvedCwd, absolute);
11496
- 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)) {
11497
11693
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
11498
11694
  }
11499
- return { relative: relative13.split(path25__namespace.sep).join("/"), outsideRoot: false };
11695
+ return { relative: relative14.split(path25__namespace.sep).join("/"), outsideRoot: false };
11500
11696
  }
11501
11697
  function findRuleMatch(rules, relativePath) {
11502
11698
  return rules.find(
11503
11699
  (rule) => matchRule(relativePath, rule.match)
11504
11700
  );
11505
11701
  }
11506
- function findRecordedAncestor(skipped, relative13, maskedPath2) {
11702
+ function findRecordedAncestor(skipped, relative14, maskedPath2) {
11507
11703
  let nearest;
11508
11704
  for (const record of skipped) {
11509
11705
  const ancestorPath = record.path;
11510
11706
  if (ancestorPath.length === 0) continue;
11511
- const isAncestor = relative13.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
11707
+ const isAncestor = relative14.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
11512
11708
  if (!isAncestor) continue;
11513
11709
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
11514
11710
  }
@@ -11524,8 +11720,8 @@ function readManifest2(config) {
11524
11720
  }
11525
11721
  function explainPath(config, target) {
11526
11722
  const normalized = normalizeTarget(config.cwd, target);
11527
- const relative13 = normalized.relative;
11528
- const maskedPath2 = findSecretInPath(relative13, config.secretRules)?.masked ?? relative13;
11723
+ const relative14 = normalized.relative;
11724
+ const maskedPath2 = findSecretInPath(relative14, config.secretRules)?.masked ?? relative14;
11529
11725
  if (normalized.outsideRoot) {
11530
11726
  return {
11531
11727
  path: maskedPath2,
@@ -11535,7 +11731,7 @@ function explainPath(config, target) {
11535
11731
  detail: "path resolves outside the configured repository root and was not inspected"
11536
11732
  };
11537
11733
  }
11538
- const absolute = path25__namespace.join(config.cwd, relative13);
11734
+ const absolute = path25__namespace.join(config.cwd, relative14);
11539
11735
  const result = {
11540
11736
  path: maskedPath2,
11541
11737
  exists: fs24__namespace.existsSync(absolute),
@@ -11553,11 +11749,11 @@ function explainPath(config, target) {
11553
11749
  // that is only missing because the walker dropped the tool's own output directory.
11554
11750
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
11555
11751
  (directory) => path25__namespace.relative(config.cwd, path25__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
11556
- ).filter((relative14) => relative14.length > 0 && !relative14.startsWith(".."))
11752
+ ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
11557
11753
  });
11558
- if (!collection.files.includes(relative13)) {
11754
+ if (!collection.files.includes(relative14)) {
11559
11755
  const record = collection.skipped.find(
11560
- (entry2) => entry2.path === relative13 || entry2.path === maskedPath2
11756
+ (entry2) => entry2.path === relative14 || entry2.path === maskedPath2
11561
11757
  );
11562
11758
  if (record) {
11563
11759
  result.reason = record.reason;
@@ -11566,7 +11762,7 @@ function explainPath(config, target) {
11566
11762
  result.reason = "missing";
11567
11763
  result.detail = "no such file or directory, relative to the configured cwd";
11568
11764
  } else {
11569
- const ancestor = findRecordedAncestor(collection.skipped, relative13, maskedPath2);
11765
+ const ancestor = findRecordedAncestor(collection.skipped, relative14, maskedPath2);
11570
11766
  if (ancestor) {
11571
11767
  result.reason = ancestor.reason;
11572
11768
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -11586,13 +11782,15 @@ function explainPath(config, target) {
11586
11782
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
11587
11783
  ...config.staged === true ? { staged: true } : {}
11588
11784
  });
11589
- inScope = scope.paths.has(relative13);
11785
+ inScope = scope.paths.has(relative14);
11590
11786
  if (!inScope && config.withDependents === true) {
11591
11787
  inScope = importsChangedFile(
11592
- relative13,
11593
- importsOfFile(relative13, absolute),
11788
+ relative14,
11789
+ importsOfFile(relative14, absolute),
11594
11790
  scope.paths,
11595
- buildImportResolver(collection.files.map((file) => ({ relativePath: file })))
11791
+ buildImportResolver(collection.files.map((file) => ({ relativePath: file })), {
11792
+ tsconfig: tsconfigPathsFor(config.cwd)
11793
+ })
11596
11794
  );
11597
11795
  }
11598
11796
  scopeDetail = scope.detail;
@@ -11648,15 +11846,15 @@ function explainPath(config, target) {
11648
11846
  result.bytes = buffer.length;
11649
11847
  result.lines = countLines(text2);
11650
11848
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
11651
- const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative13);
11849
+ const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative14);
11652
11850
  result.secretCount = findings.length;
11653
11851
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
11654
11852
  let inclusionMode = "full";
11655
- if (config.skeleton === true && isSkeletonizable(relative13)) {
11656
- const skeleton = skeletonizeTypeScript(text2, relative13);
11853
+ if (config.skeleton === true && isSkeletonizable(relative14)) {
11854
+ const skeleton = skeletonizeTypeScript(text2, relative14);
11657
11855
  if (skeleton.collapsed > 0) inclusionMode = "signatures";
11658
11856
  }
11659
- 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) {
11660
11858
  inclusionMode = "comments-stripped";
11661
11859
  }
11662
11860
  if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
@@ -11665,18 +11863,18 @@ function explainPath(config, target) {
11665
11863
  }
11666
11864
  result.inclusionMode = inclusionMode;
11667
11865
  }
11668
- result.layer = classifyLayer(relative13, config.layers);
11669
- result.kind = classifyKind(relative13, config.kinds);
11670
- result.language = detectLanguage(relative13);
11671
- 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);
11672
11870
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
11673
- const kindRule = findRuleMatch(config.kinds, relative13);
11871
+ const kindRule = findRuleMatch(config.kinds, relative14);
11674
11872
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
11675
11873
  const manifest = readManifest2(config);
11676
- 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;
11677
11875
  result.part = entry?.part ?? null;
11678
11876
  if (entry === void 0) {
11679
- const record = manifest?.skipped?.find((skip) => skip.path === relative13);
11877
+ const record = manifest?.skipped?.find((skip) => skip.path === relative14);
11680
11878
  if (record !== void 0 && (record.reason === "not-selected" || record.reason === "unchanged")) {
11681
11879
  result.included = false;
11682
11880
  result.reason = record.reason;
@@ -11741,6 +11939,7 @@ const { parentPort, workerData } = require("node:worker_threads");
11741
11939
  const manifest = mod.generateSnapshot(config, {
11742
11940
  dryRun: workerData.dryRun === true,
11743
11941
  ...(workerData.narrow ?? {}),
11942
+ ...(workerData.runId === undefined ? {} : { runId: workerData.runId }),
11744
11943
  });
11745
11944
  const skipCounts = new Map();
11746
11945
  for (const record of manifest.skipped) {
@@ -11786,8 +11985,13 @@ function generateInWorker(cwd, cliOptions, options = {}) {
11786
11985
  const finish = (result) => {
11787
11986
  if (settled) return;
11788
11987
  settled = true;
11789
- if (worker !== null) void worker.terminate();
11790
- 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
+ });
11791
11995
  };
11792
11996
  const isCjs = typeof __dirname !== "undefined";
11793
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))));
@@ -11799,7 +12003,8 @@ function generateInWorker(cwd, cliOptions, options = {}) {
11799
12003
  cwd,
11800
12004
  cliOptions,
11801
12005
  dryRun: options.dryRun === true,
11802
- narrow: options.narrow ?? {}
12006
+ narrow: options.narrow ?? {},
12007
+ ...options.runId === void 0 ? {} : { runId: options.runId }
11803
12008
  }
11804
12009
  });
11805
12010
  } catch (error) {
@@ -11964,7 +12169,16 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
11964
12169
  if (overrides.withDependents === true) cliOptions.withDependents = true;
11965
12170
  try {
11966
12171
  const config = resolveConfig(loaded.config, cliOptions, root);
11967
- 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
+ };
11968
12182
  } catch (error) {
11969
12183
  return { ok: false, message: error instanceof Error ? error.message : String(error) };
11970
12184
  }
@@ -11978,8 +12192,8 @@ function partPathFor(workspace, filename) {
11978
12192
  if (filename.length === 0 || filename.includes("\0")) return null;
11979
12193
  const partsDir = path25__namespace.resolve(workspace.root, workspace.config.outDir, "parts");
11980
12194
  const resolved = path25__namespace.resolve(partsDir, filename);
11981
- const relative13 = path25__namespace.relative(partsDir, resolved);
11982
- 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)) {
11983
12197
  return null;
11984
12198
  }
11985
12199
  let stats;
@@ -12153,11 +12367,11 @@ function toRelativePath(root, value) {
12153
12367
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
12154
12368
  const resolvedRoot = path25__namespace.resolve(root);
12155
12369
  const absolute = path25__namespace.resolve(resolvedRoot, cleaned);
12156
- const relative13 = path25__namespace.relative(resolvedRoot, absolute);
12157
- 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)) {
12158
12372
  return null;
12159
12373
  }
12160
- return relative13.split(path25__namespace.sep).join("/");
12374
+ return relative14.split(path25__namespace.sep).join("/");
12161
12375
  }
12162
12376
  function symbolsOf(entry) {
12163
12377
  const summary = entry.summary;
@@ -12263,7 +12477,7 @@ var historyTool = {
12263
12477
  const manifestRead = readManifest3(prepared.workspace);
12264
12478
  const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
12265
12479
  if (recordedLog !== void 0 && recordedLog !== null) {
12266
- const digest = crypto2.createHash("sha256").update(text2, "utf8").digest("hex");
12480
+ const digest = crypto.createHash("sha256").update(text2, "utf8").digest("hex");
12267
12481
  if (digest !== recordedLog.sha256) {
12268
12482
  return {
12269
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.",
@@ -12371,7 +12585,9 @@ var testsTool = {
12371
12585
  const cap = Math.max(1, typeof args.maxFiles === "number" ? args.maxFiles : 50);
12372
12586
  const isTest2 = (filePath) => /(^|\/)(tests?|__tests__|spec)\//.test(filePath) || /\.(test|spec)\.[a-z0-9]+$/i.test(filePath);
12373
12587
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath, file]));
12374
- const resolver = buildImportResolver(read.manifest.files, {});
12588
+ const resolver = buildImportResolver(read.manifest.files, {
12589
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
12590
+ });
12375
12591
  const testFiles = read.manifest.files.filter((file) => isTest2(file.relativePath));
12376
12592
  const importsOf = (filePath) => {
12377
12593
  const entry = read.manifest.indexes.imports.byFile.find((candidate) => candidate.path === filePath);
@@ -12419,9 +12635,13 @@ var workspaceTool = {
12419
12635
  },
12420
12636
  annotations: READ_ONLY,
12421
12637
  async handler(args, context) {
12422
- const root = path25__namespace.resolve(context.cwd, typeof args.root === "string" ? args.root : ".");
12423
- const outDir = typeof args.outDir === "string" ? args.outDir : "snapshot";
12424
- 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
+ );
12425
12645
  let text2;
12426
12646
  try {
12427
12647
  text2 = fs24__namespace.readFileSync(index, "utf8");
@@ -12478,7 +12698,9 @@ var neighborsTool = {
12478
12698
  const file = read.manifest.files.find((candidate) => candidate.relativePath === wanted) ?? read.manifest.files.find((candidate) => candidate.relativePath.toLowerCase() === wanted.toLowerCase());
12479
12699
  if (file === void 0) return { text: wanted + " is not in the snapshot; snapshot_explain says why.", isError: true };
12480
12700
  const byPath = new Map(read.manifest.files.map((candidate) => [candidate.relativePath, candidate]));
12481
- const resolver = buildImportResolver(read.manifest.files, {});
12701
+ const resolver = buildImportResolver(read.manifest.files, {
12702
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
12703
+ });
12482
12704
  const entry = read.manifest.indexes.imports.byFile.find((candidate) => candidate.path === file.relativePath);
12483
12705
  const imports = [];
12484
12706
  for (const specifier of entry?.imports ?? []) {
@@ -12620,7 +12842,9 @@ var cyclesTool = {
12620
12842
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
12621
12843
  const cap = Math.max(1, typeof args.maxComponents === "number" ? args.maxComponents : 20);
12622
12844
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath, file]));
12623
- const resolver = buildImportResolver(read.manifest.files, {});
12845
+ const resolver = buildImportResolver(read.manifest.files, {
12846
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
12847
+ });
12624
12848
  const edges = /* @__PURE__ */ new Map();
12625
12849
  for (const path26 of byPath.keys()) edges.set(path26, []);
12626
12850
  for (const entry of read.manifest.indexes.imports.byFile) {
@@ -13820,10 +14044,17 @@ var generateTool = {
13820
14044
  ...typeof args.slice === "string" ? { slice: { question: args.slice, ...typeof args.sliceTokens === "number" ? { maxTokens: args.sliceTokens } : {} } } : {},
13821
14045
  ...typeof args.budgetTokens === "number" ? { budgetTokens: args.budgetTokens } : {}
13822
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
+ }
13823
14054
  const result = await generateInWorker(
13824
14055
  workspace.root,
13825
14056
  { ...workspace.cliOptions, ...reportOptions },
13826
- { signal: controller.signal, narrow }
14057
+ { signal: controller.signal, narrow, runId: crypto.randomUUID(), lockRoots }
13827
14058
  );
13828
14059
  if (!result.ok) return failure(result.message);
13829
14060
  context.notify?.({ message: "writing the snapshot", progress: 2, total: 2 });
@@ -13857,16 +14088,42 @@ var generateTool = {
13857
14088
  };
13858
14089
  function configAsGenerated(workspace, manifest) {
13859
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;
13860
14117
  return {
13861
14118
  ...workspace.config,
13862
- ...recorded?.artifacts === void 0 ? {} : { artifacts: recorded.artifacts },
13863
- ...recorded?.stripComments === void 0 ? {} : { stripComments: recorded.stripComments },
13864
- ...recorded?.removeEmptyLines === void 0 ? {} : { removeEmptyLines: recorded.removeEmptyLines },
13865
- ...recorded?.pack === void 0 ? {} : { pack: recorded.pack },
13866
- ...recorded?.logCount === void 0 ? {} : { logCount: recorded.logCount },
13867
- ...recorded?.skeleton === void 0 ? {} : { skeleton: recorded.skeleton },
13868
- ...recorded?.sarif === void 0 ? {} : { sarif: recorded.sarif },
13869
- ...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) } : {}
13870
14127
  };
13871
14128
  }
13872
14129
  var validateTool = {
@@ -14103,7 +14360,9 @@ var dependentsTool = {
14103
14360
  }
14104
14361
  const direction = args.direction === "imports" || args.direction === "imported-by" ? String(args.direction) : "both";
14105
14362
  const limit = typeof args.limit === "number" && args.limit > 0 ? Math.floor(args.limit) : 50;
14106
- const resolver = buildImportResolver(manifest.files);
14363
+ const resolver = buildImportResolver(manifest.files, {
14364
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
14365
+ });
14107
14366
  const imports = [];
14108
14367
  const unresolved = [];
14109
14368
  if (direction !== "imported-by") {
@@ -15512,6 +15771,10 @@ function buildAgentContract() {
15512
15771
  { key: "maxPartBytes", type: "number | string", default: 307200, summary: "Per-part byte budget." },
15513
15772
  { key: "maxPartTokens", type: "number | string | null", default: null, summary: "Per-part token ceiling; narrows maxPartBytes. Minimum 1024." },
15514
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>)." },
15515
15778
  { key: "sarif", type: "boolean", default: false, summary: "Also write reports/audit.sarif." },
15516
15779
  { key: "changedSince", type: "string | null", default: null, summary: "Snapshot only files that differ from this git ref." },
15517
15780
  { key: "staged", type: "boolean", default: false, summary: "Snapshot only files staged in the index." },
@@ -16494,9 +16757,9 @@ function dosDateTime(date) {
16494
16757
  function walkFiles(root, prefix = "") {
16495
16758
  const files = [];
16496
16759
  for (const entry of fs24__namespace.readdirSync(path25__namespace.join(root, prefix), { withFileTypes: true })) {
16497
- const relative13 = prefix === "" ? entry.name : prefix + "/" + entry.name;
16498
- if (entry.isDirectory()) files.push(...walkFiles(root, relative13));
16499
- 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);
16500
16763
  }
16501
16764
  return files;
16502
16765
  }
@@ -16504,11 +16767,11 @@ function writeZip(options) {
16504
16767
  const entries = [...options.entries ?? []];
16505
16768
  if (options.directory !== void 0) {
16506
16769
  const root = options.directory;
16507
- for (const relative13 of walkFiles(root)) {
16508
- if (options.skip !== void 0 && options.skip(relative13)) continue;
16509
- 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);
16510
16773
  const stat = fs24__namespace.statSync(full);
16511
- 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 });
16512
16775
  }
16513
16776
  }
16514
16777
  if (entries.length > 65535) {
@@ -16701,8 +16964,13 @@ var SERVE_PAGE = `<!doctype html>
16701
16964
  $("counts").textContent = info.included + " included / " + info.skipped + " skipped";
16702
16965
  $("files").innerHTML = "";
16703
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.
16704
16969
  const li = document.createElement("li");
16705
- 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));
16706
16974
  $("files").appendChild(li);
16707
16975
  }
16708
16976
  }
@@ -16735,20 +17003,59 @@ async function startWebServer(options) {
16735
17003
  const host = options.host ?? "127.0.0.1";
16736
17004
  const port = options.port ?? DEFAULT_PORT;
16737
17005
  const log = options.log ?? ((line) => process.stderr.write(line + "\n"));
16738
- 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;
16739
17007
  if (token === null && !["127.0.0.1", "localhost", "::1"].includes(host)) {
16740
17008
  throw new Error("Refusing to serve " + host + " without a token.");
16741
17009
  }
16742
- 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
+ };
16743
17020
  const temporaryClones = /* @__PURE__ */ new Set();
16744
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
+ });
16745
17035
  const insideAllowedRoots = (candidate) => {
17036
+ const resolved = canonical(candidate);
17037
+ return resolved === null ? false : inside(resolved);
17038
+ };
17039
+ const lexicallyInside = (candidate) => {
16746
17040
  const resolved = path25__namespace.resolve(candidate);
16747
17041
  return allowedRoots.some((root) => {
16748
- const prefix = root.endsWith(path25__namespace.sep) ? root : root + path25__namespace.sep;
16749
- 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);
16750
17044
  });
16751
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
+ };
16752
17059
  const authorized = (request) => {
16753
17060
  if (token === null) return true;
16754
17061
  const header = request.headers.authorization ?? "";
@@ -16756,7 +17063,7 @@ async function startWebServer(options) {
16756
17063
  if (match === null) return false;
16757
17064
  const given = Buffer.from(match[1].trim(), "utf8");
16758
17065
  const expected = Buffer.from(token, "utf8");
16759
- return given.length === expected.length && crypto2.timingSafeEqual(given, expected);
17066
+ return given.length === expected.length && crypto.timingSafeEqual(given, expected);
16760
17067
  };
16761
17068
  const server = http__namespace.createServer((request, response) => {
16762
17069
  const origin = typeof request.headers.origin === "string" ? request.headers.origin : void 0;
@@ -16772,7 +17079,10 @@ async function startWebServer(options) {
16772
17079
  cors["access-control-allow-headers"] = "authorization, content-type";
16773
17080
  cors["access-control-allow-methods"] = "GET, POST, OPTIONS";
16774
17081
  }
17082
+ let responseSent = false;
16775
17083
  const send = (status, body, extra = {}) => {
17084
+ if (responseSent) return;
17085
+ responseSent = true;
16776
17086
  const text2 = typeof body === "string" ? body : JSON.stringify(body);
16777
17087
  response.writeHead(status, {
16778
17088
  ...cors,
@@ -16803,10 +17113,13 @@ async function startWebServer(options) {
16803
17113
  const url = new URL(request.url ?? "/", "http://localhost");
16804
17114
  if (request.method === "POST" && (request.url === "/mcp" || (request.url ?? "").startsWith("/mcp?"))) {
16805
17115
  let received = 0;
17116
+ let tooLarge = false;
16806
17117
  const chunks = [];
16807
17118
  request.on("data", (chunk) => {
17119
+ if (tooLarge) return;
16808
17120
  received += chunk.length;
16809
17121
  if (received > 2 * 1024 * 1024) {
17122
+ tooLarge = true;
16810
17123
  request.destroy();
16811
17124
  send(413, { error: "request body too large" });
16812
17125
  return;
@@ -16814,6 +17127,7 @@ async function startWebServer(options) {
16814
17127
  chunks.push(chunk);
16815
17128
  });
16816
17129
  request.on("end", () => {
17130
+ if (tooLarge) return;
16817
17131
  void (async () => {
16818
17132
  let message;
16819
17133
  try {
@@ -16823,9 +17137,14 @@ async function startWebServer(options) {
16823
17137
  return;
16824
17138
  }
16825
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);
16826
17145
  const answers = [];
16827
17146
  for (const item of batch) {
16828
- const answer = await mcp.handle(item);
17147
+ const answer = await server2.handle(item);
16829
17148
  if (answer !== null) answers.push(answer);
16830
17149
  }
16831
17150
  if (answers.length === 0) send(202, "");
@@ -16836,10 +17155,13 @@ async function startWebServer(options) {
16836
17155
  }
16837
17156
  if (request.method === "POST" && request.url === "/api/generate") {
16838
17157
  let received = 0;
17158
+ let tooLarge = false;
16839
17159
  const chunks = [];
16840
17160
  request.on("data", (chunk) => {
17161
+ if (tooLarge) return;
16841
17162
  received += chunk.length;
16842
17163
  if (received > MAX_BODY) {
17164
+ tooLarge = true;
16843
17165
  request.destroy();
16844
17166
  send(413, { error: "request body too large" });
16845
17167
  return;
@@ -16847,6 +17169,7 @@ async function startWebServer(options) {
16847
17169
  chunks.push(chunk);
16848
17170
  });
16849
17171
  request.on("end", () => {
17172
+ if (tooLarge) return;
16850
17173
  void (async () => {
16851
17174
  let source = "";
16852
17175
  let mode = "full";
@@ -16903,6 +17226,10 @@ async function startWebServer(options) {
16903
17226
  }
16904
17227
  } else {
16905
17228
  target = path25__namespace.resolve(options.cwd, source);
17229
+ if (!insideAllowedRoots(target)) {
17230
+ send(403, { error: "outside the served directory: " + target });
17231
+ return;
17232
+ }
16906
17233
  }
16907
17234
  let stat;
16908
17235
  try {
@@ -16920,15 +17247,26 @@ async function startWebServer(options) {
16920
17247
  send(400, { error: loaded.errors.join("; ") });
16921
17248
  return;
16922
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
+ }
16923
17262
  const started = Date.now();
16924
17263
  try {
16925
- const manifest = generateSnapshot({ ...loaded.config ?? {}, cwd: target }, {
17264
+ const manifest = generateSnapshot({ ...runConfig, cwd: target }, {
16926
17265
  ...provenance === void 0 ? {} : { source: provenance },
16927
17266
  ...mode === "slice" ? { slice: { question } } : {},
16928
17267
  ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
16929
17268
  });
16930
17269
  const seconds = ((Date.now() - started) / 1e3).toFixed(2);
16931
- const snapshotDir = path25__namespace.join(target, "snapshot");
16932
17270
  const health = auditSnapshot({ snapshotDir, repoDir: target });
16933
17271
  send(200, {
16934
17272
  path: snapshotDir,
@@ -16956,7 +17294,7 @@ async function startWebServer(options) {
16956
17294
  }
16957
17295
  if (request.method === "GET" && request.url?.startsWith("/api/health?") === true) {
16958
17296
  const target = path25__namespace.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
16959
- if (!insideAllowedRoots(target)) {
17297
+ if (!lexicallyInside(target)) {
16960
17298
  send(403, { error: "outside the served directory: " + target });
16961
17299
  return;
16962
17300
  }
@@ -16964,12 +17302,24 @@ async function startWebServer(options) {
16964
17302
  send(404, { error: "no manifest.json under " + target });
16965
17303
  return;
16966
17304
  }
17305
+ if (!insideAllowedRoots(target)) {
17306
+ send(403, { error: "outside the served directory: " + target });
17307
+ return;
17308
+ }
16967
17309
  const report2 = auditSnapshot({ snapshotDir: target, repoDir: path25__namespace.dirname(target) });
16968
17310
  send(200, { score: report2.score, counts: report2.counts, checks: report2.checks });
16969
17311
  return;
16970
17312
  }
16971
17313
  if (request.method === "GET" && (request.url?.startsWith("/api/snapshot?") === true || request.url === "/api/snapshot")) {
16972
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
+ }
16973
17323
  if (!insideAllowedRoots(target)) {
16974
17324
  send(403, { error: "outside the served directory: " + target });
16975
17325
  return;
@@ -16982,6 +17332,11 @@ async function startWebServer(options) {
16982
17332
  send(404, { error: "no manifest.json under " + target });
16983
17333
  return;
16984
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
+ }
16985
17340
  let prompt = "";
16986
17341
  try {
16987
17342
  prompt = fs24__namespace.readFileSync(path25__namespace.join(target, "PROMPT.md"), "utf8").slice(0, MAX_PREVIEW);
@@ -17001,7 +17356,7 @@ async function startWebServer(options) {
17001
17356
  }
17002
17357
  if (request.method === "GET" && request.url?.startsWith("/api/snapshot.zip") === true) {
17003
17358
  const target = path25__namespace.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17004
- if (!insideAllowedRoots(target)) {
17359
+ if (!lexicallyInside(target)) {
17005
17360
  send(403, { error: "outside the served directory: " + target });
17006
17361
  return;
17007
17362
  }
@@ -17009,6 +17364,10 @@ async function startWebServer(options) {
17009
17364
  send(404, { error: "not a snapshot directory: " + target });
17010
17365
  return;
17011
17366
  }
17367
+ if (!insideAllowedRoots(target)) {
17368
+ send(403, { error: "outside the served directory: " + target });
17369
+ return;
17370
+ }
17012
17371
  try {
17013
17372
  const zip = writeZip({ directory: target });
17014
17373
  response.writeHead(200, {
@@ -17754,9 +18113,17 @@ function renderConfig(answers) {
17754
18113
  // Replace function and method bodies with \`{ /* ... */ }\` in TypeScript files.
17755
18114
  // Signatures and comments stay, so the structure of the file survives.
17756
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,
17757
18120
  // Also write reports/audit.sarif (SARIF 2.1.0) for a CI security gate. The
17758
18121
  // matched value is never included \u2014 only the path, the line and the rule.
17759
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,
17760
18127
  // Snapshot only the files that differ from a git ref (for example "main"),
17761
18128
  // plus untracked ones. null means "snapshot everything"; any other value must
17762
18129
  // be a git ref string, and anything else is a configuration error.
@@ -18430,11 +18797,11 @@ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
18430
18797
  const entries = [];
18431
18798
  for (const directory of [outDir, tmpDir]) {
18432
18799
  if (directory === null) continue;
18433
- const relative13 = path25__namespace.relative(cwd, path25__namespace.resolve(cwd, directory)).replace(/\\/g, "/");
18434
- 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)) {
18435
18802
  continue;
18436
18803
  }
18437
- entries.push(`/${relative13}/`);
18804
+ entries.push(`/${relative14}/`);
18438
18805
  }
18439
18806
  return [...new Set(entries)];
18440
18807
  }
@@ -18765,10 +19132,10 @@ async function runInit(options) {
18765
19132
  };
18766
19133
  }
18767
19134
  function describeTarget(cwd) {
18768
- const relative13 = path25__namespace.relative(process.cwd(), cwd);
18769
- if (relative13 === "") return "this directory";
18770
- if (relative13.startsWith("..") || path25__namespace.isAbsolute(relative13)) return cwd;
18771
- 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;
18772
19139
  }
18773
19140
  function firstRunMessage(reason, cwd) {
18774
19141
  const where = describeTarget(cwd);
@@ -18870,8 +19237,8 @@ function gitDirectory(cwd) {
18870
19237
  }
18871
19238
  }
18872
19239
  function isInside3(parent, child) {
18873
- const relative13 = path25__namespace.relative(parent, child);
18874
- 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);
18875
19242
  }
18876
19243
  function isRegisteredWorktree(gitDir, cwd) {
18877
19244
  try {
@@ -19110,7 +19477,7 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
19110
19477
  };
19111
19478
  }
19112
19479
  function sha256Hex2(input) {
19113
- return crypto2__namespace.createHash("sha256").update(input).digest("hex");
19480
+ return crypto__namespace.createHash("sha256").update(input).digest("hex");
19114
19481
  }
19115
19482
  var TS_EXTENSIONS = [
19116
19483
  ".ts",
@@ -19323,7 +19690,7 @@ function maskPathText(value, secretRules) {
19323
19690
  }
19324
19691
  function maskOwnerBrief(brief, secretRules) {
19325
19692
  if (brief === void 0) return void 0;
19326
- const mask = (value) => maskPathText(value, secretRules);
19693
+ const mask = (value) => scanAndRedactSecrets(value, secretRules ?? [], "owner-brief").redacted;
19327
19694
  return {
19328
19695
  ...brief,
19329
19696
  path: mask(brief.path),
@@ -19369,9 +19736,9 @@ function listEntries(dir) {
19369
19736
  return;
19370
19737
  }
19371
19738
  for (const child of children) {
19372
- const relative13 = prefix === "" ? child.name : `${prefix}/${child.name}`;
19373
- entries.push(relative13);
19374
- 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);
19375
19742
  }
19376
19743
  };
19377
19744
  walk2(dir, "");
@@ -19406,7 +19773,7 @@ function markerInventory(dir, written) {
19406
19773
  }
19407
19774
  return { entries, files };
19408
19775
  }
19409
- function markerPayload(dir, state, id, createdAt, written) {
19776
+ function markerPayload(dir, state, id, createdAt, written, runId) {
19410
19777
  const { entries, files } = markerInventory(dir, written);
19411
19778
  const marker2 = {
19412
19779
  generator: GENERATOR_NAME,
@@ -19415,6 +19782,7 @@ function markerPayload(dir, state, id, createdAt, written) {
19415
19782
  createdAt,
19416
19783
  state,
19417
19784
  id,
19785
+ ...runId === void 0 ? {} : { runId },
19418
19786
  pid: process.pid,
19419
19787
  entries,
19420
19788
  files
@@ -19512,6 +19880,7 @@ function readOwnershipMarker(dir) {
19512
19880
  createdAt: typeof candidate.createdAt === "string" ? candidate.createdAt : "unknown",
19513
19881
  state: candidate.state,
19514
19882
  id: candidate.id,
19883
+ runId: typeof candidate.runId === "string" ? candidate.runId : void 0,
19515
19884
  pid: typeof candidate.pid === "number" ? candidate.pid : void 0,
19516
19885
  manifestSha256: typeof candidate.manifestSha256 === "string" ? candidate.manifestSha256 : void 0,
19517
19886
  entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0,
@@ -19670,13 +20039,19 @@ function assessSnapshotDirectory(dir) {
19670
20039
  };
19671
20040
  }
19672
20041
  const entries = listEntries(dir);
19673
- const foreignEntries = entries.filter(
20042
+ let foreignEntries = entries.filter(
19674
20043
  (entry) => !recorded.has(entry) && !isIgnorableEntry(entry)
19675
20044
  );
20045
+ const legacySignatureOnly = foreignEntries.length === 1 && foreignEntries[0] === SIGNATURE_FILE && verifySnapshotSignature(dir).ok;
20046
+ if (legacySignatureOnly) foreignEntries = [];
19676
20047
  if (foreignEntries.length > 0) {
19677
20048
  return { owned: false, problem: null, foreignEntries, marker: marker2 };
19678
20049
  }
19679
- 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
+ );
19680
20055
  return {
19681
20056
  owned: inventoryProblem === null,
19682
20057
  problem: inventoryProblem,
@@ -19854,13 +20229,13 @@ function startLockHeartbeat(lockPath) {
19854
20229
  return () => void 0;
19855
20230
  }
19856
20231
  }
19857
- function acquireRunLock(stagingRoot) {
20232
+ function acquireRunLock(stagingRoot, runId) {
19858
20233
  const lockPath = lockPathFor(stagingRoot);
19859
20234
  const payload = `${JSON.stringify({
19860
20235
  pid: process.pid,
19861
20236
  stagingRoot,
19862
20237
  host: os2__namespace.hostname(),
19863
- runId: crypto2__namespace.randomUUID(),
20238
+ runId,
19864
20239
  heartbeatMs: LOCK_HEARTBEAT_MS,
19865
20240
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
19866
20241
  })}
@@ -19914,6 +20289,33 @@ function canonicalLockTarget(targetPath) {
19914
20289
  function lockPathFor(stagingRoot) {
19915
20290
  return path25__namespace.join(os2__namespace.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
19916
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
+ }
19917
20319
  function lockHeartbeatAgeMs(lockPath) {
19918
20320
  try {
19919
20321
  return Date.now() - fs24__namespace.statSync(lockPath).mtimeMs;
@@ -20228,6 +20630,7 @@ function generateSnapshot(configInput, options) {
20228
20630
  assertUsableConfigInput(configInput);
20229
20631
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
20230
20632
  const dryRun = options?.dryRun ?? false;
20633
+ const runId = options?.runId ?? crypto__namespace.randomUUID();
20231
20634
  const gitInfo = getGitInfo(config.cwd, config.branch);
20232
20635
  const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
20233
20636
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
@@ -20247,7 +20650,7 @@ function generateSnapshot(configInput, options) {
20247
20650
  // output — but only at these exact paths, not at every directory that shares the name.
20248
20651
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
20249
20652
  (directory) => path25__namespace.relative(config.cwd, path25__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
20250
- ).filter((relative13) => relative13.length > 0 && !relative13.startsWith("..")),
20653
+ ).filter((relative14) => relative14.length > 0 && !relative14.startsWith("..")),
20251
20654
  // A staged path can be absent from the working tree while its index blob exists. Discovery
20252
20655
  // lists the working tree, so those paths would never reach the scan at all.
20253
20656
  ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
@@ -20934,9 +21337,13 @@ function generateSnapshot(configInput, options) {
20934
21337
  if (navigationText !== null) manifest.artifacts.navigation = artifactRecord(navigationText);
20935
21338
  const auditText = artifacts.audit ? generateAuditReport(manifest, secretFindings, config.secretRules) : null;
20936
21339
  if (auditText !== null) manifest.artifacts.audit = artifactRecord(auditText);
20937
- 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;
20938
21345
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
20939
- 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;
20940
21347
  if (artifacts.diff && diffReport === null && !isGitRepository(config.cwd)) {
20941
21348
  manifest.warnings.push(
20942
21349
  "--include-diffs was requested, but the generated directory is not a git repository; reports/diff.md was not written."
@@ -20980,7 +21387,8 @@ function generateSnapshot(configInput, options) {
20980
21387
  const entry = {
20981
21388
  ...file,
20982
21389
  content,
20983
- inclusionMode: "full",
21390
+ inclusionMode: file.inclusionMode === "comments-stripped" ? "comments-stripped" : "full",
21391
+ ...file.emptyLinesRemoved === true ? { emptyLinesRemoved: true } : {},
20984
21392
  isPreviewTruncated: false,
20985
21393
  includedBytes: Buffer.byteLength(content, "utf8"),
20986
21394
  includedLines: countLines(content)
@@ -21048,7 +21456,7 @@ function generateSnapshot(configInput, options) {
21048
21456
  const lockKeys = Array.from(/* @__PURE__ */ new Set([tmpDir, outDir])).sort();
21049
21457
  const releases = [];
21050
21458
  try {
21051
- for (const key of lockKeys) releases.push(acquireRunLock(key));
21459
+ for (const key of lockKeys) releases.push(acquireRunLock(key, runId));
21052
21460
  } catch (error) {
21053
21461
  for (const release of [...releases].reverse()) release();
21054
21462
  throw error;
@@ -21064,7 +21472,7 @@ function generateSnapshot(configInput, options) {
21064
21472
  ensureParentDirectory(outDir, "outDir");
21065
21473
  fs24__namespace.mkdirSync(tmpDir, { recursive: true });
21066
21474
  cleanStaleRunDirs(tmpDir);
21067
- const snapshotId = crypto2__namespace.randomUUID();
21475
+ const snapshotId = crypto__namespace.randomUUID();
21068
21476
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
21069
21477
  stagingDir = path25__namespace.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
21070
21478
  fs24__namespace.mkdirSync(stagingDir);
@@ -21075,6 +21483,7 @@ function generateSnapshot(configInput, options) {
21075
21483
  createdAt,
21076
21484
  state: "staging",
21077
21485
  id: snapshotId,
21486
+ runId,
21078
21487
  pid: process.pid
21079
21488
  });
21080
21489
  const partsDir = path25__namespace.join(stagingDir, "parts");
@@ -21143,6 +21552,17 @@ function generateSnapshot(configInput, options) {
21143
21552
  if (artifacts.manifest) {
21144
21553
  writeArtifact(stagingDir, "manifest.json", JSON.stringify(manifest, null, 2));
21145
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
+ }
21146
21566
  if (monolithJson !== null) {
21147
21567
  writeArtifact(stagingDir, "full-codebase.json", monolithJson);
21148
21568
  }
@@ -21154,7 +21574,7 @@ function generateSnapshot(configInput, options) {
21154
21574
  }
21155
21575
  writeOwnershipMarker(
21156
21576
  stagingDir,
21157
- markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts)
21577
+ markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21158
21578
  );
21159
21579
  swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
21160
21580
  stagingDir = null;
@@ -21165,10 +21585,16 @@ function generateSnapshot(configInput, options) {
21165
21585
  if (artifacts.manifest && manifest.warnings.length !== warningsBeforeHook) {
21166
21586
  writeManifestAtomically(path25__namespace.join(outDir, "manifest.json"), manifest);
21167
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
+ }
21168
21594
  }
21169
21595
  writeOwnershipMarker(
21170
21596
  outDir,
21171
- markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts)
21597
+ markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21172
21598
  );
21173
21599
  };
21174
21600
  if (config.hooks.afterGenerate) shipHookState();
@@ -21325,6 +21751,7 @@ exports.parseRemoteSource = parseRemoteSource;
21325
21751
  exports.partitionFiles = partitionFiles;
21326
21752
  exports.planFirstRun = planFirstRun;
21327
21753
  exports.profileForPath = profileForPath;
21754
+ exports.releaseAbandonedRun = releaseAbandonedRun;
21328
21755
  exports.renderConfig = renderConfig;
21329
21756
  exports.renderDiffText = renderDiffText;
21330
21757
  exports.renderExplainText = renderExplainText;
@@ -21345,6 +21772,7 @@ exports.summarizeMarkdown = summarizeMarkdown;
21345
21772
  exports.summarizeTypeScriptSource = summarizeTypeScriptSource;
21346
21773
  exports.summarizeWithProfile = summarizeWithProfile;
21347
21774
  exports.supportsTypeScriptImports = supportsTypeScriptImports;
21775
+ exports.tokenAllowedForHost = tokenAllowedForHost;
21348
21776
  exports.treeTruncationWarnings = treeTruncationWarnings;
21349
21777
  exports.truncatePreview = truncatePreview;
21350
21778
  exports.truncateToBytes = truncateToBytes;