codebase-snapshot 0.20.13 → 0.22.0

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.
Files changed (51) hide show
  1. package/CHANGELOG.md +45 -6
  2. package/README.md +46 -19
  3. package/SECURITY.md +2 -2
  4. package/dist/bin.js +14535 -12036
  5. package/dist/{chunk-GNVRD7XS.js → chunk-NPCDJBE4.js} +6097 -4425
  6. package/dist/cli.cjs +11184 -8708
  7. package/dist/cli.d.cts +94 -2
  8. package/dist/cli.d.ts +94 -2
  9. package/dist/cli.js +944 -95
  10. package/dist/{generate-worker-DMzNbsAW.d.cts → generate-worker-BUNhTXkj.d.cts} +2 -2
  11. package/dist/{generate-worker-CRMESc0b.d.ts → generate-worker-TUMvHlgz.d.ts} +2 -2
  12. package/dist/index.cjs +6073 -4423
  13. package/dist/index.d.cts +281 -63
  14. package/dist/index.d.ts +281 -63
  15. package/dist/index.js +1 -1
  16. package/dist/mcp.cjs +10240 -4315
  17. package/dist/mcp.d.cts +13 -7
  18. package/dist/mcp.d.ts +13 -7
  19. package/dist/mcp.js +1 -1
  20. package/dist/{types-C5ytHMYz.d.ts → types-DQXKiaXk.d.cts} +50 -2
  21. package/dist/{types-C5ytHMYz.d.cts → types-DQXKiaXk.d.ts} +50 -2
  22. package/docs/about.md +86 -0
  23. package/docs/agent.md +28 -6
  24. package/docs/answer.md +99 -48
  25. package/docs/benchmarks.md +34 -34
  26. package/docs/brief.md +80 -81
  27. package/docs/cli.md +126 -25
  28. package/docs/codebase-token-budget.md +14 -13
  29. package/docs/contents.md +68 -0
  30. package/docs/deploy.md +2 -2
  31. package/docs/faq.md +112 -0
  32. package/docs/glossary.md +152 -0
  33. package/docs/guard.md +154 -0
  34. package/docs/health.md +1 -1
  35. package/docs/how-to-feed-a-repo-to-claude.md +6 -0
  36. package/docs/impact.md +102 -0
  37. package/docs/install.md +4 -3
  38. package/docs/llm-codebase-context.md +166 -0
  39. package/docs/mcp-server-for-codebase.md +163 -0
  40. package/docs/mcp.md +48 -67
  41. package/docs/migration.md +83 -90
  42. package/docs/output.md +1 -3
  43. package/docs/security-review.md +8 -8
  44. package/docs/slice.md +1 -1
  45. package/docs/tools.md +159 -185
  46. package/docs/troubleshooting.md +11 -11
  47. package/docs/vs-code2prompt.md +7 -0
  48. package/docs/vs-gitingest.md +7 -0
  49. package/docs/vs-repomix.md +10 -1
  50. package/docs/workspace.md +1 -1
  51. package/package.json +8 -2
package/dist/cli.js CHANGED
@@ -1,25 +1,230 @@
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, explainPath, compareManifests, loadManifest, 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, stripJsonComments, parseByteSize, gitignorePath, appendGitignoreEntries, escapeControls, runWithStdoutCapture, MIN_MAX_PART_TOKENS, MIN_MAX_PART_BYTES, renderContractText, renderExplainText } from './chunk-GNVRD7XS.js';
3
- export { buildAgentContract } from './chunk-GNVRD7XS.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-NPCDJBE4.js';
3
+ export { buildAgentContract } from './chunk-NPCDJBE4.js';
4
4
  import { spawnSync } from 'child_process';
5
5
  import * as fs2 from 'fs';
6
- import * as path2 from 'path';
6
+ import * as path3 from 'path';
7
+ import { fileURLToPath } from 'url';
7
8
  import { parseArgs } from 'util';
8
9
 
9
- var SKILL_TARGETS = ["claude", "cursor", "all"];
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 toGap(entry) {
18
+ return {
19
+ kind: "consumer",
20
+ path: entry.path,
21
+ distance: entry.distance,
22
+ via: entry.via,
23
+ ...entry.confidence === void 0 ? {} : { confidence: entry.confidence }
24
+ };
25
+ }
26
+ function testGap(entry) {
27
+ return { kind: "test", path: entry.path, covers: [...entry.covers] };
28
+ }
29
+ function routeGap(entry) {
30
+ return { kind: "route", path: entry.path, methods: [...entry.methods] };
31
+ }
32
+ function buildGuardReport(impact) {
33
+ const changed = impact.changed.filter((entry) => entry.deleted !== true).map((entry) => entry.path);
34
+ const changedSet = new Set(changed);
35
+ const consumers = impact.affected.filter((entry) => !changedSet.has(entry.path));
36
+ const tests = impact.tests.filter((entry) => !changedSet.has(entry.path));
37
+ const routes = (impact.routesAffected ?? []).filter((entry) => !changedSet.has(entry.path));
38
+ const consumerPart = take(consumers, MAX_CONSUMERS);
39
+ const testPart = take(tests, MAX_TESTS);
40
+ const routePart = take(routes, MAX_ROUTES);
41
+ const gaps = [
42
+ ...consumerPart.taken.map(toGap),
43
+ ...testPart.taken.map(testGap),
44
+ ...routePart.taken.map(routeGap)
45
+ ];
46
+ return {
47
+ schemaVersion: 1,
48
+ changed,
49
+ gaps,
50
+ trust: impact.trust,
51
+ truncated: impact.truncated || consumerPart.omitted > 0 || testPart.omitted > 0 || routePart.omitted > 0,
52
+ omitted: {
53
+ consumers: consumerPart.omitted,
54
+ tests: testPart.omitted,
55
+ routes: routePart.omitted
56
+ }
57
+ };
58
+ }
59
+ function label(gap) {
60
+ if (gap.kind === "test") return "test";
61
+ if (gap.kind === "route") return "route";
62
+ return "consumer";
63
+ }
64
+ function renderGuardText(report) {
65
+ if (report.gaps.length === 0) {
66
+ return "Change Guard: no gaps in this change.\n changed: " + report.changed.length + " file(s); coverage: " + report.trust.coverage + "\n";
67
+ }
68
+ const lines = [];
69
+ lines.push("Change Guard: " + report.gaps.length + " gap(s) in this change");
70
+ for (const gap of report.gaps) {
71
+ const parts = [gap.path];
72
+ if (gap.kind === "consumer") {
73
+ const meta = [];
74
+ if (gap.distance !== void 0) meta.push(gap.distance + " hop" + (gap.distance === 1 ? "" : "s"));
75
+ if (gap.confidence !== void 0) meta.push(gap.confidence);
76
+ if (gap.via !== void 0) meta.push("via " + gap.via);
77
+ if (meta.length > 0) parts.push("(" + meta.join(", ") + ")");
78
+ } else if (gap.kind === "test") {
79
+ parts.push("(test" + (gap.covers && gap.covers.length > 0 ? ": " + gap.covers.join(", ") : "") + ")");
80
+ } else {
81
+ parts.push("(route" + (gap.methods && gap.methods.length > 0 ? ": " + gap.methods.join(", ") : "") + ")");
82
+ }
83
+ lines.push(" " + label(gap).padEnd(9) + parts.join(" "));
84
+ }
85
+ if (report.truncated) {
86
+ const omitted = report.omitted;
87
+ lines.push(
88
+ " \u2026 truncated: " + omitted.consumers + " consumer(s), " + omitted.tests + " test(s), " + omitted.routes + " route(s) omitted"
89
+ );
90
+ }
91
+ lines.push(" coverage: " + report.trust.coverage + " \xB7 confidence: symbol-pruned");
92
+ return lines.join("\n");
93
+ }
94
+ function truncateGuardText(text, maxChars) {
95
+ if (text.length <= maxChars) return text;
96
+ const marker = "\n\u2026 run codebase-snapshot guard --changed for the full list";
97
+ const room = Math.max(0, maxChars - marker.length);
98
+ return text.slice(0, room).trimEnd() + marker;
99
+ }
100
+ function renderGuardHookText(report, maxChars = MAX_HOOK_CHARS) {
101
+ if (report.gaps.length === 0) return "";
102
+ const lines = ["[change-guard] " + report.gaps.length + " gap(s) in this change:"];
103
+ for (const gap of report.gaps) {
104
+ if (gap.kind === "consumer") {
105
+ lines.push(
106
+ " " + gap.path + (gap.distance === void 0 ? "" : " (" + gap.distance + " hop" + (gap.distance === 1 ? "" : "s") + ")")
107
+ );
108
+ } else if (gap.kind === "test") {
109
+ lines.push(" test " + gap.path);
110
+ } else {
111
+ lines.push(" route " + gap.path + (gap.methods && gap.methods.length > 0 ? " (" + gap.methods.join(", ") + ")" : ""));
112
+ }
113
+ }
114
+ lines.push("coverage: " + report.trust.coverage + " \xB7 confidence: symbol-pruned");
115
+ lines.push("run: npx codebase-snapshot brief --diff HEAD");
116
+ return truncateGuardText(lines.join("\n"), maxChars);
117
+ }
118
+ function renderGuardHook(report, client, event, maxChars = MAX_HOOK_CHARS) {
119
+ const text = renderGuardHookText(report, maxChars);
120
+ if (text.length === 0) return "{}";
121
+ if (client === "claude") {
122
+ return JSON.stringify({
123
+ hookSpecificOutput: {
124
+ hookEventName: event,
125
+ additionalContext: text
126
+ }
127
+ });
128
+ }
129
+ return JSON.stringify({ additionalContext: text });
130
+ }
131
+ function normalizePath(cwd, raw) {
132
+ const value = raw.trim();
133
+ if (value.length === 0 || value.includes("\0")) return null;
134
+ const absolute = path3.isAbsolute(value) ? value : path3.resolve(cwd, value);
135
+ const relative4 = path3.relative(cwd, absolute).split(path3.sep).join("/");
136
+ if (relative4 === "" || relative4 === ".." || relative4.startsWith("../") || path3.isAbsolute(relative4)) {
137
+ return null;
138
+ }
139
+ return relative4;
140
+ }
141
+ function collectPaths(value, out, depth = 0) {
142
+ if (depth > 6 || value === null || typeof value !== "object") return;
143
+ if (Array.isArray(value)) {
144
+ for (const item of value) collectPaths(item, out, depth + 1);
145
+ return;
146
+ }
147
+ const record = value;
148
+ for (const [key, item] of Object.entries(record)) {
149
+ if (typeof item === "string" && /^(file_path|filePath|path|file|filename|fileName)$/i.test(key)) {
150
+ out.add(item);
151
+ continue;
152
+ }
153
+ if (Array.isArray(item) && /^(files|paths|file_paths|filePaths)$/i.test(key)) {
154
+ for (const entry of item) if (typeof entry === "string") out.add(entry);
155
+ continue;
156
+ }
157
+ if (typeof item === "object" && item !== null) collectPaths(item, out, depth + 1);
158
+ }
159
+ }
160
+ function parseGuardHookInput(client, raw, cwd) {
161
+ let payload;
162
+ try {
163
+ payload = JSON.parse(raw);
164
+ } catch {
165
+ throw new Error("guard --hook expects one JSON object on stdin.");
166
+ }
167
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
168
+ throw new Error("guard --hook expects one JSON object on stdin.");
169
+ }
170
+ const record = payload;
171
+ const candidates = /* @__PURE__ */ new Set();
172
+ if (client === "claude") {
173
+ const toolInput = record.tool_input;
174
+ if (toolInput !== null && typeof toolInput === "object") collectPaths(toolInput, candidates);
175
+ const toolResponse = record.tool_response;
176
+ if (toolResponse !== null && typeof toolResponse === "object") collectPaths(toolResponse, candidates);
177
+ if (typeof record.file_path === "string") candidates.add(record.file_path);
178
+ } else if (client === "copilot") {
179
+ if (typeof record.toolArgs === "string") {
180
+ try {
181
+ collectPaths(JSON.parse(record.toolArgs), candidates);
182
+ } catch {
183
+ }
184
+ } else if (record.toolArgs !== null && typeof record.toolArgs === "object") {
185
+ collectPaths(record.toolArgs, candidates);
186
+ }
187
+ if (record.tool_input !== null && typeof record.tool_input === "object") {
188
+ collectPaths(record.tool_input, candidates);
189
+ }
190
+ } else {
191
+ if (record.tool_input !== null && typeof record.tool_input === "object") {
192
+ collectPaths(record.tool_input, candidates);
193
+ }
194
+ if (record.toolArgs !== null && typeof record.toolArgs === "object") {
195
+ collectPaths(record.toolArgs, candidates);
196
+ }
197
+ if (typeof record.path === "string") candidates.add(record.path);
198
+ }
199
+ const paths = [];
200
+ for (const candidate of candidates) {
201
+ const normalized = normalizePath(cwd, candidate);
202
+ if (normalized !== null) paths.push(normalized);
203
+ }
204
+ const sessionId = typeof record.session_id === "string" ? record.session_id : typeof record.sessionId === "string" ? record.sessionId : void 0;
205
+ const event = typeof record.hook_event_name === "string" ? record.hook_event_name : typeof record.hookEventName === "string" ? record.hookEventName : "PostToolUse";
206
+ return {
207
+ paths: [...new Set(paths)].sort((left, right) => left.localeCompare(right)),
208
+ ...sessionId === void 0 ? {} : { sessionId },
209
+ event
210
+ };
211
+ }
212
+ var SKILL_TARGETS = ["agents", "claude", "cursor", "all"];
10
213
  var REFUSED = "Refusing to install the agent skill";
