revgraph 0.0.0-stage → 0.1.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.
@@ -0,0 +1,126 @@
1
+ {
2
+ "version": 1,
3
+ "default_excludes": [
4
+ "pnpm-lock.yaml",
5
+ "package-lock.json",
6
+ "yarn.lock",
7
+ "bun.lock",
8
+ "bun.lockb",
9
+ "Cargo.lock",
10
+ "go.sum",
11
+ "poetry.lock",
12
+ "uv.lock",
13
+ "CHANGELOG.md",
14
+ "dist/**",
15
+ "build/**",
16
+ "node_modules/**",
17
+ "target/**",
18
+ ".next/**",
19
+ "coverage/**",
20
+ "*.min.js",
21
+ "*.min.css",
22
+ "*.map",
23
+ "*.png",
24
+ "*.jpg",
25
+ "*.jpeg",
26
+ "*.gif",
27
+ "*.webp",
28
+ "*.ico",
29
+ "*.icns",
30
+ "*.woff",
31
+ "*.woff2",
32
+ "*.ttf",
33
+ "*.otf",
34
+ "*.mp4",
35
+ "*.zip",
36
+ "*.tar.gz",
37
+ "*.pdf"
38
+ ],
39
+ "global_principles": [
40
+ "HIGH SIGNAL ONLY: Report concrete bugs, security vulnerabilities (injection, SSRF, auth bypass, secret leak, path traversal), data loss/corruption, race conditions, or contract/API breakages.",
41
+ "CONCRETE SCENARIO & CONFIDENCE >= 80: Every finding must explain how the failure triggers and carry a 0-100 confidence score. Silently drop anything below 80.",
42
+ "NO LINTER NOISE: Do not report formatting, import ordering, naming preferences, or issues already caught by typecheckers, linters, or formatters. Cap Nit items at 5.",
43
+ "FOLLOW THE GRAPH: Whenever a modified exported symbol changes signature, return shape, nullability, or error semantics, inspect the caller sites listed in the dependency graph before concluding."
44
+ ],
45
+ "static_alerts": [],
46
+ "rules": [
47
+ {
48
+ "id": "ts-js",
49
+ "name": "TypeScript / JavaScript",
50
+ "patterns": [
51
+ "**/*.ts",
52
+ "**/*.tsx",
53
+ "**/*.js",
54
+ "**/*.jsx",
55
+ "**/*.mjs",
56
+ "**/*.cjs"
57
+ ],
58
+ "checklist": [
59
+ "Nullability & runtime types: Check unvalidated external/JSON/API inputs, unsafe type assertions (`as Foo`, non-null `!`), and unhandled `undefined`/`null` access.",
60
+ "Async & lifecycle: Check missing `await`, unhandled promise rejections, stale closures, race conditions in concurrent requests, and leaked timers/listeners/subscriptions on cleanup.",
61
+ "Security: Flag XSS (`dangerouslySetInnerHTML`, unsanitized HTML/URL sinks), prototype pollution, command injection in `exec`/`spawn`, or secrets logged/persisted to client storage."
62
+ ]
63
+ },
64
+ {
65
+ "id": "python",
66
+ "name": "Python",
67
+ "patterns": [
68
+ "**/*.py"
69
+ ],
70
+ "checklist": [
71
+ "State & mutability: Flag mutable default arguments (`def f(x=[])`), shared class-level mutable state, and unclosed resources (files, sockets, DB sessions missing context managers).",
72
+ "Error handling & edge cases: Avoid bare `except:` or silently swallowed exceptions; check `None` handling, off-by-one/empty-input cases, and blocking I/O inside `async def`.",
73
+ "Security: Check SQL string interpolation, `shell=True` subprocess calls, unsafe deserialization (`pickle`, `yaml.load`), path traversal, and SSRF on user-controlled URLs."
74
+ ]
75
+ },
76
+ {
77
+ "id": "go",
78
+ "name": "Go",
79
+ "patterns": [
80
+ "**/*.go"
81
+ ],
82
+ "checklist": [
83
+ "Errors & nil safety: Verify returned errors are checked and not masked; guard nil pointers, nil interface traps, and uninitialized maps before writes.",
84
+ "Concurrency & leaks: Check goroutine leaks (missing context cancellation/channel close), shared-state data races, mutex copy/deadlock, and `defer` inside loops.",
85
+ "Resources & security: Ensure HTTP response bodies, files, and DB rows/statements are closed; check parameterized SQL queries and context propagation."
86
+ ]
87
+ },
88
+ {
89
+ "id": "rust",
90
+ "name": "Rust",
91
+ "patterns": [
92
+ "**/*.rs"
93
+ ],
94
+ "checklist": [
95
+ "Panic safety: Flag `.unwrap()`, `.expect()`, or byte-index string slicing (`&s[..n]` on UTF-8) reachable from user, file, or network input.",
96
+ "Async & locking: Never hold `std::sync::MutexGuard` across `.await`; check lock ordering, channel backpressure, and cancellation safety.",
97
+ "Safety & cleanup: Audit any `unsafe` blocks for soundness invariants; verify partial failures do not corrupt files or leave inconsistent state."
98
+ ]
99
+ },
100
+ {
101
+ "id": "sql-migrations",
102
+ "name": "Database & Migrations",
103
+ "patterns": [
104
+ "**/*.sql",
105
+ "**/migrations/**",
106
+ "**/schema/**"
107
+ ],
108
+ "checklist": [
109
+ "Backward & upgrade safety: Check for destructive column/table drops, missing `DEFAULT` on `NOT NULL` column additions, or table-locking DDL on large tables.",
110
+ "Idempotency & transactions: Verify migrations handle existing production data safely without data loss or broken foreign-key constraints."
111
+ ]
112
+ },
113
+ {
114
+ "id": "ci-shell",
115
+ "name": "CI Workflows & Shell Scripts",
116
+ "patterns": [
117
+ ".github/workflows/**",
118
+ "**/*.sh"
119
+ ],
120
+ "checklist": [
121
+ "Injection & secrets: Flag untrusted GitHub expression interpolation (`${{ github.event.pull_request.title }}`) directly inside `run:` shell commands, overly broad `permissions`, or exposed secrets.",
122
+ "Quoting & failure modes: Check unquoted shell variables, missing `set -euo pipefail`, and unsafe `rm`/path expansion."
123
+ ]
124
+ }
125
+ ]
126
+ }
@@ -0,0 +1,471 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { collectReviewTarget, matchesAnyGlob } from "./git.mjs";
7
+ import { buildDependencyGraph } from "./graph.mjs";
8
+
9
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
10
+ const DEFAULT_RULES_PATH = path.resolve(__dirname, "../references/rules.json");
11
+ const SCHEMA_VERSION = 1;
12
+ const VERSION = "0.1.0";
13
+ const MAX_BG_FILE_BYTES = 1024 * 1024;
14
+ const MAX_BG_CHARS = 8000;
15
+
16
+ function printHelp() {
17
+ console.log(`revgraph v${VERSION} — Zero-build, dependency-graph-aware code review CLI for coding agents
18
+
19
+ Usage:
20
+ revgraph <command> [options]
21
+
22
+ Commands:
23
+ pack Run preview + dependency graph + grouped rules in one shot (Recommended)
24
+ preview Determine review mode, refs, reviewable & excluded files
25
+ graph Build dependency graph, changed-symbol callers & deterministic static checks
26
+ rules [paths...] Resolve matched review rules grouped by rule set
27
+
28
+ Target Options (mutually exclusive; default = workspace changes):
29
+ --pr <num|url> Review a GitHub PR via gh CLI (read-only, never modifies working tree)
30
+ --from <ref> Base ref for branch/range comparison
31
+ --to <ref> Head ref for branch/range comparison (default: HEAD)
32
+ -c, --commit <sha> Review a single commit
33
+
34
+ Shared Options:
35
+ --repo <path> Repository root (default: cwd)
36
+ --rule <path> Custom rules.json path (highest priority; merges with defaults unless extends:false)
37
+ --exclude <globs> Comma-separated extra exclude patterns
38
+ -b, --background <text> Business/PR context note
39
+ -B, --background-file <path> Business context from Markdown file (max 1 MiB / 8000 chars)
40
+ -f, --format <markdown|json> Output format (default: markdown)
41
+ -o, --output <path> Write output to file instead of stdout
42
+ -v, --version Print version
43
+ -h, --help Show this help
44
+ `);
45
+ }
46
+
47
+ function parseArgs(argv) {
48
+ const args = argv.slice(2);
49
+ if (args.length === 0 || args.includes("-h") || args.includes("--help")) {
50
+ printHelp();
51
+ process.exit(0);
52
+ }
53
+ if (args[0] === "-v" || args[0] === "--version") {
54
+ console.log(VERSION);
55
+ process.exit(0);
56
+ }
57
+
58
+ const command = args[0];
59
+ const opts = {
60
+ repo: process.cwd(),
61
+ format: "markdown",
62
+ exclude: [],
63
+ positionals: [],
64
+ };
65
+
66
+ for (let i = 1; i < args.length; i++) {
67
+ const a = args[i];
68
+ const next = () => {
69
+ if (i + 1 >= args.length) throw new Error(`Missing value for flag ${a}`);
70
+ return args[++i];
71
+ };
72
+ if (a === "--pr") opts.pr = next();
73
+ else if (a === "--from") opts.from = next();
74
+ else if (a === "--to") opts.to = next();
75
+ else if (a === "-c" || a === "--commit") opts.commit = next();
76
+ else if (a === "--repo") opts.repo = path.resolve(next());
77
+ else if (a === "--rule") opts.rule = path.resolve(next());
78
+ else if (a === "--exclude") {
79
+ opts.exclude.push(
80
+ ...next()
81
+ .split(",")
82
+ .map((s) => s.trim())
83
+ .filter(Boolean),
84
+ );
85
+ } else if (a === "-b" || a === "--background") opts.background = next();
86
+ else if (a === "-B" || a === "--background-file") opts.backgroundFile = path.resolve(next());
87
+ else if (a === "-f" || a === "--format") opts.format = next();
88
+ else if (a === "-o" || a === "--output") opts.output = path.resolve(next());
89
+ else if (a.startsWith("-")) throw new Error(`Unknown flag: ${a}`);
90
+ else opts.positionals.push(a);
91
+ }
92
+
93
+ if (opts.format !== "markdown" && opts.format !== "json") {
94
+ throw new Error(`Invalid --format "${opts.format}". Expected "markdown" or "json".`);
95
+ }
96
+
97
+ const targetModes = [Boolean(opts.pr), Boolean(opts.commit), Boolean(opts.from || opts.to)].filter(Boolean);
98
+ if (targetModes.length > 1) {
99
+ throw new Error("Target flags --pr, --commit, and --from/--to are mutually exclusive.");
100
+ }
101
+
102
+ return { command, opts };
103
+ }
104
+
105
+ function readJsonFile(filePath) {
106
+ try {
107
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
108
+ } catch (err) {
109
+ throw new Error(`Failed to parse rules file ${filePath}: ${err.message}`);
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Resolve & merge rules across 4 priority tiers:
115
+ * 1. --rule <path>
116
+ * 2. <repo>/.revgraph/rules.json
117
+ * 3. ~/.revgraph/rules.json
118
+ * 4. built-in references/rules.json
119
+ * User/repo configs extend built-in defaults by default; set `"extends": false` to opt out.
120
+ */
121
+ export function loadMergedRules(repoRoot, customRulePath) {
122
+ const builtin = fs.existsSync(DEFAULT_RULES_PATH)
123
+ ? readJsonFile(DEFAULT_RULES_PATH)
124
+ : { default_excludes: [], global_principles: [], static_alerts: [], rules: [] };
125
+
126
+ const userCandidates = [
127
+ path.join(os.homedir(), ".revgraph", "rules.json"),
128
+ path.join(repoRoot, ".revgraph", "rules.json"),
129
+ customRulePath,
130
+ ].filter(Boolean);
131
+
132
+ if (customRulePath && !fs.existsSync(customRulePath)) {
133
+ throw new Error(`Custom rule file not found: ${customRulePath}`);
134
+ }
135
+
136
+ let orderedLayers = fs.existsSync(DEFAULT_RULES_PATH)
137
+ ? [{ source: DEFAULT_RULES_PATH, data: builtin, isBuiltin: true }]
138
+ : [];
139
+
140
+ for (const p of userCandidates) {
141
+ if (!fs.existsSync(p)) continue;
142
+ const data = readJsonFile(p);
143
+ if (data.extends === false) {
144
+ orderedLayers = [{ source: p, data, isBuiltin: false }];
145
+ } else {
146
+ orderedLayers.push({ source: p, data, isBuiltin: false });
147
+ }
148
+ }
149
+
150
+ const sources = orderedLayers.map((l) => l.source);
151
+
152
+ const excludes = [];
153
+ const principles = [];
154
+ const alertMap = new Map();
155
+ const ruleMap = new Map();
156
+
157
+ for (const layer of orderedLayers) {
158
+ const d = layer.data;
159
+ for (const ex of d.default_excludes || d.excludes || []) {
160
+ if (!excludes.includes(ex)) excludes.push(ex);
161
+ }
162
+ for (const pr of d.global_principles || []) {
163
+ if (!principles.includes(pr)) principles.push(pr);
164
+ }
165
+ for (const al of d.static_alerts || []) {
166
+ alertMap.set(al.id || `${al.file || ""}:${al.diff_regex || al.import_regex}`, al);
167
+ }
168
+ for (const r of d.rules || []) {
169
+ const tagged = { ...r, _builtin: Boolean(layer.isBuiltin) };
170
+ // Matching id replaces lower-priority rule
171
+ ruleMap.set(r.id || r.name || JSON.stringify(r.patterns), tagged);
172
+ }
173
+ }
174
+
175
+ return {
176
+ sources,
177
+ data: {
178
+ default_excludes: excludes,
179
+ global_principles: principles,
180
+ static_alerts: Array.from(alertMap.values()),
181
+ rules: Array.from(ruleMap.values()),
182
+ },
183
+ };
184
+ }
185
+
186
+ export function resolveRulesForFiles(filePaths, rulesObj) {
187
+ const grouped = new Map();
188
+ const rules = rulesObj.rules || [];
189
+
190
+ for (const rel of filePaths) {
191
+ const allMatched = rules.filter((r) => matchesAnyGlob(rel, r.patterns || []));
192
+ const hasOverride = allMatched.some((r) => !r._builtin && r.override === true);
193
+ const matched = hasOverride ? allMatched.filter((r) => !r._builtin) : allMatched;
194
+
195
+ const key = matched.map((r) => r.id || r.name).join("+") || "general";
196
+ if (!grouped.has(key)) {
197
+ grouped.set(key, {
198
+ group_id: key,
199
+ rule_names: matched.map((r) => r.name || r.id),
200
+ files: [],
201
+ checklist: matched.flatMap((r) =>
202
+ (r.checklist || []).map((item) => `[${r.id || r.name}] ${item}`),
203
+ ),
204
+ });
205
+ }
206
+ grouped.get(key).files.push(rel);
207
+ }
208
+
209
+ return {
210
+ global_principles: rulesObj.global_principles || [],
211
+ groups: Array.from(grouped.values()),
212
+ };
213
+ }
214
+
215
+ function loadBackground(opts) {
216
+ if (opts.backgroundFile) {
217
+ if (!fs.existsSync(opts.backgroundFile)) {
218
+ throw new Error(`--background-file not found: ${opts.backgroundFile}`);
219
+ }
220
+ const stat = fs.statSync(opts.backgroundFile);
221
+ if (stat.size > MAX_BG_FILE_BYTES) {
222
+ throw new Error(
223
+ `--background-file exceeds 1 MiB limit (${stat.size} bytes). Summarize the context and retry with -b or a smaller file.`,
224
+ );
225
+ }
226
+ const text = fs.readFileSync(opts.backgroundFile, "utf8").trim();
227
+ if (text.length > MAX_BG_CHARS) {
228
+ throw new Error(
229
+ `--background-file exceeds ${MAX_BG_CHARS} character limit (${text.length} chars). Summarize the context and retry.`,
230
+ );
231
+ }
232
+ return text;
233
+ }
234
+ return opts.background ? opts.background.trim() : null;
235
+ }
236
+
237
+ function sanitizeTarget(target) {
238
+ const copy = { ...target };
239
+ delete copy._fallbackDiffMap;
240
+ return copy;
241
+ }
242
+
243
+ function formatMarkdown({ target, graph, rulesResult, background }) {
244
+ const out = [];
245
+ out.push("# revgraph Review Context Pack");
246
+ out.push("");
247
+
248
+ if (target) {
249
+ out.push("## 1. Target & Scope");
250
+ out.push(`- **Mode**: \`${target.mode}\``);
251
+ if (target.pr) {
252
+ out.push(`- **PR**: #${target.pr.number} — ${target.pr.title} (by \`@${target.pr.author}\`)`);
253
+ out.push(`- **URL**: ${target.pr.url}`);
254
+ out.push(`- **Branches**: \`${target.pr.base_ref}\` ← \`${target.pr.head_ref}\``);
255
+ }
256
+ if (target.merge_base) out.push(`- **Merge Base**: \`${target.merge_base}\``);
257
+ if (target.head_git_ref) out.push(`- **Head Git Ref**: \`${target.head_git_ref}\``);
258
+ if (target.commit) out.push(`- **Commit**: \`${target.commit}\``);
259
+ out.push(
260
+ `- **Files**: ${target.reviewable_files.length} reviewable, ${target.excluded_files.length} excluded`,
261
+ );
262
+ if (target.warnings.length > 0) {
263
+ out.push(`- **Warnings**: ${target.warnings.join(" | ")}`);
264
+ }
265
+ out.push("");
266
+
267
+ if (target.pr?.body) {
268
+ out.push("### PR Description");
269
+ out.push(target.pr.body.trim().slice(0, 2000));
270
+ out.push("");
271
+ }
272
+ if (background) {
273
+ out.push("### Background Context");
274
+ out.push(background);
275
+ out.push("");
276
+ }
277
+ }
278
+
279
+ if (graph) {
280
+ out.push("## 2. Deterministic Static Alerts (Pre-LLM)");
281
+ if (graph.static_alerts.length === 0) {
282
+ out.push("- None detected.");
283
+ } else {
284
+ for (const a of graph.static_alerts) {
285
+ const loc = a.line ? `\`${a.file}:${a.line}\`` : `\`${a.file}\``;
286
+ out.push(`- **[${a.severity.toUpperCase()} / ${a.code}]** ${loc}: ${a.message}`);
287
+ }
288
+ }
289
+ out.push("");
290
+
291
+ const tauriNote = graph.stats.tauri_detected ? ", Tauri IPC active" : "";
292
+ out.push(
293
+ `## 3. Dependency & Impact Graph (${graph.stats.indexed_files} source files indexed in ${graph.stats.elapsed_ms}ms${tauriNote})`,
294
+ );
295
+ out.push("```mermaid");
296
+ out.push(graph.mermaid);
297
+ out.push("```");
298
+ out.push("");
299
+
300
+ if (graph.ipc_bridges.length > 0) {
301
+ out.push("### Cross-Language Tauri IPC & Event Bridges");
302
+ for (const b of graph.ipc_bridges) {
303
+ const kind = b.type === "tauri_command" ? "invoke" : "event";
304
+ const reg = b.type === "tauri_command" ? (b.registered ? "registered" : "UNREGISTERED!") : "";
305
+ out.push(
306
+ `- \`${kind}:${b.name}\`${reg ? ` (${reg})` : ""}: \`${b.from_file}:${b.from_line}\` → \`${b.to_file}:${b.to_line}\``,
307
+ );
308
+ }
309
+ out.push("");
310
+ }
311
+
312
+ out.push("### Recommended Review Order (Contracts & Leaf Dependencies First)");
313
+ out.push("| # | Risk | Blast | File | Lang | Why |");
314
+ out.push("|---|------|-------|------|------|-----|");
315
+ for (const r of graph.review_order) {
316
+ out.push(`| ${r.order} | ${r.risk_tier} | ${r.blast_score} | \`${r.path}\` | ${r.lang} | ${r.reason} |`);
317
+ }
318
+ out.push("");
319
+
320
+ out.push("### Changed Symbols & Caller Impact (1-2 Hop)");
321
+ for (const f of graph.files) {
322
+ out.push(
323
+ `#### \`${f.path}\` (${f.status}, +${f.insertions}/-${f.deletions}, blast=${f.blast_score}, callers=${f.upstream_1hop_total} direct / ${f.upstream_2hop_count} 2-hop)`,
324
+ );
325
+ if (f.upstream_1hop.length > 0) {
326
+ const suffix =
327
+ f.upstream_1hop_total > f.upstream_1hop.length
328
+ ? ` (+${f.upstream_1hop_total - f.upstream_1hop.length} more)`
329
+ : "";
330
+ out.push(`- **Imported/Called by**: ${f.upstream_1hop.map((x) => `\`${x}\``).join(", ")}${suffix}`);
331
+ }
332
+ if (f.downstream_1hop.length > 0) {
333
+ const suffix =
334
+ f.downstream_1hop_total > f.downstream_1hop.length
335
+ ? ` (+${f.downstream_1hop_total - f.downstream_1hop.length} more)`
336
+ : "";
337
+ out.push(`- **Depends on**: ${f.downstream_1hop.map((x) => `\`${x}\``).join(", ")}${suffix}`);
338
+ }
339
+ if (f.changed_symbols.length > 0) {
340
+ out.push("- **Changed symbols**:");
341
+ for (const s of f.changed_symbols) {
342
+ const sigTag = s.signature_changed ? " **[SIGNATURE CHANGED]**" : "";
343
+ const callerSummary =
344
+ s.callers.length > 0
345
+ ? ` → callers (${s.total_caller_sites}): ` +
346
+ s.callers.map((c) => `\`${c.file}:${c.line}\`(${c.via})`).join(", ")
347
+ : "";
348
+ out.push(` - \`${s.kind} ${s.name}\` (L${s.lines})${sigTag}${callerSummary}`);
349
+ }
350
+ }
351
+ out.push("");
352
+ }
353
+ }
354
+
355
+ if (target) {
356
+ out.push("## 4. Review Checklist & Diff Commands");
357
+ if (target.reviewable_files.length === 0) {
358
+ out.push("- No reviewable files found.");
359
+ } else {
360
+ for (const f of target.reviewable_files) {
361
+ out.push(`- [ ] \`${f.path}\` (${f.status}, +${f.insertions}/-${f.deletions}) — \`${f.diff_cmd}\``);
362
+ }
363
+ }
364
+ if (target.excluded_files.length > 0) {
365
+ out.push("");
366
+ out.push("<details><summary>Excluded files</summary>");
367
+ out.push("");
368
+ for (const e of target.excluded_files) {
369
+ out.push(`- \`${e.path}\` (${e.reason})`);
370
+ }
371
+ out.push("</details>");
372
+ }
373
+ out.push("");
374
+ }
375
+
376
+ if (rulesResult) {
377
+ out.push("## 5. Matched Review Rules");
378
+ if (rulesResult.global_principles.length > 0) {
379
+ out.push("### Global Principles");
380
+ for (const p of rulesResult.global_principles) out.push(`- ${p}`);
381
+ out.push("");
382
+ }
383
+ for (const g of rulesResult.groups) {
384
+ out.push(`### Rule Group: ${g.rule_names.length > 0 ? g.rule_names.join(" + ") : "General"}`);
385
+ out.push(`- **Files**: ${g.files.map((x) => `\`${x}\``).join(", ")}`);
386
+ for (const item of g.checklist) out.push(`- ${item}`);
387
+ out.push("");
388
+ }
389
+ }
390
+
391
+ return out.join("\n");
392
+ }
393
+
394
+ function main() {
395
+ const { command, opts } = parseArgs(process.argv);
396
+ const background = loadBackground(opts);
397
+ const rulesLoaded = loadMergedRules(opts.repo, opts.rule);
398
+ const excludePatterns = [...(rulesLoaded.data.default_excludes || []), ...opts.exclude];
399
+
400
+ let payload;
401
+ let mdPayload;
402
+
403
+ if (command === "rules") {
404
+ let files = opts.positionals;
405
+ if (files.length === 0) {
406
+ const target = collectReviewTarget(opts.repo, opts, excludePatterns);
407
+ files = target.reviewable_files.map((f) => f.path);
408
+ }
409
+ const rulesResult = resolveRulesForFiles(files, rulesLoaded.data);
410
+ payload = { schema_version: SCHEMA_VERSION, rules_sources: rulesLoaded.sources, ...rulesResult };
411
+ mdPayload = formatMarkdown({ rulesResult });
412
+ } else if (command === "preview") {
413
+ const target = collectReviewTarget(opts.repo, opts, excludePatterns);
414
+ payload = {
415
+ schema_version: SCHEMA_VERSION,
416
+ ...sanitizeTarget(target),
417
+ ...(background ? { background } : {}),
418
+ };
419
+ mdPayload = formatMarkdown({ target, background });
420
+ } else if (command === "graph") {
421
+ const target = collectReviewTarget(opts.repo, opts, excludePatterns);
422
+ const graph = buildDependencyGraph(target, rulesLoaded.data);
423
+ payload = {
424
+ schema_version: SCHEMA_VERSION,
425
+ mode: target.mode,
426
+ ...(target.pr ? { pr: target.pr } : {}),
427
+ graph,
428
+ };
429
+ mdPayload = formatMarkdown({ target, graph, background });
430
+ } else if (command === "pack") {
431
+ const target = collectReviewTarget(opts.repo, opts, excludePatterns);
432
+ const graph = buildDependencyGraph(target, rulesLoaded.data);
433
+ const rulesResult = resolveRulesForFiles(
434
+ target.reviewable_files.map((f) => f.path),
435
+ rulesLoaded.data,
436
+ );
437
+ payload = {
438
+ schema_version: SCHEMA_VERSION,
439
+ ...sanitizeTarget(target),
440
+ ...(background ? { background } : {}),
441
+ rules_sources: rulesLoaded.sources,
442
+ graph,
443
+ rules: rulesResult,
444
+ };
445
+ mdPayload = formatMarkdown({ target, graph, rulesResult, background });
446
+ } else {
447
+ throw new Error(`Unknown command "${command}". Expected one of: pack, preview, graph, rules.`);
448
+ }
449
+
450
+ const rendered = opts.format === "json" ? JSON.stringify(payload, null, 2) + "\n" : mdPayload + "\n";
451
+
452
+ if (opts.output) {
453
+ fs.mkdirSync(path.dirname(opts.output), { recursive: true });
454
+ fs.writeFileSync(opts.output, rendered, "utf8");
455
+ console.log(`Wrote revgraph output to ${opts.output}`);
456
+ } else {
457
+ process.stdout.write(rendered);
458
+ }
459
+ }
460
+
461
+ const isMain =
462
+ process.argv[1] &&
463
+ fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
464
+ if (isMain) {
465
+ try {
466
+ main();
467
+ } catch (err) {
468
+ console.error(`[revgraph] Error: ${err.message}`);
469
+ process.exit(1);
470
+ }
471
+ }