codebase-snapshot 0.20.2 → 0.20.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- import * as crypto3 from 'crypto';
2
- import { createHash, randomBytes, timingSafeEqual } from 'crypto';
1
+ import * as crypto from 'crypto';
2
+ import { createHash, randomBytes, timingSafeEqual, randomUUID } from 'crypto';
3
3
  import { Worker } from 'worker_threads';
4
4
  import { AsyncLocalStorage } from 'async_hooks';
5
5
  import * as fs24 from 'fs';
@@ -621,9 +621,9 @@ var rubyProfile = {
621
621
  eachLine(content, (line) => {
622
622
  const trimmed = line.trim();
623
623
  if (!trimmed || trimmed.startsWith("#")) return;
624
- const relative13 = REQUIRE_RELATIVE.exec(trimmed);
625
- if (relative13) {
626
- summary.imports.push(`./${relative13[1]}`);
624
+ const relative14 = REQUIRE_RELATIVE.exec(trimmed);
625
+ if (relative14) {
626
+ summary.imports.push(`./${relative14[1]}`);
627
627
  return;
628
628
  }
629
629
  const required = REQUIRE.exec(trimmed);
@@ -1970,8 +1970,8 @@ function workspacePackageDirs(cwd, patterns) {
1970
1970
  function scanWorkspacePackages(cwd, patterns) {
1971
1971
  const files = /* @__PURE__ */ new Set();
1972
1972
  const dependencies = /* @__PURE__ */ new Set();
1973
- for (const relative13 of workspacePackageDirs(cwd, patterns)) {
1974
- const full = path25.join(cwd, relative13);
1973
+ for (const relative14 of workspacePackageDirs(cwd, patterns)) {
1974
+ const full = path25.join(cwd, relative14);
1975
1975
  try {
1976
1976
  for (const entry of fs24.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
1977
1977
  } catch {
@@ -3999,10 +3999,68 @@ function applySpansKeepingQuotes(line, spans) {
3999
3999
  out += line.slice(cursor);
4000
4000
  return out;
4001
4001
  }
4002
+ var SIGNATURE_FILE = "signature.json";
4003
+ function loadSigningKey(environment = process.env) {
4004
+ const pem = environment.SNAPSHOT_SIGNING_KEY;
4005
+ if (pem === void 0 || pem.trim() === "") return null;
4006
+ return crypto.createPrivateKey({ key: pem, format: "pem" });
4007
+ }
4008
+ function signManifest(manifestPath, options = {}) {
4009
+ const bytes = fs24.readFileSync(manifestPath);
4010
+ const manifest = JSON.parse(bytes.toString("utf8"));
4011
+ if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
4012
+ throw new Error("refusing to sign: the manifest has no valid fingerprint");
4013
+ }
4014
+ const configured = options.key ?? null;
4015
+ const key = configured ?? crypto.generateKeyPairSync("ed25519").privateKey;
4016
+ const publicKey = crypto.createPublicKey(key).export({ type: "spki", format: "der" }).toString("base64");
4017
+ const signature = crypto.sign(null, bytes, key).toString("base64");
4018
+ return {
4019
+ algorithm: "ed25519",
4020
+ signedAt: options.signedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
4021
+ fingerprint: manifest.fingerprint,
4022
+ manifestSha256: crypto.createHash("sha256").update(bytes).digest("hex"),
4023
+ publicKey,
4024
+ signature,
4025
+ keyOrigin: configured === null ? "generated" : "configured"
4026
+ };
4027
+ }
4028
+ function verifySnapshotSignature(snapshotDir) {
4029
+ const signaturePath = path25.join(snapshotDir, SIGNATURE_FILE);
4030
+ const manifestPath = path25.join(snapshotDir, "manifest.json");
4031
+ if (!fs24.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
4032
+ let record;
4033
+ try {
4034
+ record = JSON.parse(fs24.readFileSync(signaturePath, "utf8"));
4035
+ } catch (error) {
4036
+ return { ok: false, reason: "signature.json is not JSON: " + error.message };
4037
+ }
4038
+ if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
4039
+ return { ok: false, reason: "signature.json is not an ed25519 record" };
4040
+ }
4041
+ let bytes;
4042
+ try {
4043
+ bytes = fs24.readFileSync(manifestPath);
4044
+ } catch {
4045
+ return { ok: false, reason: "the signed manifest is missing" };
4046
+ }
4047
+ const sha2562 = crypto.createHash("sha256").update(bytes).digest("hex");
4048
+ if (sha2562 !== record.manifestSha256) {
4049
+ return { ok: false, reason: "manifest.json changed after it was signed" };
4050
+ }
4051
+ let verified = false;
4052
+ try {
4053
+ const key = crypto.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
4054
+ verified = crypto.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
4055
+ } catch (error) {
4056
+ return { ok: false, reason: "the signature could not be checked: " + error.message };
4057
+ }
4058
+ return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
4059
+ }
4002
4060
 
4003
4061
  // src/version.ts
4004
4062
  var GENERATOR_NAME = "codebase-snapshot";
4005
- var GENERATOR_VERSION = "0.20.2";
4063
+ var GENERATOR_VERSION = "0.20.4";
4006
4064
  var SCHEMA_VERSION = "3.0.0";
4007
4065
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
4008
4066
  function isOurGeneratorName(name) {
@@ -4034,8 +4092,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
4034
4092
  };
4035
4093
  }
4036
4094
  function isInside(root, candidate) {
4037
- const relative13 = path25.relative(root, candidate);
4038
- return relative13 === "" || !relative13.startsWith(`..${path25.sep}`) && relative13 !== ".." && !path25.isAbsolute(relative13);
4095
+ const relative14 = path25.relative(root, candidate);
4096
+ return relative14 === "" || !relative14.startsWith(`..${path25.sep}`) && relative14 !== ".." && !path25.isAbsolute(relative14);
4039
4097
  }
4040
4098
  var GIT_OUTPUT_LIMIT = 68157440;
4041
4099
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -4509,7 +4567,7 @@ function listIgnoredPaths(cwd) {
4509
4567
  }
4510
4568
  function hasSnapshotMarker(target) {
4511
4569
  try {
4512
- return fs24.statSync(target).isDirectory() && fs24.existsSync(path25.join(target, ".codebase-snapshot"));
4570
+ return fs24.statSync(target).isDirectory() && isToolOwnedDirectory2(target);
4513
4571
  } catch {
4514
4572
  return false;
4515
4573
  }
@@ -4550,7 +4608,9 @@ function isToolOwnedDirectory2(dir) {
4550
4608
  return false;
4551
4609
  }
4552
4610
  return entries.every(
4553
- (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || accounted.has(entry)
4611
+ (entry) => entry === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry) || // A snapshot signed before signing moved into staging has a valid signature.json the old
4612
+ // marker could not record. It is our artifact when the signature verifies.
4613
+ entry === "signature.json" && verifySnapshotSignature(dir).ok || accounted.has(entry)
4554
4614
  );
4555
4615
  }
4556
4616
  function makeToolOwnedDecider(cwd, toolOwnedPaths) {
@@ -4660,6 +4720,15 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
4660
4720
  });
4661
4721
  continue;
4662
4722
  }
4723
+ const targetRelative = path25.relative(rootReal, targetReal).split(path25.sep).join("/");
4724
+ if (isSensitivePath(targetRelative)) {
4725
+ report2(linkedPath, {
4726
+ path: linkedPath,
4727
+ reason: "sensitive-file",
4728
+ detail: "link target is a credential-bearing file; not followed"
4729
+ });
4730
+ continue;
4731
+ }
4663
4732
  kept.push(candidate);
4664
4733
  }
4665
4734
  return kept;
@@ -5126,21 +5195,25 @@ var CONFIG_KEY_NAMES = [
5126
5195
  "kinds",
5127
5196
  "largeFileBytes",
5128
5197
  "layers",
5198
+ "logCount",
5129
5199
  "layersMode",
5130
5200
  "maxMonolithBytes",
5131
5201
  "maxPartBytes",
5132
5202
  "maxParts",
5133
5203
  "maxPartTokens",
5134
5204
  "outDir",
5205
+ "pack",
5135
5206
  "preset",
5136
5207
  "previewHeadLines",
5137
5208
  "promptTask",
5138
5209
  "staged",
5139
5210
  "previewTailLines",
5211
+ "removeEmptyLines",
5140
5212
  "secretRules",
5141
5213
  "secrets",
5142
5214
  "sarif",
5143
5215
  "skeleton",
5216
+ "stripComments",
5144
5217
  "tmpDir",
5145
5218
  "withDependents"
5146
5219
  ];
@@ -5455,7 +5528,34 @@ function readConfiguredBrief(cwd, value) {
5455
5528
  "brief must be a path to a markdown file (received " + describeValue2(value) + ")."
5456
5529
  );
5457
5530
  }
5458
- const filePath = path25.resolve(cwd, value);
5531
+ const rootReal = (() => {
5532
+ try {
5533
+ return fs24.realpathSync(cwd);
5534
+ } catch {
5535
+ return path25.resolve(cwd);
5536
+ }
5537
+ })();
5538
+ const requested = path25.resolve(cwd, value);
5539
+ let filePath;
5540
+ try {
5541
+ filePath = fs24.realpathSync(requested);
5542
+ } catch {
5543
+ throw new Error(
5544
+ 'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
5545
+ );
5546
+ }
5547
+ const relative14 = path25.relative(rootReal, filePath);
5548
+ if (relative14.length === 0 || relative14 === ".." || relative14.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative14)) {
5549
+ throw new Error(
5550
+ 'brief "' + value + '" resolves outside the repository. A brief must be a file inside the repository being described; an absolute or parent path is refused.'
5551
+ );
5552
+ }
5553
+ const posixRelative = relative14.split(path25.sep).join("/");
5554
+ if (isSensitivePath(posixRelative) || isSensitivePath(value)) {
5555
+ throw new Error(
5556
+ 'brief "' + value + '" is a credential-bearing file. A snapshot must not reproduce secrets, so it cannot be used as the owner brief.'
5557
+ );
5558
+ }
5459
5559
  let text2;
5460
5560
  try {
5461
5561
  if (!fs24.statSync(filePath).isFile()) throw new Error("not a file");
@@ -5572,11 +5672,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
5572
5672
  const patterns = [];
5573
5673
  for (const dir of [outDir, tmpDir]) {
5574
5674
  const absolute = path25.resolve(cwd, dir);
5575
- const relative13 = path25.relative(cwd, absolute);
5576
- if (!relative13 || relative13 === ".." || relative13.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative13)) {
5675
+ const relative14 = path25.relative(cwd, absolute);
5676
+ if (!relative14 || relative14 === ".." || relative14.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative14)) {
5577
5677
  continue;
5578
5678
  }
5579
- patterns.push(`${relative13.replace(/\\/g, "/")}/**`);
5679
+ patterns.push(`${relative14.replace(/\\/g, "/")}/**`);
5580
5680
  }
5581
5681
  return patterns;
5582
5682
  }
@@ -6241,7 +6341,7 @@ var BUILTIN_RULE_IDS = new Map(
6241
6341
  function ruleIdFor(name) {
6242
6342
  const builtin = BUILTIN_RULE_IDS.get(name);
6243
6343
  if (builtin !== void 0) return builtin;
6244
- const digest = crypto3.createHash("sha256").update(name).digest("hex").slice(0, 8);
6344
+ const digest = crypto.createHash("sha256").update(name).digest("hex").slice(0, 8);
6245
6345
  return `CS${digest.toUpperCase()}`;
6246
6346
  }
6247
6347
  function generateSarifReport(manifest, findings, rules, toolVersion) {
@@ -6579,7 +6679,7 @@ function renumberParts(parts, contentFingerprint) {
6579
6679
  filename: nameFor(index + 1),
6580
6680
  byteSize: Buffer.byteLength(markdown, "utf8"),
6581
6681
  estimatedTokens,
6582
- sha256: crypto3.createHash("sha256").update(markdown).digest("hex"),
6682
+ sha256: crypto.createHash("sha256").update(markdown).digest("hex"),
6583
6683
  lines: countLines(markdown),
6584
6684
  fileCount: included.length,
6585
6685
  layersCovered: Object.keys(layerCounts).sort()
@@ -6705,7 +6805,7 @@ function rehashPart(part, markdown) {
6705
6805
  metadata: {
6706
6806
  ...part.metadata,
6707
6807
  byteSize: Buffer.byteLength(redistributed, "utf8"),
6708
- sha256: crypto3.createHash("sha256").update(redistributed).digest("hex"),
6808
+ sha256: crypto.createHash("sha256").update(redistributed).digest("hex"),
6709
6809
  lines: countLines(redistributed),
6710
6810
  estimatedTokens
6711
6811
  }
@@ -6786,7 +6886,7 @@ function renderGroups(groups, contentFingerprint, assemble = (group, index, tota
6786
6886
  return groups.map((group, index) => {
6787
6887
  const { filename, content, estimatedTokens } = assemble(group, index, total);
6788
6888
  const byteSize = Buffer.byteLength(content, "utf8");
6789
- const sha2562 = crypto3.createHash("sha256").update(content).digest("hex");
6889
+ const sha2562 = crypto.createHash("sha256").update(content).digest("hex");
6790
6890
  const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
6791
6891
  const includedFiles = group.sections.map(({ file }) => ({
6792
6892
  relativePath: file.relativePath,
@@ -6868,7 +6968,7 @@ function renderSummary(summary, inclusionMode) {
6868
6968
  }
6869
6969
  function anchorForPath(filePath) {
6870
6970
  const slug = filePath.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
6871
- const digest = crypto3.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
6971
+ const digest = crypto.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
6872
6972
  return `${slug || "file"}-${digest}`;
6873
6973
  }
6874
6974
 
@@ -7375,12 +7475,27 @@ function runGit(cwd, args) {
7375
7475
  function isGitRepository(cwd) {
7376
7476
  return runGit(cwd, ["rev-parse", "--is-inside-work-tree"]).out.trim() === "true";
7377
7477
  }
7478
+ function diffSectionPaths(body) {
7479
+ const paths = /* @__PURE__ */ new Set();
7480
+ for (const line of body.split("\n")) {
7481
+ const plus = /^\+\+\+ b\/(.*)$/.exec(line);
7482
+ if (plus !== null) paths.add(plus[1]);
7483
+ const minus = /^--- a\/(.*)$/.exec(line);
7484
+ if (minus !== null) paths.add(minus[1]);
7485
+ const header = /^diff --git a\/(.*?) b\/(.*)$/.exec(line);
7486
+ if (header !== null) {
7487
+ paths.add(header[1]);
7488
+ paths.add(header[2]);
7489
+ }
7490
+ }
7491
+ return [...paths];
7492
+ }
7378
7493
  function generateDiffReport(cwd, options = {}) {
7379
7494
  if (!isGitRepository(cwd)) return null;
7380
7495
  const maxBytes = options.maxBytes ?? 200 * 1024;
7381
7496
  const sections = [];
7382
- let bytes = 0;
7383
7497
  let truncated = false;
7498
+ let omittedSensitive = 0;
7384
7499
  const commands = [
7385
7500
  ["Unstaged", ["diff", "--no-color"]],
7386
7501
  ["Staged", ["diff", "--cached", "--no-color"]]
@@ -7388,28 +7503,47 @@ function generateDiffReport(cwd, options = {}) {
7388
7503
  for (const [title, args] of commands) {
7389
7504
  const result = runGit(cwd, args);
7390
7505
  if (!result.ok || result.out.trim() === "") continue;
7391
- const body = result.out;
7392
- bytes += Buffer.byteLength(body, "utf8");
7393
- const used = Buffer.byteLength(sections.join(""), "utf8");
7394
- const remaining = Math.max(0, maxBytes - used);
7395
- const chunk = Buffer.byteLength(body, "utf8") > remaining ? body.slice(0, remaining) : body;
7396
- if (chunk.length < body.length) truncated = true;
7397
- sections.push("## " + title + " changes\n\nRun: git " + args.join(" ") + "\n\n```diff\n" + chunk + "\n```");
7506
+ const rawSections = result.out.split(/(?=^diff --git )/m).filter((section) => section.length > 0);
7507
+ for (const rawSection of rawSections) {
7508
+ const paths2 = diffSectionPaths(rawSection);
7509
+ const blocked = paths2.some((path26) => isSensitivePath(path26) || options.excluded?.(path26) === true);
7510
+ if (blocked) {
7511
+ omittedSensitive += 1;
7512
+ continue;
7513
+ }
7514
+ const used = Buffer.byteLength(sections.join(""), "utf8");
7515
+ const remaining = Math.max(0, maxBytes - used);
7516
+ if (remaining === 0) {
7517
+ truncated = true;
7518
+ break;
7519
+ }
7520
+ const chunk = truncateToBytes(rawSection, remaining);
7521
+ if (chunk.isTruncated) truncated = true;
7522
+ sections.push(
7523
+ "## " + title + " changes\n\nRun: git " + args.join(" ") + "\n\n```diff\n" + chunk.content + "\n```"
7524
+ );
7525
+ if (chunk.isTruncated) break;
7526
+ }
7398
7527
  }
7399
7528
  if (sections.length === 0) return null;
7400
7529
  const paths = /* @__PURE__ */ new Set();
7401
- for (const match of sections.join("\n").matchAll(/^\+\+\+ b\/(.+)$/gm)) paths.add(match[1]);
7402
- const text2 = [
7530
+ for (const section of sections) for (const path26 of diffSectionPaths(section)) paths.add(path26);
7531
+ const joined = [
7403
7532
  "# Uncommitted changes",
7404
7533
  "",
7405
7534
  "Generated from the repository at the moment the snapshot was written. Untracked files are not",
7406
7535
  "in a diff until they are added; this artifact says what git reports, not what git ignores.",
7407
7536
  "",
7537
+ ...omittedSensitive > 0 ? [
7538
+ "> " + omittedSensitive + " file section(s) omitted: their path is credential-bearing or excluded from the snapshot.",
7539
+ ""
7540
+ ] : [],
7408
7541
  ...sections,
7409
7542
  ...truncated ? ["", "> Truncated at " + maxBytes + " bytes. Run git diff for the rest."] : [],
7410
7543
  ""
7411
7544
  ].join("\n");
7412
- return { text: text2, bytes, truncated, paths: [...paths].sort() };
7545
+ const text2 = scanAndRedactSecrets(joined, options.secretRules ?? [], "reports/diff.md").redacted;
7546
+ return { text: text2, bytes: Buffer.byteLength(text2, "utf8"), truncated, paths: [...paths].sort() };
7413
7547
  }
7414
7548
  function generateLogReport(cwd, options = {}) {
7415
7549
  const count = Math.max(1, Math.min(500, options.count ?? 20));
@@ -7423,13 +7557,15 @@ function generateLogReport(cwd, options = {}) {
7423
7557
  const body = (result.stdout ?? "").trim();
7424
7558
  if (body === "") return null;
7425
7559
  const lines = body.split("\n");
7560
+ const redacted = scanAndRedactSecrets(body, options.secretRules ?? [], "reports/log.md").redacted;
7561
+ const joined = truncateToBytes(redacted, maxBytes).content;
7426
7562
  const text2 = [
7427
7563
  "# Recent commits",
7428
7564
  "",
7429
7565
  "The last " + count + " commits, newest first, one line each.",
7430
7566
  "",
7431
7567
  "```text",
7432
- lines.join("\n").slice(0, maxBytes),
7568
+ joined,
7433
7569
  "```",
7434
7570
  ""
7435
7571
  ].join("\n");
@@ -8397,8 +8533,8 @@ function tsconfigPathsFor(cwd) {
8397
8533
  return value;
8398
8534
  }
8399
8535
  function repositoryRelative(cwd, target) {
8400
- const relative13 = path25.relative(cwd, target).replace(/\\/g, "/");
8401
- return relative13.length === 0 || !relative13.startsWith("..") && !path25.isAbsolute(relative13) ? relative13 : null;
8536
+ const relative14 = path25.relative(cwd, target).replace(/\\/g, "/");
8537
+ return relative14.length === 0 || !relative14.startsWith("..") && !path25.isAbsolute(relative14) ? relative14 : null;
8402
8538
  }
8403
8539
  function rememberFirst(map, key, value) {
8404
8540
  if (!map.has(key)) map.set(key, value);
@@ -8649,71 +8785,6 @@ function detectLanguage(filePath) {
8649
8785
  const ext = path25.posix.extname(base).toLowerCase();
8650
8786
  return LANGUAGE_BY_EXTENSION[ext] ?? "text";
8651
8787
  }
8652
- var SIGNATURE_FILE = "signature.json";
8653
- function loadSigningKey(environment = process.env) {
8654
- const pem = environment.SNAPSHOT_SIGNING_KEY;
8655
- if (pem === void 0 || pem.trim() === "") return null;
8656
- return crypto3.createPrivateKey({ key: pem, format: "pem" });
8657
- }
8658
- function signManifest(manifestPath, options = {}) {
8659
- const bytes = fs24.readFileSync(manifestPath);
8660
- const manifest = JSON.parse(bytes.toString("utf8"));
8661
- if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
8662
- throw new Error("refusing to sign: the manifest has no valid fingerprint");
8663
- }
8664
- const configured = options.key ?? null;
8665
- const key = configured ?? crypto3.generateKeyPairSync("ed25519").privateKey;
8666
- const publicKey = crypto3.createPublicKey(key).export({ type: "spki", format: "der" }).toString("base64");
8667
- const signature = crypto3.sign(null, bytes, key).toString("base64");
8668
- return {
8669
- algorithm: "ed25519",
8670
- signedAt: options.signedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
8671
- fingerprint: manifest.fingerprint,
8672
- manifestSha256: crypto3.createHash("sha256").update(bytes).digest("hex"),
8673
- publicKey,
8674
- signature,
8675
- keyOrigin: configured === null ? "generated" : "configured"
8676
- };
8677
- }
8678
- function writeSignature(snapshotDir, record) {
8679
- const target = path25.join(snapshotDir, SIGNATURE_FILE);
8680
- fs24.writeFileSync(target, JSON.stringify(record, null, 2) + "\n", "utf8");
8681
- return target;
8682
- }
8683
- function verifySnapshotSignature(snapshotDir) {
8684
- const signaturePath = path25.join(snapshotDir, SIGNATURE_FILE);
8685
- const manifestPath = path25.join(snapshotDir, "manifest.json");
8686
- if (!fs24.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
8687
- let record;
8688
- try {
8689
- record = JSON.parse(fs24.readFileSync(signaturePath, "utf8"));
8690
- } catch (error) {
8691
- return { ok: false, reason: "signature.json is not JSON: " + error.message };
8692
- }
8693
- if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
8694
- return { ok: false, reason: "signature.json is not an ed25519 record" };
8695
- }
8696
- let bytes;
8697
- try {
8698
- bytes = fs24.readFileSync(manifestPath);
8699
- } catch {
8700
- return { ok: false, reason: "the signed manifest is missing" };
8701
- }
8702
- const sha2562 = crypto3.createHash("sha256").update(bytes).digest("hex");
8703
- if (sha2562 !== record.manifestSha256) {
8704
- return { ok: false, reason: "manifest.json changed after it was signed" };
8705
- }
8706
- let verified = false;
8707
- try {
8708
- const key = crypto3.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
8709
- verified = crypto3.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
8710
- } catch (error) {
8711
- return { ok: false, reason: "the signature could not be checked: " + error.message };
8712
- }
8713
- return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
8714
- }
8715
-
8716
- // src/validator/validate.ts
8717
8788
  function maskedPath(value, secretRules) {
8718
8789
  return findSecretInPath(value, secretRules)?.masked ?? value;
8719
8790
  }
@@ -8777,7 +8848,7 @@ function emptyDrift() {
8777
8848
  };
8778
8849
  }
8779
8850
  function sha256Hex(buffer) {
8780
- return crypto3.createHash("sha256").update(buffer).digest("hex");
8851
+ return crypto.createHash("sha256").update(buffer).digest("hex");
8781
8852
  }
8782
8853
  function wouldNowBeIncluded(cwd, relativePath) {
8783
8854
  const absolutePath = path25.join(cwd, relativePath);
@@ -9130,17 +9201,18 @@ function validateSnapshot(configInput) {
9130
9201
  return skippedReasons.get(maskedPath(diskFile, config.secretRules)) ?? null;
9131
9202
  };
9132
9203
  let unchangedScope = null;
9204
+ let stagedScope = null;
9133
9205
  const recordedChangedSince = manifest.config?.changedSince;
9134
9206
  const recordedStaged = manifest.config?.staged === true;
9135
9207
  const recordedWithDependents = manifest.config?.withDependents === true;
9136
9208
  if (recordedChangedSince !== void 0 || recordedStaged) {
9137
9209
  try {
9138
- unchangedScope = new Set(
9139
- resolveChangedScope(config.cwd, {
9140
- ...recordedChangedSince === void 0 ? {} : { changedSince: recordedChangedSince },
9141
- ...recordedStaged ? { staged: true } : {}
9142
- }).paths
9143
- );
9210
+ const scope = resolveChangedScope(config.cwd, {
9211
+ ...recordedChangedSince === void 0 ? {} : { changedSince: recordedChangedSince },
9212
+ ...recordedStaged ? { staged: true } : {}
9213
+ });
9214
+ unchangedScope = new Set(scope.paths);
9215
+ if (recordedStaged) stagedScope = new Set(scope.stagedPaths);
9144
9216
  } catch {
9145
9217
  warnings.push(
9146
9218
  "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."
@@ -9151,7 +9223,11 @@ function validateSnapshot(configInput) {
9151
9223
  function becameDependent(diskFile) {
9152
9224
  if (!recordedWithDependents || unchangedScope === null) return false;
9153
9225
  dependentResolver ??= buildImportResolver(
9154
- collection.files.map((file) => ({ relativePath: file }))
9226
+ collection.files.map((file) => ({ relativePath: file })),
9227
+ {
9228
+ tsconfig: tsconfigPathsFor(config.cwd),
9229
+ ...unchangedScope === null ? {} : { extraPaths: unchangedScope }
9230
+ }
9155
9231
  );
9156
9232
  return importsChangedFile(
9157
9233
  diskFile,
@@ -9174,7 +9250,7 @@ function validateSnapshot(configInput) {
9174
9250
  // snapshot was reported as drifting.
9175
9251
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
9176
9252
  (directory) => path25.relative(config.cwd, path25.resolve(config.cwd, directory)).replace(/\\/g, "/")
9177
- ).filter((relative13) => relative13.length > 0 && !relative13.startsWith(".."))
9253
+ ).filter((relative14) => relative14.length > 0 && !relative14.startsWith(".."))
9178
9254
  });
9179
9255
  for (const diskFile of collection.files) {
9180
9256
  const snapshotHash = manifestFileMap.get(diskFile);
@@ -9200,7 +9276,8 @@ function validateSnapshot(configInput) {
9200
9276
  }
9201
9277
  let diskHash;
9202
9278
  try {
9203
- diskHash = sha256Hex(fs24.readFileSync(path25.join(config.cwd, diskFile)));
9279
+ const stagedBlob = recordedStaged && stagedScope?.has(diskFile) === true ? readStagedBlob(config.cwd, diskFile) : null;
9280
+ diskHash = sha256Hex(stagedBlob ?? fs24.readFileSync(path25.join(config.cwd, diskFile)));
9204
9281
  } catch (err) {
9205
9282
  if (err.code === "ENOENT") {
9206
9283
  drift.missingOnDisk.push(diskFile);
@@ -9654,8 +9731,8 @@ function validateSnapshot(configInput) {
9654
9731
  const target = match[1].split("#")[0];
9655
9732
  if (target.length === 0 || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
9656
9733
  const resolved = path25.resolve(snapshotDir, "reports", target);
9657
- const relative13 = path25.relative(snapshotDir, resolved);
9658
- if (relative13.startsWith("..") || path25.isAbsolute(relative13) || !fs24.existsSync(resolved)) {
9734
+ const relative14 = path25.relative(snapshotDir, resolved);
9735
+ if (relative14.startsWith("..") || path25.isAbsolute(relative14) || !fs24.existsSync(resolved)) {
9659
9736
  drift.partIssues.push({
9660
9737
  part: key,
9661
9738
  issue: `links to ${maskedPath(target, config.secretRules)}, which does not exist in the snapshot`
@@ -9749,24 +9826,93 @@ function validateSnapshot(configInput) {
9749
9826
  };
9750
9827
  }
9751
9828
  var HOST_PATTERN = /^[a-z0-9.-]+$/i;
9829
+ function parseIPv4(value) {
9830
+ const parts = value.split(".");
9831
+ if (parts.length !== 4) return null;
9832
+ const octets = [];
9833
+ for (const part of parts) {
9834
+ if (!/^\d{1,3}$/.test(part)) return null;
9835
+ const octet = Number(part);
9836
+ if (octet > 255) return null;
9837
+ octets.push(octet);
9838
+ }
9839
+ return octets;
9840
+ }
9841
+ function isPrivateIPv4(octets) {
9842
+ const [a, b] = octets;
9843
+ 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;
9844
+ }
9845
+ function parseIPv6(value) {
9846
+ const withoutZone = value.split("%")[0] ?? value;
9847
+ if (!withoutZone.includes(":")) return null;
9848
+ const halves = withoutZone.split("::");
9849
+ if (halves.length > 2) return null;
9850
+ const left = halves[0] === "" ? [] : halves[0].split(":");
9851
+ const right = halves.length === 2 && halves[1] !== "" ? halves[1].split(":") : [];
9852
+ const groups = [...left, ...right];
9853
+ if (halves.length === 1 && groups.length !== 8) return null;
9854
+ if (halves.length === 2 && groups.length > 7) return null;
9855
+ const expand = (group) => {
9856
+ if (group.includes(".")) {
9857
+ const octets = parseIPv4(group);
9858
+ if (octets === null) return null;
9859
+ return [
9860
+ (octets[0] << 8 | octets[1]).toString(16),
9861
+ (octets[2] << 8 | octets[3]).toString(16)
9862
+ ];
9863
+ }
9864
+ return [group];
9865
+ };
9866
+ const expanded = [];
9867
+ for (const group of groups) {
9868
+ const next = expand(group);
9869
+ if (next === null) return null;
9870
+ expanded.push(...next);
9871
+ }
9872
+ if (halves.length === 1 && expanded.length !== 8) return null;
9873
+ if (halves.length === 2 && expanded.length > 8) return null;
9874
+ const missing = 8 - expanded.length;
9875
+ const full = halves.length === 2 ? [...expanded.slice(0, left.length), ...Array(missing).fill("0"), ...expanded.slice(left.length)] : expanded;
9876
+ if (full.length !== 8) return null;
9877
+ const numbers = [];
9878
+ for (const group of full) {
9879
+ if (!/^[0-9a-f]{1,4}$/i.test(group)) return null;
9880
+ numbers.push(Number.parseInt(group, 16));
9881
+ }
9882
+ return numbers;
9883
+ }
9884
+ function isPrivateIPv6(groups) {
9885
+ const [first, second, third, fourth, fifth, sixth, seventh, eighth] = groups;
9886
+ const allZeroThrough = (count) => groups.slice(0, count).every((group) => group === 0);
9887
+ if (groups.every((group) => group === 0)) return true;
9888
+ if (allZeroThrough(7) && eighth === 1) return true;
9889
+ if ((first & 65024) === 64512) return true;
9890
+ if ((first & 65472) === 65152) return true;
9891
+ if ((first & 65472) === 65216) return true;
9892
+ if ((first & 65280) === 65280) return true;
9893
+ if (first === 8193 && second === 3512) return true;
9894
+ const mapped = (offset) => isPrivateIPv4([
9895
+ groups[offset] >> 8,
9896
+ groups[offset] & 255,
9897
+ groups[offset + 1] >> 8,
9898
+ groups[offset + 1] & 255
9899
+ ]);
9900
+ if (allZeroThrough(5) && sixth === 65535) return mapped(6);
9901
+ if (allZeroThrough(6) && (seventh !== 0 || eighth !== 0)) return mapped(6);
9902
+ if (first === 100 && second === 65435 && third === 0 && fourth === 0 && fifth === 0 && sixth === 0) {
9903
+ return mapped(6);
9904
+ }
9905
+ if (first === 8194) return mapped(1);
9906
+ return false;
9907
+ }
9752
9908
  function isPrivateHost(host) {
9753
- const value = host.toLowerCase().replace(/^\[|\]$/g, "");
9909
+ const value = host.toLowerCase().replace(/^\[|\]$/g, "").split("%")[0] ?? "";
9754
9910
  if (value === "localhost" || value.endsWith(".localhost") || value.endsWith(".local")) return true;
9755
9911
  if (value === "::1" || value === "0.0.0.0" || value === "::") return true;
9756
- if (value.startsWith("fc") || value.startsWith("fd")) return true;
9757
- if (value.startsWith("fe80")) return true;
9758
- const parts = value.split(".");
9759
- if (parts.length === 4 && parts.every((part) => /^\d{1,3}$/.test(part))) {
9760
- const octets = parts.map(Number);
9761
- if (octets.some((octet) => octet > 255)) return true;
9762
- if (octets[0] === 127) return true;
9763
- if (octets[0] === 10) return true;
9764
- if (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) return true;
9765
- if (octets[0] === 192 && octets[1] === 168) return true;
9766
- if (octets[0] === 169 && octets[1] === 254) return true;
9767
- if (octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127) return true;
9768
- if (octets[0] === 0) return true;
9769
- }
9912
+ const ipv4 = parseIPv4(value);
9913
+ if (ipv4 !== null) return isPrivateIPv4(ipv4);
9914
+ const ipv6 = parseIPv6(value);
9915
+ if (ipv6 !== null) return isPrivateIPv6(ipv6);
9770
9916
  return false;
9771
9917
  }
9772
9918
  function parseRemoteSource(input, options = {}) {
@@ -9841,14 +9987,25 @@ async function assertPublicHost(host, allowPrivate) {
9841
9987
  }
9842
9988
  }
9843
9989
  }
9990
+ function tokenHosts() {
9991
+ const configured = process.env.CODEBASE_SNAPSHOT_GITHUB_HOSTS;
9992
+ if (configured === void 0 || configured.trim() === "") return ["github.com"];
9993
+ return configured.split(",").map((entry) => entry.trim().toLowerCase()).filter((entry) => entry.length > 0);
9994
+ }
9995
+ function tokenAllowedForHost(host) {
9996
+ return tokenHosts().includes(host.toLowerCase().replace(/^\[|\]$/g, ""));
9997
+ }
9844
9998
  function gitEnvironment(token, host) {
9845
9999
  const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_LFS_SKIP_SMUDGE: "1" };
9846
10000
  delete env.GIT_ASKPASS;
9847
10001
  delete env.SSH_ASKPASS;
9848
10002
  if (token !== void 0 && token !== null && token !== "") {
9849
- env.GIT_CONFIG_COUNT = "1";
9850
- env.GIT_CONFIG_KEY_0 = "http.https://" + host + "/.extraheader";
9851
- env.GIT_CONFIG_VALUE_0 = "Authorization: Basic " + Buffer.from("x-access-token:" + token).toString("base64");
10003
+ const normalizedHost = host.toLowerCase().replace(/^\[|\]$/g, "");
10004
+ if (tokenAllowedForHost(normalizedHost)) {
10005
+ env.GIT_CONFIG_COUNT = "1";
10006
+ env.GIT_CONFIG_KEY_0 = "http.https://" + normalizedHost + "/.extraheader";
10007
+ env.GIT_CONFIG_VALUE_0 = "Authorization: Basic " + Buffer.from("x-access-token:" + token).toString("base64");
10008
+ }
9852
10009
  }
9853
10010
  return env;
9854
10011
  }
@@ -9858,15 +10015,29 @@ async function cloneRepository(source, options) {
9858
10015
  const dest = path25.resolve(options.dest);
9859
10016
  fs24.rmSync(dest, { recursive: true, force: true });
9860
10017
  fs24.mkdirSync(dest, { recursive: true });
9861
- const args = ["clone", "--depth", "1", "--single-branch", "--no-tags", "--quiet"];
9862
- if (options.ref !== void 0 && options.ref !== null && options.ref !== "") {
9863
- args.push("--branch", options.ref);
10018
+ const ref = options.ref ?? source.ref;
10019
+ const args = [
10020
+ "-c",
10021
+ "http.followRedirects=false",
10022
+ ...source.kind === "https" ? ["-c", "protocol.file.allow=never", "-c", "protocol.ssh.allow=never"] : [],
10023
+ "clone",
10024
+ "--depth",
10025
+ "1",
10026
+ "--single-branch",
10027
+ "--no-tags",
10028
+ "--quiet"
10029
+ ];
10030
+ if (ref !== void 0 && ref !== null && ref !== "") {
10031
+ args.push("--branch", ref);
9864
10032
  }
9865
10033
  args.push(source.url, dest);
9866
- log("clone: " + source.url + (options.ref ? " (" + options.ref + ")" : ""));
10034
+ log("clone: " + source.url + (ref ? " (" + ref + ")" : ""));
9867
10035
  const started = Date.now();
9868
10036
  const result = spawnSync("git", args, {
9869
- env: gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
10037
+ env: {
10038
+ ...gitEnvironment(options.token, source.host === "file" ? "localhost" : source.host),
10039
+ ...source.kind === "https" ? { GIT_ALLOW_PROTOCOL: "https" } : {}
10040
+ },
9870
10041
  timeout: options.timeoutMs ?? 18e4,
9871
10042
  encoding: "utf8",
9872
10043
  windowsHide: true
@@ -9894,7 +10065,7 @@ async function cloneRepository(source, options) {
9894
10065
  host: source.host,
9895
10066
  owner: source.owner,
9896
10067
  repo: source.repo,
9897
- ref: options.ref !== void 0 && options.ref !== null && options.ref !== "" ? options.ref : source.ref,
10068
+ ref: ref !== void 0 && ref !== null && ref !== "" ? ref : null,
9898
10069
  commit,
9899
10070
  fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
9900
10071
  }
@@ -10264,9 +10435,9 @@ function walk(dir, prefix = "") {
10264
10435
  }
10265
10436
  const files = [];
10266
10437
  for (const entry of entries) {
10267
- const relative13 = prefix === "" ? entry.name : prefix + "/" + entry.name;
10268
- if (entry.isDirectory()) files.push(...walk(path25.join(dir, entry.name), relative13));
10269
- else if (entry.isFile()) files.push(relative13);
10438
+ const relative14 = prefix === "" ? entry.name : prefix + "/" + entry.name;
10439
+ if (entry.isDirectory()) files.push(...walk(path25.join(dir, entry.name), relative14));
10440
+ else if (entry.isFile()) files.push(relative14);
10270
10441
  }
10271
10442
  return files;
10272
10443
  }
@@ -10304,13 +10475,14 @@ function secretTokens(text2) {
10304
10475
  }
10305
10476
  return [...tokens];
10306
10477
  }
10307
- function artifactTextContains(snapshotDir, token) {
10308
- for (const relative13 of walk(snapshotDir)) {
10309
- if (!TEXT_ARTIFACT.test(relative13)) continue;
10310
- const text2 = readText2(path25.join(snapshotDir, relative13));
10311
- if (text2 !== null && text2.includes(token)) return true;
10478
+ function readArtifactTexts(snapshotDir) {
10479
+ const texts = [];
10480
+ for (const relative14 of walk(snapshotDir)) {
10481
+ if (!TEXT_ARTIFACT.test(relative14)) continue;
10482
+ const text2 = readText2(path25.join(snapshotDir, relative14));
10483
+ if (text2 !== null) texts.push(text2);
10312
10484
  }
10313
- return false;
10485
+ return texts;
10314
10486
  }
10315
10487
  function findHostPaths(snapshotDir, repoDir) {
10316
10488
  const patterns = [
@@ -10323,15 +10495,15 @@ function findHostPaths(snapshotDir, repoDir) {
10323
10495
  ];
10324
10496
  const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
10325
10497
  const hits = /* @__PURE__ */ new Set();
10326
- for (const relative13 of walk(snapshotDir)) {
10327
- if (!TEXT_ARTIFACT.test(relative13)) continue;
10328
- const text2 = readText2(path25.join(snapshotDir, relative13));
10498
+ for (const relative14 of walk(snapshotDir)) {
10499
+ if (!TEXT_ARTIFACT.test(relative14)) continue;
10500
+ const text2 = readText2(path25.join(snapshotDir, relative14));
10329
10501
  if (text2 === null) continue;
10330
10502
  for (const pattern of patterns) {
10331
- for (const match of text2.match(pattern) ?? []) hits.add(relative13 + ": " + match);
10503
+ for (const match of text2.match(pattern) ?? []) hits.add(relative14 + ": " + match);
10332
10504
  }
10333
10505
  repoPattern.lastIndex = 0;
10334
- if (repoPattern.test(text2)) hits.add(relative13 + ": the repository absolute path");
10506
+ if (repoPattern.test(text2)) hits.add(relative14 + ": the repository absolute path");
10335
10507
  }
10336
10508
  return [...hits];
10337
10509
  }
@@ -10578,13 +10750,13 @@ function auditSnapshot(options) {
10578
10750
  let artifactCount = 0;
10579
10751
  for (const [key, value] of Object.entries(artifacts)) {
10580
10752
  if (value === null || value === void 0) continue;
10581
- const relative13 = ARTIFACT_FILES[key];
10582
- if (relative13 === void 0) continue;
10753
+ const relative14 = ARTIFACT_FILES[key];
10754
+ if (relative14 === void 0) continue;
10583
10755
  artifactCount += 1;
10584
- const bytes = readBytes(path25.join(snapshotDir, relative13));
10585
- if (bytes === null) artifactProblems.push(relative13 + " is missing");
10756
+ const bytes = readBytes(path25.join(snapshotDir, relative14));
10757
+ if (bytes === null) artifactProblems.push(relative14 + " is missing");
10586
10758
  else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
10587
- artifactProblems.push(relative13 + " changed");
10759
+ artifactProblems.push(relative14 + " changed");
10588
10760
  }
10589
10761
  }
10590
10762
  checks.push(
@@ -11314,25 +11486,25 @@ function auditSnapshot(options) {
11314
11486
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
11315
11487
  const leakHits = [];
11316
11488
  let scannedBytes = 0;
11317
- for (const relative13 of walk(snapshotDir)) {
11318
- if (!TEXT_ARTIFACT.test(relative13) || scannedBytes > scanBudget) continue;
11319
- if (relative13 === SIGNATURE_FILE) continue;
11320
- const text2 = readText2(path25.join(snapshotDir, relative13));
11489
+ for (const relative14 of walk(snapshotDir)) {
11490
+ if (!TEXT_ARTIFACT.test(relative14) || scannedBytes > scanBudget) continue;
11491
+ if (relative14 === SIGNATURE_FILE) continue;
11492
+ const text2 = readText2(path25.join(snapshotDir, relative14));
11321
11493
  if (text2 === null) continue;
11322
11494
  scannedBytes += Buffer.byteLength(text2, "utf8");
11323
11495
  let findingCount = 0;
11324
- if (/^parts[\\/].*\.md$/i.test(relative13)) {
11496
+ if (/^parts[\\/].*\.md$/i.test(relative14)) {
11325
11497
  let headerText = text2;
11326
11498
  for (const section of parsePartSections(text2)) {
11327
11499
  findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
11328
11500
  headerText = headerText.replace(section.body, "");
11329
11501
  }
11330
- findingCount += scanAndRedactSecrets(headerText, rules, relative13).findings.length;
11502
+ findingCount += scanAndRedactSecrets(headerText, rules, relative14).findings.length;
11331
11503
  } else {
11332
- findingCount = scanAndRedactSecrets(text2, rules, relative13).findings.length;
11504
+ findingCount = scanAndRedactSecrets(text2, rules, relative14).findings.length;
11333
11505
  }
11334
11506
  if (findingCount > 0) {
11335
- leakHits.push(relative13 + " (" + findingCount + " line(s))");
11507
+ leakHits.push(relative14 + " (" + findingCount + " line(s))");
11336
11508
  }
11337
11509
  }
11338
11510
  const signatureRecordPath = path25.join(snapshotDir, SIGNATURE_FILE);
@@ -11377,13 +11549,15 @@ function auditSnapshot(options) {
11377
11549
  );
11378
11550
  const leakedFrom = [];
11379
11551
  let compared = 0;
11552
+ const artifactTexts = readArtifactTexts(snapshotDir);
11553
+ const artifactContains = (token) => artifactTexts.some((text2) => text2.includes(token));
11380
11554
  for (const record of skippedSensitive.slice(0, 40)) {
11381
11555
  if (record.path.includes("[REDACTED") || compared > 400) continue;
11382
11556
  const text2 = readText2(path25.join(repoDir, record.path));
11383
11557
  if (text2 === null) continue;
11384
11558
  for (const token of secretTokens(text2)) {
11385
11559
  compared += 1;
11386
- if (artifactTextContains(snapshotDir, token)) leakedFrom.push(record.path);
11560
+ if (artifactContains(token)) leakedFrom.push(record.path);
11387
11561
  }
11388
11562
  }
11389
11563
  checks.push(
@@ -11533,23 +11707,23 @@ function describeMatcher(matcher) {
11533
11707
  function normalizeTarget(cwd, target) {
11534
11708
  const resolvedCwd = path25.resolve(cwd);
11535
11709
  const absolute = path25.resolve(resolvedCwd, target);
11536
- const relative13 = path25.relative(resolvedCwd, absolute);
11537
- if (relative13 === "" || relative13 === ".." || relative13.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative13)) {
11710
+ const relative14 = path25.relative(resolvedCwd, absolute);
11711
+ if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative14)) {
11538
11712
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
11539
11713
  }
11540
- return { relative: relative13.split(path25.sep).join("/"), outsideRoot: false };
11714
+ return { relative: relative14.split(path25.sep).join("/"), outsideRoot: false };
11541
11715
  }
11542
11716
  function findRuleMatch(rules, relativePath) {
11543
11717
  return rules.find(
11544
11718
  (rule) => matchRule(relativePath, rule.match)
11545
11719
  );
11546
11720
  }
11547
- function findRecordedAncestor(skipped, relative13, maskedPath2) {
11721
+ function findRecordedAncestor(skipped, relative14, maskedPath2) {
11548
11722
  let nearest;
11549
11723
  for (const record of skipped) {
11550
11724
  const ancestorPath = record.path;
11551
11725
  if (ancestorPath.length === 0) continue;
11552
- const isAncestor = relative13.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
11726
+ const isAncestor = relative14.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
11553
11727
  if (!isAncestor) continue;
11554
11728
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
11555
11729
  }
@@ -11565,8 +11739,8 @@ function readManifest2(config) {
11565
11739
  }
11566
11740
  function explainPath(config, target) {
11567
11741
  const normalized = normalizeTarget(config.cwd, target);
11568
- const relative13 = normalized.relative;
11569
- const maskedPath2 = findSecretInPath(relative13, config.secretRules)?.masked ?? relative13;
11742
+ const relative14 = normalized.relative;
11743
+ const maskedPath2 = findSecretInPath(relative14, config.secretRules)?.masked ?? relative14;
11570
11744
  if (normalized.outsideRoot) {
11571
11745
  return {
11572
11746
  path: maskedPath2,
@@ -11576,7 +11750,7 @@ function explainPath(config, target) {
11576
11750
  detail: "path resolves outside the configured repository root and was not inspected"
11577
11751
  };
11578
11752
  }
11579
- const absolute = path25.join(config.cwd, relative13);
11753
+ const absolute = path25.join(config.cwd, relative14);
11580
11754
  const result = {
11581
11755
  path: maskedPath2,
11582
11756
  exists: fs24.existsSync(absolute),
@@ -11594,11 +11768,11 @@ function explainPath(config, target) {
11594
11768
  // that is only missing because the walker dropped the tool's own output directory.
11595
11769
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
11596
11770
  (directory) => path25.relative(config.cwd, path25.resolve(config.cwd, directory)).replace(/\\/g, "/")
11597
- ).filter((relative14) => relative14.length > 0 && !relative14.startsWith(".."))
11771
+ ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
11598
11772
  });
11599
- if (!collection.files.includes(relative13)) {
11773
+ if (!collection.files.includes(relative14)) {
11600
11774
  const record = collection.skipped.find(
11601
- (entry2) => entry2.path === relative13 || entry2.path === maskedPath2
11775
+ (entry2) => entry2.path === relative14 || entry2.path === maskedPath2
11602
11776
  );
11603
11777
  if (record) {
11604
11778
  result.reason = record.reason;
@@ -11607,7 +11781,7 @@ function explainPath(config, target) {
11607
11781
  result.reason = "missing";
11608
11782
  result.detail = "no such file or directory, relative to the configured cwd";
11609
11783
  } else {
11610
- const ancestor = findRecordedAncestor(collection.skipped, relative13, maskedPath2);
11784
+ const ancestor = findRecordedAncestor(collection.skipped, relative14, maskedPath2);
11611
11785
  if (ancestor) {
11612
11786
  result.reason = ancestor.reason;
11613
11787
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -11627,13 +11801,15 @@ function explainPath(config, target) {
11627
11801
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
11628
11802
  ...config.staged === true ? { staged: true } : {}
11629
11803
  });
11630
- inScope = scope.paths.has(relative13);
11804
+ inScope = scope.paths.has(relative14);
11631
11805
  if (!inScope && config.withDependents === true) {
11632
11806
  inScope = importsChangedFile(
11633
- relative13,
11634
- importsOfFile(relative13, absolute),
11807
+ relative14,
11808
+ importsOfFile(relative14, absolute),
11635
11809
  scope.paths,
11636
- buildImportResolver(collection.files.map((file) => ({ relativePath: file })))
11810
+ buildImportResolver(collection.files.map((file) => ({ relativePath: file })), {
11811
+ tsconfig: tsconfigPathsFor(config.cwd)
11812
+ })
11637
11813
  );
11638
11814
  }
11639
11815
  scopeDetail = scope.detail;
@@ -11689,15 +11865,15 @@ function explainPath(config, target) {
11689
11865
  result.bytes = buffer.length;
11690
11866
  result.lines = countLines(text2);
11691
11867
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
11692
- const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative13);
11868
+ const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative14);
11693
11869
  result.secretCount = findings.length;
11694
11870
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
11695
11871
  let inclusionMode = "full";
11696
- if (config.skeleton === true && isSkeletonizable(relative13)) {
11697
- const skeleton = skeletonizeTypeScript(text2, relative13);
11872
+ if (config.skeleton === true && isSkeletonizable(relative14)) {
11873
+ const skeleton = skeletonizeTypeScript(text2, relative14);
11698
11874
  if (skeleton.collapsed > 0) inclusionMode = "signatures";
11699
11875
  }
11700
- if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative13) && stripComments2(text2, relative13).removed > 0) {
11876
+ if (inclusionMode === "full" && config.stripComments === true && isCommentStrippable(relative14) && stripComments2(text2, relative14).removed > 0) {
11701
11877
  inclusionMode = "comments-stripped";
11702
11878
  }
11703
11879
  if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
@@ -11706,18 +11882,18 @@ function explainPath(config, target) {
11706
11882
  }
11707
11883
  result.inclusionMode = inclusionMode;
11708
11884
  }
11709
- result.layer = classifyLayer(relative13, config.layers);
11710
- result.kind = classifyKind(relative13, config.kinds);
11711
- result.language = detectLanguage(relative13);
11712
- const layerRule = findRuleMatch(config.layers, relative13);
11885
+ result.layer = classifyLayer(relative14, config.layers);
11886
+ result.kind = classifyKind(relative14, config.kinds);
11887
+ result.language = detectLanguage(relative14);
11888
+ const layerRule = findRuleMatch(config.layers, relative14);
11713
11889
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
11714
- const kindRule = findRuleMatch(config.kinds, relative13);
11890
+ const kindRule = findRuleMatch(config.kinds, relative14);
11715
11891
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
11716
11892
  const manifest = readManifest2(config);
11717
- const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative13) : void 0;
11893
+ const entry = Array.isArray(manifest?.files) ? manifest.files.find((file) => file.relativePath === relative14) : void 0;
11718
11894
  result.part = entry?.part ?? null;
11719
11895
  if (entry === void 0) {
11720
- const record = manifest?.skipped?.find((skip) => skip.path === relative13);
11896
+ const record = manifest?.skipped?.find((skip) => skip.path === relative14);
11721
11897
  if (record !== void 0 && (record.reason === "not-selected" || record.reason === "unchanged")) {
11722
11898
  result.included = false;
11723
11899
  result.reason = record.reason;
@@ -11782,6 +11958,7 @@ const { parentPort, workerData } = require("node:worker_threads");
11782
11958
  const manifest = mod.generateSnapshot(config, {
11783
11959
  dryRun: workerData.dryRun === true,
11784
11960
  ...(workerData.narrow ?? {}),
11961
+ ...(workerData.runId === undefined ? {} : { runId: workerData.runId }),
11785
11962
  });
11786
11963
  const skipCounts = new Map();
11787
11964
  for (const record of manifest.skipped) {
@@ -11827,8 +12004,13 @@ function generateInWorker(cwd, cliOptions, options = {}) {
11827
12004
  const finish = (result) => {
11828
12005
  if (settled) return;
11829
12006
  settled = true;
11830
- if (worker !== null) void worker.terminate();
11831
- resolve14(result);
12007
+ const terminated = worker === null ? Promise.resolve(void 0) : worker.terminate();
12008
+ void terminated.catch(() => void 0).then(() => {
12009
+ if (!result.ok && options.runId !== void 0 && options.lockRoots !== void 0) {
12010
+ releaseAbandonedRun(options.lockRoots, options.runId);
12011
+ }
12012
+ resolve14(result);
12013
+ });
11832
12014
  };
11833
12015
  const isCjs = typeof __dirname !== "undefined";
11834
12016
  const directory = isCjs ? __dirname : path25.dirname(fileURLToPath(import.meta.url));
@@ -11840,7 +12022,8 @@ function generateInWorker(cwd, cliOptions, options = {}) {
11840
12022
  cwd,
11841
12023
  cliOptions,
11842
12024
  dryRun: options.dryRun === true,
11843
- narrow: options.narrow ?? {}
12025
+ narrow: options.narrow ?? {},
12026
+ ...options.runId === void 0 ? {} : { runId: options.runId }
11844
12027
  }
11845
12028
  });
11846
12029
  } catch (error) {
@@ -12005,7 +12188,16 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
12005
12188
  if (overrides.withDependents === true) cliOptions.withDependents = true;
12006
12189
  try {
12007
12190
  const config = resolveConfig(loaded.config, cliOptions, root);
12008
- return { ok: true, workspace: { root, config, configFile: loaded.file, cliOptions } };
12191
+ return {
12192
+ ok: true,
12193
+ workspace: {
12194
+ root,
12195
+ config,
12196
+ configFile: loaded.file,
12197
+ sourceConfig: loaded.config ?? null,
12198
+ cliOptions
12199
+ }
12200
+ };
12009
12201
  } catch (error) {
12010
12202
  return { ok: false, message: error instanceof Error ? error.message : String(error) };
12011
12203
  }
@@ -12019,8 +12211,8 @@ function partPathFor(workspace, filename) {
12019
12211
  if (filename.length === 0 || filename.includes("\0")) return null;
12020
12212
  const partsDir = path25.resolve(workspace.root, workspace.config.outDir, "parts");
12021
12213
  const resolved = path25.resolve(partsDir, filename);
12022
- const relative13 = path25.relative(partsDir, resolved);
12023
- if (relative13.length === 0 || relative13.includes(path25.sep) || relative13.includes("/") || relative13.includes("\\") || path25.isAbsolute(relative13)) {
12214
+ const relative14 = path25.relative(partsDir, resolved);
12215
+ if (relative14.length === 0 || relative14.includes(path25.sep) || relative14.includes("/") || relative14.includes("\\") || path25.isAbsolute(relative14)) {
12024
12216
  return null;
12025
12217
  }
12026
12218
  let stats;
@@ -12194,11 +12386,11 @@ function toRelativePath(root, value) {
12194
12386
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
12195
12387
  const resolvedRoot = path25.resolve(root);
12196
12388
  const absolute = path25.resolve(resolvedRoot, cleaned);
12197
- const relative13 = path25.relative(resolvedRoot, absolute);
12198
- if (relative13 === "" || relative13 === ".." || relative13.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative13)) {
12389
+ const relative14 = path25.relative(resolvedRoot, absolute);
12390
+ if (relative14 === "" || relative14 === ".." || relative14.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative14)) {
12199
12391
  return null;
12200
12392
  }
12201
- return relative13.split(path25.sep).join("/");
12393
+ return relative14.split(path25.sep).join("/");
12202
12394
  }
12203
12395
  function symbolsOf(entry) {
12204
12396
  const summary = entry.summary;
@@ -12412,7 +12604,9 @@ var testsTool = {
12412
12604
  const cap = Math.max(1, typeof args.maxFiles === "number" ? args.maxFiles : 50);
12413
12605
  const isTest2 = (filePath) => /(^|\/)(tests?|__tests__|spec)\//.test(filePath) || /\.(test|spec)\.[a-z0-9]+$/i.test(filePath);
12414
12606
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath, file]));
12415
- const resolver = buildImportResolver(read.manifest.files, {});
12607
+ const resolver = buildImportResolver(read.manifest.files, {
12608
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
12609
+ });
12416
12610
  const testFiles = read.manifest.files.filter((file) => isTest2(file.relativePath));
12417
12611
  const importsOf = (filePath) => {
12418
12612
  const entry = read.manifest.indexes.imports.byFile.find((candidate) => candidate.path === filePath);
@@ -12460,9 +12654,13 @@ var workspaceTool = {
12460
12654
  },
12461
12655
  annotations: READ_ONLY,
12462
12656
  async handler(args, context) {
12463
- const root = path25.resolve(context.cwd, typeof args.root === "string" ? args.root : ".");
12464
- const outDir = typeof args.outDir === "string" ? args.outDir : "snapshot";
12465
- const index = path25.resolve(root, outDir, "WORKSPACE.json");
12657
+ const prepared = await prepare(args, context, outDirOverride(args));
12658
+ if (!prepared.ok) return prepared.outcome;
12659
+ const index = path25.resolve(
12660
+ prepared.workspace.root,
12661
+ prepared.workspace.config.outDir,
12662
+ "WORKSPACE.json"
12663
+ );
12466
12664
  let text2;
12467
12665
  try {
12468
12666
  text2 = fs24.readFileSync(index, "utf8");
@@ -12519,7 +12717,9 @@ var neighborsTool = {
12519
12717
  const file = read.manifest.files.find((candidate) => candidate.relativePath === wanted) ?? read.manifest.files.find((candidate) => candidate.relativePath.toLowerCase() === wanted.toLowerCase());
12520
12718
  if (file === void 0) return { text: wanted + " is not in the snapshot; snapshot_explain says why.", isError: true };
12521
12719
  const byPath = new Map(read.manifest.files.map((candidate) => [candidate.relativePath, candidate]));
12522
- const resolver = buildImportResolver(read.manifest.files, {});
12720
+ const resolver = buildImportResolver(read.manifest.files, {
12721
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
12722
+ });
12523
12723
  const entry = read.manifest.indexes.imports.byFile.find((candidate) => candidate.path === file.relativePath);
12524
12724
  const imports = [];
12525
12725
  for (const specifier of entry?.imports ?? []) {
@@ -12661,7 +12861,9 @@ var cyclesTool = {
12661
12861
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
12662
12862
  const cap = Math.max(1, typeof args.maxComponents === "number" ? args.maxComponents : 20);
12663
12863
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath, file]));
12664
- const resolver = buildImportResolver(read.manifest.files, {});
12864
+ const resolver = buildImportResolver(read.manifest.files, {
12865
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
12866
+ });
12665
12867
  const edges = /* @__PURE__ */ new Map();
12666
12868
  for (const path26 of byPath.keys()) edges.set(path26, []);
12667
12869
  for (const entry of read.manifest.indexes.imports.byFile) {
@@ -13861,10 +14063,17 @@ var generateTool = {
13861
14063
  ...typeof args.slice === "string" ? { slice: { question: args.slice, ...typeof args.sliceTokens === "number" ? { maxTokens: args.sliceTokens } : {} } } : {},
13862
14064
  ...typeof args.budgetTokens === "number" ? { budgetTokens: args.budgetTokens } : {}
13863
14065
  };
14066
+ let lockRoots;
14067
+ try {
14068
+ const safe = resolveSafeOutputDirs(workspace.config);
14069
+ lockRoots = [safe.outDir, safe.tmpDir];
14070
+ } catch (error) {
14071
+ return failure(error instanceof Error ? error.message : String(error));
14072
+ }
13864
14073
  const result = await generateInWorker(
13865
14074
  workspace.root,
13866
14075
  { ...workspace.cliOptions, ...reportOptions },
13867
- { signal: controller.signal, narrow }
14076
+ { signal: controller.signal, narrow, runId: randomUUID(), lockRoots }
13868
14077
  );
13869
14078
  if (!result.ok) return failure(result.message);
13870
14079
  context.notify?.({ message: "writing the snapshot", progress: 2, total: 2 });
@@ -13898,16 +14107,42 @@ var generateTool = {
13898
14107
  };
13899
14108
  function configAsGenerated(workspace, manifest) {
13900
14109
  const recorded = manifest.config;
14110
+ const cli = workspace.cliOptions;
14111
+ const source = workspace.sourceConfig;
14112
+ const configured = (key) => source !== null && Object.prototype.hasOwnProperty.call(source, key);
14113
+ const sourceArtifacts = source !== null && source.artifacts !== null && typeof source.artifacts === "object" ? source.artifacts : null;
14114
+ const artifacts = { ...workspace.config.artifacts };
14115
+ if (recorded?.artifacts !== void 0) {
14116
+ for (const [key, value] of Object.entries(recorded.artifacts)) {
14117
+ if (sourceArtifacts === null || !Object.prototype.hasOwnProperty.call(sourceArtifacts, key)) {
14118
+ artifacts[key] = value;
14119
+ }
14120
+ }
14121
+ }
14122
+ let artifactOverride = recorded?.artifacts !== void 0;
14123
+ if (cli.includeDiffs === true) {
14124
+ artifacts.diff = true;
14125
+ artifactOverride = true;
14126
+ }
14127
+ if (cli.includeLogs !== void 0) {
14128
+ artifacts.log = true;
14129
+ artifactOverride = true;
14130
+ }
14131
+ if (cli.tokenTree === true) {
14132
+ artifacts.tokenTree = true;
14133
+ artifactOverride = true;
14134
+ }
14135
+ const choose = (key, recordedValue, current, cliValue) => cliValue !== void 0 ? cliValue : configured(key) ? current : recordedValue ?? current;
13901
14136
  return {
13902
14137
  ...workspace.config,
13903
- ...recorded?.artifacts === void 0 ? {} : { artifacts: recorded.artifacts },
13904
- ...recorded?.stripComments === void 0 ? {} : { stripComments: recorded.stripComments },
13905
- ...recorded?.removeEmptyLines === void 0 ? {} : { removeEmptyLines: recorded.removeEmptyLines },
13906
- ...recorded?.pack === void 0 ? {} : { pack: recorded.pack },
13907
- ...recorded?.logCount === void 0 ? {} : { logCount: recorded.logCount },
13908
- ...recorded?.skeleton === void 0 ? {} : { skeleton: recorded.skeleton },
13909
- ...recorded?.sarif === void 0 ? {} : { sarif: recorded.sarif },
13910
- ...recorded?.maxParts === void 0 ? {} : { maxParts: recorded.maxParts }
14138
+ ...artifactOverride ? { artifacts } : {},
14139
+ ...cli.stripComments === true || configured("stripComments") || recorded?.stripComments !== void 0 ? { stripComments: choose("stripComments", recorded?.stripComments, workspace.config.stripComments, cli.stripComments === true ? true : void 0) } : {},
14140
+ ...cli.removeEmptyLines === true || configured("removeEmptyLines") || recorded?.removeEmptyLines !== void 0 ? { removeEmptyLines: choose("removeEmptyLines", recorded?.removeEmptyLines, workspace.config.removeEmptyLines, cli.removeEmptyLines === true ? true : void 0) } : {},
14141
+ ...cli.pack !== void 0 || configured("pack") || recorded?.pack !== void 0 ? { pack: choose("pack", recorded?.pack ?? void 0, workspace.config.pack, cli.pack) } : {},
14142
+ ...cli.includeLogs !== void 0 || configured("logCount") || recorded?.logCount !== void 0 ? { logCount: choose("logCount", recorded?.logCount, workspace.config.logCount, cli.includeLogs) } : {},
14143
+ ...cli.skeleton === true || configured("skeleton") || recorded?.skeleton !== void 0 ? { skeleton: choose("skeleton", recorded?.skeleton, workspace.config.skeleton, cli.skeleton === true ? true : void 0) } : {},
14144
+ ...cli.sarif === true || configured("sarif") || recorded?.sarif !== void 0 ? { sarif: choose("sarif", recorded?.sarif, workspace.config.sarif, cli.sarif === true ? true : void 0) } : {},
14145
+ ...configured("maxParts") || recorded?.maxParts !== void 0 ? { maxParts: choose("maxParts", recorded?.maxParts, workspace.config.maxParts) } : {}
13911
14146
  };
13912
14147
  }
13913
14148
  var validateTool = {
@@ -14144,7 +14379,9 @@ var dependentsTool = {
14144
14379
  }
14145
14380
  const direction = args.direction === "imports" || args.direction === "imported-by" ? String(args.direction) : "both";
14146
14381
  const limit = typeof args.limit === "number" && args.limit > 0 ? Math.floor(args.limit) : 50;
14147
- const resolver = buildImportResolver(manifest.files);
14382
+ const resolver = buildImportResolver(manifest.files, {
14383
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
14384
+ });
14148
14385
  const imports = [];
14149
14386
  const unresolved = [];
14150
14387
  if (direction !== "imported-by") {
@@ -15622,6 +15859,10 @@ function buildAgentContract() {
15622
15859
  { key: "maxPartBytes", type: "number | string", default: 307200, summary: "Per-part byte budget." },
15623
15860
  { key: "maxPartTokens", type: "number | string | null", default: null, summary: "Per-part token ceiling; narrows maxPartBytes. Minimum 1024." },
15624
15861
  { key: "skeleton", type: "boolean", default: false, summary: "Collapse function bodies to `{ /* ... */ }` in TS, JS, TSX and JSX files." },
15862
+ { key: "stripComments", type: "boolean", default: false, summary: "Remove comment text from JS/TS bodies." },
15863
+ { key: "removeEmptyLines", type: "boolean", default: false, summary: "Drop blank lines from emitted bodies; the part's line numbers move, and files[] records emptyLinesRemoved." },
15864
+ { key: "pack", type: '"single" | "xml" | "json" | null', default: null, summary: "Write one single-file pack in this format." },
15865
+ { key: "logCount", type: "number", default: 20, summary: "Commit lines in reports/log.md (also set by --include-logs <n>)." },
15625
15866
  { key: "sarif", type: "boolean", default: false, summary: "Also write reports/audit.sarif." },
15626
15867
  { key: "changedSince", type: "string | null", default: null, summary: "Snapshot only files that differ from this git ref." },
15627
15868
  { key: "staged", type: "boolean", default: false, summary: "Snapshot only files staged in the index." },
@@ -16793,9 +17034,9 @@ function dosDateTime(date) {
16793
17034
  function walkFiles(root, prefix = "") {
16794
17035
  const files = [];
16795
17036
  for (const entry of fs24.readdirSync(path25.join(root, prefix), { withFileTypes: true })) {
16796
- const relative13 = prefix === "" ? entry.name : prefix + "/" + entry.name;
16797
- if (entry.isDirectory()) files.push(...walkFiles(root, relative13));
16798
- else if (entry.isFile()) files.push(relative13);
17037
+ const relative14 = prefix === "" ? entry.name : prefix + "/" + entry.name;
17038
+ if (entry.isDirectory()) files.push(...walkFiles(root, relative14));
17039
+ else if (entry.isFile()) files.push(relative14);
16799
17040
  }
16800
17041
  return files;
16801
17042
  }
@@ -16803,11 +17044,11 @@ function writeZip(options) {
16803
17044
  const entries = [...options.entries ?? []];
16804
17045
  if (options.directory !== void 0) {
16805
17046
  const root = options.directory;
16806
- for (const relative13 of walkFiles(root)) {
16807
- if (options.skip !== void 0 && options.skip(relative13)) continue;
16808
- const full = path25.join(root, relative13);
17047
+ for (const relative14 of walkFiles(root)) {
17048
+ if (options.skip !== void 0 && options.skip(relative14)) continue;
17049
+ const full = path25.join(root, relative14);
16809
17050
  const stat = fs24.statSync(full);
16810
- entries.push({ name: relative13, content: fs24.readFileSync(full), mtime: stat.mtime });
17051
+ entries.push({ name: relative14, content: fs24.readFileSync(full), mtime: stat.mtime });
16811
17052
  }
16812
17053
  }
16813
17054
  if (entries.length > 65535) {
@@ -17000,8 +17241,13 @@ var SERVE_PAGE = `<!doctype html>
17000
17241
  $("counts").textContent = info.included + " included / " + info.skipped + " skipped";
17001
17242
  $("files").innerHTML = "";
17002
17243
  for (const file of info.files.slice(0, 400)) {
17244
+ // A manifest is untrusted input. Interpolating file.part (or a path) into innerHTML let a
17245
+ // crafted manifest run script in the serve origin and read the token from localStorage.
17003
17246
  const li = document.createElement("li");
17004
- li.innerHTML = "<b>" + file.path.replace(/[<>&]/g, "") + "</b> " + file.part;
17247
+ const name = document.createElement("b");
17248
+ name.textContent = file.path;
17249
+ li.appendChild(name);
17250
+ li.appendChild(document.createTextNode(" " + file.part));
17005
17251
  $("files").appendChild(li);
17006
17252
  }
17007
17253
  }
@@ -17038,16 +17284,55 @@ async function startWebServer(options) {
17038
17284
  if (token === null && !["127.0.0.1", "localhost", "::1"].includes(host)) {
17039
17285
  throw new Error("Refusing to serve " + host + " without a token.");
17040
17286
  }
17041
- const mcp = createServer({ cwd: options.cwd, log });
17287
+ const createMcp = () => createServer({ cwd: options.cwd, log });
17288
+ const mcpPerSocket = /* @__PURE__ */ new WeakMap();
17289
+ const mcpFor = (socket) => {
17290
+ let server2 = mcpPerSocket.get(socket);
17291
+ if (server2 === void 0) {
17292
+ server2 = createMcp();
17293
+ mcpPerSocket.set(socket, server2);
17294
+ }
17295
+ return server2;
17296
+ };
17042
17297
  const temporaryClones = /* @__PURE__ */ new Set();
17043
17298
  const allowedRoots = [path25.resolve(options.cwd)];
17299
+ const canonical = (candidate) => {
17300
+ try {
17301
+ return fs24.realpathSync(candidate);
17302
+ } catch {
17303
+ return null;
17304
+ }
17305
+ };
17306
+ const inside = (resolved) => allowedRoots.some((root) => {
17307
+ const canonicalRoot = canonical(root);
17308
+ if (canonicalRoot === null) return false;
17309
+ const relative14 = path25.relative(canonicalRoot, resolved);
17310
+ return relative14 === "" || !relative14.startsWith(`..${path25.sep}`) && relative14 !== ".." && !path25.isAbsolute(relative14);
17311
+ });
17044
17312
  const insideAllowedRoots = (candidate) => {
17313
+ const resolved = canonical(candidate);
17314
+ return resolved === null ? false : inside(resolved);
17315
+ };
17316
+ const lexicallyInside = (candidate) => {
17045
17317
  const resolved = path25.resolve(candidate);
17046
17318
  return allowedRoots.some((root) => {
17047
- const prefix = root.endsWith(path25.sep) ? root : root + path25.sep;
17048
- return resolved === root || resolved.startsWith(prefix);
17319
+ const prefix = path25.resolve(root) + path25.sep;
17320
+ return resolved === path25.resolve(root) || resolved.startsWith(prefix);
17049
17321
  });
17050
17322
  };
17323
+ const insideAllowedRootsForWrite = (candidate) => {
17324
+ let existing = path25.resolve(candidate);
17325
+ const tail = [];
17326
+ while (!fs24.existsSync(existing)) {
17327
+ tail.unshift(path25.basename(existing));
17328
+ const parent = path25.dirname(existing);
17329
+ if (parent === existing) break;
17330
+ existing = parent;
17331
+ }
17332
+ const resolved = canonical(existing);
17333
+ if (resolved === null) return false;
17334
+ return inside(tail.length === 0 ? resolved : path25.join(resolved, ...tail));
17335
+ };
17051
17336
  const authorized = (request) => {
17052
17337
  if (token === null) return true;
17053
17338
  const header = request.headers.authorization ?? "";
@@ -17071,7 +17356,10 @@ async function startWebServer(options) {
17071
17356
  cors["access-control-allow-headers"] = "authorization, content-type";
17072
17357
  cors["access-control-allow-methods"] = "GET, POST, OPTIONS";
17073
17358
  }
17359
+ let responseSent = false;
17074
17360
  const send = (status, body, extra = {}) => {
17361
+ if (responseSent) return;
17362
+ responseSent = true;
17075
17363
  const text2 = typeof body === "string" ? body : JSON.stringify(body);
17076
17364
  response.writeHead(status, {
17077
17365
  ...cors,
@@ -17102,10 +17390,13 @@ async function startWebServer(options) {
17102
17390
  const url = new URL(request.url ?? "/", "http://localhost");
17103
17391
  if (request.method === "POST" && (request.url === "/mcp" || (request.url ?? "").startsWith("/mcp?"))) {
17104
17392
  let received = 0;
17393
+ let tooLarge = false;
17105
17394
  const chunks = [];
17106
17395
  request.on("data", (chunk) => {
17396
+ if (tooLarge) return;
17107
17397
  received += chunk.length;
17108
17398
  if (received > 2 * 1024 * 1024) {
17399
+ tooLarge = true;
17109
17400
  request.destroy();
17110
17401
  send(413, { error: "request body too large" });
17111
17402
  return;
@@ -17113,6 +17404,7 @@ async function startWebServer(options) {
17113
17404
  chunks.push(chunk);
17114
17405
  });
17115
17406
  request.on("end", () => {
17407
+ if (tooLarge) return;
17116
17408
  void (async () => {
17117
17409
  let message;
17118
17410
  try {
@@ -17122,9 +17414,14 @@ async function startWebServer(options) {
17122
17414
  return;
17123
17415
  }
17124
17416
  const batch = Array.isArray(message) ? message : [message];
17417
+ if (batch.length > 100) {
17418
+ send(400, { error: "JSON-RPC batch is limited to 100 messages" });
17419
+ return;
17420
+ }
17421
+ const server2 = mcpFor(request.socket);
17125
17422
  const answers = [];
17126
17423
  for (const item of batch) {
17127
- const answer = await mcp.handle(item);
17424
+ const answer = await server2.handle(item);
17128
17425
  if (answer !== null) answers.push(answer);
17129
17426
  }
17130
17427
  if (answers.length === 0) send(202, "");
@@ -17135,10 +17432,13 @@ async function startWebServer(options) {
17135
17432
  }
17136
17433
  if (request.method === "POST" && request.url === "/api/generate") {
17137
17434
  let received = 0;
17435
+ let tooLarge = false;
17138
17436
  const chunks = [];
17139
17437
  request.on("data", (chunk) => {
17438
+ if (tooLarge) return;
17140
17439
  received += chunk.length;
17141
17440
  if (received > MAX_BODY) {
17441
+ tooLarge = true;
17142
17442
  request.destroy();
17143
17443
  send(413, { error: "request body too large" });
17144
17444
  return;
@@ -17146,6 +17446,7 @@ async function startWebServer(options) {
17146
17446
  chunks.push(chunk);
17147
17447
  });
17148
17448
  request.on("end", () => {
17449
+ if (tooLarge) return;
17149
17450
  void (async () => {
17150
17451
  let source = "";
17151
17452
  let mode = "full";
@@ -17202,6 +17503,10 @@ async function startWebServer(options) {
17202
17503
  }
17203
17504
  } else {
17204
17505
  target = path25.resolve(options.cwd, source);
17506
+ if (!insideAllowedRoots(target)) {
17507
+ send(403, { error: "outside the served directory: " + target });
17508
+ return;
17509
+ }
17205
17510
  }
17206
17511
  let stat;
17207
17512
  try {
@@ -17219,15 +17524,26 @@ async function startWebServer(options) {
17219
17524
  send(400, { error: loaded.errors.join("; ") });
17220
17525
  return;
17221
17526
  }
17527
+ const runConfig = isRemote ? {
17528
+ ...loaded.config ?? {},
17529
+ outDir: "snapshot",
17530
+ tmpDir: "snapshot.tmp",
17531
+ hooks: {}
17532
+ } : loaded.config ?? {};
17533
+ const configuredOutDir = typeof runConfig.outDir === "string" && runConfig.outDir.trim() !== "" ? runConfig.outDir : "snapshot";
17534
+ const snapshotDir = path25.resolve(target, configuredOutDir);
17535
+ if (!insideAllowedRootsForWrite(snapshotDir)) {
17536
+ send(403, { error: "the configured outDir resolves outside the served directory" });
17537
+ return;
17538
+ }
17222
17539
  const started = Date.now();
17223
17540
  try {
17224
- const manifest = generateSnapshot({ ...loaded.config ?? {}, cwd: target }, {
17541
+ const manifest = generateSnapshot({ ...runConfig, cwd: target }, {
17225
17542
  ...provenance === void 0 ? {} : { source: provenance },
17226
17543
  ...mode === "slice" ? { slice: { question } } : {},
17227
17544
  ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
17228
17545
  });
17229
17546
  const seconds = ((Date.now() - started) / 1e3).toFixed(2);
17230
- const snapshotDir = path25.join(target, "snapshot");
17231
17547
  const health = auditSnapshot({ snapshotDir, repoDir: target });
17232
17548
  send(200, {
17233
17549
  path: snapshotDir,
@@ -17255,7 +17571,7 @@ async function startWebServer(options) {
17255
17571
  }
17256
17572
  if (request.method === "GET" && request.url?.startsWith("/api/health?") === true) {
17257
17573
  const target = path25.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17258
- if (!insideAllowedRoots(target)) {
17574
+ if (!lexicallyInside(target)) {
17259
17575
  send(403, { error: "outside the served directory: " + target });
17260
17576
  return;
17261
17577
  }
@@ -17263,12 +17579,24 @@ async function startWebServer(options) {
17263
17579
  send(404, { error: "no manifest.json under " + target });
17264
17580
  return;
17265
17581
  }
17582
+ if (!insideAllowedRoots(target)) {
17583
+ send(403, { error: "outside the served directory: " + target });
17584
+ return;
17585
+ }
17266
17586
  const report2 = auditSnapshot({ snapshotDir: target, repoDir: path25.dirname(target) });
17267
17587
  send(200, { score: report2.score, counts: report2.counts, checks: report2.checks });
17268
17588
  return;
17269
17589
  }
17270
17590
  if (request.method === "GET" && (request.url?.startsWith("/api/snapshot?") === true || request.url === "/api/snapshot")) {
17271
17591
  const target = path25.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17592
+ if (!lexicallyInside(target)) {
17593
+ send(403, { error: "outside the served directory: " + target });
17594
+ return;
17595
+ }
17596
+ if (!fs24.existsSync(path25.join(target, "manifest.json"))) {
17597
+ send(404, { error: "no manifest.json under " + target });
17598
+ return;
17599
+ }
17272
17600
  if (!insideAllowedRoots(target)) {
17273
17601
  send(403, { error: "outside the served directory: " + target });
17274
17602
  return;
@@ -17281,6 +17609,11 @@ async function startWebServer(options) {
17281
17609
  send(404, { error: "no manifest.json under " + target });
17282
17610
  return;
17283
17611
  }
17612
+ const shapeProblem = describeManifestShapeProblem(manifest);
17613
+ if (shapeProblem !== null) {
17614
+ send(400, { error: "manifest.json is not a snapshot manifest: " + shapeProblem });
17615
+ return;
17616
+ }
17284
17617
  let prompt = "";
17285
17618
  try {
17286
17619
  prompt = fs24.readFileSync(path25.join(target, "PROMPT.md"), "utf8").slice(0, MAX_PREVIEW);
@@ -17300,7 +17633,7 @@ async function startWebServer(options) {
17300
17633
  }
17301
17634
  if (request.method === "GET" && request.url?.startsWith("/api/snapshot.zip") === true) {
17302
17635
  const target = path25.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17303
- if (!insideAllowedRoots(target)) {
17636
+ if (!lexicallyInside(target)) {
17304
17637
  send(403, { error: "outside the served directory: " + target });
17305
17638
  return;
17306
17639
  }
@@ -17308,6 +17641,10 @@ async function startWebServer(options) {
17308
17641
  send(404, { error: "not a snapshot directory: " + target });
17309
17642
  return;
17310
17643
  }
17644
+ if (!insideAllowedRoots(target)) {
17645
+ send(403, { error: "outside the served directory: " + target });
17646
+ return;
17647
+ }
17311
17648
  try {
17312
17649
  const zip = writeZip({ directory: target });
17313
17650
  response.writeHead(200, {
@@ -18053,9 +18390,17 @@ function renderConfig(answers) {
18053
18390
  // Replace function and method bodies with \`{ /* ... */ }\` in TypeScript files.
18054
18391
  // Signatures and comments stay, so the structure of the file survives.
18055
18392
  skeleton: ${answers.skeleton},
18393
+ // Remove comment text from JavaScript and TypeScript bodies.
18394
+ stripComments: false,
18395
+ // Drop blank lines from emitted bodies; line numbers in the part move.
18396
+ removeEmptyLines: false,
18056
18397
  // Also write reports/audit.sarif (SARIF 2.1.0) for a CI security gate. The
18057
18398
  // matched value is never included \u2014 only the path, the line and the rule.
18058
18399
  sarif: ${answers.sarif},
18400
+ // Commit lines in reports/log.md when the log artifact is enabled.
18401
+ logCount: 20,
18402
+ // Write one single-file pack: "single", "xml" or "json". null = no pack.
18403
+ pack: null,
18059
18404
  // Snapshot only the files that differ from a git ref (for example "main"),
18060
18405
  // plus untracked ones. null means "snapshot everything"; any other value must
18061
18406
  // be a git ref string, and anything else is a configuration error.
@@ -18729,11 +19074,11 @@ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
18729
19074
  const entries = [];
18730
19075
  for (const directory of [outDir, tmpDir]) {
18731
19076
  if (directory === null) continue;
18732
- const relative13 = path25.relative(cwd, path25.resolve(cwd, directory)).replace(/\\/g, "/");
18733
- if (relative13 === "" || relative13 === "." || relative13.startsWith("..") || path25.isAbsolute(relative13)) {
19077
+ const relative14 = path25.relative(cwd, path25.resolve(cwd, directory)).replace(/\\/g, "/");
19078
+ if (relative14 === "" || relative14 === "." || relative14.startsWith("..") || path25.isAbsolute(relative14)) {
18734
19079
  continue;
18735
19080
  }
18736
- entries.push(`/${relative13}/`);
19081
+ entries.push(`/${relative14}/`);
18737
19082
  }
18738
19083
  return [...new Set(entries)];
18739
19084
  }
@@ -19064,10 +19409,10 @@ async function runInit(options) {
19064
19409
  };
19065
19410
  }
19066
19411
  function describeTarget(cwd) {
19067
- const relative13 = path25.relative(process.cwd(), cwd);
19068
- if (relative13 === "") return "this directory";
19069
- if (relative13.startsWith("..") || path25.isAbsolute(relative13)) return cwd;
19070
- return relative13;
19412
+ const relative14 = path25.relative(process.cwd(), cwd);
19413
+ if (relative14 === "") return "this directory";
19414
+ if (relative14.startsWith("..") || path25.isAbsolute(relative14)) return cwd;
19415
+ return relative14;
19071
19416
  }
19072
19417
  function firstRunMessage(reason, cwd) {
19073
19418
  const where = describeTarget(cwd);
@@ -19169,8 +19514,8 @@ function gitDirectory(cwd) {
19169
19514
  }
19170
19515
  }
19171
19516
  function isInside3(parent, child) {
19172
- const relative13 = path25.relative(parent, child);
19173
- return relative13 === "" || !relative13.startsWith("..") && !path25.isAbsolute(relative13);
19517
+ const relative14 = path25.relative(parent, child);
19518
+ return relative14 === "" || !relative14.startsWith("..") && !path25.isAbsolute(relative14);
19174
19519
  }
19175
19520
  function isRegisteredWorktree(gitDir, cwd) {
19176
19521
  try {
@@ -19409,7 +19754,7 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
19409
19754
  };
19410
19755
  }
19411
19756
  function sha256Hex2(input) {
19412
- return crypto3.createHash("sha256").update(input).digest("hex");
19757
+ return crypto.createHash("sha256").update(input).digest("hex");
19413
19758
  }
19414
19759
  var TS_EXTENSIONS = [
19415
19760
  ".ts",
@@ -19622,7 +19967,7 @@ function maskPathText(value, secretRules) {
19622
19967
  }
19623
19968
  function maskOwnerBrief(brief, secretRules) {
19624
19969
  if (brief === void 0) return void 0;
19625
- const mask = (value) => maskPathText(value, secretRules);
19970
+ const mask = (value) => scanAndRedactSecrets(value, secretRules ?? [], "owner-brief").redacted;
19626
19971
  return {
19627
19972
  ...brief,
19628
19973
  path: mask(brief.path),
@@ -19668,9 +20013,9 @@ function listEntries(dir) {
19668
20013
  return;
19669
20014
  }
19670
20015
  for (const child of children) {
19671
- const relative13 = prefix === "" ? child.name : `${prefix}/${child.name}`;
19672
- entries.push(relative13);
19673
- if (child.isDirectory()) walk2(path25.join(absolute, child.name), relative13);
20016
+ const relative14 = prefix === "" ? child.name : `${prefix}/${child.name}`;
20017
+ entries.push(relative14);
20018
+ if (child.isDirectory()) walk2(path25.join(absolute, child.name), relative14);
19674
20019
  }
19675
20020
  };
19676
20021
  walk2(dir, "");
@@ -19705,7 +20050,7 @@ function markerInventory(dir, written) {
19705
20050
  }
19706
20051
  return { entries, files };
19707
20052
  }
19708
- function markerPayload(dir, state, id, createdAt, written) {
20053
+ function markerPayload(dir, state, id, createdAt, written, runId) {
19709
20054
  const { entries, files } = markerInventory(dir, written);
19710
20055
  const marker2 = {
19711
20056
  generator: GENERATOR_NAME,
@@ -19714,6 +20059,7 @@ function markerPayload(dir, state, id, createdAt, written) {
19714
20059
  createdAt,
19715
20060
  state,
19716
20061
  id,
20062
+ ...runId === void 0 ? {} : { runId },
19717
20063
  pid: process.pid,
19718
20064
  entries,
19719
20065
  files
@@ -19811,6 +20157,7 @@ function readOwnershipMarker(dir) {
19811
20157
  createdAt: typeof candidate.createdAt === "string" ? candidate.createdAt : "unknown",
19812
20158
  state: candidate.state,
19813
20159
  id: candidate.id,
20160
+ runId: typeof candidate.runId === "string" ? candidate.runId : void 0,
19814
20161
  pid: typeof candidate.pid === "number" ? candidate.pid : void 0,
19815
20162
  manifestSha256: typeof candidate.manifestSha256 === "string" ? candidate.manifestSha256 : void 0,
19816
20163
  entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0,
@@ -19969,13 +20316,19 @@ function assessSnapshotDirectory(dir) {
19969
20316
  };
19970
20317
  }
19971
20318
  const entries = listEntries(dir);
19972
- const foreignEntries = entries.filter(
20319
+ let foreignEntries = entries.filter(
19973
20320
  (entry) => !recorded.has(entry) && !isIgnorableEntry(entry)
19974
20321
  );
20322
+ const legacySignatureOnly = foreignEntries.length === 1 && foreignEntries[0] === SIGNATURE_FILE && verifySnapshotSignature(dir).ok;
20323
+ if (legacySignatureOnly) foreignEntries = [];
19975
20324
  if (foreignEntries.length > 0) {
19976
20325
  return { owned: false, problem: null, foreignEntries, marker: marker2 };
19977
20326
  }
19978
- const inventoryProblem = marker2.files === void 0 ? null : verifyMarkerInventory(dir, entries, marker2.files);
20327
+ const inventoryProblem = marker2.files === void 0 ? null : verifyMarkerInventory(
20328
+ dir,
20329
+ legacySignatureOnly ? entries.filter((entry) => entry !== SIGNATURE_FILE) : entries,
20330
+ marker2.files
20331
+ );
19979
20332
  return {
19980
20333
  owned: inventoryProblem === null,
19981
20334
  problem: inventoryProblem,
@@ -20153,13 +20506,13 @@ function startLockHeartbeat(lockPath) {
20153
20506
  return () => void 0;
20154
20507
  }
20155
20508
  }
20156
- function acquireRunLock(stagingRoot) {
20509
+ function acquireRunLock(stagingRoot, runId) {
20157
20510
  const lockPath = lockPathFor(stagingRoot);
20158
20511
  const payload = `${JSON.stringify({
20159
20512
  pid: process.pid,
20160
20513
  stagingRoot,
20161
20514
  host: os2.hostname(),
20162
- runId: crypto3.randomUUID(),
20515
+ runId,
20163
20516
  heartbeatMs: LOCK_HEARTBEAT_MS,
20164
20517
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
20165
20518
  })}
@@ -20213,6 +20566,33 @@ function canonicalLockTarget(targetPath) {
20213
20566
  function lockPathFor(stagingRoot) {
20214
20567
  return path25.join(os2.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
20215
20568
  }
20569
+ function releaseAbandonedRun(stagingRoots, runId) {
20570
+ if (runId.length === 0) return;
20571
+ for (const root of new Set(stagingRoots)) {
20572
+ const lockPath = lockPathFor(root);
20573
+ try {
20574
+ const payload = JSON.parse(fs24.readFileSync(lockPath, "utf8"));
20575
+ if (payload.runId === runId) fs24.rmSync(lockPath, { force: true });
20576
+ } catch {
20577
+ }
20578
+ let entries;
20579
+ try {
20580
+ entries = fs24.readdirSync(root);
20581
+ } catch {
20582
+ continue;
20583
+ }
20584
+ for (const name of entries) {
20585
+ if (!name.startsWith(RUN_DIR_PREFIX)) continue;
20586
+ const directory = path25.join(root, name);
20587
+ const { marker: marker2 } = readOwnershipMarker(directory);
20588
+ if (marker2?.runId !== runId) continue;
20589
+ try {
20590
+ fs24.rmSync(directory, { recursive: true, force: true });
20591
+ } catch {
20592
+ }
20593
+ }
20594
+ }
20595
+ }
20216
20596
  function lockHeartbeatAgeMs(lockPath) {
20217
20597
  try {
20218
20598
  return Date.now() - fs24.statSync(lockPath).mtimeMs;
@@ -20527,6 +20907,7 @@ function generateSnapshot(configInput, options) {
20527
20907
  assertUsableConfigInput(configInput);
20528
20908
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
20529
20909
  const dryRun = options?.dryRun ?? false;
20910
+ const runId = options?.runId ?? crypto.randomUUID();
20530
20911
  const gitInfo = getGitInfo(config.cwd, config.branch);
20531
20912
  const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
20532
20913
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
@@ -20546,7 +20927,7 @@ function generateSnapshot(configInput, options) {
20546
20927
  // output — but only at these exact paths, not at every directory that shares the name.
20547
20928
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
20548
20929
  (directory) => path25.relative(config.cwd, path25.resolve(config.cwd, directory)).replace(/\\/g, "/")
20549
- ).filter((relative13) => relative13.length > 0 && !relative13.startsWith("..")),
20930
+ ).filter((relative14) => relative14.length > 0 && !relative14.startsWith("..")),
20550
20931
  // A staged path can be absent from the working tree while its index blob exists. Discovery
20551
20932
  // lists the working tree, so those paths would never reach the scan at all.
20552
20933
  ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
@@ -21233,9 +21614,13 @@ function generateSnapshot(configInput, options) {
21233
21614
  if (navigationText !== null) manifest.artifacts.navigation = artifactRecord(navigationText);
21234
21615
  const auditText = artifacts.audit ? generateAuditReport(manifest, secretFindings, config.secretRules) : null;
21235
21616
  if (auditText !== null) manifest.artifacts.audit = artifactRecord(auditText);
21236
- const diffReport = artifacts.diff ? generateDiffReport(config.cwd) : null;
21617
+ const reportExcludes = [...config.excludePatterns, ...config.presetExclude];
21618
+ const diffReport = artifacts.diff ? generateDiffReport(config.cwd, {
21619
+ secretRules: config.secretRules,
21620
+ excluded: (relativePath) => reportExcludes.some((pattern) => matchesExclude(relativePath, pattern))
21621
+ }) : null;
21237
21622
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
21238
- const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount }) : null;
21623
+ const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount, secretRules: config.secretRules }) : null;
21239
21624
  if (artifacts.diff && diffReport === null && !isGitRepository(config.cwd)) {
21240
21625
  manifest.warnings.push(
21241
21626
  "--include-diffs was requested, but the generated directory is not a git repository; reports/diff.md was not written."
@@ -21279,7 +21664,8 @@ function generateSnapshot(configInput, options) {
21279
21664
  const entry = {
21280
21665
  ...file,
21281
21666
  content,
21282
- inclusionMode: "full",
21667
+ inclusionMode: file.inclusionMode === "comments-stripped" ? "comments-stripped" : "full",
21668
+ ...file.emptyLinesRemoved === true ? { emptyLinesRemoved: true } : {},
21283
21669
  isPreviewTruncated: false,
21284
21670
  includedBytes: Buffer.byteLength(content, "utf8"),
21285
21671
  includedLines: countLines(content)
@@ -21347,7 +21733,7 @@ function generateSnapshot(configInput, options) {
21347
21733
  const lockKeys = Array.from(/* @__PURE__ */ new Set([tmpDir, outDir])).sort();
21348
21734
  const releases = [];
21349
21735
  try {
21350
- for (const key of lockKeys) releases.push(acquireRunLock(key));
21736
+ for (const key of lockKeys) releases.push(acquireRunLock(key, runId));
21351
21737
  } catch (error) {
21352
21738
  for (const release of [...releases].reverse()) release();
21353
21739
  throw error;
@@ -21363,7 +21749,7 @@ function generateSnapshot(configInput, options) {
21363
21749
  ensureParentDirectory(outDir, "outDir");
21364
21750
  fs24.mkdirSync(tmpDir, { recursive: true });
21365
21751
  cleanStaleRunDirs(tmpDir);
21366
- const snapshotId = crypto3.randomUUID();
21752
+ const snapshotId = crypto.randomUUID();
21367
21753
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
21368
21754
  stagingDir = path25.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
21369
21755
  fs24.mkdirSync(stagingDir);
@@ -21374,6 +21760,7 @@ function generateSnapshot(configInput, options) {
21374
21760
  createdAt,
21375
21761
  state: "staging",
21376
21762
  id: snapshotId,
21763
+ runId,
21377
21764
  pid: process.pid
21378
21765
  });
21379
21766
  const partsDir = path25.join(stagingDir, "parts");
@@ -21442,6 +21829,17 @@ function generateSnapshot(configInput, options) {
21442
21829
  if (artifacts.manifest) {
21443
21830
  writeArtifact(stagingDir, "manifest.json", JSON.stringify(manifest, null, 2));
21444
21831
  }
21832
+ if (options?.sign !== void 0) {
21833
+ if (!artifacts.manifest) {
21834
+ throw new Error(
21835
+ "Refusing to sign: manifest.json is disabled for this run. Signing covers the manifest, so enable the manifest artifact or drop --sign."
21836
+ );
21837
+ }
21838
+ const record = signManifest(path25.join(stagingDir, "manifest.json"), {
21839
+ key: options.sign.key ?? null
21840
+ });
21841
+ writeArtifact(stagingDir, SIGNATURE_FILE, JSON.stringify(record, null, 2) + "\n");
21842
+ }
21445
21843
  if (monolithJson !== null) {
21446
21844
  writeArtifact(stagingDir, "full-codebase.json", monolithJson);
21447
21845
  }
@@ -21453,7 +21851,7 @@ function generateSnapshot(configInput, options) {
21453
21851
  }
21454
21852
  writeOwnershipMarker(
21455
21853
  stagingDir,
21456
- markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts)
21854
+ markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21457
21855
  );
21458
21856
  swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
21459
21857
  stagingDir = null;
@@ -21464,10 +21862,16 @@ function generateSnapshot(configInput, options) {
21464
21862
  if (artifacts.manifest && manifest.warnings.length !== warningsBeforeHook) {
21465
21863
  writeManifestAtomically(path25.join(outDir, "manifest.json"), manifest);
21466
21864
  recordArtifact(outDir, "manifest.json");
21865
+ if (options?.sign !== void 0) {
21866
+ const record = signManifest(path25.join(outDir, "manifest.json"), {
21867
+ key: options.sign.key ?? null
21868
+ });
21869
+ writeArtifact(outDir, SIGNATURE_FILE, JSON.stringify(record, null, 2) + "\n");
21870
+ }
21467
21871
  }
21468
21872
  writeOwnershipMarker(
21469
21873
  outDir,
21470
- markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts)
21874
+ markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21471
21875
  );
21472
21876
  };
21473
21877
  if (config.hooks.afterGenerate) shipHookState();
@@ -21530,4 +21934,4 @@ async function generateSnapshotAsync(configInput, options) {
21530
21934
  return manifest;
21531
21935
  }
21532
21936
 
21533
- export { ARTIFACT_NAMES, CHECK_INTERVAL_MS, COMMAND_OPTION_SCOPE, CONFIG_KEYS, DEFAULT_ANSWERS, DEFAULT_SECRET_PATTERNS, ERROR_CODES, FAILURE_INTERVAL_MS, GENERATOR_NAME, GENERATOR_VERSION, HOOK_MARKER, LANGUAGE_PROFILES, LEGACY_PROTOCOL_VERSIONS, MAX_LINE_BYTES, METHOD3 as METHOD, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, MODERN_PROTOCOL_VERSIONS, PACKAGE_LATEST_URL, PRESETS, PromptBack, PromptCancelled, REPORT_RESOURCE_URIS, REQUEST_TIMEOUT_MS, RESOURCE_TEMPLATE_URIS, SCHEMA_VERSION, SERVER_INSTRUCTIONS, SKILL_NAME, STATIC_RESOURCE_URIS, SUPPORTED_PROTOCOL_VERSIONS, UP_TO_DATE_INTERVAL_MS, anchorForPath, appendGitignoreEntries, assertPublicHost, assertReplaceable, assertUsableConfigInput, auditSnapshot, buildAgentContract, buildImportResolver, buildPrompts, buildResourceProvider, buildTools, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, classifyRequest, cloneRepository, coerceNumericStrings, collectFiles, commandsForOption, compareManifests, configDigest, countInvalidUtf8Bytes, countLines, crc32, createLineReader, createMcpServer, createServer, createSession, createWriter, decodeText, defaultIO, defineConfig, describeManifestShapeProblem, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, escapeControls, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findConfigFile, findSecretInPath, findSection, firstRunMessage, formatNumber, formatTokens, formatUpdateNotice, generateInWorker, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, inspectModernMeta, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isCommentStrippable, isDiscoveryMode, isEffectivelyEmpty, isInteractive, isNewer, isPrivateHost, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, loadSigningKey, lockPathFor, makeCloneDirectory, markResolvedConfig, matchRule, matchesExclude, negotiateLegacyVersion, normalizeResolvedConfig, parseByteSize, parsePartSections, parseRemoteSource, partitionFiles, planFirstRun, profileForPath, renderConfig, renderContractText, renderDiffText, renderExplainText, renderSkill, renumberParts, resolveChangedScope, resolveConfig, resolveLatest, resolveSafeOutputDirs, resolveSpecifier, runInit, runStdioServer, runWithStdoutCapture, scanAndRedactSecrets, shouldCheck, signManifest, skeletonizeTypeScript, startWebServer, stripComments2 as stripComments, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, treeTruncationWarnings, truncatePreview, truncateToBytes, tsconfigPathsFor, unknownPresetMessage, updateCommand, validateArguments, validateSnapshot, walkFiles, windowText, workerEntry, wrapLines, writeSignature, writeZip };
21937
+ export { ARTIFACT_NAMES, CHECK_INTERVAL_MS, COMMAND_OPTION_SCOPE, CONFIG_KEYS, DEFAULT_ANSWERS, DEFAULT_SECRET_PATTERNS, ERROR_CODES, FAILURE_INTERVAL_MS, GENERATOR_NAME, GENERATOR_VERSION, HOOK_MARKER, LANGUAGE_PROFILES, LEGACY_PROTOCOL_VERSIONS, MAX_LINE_BYTES, METHOD3 as METHOD, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, MODERN_PROTOCOL_VERSIONS, PACKAGE_LATEST_URL, PRESETS, PromptBack, PromptCancelled, REPORT_RESOURCE_URIS, REQUEST_TIMEOUT_MS, RESOURCE_TEMPLATE_URIS, SCHEMA_VERSION, SERVER_INSTRUCTIONS, SIGNATURE_FILE, SKILL_NAME, STATIC_RESOURCE_URIS, SUPPORTED_PROTOCOL_VERSIONS, UP_TO_DATE_INTERVAL_MS, anchorForPath, appendGitignoreEntries, assertPublicHost, assertReplaceable, assertUsableConfigInput, auditSnapshot, buildAgentContract, buildImportResolver, buildPrompts, buildResourceProvider, buildTools, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, classifyRequest, cloneRepository, coerceNumericStrings, collectFiles, commandsForOption, compareManifests, configDigest, countInvalidUtf8Bytes, countLines, crc32, createLineReader, createMcpServer, createServer, createSession, createWriter, decodeText, defaultIO, defineConfig, describeManifestShapeProblem, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, escapeControls, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findConfigFile, findSecretInPath, findSection, firstRunMessage, formatNumber, formatTokens, formatUpdateNotice, generateInWorker, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, inspectModernMeta, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isCommentStrippable, isDiscoveryMode, isEffectivelyEmpty, isInteractive, isNewer, isPrivateHost, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, loadSigningKey, lockPathFor, makeCloneDirectory, markResolvedConfig, matchRule, matchesExclude, negotiateLegacyVersion, normalizeResolvedConfig, parseByteSize, parsePartSections, parseRemoteSource, partitionFiles, planFirstRun, profileForPath, releaseAbandonedRun, renderConfig, renderContractText, renderDiffText, renderExplainText, renderSkill, renumberParts, resolveChangedScope, resolveConfig, resolveLatest, resolveSafeOutputDirs, resolveSpecifier, runInit, runStdioServer, runWithStdoutCapture, scanAndRedactSecrets, shouldCheck, skeletonizeTypeScript, startWebServer, stripComments2 as stripComments, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, tokenAllowedForHost, treeTruncationWarnings, truncatePreview, truncateToBytes, tsconfigPathsFor, unknownPresetMessage, updateCommand, validateArguments, validateSnapshot, walkFiles, windowText, workerEntry, wrapLines, writeZip };