codebase-snapshot 0.20.3 → 0.20.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.3";
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
  }
@@ -10306,9 +10477,9 @@ function secretTokens(text2) {
10306
10477
  }
10307
10478
  function readArtifactTexts(snapshotDir) {
10308
10479
  const texts = [];
10309
- for (const relative13 of walk(snapshotDir)) {
10310
- if (!TEXT_ARTIFACT.test(relative13)) continue;
10311
- const text2 = readText2(path25.join(snapshotDir, relative13));
10480
+ for (const relative14 of walk(snapshotDir)) {
10481
+ if (!TEXT_ARTIFACT.test(relative14)) continue;
10482
+ const text2 = readText2(path25.join(snapshotDir, relative14));
10312
10483
  if (text2 !== null) texts.push(text2);
10313
10484
  }
10314
10485
  return texts;
@@ -10324,15 +10495,15 @@ function findHostPaths(snapshotDir, repoDir) {
10324
10495
  ];
10325
10496
  const repoPattern = new RegExp(escapeRegExp(repoDir), "g");
10326
10497
  const hits = /* @__PURE__ */ new Set();
10327
- for (const relative13 of walk(snapshotDir)) {
10328
- if (!TEXT_ARTIFACT.test(relative13)) continue;
10329
- 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));
10330
10501
  if (text2 === null) continue;
10331
10502
  for (const pattern of patterns) {
10332
- for (const match of text2.match(pattern) ?? []) hits.add(relative13 + ": " + match);
10503
+ for (const match of text2.match(pattern) ?? []) hits.add(relative14 + ": " + match);
10333
10504
  }
10334
10505
  repoPattern.lastIndex = 0;
10335
- if (repoPattern.test(text2)) hits.add(relative13 + ": the repository absolute path");
10506
+ if (repoPattern.test(text2)) hits.add(relative14 + ": the repository absolute path");
10336
10507
  }
10337
10508
  return [...hits];
10338
10509
  }
