codebase-snapshot 0.21.0 → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,31 +1,251 @@
1
1
  import './chunk-WMEZFLUT.js';
2
- import { shouldCheck, checkForUpdate, GENERATOR_VERSION, cacheFilePath, formatUpdateNotice, installKind, buildAgentContract, startWebServer, startHttpTransport, buildTools, runStdioServer, parseRemoteSource, assertPublicHost, cloneRepository, makeCloneDirectory, loadConfigFileDetailed, resolveConfig, validateSnapshot, readConfinedText, auditSnapshot, describeManifestShapeProblem, loadManifest, buildLiveIndex, resolveImpactChanges, computeImpact, DEFAULT_MAX_PROGRAM_FILES, findMultipleSymbolReferences, planTestRun, renderImpactText, runTestPlan, briefFromPaths, resolveDiffBase, filterAndRedactDiff, matchesExclude, defaultIgnoreReason, isSensitivePath, findSection, parsePartSections, buildBrief, explainPath, compareManifests, renderDiffText, generateSnapshot, getGitInfo, loadSigningKey, SIGNATURE_FILE, formatNumber, isDiscoveryMode, ARTIFACT_NAMES, COMMAND_OPTION_SCOPE, commandsForOption, getPreset, unknownPresetMessage, GENERATOR_NAME, runInit, installPreCommitHook, PromptCancelled, SKILL_NAME, renderSkill, resolveLatest, isNewer, updateCommand, findConfigFile, planFirstRun, isEffectivelyEmpty, isInteractive, defaultIO, hasPriorSnapshot, DEFAULT_ANSWERS, firstRunMessage, escapeControls, stripJsonComments, parseByteSize, gitignorePath, appendGitignoreEntries, runWithStdoutCapture, inlineCode, findSecretInPath, MIN_MAX_PART_TOKENS, MIN_MAX_PART_BYTES, renderContractText, renderExplainText } from './chunk-TDPYLX7X.js';
3
- export { buildAgentContract } from './chunk-TDPYLX7X.js';
2
+ import { shouldCheck, checkForUpdate, GENERATOR_VERSION, cacheFilePath, formatUpdateNotice, installKind, buildAgentContract, startWebServer, startHttpTransport, buildTools, runStdioServer, parseRemoteSource, assertPublicHost, cloneRepository, makeCloneDirectory, loadConfigFileDetailed, assertServerSafeConfig, resolveConfig, validateSnapshot, readConfinedText, auditSnapshot, describeManifestShapeProblem, loadManifest, buildLiveIndex, resolveImpactChanges, computeImpact, DEFAULT_MAX_PROGRAM_FILES, findMultipleSymbolReferences, planTestRun, renderImpactText, runTestPlan, briefFromPaths, resolveDiffBase, filterAndRedactDiff, matchesExclude, defaultIgnoreReason, isSensitivePath, findSection, parsePartSections, buildBrief, explainPath, compareManifests, renderDiffText, generateSnapshot, getGitInfo, loadSigningKey, SIGNATURE_FILE, formatNumber, isDiscoveryMode, ARTIFACT_NAMES, COMMAND_OPTION_SCOPE, commandsForOption, getPreset, unknownPresetMessage, GENERATOR_NAME, runInit, installPreCommitHook, PromptCancelled, SKILL_NAME, renderSkill, resolveLatest, isNewer, updateCommand, findConfigFile, planFirstRun, isEffectivelyEmpty, isInteractive, defaultIO, hasPriorSnapshot, DEFAULT_ANSWERS, firstRunMessage, escapeControls, stripJsonComments, parseByteSize, gitignorePath, appendGitignoreEntries, runWithStdoutCapture, inlineCode, findSecretInPath, MIN_MAX_PART_TOKENS, MIN_MAX_PART_BYTES, renderContractText, renderExplainText } from './chunk-7AAXOTKS.js';
3
+ export { buildAgentContract } from './chunk-7AAXOTKS.js';
4
4
  import { spawnSync } from 'child_process';
5
- import * as fs2 from 'fs';
6
- import * as path2 from 'path';
5
+ import * as fs3 from 'fs';
6
+ import * as path3 from 'path';
7
7
  import { fileURLToPath } from 'url';
8
8
  import { parseArgs } from 'util';
9
9
 
10
+ var MAX_CONSUMERS = 10;
11
+ var MAX_TESTS = 5;
12
+ var MAX_ROUTES = 5;
13
+ var MAX_HOOK_CHARS = 1200;
14
+ function take(values, limit) {
15
+ return { taken: values.slice(0, limit), omitted: Math.max(0, values.length - limit) };
16
+ }
17
+ function safePath(value) {
18
+ return escapeControls(findSecretInPath(value)?.masked ?? value);
19
+ }
20
+ function toGap(entry) {
21
+ return {
22
+ kind: "consumer",
23
+ path: safePath(entry.path),
24
+ distance: entry.distance,
25
+ via: safePath(entry.via),
26
+ ...entry.confidence === void 0 ? {} : { confidence: entry.confidence }
27
+ };
28
+ }
29
+ function testGap(entry) {
30
+ return { kind: "test", path: safePath(entry.path), covers: entry.covers.map(safePath) };
31
+ }
32
+ function routeGap(entry) {
33
+ return { kind: "route", path: safePath(entry.path), methods: [...entry.methods] };
34
+ }
35
+ function buildGuardReport(impact) {
36
+ const changedSet = new Set(impact.changed.map((entry) => entry.path));
37
+ const changed = impact.changed.map((entry) => safePath(entry.path));
38
+ const consumers = impact.affected.filter((entry) => !changedSet.has(entry.path));
39
+ const tests = impact.tests.filter((entry) => !changedSet.has(entry.path));
40
+ const routes = (impact.routesAffected ?? []).filter((entry) => !changedSet.has(entry.path));
41
+ const consumerPart = take(consumers, MAX_CONSUMERS);
42
+ const testPart = take(tests, MAX_TESTS);
43
+ const routePart = take(routes, MAX_ROUTES);
44
+ const gaps = [
45
+ ...consumerPart.taken.map(toGap),
46
+ ...testPart.taken.map(testGap),
47
+ ...routePart.taken.map(routeGap)
48
+ ];
49
+ const symbolPruned = impact.affected.some(
50
+ (entry) => entry.impactKind === "direct-symbol" || entry.impactKind === "reexport" || entry.impactKind === "namespace-or-cjs"
51
+ );
52
+ return {
53
+ schemaVersion: 1,
54
+ changed,
55
+ gaps,
56
+ trust: impact.trust,
57
+ confidence: symbolPruned ? "symbol-pruned" : "file-import",
58
+ truncated: impact.truncated || consumerPart.omitted > 0 || testPart.omitted > 0 || routePart.omitted > 0,
59
+ omitted: {
60
+ consumers: consumerPart.omitted,
61
+ tests: testPart.omitted,
62
+ routes: routePart.omitted
63
+ }
64
+ };
65
+ }
66
+ function label(gap) {
67
+ if (gap.kind === "test") return "test";
68
+ if (gap.kind === "route") return "route";
69
+ return "consumer";
70
+ }
71
+ function renderGuardText(report) {
72
+ if (report.gaps.length === 0) {
73
+ return "Change Guard: no gaps in this change.\n changed: " + report.changed.length + " file(s); coverage: " + report.trust.coverage + "\n";
74
+ }
75
+ const lines = [];
76
+ lines.push("Change Guard: " + report.gaps.length + " gap(s) in this change");
77
+ for (const gap of report.gaps) {
78
+ const parts = [gap.path];
79
+ if (gap.kind === "consumer") {
80
+ const meta = [];
81
+ if (gap.distance !== void 0) meta.push(gap.distance + " hop" + (gap.distance === 1 ? "" : "s"));
82
+ if (gap.confidence !== void 0) meta.push(gap.confidence);
83
+ if (gap.via !== void 0) meta.push("via " + gap.via);
84
+ if (meta.length > 0) parts.push("(" + meta.join(", ") + ")");
85
+ } else if (gap.kind === "test") {
86
+ parts.push("(test" + (gap.covers && gap.covers.length > 0 ? ": " + gap.covers.join(", ") : "") + ")");
87
+ } else {
88
+ parts.push("(route" + (gap.methods && gap.methods.length > 0 ? ": " + gap.methods.join(", ") : "") + ")");
89
+ }
90
+ lines.push(" " + label(gap).padEnd(9) + parts.join(" "));
91
+ }
92
+ if (report.truncated) {
93
+ const omitted = report.omitted;
94
+ lines.push(
95
+ " \u2026 truncated: " + omitted.consumers + " consumer(s), " + omitted.tests + " test(s), " + omitted.routes + " route(s) omitted"
96
+ );
97
+ }
98
+ lines.push(" coverage: " + report.trust.coverage + " \xB7 confidence: " + report.confidence);
99
+ return lines.join("\n");
100
+ }
101
+ function truncateGuardText(text, maxChars) {
102
+ if (text.length <= maxChars) return text;
103
+ const marker = "\n\u2026 run codebase-snapshot guard --changed for the full list";
104
+ const room = Math.max(0, maxChars - marker.length);
105
+ return text.slice(0, room).trimEnd() + marker;
106
+ }
107
+ function renderGuardHookText(report, maxChars = MAX_HOOK_CHARS) {
108
+ if (report.gaps.length === 0) return "";
109
+ const lines = ["[change-guard] " + report.gaps.length + " gap(s) in this change:"];
110
+ for (const gap of report.gaps) {
111
+ if (gap.kind === "consumer") {
112
+ lines.push(
113
+ " " + gap.path + (gap.distance === void 0 ? "" : " (" + gap.distance + " hop" + (gap.distance === 1 ? "" : "s") + ")")
114
+ );
115
+ } else if (gap.kind === "test") {
116
+ lines.push(" test " + gap.path);
117
+ } else {
118
+ lines.push(" route " + gap.path + (gap.methods && gap.methods.length > 0 ? " (" + gap.methods.join(", ") + ")" : ""));
119
+ }
120
+ }
121
+ lines.push("coverage: " + report.trust.coverage + " \xB7 confidence: " + report.confidence);
122
+ lines.push("run: npx codebase-snapshot brief --diff HEAD");
123
+ return truncateGuardText(lines.join("\n"), maxChars);
124
+ }
125
+ function renderGuardHook(report, client, event, maxChars = MAX_HOOK_CHARS) {
126
+ const text = renderGuardHookText(report, maxChars);
127
+ if (text.length === 0) return "{}";
128
+ if (client === "claude") {
129
+ return JSON.stringify({
130
+ hookSpecificOutput: {
131
+ hookEventName: event,
132
+ additionalContext: text
133
+ }
134
+ });
135
+ }
136
+ return JSON.stringify({ additionalContext: text });
137
+ }
138
+ function canonicalForRelative(target) {
139
+ try {
140
+ return fs3.realpathSync.native(target);
141
+ } catch {
142
+ try {
143
+ return path3.join(fs3.realpathSync.native(path3.dirname(target)), path3.basename(target));
144
+ } catch {
145
+ return path3.resolve(target);
146
+ }
147
+ }
148
+ }
149
+ function normalizePath(cwd, raw) {
150
+ const value = raw.trim();
151
+ if (value.length === 0 || value.includes("\0")) return null;
152
+ const absolute = path3.isAbsolute(value) ? value : path3.resolve(cwd, value);
153
+ const relative4 = path3.relative(canonicalForRelative(cwd), canonicalForRelative(absolute)).split(path3.sep).join("/");
154
+ if (relative4 === "" || relative4 === ".." || relative4.startsWith("../") || path3.isAbsolute(relative4)) {
155
+ return null;
156
+ }
157
+ return relative4;
158
+ }
159
+ function collectPaths(value, out, depth = 0) {
160
+ if (depth > 6 || value === null || typeof value !== "object") return;
161
+ if (Array.isArray(value)) {
162
+ for (const item of value) collectPaths(item, out, depth + 1);
163
+ return;
164
+ }
165
+ const record = value;
166
+ for (const [key, item] of Object.entries(record)) {
167
+ if (typeof item === "string" && /^(file_path|filePath|path|file|filename|fileName)$/i.test(key)) {
168
+ out.add(item);
169
+ continue;
170
+ }
171
+ if (Array.isArray(item) && /^(files|paths|file_paths|filePaths)$/i.test(key)) {
172
+ for (const entry of item) if (typeof entry === "string") out.add(entry);
173
+ continue;
174
+ }
175
+ if (typeof item === "object" && item !== null) collectPaths(item, out, depth + 1);
176
+ }
177
+ }
178
+ function parseGuardHookInput(client, raw, cwd) {
179
+ let payload;
180
+ try {
181
+ payload = JSON.parse(raw);
182
+ } catch {
183
+ throw new Error("guard --hook expects one JSON object on stdin.");
184
+ }
185
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
186
+ throw new Error("guard --hook expects one JSON object on stdin.");
187
+ }
188
+ const record = payload;
189
+ const candidates = /* @__PURE__ */ new Set();
190
+ if (client === "claude") {
191
+ const toolInput = record.tool_input;
192
+ if (toolInput !== null && typeof toolInput === "object") collectPaths(toolInput, candidates);
193
+ const toolResponse = record.tool_response;
194
+ if (toolResponse !== null && typeof toolResponse === "object") collectPaths(toolResponse, candidates);
195
+ if (typeof record.file_path === "string") candidates.add(record.file_path);
196
+ } else if (client === "copilot") {
197
+ if (typeof record.toolArgs === "string") {
198
+ try {
199
+ collectPaths(JSON.parse(record.toolArgs), candidates);
200
+ } catch {
201
+ }
202
+ } else if (record.toolArgs !== null && typeof record.toolArgs === "object") {
203
+ collectPaths(record.toolArgs, candidates);
204
+ }
205
+ if (record.tool_input !== null && typeof record.tool_input === "object") {
206
+ collectPaths(record.tool_input, candidates);
207
+ }
208
+ } else {
209
+ if (record.tool_input !== null && typeof record.tool_input === "object") {
210
+ collectPaths(record.tool_input, candidates);
211
+ }
212
+ if (record.toolArgs !== null && typeof record.toolArgs === "object") {
213
+ collectPaths(record.toolArgs, candidates);
214
+ }
215
+ if (typeof record.path === "string") candidates.add(record.path);
216
+ }
217
+ const paths = [];
218
+ for (const candidate of candidates) {
219
+ const normalized = normalizePath(cwd, candidate);
220
+ if (normalized !== null) paths.push(normalized);
221
+ }
222
+ const sessionId = typeof record.session_id === "string" ? record.session_id : typeof record.sessionId === "string" ? record.sessionId : void 0;
223
+ const event = typeof record.hook_event_name === "string" ? record.hook_event_name : typeof record.hookEventName === "string" ? record.hookEventName : "PostToolUse";
224
+ return {
225
+ paths: [...new Set(paths)].sort((left, right) => left.localeCompare(right)),
226
+ ...sessionId === void 0 ? {} : { sessionId },
227
+ event
228
+ };
229
+ }
10
230
  var SKILL_TARGETS = ["agents", "claude", "cursor", "all"];