11
214
  var LEGACY_AGENTS_MARKER = "<!-- codebase-snapshot:skill:start -->";
12
215
  function targetPath(cwd, target) {
13
216
  switch (target) {
217
+ case "agents":
218
+ return path3.join(cwd, ".agents", "skills", SKILL_NAME, "SKILL.md");
14
219
  case "claude":
15
- return path2.join(cwd, ".claude", "skills", SKILL_NAME, "SKILL.md");
220
+ return path3.join(cwd, ".claude", "skills", SKILL_NAME, "SKILL.md");
16
221
  case "cursor":
17
- return path2.join(cwd, ".cursor", "rules", `${SKILL_NAME}.mdc`);
222
+ return path3.join(cwd, ".cursor", "rules", `${SKILL_NAME}.mdc`);
18
223
  }
19
224
  }
20
225
  function assertWritableInsideRepository(cwd, filePath) {
21
226
  const root = fs2.realpathSync(cwd);
22
- const shown = path2.relative(root, filePath) || filePath;
227
+ const shown = path3.relative(root, filePath) || filePath;
23
228
  let stat = null;
24
229
  try {
25
230
  stat = fs2.lstatSync(filePath);
@@ -39,14 +244,14 @@ function assertWritableInsideRepository(cwd, filePath) {
39
244
  let existing = filePath;
40
245
  const missing = [];
41
246
  while (!fs2.existsSync(existing)) {
42
- missing.unshift(path2.basename(existing));
43
- const parent = path2.dirname(existing);
247
+ missing.unshift(path3.basename(existing));
248
+ const parent = path3.dirname(existing);
44
249
  if (parent === existing) break;
45
250
  existing = parent;
46
251
  }
47
252
  const realAncestor = fs2.realpathSync(existing);
48
- const resolved = missing.length === 0 ? realAncestor : path2.join(realAncestor, ...missing);
49
- if (resolved !== root && !resolved.startsWith(`${root}${path2.sep}`)) {
253
+ const resolved = missing.length === 0 ? realAncestor : path3.join(realAncestor, ...missing);
254
+ if (resolved !== root && !resolved.startsWith(`${root}${path3.sep}`)) {
50
255
  throw new Error(
51
256
  `${REFUSED}: ${shown} resolves outside the repository (${resolved}). Move it back inside ${root}, or remove the link, and run again.`
52
257
  );
@@ -55,12 +260,12 @@ function assertWritableInsideRepository(cwd, filePath) {
55
260
  function writeIfChanged(target, filePath, content) {
56
261
  const existing = fs2.existsSync(filePath) ? fs2.readFileSync(filePath, "utf8") : null;
57
262
  if (existing === content) return { target, path: filePath, action: "unchanged" };
58
- fs2.mkdirSync(path2.dirname(filePath), { recursive: true });
263
+ fs2.mkdirSync(path3.dirname(filePath), { recursive: true });
59
264
  fs2.writeFileSync(filePath, content, "utf8");
60
265
  return { target, path: filePath, action: existing === null ? "created" : "updated" };
61
266
  }
62
267
  function legacyAgentsNote(cwd) {
63
- const filePath = path2.join(cwd, "AGENTS.md");
268
+ const filePath = path3.join(cwd, "AGENTS.md");
64
269
  try {
65
270
  if (!fs2.existsSync(filePath)) return null;
66
271
  if (!fs2.readFileSync(filePath, "utf8").includes(LEGACY_AGENTS_MARKER)) return null;
@@ -69,16 +274,17 @@ function legacyAgentsNote(cwd) {
69
274
  }
70
275
  return `AGENTS.md still contains the section an earlier version installed (between the "${LEGACY_AGENTS_MARKER}" markers). This command no longer edits that file: it is your project's own agent instructions. Delete the block if you do not want it.`;
71
276
  }
72
- function installSkill(cwd, target = "all") {
277
+ function installSkill(cwd, target = "all", options = {}) {
73
278
  const skill = renderSkill();
74
279
  const written = [];
75
280
  const notes = [];
76
- const wanted = target === "all" ? ["claude", "cursor"] : [target];
281
+ const wanted = target === "all" ? ["agents", "claude", "cursor"] : [target];
77
282
  for (const item of wanted) assertWritableInsideRepository(cwd, targetPath(cwd, item));
78
283
  const createsSomething = wanted.some((item) => !fs2.existsSync(targetPath(cwd, item)));
79
284
  if (createsSomething) {
80
- assertWritableInsideRepository(cwd, path2.join(cwd, ".gitignore"));
285
+ assertWritableInsideRepository(cwd, path3.join(cwd, ".gitignore"));
81
286
  }
287
+ const pendingMcp = options.withMcp === true ? prepareMcpConfig(cwd) : null;
82
288
  for (const item of wanted) {
83
289
  written.push(writeIfChanged(item, targetPath(cwd, item), skill));
84
290
  }
@@ -87,7 +293,57 @@ function installSkill(cwd, target = "all") {
87
293
  if (ignore.note !== null) notes.push(ignore.note);
88
294
  const legacy = legacyAgentsNote(cwd);
89
295
  if (legacy !== null) notes.push(legacy);
90
- return { cwd, written, gitignored: ignore.added, notes };
296
+ let mcp;
297
+ if (pendingMcp !== null) {
298
+ if (pendingMcp.note !== null) notes.push(pendingMcp.note);
299
+ if (pendingMcp.content !== null) {
300
+ fs2.writeFileSync(pendingMcp.filePath, pendingMcp.content, "utf8");
301
+ }
302
+ mcp = { path: pendingMcp.filePath, action: pendingMcp.action };
303
+ }
304
+ return { cwd, written, gitignored: ignore.added, notes, ...mcp === void 0 ? {} : { mcp } };
305
+ }
306
+ function prepareMcpConfig(cwd) {
307
+ const filePath = path3.join(cwd, ".mcp.json");
308
+ assertWritableInsideRepository(cwd, filePath);
309
+ const desired = { command: "npx", args: ["-y", "codebase-snapshot@latest", "mcp"] };
310
+ let parsed = {};
311
+ let existing = null;
312
+ if (fs2.existsSync(filePath)) {
313
+ existing = fs2.readFileSync(filePath, "utf8");
314
+ let candidate;
315
+ try {
316
+ candidate = JSON.parse(existing);
317
+ } catch {
318
+ throw new Error(REFUSED + ": .mcp.json is not valid JSON. Fix it or remove it, then run again.");
319
+ }
320
+ if (candidate === null || typeof candidate !== "object" || Array.isArray(candidate)) {
321
+ throw new Error(REFUSED + ": .mcp.json must contain a JSON object.");
322
+ }
323
+ parsed = candidate;
324
+ }
325
+ const servers = parsed.mcpServers;
326
+ if (servers !== void 0 && (servers === null || typeof servers !== "object" || Array.isArray(servers))) {
327
+ throw new Error(REFUSED + ": .mcp.json#mcpServers must be an object.");
328
+ }
329
+ const map = servers ?? {};
330
+ const current = map["codebase-snapshot"];
331
+ if (current !== void 0) {
332
+ if (JSON.stringify(current) === JSON.stringify(desired)) {
333
+ return { filePath, action: "unchanged", content: null, note: null };
334
+ }
335
+ return {
336
+ filePath,
337
+ action: "unchanged",
338
+ content: null,
339
+ note: "Kept the existing codebase-snapshot entry in .mcp.json; it differs from the generated one."
340
+ };
341
+ }
342
+ map["codebase-snapshot"] = desired;
343
+ parsed.mcpServers = map;
344
+ const text = JSON.stringify(parsed, null, 2) + "\n";
345
+ if (text === existing) return { filePath, action: "unchanged", content: null, note: null };
346
+ return { filePath, action: existing === null ? "created" : "updated", content: text, note: null };
91
347
  }
92
348
  function isSkillTarget(value) {
93
349
  return SKILL_TARGETS.includes(value);
@@ -102,6 +358,9 @@ var COMMAND_ALIASES = /* @__PURE__ */ new Map([
102
358
  ["check", "validate"],
103
359
  ["health", "health"],
104
360
  ["report", "report"],
361
+ ["impact", "impact"],
362
+ ["guard", "guard"],
363
+ ["brief", "brief"],
105
364
  ["init", "init"],
106
365
  ["setup", "setup"],
107
366
  ["explain", "explain"],
@@ -117,6 +376,9 @@ var COMMAND_ARITY = {
117
376
  validate: 0,
118
377
  health: 0,
119
378
  report: 0,
379
+ impact: 0,
380
+ guard: 0,
381
+ brief: 1,
120
382
  init: 0,
121
383
  setup: 0,
122
384
  explain: 1,
@@ -160,6 +422,26 @@ var CLI_OPTIONS = {
160
422
  "no-update-check": { type: "boolean" },
161
423
  "install-hook": { type: "boolean" },
162
424
  "changed-since": { type: "string" },
425
+ diff: { type: "string" },
426
+ paths: { type: "string" },
427
+ hook: { type: "string" },
428
+ changed: { type: "boolean" },
429
+ "max-chars": { type: "string" },
430
+ depth: { type: "string" },
431
+ "max-results": { type: "string" },
432
+ "no-cache": { type: "boolean" },
433
+ "no-live": { type: "boolean" },
434
+ "tests-paths": { type: "boolean" },
435
+ run: { type: "boolean" },
436
+ precise: { type: "boolean" },
437
+ "include-imports": { type: "boolean" },
438
+ "include-cycles": { type: "boolean" },
439
+ copy: { type: "boolean" },
440
+ out: { type: "string" },
441
+ "max-tokens": { type: "string" },
442
+ "lines-per-file": { type: "string" },
443
+ "include-tests": { type: "boolean" },
444
+ "with-mcp": { type: "boolean" },
163
445
  "with-dependents": { type: "boolean" },
164
446
  staged: { type: "boolean" },
165
447
  skeleton: { type: "boolean" },
@@ -218,6 +500,9 @@ Commands:
218
500
  health Audit a snapshot for leaks, lies and wasted tokens (--strict, --format json)
219
501
  init Generate a starter snapshot.config file
220
502
  report Print codebase health, layer metrics, and secret audit
503
+ impact Report changed files, transitive importers, routes and candidate tests
504
+ guard Check a change for untouched consumers, tests and routes (hook-aware)
505
+ brief One redacted review pack: impact, diff hunks and bounded source windows
221
506
  explain <path> Show how one path would be treated: layer, kind, part, skips
222
507
  diff <a> <b> Compare two snapshots (directories or manifest.json files)
223
508
  describe Print the machine-readable contract (--format json for agents)
@@ -263,7 +548,8 @@ Options:
263
548
  (readme, prompt, manifest, parts, navigation,
264
549
  projectTree, audit, diff, log, tokenTree, monolith)
265
550
  --only-artifacts <names> Write *only* these artifacts
266
- --format <text|json> CLI output format (default: text)
551
+ --format <text|json|markdown|pr-comment>
552
+ CLI output format; markdown/pr-comment apply to impact and brief
267
553
  --dry-run Compute the snapshot without writing anything
268
554
  --watch Re-generate whenever the repository changes
269
555
  --no-config Ignore snapshot.config.* and use the built-in defaults
@@ -303,9 +589,33 @@ Options:
303
589
  --all-members Audit every snapshot a --workspace run wrote
304
590
  --deep Replay every full body against the source on disk
305
591
 
592
+ impact and brief:
593
+ --diff <ref> Compare the working tree against this git ref
594
+ --paths <a,b> Treat these repository-relative paths as the change
595
+ --depth <n> Reverse-import hops to follow (default: 3, max: 8)
596
+ --max-results <n> Cap affected files (default: 200, max: 1000)
597
+ --tests-paths Print candidate test paths, one per line
598
+ --run Run the detected test runner (text format only)
599
+ --precise Add bounded compiler-resolved symbol references
600
+
601
+ guard only:
602
+ --hook <client> Read one hook payload from stdin: claude | copilot | codex | raw
603
+ --changed Check the working tree against HEAD (default when no --hook)
604
+ --max-chars <n> Cap the model-facing hook text (default 1200, max 10000)
605
+ --include-imports Include outgoing imports of changed files
606
+ --include-cycles Include import cycles in the impacted subgraph
607
+ --no-live Require the persisted snapshot instead of the live index
608
+ --no-cache Bypass the OS live-index summary cache
609
+ --max-tokens <n> Brief token budget (default: 12000, minimum: 500)
610
+ --lines-per-file <n> Brief lines per file (default: 80)
611
+ --include-tests Include candidate tests in the brief
612
+ --copy Copy the brief to the clipboard
613
+ --out <path> Write the brief inside the repository
614
+
306
615
  skill only:
307
616
  --install Write the skill into the repository instead of printing
308
- --target <name> claude | cursor | all (default: all)
617
+ --target <name> agents | claude | cursor | all (default: all)
618
+ --with-mcp Also merge a server entry into .mcp.json
309
619
 
310
620
  --no-update-check Skip the check for a newer published version
311
621
 
@@ -362,6 +672,9 @@ function parseCountOption(raw, optionName, minimum = 0) {
362
672
  }
363
673
  return value;
364
674
  }
675
+ function isGuardClient(value) {
676
+ return value === "claude" || value === "copilot" || value === "codex" || value === "raw";
677
+ }
365
678
  function parsePromptTask(value) {
366
679
  if (value === void 0) return void 0;
367
680
  if (value === "audit" || value === "review" || value === "explain") return value;
@@ -483,7 +796,10 @@ function parseCliArgs(argv) {
483
796
  args = positionals.slice(1);
484
797
  }
485
798
  const expectedArgs = COMMAND_ARITY[command];
486
- if (args.length !== expectedArgs) {
799
+ if (command === "brief" && args.length > 1) {
800
+ throw new UsageError("brief takes at most one question. Put a path or reference in --diff or --paths.");
801
+ }
802
+ if (args.length !== expectedArgs && !(command === "brief" && args.length === 0)) {
487
803
  if (command === "explain") {
488
804
  throw new UsageError("explain expects exactly one path.");
489
805
  }
@@ -497,8 +813,66 @@ function parseCliArgs(argv) {
497
813
  );
498
814
  }
499
815
  const rawFormat = values.format === void 0 ? "text" : String(values.format);
500
- if (rawFormat !== "text" && rawFormat !== "json") {
501
- throw new UsageError(`--format must be "text" or "json", received "${rawFormat}".`);
816
+ const allowedFormats = ["text", "json"];
817
+ if (command === "impact" || command === "brief") {
818
+ allowedFormats.push("markdown", "pr-comment");
819
+ }
820
+ if (!allowedFormats.includes(rawFormat)) {
821
+ throw new UsageError(
822
+ command === "impact" || command === "brief" ? `--format must be "text", "json", "markdown" or "pr-comment", received "${rawFormat}".` : `--format must be "text" or "json", received "${rawFormat}".`
823
+ );
824
+ }
825
+ const rawDiff = values.diff === void 0 ? void 0 : String(values.diff).trim();
826
+ if (rawDiff !== void 0 && rawDiff.startsWith("-")) {
827
+ throw new UsageError(
828
+ `--diff expects a git ref, not an option (received "${rawDiff}"). Name a branch, tag, or commit.`
829
+ );
830
+ }
831
+ const rawPaths = values.paths === void 0 ? void 0 : String(values.paths);
832
+ const paths = rawPaths === void 0 ? void 0 : rawPaths.split(",").map((item) => item.trim()).filter((item) => item.length > 0);
833
+ if (paths !== void 0 && paths.length === 0) {
834
+ throw new UsageError("--paths expects at least one repository-relative path.");
835
+ }
836
+ for (const item of paths ?? []) {
837
+ const normalized = item.replace(/\\/g, "/").replace(/^\.\/+/, "");
838
+ if (normalized.length === 0 || normalized.startsWith("/") || /^[A-Za-z]:\//.test(normalized) || normalized.split("/").includes("..")) {
839
+ throw new UsageError(
840
+ `--paths accepts repository-relative paths only; "${item}" is absolute or escapes the repository.`
841
+ );
842
+ }
843
+ }
844
+ const rawHook = values.hook === void 0 ? void 0 : String(values.hook);
845
+ if (rawHook !== void 0 && !isGuardClient(rawHook)) {
846
+ throw new UsageError(
847
+ `--hook must be one of: claude, copilot, codex, raw (received "${rawHook}").`
848
+ );
849
+ }
850
+ if (rawHook !== void 0) {
851
+ if (paths !== void 0 || rawDiff !== void 0) {
852
+ throw new UsageError(
853
+ "guard --hook reads the changed paths from its stdin payload; do not pass --paths or --diff."
854
+ );
855
+ }
856
+ if (values.changed === true) {
857
+ throw new UsageError("guard --hook already runs on the payload; do not pass --changed.");
858
+ }
859
+ }
860
+ const maxChars = parseCountOption(values["max-chars"], "max-chars", 200);
861
+ if (maxChars !== void 0 && maxChars > 1e4) {
862
+ throw new UsageError(`--max-chars must be at most 10000, received ${maxChars}.`);
863
+ }
864
+ if (command === "impact" || command === "brief") {
865
+ if (rawDiff !== void 0 && paths !== void 0) {
866
+ throw new UsageError("impact accepts either --diff <ref> or --paths <a,b>, not both.");
867
+ }
868
+ }
869
+ const depth = parseCountOption(values.depth, "depth", 1);
870
+ if (depth !== void 0 && depth > 8) {
871
+ throw new UsageError(`--depth must be at most 8, received ${depth}.`);
872
+ }
873
+ const maxResults = parseCountOption(values["max-results"], "max-results", 1);
874
+ if (maxResults !== void 0 && maxResults > 1e3) {
875
+ throw new UsageError(`--max-results must be at most 1000, received ${maxResults}.`);
502
876
  }
503
877
  const rawDiscovery = values.discovery === void 0 ? void 0 : String(values.discovery);
504
878
  if (rawDiscovery !== void 0 && !isDiscoveryMode(rawDiscovery)) {
@@ -551,6 +925,14 @@ function parseCliArgs(argv) {
551
925
  const requested = String(values.preset);
552
926
  if (!getPreset(requested)) throw new UsageError(unknownPresetMessage(requested));
553
927
  }
928
+ if (command === "skill" && values["with-mcp"] === true && values.install !== true) {
929
+ throw new UsageError("--with-mcp only applies to `skill --install`.");
930
+ }
931
+ if (command === "brief" && args.length > 0 && (values.diff !== void 0 || values.paths !== void 0 || values.depth !== void 0 || values["max-results"] !== void 0)) {
932
+ throw new UsageError(
933
+ "brief takes either a question or change options (--diff, --paths, --depth, --max-results), not both."
934
+ );
935
+ }
554
936
  if (command === "skill" && values.target !== void 0 && !isSkillTarget(String(values.target))) {
555
937
  throw new UsageError(
556
938
  `--target must be one of: ${SKILL_TARGETS.join(", ")} (received "${String(values.target)}").`
@@ -577,12 +959,27 @@ function parseCliArgs(argv) {
577
959
  include: values.include === void 0 ? void 0 : String(values.include),
578
960
  exclude: values.exclude === void 0 ? void 0 : String(values.exclude),
579
961
  yes: values.yes === true,
962
+ noCache: values["no-cache"] === true,
963
+ noLive: values["no-live"] === true,
964
+ testsPaths: values["tests-paths"] === true,
965
+ runTests: values.run === true,
966
+ precise: values.precise === true,
967
+ includeImports: values["include-imports"] === true,
968
+ includeCycles: values["include-cycles"] === true,
969
+ copy: values.copy === true,
970
+ out: values.out === void 0 ? void 0 : String(values.out),
971
+ maxTokens: parseCountOption(values["max-tokens"], "max-tokens", 500),
972
+ linesPerFile: parseCountOption(values["lines-per-file"], "lines-per-file", 10),
973
+ includeTestsOnly: values["include-tests"] === true,
974
+ withMcp: values["with-mcp"] === true,
975
+ markdown: rawFormat === "markdown" || rawFormat === "pr-comment",
976
+ prComment: rawFormat === "pr-comment",
580
977
  force: values.force === true,
581
978
  autopilot: values.autopilot === true,
582
979
  install: values.install === true,
583
980
  noInstall: values["no-install"] === true,
584
981
  target: values.target === void 0 ? void 0 : String(values.target),
585
- cwd: values.cwd === void 0 ? process.cwd() : path2.resolve(String(values.cwd)),
982
+ cwd: values.cwd === void 0 ? process.cwd() : path3.resolve(String(values.cwd)),
586
983
  outDir: values["out-dir"] === void 0 ? void 0 : String(values["out-dir"]),
587
984
  includeMonolith: values["include-monolith"] === true || onlyNamesMonolith === true ? true : void 0,
588
985
  includeSensitiveFiles: values["include-sensitive-files"] === true ? true : void 0,
@@ -623,6 +1020,13 @@ function parseCliArgs(argv) {
623
1020
  noUpdateCheck: values["no-update-check"] === true,
624
1021
  installHook: values["install-hook"] === true,
625
1022
  changedSince: values["changed-since"] === void 0 ? void 0 : String(values["changed-since"]),
1023
+ diff: rawDiff,
1024
+ paths,
1025
+ hook: rawHook === void 0 ? void 0 : rawHook,
1026
+ changed: values.changed === true,
1027
+ maxChars,
1028
+ depth,
1029
+ maxResults,
626
1030
  // `undefined` when the flag was not given, never `false`.
627
1031
  //
628
1032
  // `resolveConfig` reads these as `cliOptions.x ?? config.x`, so a `false` here is an
@@ -694,15 +1098,135 @@ function fail(format, message, exitCode = 1) {
694
1098
  }
695
1099
  return exitCode;
696
1100
  }
1101
+ function markdownValue(value) {
1102
+ return inlineCode(findSecretInPath(value)?.masked ?? value);
1103
+ }
1104
+ function renderImpactMarkdown(report) {
1105
+ const lines = [];
1106
+ lines.push("# Impact report");
1107
+ lines.push("");
1108
+ lines.push(
1109
+ "Trust: source=" + report.trust.indexSource + " \xB7 freshness=" + report.trust.freshness + " \xB7 coverage=" + report.trust.coverage + " \xB7 redacted=" + report.trust.redactedLines
1110
+ );
1111
+ lines.push("");
1112
+ lines.push("**Changed:** " + report.changed.length + " \xB7 **Affected:** " + report.affected.length + " \xB7 **Tests:** " + report.tests.length);
1113
+ lines.push("");
1114
+ lines.push("## Changed");
1115
+ lines.push(report.changed.length === 0 ? "_None._" : report.changed.map((entry) => "- " + markdownValue(entry.path) + (entry.deleted ? " (deleted)" : "")).join("\n"));
1116
+ lines.push("");
1117
+ lines.push("## Affected");
1118
+ lines.push(report.affected.length === 0 ? "_None._" : report.affected.map((entry) => "- " + markdownValue(entry.path) + " \u2014 " + entry.distance + " hop via " + markdownValue(entry.via) + " (" + markdownValue(entry.specifier) + ")").join("\n"));
1119
+ lines.push("");
1120
+ if (report.routesAffected !== void 0 && report.routesAffected.length > 0) {
1121
+ lines.push("## Routes affected");
1122
+ lines.push(report.routesAffected.map((route) => "- " + markdownValue(route.path) + " (" + route.methods.map(markdownValue).join(", ") + ")").join("\n"));
1123
+ lines.push("");
1124
+ }
1125
+ lines.push("## Candidate tests");
1126
+ lines.push(report.tests.length === 0 ? "_None._" : report.tests.map((test) => "- " + markdownValue(test.path) + " \u2014 covers " + test.covers.map(markdownValue).join(", ")).join("\n"));
1127
+ if (report.unresolved.length > 0) {
1128
+ lines.push("");
1129
+ lines.push("## Unresolved internal imports");
1130
+ lines.push(report.unresolved.map((entry) => "- " + markdownValue(entry.path) + ": " + markdownValue(entry.specifier)).join("\n"));
1131
+ }
1132
+ if (report.cycles !== void 0 && report.cycles.length > 0) {
1133
+ lines.push("");
1134
+ lines.push("## Import cycles");
1135
+ lines.push(report.cycles.map((cycle) => "- " + cycle.map(markdownValue).join(" -> ")).join("\n"));
1136
+ }
1137
+ if (report.imports !== void 0) {
1138
+ const entries = Object.entries(report.imports).filter(([, targets]) => targets.length > 0);
1139
+ if (entries.length > 0) {
1140
+ lines.push("");
1141
+ lines.push("## Outgoing imports");
1142
+ lines.push(entries.map(([source, targets]) => "- " + markdownValue(source) + " -> " + targets.map(markdownValue).join(", ")).join("\n"));
1143
+ }
1144
+ }
1145
+ if (report.precise !== void 0) {
1146
+ lines.push("");
1147
+ lines.push("## Precise symbol references (" + report.precise.coverage + ")");
1148
+ lines.push(
1149
+ report.precise.references.length === 0 ? "_None._" : report.precise.references.slice(0, 25).map((reference) => "- " + markdownValue(reference.path + ":" + reference.line) + " (" + markdownValue(reference.name) + ")").join("\n")
1150
+ );
1151
+ if (report.precise.reasons.length > 0) {
1152
+ lines.push(...report.precise.reasons.slice(0, 3).map((reason) => "- Note: " + escapeControls(reason)));
1153
+ }
1154
+ }
1155
+ if (report.warnings.length > 0) {
1156
+ lines.push("");
1157
+ lines.push("## Warnings");
1158
+ lines.push(report.warnings.map((warning) => "- " + escapeControls(warning)).join("\n"));
1159
+ }
1160
+ lines.push("");
1161
+ return lines.join("\n");
1162
+ }
1163
+ function realPathInside(realRoot, candidate) {
1164
+ const fold = (value) => process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
1165
+ const relative4 = path3.relative(fold(realRoot), fold(candidate));
1166
+ return relative4.length === 0 || relative4 !== ".." && !relative4.startsWith(".." + path3.sep) && !path3.isAbsolute(relative4);
1167
+ }
1168
+ function writeInside(root, relative4, content) {
1169
+ const target = path3.resolve(root, relative4);
1170
+ const rel = path3.relative(path3.resolve(root), target);
1171
+ if (rel.length === 0 || rel === ".." || rel.startsWith(".." + path3.sep) || path3.isAbsolute(rel)) {
1172
+ throw new Error("--out must resolve inside the repository.");
1173
+ }
1174
+ const parent = path3.dirname(target);
1175
+ const realRoot = fs2.realpathSync(root);
1176
+ let existingAncestor = parent;
1177
+ while (!fs2.existsSync(existingAncestor)) {
1178
+ const next = path3.dirname(existingAncestor);
1179
+ if (next === existingAncestor) break;
1180
+ existingAncestor = next;
1181
+ }
1182
+ if (!realPathInside(realRoot, fs2.realpathSync(existingAncestor))) {
1183
+ throw new Error("--out resolves outside the repository through a link.");
1184
+ }
1185
+ fs2.mkdirSync(parent, { recursive: true });
1186
+ if (!realPathInside(realRoot, fs2.realpathSync(parent))) {
1187
+ throw new Error("--out resolves outside the repository through a link.");
1188
+ }
1189
+ try {
1190
+ const existing = fs2.lstatSync(target);
1191
+ if (existing.isSymbolicLink() || !existing.isFile() || existing.nlink > 1) {
1192
+ throw new Error("--out must be a regular file that is not a symbolic or hard link.");
1193
+ }
1194
+ } catch (error) {
1195
+ if (error.code !== "ENOENT") throw error;
1196
+ }
1197
+ const temporary = path3.join(parent, "." + path3.basename(target) + ".tmp-" + process.pid + "-" + Math.random().toString(16).slice(2));
1198
+ fs2.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx", mode: 384 });
1199
+ try {
1200
+ fs2.renameSync(temporary, target);
1201
+ } catch (error) {
1202
+ try {
1203
+ fs2.unlinkSync(temporary);
1204
+ } catch (cleanupError) {
1205
+ warn("Could not remove temporary file " + temporary + ": " + cleanupError.message);
1206
+ }
1207
+ throw error;
1208
+ }
1209
+ return target;
1210
+ }
1211
+ function copyToClipboard(text) {
1212
+ const commands = process.platform === "win32" ? [["clip", []]] : process.platform === "darwin" ? [["pbcopy", []]] : [["wl-copy", []], ["xclip", ["-selection", "clipboard"]]];
1213
+ let last = null;
1214
+ for (const [command, args] of commands) {
1215
+ const result = spawnSync(command, args, { input: text, stdio: ["pipe", "ignore", "pipe"], shell: false });
1216
+ if (result.error === void 0 && result.status === 0) return;
1217
+ last = result.error === void 0 ? command + " exited " + result.status : result.error.message;
1218
+ }
1219
+ throw new Error("Could not copy the brief to the clipboard: " + (last ?? "no clipboard command available"));
1220
+ }
697
1221
  function splitList(value) {
698
1222
  if (value === void 0) return void 0;
699
1223
  return value.split(",").map((entry) => entry.trim()).filter(Boolean);
700
1224
  }
701
1225
  function displayOutPath(cwd, outDir, ...segments) {
702
- const absolute = path2.resolve(cwd, outDir, ...segments);
703
- const relative3 = path2.relative(cwd, absolute);
704
- if (relative3 !== "" && relative3 !== ".." && !relative3.startsWith(`..${path2.sep}`) && !relative3.startsWith("../") && !path2.isAbsolute(relative3)) {
705
- return relative3;
1226
+ const absolute = path3.resolve(cwd, outDir, ...segments);
1227
+ const relative4 = path3.relative(cwd, absolute);
1228
+ if (relative4 !== "" && relative4 !== ".." && !relative4.startsWith(`..${path3.sep}`) && !relative4.startsWith("../") && !path3.isAbsolute(relative4)) {
1229
+ return relative4;
706
1230
  }
707
1231
  return absolute;
708
1232
  }
@@ -711,7 +1235,7 @@ function nextStepHint(cwd, scriptsAddedNow) {
711
1235
  if (!hasScript) {
712
1236
  try {
713
1237
  const parsed = JSON.parse(
714
- stripJsonComments(fs2.readFileSync(path2.join(cwd, "package.json"), "utf8"))
1238
+ stripJsonComments(fs2.readFileSync(path3.join(cwd, "package.json"), "utf8"))
715
1239
  );
716
1240
  hasScript = typeof parsed.scripts?.snapshot === "string";
717
1241
  } catch {
@@ -719,7 +1243,7 @@ function nextStepHint(cwd, scriptsAddedNow) {
719
1243
  }
720
1244
  }
721
1245
  if (!hasScript) return `npx ${GENERATOR_NAME} generate`;
722
- const bin = path2.join(cwd, "node_modules", ".bin", "codebase-snapshot");
1246
+ const bin = path3.join(cwd, "node_modules", ".bin", "codebase-snapshot");
723
1247
  const installed = fs2.existsSync(bin) || fs2.existsSync(`${bin}.cmd`);
724
1248
  return installed ? "npm run snapshot" : "npm install && npm run snapshot";
725
1249
  }
@@ -756,7 +1280,7 @@ async function runInitCommand(invocation) {
756
1280
  if (hook) for (const note of hook.notes) info(` ${note}`);
757
1281
  return 0;
758
1282
  }
759
- info(`\u2705 Created ${path2.basename(result.configPath)} (${presetSummary(result)})`);
1283
+ info(`\u2705 Created ${path3.basename(result.configPath)} (${presetSummary(result)})`);
760
1284
  if (result.scripts.length > 0) info(` Added npm scripts: ${result.scripts.join(", ")}`);
761
1285
  if (result.dependency.added && result.dependency.range !== null) {
762
1286
  info(` Added devDependency: ${result.dependency.name} ${result.dependency.range}`);
@@ -766,10 +1290,10 @@ async function runInitCommand(invocation) {
766
1290
  }
767
1291
  if (result.briefWritten) {
768
1292
  info(
769
- ` 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.`
1293
+ ` 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.`
770
1294
  );
771
1295
  } else if (fs2.existsSync(result.briefPath)) {
772
- info(` Kept ${path2.basename(result.briefPath)}: it already exists, and is never overwritten.`);
1296
+ info(` Kept ${path3.basename(result.briefPath)}: it already exists, and is never overwritten.`);
773
1297
  }
774
1298
  for (const note of result.notes) info(` \u26A0 ${note}`);
775
1299
  if (hook) for (const note of hook.notes) info(` ${note}`);
@@ -806,18 +1330,18 @@ function renderHealthText(report) {
806
1330
  function generatorOrigin(cwd) {
807
1331
  try {
808
1332
  const pkg = JSON.parse(
809
- stripJsonComments(fs2.readFileSync(path2.join(cwd, "package.json"), "utf8"))
1333
+ stripJsonComments(fs2.readFileSync(path3.join(cwd, "package.json"), "utf8"))
810
1334
  );
811
1335
  const spec = pkg.dependencies?.["codebase-snapshot"] ?? pkg.devDependencies?.["codebase-snapshot"];
812
1336
  if (typeof spec === "string") return `project dependency ${spec}`;
813
1337
  } catch {
814
1338
  }
815
1339
  const entry = process.argv[1] ?? "";
816
- if (entry.includes("_npx") || entry.includes(`${path2.sep}npx${path2.sep}`)) return "via npx";
1340
+ if (entry.includes("_npx") || entry.includes(`${path3.sep}npx${path3.sep}`)) return "via npx";
817
1341
  return "global or direct install";
818
1342
  }
819
1343
  function detectPackageManager(cwd) {
820
- const has = (name) => fs2.existsSync(path2.join(cwd, name));
1344
+ const has = (name) => fs2.existsSync(path3.join(cwd, name));
821
1345
  if (has("bun.lockb") || has("bun.lock")) return { name: "bun", command: "bun", args: ["install"] };
822
1346
  if (has("pnpm-lock.yaml")) return { name: "pnpm", command: "pnpm", args: ["install"] };
823
1347
  if (has("yarn.lock")) return { name: "yarn", command: "yarn", args: ["install"] };
@@ -934,7 +1458,7 @@ async function runSetupCommand(invocation, options = {}) {
934
1458
  }
935
1459
  info("\n\u{1F9EA} Dry run \u2014 setup would:");
936
1460
  info(
937
- ` 1. ${init.reused ? `keep ${path2.basename(keptConfigPath)}` : `write ${path2.basename(keptConfigPath)} (preset: ${appliedPreset})`}`
1461
+ ` 1. ${init.reused ? `keep ${path3.basename(keptConfigPath)}` : `write ${path3.basename(keptConfigPath)} (preset: ${appliedPreset})`}`
938
1462
  );
939
1463
  info(" 2. add the npm scripts, the devDependency and the .gitignore entries");
940
1464
  if (manager !== null) info(` 3. install with ${manager}`);
@@ -947,9 +1471,9 @@ async function runSetupCommand(invocation, options = {}) {
947
1471
  if (invocation.format !== "json") {
948
1472
  if (!interactive) info(`\u{1F680} Setup for: ${invocation.cwd}`);
949
1473
  if (init.reused) {
950
- info(`\u267B Keeping ${path2.basename(keptConfigPath)}`);
1474
+ info(`\u267B Keeping ${path3.basename(keptConfigPath)}`);
951
1475
  } else {
952
- info(`\u2705 Created ${path2.basename(keptConfigPath)} (${presetSummary(init)})`);
1476
+ info(`\u2705 Created ${path3.basename(keptConfigPath)} (${presetSummary(init)})`);
953
1477
  }
954
1478
  if (init.scripts.length > 0) info(` Added npm scripts: ${init.scripts.join(", ")}`);
955
1479
  if (init.dependency.added && init.dependency.range !== null) {
@@ -960,7 +1484,7 @@ async function runSetupCommand(invocation, options = {}) {
960
1484
  }
961
1485
  if (init.briefWritten) {
962
1486
  info(
963
- ` 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.`
1487
+ ` 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.`
964
1488
  );
965
1489
  }
966
1490
  if (hook) for (const note of hook.notes) info(` ${note}`);
@@ -968,7 +1492,7 @@ async function runSetupCommand(invocation, options = {}) {
968
1492
  info(` \u26A0 --preset ${invocation.preset} was not applied: the existing config is kept.`);
969
1493
  }
970
1494
  }
971
- const hasManifest = fs2.existsSync(path2.join(invocation.cwd, "package.json"));
1495
+ const hasManifest = fs2.existsSync(path3.join(invocation.cwd, "package.json"));
972
1496
  let install = null;
973
1497
  if (invocation.noInstall) {
974
1498
  if (invocation.format !== "json") info(" Skipped the install (--no-install)");
@@ -1123,7 +1647,9 @@ function runSkillCommand(invocation) {
1123
1647
  return 0;
1124
1648
  }
1125
1649
  try {
1126
- const result = installSkill(invocation.cwd, invocation.target);
1650
+ const result = installSkill(invocation.cwd, invocation.target, {
1651
+ withMcp: invocation.withMcp
1652
+ });
1127
1653
  if (invocation.format === "json") {
1128
1654
  process.stdout.write(`${JSON.stringify(result, null, 2)}
1129
1655
  `);
@@ -1131,7 +1657,7 @@ function runSkillCommand(invocation) {
1131
1657
  }
1132
1658
  info(`\u2705 Agent skill installed (${SKILL_NAME}):`);
1133
1659
  for (const item of result.written) {
1134
- const shown = path2.relative(invocation.cwd, item.path) || item.path;
1660
+ const shown = path3.relative(invocation.cwd, item.path) || item.path;
1135
1661
  info(` - ${item.action.padEnd(9)} ${shown}`);
1136
1662
  }
1137
1663
  if (result.gitignored.length > 0) {
@@ -1139,9 +1665,13 @@ function runSkillCommand(invocation) {
1139
1665
  info(` Added to .gitignore: ${result.gitignored.join(", ")}`);
1140
1666
  info(" These files are this tool's own documentation, so they stay out of git.");
1141
1667
  }
1668
+ if (result.mcp !== void 0) {
1669
+ const shown = path3.relative(invocation.cwd, result.mcp.path) || result.mcp.path;
1670
+ info(` - ${result.mcp.action.padEnd(9)} ${shown} (codebase-snapshot MCP entry)`);
1671
+ }
1142
1672
  for (const note of result.notes) info(` \u26A0 ${note}`);
1143
1673
  info("");
1144
- info(" Agents that read .claude/skills or .cursor/rules will pick this up automatically.");
1674
+ info(" Agents that read .agents/skills, .claude/skills or .cursor/rules will pick this up automatically.");
1145
1675
  return 0;
1146
1676
  } catch (err) {
1147
1677
  return fail(invocation.format, `Could not install the skill: ${err.message}`);
@@ -1207,6 +1737,78 @@ function guardClosedStdout() {
1207
1737
  throw error;
1208
1738
  });
1209
1739
  }
1740
+ async function readStdin(limit = 1024 * 1024) {
1741
+ const chunks = [];
1742
+ let size = 0;
1743
+ for await (const chunk of process.stdin) {
1744
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
1745
+ size += buffer.length;
1746
+ if (size > limit) throw new Error("the hook payload exceeds 1 MiB");
1747
+ chunks.push(buffer);
1748
+ }
1749
+ return Buffer.concat(chunks).toString("utf8");
1750
+ }
1751
+ async function runGuardCommand(invocation, resolved) {
1752
+ const client = invocation.hook;
1753
+ try {
1754
+ let paths = invocation.paths;
1755
+ let event = "PostToolUse";
1756
+ if (client !== void 0) {
1757
+ const parsed = parseGuardHookInput(client, await readStdin(), resolved.cwd);
1758
+ paths = parsed.paths;
1759
+ event = parsed.event;
1760
+ if (paths.length === 0) {
1761
+ process.stdout.write("{}\n");
1762
+ return 0;
1763
+ }
1764
+ }
1765
+ const changes = resolveImpactChanges(resolved.cwd, {
1766
+ ...paths === void 0 ? { diff: invocation.diff ?? "HEAD" } : { paths }
1767
+ });
1768
+ const manifestPath = path3.resolve(resolved.cwd, resolved.outDir, "manifest.json");
1769
+ let manifest;
1770
+ let trust;
1771
+ if (invocation.noLive) {
1772
+ if (!fs2.existsSync(manifestPath)) {
1773
+ if (client !== void 0) {
1774
+ warn("guard: no snapshot manifest; the hook was skipped.");
1775
+ process.stdout.write("{}\n");
1776
+ return 0;
1777
+ }
1778
+ return fail(
1779
+ invocation.format,
1780
+ "Manifest not found at " + manifestPath + ". Run generate first, or omit --no-live."
1781
+ );
1782
+ }
1783
+ manifest = loadManifest(manifestPath);
1784
+ } else {
1785
+ const live = await buildLiveIndex(resolved, { useDiskCache: !invocation.noCache });
1786
+ manifest = live.manifest;
1787
+ trust = live.trust;
1788
+ }
1789
+ const impact = computeImpact({
1790
+ manifest,
1791
+ cwd: resolved.cwd,
1792
+ changes,
1793
+ manifestPath,
1794
+ ...trust === void 0 ? {} : { trust }
1795
+ });
1796
+ const report = buildGuardReport(impact);
1797
+ if (client !== void 0) {
1798
+ process.stdout.write(renderGuardHook(report, client, event, invocation.maxChars ?? 1200) + "\n");
1799
+ return 0;
1800
+ }
1801
+ emit(invocation.format, report, () => info(renderGuardText(report)));
1802
+ return 0;
1803
+ } catch (err) {
1804
+ if (client !== void 0) {
1805
+ warn("guard: " + err.message + " (hook skipped)");
1806
+ process.stdout.write("{}\n");
1807
+ return 0;
1808
+ }
1809
+ return fail(invocation.format, err.message);
1810
+ }
1811
+ }
1210
1812
  async function main(argv = process.argv.slice(2)) {
1211
1813
  guardClosedStdout();
1212
1814
  const pending = process.stdout.isTTY === true && shouldCheck(argv, process.env) ? checkForUpdate({ current: GENERATOR_VERSION, cacheFile: cacheFilePath() }) : null;
@@ -1294,7 +1896,7 @@ ${USAGE}
1294
1896
  }
1295
1897
  if (invocation.command === "serve") {
1296
1898
  const server = await startWebServer({
1297
- cwd: path2.resolve(invocation.cwd),
1899
+ cwd: path3.resolve(invocation.cwd),
1298
1900
  ...invocation.host === void 0 ? {} : { host: invocation.host },
1299
1901
  ...invocation.port === void 0 ? {} : { port: invocation.port },
1300
1902
  ...tokenOption,
@@ -1309,9 +1911,9 @@ ${USAGE}
1309
1911
  } else {
1310
1912
  warn(" WARNING: --no-auth is on. Any page on this machine can read the repository.");
1311
1913
  }
1312
- await new Promise((resolve2) => {
1914
+ await new Promise((resolve3) => {
1313
1915
  const stop = () => {
1314
- void server.close().then(resolve2);
1916
+ void server.close().then(resolve3);
1315
1917
  };
1316
1918
  process.once("SIGINT", stop);
1317
1919
  process.once("SIGTERM", stop);
@@ -1321,7 +1923,7 @@ ${USAGE}
1321
1923
  if (invocation.command === "mcp") {
1322
1924
  if (invocation.http === true) {
1323
1925
  const transport = await startHttpTransport({
1324
- cwd: path2.resolve(invocation.cwd),
1926
+ cwd: path3.resolve(invocation.cwd),
1325
1927
  noConfig: invocation.noConfig,
1326
1928
  ...invocation.host === void 0 ? {} : { host: invocation.host },
1327
1929
  ...invocation.port === void 0 ? {} : { port: invocation.port },
@@ -1337,9 +1939,9 @@ ${USAGE}
1337
1939
  } else {
1338
1940
  warn(" WARNING: --no-auth is on. Any page on this machine can read the repository.");
1339
1941
  }
1340
- await new Promise((resolve2) => {
1942
+ await new Promise((resolve3) => {
1341
1943
  const stop = () => {
1342
- void transport.close().then(resolve2);
1944
+ void transport.close().then(resolve3);
1343
1945
  };
1344
1946
  process.once("SIGINT", stop);
1345
1947
  process.once("SIGTERM", stop);
@@ -1347,7 +1949,7 @@ ${USAGE}
1347
1949
  return 0;
1348
1950
  }
1349
1951
  return await runStdioServer({
1350
- cwd: path2.resolve(invocation.cwd),
1952
+ cwd: path3.resolve(invocation.cwd),
1351
1953
  noConfig: invocation.noConfig
1352
1954
  });
1353
1955
  }
@@ -1377,7 +1979,7 @@ ${USAGE}
1377
1979
  log: (line) => info(" " + line)
1378
1980
  });
1379
1981
  sourceProvenance = clone.provenance;
1380
- const outDir = path2.resolve(invocation.cwd, invocation.outDir ?? "snapshot");
1982
+ const outDir = path3.resolve(invocation.cwd, invocation.outDir ?? "snapshot");
1381
1983
  invocation = { ...invocation, cwd: clone.directory, outDir, noConfig: true };
1382
1984
  info(
1383
1985
  " Source: " + parsed.source.owner + "/" + parsed.source.repo + "@" + clone.commit.slice(0, 12) + " (fetched " + clone.provenance.fetchedAt + ")"
@@ -1407,7 +2009,7 @@ ${USAGE}
1407
2009
  );
1408
2010
  }
1409
2011
  for (const warning of loaded.warnings) warn(`\u26A0 Config: ${warning}`);
1410
- if (loaded.file) info(`\u2699 Using config ${path2.relative(process.cwd(), loaded.file) || loaded.file}`);
2012
+ if (loaded.file) info(`\u2699 Using config ${path3.relative(process.cwd(), loaded.file) || loaded.file}`);
1411
2013
  let resolved;
1412
2014
  try {
1413
2015
  resolved = resolveConfig(
@@ -1418,6 +2020,9 @@ ${USAGE}
1418
2020
  } catch (err) {
1419
2021
  return fail(invocation.format, err.message);
1420
2022
  }
2023
+ if (invocation.command === "guard") {
2024
+ return await runGuardCommand(invocation, resolved);
2025
+ }
1421
2026
  if (invocation.command === "validate") {
1422
2027
  const result = validateSnapshot(resolved);
1423
2028
  emit(invocation.format, result, () => renderValidateText(result));
@@ -1425,8 +2030,8 @@ ${USAGE}
1425
2030
  }
1426
2031
  if (invocation.command === "health") {
1427
2032
  if (invocation.allMembers === true) {
1428
- const outRoot = path2.resolve(resolved.cwd, resolved.outDir);
1429
- const indexPath = path2.join(outRoot, "WORKSPACE.json");
2033
+ const outRoot = path3.resolve(resolved.cwd, resolved.outDir);
2034
+ const indexPath = path3.join(outRoot, "WORKSPACE.json");
1430
2035
  if (!fs2.existsSync(indexPath)) {
1431
2036
  return fail(
1432
2037
  invocation.format,
@@ -1445,15 +2050,15 @@ ${USAGE}
1445
2050
  }
1446
2051
  const rows = [];
1447
2052
  const insidePath = (parent, child) => {
1448
- const relative3 = path2.relative(parent, child);
1449
- return relative3 === "" || relative3 !== ".." && !relative3.startsWith(`..${path2.sep}`) && !relative3.startsWith("../") && !path2.isAbsolute(relative3);
2053
+ const relative4 = path3.relative(parent, child);
2054
+ return relative4 === "" || relative4 !== ".." && !relative4.startsWith(`..${path3.sep}`) && !relative4.startsWith("../") && !path3.isAbsolute(relative4);
1450
2055
  };
1451
2056
  for (const member of index.members ?? []) {
1452
2057
  const name = member.name ?? "?";
1453
- const snapshotDir2 = path2.resolve(outRoot, name);
2058
+ const snapshotDir2 = path3.resolve(outRoot, name);
1454
2059
  const repoPath = member.path ?? name;
1455
- const repoDir = path2.resolve(resolved.cwd, repoPath);
1456
- if (name.length === 0 || path2.isAbsolute(name) || name.split(/[\\/]/).includes("..") || !insidePath(outRoot, snapshotDir2) || path2.isAbsolute(repoPath) || repoPath.split(/[\\/]/).includes("..") || !insidePath(resolved.cwd, repoDir)) {
2060
+ const repoDir = path3.resolve(resolved.cwd, repoPath);
2061
+ if (name.length === 0 || path3.isAbsolute(name) || name.split(/[\\/]/).includes("..") || !insidePath(outRoot, snapshotDir2) || path3.isAbsolute(repoPath) || repoPath.split(/[\\/]/).includes("..") || !insidePath(resolved.cwd, repoDir)) {
1457
2062
  rows.push({
1458
2063
  name,
1459
2064
  score: 0,
@@ -1484,7 +2089,7 @@ ${USAGE}
1484
2089
  canonicalSnapshot = snapshotDir2;
1485
2090
  canonicalRepo = repoDir;
1486
2091
  }
1487
- if (!fs2.existsSync(path2.join(snapshotDir2, "manifest.json"))) {
2092
+ if (!fs2.existsSync(path3.join(snapshotDir2, "manifest.json"))) {
1488
2093
  rows.push({ name, score: 0, counts: { pass: 0, warn: 0, fail: 1 }, failed: [], error: "no snapshot at " + snapshotDir2 });
1489
2094
  continue;
1490
2095
  }
@@ -1531,7 +2136,7 @@ ${USAGE}
1531
2136
  if (invocation.strict === true && totals.warn > 0) return 1;
1532
2137
  return 0;
1533
2138
  }
1534
- const snapshotDir = path2.resolve(resolved.cwd, resolved.outDir);
2139
+ const snapshotDir = path3.resolve(resolved.cwd, resolved.outDir);
1535
2140
  const report = auditSnapshot({
1536
2141
  snapshotDir,
1537
2142
  repoDir: resolved.cwd,
@@ -1544,7 +2149,7 @@ ${USAGE}
1544
2149
  return 0;
1545
2150
  }
1546
2151
  if (invocation.command === "report") {
1547
- const manifestPath = path2.resolve(resolved.cwd, resolved.outDir, "manifest.json");
2152
+ const manifestPath = path3.resolve(resolved.cwd, resolved.outDir, "manifest.json");
1548
2153
  if (!fs2.existsSync(manifestPath)) {
1549
2154
  return fail(invocation.format, `Manifest not found at ${manifestPath}. Run generate first.`);
1550
2155
  }
@@ -1607,7 +2212,7 @@ ${USAGE}
1607
2212
  if (manifest.delta !== void 0) {
1608
2213
  const delta = manifest.delta;
1609
2214
  info("\n Selection (delta):");
1610
- info(` - Against: ${path2.basename(delta.base.path)} (${delta.base.fingerprint.slice(0, 12)})`);
2215
+ info(` - Against: ${path3.basename(delta.base.path)} (${delta.base.fingerprint.slice(0, 12)})`);
1611
2216
  info(
1612
2217
  ` - Changed: ${delta.changed.length} changed, ${delta.added.length} added, ${delta.removed.length} removed, ${delta.unchanged.length} unchanged`
1613
2218
  );
@@ -1615,6 +2220,243 @@ ${USAGE}
1615
2220
  });
1616
2221
  return 0;
1617
2222
  }
2223
+ if (invocation.command === "impact") {
2224
+ try {
2225
+ const manifestPath = path3.resolve(resolved.cwd, resolved.outDir, "manifest.json");
2226
+ let manifest;
2227
+ let live = null;
2228
+ if (invocation.noLive) {
2229
+ if (!fs2.existsSync(manifestPath)) {
2230
+ return fail(invocation.format, "Manifest not found at " + manifestPath + ". Run generate first, or omit --no-live.");
2231
+ }
2232
+ manifest = loadManifest(manifestPath);
2233
+ } else {
2234
+ live = await buildLiveIndex(resolved, { useDiskCache: !invocation.noCache });
2235
+ manifest = live.manifest;
2236
+ }
2237
+ const changes = resolveImpactChanges(resolved.cwd, {
2238
+ ...invocation.diff !== void 0 ? { diff: invocation.diff } : invocation.paths !== void 0 ? { paths: invocation.paths } : { diff: "HEAD" }
2239
+ });
2240
+ const report = computeImpact({
2241
+ manifest,
2242
+ cwd: resolved.cwd,
2243
+ changes,
2244
+ manifestPath,
2245
+ ...invocation.depth === void 0 ? {} : { depth: invocation.depth },
2246
+ ...invocation.maxResults === void 0 ? {} : { maxResults: invocation.maxResults },
2247
+ ...live === null ? {} : { trust: live.trust },
2248
+ includeImports: invocation.includeImports,
2249
+ includeCycles: invocation.includeCycles
2250
+ });
2251
+ if (invocation.precise) {
2252
+ const targets = [];
2253
+ const seenTargets = /* @__PURE__ */ new Set();
2254
+ for (const entry of report.changed) {
2255
+ const file = manifest.files.find((candidate) => candidate.relativePath === entry.path);
2256
+ const summary = file?.summary;
2257
+ const exportsList = summary && "exports" in summary && Array.isArray(summary.exports) ? summary.exports : [];
2258
+ for (const symbol of exportsList) {
2259
+ const name = String(symbol);
2260
+ const dedupeKey = entry.path + "\0" + name;
2261
+ if (seenTargets.has(dedupeKey)) continue;
2262
+ seenTargets.add(dedupeKey);
2263
+ targets.push({ symbolName: name, targetPath: entry.path });
2264
+ }
2265
+ }
2266
+ const tsEntries = live === null ? [] : manifest.files.filter((entry) => /\.(?:[cm]?[jt]sx?)$/i.test(entry.relativePath));
2267
+ if (live === null || tsEntries.length === 0) {
2268
+ report.trust.coverage = "partial";
2269
+ report.trust.reasons = [...report.trust.reasons, "--precise needs the live index; pass without --no-live."];
2270
+ } else if (tsEntries.length > DEFAULT_MAX_PROGRAM_FILES) {
2271
+ const reason = "TypeScript compiler pass skipped: " + tsEntries.length + " TS/JS files exceed the " + DEFAULT_MAX_PROGRAM_FILES + "-file cap; fell back to import-binding results";
2272
+ report.trust.coverage = "partial";
2273
+ report.trust.reasons = [.../* @__PURE__ */ new Set([...report.trust.reasons, reason])];
2274
+ report.precise = { references: [], coverage: "partial", reasons: [reason] };
2275
+ } else if (targets.length === 0) {
2276
+ report.precise = { references: [], coverage: report.trust.coverage, reasons: [] };
2277
+ } else {
2278
+ const files = tsEntries.map((entry) => {
2279
+ const body = live?.readRedactedFile(entry.relativePath);
2280
+ return body === null || body === void 0 ? null : { relativePath: entry.relativePath, content: body.text };
2281
+ }).filter((entry) => entry !== null);
2282
+ const found = findMultipleSymbolReferences({
2283
+ root: resolved.cwd,
2284
+ files,
2285
+ targets
2286
+ });
2287
+ const references = [];
2288
+ for (const item of found.results) references.push(...item.references);
2289
+ if (found.coverage === "partial") {
2290
+ report.trust.coverage = "partial";
2291
+ report.trust.reasons = [.../* @__PURE__ */ new Set([...report.trust.reasons, ...found.reasons])];
2292
+ }
2293
+ report.precise = {
2294
+ references,
2295
+ coverage: report.trust.coverage,
2296
+ reasons: found.reasons
2297
+ };
2298
+ }
2299
+ }
2300
+ if (invocation.testsPaths) {
2301
+ if (invocation.runTests && invocation.format !== "text") {
2302
+ return fail(invocation.format, "--run streams test output; use --format text.");
2303
+ }
2304
+ if (!invocation.runTests) {
2305
+ if (invocation.format === "json") {
2306
+ process.stdout.write(JSON.stringify(report.tests.map((entry) => entry.path), null, 2) + "\n");
2307
+ } else {
2308
+ for (const entry of report.tests) process.stdout.write(entry.path + "\n");
2309
+ }
2310
+ return 0;
2311
+ }
2312
+ }
2313
+ if (invocation.runTests) {
2314
+ if (invocation.format !== "text") {
2315
+ return fail(invocation.format, "--run streams test output; use --format text.");
2316
+ }
2317
+ const plan = planTestRun(resolved.cwd, {
2318
+ changedPaths: report.changed.map((entry) => entry.path),
2319
+ testPaths: report.tests.map((entry) => entry.path)
2320
+ });
2321
+ info(renderImpactText(report));
2322
+ if (plan.warning !== void 0) warn("Warning: " + plan.warning);
2323
+ if (plan.kind === "none") {
2324
+ info("No candidate tests were found; nothing was run.");
2325
+ return 0;
2326
+ }
2327
+ info("Running " + plan.kind + ": " + plan.command + " " + plan.args.join(" "));
2328
+ const result = runTestPlan(resolved.cwd, plan);
2329
+ if (result.timedOut) {
2330
+ warn("The test run exceeded its five-minute timeout and was terminated.");
2331
+ return 1;
2332
+ }
2333
+ return result.exitCode ?? 1;
2334
+ }
2335
+ if (invocation.format === "markdown" || invocation.format === "pr-comment") {
2336
+ process.stdout.write(renderImpactMarkdown(report) + "\n");
2337
+ return 0;
2338
+ }
2339
+ emit(invocation.format, report, () => info(renderImpactText(report)));
2340
+ return 0;
2341
+ } catch (err) {
2342
+ return fail(invocation.format, err.message);
2343
+ }
2344
+ }
2345
+ if (invocation.command === "brief") {
2346
+ try {
2347
+ const manifestPath = path3.resolve(resolved.cwd, resolved.outDir, "manifest.json");
2348
+ let manifest;
2349
+ let live = null;
2350
+ if (invocation.noLive) {
2351
+ if (!fs2.existsSync(manifestPath)) {
2352
+ return fail(invocation.format, "Manifest not found at " + manifestPath + ". Run generate first, or omit --no-live.");
2353
+ }
2354
+ manifest = loadManifest(manifestPath);
2355
+ } else {
2356
+ live = await buildLiveIndex(resolved, { useDiskCache: !invocation.noCache });
2357
+ manifest = live.manifest;
2358
+ }
2359
+ const question = invocation.args[0];
2360
+ let changes;
2361
+ if (question === void 0) {
2362
+ changes = briefFromPaths(resolved.cwd, {
2363
+ ...invocation.diff !== void 0 ? { diff: invocation.diff } : invocation.paths !== void 0 ? { paths: invocation.paths } : { diff: "HEAD" }
2364
+ });
2365
+ }
2366
+ let diffText;
2367
+ const diffNotes = [];
2368
+ if (invocation.diff !== void 0 || question === void 0 && invocation.paths === void 0) {
2369
+ const ref = invocation.diff ?? "HEAD";
2370
+ const resolvedBase = resolveDiffBase(resolved.cwd, ref);
2371
+ 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, "--"];
2372
+ const result = spawnSync("git", diffArgs, {
2373
+ cwd: resolved.cwd,
2374
+ encoding: "utf8",
2375
+ shell: false,
2376
+ maxBuffer: 64 * 1024 * 1024
2377
+ });
2378
+ if (result.status === 0) {
2379
+ const reportExcludes = [...resolved.excludePatterns, ...resolved.presetExclude];
2380
+ const filtered = filterAndRedactDiff(result.stdout, resolved.secretRules, {
2381
+ // The diff report generated by `generate` applies the repository's include/exclude
2382
+ // rules; `brief --diff` used to pass only the secret rules, so a tracked file the
2383
+ // config excluded still appeared in the review pack.
2384
+ excluded: (relativePath) => resolved.include.length > 0 && !resolved.include.some((pattern) => matchesExclude(relativePath, pattern)) || reportExcludes.some((pattern) => matchesExclude(relativePath, pattern)) || defaultIgnoreReason(relativePath) !== null
2385
+ });
2386
+ diffText = filtered.text;
2387
+ if (filtered.omittedSensitive > 0) {
2388
+ diffNotes.push(filtered.omittedSensitive + " sensitive file section(s) were omitted from the diff.");
2389
+ }
2390
+ if (filtered.omittedUnparseable > 0) {
2391
+ diffNotes.push(filtered.omittedUnparseable + " unparseable file section(s) were omitted from the diff.");
2392
+ }
2393
+ }
2394
+ }
2395
+ const readBody = (relativePath) => {
2396
+ if (live !== null) {
2397
+ const body = live.readRedactedFile(relativePath);
2398
+ return body === null ? null : body.text;
2399
+ }
2400
+ if (isSensitivePath(relativePath)) return null;
2401
+ const file = manifest.files.find((candidate) => candidate.relativePath === relativePath);
2402
+ if (file === void 0) return null;
2403
+ const snapshotDir = path3.resolve(resolved.cwd, resolved.outDir);
2404
+ const read = readConfinedText(
2405
+ snapshotDir,
2406
+ path3.posix.join("parts", file.part),
2407
+ 16 * 1024 * 1024
2408
+ );
2409
+ if (!read.ok) return null;
2410
+ return findSection(parsePartSections(read.text), relativePath)?.body ?? null;
2411
+ };
2412
+ const brief = buildBrief({
2413
+ cwd: resolved.cwd,
2414
+ manifest,
2415
+ ...question === void 0 ? {} : { question },
2416
+ ...changes === void 0 ? {} : { changes },
2417
+ ...diffText === void 0 ? {} : { diff: diffText },
2418
+ ...diffNotes.length === 0 ? {} : { diffNotes },
2419
+ readBody,
2420
+ secretRules: resolved.secretRules,
2421
+ maxTokens: invocation.maxTokens,
2422
+ linesPerFile: invocation.linesPerFile,
2423
+ includeTests: invocation.includeTestsOnly,
2424
+ prComment: invocation.prComment,
2425
+ ...invocation.depth === void 0 ? {} : { depth: invocation.depth },
2426
+ ...invocation.maxResults === void 0 ? {} : { maxResults: invocation.maxResults },
2427
+ ...live === null ? {} : { trust: live.trust }
2428
+ });
2429
+ if (invocation.out !== void 0) {
2430
+ const written = writeInside(resolved.cwd, invocation.out, brief.markdown);
2431
+ info("Wrote " + path3.relative(resolved.cwd, written));
2432
+ } else if (invocation.format !== "json") {
2433
+ process.stdout.write(brief.markdown);
2434
+ }
2435
+ if (invocation.copy) {
2436
+ copyToClipboard(brief.markdown);
2437
+ info("Copied the brief to the clipboard.");
2438
+ }
2439
+ if (invocation.format === "json") {
2440
+ const trust = live?.trust ?? brief.impact?.trust;
2441
+ process.stdout.write(
2442
+ JSON.stringify(
2443
+ {
2444
+ markdown: brief.markdown,
2445
+ usedTokens: brief.usedTokens,
2446
+ files: brief.files,
2447
+ omitted: brief.omitted,
2448
+ ...trust === void 0 ? {} : { trust }
2449
+ },
2450
+ null,
2451
+ 2
2452
+ ) + "\n"
2453
+ );
2454
+ }
2455
+ return 0;
2456
+ } catch (err) {
2457
+ return fail(invocation.format, err.message);
2458
+ }
2459
+ }
1618
2460
  if (invocation.command === "explain") {
1619
2461
  const result = explainPath(resolved, invocation.args[0]);
1620
2462
  emit(invocation.format, result, () => info(renderExplainText(result)));
@@ -1662,10 +2504,10 @@ ${USAGE}
1662
2504
  "--workspace writes one snapshot per member; --remote, --delta, --slice, --budget-tokens and --sign do not combine with it."
1663
2505
  );
1664
2506
  }
1665
- const outRoot = path2.resolve(invocation.cwd, invocation.outDir ?? "snapshot");
1666
- const workspaceCwd = path2.resolve(invocation.cwd);
1667
- const outRootRelative = path2.relative(outRoot, workspaceCwd);
1668
- if (outRootRelative === "" || outRootRelative !== ".." && !outRootRelative.startsWith(`..${path2.sep}`) && !outRootRelative.startsWith("../") && !path2.isAbsolute(outRootRelative)) {
2507
+ const outRoot = path3.resolve(invocation.cwd, invocation.outDir ?? "snapshot");
2508
+ const workspaceCwd = path3.resolve(invocation.cwd);
2509
+ const outRootRelative = path3.relative(outRoot, workspaceCwd);
2510
+ if (outRootRelative === "" || outRootRelative !== ".." && !outRootRelative.startsWith(`..${path3.sep}`) && !outRootRelative.startsWith("../") && !path3.isAbsolute(outRootRelative)) {
1669
2511
  return fail(
1670
2512
  invocation.format,
1671
2513
  `--workspace refuses --out-dir ${outRoot}: it is the working directory or one of its ancestors.`
@@ -1673,8 +2515,8 @@ ${USAGE}
1673
2515
  }
1674
2516
  const plannedNames = /* @__PURE__ */ new Map();
1675
2517
  for (const member of members) {
1676
- const directory = path2.resolve(invocation.cwd, member);
1677
- const name = path2.basename(directory);
2518
+ const directory = path3.resolve(invocation.cwd, member);
2519
+ const name = path3.basename(directory);
1678
2520
  const previous = plannedNames.get(name);
1679
2521
  if (previous !== void 0) {
1680
2522
  return fail(
@@ -1687,8 +2529,8 @@ ${USAGE}
1687
2529
  const records = [];
1688
2530
  let failed = 0;
1689
2531
  for (const member of members) {
1690
- const directory = path2.resolve(invocation.cwd, member);
1691
- const name = path2.basename(directory);
2532
+ const directory = path3.resolve(invocation.cwd, member);
2533
+ const name = path3.basename(directory);
1692
2534
  let stat;
1693
2535
  try {
1694
2536
  stat = fs2.statSync(directory);
@@ -1708,7 +2550,7 @@ ${USAGE}
1708
2550
  {
1709
2551
  ...generateCliOptions(invocation),
1710
2552
  cwd: directory,
1711
- outDir: path2.join(outRoot, name)
2553
+ outDir: path3.join(outRoot, name)
1712
2554
  },
1713
2555
  directory
1714
2556
  );
@@ -1735,10 +2577,10 @@ ${USAGE}
1735
2577
  for (const entry of record.imports) {
1736
2578
  for (const specifier of entry.imports) {
1737
2579
  if (!specifier.startsWith(".")) continue;
1738
- const resolved2 = path2.resolve(record.path, path2.dirname(entry.path), specifier);
2580
+ const resolved2 = path3.resolve(record.path, path3.dirname(entry.path), specifier);
1739
2581
  for (const other of records) {
1740
2582
  if (other === record) continue;
1741
- const prefix = other.path + path2.sep;
2583
+ const prefix = other.path + path3.sep;
1742
2584
  if (!resolved2.startsWith(prefix) && resolved2 !== other.path) continue;
1743
2585
  const bucket = counts.get(other.name) ?? { count: 0, examples: [] };
1744
2586
  bucket.count += 1;
@@ -1763,12 +2605,12 @@ ${USAGE}
1763
2605
  // Store the member path relative to the workspace cwd, as manifest paths already are.
1764
2606
  members: records.map(({ imports: _imports, ...rest }) => ({
1765
2607
  ...rest,
1766
- path: path2.relative(workspaceCwd, rest.path).split(path2.sep).join("/") || "."
2608
+ path: path3.relative(workspaceCwd, rest.path).split(path3.sep).join("/") || "."
1767
2609
  })),
1768
2610
  links
1769
2611
  };
1770
2612
  if (!invocation.dryRun) {
1771
- const workspacePath = path2.join(outRoot, "WORKSPACE.json");
2613
+ const workspacePath = path3.join(outRoot, "WORKSPACE.json");
1772
2614
  try {
1773
2615
  const stats = fs2.lstatSync(workspacePath);
1774
2616
  if (stats.isSymbolicLink() || !stats.isFile()) {
@@ -1811,8 +2653,8 @@ ${USAGE}
1811
2653
  try {
1812
2654
  let deltaBase;
1813
2655
  if (invocation.delta !== void 0) {
1814
- const basePath = path2.resolve(invocation.cwd, invocation.delta);
1815
- const manifestPath = fs2.existsSync(basePath) && fs2.statSync(basePath).isDirectory() ? path2.join(basePath, "manifest.json") : basePath;
2656
+ const basePath = path3.resolve(invocation.cwd, invocation.delta);
2657
+ const manifestPath = fs2.existsSync(basePath) && fs2.statSync(basePath).isDirectory() ? path3.join(basePath, "manifest.json") : basePath;
1816
2658
  if (!fs2.existsSync(manifestPath)) {
1817
2659
  return fail(invocation.format, "No manifest at " + manifestPath + ". Point --delta at a snapshot directory or its manifest.json.");
1818
2660
  }
@@ -1826,8 +2668,8 @@ ${USAGE}
1826
2668
  if (shape !== null) {
1827
2669
  return fail(invocation.format, manifestPath + " is not a snapshot manifest: " + shape);
1828
2670
  }
1829
- const relativeBase = path2.relative(invocation.cwd, manifestPath).split(path2.sep).join("/");
1830
- const recordedBase = relativeBase === "" || relativeBase === ".." || relativeBase.startsWith(`..${path2.sep}`) || relativeBase.startsWith("../") || path2.isAbsolute(relativeBase) ? path2.basename(manifestPath) : relativeBase;
2671
+ const relativeBase = path3.relative(invocation.cwd, manifestPath).split(path3.sep).join("/");
2672
+ const recordedBase = relativeBase === "" || relativeBase === ".." || relativeBase.startsWith(`..${path3.sep}`) || relativeBase.startsWith("../") || path3.isAbsolute(relativeBase) ? path3.basename(manifestPath) : relativeBase;
1831
2673
  deltaBase = { manifest: base, path: recordedBase };
1832
2674
  info(" Delta base: " + recordedBase + " (" + base.files.length + " files, fingerprint " + base.fingerprint.slice(0, 12) + ")");
1833
2675
  }
@@ -1845,7 +2687,7 @@ ${USAGE}
1845
2687
  ...invocation.sign === true && !invocation.dryRun ? { sign: { key: loadSigningKey() } } : {}
1846
2688
  });
1847
2689
  if (invocation.sign === true && !invocation.dryRun) {
1848
- const signaturePath = path2.resolve(resolved.cwd, resolved.outDir, SIGNATURE_FILE);
2690
+ const signaturePath = path3.resolve(resolved.cwd, resolved.outDir, SIGNATURE_FILE);
1849
2691
  try {
1850
2692
  const record = JSON.parse(fs2.readFileSync(signaturePath, "utf8"));
1851
2693
  info(
@@ -2000,19 +2842,19 @@ function finishWatchRun(state, now) {
2000
2842
  };
2001
2843
  }
2002
2844
  function comparablePath(value) {
2003
- const absolute = path2.resolve(value);
2845
+ const absolute = path3.resolve(value);
2004
2846
  return process.platform === "win32" ? absolute.toLowerCase() : absolute;
2005
2847
  }
2006
2848
  function isSameOrInside(parent, candidate) {
2007
- const relative3 = path2.relative(parent, candidate);
2008
- return relative3 === "" || relative3 !== ".." && !relative3.startsWith(`..${path2.sep}`) && !path2.isAbsolute(relative3);
2849
+ const relative4 = path3.relative(parent, candidate);
2850
+ return relative4 === "" || relative4 !== ".." && !relative4.startsWith(`..${path3.sep}`) && !path3.isAbsolute(relative4);
2009
2851
  }
2010
2852
  function isGeneratedWatchPath(candidate, paths) {
2011
- const absolute = comparablePath(path2.resolve(paths.cwd, candidate));
2012
- const outDir = comparablePath(path2.resolve(paths.cwd, paths.outDir));
2013
- const tmpDir = comparablePath(path2.resolve(paths.cwd, paths.tmpDir));
2853
+ const absolute = comparablePath(path3.resolve(paths.cwd, candidate));
2854
+ const outDir = comparablePath(path3.resolve(paths.cwd, paths.outDir));
2855
+ const tmpDir = comparablePath(path3.resolve(paths.cwd, paths.tmpDir));
2014
2856
  if (isSameOrInside(outDir, absolute) || isSameOrInside(tmpDir, absolute)) return true;
2015
- const offsets = [path2.basename(outDir), path2.basename(tmpDir)].filter((name) => name.length > 0);
2857
+ const offsets = [path3.basename(outDir), path3.basename(tmpDir)].filter((name) => name.length > 0);
2016
2858
  const leftover = absolute.split(/[\\/]+/).some(
2017
2859
  (segment) => offsets.some(
2018
2860
  (name) => segment.startsWith(`${name}.backup-`) || segment.startsWith(`${name}.partial-`)
@@ -2035,8 +2877,8 @@ function decideWatchEvent(state, event, paths) {
2035
2877
  function watchPathsFor(config) {
2036
2878
  return {
2037
2879
  cwd: config.cwd,
2038
- outDir: path2.resolve(config.cwd, config.outDir),
2039
- tmpDir: path2.resolve(config.cwd, config.tmpDir)
2880
+ outDir: path3.resolve(config.cwd, config.outDir),
2881
+ tmpDir: path3.resolve(config.cwd, config.tmpDir)
2040
2882
  };
2041
2883
  }
2042
2884
  function watchSupportProblem(platform = process.platform, version = process.versions.node) {
@@ -2114,7 +2956,7 @@ async function runWatchLoop(invocation, resolved, options) {
2114
2956
  const decision = decideWatchEvent(
2115
2957
  state,
2116
2958
  {
2117
- path: filename ? path2.resolve(resolved.cwd, filename.toString()) : null,
2959
+ path: filename ? path3.resolve(resolved.cwd, filename.toString()) : null,
2118
2960
  now: performance.now()
2119
2961
  },
2120
2962
  paths
@@ -2140,12 +2982,12 @@ async function runWatchLoop(invocation, resolved, options) {
2140
2982
  info(`\u26A0 Watch error: ${err.message}`);
2141
2983
  info(" The watcher may have missed changes. Restart with Ctrl+C if they stop arriving.");
2142
2984
  });
2143
- await new Promise((resolve2) => {
2985
+ await new Promise((resolve3) => {
2144
2986
  const stop = () => {
2145
2987
  stopped = true;
2146
2988
  if (timer) clearTimeout(timer);
2147
2989
  watcher.close();
2148
- resolve2();
2990
+ resolve3();
2149
2991
  };
2150
2992
  process.once("SIGINT", stop);
2151
2993
  process.once("SIGTERM", stop);
@@ -2153,8 +2995,15 @@ async function runWatchLoop(invocation, resolved, options) {
2153
2995
  return 0;
2154
2996
  }
2155
2997
  var entryFile = process.argv[1] ?? "";
2156
- var entryName = path2.basename(entryFile).toLowerCase();
2157
- var invokedDirectly = entryName === "cli.js" || entryName === "cli.cjs";
2998
+ var sameFile = (left, right) => {
2999
+ try {
3000
+ return fs2.realpathSync(path3.resolve(left)) === fs2.realpathSync(path3.resolve(right));
3001
+ } catch {
3002
+ return false;
3003
+ }
3004
+ };
3005
+ var entryName = path3.basename(entryFile).toLowerCase();
3006
+ var invokedDirectly = (entryName === "cli.js" || entryName === "cli.cjs") && entryFile.length > 0 && sameFile(entryFile, fileURLToPath(import.meta.url));
2158
3007
  if (invokedDirectly) {
2159
3008
  void main().then(
2160
3009
  (code) => {