-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
1211 lines (1115 loc) · 59 KB
/
Copy pathcli.ts
File metadata and controls
1211 lines (1115 loc) · 59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from "fs";
import path from "path";
import { execSync } from "child_process";
import { fileURLToPath } from "url";
import chokidar from "chokidar";
import { toSarif } from "./sarif.js";
import {
analyze,
loadConfig,
loadDotenv,
isIgnored,
getChangedLinesForFile,
getPreviousContent,
isGitRepo,
repoRoot,
headSha,
runGate,
explainFinding,
deepReview,
isAiAvailable,
complete,
aiKeyEnv,
describeProvider,
tierCounts,
overallTier,
TIER_ORDER,
reviewChanges,
reviewHistory,
isCommitish,
isValidRange,
getRecallProvider,
initTreeSitter,
reviewGuidelines,
recordLearning,
loadLearnings,
loadMergedLearnings,
mergeLearningStores,
readStoreFile,
applyLearnings,
predictedSignal,
realizedSignal,
graphStatus,
resolveGraphConfig,
makeCodeGraphProvider,
IMPACT_RULES,
shouldShowGraphTip,
recordGraphTipShown,
recordTurn,
hasAstSupport,
} from "./core/index.js";
import { c, formatReport, formatHistory, formatFile, badge, summaryLine } from "./report.js";
import type { HistorySelection } from "./core/types.js";
import { runMcpServer } from "./mcp.js";
import { buildPrReview, resolveGithubContext, postPrReview } from "./github.js";
import { runBench, CORPUS } from "./bench.js";
import { runMarginalSampled, modelRunner, scenariosForMode, SCENARIOS, type SampledResult, type Mode } from "./marginal.js";
import { complianceReport } from "./compliance.js";
import { buildMetrics, agentVerdict } from "./metrics.js";
import { detectProjectDefaults, tailorConfig } from "./scaffold.js";
import type { Finding, AnalyzeResult, Config, Tier } from "./core/types.js";
declare const __DIFFGATE_VERSION__: string;
const CLI_PATH = fileURLToPath(import.meta.url);
const VERSION = typeof __DIFFGATE_VERSION__ !== "undefined" ? __DIFFGATE_VERSION__ : "0.0.0";
// Flags that take a value, so `--flag value` (space-separated) is accepted alongside
// `--flag=value`. Anything not listed here stays a boolean sentinel on bare `--flag`.
const VALUE_FLAGS = new Set([
"agent-mode", "author", "base", "base-url", "delay-ms", "fail-on", "format",
"limit", "max-tokens", "mode", "model", "note", "out", "pr", "provider",
"range", "samples", "scenarios", "session", "since", "temperature", "token-param",
]);
function parseArgs(argv: string[]): { pos: string[]; flags: Record<string, string | true> } {
const flags: Record<string, string | true> = {};
const pos: string[] = [];
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a.startsWith("--")) {
const [k, v] = a.slice(2).split("=");
if (v !== undefined) {
flags[k] = v;
} else if (VALUE_FLAGS.has(k) && i + 1 < argv.length && !argv[i + 1].startsWith("-")) {
flags[k] = argv[++i];
} else {
flags[k] = true;
}
} else if (a.startsWith("-") && a.length > 1) {
flags[a.slice(1)] = true;
} else {
pos.push(a);
}
}
return { pos, flags };
}
function fail(msg: string): never {
console.error(c.red(`✖ ${msg}`));
process.exit(2);
}
/** Validate --fail-on. A typo (`--fail-on=oragne`) must fail loudly, not silently gate at the
* default tier — that would change what blocks without anyone noticing. */
function resolveFailOn(flags: Record<string, string | true>, fallback = "orange"): string {
const raw = flags["fail-on"];
if (raw === undefined) return fallback;
if (raw === true || TIER_ORDER[raw] === undefined) {
fail(`--fail-on expects green|yellow|orange, got ${raw === true ? "no value" : `"${raw}"`}.`);
}
return raw as string;
}
/** Shared gate exit: 1 when findings reach failOn (unless --no-fail). Machine-readable modes
* (--json/--sarif) route through this too so they can't silently exit 0 on a blocked change. */
function exitGate(findings: Finding[], failOn: string, flags: Record<string, string | true>): never {
const failRank = TIER_ORDER[failOn] ?? 2;
const blocked = findings.some((f) => f.blocking || (TIER_ORDER[f.tier] ?? 0) >= failRank);
process.exit(blocked && !flags["no-fail"] ? 1 : 0);
}
function resolveMode(flags: Record<string, string | true>, config: Config): string {
if (flags["staged"]) return "staged";
if (flags["working"]) return "working";
return config.gate.mode || "working";
}
const AGENT_MODES = ["advisory", "gated", "off"] as const;
/** Resolve `--agent-mode=<mode>` (or `--agent-mode mode`), warning on a missing/unknown value.
* Returns undefined → use configured mode. */
function resolveAgentMode(flags: Record<string, string | true>): (typeof AGENT_MODES)[number] | undefined {
const raw = flags["agent-mode"];
if (raw === undefined) return undefined;
if (raw === true) {
console.error(c.yellow("⚠ --agent-mode needs a value: use --agent-mode=advisory|gated|off or --agent-mode advisory|gated|off. Falling back to configured mode."));
return undefined;
}
if (!(AGENT_MODES as readonly string[]).includes(raw)) {
console.error(c.yellow(`⚠ Unknown --agent-mode=${raw}; expected advisory|gated|off. Falling back to configured mode.`));
return undefined;
}
return raw as (typeof AGENT_MODES)[number];
}
async function printAiExplanations(findings: Finding[], files: AnalyzeResult[], config: Config, limit = 8): Promise<void> {
if (!isAiAvailable(config)) {
console.log(c.dim(`\n (AI explanations off — set ai.enabled in .diffgate.json and export $${aiKeyEnv(config)} to enable.)`));
return;
}
const byFile = new Map(files.map((f) => [f.filePath, f]));
const targets = findings.filter((f) => f.tier === "orange" || f.blocking).slice(0, limit);
if (targets.length === 0) return;
console.log(c.bold("\n🤖 AI review") + c.dim(` (${describeProvider(config)})\n`));
for (const finding of targets) {
const file = findFileFor(finding, files);
const fileRes = file ? byFile.get(file.filePath) : undefined;
const snippet = fileRes ? snippetAround(fileRes, finding) : (finding.code || "");
try {
const { text, model } = await explainFinding({
finding,
snippet,
language: fileRes?.language || "text",
config,
});
console.log(` ${badge(finding.tier)} ${c.bold(finding.title)} ${c.dim("(" + model + ")")}`);
console.log(indent(text, 4) + "\n");
} catch (e) {
console.log(c.dim(` (AI explanation failed: ${(e as Error).message})\n`));
}
}
}
function findFileFor(finding: Finding, files: AnalyzeResult[]): AnalyzeResult | undefined {
return files.find((f) => f.findings.includes(finding));
}
async function printDeepReviews(findings: Finding[], files: AnalyzeResult[], config: Config, cwd: string, limit = 5): Promise<void> {
if (!isAiAvailable(config)) {
console.log(c.dim(`\n (Deep Review needs AI — set ai.enabled and $${aiKeyEnv(config)}, or use a local provider.)`));
return;
}
const root = repoRoot(cwd) || cwd;
const targets = findings.filter((f) => f.tier === "orange" || f.blocking).slice(0, limit);
if (targets.length === 0) {
console.log(c.dim("\n (No orange findings to deep-review.)"));
return;
}
console.log(c.bold("\n🔬 Deep Review") + c.dim(` (${describeProvider(config)} · agentic)\n`));
for (const f of targets) {
const fileRes = findFileFor(f, files);
if (!fileRes) continue;
const rel = path.relative(root, fileRes.filePath);
console.log(` ${badge(f.tier)} ${c.bold(f.title)} ${c.dim(rel + ":" + f.line)}`);
try {
const res = await deepReview({
finding: f,
filePath: rel,
snippet: snippetAround(fileRes, f, 6),
language: fileRes.language,
cwd: root,
config,
onStep: ({ name, input }) =>
console.log(c.gray(` ⚙ ${name}(${JSON.stringify(input).slice(0, 70)})`)),
});
console.log(c.dim(` ↳ ${res.steps} step(s) · ${res.model}`));
console.log(indent(res.verdict, 4) + "\n");
} catch (e) {
console.log(c.dim(` (deep review failed: ${(e as Error).message})\n`));
}
}
}
function snippetAround(fileRes: AnalyzeResult, finding: Finding, radius = 4): string {
if (!fileRes) return finding.code || "";
try {
const content = fs.readFileSync(fileRes.filePath, "utf-8").split("\n");
const start = Math.max(0, finding.line - 1 - radius);
const end = Math.min(content.length, finding.line + radius);
return content.slice(start, end).join("\n");
} catch {
return finding.code || "";
}
}
function indent(text: string, n: number): string {
const pad = " ".repeat(n);
return text.split("\n").map((l) => pad + l).join("\n");
}
/**
* Decide whether `check` should scan git history instead of the working diff, and resolve the
* selection. History mode triggers on --since/--range/--author/--ai, or a positional that is a
* commit-ish rather than an existing directory. Returns { cwd, sel } or null (→ working-diff mode).
*/
function resolveHistorySelection(
pos: string[],
flags: Record<string, string | true>
): { cwd: string; sel: HistorySelection } | null {
const p0 = pos[0];
const p0IsDir = !!p0 && fs.existsSync(p0) && (() => { try { return fs.statSync(p0).isDirectory(); } catch { return false; } })();
const cwd = path.resolve(p0IsDir ? (p0 as string) : ".");
// A positional that isn't an existing dir but resolves to a commit → single-commit review.
const commit = !p0IsDir && p0 && isCommitish(cwd, p0) ? p0 : undefined;
const since = typeof flags["since"] === "string" ? (flags["since"] as string) : undefined;
const range = typeof flags["range"] === "string" ? (flags["range"] as string) : undefined;
const author = typeof flags["author"] === "string" ? (flags["author"] as string) : undefined;
// `--ai-authored` (not `--ai` — that's reserved for AI explanations) filters to agent commits.
const ai = !!flags["ai-authored"];
const limit = typeof flags["limit"] === "string" ? Math.max(1, parseInt(flags["limit"] as string, 10) || 50) : undefined;
if (!commit && !since && !range && !author && !ai) return null;
const sel: HistorySelection = { commit, since, range, author, ai, ...(limit ? { limit } : {}) };
return { cwd, sel };
}
async function cmdHistory(cwd: string, sel: HistorySelection, flags: Record<string, string | true>): Promise<void> {
// Exit 2, not a warn-and-pass: a gate that reports "clean" because it never ran is a false pass.
if (!isGitRepo(cwd)) {
fail(`Not a git repository: ${cwd} — \`diffgate check --since/--range/--author\` audits commit history and needs one.`);
}
if (sel.range && !isValidRange(cwd, sel.range)) {
fail(`--range does not resolve: "${sel.range}". A bad range would silently scan 0 commits and pass.`);
}
// Validate --fail-on up front so a typo fails before the scan, not after.
const failOn = flags["fail-on"] !== undefined ? resolveFailOn(flags) : undefined;
const result = reviewHistory(cwd, sel);
if (flags["json"]) {
const out = result.commits.map((r) => ({
sha: r.commit.sha,
shortSha: r.commit.shortSha,
author: r.commit.author,
email: r.commit.email,
coAuthors: r.commit.coAuthors,
date: r.commit.date,
subject: r.commit.subject,
tier: r.tier,
counts: r.counts,
blocking: r.blocking,
findings: r.files.flatMap((f) => f.findings.map((fd) => ({ file: path.relative(cwd, f.filePath) || f.filePath, ...fd }))),
}));
console.log(JSON.stringify({ scanned: result.scanned, withFindings: result.withFindings, commits: out }, null, 2));
} else {
console.log(formatHistory(result, cwd));
}
// History mode is report-only (auditing the past, not gating a commit): exit 0 unless the caller
// explicitly asks to fail with --fail-on. Applies to --json output too.
if (failOn !== undefined) {
const failRank = TIER_ORDER[failOn] ?? 2;
const blocked = result.commits.some((r) => r.files.some((f) => f.findings.some((fd) => fd.blocking || (TIER_ORDER[fd.tier] ?? 0) >= failRank)));
if (!flags["json"]) {
console.log("");
console.log(blocked ? c.red(`✖ Findings at/above ${failOn} in history.`) : c.green("✔ No findings at/above threshold."));
}
process.exit(blocked && !flags["no-fail"] ? 1 : 0);
}
}
async function cmdCheck(pos: string[], flags: Record<string, string | true>): Promise<void> {
const hist = resolveHistorySelection(pos, flags);
if (hist) return cmdHistory(hist.cwd, hist.sel, flags);
const cwd = path.resolve(pos[0] || ".");
// A positional that is neither an existing directory nor a commit-ish is a typo, not a workspace.
if (pos[0] && !fs.existsSync(cwd)) {
fail(`No such directory or commit: ${pos[0]}`);
}
// Exit 2, not warn-and-exit-0: in CI a gate that silently doesn't run is a false pass. (This
// also keeps --json stdout parseable — the old warning was printed to stdout.)
if (!isGitRepo(cwd)) {
fail(`Not a git repository: ${cwd} — \`diffgate check\` reviews your git diff. Use \`diffgate scan\` to analyze files directly.`);
}
const { config } = loadConfig(cwd);
const mode = resolveMode(flags, config);
const failOn = resolveFailOn(flags, config.gate.failOn || "orange");
const base = typeof flags["base"] === "string" ? (flags["base"] as string) : undefined;
// An unresolvable base (e.g. origin/main in a shallow CI clone that never fetched it) would make
// `git diff <base>` fail silently → 0 changed files → a false pass. Refuse it loudly instead.
if (base && !isCommitish(cwd, base)) {
fail(`--base ref not found: "${base}". Fetch it first (e.g. \`git fetch origin main\`) — an unresolvable base would silently diff nothing and pass.`);
}
// `--recall` force-enables borrowed recall (semgrep) for this run, overriding the config gate.
// Off otherwise; in CI it activates automatically when `recall.enabled` is "ci".
let recall: NonNullable<Parameters<typeof reviewChanges>[1]>["recall"];
if (flags["recall"]) {
recall = getRecallProvider(cwd, { ...config, recall: { ...(config.recall || {}), enabled: true } });
if (!recall) console.error(c.yellow("⚠ --recall: semgrep not found on PATH — skipping borrowed recall."));
}
const review = reviewChanges(cwd, { mode, base, ...(recall !== undefined ? { recall } : {}) });
const allFindings = review.files.flatMap((f) => f.findings);
if (flags["json"]) {
console.log(JSON.stringify({ mode, ...stripForJson(review) }, null, 2));
exitGate(allFindings, failOn, flags);
}
if (flags["sarif"] || flags["format"] === "sarif") {
console.log(toSarif(review.files, cwd, VERSION));
exitGate(allFindings, failOn, flags);
}
if (flags["github"] || flags["format"] === "github") {
printGithubAnnotations(review.files, cwd);
exitGate(allFindings, failOn, flags);
}
if (flags["agent"]) {
const modeOverride = resolveAgentMode(flags);
const agentCfg = { ...config.gate.agent, ...(modeOverride ? { mode: modeOverride } : {}) };
// Budget enforcement is opt-in (a session id) so CI/one-shot runs stay deterministic. With a
// session, findings that outlast escalateAfterTurns are promoted to a human-review escalation.
const sessionId = typeof flags["session"] === "string" ? (flags["session"] as string) : process.env.DIFFGATE_AGENT_SESSION || undefined;
let overBudget: Set<string> | undefined;
if (sessionId && agentCfg.mode !== "off") {
const root = repoRoot(cwd) || cwd;
const entries = review.files.flatMap((fr) => fr.findings.map((f) => ({ file: fr.filePath, finding: f })));
overBudget = recordTurn(root, sessionId, entries, { escalateAfterTurns: agentCfg.escalateAfterTurns ?? 2 }).overBudget;
}
const v = agentVerdict(review.files, agentCfg, overBudget ? { overBudget } : {});
console.log(JSON.stringify(v, null, 2));
process.exit(v.verdict === "blocked" && !flags["no-fail"] ? 1 : 0);
}
if (flags["pr"] || flags["pr-dry-run"]) {
await runPrReview(review.files, cwd, config, flags);
return;
}
console.log(formatReport(review.files, review, cwd));
console.log(c.dim(`\n diff mode: ${mode}`));
maybeGraphTip(review.files, config, cwd);
if (flags["deep"]) await printDeepReviews(allFindings, review.files, config, cwd);
else if (flags["ai"]) await printAiExplanations(allFindings, review.files, config);
let gateFailed = false;
if (!flags["no-gate"]) {
const gate = await runGate({ cwd, config, findings: allFindings });
if (gate.ran) {
const gateRes = gate as { success?: boolean; durationMs?: number; code?: number; command?: string; stdout?: string; stderr?: string };
const status = gateRes.success
? c.green(`✓ passed (${((gateRes.durationMs ?? 0) / 1000).toFixed(1)}s)`)
: c.red(`✗ failed (exit ${gateRes.code})`);
console.log(`\n ${c.bold("Gate:")} ${c.dim(config.testCommand ?? "")} — ${status}`);
if (!gateRes.success) {
gateFailed = true;
const out = ((gateRes.stdout || "") + (gateRes.stderr || "")).trim().split("\n").slice(-15).join("\n");
console.log(indent(c.dim(out), 4));
}
}
}
const failRank = TIER_ORDER[failOn] ?? 2;
const tripped = allFindings.some((f) => f.blocking || (TIER_ORDER[f.tier] ?? 0) >= failRank);
const blocked = tripped || gateFailed;
console.log("");
if (blocked) {
const reasons: string[] = [];
if (tripped) reasons.push(`findings at/above ${failOn}`);
if (gateFailed) reasons.push("gate command failed");
console.log(c.red(`✖ Blocked — ${reasons.join(" + ")}.`));
} else {
console.log(c.green("✔ Passed — clear to commit."));
}
process.exit(blocked && !flags["no-fail"] ? 1 : 0);
}
function stripForJson(review: ReturnType<typeof reviewChanges>) {
return {
tier: review.tier,
counts: review.counts,
blocking: review.blocking,
files: review.files.map((f) => ({
file: f.filePath,
language: f.language,
tier: f.tier,
findings: f.findings,
})),
};
}
const BINARY_EXT = new Set([
".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico", ".pdf", ".zip", ".gz", ".tar",
".woff", ".woff2", ".ttf", ".eot", ".mp4", ".mov", ".mp3", ".wasm", ".so", ".dylib",
".class", ".jar", ".lock",
]);
function isProbablyBinary(filePath: string): boolean {
if (BINARY_EXT.has(path.extname(filePath).toLowerCase())) return true;
try {
const fd = fs.openSync(filePath, "r");
const buf = Buffer.alloc(1024);
const n = fs.readSync(fd, buf, 0, 1024, 0);
fs.closeSync(fd);
return buf.subarray(0, n).includes(0);
} catch {
return true;
}
}
function* walkFiles(dir: string, config: Config, root: string): Generator<string> {
let entries: fs.Dirent[] = [];
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
const fp = path.join(dir, entry.name);
if (isIgnored(fp, config, root)) continue;
if (entry.isDirectory()) {
yield* walkFiles(fp, config, root);
} else if (entry.isFile()) {
try {
if (fs.statSync(fp).size > 1024 * 1024) continue;
} catch {
continue;
}
if (isProbablyBinary(fp)) continue;
yield fp;
}
}
}
async function cmdScan(pos: string[], flags: Record<string, string | true>): Promise<void> {
const target = path.resolve(pos[0] || ".");
let stat: fs.Stats | undefined;
try {
stat = fs.statSync(target);
} catch {
fail(`No such file or directory: ${target}`);
}
const baseDir = stat!.isDirectory() ? target : path.dirname(target);
const { config } = loadConfig(baseDir);
const filePaths = stat!.isDirectory()
? [...walkFiles(target, config, target)]
: [target];
// An unreadable/empty target yields 0 files → an empty (passing) report. Say so on stderr so a
// "clean" scan of nothing is distinguishable from a clean scan of code.
if (filePaths.length === 0) {
console.error(c.yellow(`⚠ No scannable files found under ${target} (unreadable, ignored, or binary-only).`));
}
const learnings = loadLearnings(repoRoot(baseDir) || baseDir);
const files: AnalyzeResult[] = [];
for (const fp of filePaths) {
let content: string;
try {
content = fs.readFileSync(fp, "utf-8");
} catch {
continue;
}
const res = applyLearnings(analyze({ filePath: fp, content, config }), learnings);
if (res.findings.length > 0) files.push(res);
}
const allFindings = files.flatMap((f) => f.findings);
const review = { files, counts: tierCounts(allFindings), tier: overallTier(allFindings), blocking: allFindings.some((f) => f.blocking) };
// Scan is report-only by default; --fail-on opts into gating. Validate it before any output.
const failOn = flags["fail-on"] !== undefined ? resolveFailOn(flags) : undefined;
if (flags["json"]) {
console.log(JSON.stringify(stripForJson({ ...review, config }), null, 2));
if (failOn !== undefined) exitGate(allFindings, failOn, flags);
return;
}
const reviewCwd = stat!.isDirectory() ? target : baseDir;
if (flags["sarif"] || flags["format"] === "sarif") {
console.log(toSarif(files, reviewCwd, VERSION));
if (failOn !== undefined) exitGate(allFindings, failOn, flags);
return;
}
console.log(formatReport(files, review, reviewCwd));
if (flags["deep"]) await printDeepReviews(allFindings, files, config, reviewCwd);
else if (flags["ai"]) await printAiExplanations(allFindings, files, config);
if (failOn !== undefined) exitGate(allFindings, failOn, flags);
}
function cmdWatch(pos: string[], _flags: Record<string, string | true>): void {
const cwd = path.resolve(pos[0] || ".");
const { config, path: cfgPath } = loadConfig(cwd);
const git = isGitRepo(cwd);
console.log(c.bold("🛡 DiffGate — live review") + c.dim(` watching ${cwd}`));
console.log(c.dim(
` ${cfgPath ? "config: " + path.relative(cwd, cfgPath) : "no .diffgate.json (defaults)"} · ` +
`${git ? "diff-aware (vs HEAD)" : "whole-file (not a git repo)"} · Ctrl-C to stop`
));
console.log(c.gray(" " + "─".repeat(70)));
const watcher = chokidar.watch(cwd, {
// Share the engine's ignore policy so we don't watch build/cache output dirs (.next, out,
// __pycache__, target, …). The leading-dot regex covers ad-hoc dot-dirs as a backstop.
ignored: [/(^|[\/\\])\../, ...(config.ignore || [])],
ignoreInitial: true,
persistent: true,
});
watcher.on("change", async (fp: string) => {
if (isIgnored(fp, config, cwd)) return;
let content: string;
try {
content = fs.readFileSync(fp, "utf-8");
} catch {
return;
}
const changedLines = git ? getChangedLinesForFile(cwd, fp, { mode: "working" }) : null;
const previousContent = git ? getPreviousContent(cwd, fp, { mode: "working" }) : null;
const res = analyze({ filePath: fp, content, previousContent, changedLines, config });
const t = new Date().toLocaleTimeString();
if (res.findings.length === 0) {
console.log(`${c.gray(t)} ${badge("green")} ${c.dim(path.relative(cwd, fp))} — clear`);
return;
}
console.log(`${c.gray(t)} ${path.relative(cwd, fp)} ${summaryLine(res.counts)}`);
console.log(formatFile(res, cwd));
});
watcher.on("error", (e: Error) => console.error(c.red(`watch error: ${e.message}`)));
}
async function cmdExplain(pos: string[], flags: Record<string, string | true>): Promise<void> {
const target = path.resolve(pos[0] || "");
if (!pos[0] || !fs.existsSync(target)) fail("Usage: diffgate explain <file>");
const { config } = loadConfig(path.dirname(target));
if (!isAiAvailable(config)) {
fail(`AI is not configured. Set "ai": { "enabled": true } in .diffgate.json and export $${aiKeyEnv(config)}.`);
}
const content = fs.readFileSync(target, "utf-8");
const res = analyze({ filePath: target, content, config });
if (res.findings.length === 0) {
console.log(c.green("✔ No findings to explain."));
return;
}
console.log(formatReport([res], { counts: res.counts, tier: res.tier }, path.dirname(target)));
if (flags["deep"]) await printDeepReviews(res.findings, [res], config, path.dirname(target));
else await printAiExplanations(res.findings, [res], config, 20);
}
// GitHub Actions workflow-command annotations — render inline on the PR "Files changed" tab.
function ghEscapeData(s: string): string {
return s.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
}
function ghEscapeProp(s: string): string {
return ghEscapeData(s).replace(/,/g, "%2C").replace(/:/g, "%3A");
}
function printGithubAnnotations(files: AnalyzeResult[], cwd: string): void {
const level: Record<string, string> = { orange: "error", yellow: "warning", green: "notice" };
for (const file of files) {
const rel = path.relative(cwd, file.filePath);
for (const f of file.findings) {
const props = [
`file=${ghEscapeProp(rel)}`,
`line=${f.line}`,
f.endLine ? `endLine=${f.endLine}` : "",
`title=${ghEscapeProp("DiffGate: " + f.title)}`,
].filter(Boolean).join(",");
// f.message already carries the blast-radius summary when the impact pass enriched it.
console.log(`::${level[f.tier] || "warning"} ${props}::${ghEscapeData(f.message)}`);
}
}
}
async function runPrReview(files: AnalyzeResult[], cwd: string, config: Config, flags: Record<string, string | true>): Promise<void> {
const failOn = resolveFailOn(flags, config.gate.failOn || "orange") as Tier;
const payload = buildPrReview(files, cwd, { failOn });
const prFlag = typeof flags["pr"] === "string" ? (flags["pr"] as string) : undefined;
const ctx = resolveGithubContext(process.env, prFlag, (p) => {
try { return fs.readFileSync(p, "utf-8"); } catch { return null; }
});
if (!ctx.sha) ctx.sha = headSha(cwd);
if (flags["pr-dry-run"] || !ctx.token) {
if (!flags["pr-dry-run"] && !ctx.token) console.error(c.dim("(no GITHUB_TOKEN — dry-run; showing the payload that would be posted)"));
console.log(JSON.stringify({ context: { repo: ctx.repo, prNumber: ctx.prNumber, sha: ctx.sha, hasToken: !!ctx.token }, ...payload }, null, 2));
} else {
const r = await postPrReview(payload, ctx, fetch as unknown as Parameters<typeof postPrReview>[2]);
if (r.posted) console.log(c.green(`✔ Posted DiffGate review to ${ctx.repo}${ctx.prNumber ? ` PR #${ctx.prNumber}` : ""} (${payload.event})`));
else console.log(c.yellow(`⚠ Did not post: ${r.reason}`));
}
process.exit(payload.blocked && !flags["no-fail"] ? 1 : 0);
}
async function cmdReport(pos: string[], flags: Record<string, string | true>): Promise<void> {
const cwd = path.resolve(pos[0] || ".");
if (!isGitRepo(cwd)) fail("`diffgate report` needs a git repo (it summarizes your diff). Use `diffgate scan` for whole-file analysis.");
const { config } = loadConfig(cwd);
const mode = resolveMode(flags, config);
const base = typeof flags["base"] === "string" ? (flags["base"] as string) : undefined;
if (base && !isCommitish(cwd, base)) {
fail(`--base ref not found: "${base}". Fetch it first — an unresolvable base would silently diff nothing.`);
}
const review = reviewChanges(cwd, { mode, base });
const root = repoRoot(cwd) || cwd;
if (flags["compliance"]) {
const rep = complianceReport(review.files);
if (flags["json"]) { console.log(JSON.stringify(rep, null, 2)); return; }
console.log(c.bold("🛡 DiffGate — SOC 2 control evidence") + c.dim(` (diff mode: ${mode})\n`));
if (rep.evidence.length === 0) {
console.log(c.dim(" No control-relevant findings in the changed lines."));
} else {
for (const e of rep.evidence) {
console.log(` ${c.bold(e.control.id)} ${e.control.title}`);
console.log(` ${c.dim(`${e.findings} finding(s) · ${e.rules.join(", ")}`)}`);
}
}
console.log("");
console.log(c.dim(` The orange gate enforces CC8.1 (changes reviewed before deploy). ${rep.blocked ? c.orange("Gate would block this change.") : "No blocking findings."}`));
if (rep.unmapped.length) console.log(c.dim(` Unmapped findings: ${rep.unmapped.join(", ")}`));
return;
}
const learnings = loadMergedLearnings(root, config.learnings?.shared || [], root);
const m = buildMetrics(review.files, learnings, root);
if (flags["json"]) { console.log(JSON.stringify(m, null, 2)); return; }
console.log(c.bold("🛡 DiffGate — review metrics") + c.dim(` (diff mode: ${mode})\n`));
console.log(` ${summaryLine(m.counts)} ${c.dim(`${m.total} findings across ${m.filesWithFindings} file(s)`)}`);
console.log(` ${m.blocked ? c.red("✖ would block merge") : c.green("✔ clear to merge")}\n`);
if (m.topRules.length) {
console.log(c.bold(" Top rules"));
for (const r of m.topRules) console.log(` ${String(r.count).padStart(3)} × ${r.rule}`);
console.log("");
}
if (m.topFiles.some((f) => f.total > 0)) {
console.log(c.bold(" Hotspot files"));
for (const f of m.topFiles.filter((f) => f.total > 0)) console.log(` ${c.dim(`🟠${f.orange} / ${f.total}`)} ${f.file}`);
console.log("");
}
console.log(c.bold(" Learnings (noise-reduction loop)"));
console.log(` ${m.learnings.dismissed} dismissed · ${m.learnings.confirmed} confirmed · ${m.learnings.total} total`);
if (m.learnings.noisiestRules.length) {
console.log(c.dim(` noisiest: ${m.learnings.noisiestRules.map((r) => `${r.rule}(${r.count})`).join(", ")}`));
}
}
function cmdBench(pos: string[], flags: Record<string, string | true>): void {
const result = runBench(analyze, CORPUS);
if (flags["json"]) { console.log(JSON.stringify(result, null, 2)); return; }
console.log(c.bold("🛡 DiffGate — noise benchmark") + c.dim(` ${result.cases} cases (${result.positives} positive, ${result.cleanCases} clean)\n`));
console.log(c.bold(" rule".padEnd(26) + "prec rec f1 tp/fp/fn"));
for (const r of result.rules) {
console.log(
" " + r.rule.padEnd(24) +
`${pct(r.precision)} ${pct(r.recall)} ${pct(r.f1)} ${c.dim(`${r.tp}/${r.fp}/${r.fn}`)}`
);
}
const o = result.overall;
console.log(c.bold("\n overall".padEnd(26) + `${pct(o.precision)} ${pct(o.recall)} ${pct(o.f1)} ${c.dim(`${o.tp}/${o.fp}/${o.fn}`)}`));
const blocks = result.falseBlocksPerCleanCase;
const blocksStr = `${blocks.toFixed(2)} false BLOCK(s) per clean change`;
console.log(` ${c.bold("Gate noise:")} ${blocks === 0 ? c.green(blocksStr) : c.red(blocksStr)} ${c.dim(`(${result.advisoriesPerCleanCase.toFixed(2)} advisory/clean change)`)}`);
console.log(c.dim("\n Methodology: BENCHMARK.md. Corpus is versioned in src/bench.ts — reproduce with `diffgate bench --json`."));
}
function pct(n: number): string {
return (n * 100).toFixed(0).padStart(3) + "%";
}
async function cmdMarginal(pos: string[], flags: Record<string, string | true>): Promise<void> {
const cwd = pos[0] ? path.resolve(pos[0]) : process.cwd();
const { config: base } = loadConfig(cwd);
// Build the agent's model config: start from any .diffgate.json `ai` block, override with flags.
// Defaults target a local LM Studio endpoint — most privacy-conscious users run a local model.
const provider = (flags["provider"] as string) || base.ai?.provider || "lmstudio";
const baseURL = (flags["base-url"] as string) || base.ai?.baseURL || process.env["DIFFGATE_MARGINAL_BASE_URL"] || undefined;
const model = (flags["model"] as string) || (typeof base.ai?.model === "string" ? base.ai.model : undefined) || process.env["DIFFGATE_MARGINAL_MODEL"];
// Reasoning models (e.g. Qwen on LM Studio) need headroom: a small budget gets consumed by the
// <think> block, leaving no code. Default generously; override with --max-tokens.
const maxTokens = flags["max-tokens"] ? parseInt(flags["max-tokens"] as string, 10) : base.ai?.maxTokens || 4096;
// Sampling for confidence: --samples=K runs each scenario K times; --temperature controls variance.
// K>1 at temperature 0 is pointless (every sample identical) — default to 0.7 when sampling.
const samples = flags["samples"] ? Math.max(1, parseInt(flags["samples"] as string, 10)) : 1;
let temperature =
flags["temperature"] !== undefined ? parseFloat(flags["temperature"] as string)
: base.ai?.temperature ?? (samples > 1 ? 0.7 : 0);
// gpt-5.x / o-series reasoning models reject any non-default temperature (only 1 is supported), so a
// temp-0 or sampling temp would 400 every call. Force 1 for that family; OpenAI samples then carry
// the model's default variance (the local model provides the lower-temperature / tighter-CI anchor).
if (model && /^(gpt-5|o[1-9])/.test(model) && temperature !== 1) {
if (!flags["json"]) process.stderr.write(c.dim(`(${model} only supports the default temperature — using 1 instead of ${temperature})\n`));
temperature = 1;
}
// Which mode(s): greenfield (whole-file generation), edit (edit a seed, analyze changed lines), or both.
const modeFlag = ((flags["mode"] as string) || "greenfield").toLowerCase();
const modes: Mode[] = modeFlag === "both" ? ["greenfield", "edit"] : modeFlag === "edit" ? ["edit"] : ["greenfield"];
// OpenAI's gpt-5.x / o-series reject `max_tokens` — they require `max_completion_tokens`. Pick the
// right param from the model id unless the user pins one with --token-param.
const tokenParam =
(flags["token-param"] as string) || base.ai?.tokenParam ||
(model && /^(gpt-5|o[1-9])/.test(model) ? "max_completion_tokens" : undefined);
// If --provider is explicit, start from a clean ai block: inheriting .diffgate.json's apiKeyEnv /
// model / wire would bind the new provider to the wrong key (e.g. an Anthropic key env for OpenAI).
const inherited = flags["provider"] ? {} : base.ai;
const config = { ...base, ai: { ...inherited, enabled: true, provider, maxTokens, temperature, ...(tokenParam ? { tokenParam } : {}), ...(baseURL ? { baseURL } : {}), ...(model ? { model } : {}) } } as Config;
if (!model) {
fail("No model set. Pass --model=<id> (e.g. --model=qwen/qwen3.5-9b) or set ai.model in .diffgate.json.");
return;
}
// Scenario filtering: --scenarios=id1,id2,... runs only the named subset; --limit=N slices the array.
let scenarios = SCENARIOS;
if (flags["scenarios"]) {
const ids = new Set((flags["scenarios"] as string).split(",").map((s) => s.trim()).filter(Boolean));
scenarios = SCENARIOS.filter((s) => ids.has(s.id));
if (scenarios.length === 0) { fail(`--scenarios filter matched no scenario IDs. Check spelling. Available: ${SCENARIOS.map((s) => s.id).join(", ")}`); return; }
} else if (flags["limit"]) {
scenarios = SCENARIOS.slice(0, parseInt(flags["limit"] as string, 10));
}
const delayMs = flags["delay-ms"] ? parseInt(flags["delay-ms"] as string, 10) : undefined;
const completeFn = async (args: { system: string; prompt: string; config: Partial<Config>; noThink?: boolean }) =>
complete({ system: args.system, prompt: args.prompt, config: args.config, noThink: args.noThink });
const runner = modelRunner(completeFn, config);
const analyzeFn = (a: { filePath: string; content: string; previousContent?: string | null; changedLines?: Set<number> | null; config: Config }) => analyze(a);
const outDir = flags["out"] as string | undefined;
const scen = new Map(SCENARIOS.map((s) => [s.id, s]));
const results: SampledResult[] = [];
for (const mode of modes) {
const n = scenariosForMode(scenarios, mode).length;
if (!flags["json"]) {
const delayNote = delayMs ? c.dim(` (${delayMs}ms delay/scenario)`) : "";
process.stderr.write(c.dim(
`Asking ${c.bold(describeProvider(config))} · ${model} for ${n} ${mode} tasks × ${samples} sample(s) @ temp ${temperature}${delayNote}…\n`));
}
const result = await runMarginalSampled(scenarios, runner, analyzeFn, {
mode, samples, capture: !!outDir, delayMs,
onSample: (i) => { if (!flags["json"] && samples > 1) process.stderr.write(c.dim(` ${mode} sample ${i + 1}/${samples} done\n`)); },
});
if (outDir) {
result.runs.forEach((run, i) => {
const dir = path.join(outDir, mode, `sample-${i + 1}`);
fs.mkdirSync(dir, { recursive: true });
for (const r of run.byScenario) {
if (r.code != null) fs.writeFileSync(path.join(dir, scen.get(r.id)?.filename || `${r.id}.txt`), r.code);
if (r.raw != null) fs.writeFileSync(path.join(dir, `${r.id}.raw.md`), r.raw);
}
});
process.stderr.write(c.dim(`Wrote generated code (${mode}, ${samples} sample(s)) to ${path.join(outDir, mode)}\n`));
}
results.push(result);
}
if (flags["json"]) {
// Keep captured code out of the machine-readable JSON; the files are the artifact.
const json = results.map((r) => ({ ...r, runs: r.runs.map((run) => ({ ...run, byScenario: run.byScenario.map(({ code: _c, raw: _r, ...rest }) => rest) })) }));
console.log(JSON.stringify(json.length === 1 ? json[0] : json, null, 2));
return;
}
for (const result of results) renderMarginal(result, model);
}
function renderMarginal(result: SampledResult, model: string): void {
const pct = (x: number) => `${(x * 100).toFixed(0)}%`;
console.log(c.bold("🛡 DiffGate — marginal-catch experiment") +
c.dim(` ${result.scenarios} ${result.mode} tasks × ${result.samples} sample(s) · agent: ${model}\n`));
for (const a of result.byScenario) {
const freq = a.samples - a.errors > 0 ? `${a.defect}/${a.samples - a.errors}` : "—";
const tag =
a.defect > 0 ? c.orange("DEFECT ") :
a.advisory > 0 ? c.yellow("advisory") :
a.errors === a.samples ? c.yellow("err ") :
c.green("clean ");
const gap = a.knownGap ? c.dim(" [gap]") : "";
const detail = a.knownGap
? c.dim(`clean=${a.clean}/${a.samples - a.errors} — DiffGate has no rule; inspect code`)
: c.dim(`defect ${freq}` + (a.advisory ? `, advisory ${a.advisory}` : ""));
console.log(` ${tag} ${a.id.padEnd(24)}${gap} ${detail}`);
}
const rate = result.defectRate;
const headline = `${pct(rate)} marginal defect-catch rate`;
const colored = rate >= 0.5 ? c.orange(headline) : rate > 0 ? c.yellow(headline) : c.green(headline);
console.log(c.bold("\n " + colored) +
c.dim(` 95% CI [${pct(result.ci.low)}, ${pct(result.ci.high)}] (${result.defectCatches}/${result.trials} non-gap trials shipped unsafe code DiffGate caught)`));
console.log(c.dim(` + ${pct(result.advisoryRate)} advisory rate (auth-crypto / destructive-migration / shell-out) — fire on correct code too, reported separately.`));
if (result.gapClean) console.log(c.dim(` ${result.gapClean} known-gap sample(s) scored clean — DiffGate has no rule; inspect captured code to tell model-safe from a miss.`));
if (result.errors) console.log(c.dim(` ${result.errors} sample(s) errored (model unreachable / empty output).`));
console.log(c.dim("\n Reads as: how often the agent SHIPS unsafe code DiffGate would catch, with no security hint."));
console.log(c.dim(" High ⇒ before-the-diff catches real diffs you'd otherwise see. Low ⇒ the model already avoids these.\n"));
}
async function cmdGuidelines(pos: string[], flags: Record<string, string | true>): Promise<void> {
const cwd = path.resolve(pos[0] || ".");
const mode = flags["staged"] ? "staged" : "working";
// Progress goes to stderr so `--json` stdout stays parseable.
const res = await reviewGuidelines(cwd, { mode, log: (m) => console.error(c.dim(m)) });
if (flags["json"]) { console.log(JSON.stringify(res, null, 2)); return; }
if (res.mode === "host") {
// No model configured — guideline review needs either a provider or an agent host.
if (res.payload.groups.length === 0) { console.log(c.green("✔ No coding-guideline files apply to the changed files.")); return; }
console.log(c.yellow("No AI model configured for guideline review."));
console.log(c.dim(`Found guidelines in: ${res.payload.groups.flatMap((g) => g.sources).join(", ")}`));
console.log(c.dim("Configure ai.* in .diffgate.json, or run DiffGate via an MCP agent (diffgate_guidelines) to evaluate with the agent's own model."));
return;
}
if (res.findings.length === 0) { console.log(c.green("✔ No coding-guideline violations in the changed lines.")); return; }
for (const f of res.findings) {
console.log(`${badge(f.tier)} ${c.bold(f.title)} ${c.dim(f.ruleId)}`);
console.log(` ${f.message}`);
if (f.code) console.log(c.dim(` ${f.line}: ${f.code}`));
}
}
function cmdFeedback(pos: string[], flags: Record<string, string | true>): void {
const ruleId = pos[0];
const fileArg = pos[1];
const lineArg = pos[2];
if (!ruleId || !fileArg || !lineArg) {
fail('Usage: diffgate feedback <ruleId> <file> <line> [--confirm] [--note=...] (default: dismiss as noise)');
}
const abs = path.resolve(fileArg);
if (!fs.existsSync(abs)) fail(`No such file: ${abs}`);
const line = parseInt(lineArg, 10);
if (!Number.isInteger(line) || line < 1) fail(`Invalid line number: ${lineArg}`);
const code = (fs.readFileSync(abs, "utf-8").split("\n")[line - 1] ?? "").trim();
if (!code) fail(`Line ${line} of ${fileArg} is empty — nothing to record.`);
const verdict = flags["confirm"] ? "confirm" : "dismiss";
const root = repoRoot(path.dirname(abs)) || path.dirname(abs);
const entry = recordLearning(root, { ruleId, code, verdict, file: path.relative(root, abs), note: flags["note"] as string });
console.log(c.green(`✔ Recorded ${verdict} for ${c.bold(ruleId)} on ${path.relative(root, abs)}:${line}`));
if (verdict === "dismiss") console.log(c.dim(` This exact flagged code won't be reported again. Stored in .diffgate/learnings.json (${entry.id}).`));
}
function cmdStats(pos: string[], flags: Record<string, string | true>): void {
const cwd = path.resolve(pos[0] || ".");
const root = repoRoot(cwd) || cwd;
const realized = realizedSignal(loadLearnings(root));
let predicted: ReturnType<typeof predictedSignal> | null = null;
if (isGitRepo(cwd)) {
try {
predicted = predictedSignal(reviewChanges(cwd, { mode: resolveMode(flags, loadConfig(cwd).config) }).counts);
} catch {
/* best-effort */
}
}
if (flags["json"]) {
console.log(JSON.stringify({ realized, predicted }, null, 2));
return;
}
console.log(`${c.bold("🛡 DiffGate")} ${c.dim("— signal report")}\n`);
console.log(c.bold("Realized") + c.dim(" (from reviewer verdicts in .diffgate/learnings.json)"));
if (realized.total === 0) {
console.log(c.dim(" No verdicts recorded yet. Run `diffgate feedback <ruleId> <file> <line>` to start measuring.\n"));
} else {
const ratioStr = realized.signalRatio >= 0.6 ? c.green(pct(realized.signalRatio)) : c.orange(pct(realized.signalRatio));
console.log(` ${c.green(realized.confirmed + " confirmed")} · ${c.dim(realized.dismissed + " dismissed")} · signal ratio ${ratioStr}`);
if (realized.chronicNoise.length) {
console.log("\n " + c.bold("Chronically noisy rules") + c.dim(" (high dismiss rate)"));
for (const r of realized.chronicNoise) {
console.log(
` ${c.orange(r.ruleId.padEnd(22))} ${r.dismissed}/${r.total} dismissed ${c.dim("(" + pct(r.dismissRate) + " noise)")} ` +
c.dim(`→ "rules": { "${r.ruleId}": false }`)
);
}
}
console.log("");
}
if (predicted) {
console.log(c.bold("Predicted") + c.dim(" (current diff: 🟠/🟡 = signal, 🟢 = low-signal)"));
console.log(` ${summaryLine({ green: predicted.t3, yellow: predicted.t2, orange: predicted.t1 })} signal ratio ${c.bold(pct(predicted.ratio))}`);
}
}
// One-line, non-nagging nudge for CodeGraph, fading out after a few shows. Two triggers, because
// the value is highest in two cases the deterministic core can't fully serve:
// 1. a public-surface finding (JS/TS) that cross-file blast radius would enrich, or
// 2. findings in a NON-AST language (Python/Go/Java/…), which only get pattern-rule precision
// in-file — exactly the users CodeGraph helps most (cross-file caller/taint across 38+ langs).
// Only fires when graphing is enabled and there is no index yet.
function maybeGraphTip(files: AnalyzeResult[], config: Config, cwd: string): void {
const status = graphStatus(config);
if (!status.enabled || status.indexed) return;
const root = repoRoot(cwd) || cwd;
if (!shouldShowGraphTip(root)) return;
const findings = files.flatMap((f) => f.findings);
const hasImpactFinding = findings.some((f) => IMPACT_RULES.has(f.ruleId));
const nonAstLangs = [...new Set(files.filter((f) => f.findings.length > 0 && !hasAstSupport(f.language)).map((f) => f.language))];
if (!hasImpactFinding && nonAstLangs.length === 0) return;
const how = status.commandFound ? "`diffgate graph index`" : "install CodeGraph, then `diffgate graph index`";
if (!hasImpactFinding && nonAstLangs.length > 0) {
const label = nonAstLangs.length === 1 ? cap(nonAstLangs[0]) : "This codebase";
console.log(c.dim(`\n 💡 Optional: ${label} gets pattern-rule precision in-file. CodeGraph adds cross-file caller & taint analysis (38+ languages) — ${how}.`));
} else {
console.log(c.dim(`\n 💡 Optional: cross-file blast radius is off — ${how} to route reviewers by caller count.`));
}
recordGraphTipShown(root);
}
function cap(s: string): string {
return s.charAt(0).toUpperCase() + s.slice(1);
}
function cmdGraph(pos: string[], flags: Record<string, string | true>): void {
const sub = pos[0] || "status";
const cwd = path.resolve(pos[1] || ".");
const { config } = loadConfig(cwd);
const g = resolveGraphConfig(config);
const status = graphStatus(config);
if (sub === "status") {
if (flags["json"]) { console.log(JSON.stringify(status, null, 2)); return; }
const dot = (ok: boolean) => (ok ? c.green("●") : c.gray("○"));
console.log(`${c.bold("🛡 DiffGate")} ${c.dim("— code graph")}\n`);
console.log(` ${dot(status.enabled)} enabled ${c.dim(status.enabled ? "yes" : "no (graph.enabled=false / mode=off)")}`);
console.log(` ${dot(status.commandFound)} ${("`" + status.command + "`").padEnd(20)} ${c.dim(status.commandFound ? "found on PATH" : "not on PATH")}`);
console.log(` ${dot(status.indexed)} indexed ${c.dim(status.indexed ? status.dbPath : "no index")}`);
console.log(` ${dot(status.reachability)} reachability ${c.dim(status.reachability ? "escalate non-JS injection when reachable from an entry point" : "off")}`);
console.log(`\n ${status.indexed ? c.green("✔ " + status.reason) : c.yellow(status.reason)}`);
return;
}
if (sub === "index") {
if (g.enabled === false || g.mode === "off") {
fail("Graphing is disabled in .diffgate.json (graph.enabled=false / mode=off).");
}
if (!status.commandFound) {
console.log(c.yellow(`✖ ${g.command} not found on PATH.`));
console.log(c.dim("\n Install CodeGraph (github.com/codegraph-ai/CodeGraph), e.g.:"));
console.log(" " + c.bold("npm i -g @codegraph-ai/codegraph") + c.dim(" # or download a release binary"));
console.log(c.dim(` Then re-run ${c.bold("diffgate graph index")}. Set "graph.command" if the binary is named differently.`));
process.exit(1);
}
console.log(c.dim(`Indexing ${cwd} with ${g.command}${flags["full"] ? " (full reindex)" : ""}…`));
const provider = makeCodeGraphProvider(cwd, g);
const ok = typeof provider.reindex === "function" ? provider.reindex({ full: !!flags["full"] }) : false;
if (ok) {
console.log(c.green(`✔ Indexed. Cross-file blast radius is now active for ${path.basename(cwd)}.`));
console.log(c.dim(" CodeGraph keeps the index fresh via filesystem events; re-run after large refactors."));
} else {
console.log(c.yellow("⚠ Index command returned no confirmation."));
console.log(c.dim(` Verify ${g.command} runs standalone, or index manually per CodeGraph's docs. Checked: ${status.dbPath}`));
process.exit(1);
}
return;
}
fail(`Unknown graph subcommand: ${sub}. Use \`diffgate graph status\` or \`diffgate graph index\`.`);
}
const INIT_TEMPLATE = {
testCommand: null,
gate: { mode: "working", failOn: "orange" },
"//testScope": "Down-tier non-exempt orange findings in test/fixture files (orange → yellow, non-blocking) so test scaffolding doesn't block the gate. Secrets & destructive schema stay blocking. Set false to gate test code like prod.",
testScope: true,
ai: { enabled: false, model: "claude-sonnet-4-6", apiKeyEnv: "ANTHROPIC_API_KEY" },