11
231
  var REFUSED = "Refusing to install the agent skill";
12
232
  var LEGACY_AGENTS_MARKER = "<!-- codebase-snapshot:skill:start -->";
13
233
  function targetPath(cwd, target) {
14
234
  switch (target) {
15
235
  case "agents":
16
- return path2.join(cwd, ".agents", "skills", SKILL_NAME, "SKILL.md");
236
+ return path3.join(cwd, ".agents", "skills", SKILL_NAME, "SKILL.md");
17
237
  case "claude":
18
- return path2.join(cwd, ".claude", "skills", SKILL_NAME, "SKILL.md");
238
+ return path3.join(cwd, ".claude", "skills", SKILL_NAME, "SKILL.md");
19
239
  case "cursor":
20
- return path2.join(cwd, ".cursor", "rules", `${SKILL_NAME}.mdc`);
240
+ return path3.join(cwd, ".cursor", "rules", `${SKILL_NAME}.mdc`);
21
241
  }
22
242
  }
23
243
  function assertWritableInsideRepository(cwd, filePath) {
24
- const root = fs2.realpathSync(cwd);
25
- const shown = path2.relative(root, filePath) || filePath;
244
+ const root = fs3.realpathSync(cwd);
245
+ const shown = path3.relative(root, filePath) || filePath;
26
246
  let stat = null;
27
247
  try {
28
- stat = fs2.lstatSync(filePath);
248
+ stat = fs3.lstatSync(filePath);
29
249
  } catch {
30
250
  stat = null;
31
251
  }
@@ -41,32 +261,32 @@ function assertWritableInsideRepository(cwd, filePath) {
41
261
  }
42
262
  let existing = filePath;
43
263
  const missing = [];
44
- while (!fs2.existsSync(existing)) {
45
- missing.unshift(path2.basename(existing));
46
- const parent = path2.dirname(existing);
264
+ while (!fs3.existsSync(existing)) {
265
+ missing.unshift(path3.basename(existing));
266
+ const parent = path3.dirname(existing);
47
267
  if (parent === existing) break;
48
268
  existing = parent;
49
269
  }
50
- const realAncestor = fs2.realpathSync(existing);
51
- const resolved = missing.length === 0 ? realAncestor : path2.join(realAncestor, ...missing);
52
- if (resolved !== root && !resolved.startsWith(`${root}${path2.sep}`)) {
270
+ const realAncestor = fs3.realpathSync(existing);
271
+ const resolved = missing.length === 0 ? realAncestor : path3.join(realAncestor, ...missing);
272
+ if (resolved !== root && !resolved.startsWith(`${root}${path3.sep}`)) {
53
273
  throw new Error(
54
274
  `${REFUSED}: ${shown} resolves outside the repository (${resolved}). Move it back inside ${root}, or remove the link, and run again.`
55
275
  );
56
276
  }
57
277
  }
58
278
  function writeIfChanged(target, filePath, content) {
59
- const existing = fs2.existsSync(filePath) ? fs2.readFileSync(filePath, "utf8") : null;
279
+ const existing = fs3.existsSync(filePath) ? fs3.readFileSync(filePath, "utf8") : null;
60
280
  if (existing === content) return { target, path: filePath, action: "unchanged" };
61
- fs2.mkdirSync(path2.dirname(filePath), { recursive: true });
62
- fs2.writeFileSync(filePath, content, "utf8");
281
+ fs3.mkdirSync(path3.dirname(filePath), { recursive: true });
282
+ fs3.writeFileSync(filePath, content, "utf8");
63
283
  return { target, path: filePath, action: existing === null ? "created" : "updated" };
64
284
  }
65
285
  function legacyAgentsNote(cwd) {
66
- const filePath = path2.join(cwd, "AGENTS.md");
286
+ const filePath = path3.join(cwd, "AGENTS.md");
67
287
  try {
68
- if (!fs2.existsSync(filePath)) return null;
69
- if (!fs2.readFileSync(filePath, "utf8").includes(LEGACY_AGENTS_MARKER)) return null;
288
+ if (!fs3.existsSync(filePath)) return null;
289
+ if (!fs3.readFileSync(filePath, "utf8").includes(LEGACY_AGENTS_MARKER)) return null;
70
290
  } catch {
71
291
  return null;
72
292
  }
@@ -78,9 +298,9 @@ function installSkill(cwd, target = "all", options = {}) {
78
298
  const notes = [];
79
299
  const wanted = target === "all" ? ["agents", "claude", "cursor"] : [target];
80
300
  for (const item of wanted) assertWritableInsideRepository(cwd, targetPath(cwd, item));
81
- const createsSomething = wanted.some((item) => !fs2.existsSync(targetPath(cwd, item)));
301
+ const createsSomething = wanted.some((item) => !fs3.existsSync(targetPath(cwd, item)));
82
302
  if (createsSomething) {
83
- assertWritableInsideRepository(cwd, path2.join(cwd, ".gitignore"));
303
+ assertWritableInsideRepository(cwd, path3.join(cwd, ".gitignore"));
84
304
  }
85
305
  const pendingMcp = options.withMcp === true ? prepareMcpConfig(cwd) : null;
86
306
  for (const item of wanted) {
@@ -95,20 +315,20 @@ function installSkill(cwd, target = "all", options = {}) {
95
315
  if (pendingMcp !== null) {
96
316
  if (pendingMcp.note !== null) notes.push(pendingMcp.note);
97
317
  if (pendingMcp.content !== null) {
98
- fs2.writeFileSync(pendingMcp.filePath, pendingMcp.content, "utf8");
318
+ fs3.writeFileSync(pendingMcp.filePath, pendingMcp.content, "utf8");
99
319
  }
100
320
  mcp = { path: pendingMcp.filePath, action: pendingMcp.action };
101
321
  }
102
322
  return { cwd, written, gitignored: ignore.added, notes, ...mcp === void 0 ? {} : { mcp } };
103
323
  }
104
324
  function prepareMcpConfig(cwd) {
105
- const filePath = path2.join(cwd, ".mcp.json");
325
+ const filePath = path3.join(cwd, ".mcp.json");
106
326
  assertWritableInsideRepository(cwd, filePath);
107
327
  const desired = { command: "npx", args: ["-y", "codebase-snapshot@latest", "mcp"] };
108
328
  let parsed = {};
109
329
  let existing = null;
110
- if (fs2.existsSync(filePath)) {
111
- existing = fs2.readFileSync(filePath, "utf8");
330
+ if (fs3.existsSync(filePath)) {
331
+ existing = fs3.readFileSync(filePath, "utf8");
112
332
  let candidate;
113
333
  try {
114
334
  candidate = JSON.parse(existing);
@@ -157,6 +377,7 @@ var COMMAND_ALIASES = /* @__PURE__ */ new Map([
157
377
  ["health", "health"],
158
378
  ["report", "report"],
159
379
  ["impact", "impact"],
380
+ ["guard", "guard"],
160
381
  ["brief", "brief"],
161
382
  ["init", "init"],
162
383
  ["setup", "setup"],
@@ -174,6 +395,7 @@ var COMMAND_ARITY = {
174
395
  health: 0,
175
396
  report: 0,
176
397
  impact: 0,
398
+ guard: 0,
177
399
  brief: 1,
178
400
  init: 0,
179
401
  setup: 0,
@@ -220,6 +442,9 @@ var CLI_OPTIONS = {
220
442
  "changed-since": { type: "string" },
221
443
  diff: { type: "string" },
222
444
  paths: { type: "string" },
445
+ hook: { type: "string" },
446
+ changed: { type: "boolean" },
447
+ "max-chars": { type: "string" },
223
448
  depth: { type: "string" },
224
449
  "max-results": { type: "string" },
225
450
  "no-cache": { type: "boolean" },
@@ -294,6 +519,7 @@ Commands:
294
519
  init Generate a starter snapshot.config file
295
520
  report Print codebase health, layer metrics, and secret audit
296
521
  impact Report changed files, transitive importers, routes and candidate tests
522
+ guard Check a change for untouched consumers, tests and routes (hook-aware)
297
523
  brief One redacted review pack: impact, diff hunks and bounded source windows
298
524
  explain <path> Show how one path would be treated: layer, kind, part, skips
299
525
  diff <a> <b> Compare two snapshots (directories or manifest.json files)
@@ -381,24 +607,33 @@ Options:
381
607
  --all-members Audit every snapshot a --workspace run wrote
382
608
  --deep Replay every full body against the source on disk
383
609
 
384
- impact and brief:
385
- --diff <ref> Compare the working tree against this git ref
386
- --paths <a,b> Treat these repository-relative paths as the change
387
- --depth <n> Reverse-import hops to follow (default: 3, max: 8)
388
- --max-results <n> Cap affected files (default: 200, max: 1000)
610
+ impact only:
389
611
  --tests-paths Print candidate test paths, one per line
390
612
  --run Run the detected test runner (text format only)
391
613
  --precise Add bounded compiler-resolved symbol references
392
614
  --include-imports Include outgoing imports of changed files
393
615
  --include-cycles Include import cycles in the impacted subgraph
394
- --no-live Require the persisted snapshot instead of the live index
395
- --no-cache Bypass the OS live-index summary cache
616
+
617
+ guard only:
618
+ --hook <client> Read one hook payload from stdin: claude | copilot | codex | raw
619
+ --changed Check the working tree against HEAD (default when no --hook)
620
+ --max-chars <n> Cap the model-facing hook text (default 1200, max 10000)
621
+
622
+ brief only:
396
623
  --max-tokens <n> Brief token budget (default: 12000, minimum: 500)
397
624
  --lines-per-file <n> Brief lines per file (default: 80)
398
625
  --include-tests Include candidate tests in the brief
399
626
  --copy Copy the brief to the clipboard
400
627
  --out <path> Write the brief inside the repository
401
628
 
629
+ impact, guard and brief:
630
+ --diff <ref> Compare the working tree against this git ref
631
+ --paths <a,b> Treat these repository-relative paths as the change
632
+ --depth <n> Reverse-import hops to follow (default: 3, max: 8)
633
+ --max-results <n> Cap affected files (default: 200, max: 1000)
634
+ --no-live Require the persisted snapshot instead of the live index
635
+ --no-cache Bypass the OS live-index summary cache
636
+
402
637
  skill only:
403
638
  --install Write the skill into the repository instead of printing
404
639
  --target <name> agents | claude | cursor | all (default: all)
@@ -459,6 +694,9 @@ function parseCountOption(raw, optionName, minimum = 0) {
459
694
  }
460
695
  return value;
461
696
  }
697
+ function isGuardClient(value) {
698
+ return value === "claude" || value === "copilot" || value === "codex" || value === "raw";
699
+ }
462
700
  function parsePromptTask(value) {
463
701
  if (value === void 0) return void 0;
464
702
  if (value === "audit" || value === "review" || value === "explain") return value;
@@ -530,10 +768,10 @@ function parseCliArgs(argv) {
530
768
  }
531
769
  if (values.cwd !== void 0) {
532
770
  const target = String(values.cwd);
533
- if (!fs2.existsSync(target)) {
771
+ if (!fs3.existsSync(target)) {
534
772
  throw new UsageError(`--cwd directory does not exist: ${target}`);
535
773
  }
536
- if (!fs2.statSync(target).isDirectory()) {
774
+ if (!fs3.statSync(target).isDirectory()) {
537
775
  throw new UsageError(`--cwd is not a directory: ${target}`);
538
776
  }
539
777
  }
@@ -625,6 +863,37 @@ function parseCliArgs(argv) {
625
863
  );
626
864
  }
627
865
  }
866
+ const rawHook = values.hook === void 0 ? void 0 : String(values.hook);
867
+ if (rawHook !== void 0 && !isGuardClient(rawHook)) {
868
+ throw new UsageError(
869
+ `--hook must be one of: claude, copilot, codex, raw (received "${rawHook}").`
870
+ );
871
+ }
872
+ if (rawHook !== void 0) {
873
+ if (paths !== void 0 || rawDiff !== void 0) {
874
+ throw new UsageError(
875
+ "guard --hook reads the changed paths from its stdin payload; do not pass --paths or --diff."
876
+ );
877
+ }
878
+ if (values.changed === true) {
879
+ throw new UsageError("guard --hook already runs on the payload; do not pass --changed.");
880
+ }
881
+ }
882
+ if (command === "guard") {
883
+ if (paths !== void 0 && rawDiff !== void 0) {
884
+ throw new UsageError("guard accepts either --diff <ref> or --paths <a,b>, not both.");
885
+ }
886
+ if (values.changed === true && paths !== void 0) {
887
+ throw new UsageError("guard --changed reads the working tree; do not combine it with --paths.");
888
+ }
889
+ if (values.changed === true && rawDiff !== void 0) {
890
+ throw new UsageError("guard --changed reads the working tree; do not combine it with --diff.");
891
+ }
892
+ }
893
+ const maxChars = parseCountOption(values["max-chars"], "max-chars", 200);
894
+ if (maxChars !== void 0 && maxChars > 1e4) {
895
+ throw new UsageError(`--max-chars must be at most 10000, received ${maxChars}.`);
896
+ }
628
897
  if (command === "impact" || command === "brief") {
629
898
  if (rawDiff !== void 0 && paths !== void 0) {
630
899
  throw new UsageError("impact accepts either --diff <ref> or --paths <a,b>, not both.");
@@ -743,7 +1012,7 @@ function parseCliArgs(argv) {
743
1012
  install: values.install === true,
744
1013
  noInstall: values["no-install"] === true,
745
1014
  target: values.target === void 0 ? void 0 : String(values.target),
746
- cwd: values.cwd === void 0 ? process.cwd() : path2.resolve(String(values.cwd)),
1015
+ cwd: values.cwd === void 0 ? process.cwd() : path3.resolve(String(values.cwd)),
747
1016
  outDir: values["out-dir"] === void 0 ? void 0 : String(values["out-dir"]),
748
1017
  includeMonolith: values["include-monolith"] === true || onlyNamesMonolith === true ? true : void 0,
749
1018
  includeSensitiveFiles: values["include-sensitive-files"] === true ? true : void 0,
@@ -786,6 +1055,9 @@ function parseCliArgs(argv) {
786
1055
  changedSince: values["changed-since"] === void 0 ? void 0 : String(values["changed-since"]),
787
1056
  diff: rawDiff,
788
1057
  paths,
1058
+ hook: rawHook === void 0 ? void 0 : rawHook,
1059
+ changed: values.changed === true,
1060
+ maxChars,
789
1061
  depth,
790
1062
  maxResults,
791
1063
  // `undefined` when the flag was not given, never `false`.
@@ -923,45 +1195,45 @@ function renderImpactMarkdown(report) {
923
1195
  }
924
1196
  function realPathInside(realRoot, candidate) {
925
1197
  const fold = (value) => process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
926
- const relative3 = path2.relative(fold(realRoot), fold(candidate));
927
- return relative3.length === 0 || relative3 !== ".." && !relative3.startsWith(".." + path2.sep) && !path2.isAbsolute(relative3);
1198
+ const relative4 = path3.relative(fold(realRoot), fold(candidate));
1199
+ return relative4.length === 0 || relative4 !== ".." && !relative4.startsWith(".." + path3.sep) && !path3.isAbsolute(relative4);
928
1200
  }
929
- function writeInside(root, relative3, content) {
930
- const target = path2.resolve(root, relative3);
931
- const rel = path2.relative(path2.resolve(root), target);
932
- if (rel.length === 0 || rel === ".." || rel.startsWith(".." + path2.sep) || path2.isAbsolute(rel)) {
1201
+ function writeInside(root, relative4, content) {
1202
+ const target = path3.resolve(root, relative4);
1203
+ const rel = path3.relative(path3.resolve(root), target);
1204
+ if (rel.length === 0 || rel === ".." || rel.startsWith(".." + path3.sep) || path3.isAbsolute(rel)) {
933
1205
  throw new Error("--out must resolve inside the repository.");
934
1206
  }
935
- const parent = path2.dirname(target);
936
- const realRoot = fs2.realpathSync(root);
1207
+ const parent = path3.dirname(target);
1208
+ const realRoot = fs3.realpathSync(root);
937
1209
  let existingAncestor = parent;
938
- while (!fs2.existsSync(existingAncestor)) {
939
- const next = path2.dirname(existingAncestor);
1210
+ while (!fs3.existsSync(existingAncestor)) {
1211
+ const next = path3.dirname(existingAncestor);
940
1212
  if (next === existingAncestor) break;
941
1213
  existingAncestor = next;
942
1214
  }
943
- if (!realPathInside(realRoot, fs2.realpathSync(existingAncestor))) {
1215
+ if (!realPathInside(realRoot, fs3.realpathSync(existingAncestor))) {
944
1216
  throw new Error("--out resolves outside the repository through a link.");
945
1217
  }
946
- fs2.mkdirSync(parent, { recursive: true });
947
- if (!realPathInside(realRoot, fs2.realpathSync(parent))) {
1218
+ fs3.mkdirSync(parent, { recursive: true });
1219
+ if (!realPathInside(realRoot, fs3.realpathSync(parent))) {
948
1220
  throw new Error("--out resolves outside the repository through a link.");
949
1221
  }
950
1222
  try {
951
- const existing = fs2.lstatSync(target);
1223
+ const existing = fs3.lstatSync(target);
952
1224
  if (existing.isSymbolicLink() || !existing.isFile() || existing.nlink > 1) {
953
1225
  throw new Error("--out must be a regular file that is not a symbolic or hard link.");
954
1226
  }
955
1227
  } catch (error) {
956
1228
  if (error.code !== "ENOENT") throw error;
957
1229
  }
958
- const temporary = path2.join(parent, "." + path2.basename(target) + ".tmp-" + process.pid + "-" + Math.random().toString(16).slice(2));
959
- fs2.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx", mode: 384 });
1230
+ const temporary = path3.join(parent, "." + path3.basename(target) + ".tmp-" + process.pid + "-" + Math.random().toString(16).slice(2));
1231
+ fs3.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx", mode: 384 });
960
1232
  try {
961
- fs2.renameSync(temporary, target);
1233
+ fs3.renameSync(temporary, target);
962
1234
  } catch (error) {
963
1235
  try {
964
- fs2.unlinkSync(temporary);
1236
+ fs3.unlinkSync(temporary);
965
1237
  } catch (cleanupError) {
966
1238
  warn("Could not remove temporary file " + temporary + ": " + cleanupError.message);
967
1239
  }
@@ -984,10 +1256,10 @@ function splitList(value) {
984
1256
  return value.split(",").map((entry) => entry.trim()).filter(Boolean);
985
1257
  }
986
1258
  function displayOutPath(cwd, outDir, ...segments) {
987
- const absolute = path2.resolve(cwd, outDir, ...segments);
988
- const relative3 = path2.relative(cwd, absolute);
989
- if (relative3 !== "" && relative3 !== ".." && !relative3.startsWith(`..${path2.sep}`) && !relative3.startsWith("../") && !path2.isAbsolute(relative3)) {
990
- return relative3;
1259
+ const absolute = path3.resolve(cwd, outDir, ...segments);
1260
+ const relative4 = path3.relative(cwd, absolute);
1261
+ if (relative4 !== "" && relative4 !== ".." && !relative4.startsWith(`..${path3.sep}`) && !relative4.startsWith("../") && !path3.isAbsolute(relative4)) {
1262
+ return relative4;
991
1263
  }
992
1264
  return absolute;
993
1265
  }
@@ -996,7 +1268,7 @@ function nextStepHint(cwd, scriptsAddedNow) {
996
1268
  if (!hasScript) {
997
1269
  try {
998
1270
  const parsed = JSON.parse(
999
- stripJsonComments(fs2.readFileSync(path2.join(cwd, "package.json"), "utf8"))
1271
+ stripJsonComments(fs3.readFileSync(path3.join(cwd, "package.json"), "utf8"))
1000
1272
  );
1001
1273
  hasScript = typeof parsed.scripts?.snapshot === "string";
1002
1274
  } catch {
@@ -1004,8 +1276,8 @@ function nextStepHint(cwd, scriptsAddedNow) {
1004
1276
  }
1005
1277
  }
1006
1278
  if (!hasScript) return `npx ${GENERATOR_NAME} generate`;
1007
- const bin = path2.join(cwd, "node_modules", ".bin", "codebase-snapshot");
1008
- const installed = fs2.existsSync(bin) || fs2.existsSync(`${bin}.cmd`);
1279
+ const bin = path3.join(cwd, "node_modules", ".bin", "codebase-snapshot");
1280
+ const installed = fs3.existsSync(bin) || fs3.existsSync(`${bin}.cmd`);
1009
1281
  return installed ? "npm run snapshot" : "npm install && npm run snapshot";
1010
1282
  }
1011
1283
  function presetSummary(init) {
@@ -1041,7 +1313,7 @@ async function runInitCommand(invocation) {
1041
1313
  if (hook) for (const note of hook.notes) info(` ${note}`);
1042
1314
  return 0;
1043
1315
  }
1044
- info(`\u2705 Created ${path2.basename(result.configPath)} (${presetSummary(result)})`);
1316
+ info(`\u2705 Created ${path3.basename(result.configPath)} (${presetSummary(result)})`);
1045
1317
  if (result.scripts.length > 0) info(` Added npm scripts: ${result.scripts.join(", ")}`);
1046
1318
  if (result.dependency.added && result.dependency.range !== null) {
1047
1319
  info(` Added devDependency: ${result.dependency.name} ${result.dependency.range}`);
@@ -1051,10 +1323,10 @@ async function runInitCommand(invocation) {
1051
1323
  }
1052
1324
  if (result.briefWritten) {
1053
1325
  info(
1054
- ` Wrote ${path2.basename(result.briefPath)}: a scaffold for the half of PROMPT.md only you can write. Fill it in, then set brief: ${JSON.stringify(path2.basename(result.briefPath))} in the config to merge it.`
1326
+ ` Wrote ${path3.basename(result.briefPath)}: a scaffold for the half of PROMPT.md only you can write. Fill it in, then set brief: ${JSON.stringify(path3.basename(result.briefPath))} in the config to merge it.`
1055
1327
  );
1056
- } else if (fs2.existsSync(result.briefPath)) {
1057
- info(` Kept ${path2.basename(result.briefPath)}: it already exists, and is never overwritten.`);
1328
+ } else if (fs3.existsSync(result.briefPath)) {
1329
+ info(` Kept ${path3.basename(result.briefPath)}: it already exists, and is never overwritten.`);
1058
1330
  }
1059
1331
  for (const note of result.notes) info(` \u26A0 ${note}`);
1060
1332
  if (hook) for (const note of hook.notes) info(` ${note}`);
@@ -1091,18 +1363,18 @@ function renderHealthText(report) {
1091
1363
  function generatorOrigin(cwd) {
1092
1364
  try {
1093
1365
  const pkg = JSON.parse(
1094
- stripJsonComments(fs2.readFileSync(path2.join(cwd, "package.json"), "utf8"))
1366
+ stripJsonComments(fs3.readFileSync(path3.join(cwd, "package.json"), "utf8"))
1095
1367
  );
1096
1368
  const spec = pkg.dependencies?.["codebase-snapshot"] ?? pkg.devDependencies?.["codebase-snapshot"];
1097
1369
  if (typeof spec === "string") return `project dependency ${spec}`;
1098
1370
  } catch {
1099
1371
  }
1100
1372
  const entry = process.argv[1] ?? "";
1101
- if (entry.includes("_npx") || entry.includes(`${path2.sep}npx${path2.sep}`)) return "via npx";
1373
+ if (entry.includes("_npx") || entry.includes(`${path3.sep}npx${path3.sep}`)) return "via npx";
1102
1374
  return "global or direct install";
1103
1375
  }
1104
1376
  function detectPackageManager(cwd) {
1105
- const has = (name) => fs2.existsSync(path2.join(cwd, name));
1377
+ const has = (name) => fs3.existsSync(path3.join(cwd, name));
1106
1378
  if (has("bun.lockb") || has("bun.lock")) return { name: "bun", command: "bun", args: ["install"] };
1107
1379
  if (has("pnpm-lock.yaml")) return { name: "pnpm", command: "pnpm", args: ["install"] };
1108
1380
  if (has("yarn.lock")) return { name: "yarn", command: "yarn", args: ["install"] };
@@ -1219,7 +1491,7 @@ async function runSetupCommand(invocation, options = {}) {
1219
1491
  }
1220
1492
  info("\n\u{1F9EA} Dry run \u2014 setup would:");
1221
1493
  info(
1222
- ` 1. ${init.reused ? `keep ${path2.basename(keptConfigPath)}` : `write ${path2.basename(keptConfigPath)} (preset: ${appliedPreset})`}`
1494
+ ` 1. ${init.reused ? `keep ${path3.basename(keptConfigPath)}` : `write ${path3.basename(keptConfigPath)} (preset: ${appliedPreset})`}`
1223
1495
  );
1224
1496
  info(" 2. add the npm scripts, the devDependency and the .gitignore entries");
1225
1497
  if (manager !== null) info(` 3. install with ${manager}`);
@@ -1232,9 +1504,9 @@ async function runSetupCommand(invocation, options = {}) {
1232
1504
  if (invocation.format !== "json") {
1233
1505
  if (!interactive) info(`\u{1F680} Setup for: ${invocation.cwd}`);
1234
1506
  if (init.reused) {
1235
- info(`\u267B Keeping ${path2.basename(keptConfigPath)}`);
1507
+ info(`\u267B Keeping ${path3.basename(keptConfigPath)}`);
1236
1508
  } else {
1237
- info(`\u2705 Created ${path2.basename(keptConfigPath)} (${presetSummary(init)})`);
1509
+ info(`\u2705 Created ${path3.basename(keptConfigPath)} (${presetSummary(init)})`);
1238
1510
  }
1239
1511
  if (init.scripts.length > 0) info(` Added npm scripts: ${init.scripts.join(", ")}`);
1240
1512
  if (init.dependency.added && init.dependency.range !== null) {
@@ -1245,7 +1517,7 @@ async function runSetupCommand(invocation, options = {}) {
1245
1517
  }
1246
1518
  if (init.briefWritten) {
1247
1519
  info(
1248
- ` Wrote ${path2.basename(init.briefPath)}: a scaffold for the half of PROMPT.md only you can write. Fill it in, then set brief: ${JSON.stringify(path2.basename(init.briefPath))} in the config to merge it.`
1520
+ ` Wrote ${path3.basename(init.briefPath)}: a scaffold for the half of PROMPT.md only you can write. Fill it in, then set brief: ${JSON.stringify(path3.basename(init.briefPath))} in the config to merge it.`
1249
1521
  );
1250
1522
  }
1251
1523
  if (hook) for (const note of hook.notes) info(` ${note}`);
@@ -1253,7 +1525,7 @@ async function runSetupCommand(invocation, options = {}) {
1253
1525
  info(` \u26A0 --preset ${invocation.preset} was not applied: the existing config is kept.`);
1254
1526
  }
1255
1527
  }
1256
- const hasManifest = fs2.existsSync(path2.join(invocation.cwd, "package.json"));
1528
+ const hasManifest = fs3.existsSync(path3.join(invocation.cwd, "package.json"));
1257
1529
  let install = null;
1258
1530
  if (invocation.noInstall) {
1259
1531
  if (invocation.format !== "json") info(" Skipped the install (--no-install)");
@@ -1418,7 +1690,7 @@ function runSkillCommand(invocation) {
1418
1690
  }
1419
1691
  info(`\u2705 Agent skill installed (${SKILL_NAME}):`);
1420
1692
  for (const item of result.written) {
1421
- const shown = path2.relative(invocation.cwd, item.path) || item.path;
1693
+ const shown = path3.relative(invocation.cwd, item.path) || item.path;
1422
1694
  info(` - ${item.action.padEnd(9)} ${shown}`);
1423
1695
  }
1424
1696
  if (result.gitignored.length > 0) {
@@ -1427,7 +1699,7 @@ function runSkillCommand(invocation) {
1427
1699
  info(" These files are this tool's own documentation, so they stay out of git.");
1428
1700
  }
1429
1701
  if (result.mcp !== void 0) {
1430
- const shown = path2.relative(invocation.cwd, result.mcp.path) || result.mcp.path;
1702
+ const shown = path3.relative(invocation.cwd, result.mcp.path) || result.mcp.path;
1431
1703
  info(` - ${result.mcp.action.padEnd(9)} ${shown} (codebase-snapshot MCP entry)`);
1432
1704
  }
1433
1705
  for (const note of result.notes) info(` \u26A0 ${note}`);
@@ -1498,6 +1770,85 @@ function guardClosedStdout() {
1498
1770
  throw error;
1499
1771
  });
1500
1772
  }
1773
+ async function readStdin(limit = 1024 * 1024) {
1774
+ const chunks = [];
1775
+ let size = 0;
1776
+ for await (const chunk of process.stdin) {
1777
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
1778
+ size += buffer.length;
1779
+ if (size > limit) throw new Error("the hook payload exceeds 1 MiB");
1780
+ chunks.push(buffer);
1781
+ }
1782
+ return Buffer.concat(chunks).toString("utf8");
1783
+ }
1784
+ function guardHookSkipped(message) {
1785
+ warn("guard: " + message + " (hook skipped)");
1786
+ process.stdout.write("{}\n");
1787
+ return 0;
1788
+ }
1789
+ async function runGuardCommand(invocation, resolved) {
1790
+ const client = invocation.hook;
1791
+ try {
1792
+ let paths = invocation.paths;
1793
+ let event = "PostToolUse";
1794
+ if (client !== void 0) {
1795
+ const parsed = parseGuardHookInput(client, await readStdin(), resolved.cwd);
1796
+ paths = parsed.paths;
1797
+ event = parsed.event;
1798
+ if (paths.length === 0) {
1799
+ process.stdout.write("{}\n");
1800
+ return 0;
1801
+ }
1802
+ }
1803
+ const changes = resolveImpactChanges(resolved.cwd, {
1804
+ ...paths === void 0 ? { diff: invocation.diff ?? "HEAD" } : { paths }
1805
+ });
1806
+ const manifestPath = path3.resolve(resolved.cwd, resolved.outDir, "manifest.json");
1807
+ let manifest;
1808
+ let trust;
1809
+ if (invocation.noLive) {
1810
+ if (!fs3.existsSync(manifestPath)) {
1811
+ if (client !== void 0) {
1812
+ warn("guard: no snapshot manifest; the hook was skipped.");
1813
+ process.stdout.write("{}\n");
1814
+ return 0;
1815
+ }
1816
+ return fail(
1817
+ invocation.format,
1818
+ "Manifest not found at " + manifestPath + ". Run generate first, or omit --no-live."
1819
+ );
1820
+ }
1821
+ manifest = loadManifest(manifestPath);
1822
+ } else {
1823
+ const live = await buildLiveIndex(resolved, { useDiskCache: !invocation.noCache });
1824
+ manifest = live.manifest;
1825
+ trust = live.trust;
1826
+ }
1827
+ const impact = computeImpact({
1828
+ manifest,
1829
+ cwd: resolved.cwd,
1830
+ changes,
1831
+ manifestPath,
1832
+ ...trust === void 0 ? {} : { trust },
1833
+ ...invocation.depth === void 0 ? {} : { depth: invocation.depth },
1834
+ ...invocation.maxResults === void 0 ? {} : { maxResults: invocation.maxResults }
1835
+ });
1836
+ const report = buildGuardReport(impact);
1837
+ if (client !== void 0) {
1838
+ process.stdout.write(renderGuardHook(report, client, event, invocation.maxChars ?? 1200) + "\n");
1839
+ return 0;
1840
+ }
1841
+ emit(invocation.format, report, () => info(renderGuardText(report)));
1842
+ return 0;
1843
+ } catch (err) {
1844
+ if (client !== void 0) {
1845
+ warn("guard: " + err.message + " (hook skipped)");
1846
+ process.stdout.write("{}\n");
1847
+ return 0;
1848
+ }
1849
+ return fail(invocation.format, err.message);
1850
+ }
1851
+ }
1501
1852
  async function main(argv = process.argv.slice(2)) {
1502
1853
  guardClosedStdout();
1503
1854
  const pending = process.stdout.isTTY === true && shouldCheck(argv, process.env) ? checkForUpdate({ current: GENERATOR_VERSION, cacheFile: cacheFilePath() }) : null;
@@ -1585,7 +1936,7 @@ ${USAGE}
1585
1936
  }
1586
1937
  if (invocation.command === "serve") {
1587
1938
  const server = await startWebServer({
1588
- cwd: path2.resolve(invocation.cwd),
1939
+ cwd: path3.resolve(invocation.cwd),
1589
1940
  ...invocation.host === void 0 ? {} : { host: invocation.host },
1590
1941
  ...invocation.port === void 0 ? {} : { port: invocation.port },
1591
1942
  ...tokenOption,
@@ -1600,9 +1951,9 @@ ${USAGE}
1600
1951
  } else {
1601
1952
  warn(" WARNING: --no-auth is on. Any page on this machine can read the repository.");
1602
1953
  }
1603
- await new Promise((resolve2) => {
1954
+ await new Promise((resolve3) => {
1604
1955
  const stop = () => {
1605
- void server.close().then(resolve2);
1956
+ void server.close().then(resolve3);
1606
1957
  };
1607
1958
  process.once("SIGINT", stop);
1608
1959
  process.once("SIGTERM", stop);
@@ -1612,7 +1963,7 @@ ${USAGE}
1612
1963
  if (invocation.command === "mcp") {
1613
1964
  if (invocation.http === true) {
1614
1965
  const transport = await startHttpTransport({
1615
- cwd: path2.resolve(invocation.cwd),
1966
+ cwd: path3.resolve(invocation.cwd),
1616
1967
  noConfig: invocation.noConfig,
1617
1968
  ...invocation.host === void 0 ? {} : { host: invocation.host },
1618
1969
  ...invocation.port === void 0 ? {} : { port: invocation.port },
@@ -1628,9 +1979,9 @@ ${USAGE}
1628
1979
  } else {
1629
1980
  warn(" WARNING: --no-auth is on. Any page on this machine can read the repository.");
1630
1981
  }
1631
- await new Promise((resolve2) => {
1982
+ await new Promise((resolve3) => {
1632
1983
  const stop = () => {
1633
- void transport.close().then(resolve2);
1984
+ void transport.close().then(resolve3);
1634
1985
  };
1635
1986
  process.once("SIGINT", stop);
1636
1987
  process.once("SIGTERM", stop);
@@ -1638,7 +1989,7 @@ ${USAGE}
1638
1989
  return 0;
1639
1990
  }
1640
1991
  return await runStdioServer({
1641
- cwd: path2.resolve(invocation.cwd),
1992
+ cwd: path3.resolve(invocation.cwd),
1642
1993
  noConfig: invocation.noConfig
1643
1994
  });
1644
1995
  }
@@ -1668,8 +2019,15 @@ ${USAGE}
1668
2019
  log: (line) => info(" " + line)
1669
2020
  });
1670
2021
  sourceProvenance = clone.provenance;
1671
- const outDir = path2.resolve(invocation.cwd, invocation.outDir ?? "snapshot");
1672
- invocation = { ...invocation, cwd: clone.directory, outDir, noConfig: true };
2022
+ const outDir = path3.resolve(invocation.cwd, invocation.outDir ?? "snapshot");
2023
+ const delta = invocation.delta === void 0 ? void 0 : path3.resolve(invocation.cwd, invocation.delta);
2024
+ invocation = {
2025
+ ...invocation,
2026
+ cwd: clone.directory,
2027
+ outDir,
2028
+ ...delta === void 0 ? {} : { delta },
2029
+ noConfig: true
2030
+ };
1673
2031
  info(
1674
2032
  " Source: " + parsed.source.owner + "/" + parsed.source.repo + "@" + clone.commit.slice(0, 12) + " (fetched " + clone.provenance.fetchedAt + ")"
1675
2033
  );
@@ -1679,7 +2037,7 @@ ${USAGE}
1679
2037
  const directory = clone.directory;
1680
2038
  process.once("exit", () => {
1681
2039
  try {
1682
- fs2.rmSync(directory, { recursive: true, force: true });
2040
+ fs3.rmSync(directory, { recursive: true, force: true });
1683
2041
  } catch {
1684
2042
  }
1685
2043
  });
@@ -1688,17 +2046,39 @@ ${USAGE}
1688
2046
  return fail(invocation.format, "Remote fetch failed: " + error.message);
1689
2047
  }
1690
2048
  }
2049
+ const guardHook = invocation.command === "guard" && invocation.hook !== void 0;
1691
2050
  const skipConfig = invocation.noConfig || invocation.command === "diff";
1692
- const loaded = skipConfig ? { config: null, warnings: [], errors: [], file: null } : await loadConfigFileDetailed(invocation.cwd);
2051
+ let loaded;
2052
+ if (skipConfig) {
2053
+ loaded = { config: null, warnings: [], errors: [], file: null };
2054
+ } else {
2055
+ try {
2056
+ loaded = await loadConfigFileDetailed(
2057
+ invocation.cwd,
2058
+ guardHook ? { allowExecutableConfig: false } : {}
2059
+ );
2060
+ } catch (error) {
2061
+ if (guardHook) return guardHookSkipped(error.message);
2062
+ return fail(invocation.format, error.message);
2063
+ }
2064
+ }
1693
2065
  if (invocation.noConfig) info("\u2699 --no-config: using built-in defaults, config file ignored");
1694
2066
  if (loaded.errors.length > 0) {
2067
+ if (guardHook) return guardHookSkipped(loaded.errors.join("; "));
1695
2068
  return fail(
1696
2069
  invocation.format,
1697
2070
  `The config file could not be read: ${loaded.errors.join("; ")}. Fix it, or delete it to use the defaults.`
1698
2071
  );
1699
2072
  }
2073
+ if (guardHook) {
2074
+ try {
2075
+ assertServerSafeConfig(loaded.config, loaded.file ?? invocation.cwd);
2076
+ } catch (error) {
2077
+ return guardHookSkipped(error.message);
2078
+ }
2079
+ }
1700
2080
  for (const warning of loaded.warnings) warn(`\u26A0 Config: ${warning}`);
1701
- if (loaded.file) info(`\u2699 Using config ${path2.relative(process.cwd(), loaded.file) || loaded.file}`);
2081
+ if (loaded.file) info(`\u2699 Using config ${path3.relative(process.cwd(), loaded.file) || loaded.file}`);
1702
2082
  let resolved;
1703
2083
  try {
1704
2084
  resolved = resolveConfig(
@@ -1707,8 +2087,12 @@ ${USAGE}
1707
2087
  invocation.cwd
1708
2088
  );
1709
2089
  } catch (err) {
2090
+ if (guardHook) return guardHookSkipped(err.message);
1710
2091
  return fail(invocation.format, err.message);
1711
2092
  }
2093
+ if (invocation.command === "guard") {
2094
+ return await runGuardCommand(invocation, resolved);
2095
+ }
1712
2096
  if (invocation.command === "validate") {
1713
2097
  const result = validateSnapshot(resolved);
1714
2098
  emit(invocation.format, result, () => renderValidateText(result));
@@ -1716,9 +2100,9 @@ ${USAGE}
1716
2100
  }
1717
2101
  if (invocation.command === "health") {
1718
2102
  if (invocation.allMembers === true) {
1719
- const outRoot = path2.resolve(resolved.cwd, resolved.outDir);
1720
- const indexPath = path2.join(outRoot, "WORKSPACE.json");
1721
- if (!fs2.existsSync(indexPath)) {
2103
+ const outRoot = path3.resolve(resolved.cwd, resolved.outDir);
2104
+ const indexPath = path3.join(outRoot, "WORKSPACE.json");
2105
+ if (!fs3.existsSync(indexPath)) {
1722
2106
  return fail(
1723
2107
  invocation.format,
1724
2108
  `No workspace index at ${indexPath}. Run generate --workspace <a,b> first, or drop --all-members.`
@@ -1736,15 +2120,15 @@ ${USAGE}
1736
2120
  }
1737
2121
  const rows = [];
1738
2122
  const insidePath = (parent, child) => {
1739
- const relative3 = path2.relative(parent, child);
1740
- return relative3 === "" || relative3 !== ".." && !relative3.startsWith(`..${path2.sep}`) && !relative3.startsWith("../") && !path2.isAbsolute(relative3);
2123
+ const relative4 = path3.relative(parent, child);
2124
+ return relative4 === "" || relative4 !== ".." && !relative4.startsWith(`..${path3.sep}`) && !relative4.startsWith("../") && !path3.isAbsolute(relative4);
1741
2125
  };
1742
2126
  for (const member of index.members ?? []) {
1743
2127
  const name = member.name ?? "?";
1744
- const snapshotDir2 = path2.resolve(outRoot, name);
2128
+ const snapshotDir2 = path3.resolve(outRoot, name);
1745
2129
  const repoPath = member.path ?? name;
1746
- const repoDir = path2.resolve(resolved.cwd, repoPath);
1747
- if (name.length === 0 || path2.isAbsolute(name) || name.split(/[\\/]/).includes("..") || !insidePath(outRoot, snapshotDir2) || path2.isAbsolute(repoPath) || repoPath.split(/[\\/]/).includes("..") || !insidePath(resolved.cwd, repoDir)) {
2130
+ const repoDir = path3.resolve(resolved.cwd, repoPath);
2131
+ if (name.length === 0 || path3.isAbsolute(name) || name.split(/[\\/]/).includes("..") || !insidePath(outRoot, snapshotDir2) || path3.isAbsolute(repoPath) || repoPath.split(/[\\/]/).includes("..") || !insidePath(resolved.cwd, repoDir)) {
1748
2132
  rows.push({
1749
2133
  name,
1750
2134
  score: 0,
@@ -1757,10 +2141,10 @@ ${USAGE}
1757
2141
  let canonicalSnapshot = snapshotDir2;
1758
2142
  let canonicalRepo = repoDir;
1759
2143
  try {
1760
- const outRootReal = fs2.realpathSync(outRoot);
1761
- const cwdReal = fs2.realpathSync(resolved.cwd);
1762
- canonicalSnapshot = fs2.realpathSync(snapshotDir2);
1763
- canonicalRepo = fs2.existsSync(repoDir) ? fs2.realpathSync(repoDir) : repoDir;
2144
+ const outRootReal = fs3.realpathSync(outRoot);
2145
+ const cwdReal = fs3.realpathSync(resolved.cwd);
2146
+ canonicalSnapshot = fs3.realpathSync(snapshotDir2);
2147
+ canonicalRepo = fs3.existsSync(repoDir) ? fs3.realpathSync(repoDir) : repoDir;
1764
2148
  if (!insidePath(outRootReal, canonicalSnapshot) || !insidePath(cwdReal, canonicalRepo)) {
1765
2149
  rows.push({
1766
2150
  name,
@@ -1775,7 +2159,7 @@ ${USAGE}
1775
2159
  canonicalSnapshot = snapshotDir2;
1776
2160
  canonicalRepo = repoDir;
1777
2161
  }
1778
- if (!fs2.existsSync(path2.join(snapshotDir2, "manifest.json"))) {
2162
+ if (!fs3.existsSync(path3.join(snapshotDir2, "manifest.json"))) {
1779
2163
  rows.push({ name, score: 0, counts: { pass: 0, warn: 0, fail: 1 }, failed: [], error: "no snapshot at " + snapshotDir2 });
1780
2164
  continue;
1781
2165
  }
@@ -1784,8 +2168,8 @@ ${USAGE}
1784
2168
  const memberLoaded = await loadConfigFileDetailed(canonicalRepo, {
1785
2169
  allowExecutableConfig: false
1786
2170
  });
1787
- if (memberLoaded.errors.length === 0) {
1788
- memberSecretRules = resolveConfig(memberLoaded.config, void 0, repoDir).customSecretRules ?? [];
2171
+ if (memberLoaded.errors.length === 0 && memberLoaded.config !== null) {
2172
+ memberSecretRules = resolveConfig(memberLoaded.config, { cwd: repoDir }, repoDir).customSecretRules ?? [];
1789
2173
  }
1790
2174
  } catch {
1791
2175
  }
@@ -1822,7 +2206,7 @@ ${USAGE}
1822
2206
  if (invocation.strict === true && totals.warn > 0) return 1;
1823
2207
  return 0;
1824
2208
  }
1825
- const snapshotDir = path2.resolve(resolved.cwd, resolved.outDir);
2209
+ const snapshotDir = path3.resolve(resolved.cwd, resolved.outDir);
1826
2210
  const report = auditSnapshot({
1827
2211
  snapshotDir,
1828
2212
  repoDir: resolved.cwd,
@@ -1835,13 +2219,13 @@ ${USAGE}
1835
2219
  return 0;
1836
2220
  }
1837
2221
  if (invocation.command === "report") {
1838
- const manifestPath = path2.resolve(resolved.cwd, resolved.outDir, "manifest.json");
1839
- if (!fs2.existsSync(manifestPath)) {
2222
+ const manifestPath = path3.resolve(resolved.cwd, resolved.outDir, "manifest.json");
2223
+ if (!fs3.existsSync(manifestPath)) {
1840
2224
  return fail(invocation.format, `Manifest not found at ${manifestPath}. Run generate first.`);
1841
2225
  }
1842
2226
  let manifest;
1843
2227
  try {
1844
- manifest = JSON.parse(fs2.readFileSync(manifestPath, "utf8"));
2228
+ manifest = JSON.parse(fs3.readFileSync(manifestPath, "utf8"));
1845
2229
  } catch (err) {
1846
2230
  return fail(invocation.format, `Could not read ${manifestPath}: ${err.message}`);
1847
2231
  }
@@ -1898,7 +2282,7 @@ ${USAGE}
1898
2282
  if (manifest.delta !== void 0) {
1899
2283
  const delta = manifest.delta;
1900
2284
  info("\n Selection (delta):");
1901
- info(` - Against: ${path2.basename(delta.base.path)} (${delta.base.fingerprint.slice(0, 12)})`);
2285
+ info(` - Against: ${path3.basename(delta.base.path)} (${delta.base.fingerprint.slice(0, 12)})`);
1902
2286
  info(
1903
2287
  ` - Changed: ${delta.changed.length} changed, ${delta.added.length} added, ${delta.removed.length} removed, ${delta.unchanged.length} unchanged`
1904
2288
  );
@@ -1908,11 +2292,11 @@ ${USAGE}
1908
2292
  }
1909
2293
  if (invocation.command === "impact") {
1910
2294
  try {
1911
- const manifestPath = path2.resolve(resolved.cwd, resolved.outDir, "manifest.json");
2295
+ const manifestPath = path3.resolve(resolved.cwd, resolved.outDir, "manifest.json");
1912
2296
  let manifest;
1913
2297
  let live = null;
1914
2298
  if (invocation.noLive) {
1915
- if (!fs2.existsSync(manifestPath)) {
2299
+ if (!fs3.existsSync(manifestPath)) {
1916
2300
  return fail(invocation.format, "Manifest not found at " + manifestPath + ". Run generate first, or omit --no-live.");
1917
2301
  }
1918
2302
  manifest = loadManifest(manifestPath);
@@ -2030,11 +2414,11 @@ ${USAGE}
2030
2414
  }
2031
2415
  if (invocation.command === "brief") {
2032
2416
  try {
2033
- const manifestPath = path2.resolve(resolved.cwd, resolved.outDir, "manifest.json");
2417
+ const manifestPath = path3.resolve(resolved.cwd, resolved.outDir, "manifest.json");
2034
2418
  let manifest;
2035
2419
  let live = null;
2036
2420
  if (invocation.noLive) {
2037
- if (!fs2.existsSync(manifestPath)) {
2421
+ if (!fs3.existsSync(manifestPath)) {
2038
2422
  return fail(invocation.format, "Manifest not found at " + manifestPath + ". Run generate first, or omit --no-live.");
2039
2423
  }
2040
2424
  manifest = loadManifest(manifestPath);
@@ -2054,7 +2438,7 @@ ${USAGE}
2054
2438
  if (invocation.diff !== void 0 || question === void 0 && invocation.paths === void 0) {
2055
2439
  const ref = invocation.diff ?? "HEAD";
2056
2440
  const resolvedBase = resolveDiffBase(resolved.cwd, ref);
2057
- const diffArgs = resolvedBase === null ? ["-c", "core.quotepath=false", "-c", "diff.noprefix=false", "-c", "diff.mnemonicPrefix=false", "-c", "core.fsmonitor=false", "diff", "--cached", "--no-color", "--no-ext-diff", "--no-textconv", "-U3"] : ["-c", "core.quotepath=false", "-c", "diff.noprefix=false", "-c", "diff.mnemonicPrefix=false", "-c", "core.fsmonitor=false", "diff", "--no-color", "--no-ext-diff", "--no-textconv", "-U3", resolvedBase, "--"];
2441
+ const diffArgs = resolvedBase === null ? ["-c", "core.quotepath=false", "-c", "diff.noprefix=false", "-c", "diff.mnemonicPrefix=false", "-c", "core.fsmonitor=false", "diff", "--cached", "--no-color", "--no-ext-diff", "--no-textconv", "--relative", "-U3"] : ["-c", "core.quotepath=false", "-c", "diff.noprefix=false", "-c", "diff.mnemonicPrefix=false", "-c", "core.fsmonitor=false", "diff", "--no-color", "--no-ext-diff", "--no-textconv", "--relative", "-U3", resolvedBase, "--"];
2058
2442
  const result = spawnSync("git", diffArgs, {
2059
2443
  cwd: resolved.cwd,
2060
2444
  encoding: "utf8",
@@ -2064,6 +2448,17 @@ ${USAGE}
2064
2448
  if (result.status === 0) {
2065
2449
  const reportExcludes = [...resolved.excludePatterns, ...resolved.presetExclude];
2066
2450
  const filtered = filterAndRedactDiff(result.stdout, resolved.secretRules, {
2451
+ cwd: resolved.cwd,
2452
+ // The removed side of a hunk is not in the working tree; read it at the same ref so a
2453
+ // partially changed PEM block or block scalar is masked on both sides.
2454
+ readOld: (relativePath) => {
2455
+ const shown = spawnSync(
2456
+ "git",
2457
+ ["-c", "core.quotepath=false", "show", ref + ":" + relativePath],
2458
+ { cwd: resolved.cwd, encoding: "utf8", shell: false, maxBuffer: 64 * 1024 * 1024 }
2459
+ );
2460
+ return shown.status === 0 ? shown.stdout : null;
2461
+ },
2067
2462
  // The diff report generated by `generate` applies the repository's include/exclude
2068
2463
  // rules; `brief --diff` used to pass only the secret rules, so a tracked file the
2069
2464
  // config excluded still appeared in the review pack.
@@ -2071,7 +2466,7 @@ ${USAGE}
2071
2466
  });
2072
2467
  diffText = filtered.text;
2073
2468
  if (filtered.omittedSensitive > 0) {
2074
- diffNotes.push(filtered.omittedSensitive + " sensitive file section(s) were omitted from the diff.");
2469
+ diffNotes.push(filtered.omittedSensitive + " sensitive or excluded file section(s) were omitted from the diff.");
2075
2470
  }
2076
2471
  if (filtered.omittedUnparseable > 0) {
2077
2472
  diffNotes.push(filtered.omittedUnparseable + " unparseable file section(s) were omitted from the diff.");
@@ -2086,10 +2481,10 @@ ${USAGE}
2086
2481
  if (isSensitivePath(relativePath)) return null;
2087
2482
  const file = manifest.files.find((candidate) => candidate.relativePath === relativePath);
2088
2483
  if (file === void 0) return null;
2089
- const snapshotDir = path2.resolve(resolved.cwd, resolved.outDir);
2484
+ const snapshotDir = path3.resolve(resolved.cwd, resolved.outDir);
2090
2485
  const read = readConfinedText(
2091
2486
  snapshotDir,
2092
- path2.posix.join("parts", file.part),
2487
+ path3.posix.join("parts", file.part),
2093
2488
  16 * 1024 * 1024
2094
2489
  );
2095
2490
  if (!read.ok) return null;
@@ -2100,7 +2495,7 @@ ${USAGE}
2100
2495
  manifest,
2101
2496
  ...question === void 0 ? {} : { question },
2102
2497
  ...changes === void 0 ? {} : { changes },
2103
- ...diffText === void 0 ? {} : { diff: diffText },
2498
+ ...diffText === void 0 ? {} : { diff: diffText, diffIsRedacted: true },
2104
2499
  ...diffNotes.length === 0 ? {} : { diffNotes },
2105
2500
  readBody,
2106
2501
  secretRules: resolved.secretRules,
@@ -2114,7 +2509,7 @@ ${USAGE}
2114
2509
  });
2115
2510
  if (invocation.out !== void 0) {
2116
2511
  const written = writeInside(resolved.cwd, invocation.out, brief.markdown);
2117
- info("Wrote " + path2.relative(resolved.cwd, written));
2512
+ info("Wrote " + path3.relative(resolved.cwd, written));
2118
2513
  } else if (invocation.format !== "json") {
2119
2514
  process.stdout.write(brief.markdown);
2120
2515
  }
@@ -2190,10 +2585,10 @@ ${USAGE}
2190
2585
  "--workspace writes one snapshot per member; --remote, --delta, --slice, --budget-tokens and --sign do not combine with it."
2191
2586
  );
2192
2587
  }
2193
- const outRoot = path2.resolve(invocation.cwd, invocation.outDir ?? "snapshot");
2194
- const workspaceCwd = path2.resolve(invocation.cwd);
2195
- const outRootRelative = path2.relative(outRoot, workspaceCwd);
2196
- if (outRootRelative === "" || outRootRelative !== ".." && !outRootRelative.startsWith(`..${path2.sep}`) && !outRootRelative.startsWith("../") && !path2.isAbsolute(outRootRelative)) {
2588
+ const outRoot = path3.resolve(invocation.cwd, invocation.outDir ?? "snapshot");
2589
+ const workspaceCwd = path3.resolve(invocation.cwd);
2590
+ const outRootRelative = path3.relative(outRoot, workspaceCwd);
2591
+ if (outRootRelative === "" || outRootRelative !== ".." && !outRootRelative.startsWith(`..${path3.sep}`) && !outRootRelative.startsWith("../") && !path3.isAbsolute(outRootRelative)) {
2197
2592
  return fail(
2198
2593
  invocation.format,
2199
2594
  `--workspace refuses --out-dir ${outRoot}: it is the working directory or one of its ancestors.`
@@ -2201,8 +2596,8 @@ ${USAGE}
2201
2596
  }
2202
2597
  const plannedNames = /* @__PURE__ */ new Map();
2203
2598
  for (const member of members) {
2204
- const directory = path2.resolve(invocation.cwd, member);
2205
- const name = path2.basename(directory);
2599
+ const directory = path3.resolve(invocation.cwd, member);
2600
+ const name = path3.basename(directory);
2206
2601
  const previous = plannedNames.get(name);
2207
2602
  if (previous !== void 0) {
2208
2603
  return fail(
@@ -2215,11 +2610,11 @@ ${USAGE}
2215
2610
  const records = [];
2216
2611
  let failed = 0;
2217
2612
  for (const member of members) {
2218
- const directory = path2.resolve(invocation.cwd, member);
2219
- const name = path2.basename(directory);
2613
+ const directory = path3.resolve(invocation.cwd, member);
2614
+ const name = path3.basename(directory);
2220
2615
  let stat;
2221
2616
  try {
2222
- stat = fs2.statSync(directory);
2617
+ stat = fs3.statSync(directory);
2223
2618
  } catch {
2224
2619
  warn("\u26A0 Workspace member missing: " + member);
2225
2620
  failed += 1;
@@ -2236,7 +2631,7 @@ ${USAGE}
2236
2631
  {
2237
2632
  ...generateCliOptions(invocation),
2238
2633
  cwd: directory,
2239
- outDir: path2.join(outRoot, name)
2634
+ outDir: path3.join(outRoot, name)
2240
2635
  },
2241
2636
  directory
2242
2637
  );
@@ -2256,17 +2651,17 @@ ${USAGE}
2256
2651
  failed += 1;
2257
2652
  }
2258
2653
  }
2259
- if (!invocation.dryRun) fs2.mkdirSync(outRoot, { recursive: true });
2654
+ if (!invocation.dryRun) fs3.mkdirSync(outRoot, { recursive: true });
2260
2655
  const links = [];
2261
2656
  for (const record of records) {
2262
2657
  const counts = /* @__PURE__ */ new Map();
2263
2658
  for (const entry of record.imports) {
2264
2659
  for (const specifier of entry.imports) {
2265
2660
  if (!specifier.startsWith(".")) continue;
2266
- const resolved2 = path2.resolve(record.path, path2.dirname(entry.path), specifier);
2661
+ const resolved2 = path3.resolve(record.path, path3.dirname(entry.path), specifier);
2267
2662
  for (const other of records) {
2268
2663
  if (other === record) continue;
2269
- const prefix = other.path + path2.sep;
2664
+ const prefix = other.path + path3.sep;
2270
2665
  if (!resolved2.startsWith(prefix) && resolved2 !== other.path) continue;
2271
2666
  const bucket = counts.get(other.name) ?? { count: 0, examples: [] };
2272
2667
  bucket.count += 1;
@@ -2291,14 +2686,14 @@ ${USAGE}
2291
2686
  // Store the member path relative to the workspace cwd, as manifest paths already are.
2292
2687
  members: records.map(({ imports: _imports, ...rest }) => ({
2293
2688
  ...rest,
2294
- path: path2.relative(workspaceCwd, rest.path).split(path2.sep).join("/") || "."
2689
+ path: path3.relative(workspaceCwd, rest.path).split(path3.sep).join("/") || "."
2295
2690
  })),
2296
2691
  links
2297
2692
  };
2298
2693
  if (!invocation.dryRun) {
2299
- const workspacePath = path2.join(outRoot, "WORKSPACE.json");
2694
+ const workspacePath = path3.join(outRoot, "WORKSPACE.json");
2300
2695
  try {
2301
- const stats = fs2.lstatSync(workspacePath);
2696
+ const stats = fs3.lstatSync(workspacePath);
2302
2697
  if (stats.isSymbolicLink() || !stats.isFile()) {
2303
2698
  return fail(invocation.format, `${workspacePath} is not a regular file; refusing to replace it.`);
2304
2699
  }
@@ -2307,11 +2702,11 @@ ${USAGE}
2307
2702
  }
2308
2703
  const tempPath = `${workspacePath}.${process.pid}.${Date.now()}.tmp`;
2309
2704
  try {
2310
- fs2.writeFileSync(tempPath, JSON.stringify(document, null, 2) + "\n", "utf8");
2311
- fs2.renameSync(tempPath, workspacePath);
2705
+ fs3.writeFileSync(tempPath, JSON.stringify(document, null, 2) + "\n", "utf8");
2706
+ fs3.renameSync(tempPath, workspacePath);
2312
2707
  } catch (error) {
2313
2708
  try {
2314
- fs2.rmSync(tempPath, { force: true });
2709
+ fs3.rmSync(tempPath, { force: true });
2315
2710
  } catch {
2316
2711
  }
2317
2712
  throw error;
@@ -2339,14 +2734,14 @@ ${USAGE}
2339
2734
  try {
2340
2735
  let deltaBase;
2341
2736
  if (invocation.delta !== void 0) {
2342
- const basePath = path2.resolve(invocation.cwd, invocation.delta);
2343
- const manifestPath = fs2.existsSync(basePath) && fs2.statSync(basePath).isDirectory() ? path2.join(basePath, "manifest.json") : basePath;
2344
- if (!fs2.existsSync(manifestPath)) {
2737
+ const basePath = path3.resolve(invocation.cwd, invocation.delta);
2738
+ const manifestPath = fs3.existsSync(basePath) && fs3.statSync(basePath).isDirectory() ? path3.join(basePath, "manifest.json") : basePath;
2739
+ if (!fs3.existsSync(manifestPath)) {
2345
2740
  return fail(invocation.format, "No manifest at " + manifestPath + ". Point --delta at a snapshot directory or its manifest.json.");
2346
2741
  }
2347
2742
  let base;
2348
2743
  try {
2349
- base = JSON.parse(fs2.readFileSync(manifestPath, "utf8"));
2744
+ base = JSON.parse(fs3.readFileSync(manifestPath, "utf8"));
2350
2745
  } catch (error) {
2351
2746
  return fail(invocation.format, "Could not read " + manifestPath + ": " + error.message);
2352
2747
  }
@@ -2354,8 +2749,8 @@ ${USAGE}
2354
2749
  if (shape !== null) {
2355
2750
  return fail(invocation.format, manifestPath + " is not a snapshot manifest: " + shape);
2356
2751
  }
2357
- const relativeBase = path2.relative(invocation.cwd, manifestPath).split(path2.sep).join("/");
2358
- const recordedBase = relativeBase === "" || relativeBase === ".." || relativeBase.startsWith(`..${path2.sep}`) || relativeBase.startsWith("../") || path2.isAbsolute(relativeBase) ? path2.basename(manifestPath) : relativeBase;
2752
+ const relativeBase = path3.relative(invocation.cwd, manifestPath).split(path3.sep).join("/");
2753
+ const recordedBase = relativeBase === "" || relativeBase === ".." || relativeBase.startsWith(`..${path3.sep}`) || relativeBase.startsWith("../") || path3.isAbsolute(relativeBase) ? path3.basename(manifestPath) : relativeBase;
2359
2754
  deltaBase = { manifest: base, path: recordedBase };
2360
2755
  info(" Delta base: " + recordedBase + " (" + base.files.length + " files, fingerprint " + base.fingerprint.slice(0, 12) + ")");
2361
2756
  }
@@ -2373,9 +2768,9 @@ ${USAGE}
2373
2768
  ...invocation.sign === true && !invocation.dryRun ? { sign: { key: loadSigningKey() } } : {}
2374
2769
  });
2375
2770
  if (invocation.sign === true && !invocation.dryRun) {
2376
- const signaturePath = path2.resolve(resolved.cwd, resolved.outDir, SIGNATURE_FILE);
2771
+ const signaturePath = path3.resolve(resolved.cwd, resolved.outDir, SIGNATURE_FILE);
2377
2772
  try {
2378
- const record = JSON.parse(fs2.readFileSync(signaturePath, "utf8"));
2773
+ const record = JSON.parse(fs3.readFileSync(signaturePath, "utf8"));
2379
2774
  info(
2380
2775
  " Signature: ed25519, " + (record.keyOrigin ?? "unknown") + " key, " + (record.fingerprint ?? manifest.fingerprint).slice(0, 12)
2381
2776
  );
@@ -2528,19 +2923,19 @@ function finishWatchRun(state, now) {
2528
2923
  };
2529
2924
  }
2530
2925
  function comparablePath(value) {
2531
- const absolute = path2.resolve(value);
2926
+ const absolute = path3.resolve(value);
2532
2927
  return process.platform === "win32" ? absolute.toLowerCase() : absolute;
2533
2928
  }
2534
2929
  function isSameOrInside(parent, candidate) {
2535
- const relative3 = path2.relative(parent, candidate);
2536
- return relative3 === "" || relative3 !== ".." && !relative3.startsWith(`..${path2.sep}`) && !path2.isAbsolute(relative3);
2930
+ const relative4 = path3.relative(parent, candidate);
2931
+ return relative4 === "" || relative4 !== ".." && !relative4.startsWith(`..${path3.sep}`) && !path3.isAbsolute(relative4);
2537
2932
  }
2538
2933
  function isGeneratedWatchPath(candidate, paths) {
2539
- const absolute = comparablePath(path2.resolve(paths.cwd, candidate));
2540
- const outDir = comparablePath(path2.resolve(paths.cwd, paths.outDir));
2541
- const tmpDir = comparablePath(path2.resolve(paths.cwd, paths.tmpDir));
2934
+ const absolute = comparablePath(path3.resolve(paths.cwd, candidate));
2935
+ const outDir = comparablePath(path3.resolve(paths.cwd, paths.outDir));
2936
+ const tmpDir = comparablePath(path3.resolve(paths.cwd, paths.tmpDir));
2542
2937
  if (isSameOrInside(outDir, absolute) || isSameOrInside(tmpDir, absolute)) return true;
2543
- const offsets = [path2.basename(outDir), path2.basename(tmpDir)].filter((name) => name.length > 0);
2938
+ const offsets = [path3.basename(outDir), path3.basename(tmpDir)].filter((name) => name.length > 0);
2544
2939
  const leftover = absolute.split(/[\\/]+/).some(
2545
2940
  (segment) => offsets.some(
2546
2941
  (name) => segment.startsWith(`${name}.backup-`) || segment.startsWith(`${name}.partial-`)
@@ -2563,8 +2958,8 @@ function decideWatchEvent(state, event, paths) {
2563
2958
  function watchPathsFor(config) {
2564
2959
  return {
2565
2960
  cwd: config.cwd,
2566
- outDir: path2.resolve(config.cwd, config.outDir),
2567
- tmpDir: path2.resolve(config.cwd, config.tmpDir)
2961
+ outDir: path3.resolve(config.cwd, config.outDir),
2962
+ tmpDir: path3.resolve(config.cwd, config.tmpDir)
2568
2963
  };
2569
2964
  }
2570
2965
  function watchSupportProblem(platform = process.platform, version = process.versions.node) {
@@ -2638,11 +3033,11 @@ async function runWatchLoop(invocation, resolved, options) {
2638
3033
  info("\u{1F440} Watching for changes. Press Ctrl+C to stop.");
2639
3034
  let watcher;
2640
3035
  try {
2641
- watcher = fs2.watch(resolved.cwd, { recursive: true }, (_event, filename) => {
3036
+ watcher = fs3.watch(resolved.cwd, { recursive: true }, (_event, filename) => {
2642
3037
  const decision = decideWatchEvent(
2643
3038
  state,
2644
3039
  {
2645
- path: filename ? path2.resolve(resolved.cwd, filename.toString()) : null,
3040
+ path: filename ? path3.resolve(resolved.cwd, filename.toString()) : null,
2646
3041
  now: performance.now()
2647
3042
  },
2648
3043
  paths
@@ -2668,12 +3063,12 @@ async function runWatchLoop(invocation, resolved, options) {
2668
3063
  info(`\u26A0 Watch error: ${err.message}`);
2669
3064
  info(" The watcher may have missed changes. Restart with Ctrl+C if they stop arriving.");
2670
3065
  });
2671
- await new Promise((resolve2) => {
3066
+ await new Promise((resolve3) => {
2672
3067
  const stop = () => {
2673
3068
  stopped = true;
2674
3069
  if (timer) clearTimeout(timer);
2675
3070
  watcher.close();
2676
- resolve2();
3071
+ resolve3();
2677
3072
  };
2678
3073
  process.once("SIGINT", stop);
2679
3074
  process.once("SIGTERM", stop);
@@ -2683,12 +3078,12 @@ async function runWatchLoop(invocation, resolved, options) {
2683
3078
  var entryFile = process.argv[1] ?? "";
2684
3079
  var sameFile = (left, right) => {
2685
3080
  try {
2686
- return fs2.realpathSync(path2.resolve(left)) === fs2.realpathSync(path2.resolve(right));
3081
+ return fs3.realpathSync(path3.resolve(left)) === fs3.realpathSync(path3.resolve(right));
2687
3082
  } catch {
2688
3083
  return false;
2689
3084
  }
2690
3085
  };
2691
- var entryName = path2.basename(entryFile).toLowerCase();
3086
+ var entryName = path3.basename(entryFile).toLowerCase();
2692
3087
  var invokedDirectly = (entryName === "cli.js" || entryName === "cli.cjs") && entryFile.length > 0 && sameFile(entryFile, fileURLToPath(import.meta.url));
2693
3088
  if (invokedDirectly) {
2694
3089
  void main().then(