@@ -10579,13 +10750,13 @@ function auditSnapshot(options) {
10579
10750
  let artifactCount = 0;
10580
10751
  for (const [key, value] of Object.entries(artifacts)) {
10581
10752
  if (value === null || value === void 0) continue;
10582
- const relative13 = ARTIFACT_FILES[key];
10583
- if (relative13 === void 0) continue;
10753
+ const relative14 = ARTIFACT_FILES[key];
10754
+ if (relative14 === void 0) continue;
10584
10755
  artifactCount += 1;
10585
- const bytes = readBytes(path25.join(snapshotDir, relative13));
10586
- 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");
10587
10758
  else if (typeof value.sha256 === "string" && sha256(bytes) !== value.sha256) {
10588
- artifactProblems.push(relative13 + " changed");
10759
+ artifactProblems.push(relative14 + " changed");
10589
10760
  }
10590
10761
  }
10591
10762
  checks.push(
@@ -11315,25 +11486,25 @@ function auditSnapshot(options) {
11315
11486
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
11316
11487
  const leakHits = [];
11317
11488
  let scannedBytes = 0;
11318
- for (const relative13 of walk(snapshotDir)) {
11319
- if (!TEXT_ARTIFACT.test(relative13) || scannedBytes > scanBudget) continue;
11320
- if (relative13 === SIGNATURE_FILE) continue;
11321
- 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));
11322
11493
  if (text2 === null) continue;
11323
11494
  scannedBytes += Buffer.byteLength(text2, "utf8");
11324
11495
  let findingCount = 0;
11325
- if (/^parts[\\/].*\.md$/i.test(relative13)) {
11496
+ if (/^parts[\\/].*\.md$/i.test(relative14)) {
11326
11497
  let headerText = text2;
11327
11498
  for (const section of parsePartSections(text2)) {
11328
11499
  findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
11329
11500
  headerText = headerText.replace(section.body, "");
11330
11501
  }
11331
- findingCount += scanAndRedactSecrets(headerText, rules, relative13).findings.length;
11502
+ findingCount += scanAndRedactSecrets(headerText, rules, relative14).findings.length;
11332
11503
  } else {
11333
- findingCount = scanAndRedactSecrets(text2, rules, relative13).findings.length;
11504
+ findingCount = scanAndRedactSecrets(text2, rules, relative14).findings.length;
11334
11505
  }
11335
11506
  if (findingCount > 0) {
11336
- leakHits.push(relative13 + " (" + findingCount + " line(s))");
11507
+ leakHits.push(relative14 + " (" + findingCount + " line(s))");
11337
11508
  }
11338
11509
  }
11339
11510
  const signatureRecordPath = path25.join(snapshotDir, SIGNATURE_FILE);
@@ -11536,23 +11707,23 @@ function describeMatcher(matcher) {
11536
11707
  function normalizeTarget(cwd, target) {
11537
11708
  const resolvedCwd = path25.resolve(cwd);
11538
11709
  const absolute = path25.resolve(resolvedCwd, target);
11539
- const relative13 = path25.relative(resolvedCwd, absolute);
11540
- 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)) {
11541
11712
  return { relative: target.replace(/\\/g, "/"), outsideRoot: true };
11542
11713
  }
11543
- return { relative: relative13.split(path25.sep).join("/"), outsideRoot: false };
11714
+ return { relative: relative14.split(path25.sep).join("/"), outsideRoot: false };
11544
11715
  }
11545
11716
  function findRuleMatch(rules, relativePath) {
11546
11717
  return rules.find(
11547
11718
  (rule) => matchRule(relativePath, rule.match)
11548
11719
  );
11549
11720
  }
11550
- function findRecordedAncestor(skipped, relative13, maskedPath2) {
11721
+ function findRecordedAncestor(skipped, relative14, maskedPath2) {
11551
11722
  let nearest;
11552
11723
  for (const record of skipped) {
11553
11724
  const ancestorPath = record.path;
11554
11725
  if (ancestorPath.length === 0) continue;
11555
- const isAncestor = relative13.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
11726
+ const isAncestor = relative14.startsWith(`${ancestorPath}/`) || maskedPath2.startsWith(`${ancestorPath}/`);
11556
11727
  if (!isAncestor) continue;
11557
11728
  if (!nearest || ancestorPath.length > nearest.path.length) nearest = record;
11558
11729
  }
@@ -11568,8 +11739,8 @@ function readManifest2(config) {
11568
11739
  }
11569
11740
  function explainPath(config, target) {
11570
11741
  const normalized = normalizeTarget(config.cwd, target);
11571
- const relative13 = normalized.relative;
11572
- const maskedPath2 = findSecretInPath(relative13, config.secretRules)?.masked ?? relative13;
11742
+ const relative14 = normalized.relative;
11743
+ const maskedPath2 = findSecretInPath(relative14, config.secretRules)?.masked ?? relative14;
11573
11744
  if (normalized.outsideRoot) {
11574
11745
  return {
11575
11746
  path: maskedPath2,
@@ -11579,7 +11750,7 @@ function explainPath(config, target) {
11579
11750
  detail: "path resolves outside the configured repository root and was not inspected"
11580
11751
  };
11581
11752
  }
11582
- const absolute = path25.join(config.cwd, relative13);
11753
+ const absolute = path25.join(config.cwd, relative14);
11583
11754
  const result = {
11584
11755
  path: maskedPath2,
11585
11756
  exists: fs24.existsSync(absolute),
@@ -11597,11 +11768,11 @@ function explainPath(config, target) {
11597
11768
  // that is only missing because the walker dropped the tool's own output directory.
11598
11769
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
11599
11770
  (directory) => path25.relative(config.cwd, path25.resolve(config.cwd, directory)).replace(/\\/g, "/")
11600
- ).filter((relative14) => relative14.length > 0 && !relative14.startsWith(".."))
11771
+ ).filter((relative15) => relative15.length > 0 && !relative15.startsWith(".."))
11601
11772
  });
11602
- if (!collection.files.includes(relative13)) {
11773
+ if (!collection.files.includes(relative14)) {
11603
11774
  const record = collection.skipped.find(
11604
- (entry2) => entry2.path === relative13 || entry2.path === maskedPath2
11775
+ (entry2) => entry2.path === relative14 || entry2.path === maskedPath2
11605
11776
  );
11606
11777
  if (record) {
11607
11778
  result.reason = record.reason;
@@ -11610,7 +11781,7 @@ function explainPath(config, target) {
11610
11781
  result.reason = "missing";
11611
11782
  result.detail = "no such file or directory, relative to the configured cwd";
11612
11783
  } else {
11613
- const ancestor = findRecordedAncestor(collection.skipped, relative13, maskedPath2);
11784
+ const ancestor = findRecordedAncestor(collection.skipped, relative14, maskedPath2);
11614
11785
  if (ancestor) {
11615
11786
  result.reason = ancestor.reason;
11616
11787
  result.detail = ancestor.detail ? `${ancestor.detail} \u2014 inherited from the skipped directory \`${ancestor.path}\`` : `inside the skipped directory \`${ancestor.path}\``;
@@ -11630,13 +11801,15 @@ function explainPath(config, target) {
11630
11801
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
11631
11802
  ...config.staged === true ? { staged: true } : {}
11632
11803
  });
11633
- inScope = scope.paths.has(relative13);
11804
+ inScope = scope.paths.has(relative14);
11634
11805
  if (!inScope && config.withDependents === true) {
11635
11806
  inScope = importsChangedFile(
11636
- relative13,
11637
- importsOfFile(relative13, absolute),
11807
+ relative14,
11808
+ importsOfFile(relative14, absolute),
11638
11809
  scope.paths,
11639
- buildImportResolver(collection.files.map((file) => ({ relativePath: file })))
11810
+ buildImportResolver(collection.files.map((file) => ({ relativePath: file })), {
11811
+ tsconfig: tsconfigPathsFor(config.cwd)
11812
+ })
11640
11813
  );
11641
11814
  }
11642
11815
  scopeDetail = scope.detail;
@@ -11692,15 +11865,15 @@ function explainPath(config, target) {
11692
11865
  result.bytes = buffer.length;
11693
11866
  result.lines = countLines(text2);
11694
11867
  if (decoded.encoding !== "utf-8") result.encoding = decoded.encoding;
11695
- const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative13);
11868
+ const { findings } = scanAndRedactSecrets(text2, config.secretRules, relative14);
11696
11869
  result.secretCount = findings.length;
11697
11870
  result.secrets = findings.slice(0, 20).map((finding) => ({ rules: finding.rules, line: finding.line }));
11698
11871
  let inclusionMode = "full";
11699
- if (config.skeleton === true && isSkeletonizable(relative13)) {
11700
- const skeleton = skeletonizeTypeScript(text2, relative13);
11872
+ if (config.skeleton === true && isSkeletonizable(relative14)) {
11873
+ const skeleton = skeletonizeTypeScript(text2, relative14);
11701
11874
  if (skeleton.collapsed > 0) inclusionMode = "signatures";
11702
11875
  }
11703
- 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) {
11704
11877
  inclusionMode = "comments-stripped";
11705
11878
  }
11706
11879
  if (inclusionMode !== "signatures" && buffer.length > config.largeFileBytes) {
@@ -11709,18 +11882,18 @@ function explainPath(config, target) {
11709
11882
  }
11710
11883
  result.inclusionMode = inclusionMode;
11711
11884
  }
11712
- result.layer = classifyLayer(relative13, config.layers);
11713
- result.kind = classifyKind(relative13, config.kinds);
11714
- result.language = detectLanguage(relative13);
11715
- 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);
11716
11889
  if (layerRule) result.layerMatch = describeMatcher(layerRule.match);
11717
- const kindRule = findRuleMatch(config.kinds, relative13);
11890
+ const kindRule = findRuleMatch(config.kinds, relative14);
11718
11891
  if (kindRule) result.kindMatch = describeMatcher(kindRule.match);
11719
11892
  const manifest = readManifest2(config);
11720
- 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;
11721
11894
  result.part = entry?.part ?? null;
11722
11895
  if (entry === void 0) {
11723
- const record = manifest?.skipped?.find((skip) => skip.path === relative13);
11896
+ const record = manifest?.skipped?.find((skip) => skip.path === relative14);
11724
11897
  if (record !== void 0 && (record.reason === "not-selected" || record.reason === "unchanged")) {
11725
11898
  result.included = false;
11726
11899
  result.reason = record.reason;
@@ -11785,6 +11958,7 @@ const { parentPort, workerData } = require("node:worker_threads");
11785
11958
  const manifest = mod.generateSnapshot(config, {
11786
11959
  dryRun: workerData.dryRun === true,
11787
11960
  ...(workerData.narrow ?? {}),
11961
+ ...(workerData.runId === undefined ? {} : { runId: workerData.runId }),
11788
11962
  });
11789
11963
  const skipCounts = new Map();
11790
11964
  for (const record of manifest.skipped) {
@@ -11830,8 +12004,13 @@ function generateInWorker(cwd, cliOptions, options = {}) {
11830
12004
  const finish = (result) => {
11831
12005
  if (settled) return;
11832
12006
  settled = true;
11833
- if (worker !== null) void worker.terminate();
11834
- 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
+ });
11835
12014
  };
11836
12015
  const isCjs = typeof __dirname !== "undefined";
11837
12016
  const directory = isCjs ? __dirname : path25.dirname(fileURLToPath(import.meta.url));
@@ -11843,7 +12022,8 @@ function generateInWorker(cwd, cliOptions, options = {}) {
11843
12022
  cwd,
11844
12023
  cliOptions,
11845
12024
  dryRun: options.dryRun === true,
11846
- narrow: options.narrow ?? {}
12025
+ narrow: options.narrow ?? {},
12026
+ ...options.runId === void 0 ? {} : { runId: options.runId }
11847
12027
  }
11848
12028
  });
11849
12029
  } catch (error) {
@@ -12008,7 +12188,16 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
12008
12188
  if (overrides.withDependents === true) cliOptions.withDependents = true;
12009
12189
  try {
12010
12190
  const config = resolveConfig(loaded.config, cliOptions, root);
12011
- 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
+ };
12012
12201
  } catch (error) {
12013
12202
  return { ok: false, message: error instanceof Error ? error.message : String(error) };
12014
12203
  }
@@ -12022,8 +12211,8 @@ function partPathFor(workspace, filename) {
12022
12211
  if (filename.length === 0 || filename.includes("\0")) return null;
12023
12212
  const partsDir = path25.resolve(workspace.root, workspace.config.outDir, "parts");
12024
12213
  const resolved = path25.resolve(partsDir, filename);
12025
- const relative13 = path25.relative(partsDir, resolved);
12026
- 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)) {
12027
12216
  return null;
12028
12217
  }
12029
12218
  let stats;
@@ -12197,11 +12386,11 @@ function toRelativePath(root, value) {
12197
12386
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
12198
12387
  const resolvedRoot = path25.resolve(root);
12199
12388
  const absolute = path25.resolve(resolvedRoot, cleaned);
12200
- const relative13 = path25.relative(resolvedRoot, absolute);
12201
- 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)) {
12202
12391
  return null;
12203
12392
  }
12204
- return relative13.split(path25.sep).join("/");
12393
+ return relative14.split(path25.sep).join("/");
12205
12394
  }
12206
12395
  function symbolsOf(entry) {
12207
12396
  const summary = entry.summary;
@@ -12415,7 +12604,9 @@ var testsTool = {
12415
12604
  const cap = Math.max(1, typeof args.maxFiles === "number" ? args.maxFiles : 50);
12416
12605
  const isTest2 = (filePath) => /(^|\/)(tests?|__tests__|spec)\//.test(filePath) || /\.(test|spec)\.[a-z0-9]+$/i.test(filePath);
12417
12606
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath, file]));
12418
- const resolver = buildImportResolver(read.manifest.files, {});
12607
+ const resolver = buildImportResolver(read.manifest.files, {
12608
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
12609
+ });
12419
12610
  const testFiles = read.manifest.files.filter((file) => isTest2(file.relativePath));
12420
12611
  const importsOf = (filePath) => {
12421
12612
  const entry = read.manifest.indexes.imports.byFile.find((candidate) => candidate.path === filePath);
@@ -12463,9 +12654,13 @@ var workspaceTool = {
12463
12654
  },
12464
12655
  annotations: READ_ONLY,
12465
12656
  async handler(args, context) {
12466
- const root = path25.resolve(context.cwd, typeof args.root === "string" ? args.root : ".");
12467
- const outDir = typeof args.outDir === "string" ? args.outDir : "snapshot";
12468
- 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
+ );
12469
12664
  let text2;
12470
12665
  try {
12471
12666
  text2 = fs24.readFileSync(index, "utf8");
@@ -12522,7 +12717,9 @@ var neighborsTool = {
12522
12717
  const file = read.manifest.files.find((candidate) => candidate.relativePath === wanted) ?? read.manifest.files.find((candidate) => candidate.relativePath.toLowerCase() === wanted.toLowerCase());
12523
12718
  if (file === void 0) return { text: wanted + " is not in the snapshot; snapshot_explain says why.", isError: true };
12524
12719
  const byPath = new Map(read.manifest.files.map((candidate) => [candidate.relativePath, candidate]));
12525
- const resolver = buildImportResolver(read.manifest.files, {});
12720
+ const resolver = buildImportResolver(read.manifest.files, {
12721
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
12722
+ });
12526
12723
  const entry = read.manifest.indexes.imports.byFile.find((candidate) => candidate.path === file.relativePath);
12527
12724
  const imports = [];
12528
12725
  for (const specifier of entry?.imports ?? []) {
@@ -12664,7 +12861,9 @@ var cyclesTool = {
12664
12861
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
12665
12862
  const cap = Math.max(1, typeof args.maxComponents === "number" ? args.maxComponents : 20);
12666
12863
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath, file]));
12667
- const resolver = buildImportResolver(read.manifest.files, {});
12864
+ const resolver = buildImportResolver(read.manifest.files, {
12865
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
12866
+ });
12668
12867
  const edges = /* @__PURE__ */ new Map();
12669
12868
  for (const path26 of byPath.keys()) edges.set(path26, []);
12670
12869
  for (const entry of read.manifest.indexes.imports.byFile) {
@@ -13864,10 +14063,17 @@ var generateTool = {
13864
14063
  ...typeof args.slice === "string" ? { slice: { question: args.slice, ...typeof args.sliceTokens === "number" ? { maxTokens: args.sliceTokens } : {} } } : {},
13865
14064
  ...typeof args.budgetTokens === "number" ? { budgetTokens: args.budgetTokens } : {}
13866
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
+ }
13867
14073
  const result = await generateInWorker(
13868
14074
  workspace.root,
13869
14075
  { ...workspace.cliOptions, ...reportOptions },
13870
- { signal: controller.signal, narrow }
14076
+ { signal: controller.signal, narrow, runId: randomUUID(), lockRoots }
13871
14077
  );
13872
14078
  if (!result.ok) return failure(result.message);
13873
14079
  context.notify?.({ message: "writing the snapshot", progress: 2, total: 2 });
@@ -13901,16 +14107,42 @@ var generateTool = {
13901
14107
  };
13902
14108
  function configAsGenerated(workspace, manifest) {
13903
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;
13904
14136
  return {
13905
14137
  ...workspace.config,
13906
- ...recorded?.artifacts === void 0 ? {} : { artifacts: recorded.artifacts },
13907
- ...recorded?.stripComments === void 0 ? {} : { stripComments: recorded.stripComments },
13908
- ...recorded?.removeEmptyLines === void 0 ? {} : { removeEmptyLines: recorded.removeEmptyLines },
13909
- ...recorded?.pack === void 0 ? {} : { pack: recorded.pack },
13910
- ...recorded?.logCount === void 0 ? {} : { logCount: recorded.logCount },
13911
- ...recorded?.skeleton === void 0 ? {} : { skeleton: recorded.skeleton },
13912
- ...recorded?.sarif === void 0 ? {} : { sarif: recorded.sarif },
13913
- ...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) } : {}
13914
14146
  };
13915
14147
  }
13916
14148
  var validateTool = {
@@ -14147,7 +14379,9 @@ var dependentsTool = {
14147
14379
  }
14148
14380
  const direction = args.direction === "imports" || args.direction === "imported-by" ? String(args.direction) : "both";
14149
14381
  const limit = typeof args.limit === "number" && args.limit > 0 ? Math.floor(args.limit) : 50;
14150
- const resolver = buildImportResolver(manifest.files);
14382
+ const resolver = buildImportResolver(manifest.files, {
14383
+ tsconfig: tsconfigPathsFor(prepared.workspace.root)
14384
+ });
14151
14385
  const imports = [];
14152
14386
  const unresolved = [];
14153
14387
  if (direction !== "imported-by") {
@@ -15625,6 +15859,10 @@ function buildAgentContract() {
15625
15859
  { key: "maxPartBytes", type: "number | string", default: 307200, summary: "Per-part byte budget." },
15626
15860
  { key: "maxPartTokens", type: "number | string | null", default: null, summary: "Per-part token ceiling; narrows maxPartBytes. Minimum 1024." },
15627
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>)." },
15628
15866
  { key: "sarif", type: "boolean", default: false, summary: "Also write reports/audit.sarif." },
15629
15867
  { key: "changedSince", type: "string | null", default: null, summary: "Snapshot only files that differ from this git ref." },
15630
15868
  { key: "staged", type: "boolean", default: false, summary: "Snapshot only files staged in the index." },
@@ -16796,9 +17034,9 @@ function dosDateTime(date) {
16796
17034
  function walkFiles(root, prefix = "") {
16797
17035
  const files = [];
16798
17036
  for (const entry of fs24.readdirSync(path25.join(root, prefix), { withFileTypes: true })) {
16799
- const relative13 = prefix === "" ? entry.name : prefix + "/" + entry.name;
16800
- if (entry.isDirectory()) files.push(...walkFiles(root, relative13));
16801
- 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);
16802
17040
  }
16803
17041
  return files;
16804
17042
  }
@@ -16806,11 +17044,11 @@ function writeZip(options) {
16806
17044
  const entries = [...options.entries ?? []];
16807
17045
  if (options.directory !== void 0) {
16808
17046
  const root = options.directory;
16809
- for (const relative13 of walkFiles(root)) {
16810
- if (options.skip !== void 0 && options.skip(relative13)) continue;
16811
- 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);
16812
17050
  const stat = fs24.statSync(full);
16813
- entries.push({ name: relative13, content: fs24.readFileSync(full), mtime: stat.mtime });
17051
+ entries.push({ name: relative14, content: fs24.readFileSync(full), mtime: stat.mtime });
16814
17052
  }
16815
17053
  }
16816
17054
  if (entries.length > 65535) {
@@ -17003,8 +17241,13 @@ var SERVE_PAGE = `<!doctype html>
17003
17241
  $("counts").textContent = info.included + " included / " + info.skipped + " skipped";
17004
17242
  $("files").innerHTML = "";
17005
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.
17006
17246
  const li = document.createElement("li");
17007
- 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));
17008
17251
  $("files").appendChild(li);
17009
17252
  }
17010
17253
  }
@@ -17041,16 +17284,55 @@ async function startWebServer(options) {
17041
17284
  if (token === null && !["127.0.0.1", "localhost", "::1"].includes(host)) {
17042
17285
  throw new Error("Refusing to serve " + host + " without a token.");
17043
17286
  }
17044
- 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
+ };
17045
17297
  const temporaryClones = /* @__PURE__ */ new Set();
17046
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
+ });
17047
17312
  const insideAllowedRoots = (candidate) => {
17313
+ const resolved = canonical(candidate);
17314
+ return resolved === null ? false : inside(resolved);
17315
+ };
17316
+ const lexicallyInside = (candidate) => {
17048
17317
  const resolved = path25.resolve(candidate);
17049
17318
  return allowedRoots.some((root) => {
17050
- const prefix = root.endsWith(path25.sep) ? root : root + path25.sep;
17051
- return resolved === root || resolved.startsWith(prefix);
17319
+ const prefix = path25.resolve(root) + path25.sep;
17320
+ return resolved === path25.resolve(root) || resolved.startsWith(prefix);
17052
17321
  });
17053
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
+ };
17054
17336
  const authorized = (request) => {
17055
17337
  if (token === null) return true;
17056
17338
  const header = request.headers.authorization ?? "";
@@ -17074,7 +17356,10 @@ async function startWebServer(options) {
17074
17356
  cors["access-control-allow-headers"] = "authorization, content-type";
17075
17357
  cors["access-control-allow-methods"] = "GET, POST, OPTIONS";
17076
17358
  }
17359
+ let responseSent = false;
17077
17360
  const send = (status, body, extra = {}) => {
17361
+ if (responseSent) return;
17362
+ responseSent = true;
17078
17363
  const text2 = typeof body === "string" ? body : JSON.stringify(body);
17079
17364
  response.writeHead(status, {
17080
17365
  ...cors,
@@ -17105,10 +17390,13 @@ async function startWebServer(options) {
17105
17390
  const url = new URL(request.url ?? "/", "http://localhost");
17106
17391
  if (request.method === "POST" && (request.url === "/mcp" || (request.url ?? "").startsWith("/mcp?"))) {
17107
17392
  let received = 0;
17393
+ let tooLarge = false;
17108
17394
  const chunks = [];
17109
17395
  request.on("data", (chunk) => {
17396
+ if (tooLarge) return;
17110
17397
  received += chunk.length;
17111
17398
  if (received > 2 * 1024 * 1024) {
17399
+ tooLarge = true;
17112
17400
  request.destroy();
17113
17401
  send(413, { error: "request body too large" });
17114
17402
  return;
@@ -17116,6 +17404,7 @@ async function startWebServer(options) {
17116
17404
  chunks.push(chunk);
17117
17405
  });
17118
17406
  request.on("end", () => {
17407
+ if (tooLarge) return;
17119
17408
  void (async () => {
17120
17409
  let message;
17121
17410
  try {
@@ -17125,9 +17414,14 @@ async function startWebServer(options) {
17125
17414
  return;
17126
17415
  }
17127
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);
17128
17422
  const answers = [];
17129
17423
  for (const item of batch) {
17130
- const answer = await mcp.handle(item);
17424
+ const answer = await server2.handle(item);
17131
17425
  if (answer !== null) answers.push(answer);
17132
17426
  }
17133
17427
  if (answers.length === 0) send(202, "");
@@ -17138,10 +17432,13 @@ async function startWebServer(options) {
17138
17432
  }
17139
17433
  if (request.method === "POST" && request.url === "/api/generate") {
17140
17434
  let received = 0;
17435
+ let tooLarge = false;
17141
17436
  const chunks = [];
17142
17437
  request.on("data", (chunk) => {
17438
+ if (tooLarge) return;
17143
17439
  received += chunk.length;
17144
17440
  if (received > MAX_BODY) {
17441
+ tooLarge = true;
17145
17442
  request.destroy();
17146
17443
  send(413, { error: "request body too large" });
17147
17444
  return;
@@ -17149,6 +17446,7 @@ async function startWebServer(options) {
17149
17446
  chunks.push(chunk);
17150
17447
  });
17151
17448
  request.on("end", () => {
17449
+ if (tooLarge) return;
17152
17450
  void (async () => {
17153
17451
  let source = "";
17154
17452
  let mode = "full";
@@ -17205,6 +17503,10 @@ async function startWebServer(options) {
17205
17503
  }
17206
17504
  } else {
17207
17505
  target = path25.resolve(options.cwd, source);
17506
+ if (!insideAllowedRoots(target)) {
17507
+ send(403, { error: "outside the served directory: " + target });
17508
+ return;
17509
+ }
17208
17510
  }
17209
17511
  let stat;
17210
17512
  try {
@@ -17222,15 +17524,26 @@ async function startWebServer(options) {
17222
17524
  send(400, { error: loaded.errors.join("; ") });
17223
17525
  return;
17224
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
+ }
17225
17539
  const started = Date.now();
17226
17540
  try {
17227
- const manifest = generateSnapshot({ ...loaded.config ?? {}, cwd: target }, {
17541
+ const manifest = generateSnapshot({ ...runConfig, cwd: target }, {
17228
17542
  ...provenance === void 0 ? {} : { source: provenance },
17229
17543
  ...mode === "slice" ? { slice: { question } } : {},
17230
17544
  ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
17231
17545
  });
17232
17546
  const seconds = ((Date.now() - started) / 1e3).toFixed(2);
17233
- const snapshotDir = path25.join(target, "snapshot");
17234
17547
  const health = auditSnapshot({ snapshotDir, repoDir: target });
17235
17548
  send(200, {
17236
17549
  path: snapshotDir,
@@ -17258,7 +17571,7 @@ async function startWebServer(options) {
17258
17571
  }
17259
17572
  if (request.method === "GET" && request.url?.startsWith("/api/health?") === true) {
17260
17573
  const target = path25.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17261
- if (!insideAllowedRoots(target)) {
17574
+ if (!lexicallyInside(target)) {
17262
17575
  send(403, { error: "outside the served directory: " + target });
17263
17576
  return;
17264
17577
  }
@@ -17266,12 +17579,24 @@ async function startWebServer(options) {
17266
17579
  send(404, { error: "no manifest.json under " + target });
17267
17580
  return;
17268
17581
  }
17582
+ if (!insideAllowedRoots(target)) {
17583
+ send(403, { error: "outside the served directory: " + target });
17584
+ return;
17585
+ }
17269
17586
  const report2 = auditSnapshot({ snapshotDir: target, repoDir: path25.dirname(target) });
17270
17587
  send(200, { score: report2.score, counts: report2.counts, checks: report2.checks });
17271
17588
  return;
17272
17589
  }
17273
17590
  if (request.method === "GET" && (request.url?.startsWith("/api/snapshot?") === true || request.url === "/api/snapshot")) {
17274
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
+ }
17275
17600
  if (!insideAllowedRoots(target)) {
17276
17601
  send(403, { error: "outside the served directory: " + target });
17277
17602
  return;
@@ -17284,6 +17609,11 @@ async function startWebServer(options) {
17284
17609
  send(404, { error: "no manifest.json under " + target });
17285
17610
  return;
17286
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
+ }
17287
17617
  let prompt = "";
17288
17618
  try {
17289
17619
  prompt = fs24.readFileSync(path25.join(target, "PROMPT.md"), "utf8").slice(0, MAX_PREVIEW);
@@ -17303,7 +17633,7 @@ async function startWebServer(options) {
17303
17633
  }
17304
17634
  if (request.method === "GET" && request.url?.startsWith("/api/snapshot.zip") === true) {
17305
17635
  const target = path25.resolve(options.cwd, url.searchParams.get("path") ?? options.cwd);
17306
- if (!insideAllowedRoots(target)) {
17636
+ if (!lexicallyInside(target)) {
17307
17637
  send(403, { error: "outside the served directory: " + target });
17308
17638
  return;
17309
17639
  }
@@ -17311,6 +17641,10 @@ async function startWebServer(options) {
17311
17641
  send(404, { error: "not a snapshot directory: " + target });
17312
17642
  return;
17313
17643
  }
17644
+ if (!insideAllowedRoots(target)) {
17645
+ send(403, { error: "outside the served directory: " + target });
17646
+ return;
17647
+ }
17314
17648
  try {
17315
17649
  const zip = writeZip({ directory: target });
17316
17650
  response.writeHead(200, {
@@ -18056,9 +18390,17 @@ function renderConfig(answers) {
18056
18390
  // Replace function and method bodies with \`{ /* ... */ }\` in TypeScript files.
18057
18391
  // Signatures and comments stay, so the structure of the file survives.
18058
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,
18059
18397
  // Also write reports/audit.sarif (SARIF 2.1.0) for a CI security gate. The
18060
18398
  // matched value is never included \u2014 only the path, the line and the rule.
18061
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,
18062
18404
  // Snapshot only the files that differ from a git ref (for example "main"),
18063
18405
  // plus untracked ones. null means "snapshot everything"; any other value must
18064
18406
  // be a git ref string, and anything else is a configuration error.
@@ -18732,11 +19074,11 @@ function gitignoreEntriesFor(cwd, outDir, tmpDir) {
18732
19074
  const entries = [];
18733
19075
  for (const directory of [outDir, tmpDir]) {
18734
19076
  if (directory === null) continue;
18735
- const relative13 = path25.relative(cwd, path25.resolve(cwd, directory)).replace(/\\/g, "/");
18736
- 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)) {
18737
19079
  continue;
18738
19080
  }
18739
- entries.push(`/${relative13}/`);
19081
+ entries.push(`/${relative14}/`);
18740
19082
  }
18741
19083
  return [...new Set(entries)];
18742
19084
  }
@@ -19067,10 +19409,10 @@ async function runInit(options) {
19067
19409
  };
19068
19410
  }
19069
19411
  function describeTarget(cwd) {
19070
- const relative13 = path25.relative(process.cwd(), cwd);
19071
- if (relative13 === "") return "this directory";
19072
- if (relative13.startsWith("..") || path25.isAbsolute(relative13)) return cwd;
19073
- 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;
19074
19416
  }
19075
19417
  function firstRunMessage(reason, cwd) {
19076
19418
  const where = describeTarget(cwd);
@@ -19172,8 +19514,8 @@ function gitDirectory(cwd) {
19172
19514
  }
19173
19515
  }
19174
19516
  function isInside3(parent, child) {
19175
- const relative13 = path25.relative(parent, child);
19176
- return relative13 === "" || !relative13.startsWith("..") && !path25.isAbsolute(relative13);
19517
+ const relative14 = path25.relative(parent, child);
19518
+ return relative14 === "" || !relative14.startsWith("..") && !path25.isAbsolute(relative14);
19177
19519
  }
19178
19520
  function isRegisteredWorktree(gitDir, cwd) {
19179
19521
  try {
@@ -19412,7 +19754,7 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
19412
19754
  };
19413
19755
  }
19414
19756
  function sha256Hex2(input) {
19415
- return crypto3.createHash("sha256").update(input).digest("hex");
19757
+ return crypto.createHash("sha256").update(input).digest("hex");
19416
19758
  }
19417
19759
  var TS_EXTENSIONS = [
19418
19760
  ".ts",
@@ -19625,7 +19967,7 @@ function maskPathText(value, secretRules) {
19625
19967
  }
19626
19968
  function maskOwnerBrief(brief, secretRules) {
19627
19969
  if (brief === void 0) return void 0;
19628
- const mask = (value) => maskPathText(value, secretRules);
19970
+ const mask = (value) => scanAndRedactSecrets(value, secretRules ?? [], "owner-brief").redacted;
19629
19971
  return {
19630
19972
  ...brief,
19631
19973
  path: mask(brief.path),
@@ -19671,9 +20013,9 @@ function listEntries(dir) {
19671
20013
  return;
19672
20014
  }
19673
20015
  for (const child of children) {
19674
- const relative13 = prefix === "" ? child.name : `${prefix}/${child.name}`;
19675
- entries.push(relative13);
19676
- 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);
19677
20019
  }
19678
20020
  };
19679
20021
  walk2(dir, "");
@@ -19708,7 +20050,7 @@ function markerInventory(dir, written) {
19708
20050
  }
19709
20051
  return { entries, files };
19710
20052
  }
19711
- function markerPayload(dir, state, id, createdAt, written) {
20053
+ function markerPayload(dir, state, id, createdAt, written, runId) {
19712
20054
  const { entries, files } = markerInventory(dir, written);
19713
20055
  const marker2 = {
19714
20056
  generator: GENERATOR_NAME,
@@ -19717,6 +20059,7 @@ function markerPayload(dir, state, id, createdAt, written) {
19717
20059
  createdAt,
19718
20060
  state,
19719
20061
  id,
20062
+ ...runId === void 0 ? {} : { runId },
19720
20063
  pid: process.pid,
19721
20064
  entries,
19722
20065
  files
@@ -19814,6 +20157,7 @@ function readOwnershipMarker(dir) {
19814
20157
  createdAt: typeof candidate.createdAt === "string" ? candidate.createdAt : "unknown",
19815
20158
  state: candidate.state,
19816
20159
  id: candidate.id,
20160
+ runId: typeof candidate.runId === "string" ? candidate.runId : void 0,
19817
20161
  pid: typeof candidate.pid === "number" ? candidate.pid : void 0,
19818
20162
  manifestSha256: typeof candidate.manifestSha256 === "string" ? candidate.manifestSha256 : void 0,
19819
20163
  entries: Array.isArray(candidate.entries) && candidate.entries.every((entry) => typeof entry === "string") ? candidate.entries : void 0,
@@ -19972,13 +20316,19 @@ function assessSnapshotDirectory(dir) {
19972
20316
  };
19973
20317
  }
19974
20318
  const entries = listEntries(dir);
19975
- const foreignEntries = entries.filter(
20319
+ let foreignEntries = entries.filter(
19976
20320
  (entry) => !recorded.has(entry) && !isIgnorableEntry(entry)
19977
20321
  );
20322
+ const legacySignatureOnly = foreignEntries.length === 1 && foreignEntries[0] === SIGNATURE_FILE && verifySnapshotSignature(dir).ok;
20323
+ if (legacySignatureOnly) foreignEntries = [];
19978
20324
  if (foreignEntries.length > 0) {
19979
20325
  return { owned: false, problem: null, foreignEntries, marker: marker2 };
19980
20326
  }
19981
- 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
+ );
19982
20332
  return {
19983
20333
  owned: inventoryProblem === null,
19984
20334
  problem: inventoryProblem,
@@ -20156,13 +20506,13 @@ function startLockHeartbeat(lockPath) {
20156
20506
  return () => void 0;
20157
20507
  }
20158
20508
  }
20159
- function acquireRunLock(stagingRoot) {
20509
+ function acquireRunLock(stagingRoot, runId) {
20160
20510
  const lockPath = lockPathFor(stagingRoot);
20161
20511
  const payload = `${JSON.stringify({
20162
20512
  pid: process.pid,
20163
20513
  stagingRoot,
20164
20514
  host: os2.hostname(),
20165
- runId: crypto3.randomUUID(),
20515
+ runId,
20166
20516
  heartbeatMs: LOCK_HEARTBEAT_MS,
20167
20517
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
20168
20518
  })}
@@ -20216,6 +20566,33 @@ function canonicalLockTarget(targetPath) {
20216
20566
  function lockPathFor(stagingRoot) {
20217
20567
  return path25.join(os2.tmpdir(), `codebase-snapshot-${lockKeyFor(stagingRoot)}.lock`);
20218
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
+ }
20219
20596
  function lockHeartbeatAgeMs(lockPath) {
20220
20597
  try {
20221
20598
  return Date.now() - fs24.statSync(lockPath).mtimeMs;
@@ -20530,6 +20907,7 @@ function generateSnapshot(configInput, options) {
20530
20907
  assertUsableConfigInput(configInput);
20531
20908
  const config = isResolvedConfig(configInput) ? normalizeResolvedConfig(configInput) : resolveConfig(configInput ?? null);
20532
20909
  const dryRun = options?.dryRun ?? false;
20910
+ const runId = options?.runId ?? crypto.randomUUID();
20533
20911
  const gitInfo = getGitInfo(config.cwd, config.branch);
20534
20912
  const changedScope = config.changedSince !== void 0 || config.staged === true ? resolveChangedScope(config.cwd, {
20535
20913
  ...config.changedSince === void 0 ? {} : { changedSince: config.changedSince },
@@ -20549,7 +20927,7 @@ function generateSnapshot(configInput, options) {
20549
20927
  // output — but only at these exact paths, not at every directory that shares the name.
20550
20928
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
20551
20929
  (directory) => path25.relative(config.cwd, path25.resolve(config.cwd, directory)).replace(/\\/g, "/")
20552
- ).filter((relative13) => relative13.length > 0 && !relative13.startsWith("..")),
20930
+ ).filter((relative14) => relative14.length > 0 && !relative14.startsWith("..")),
20553
20931
  // A staged path can be absent from the working tree while its index blob exists. Discovery
20554
20932
  // lists the working tree, so those paths would never reach the scan at all.
20555
20933
  ...stagedPaths.size > 0 ? { extraPaths: [...stagedPaths] } : {}
@@ -21236,9 +21614,13 @@ function generateSnapshot(configInput, options) {
21236
21614
  if (navigationText !== null) manifest.artifacts.navigation = artifactRecord(navigationText);
21237
21615
  const auditText = artifacts.audit ? generateAuditReport(manifest, secretFindings, config.secretRules) : null;
21238
21616
  if (auditText !== null) manifest.artifacts.audit = artifactRecord(auditText);
21239
- 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;
21240
21622
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
21241
- 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;
21242
21624
  if (artifacts.diff && diffReport === null && !isGitRepository(config.cwd)) {
21243
21625
  manifest.warnings.push(
21244
21626
  "--include-diffs was requested, but the generated directory is not a git repository; reports/diff.md was not written."
@@ -21282,7 +21664,8 @@ function generateSnapshot(configInput, options) {
21282
21664
  const entry = {
21283
21665
  ...file,
21284
21666
  content,
21285
- inclusionMode: "full",
21667
+ inclusionMode: file.inclusionMode === "comments-stripped" ? "comments-stripped" : "full",
21668
+ ...file.emptyLinesRemoved === true ? { emptyLinesRemoved: true } : {},
21286
21669
  isPreviewTruncated: false,
21287
21670
  includedBytes: Buffer.byteLength(content, "utf8"),
21288
21671
  includedLines: countLines(content)
@@ -21350,7 +21733,7 @@ function generateSnapshot(configInput, options) {
21350
21733
  const lockKeys = Array.from(/* @__PURE__ */ new Set([tmpDir, outDir])).sort();
21351
21734
  const releases = [];
21352
21735
  try {
21353
- for (const key of lockKeys) releases.push(acquireRunLock(key));
21736
+ for (const key of lockKeys) releases.push(acquireRunLock(key, runId));
21354
21737
  } catch (error) {
21355
21738
  for (const release of [...releases].reverse()) release();
21356
21739
  throw error;
@@ -21366,7 +21749,7 @@ function generateSnapshot(configInput, options) {
21366
21749
  ensureParentDirectory(outDir, "outDir");
21367
21750
  fs24.mkdirSync(tmpDir, { recursive: true });
21368
21751
  cleanStaleRunDirs(tmpDir);
21369
- const snapshotId = crypto3.randomUUID();
21752
+ const snapshotId = crypto.randomUUID();
21370
21753
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
21371
21754
  stagingDir = path25.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
21372
21755
  fs24.mkdirSync(stagingDir);
@@ -21377,6 +21760,7 @@ function generateSnapshot(configInput, options) {
21377
21760
  createdAt,
21378
21761
  state: "staging",
21379
21762
  id: snapshotId,
21763
+ runId,
21380
21764
  pid: process.pid
21381
21765
  });
21382
21766
  const partsDir = path25.join(stagingDir, "parts");
@@ -21445,6 +21829,17 @@ function generateSnapshot(configInput, options) {
21445
21829
  if (artifacts.manifest) {
21446
21830
  writeArtifact(stagingDir, "manifest.json", JSON.stringify(manifest, null, 2));
21447
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
+ }
21448
21843
  if (monolithJson !== null) {
21449
21844
  writeArtifact(stagingDir, "full-codebase.json", monolithJson);
21450
21845
  }
@@ -21456,7 +21851,7 @@ function generateSnapshot(configInput, options) {
21456
21851
  }
21457
21852
  writeOwnershipMarker(
21458
21853
  stagingDir,
21459
- markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts)
21854
+ markerPayload(stagingDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21460
21855
  );
21461
21856
  swapIntoPlace(stagingDir, outDir, () => assertReplaceable(outDir, "outDir", config.secretRules));
21462
21857
  stagingDir = null;
@@ -21467,10 +21862,16 @@ function generateSnapshot(configInput, options) {
21467
21862
  if (artifacts.manifest && manifest.warnings.length !== warningsBeforeHook) {
21468
21863
  writeManifestAtomically(path25.join(outDir, "manifest.json"), manifest);
21469
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
+ }
21470
21871
  }
21471
21872
  writeOwnershipMarker(
21472
21873
  outDir,
21473
- markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts)
21874
+ markerPayload(outDir, "complete", snapshotId, createdAt, writtenArtifacts, runId)
21474
21875
  );
21475
21876
  };
21476
21877
  if (config.hooks.afterGenerate) shipHookState();
@@ -21533,4 +21934,4 @@ async function generateSnapshotAsync(configInput, options) {
21533
21934
  return manifest;
21534
21935
  }
21535
21936
 
21536
- 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 };