revgraph 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -2
- package/README.zh-CN.md +21 -2
- package/assets/showcase.png +0 -0
- package/package.json +2 -2
- package/skills/revgraph/SKILL.md +40 -15
- package/skills/revgraph/references/rules.json +4 -3
- package/skills/revgraph/scripts/cli.mjs +68 -9
- package/skills/revgraph/scripts/git.mjs +208 -2
- package/skills/revgraph/scripts/graph.mjs +26 -0
- package/skills/revgraph/scripts/parsers/tauri.mjs +30 -9
package/README.md
CHANGED
|
@@ -14,6 +14,13 @@
|
|
|
14
14
|
<p>
|
|
15
15
|
<strong>English</strong> · <a href="./README.zh-CN.md">中文文档</a>
|
|
16
16
|
</p>
|
|
17
|
+
|
|
18
|
+
<p>
|
|
19
|
+
<img src="./assets/showcase.png" alt="RevGraph pack output on farion1231/cc-switch commit dbc7eb713" width="100%" />
|
|
20
|
+
</p>
|
|
21
|
+
<p>
|
|
22
|
+
<sub>Real output from <code>revgraph pack -c dbc7eb713</code> on <a href="https://github.com/farion1231/cc-switch"><code>farion1231/cc-switch</code></a> (1,257 files indexed in 3.4s, 0 npm deps, 0 LLM tokens).</sub>
|
|
23
|
+
</p>
|
|
17
24
|
</div>
|
|
18
25
|
|
|
19
26
|
---
|
|
@@ -33,10 +40,22 @@ Most AI code reviewers read diffs file-by-file in isolation. They miss broken ca
|
|
|
33
40
|
- **Multi-language Dependency & Impact Graph**: Automatic `git ls-files` discovery (respects `.gitignore` and monorepos) with lightweight zero-dependency parsers for **TypeScript / JavaScript**, **Python**, **Go**, and **Rust** — plus **auto-detected Tauri IPC/event bridges** when `src-tauri/` is present.
|
|
34
41
|
- **Changed-Symbol & Caller Tracking**: Flags `[SIGNATURE CHANGED]` symbols and lists 1–2 hop cross-file call sites (`file:line`).
|
|
35
42
|
- **Automatic Bottom-Up Review Order**: Orders contracts/schemas and leaf dependencies before consumers, with tests and docs last.
|
|
36
|
-
- **Deterministic Pre-LLM Alerts**: Catches `BROKEN_IMPORT` (deleted files still imported), declarative project guards via `rules.json` (`diff_regex` / `import_regex`), and Tauri IPC mismatches before spending a single LLM token.
|
|
37
|
-
- **
|
|
43
|
+
- **Deterministic Pre-LLM Alerts**: Catches `BROKEN_IMPORT` (deleted files still imported), `POTENTIAL_OVERLAPPING_PR` (duplicate open PR/Draft detection), `LARGE_PR` scope warnings, declarative project guards via `rules.json` (`diff_regex` / `import_regex`), and Tauri IPC mismatches before spending a single LLM token.
|
|
44
|
+
- **Pre-Review Governance Triage & Premise Gate**: Optional `.revgraph/policy.md` (`--policy`) enables fast-exit 4-way verdicts (`LGTM` / `Request Changes` / `Hold` / `Redirect`) that decouple code quality from merge readiness, plus `Needs Author Verification` so unverified external assumptions are never silently dropped into `LGTM`.
|
|
45
|
+
- **4 Review Modes**: Local workspace (staged + unstaged + untracked), GitHub PR (`--pr <num|url>`, read-only via `gh`, extracts linked issues & overlapping open PRs, never touches your working tree), branch range (`--from..--to`), and single commit (`-c <sha>`).
|
|
38
46
|
- **4-Tier Composable Rules**: Built-in high-signal defaults for TS/JS, Python, Go, Rust, SQL/migrations, and CI/Shell, cleanly extended via `.revgraph/rules.json`.
|
|
39
47
|
|
|
48
|
+
## Real-World Evaluation (10 Merged PRs on `farion1231/cc-switch`)
|
|
49
|
+
|
|
50
|
+
Measured across **10 real cross-language commits** (**167 changed files**, `+7,515 / -709` lines, avg **1,293** indexed source files) in [`farion1231/cc-switch`](https://github.com/farion1231/cc-switch) ([full reproducible report](./docs/benchmark.md)):
|
|
51
|
+
|
|
52
|
+
| Metric | Bare Agent | With RevGraph (`v0.2.1`) | Impact |
|
|
53
|
+
|---|---:|---:|---|
|
|
54
|
+
| **0-Token Pre-LLM Context** | `0` | **19 IPC · 176 sig changes · 242 callers · 5 alerts** | Computed deterministically in **2.9s avg** (0 LLM tokens, 0 FPs) |
|
|
55
|
+
| **Verified Cross-File Bug Recall** | 4 / 4 (`100%`) | **4 / 4 (`100%`)** | Full recall on all verified Rust/TS/security/contract bugs |
|
|
56
|
+
| **Signal Precision (Anti-Noise)** | 19 comments (15 minor nits · **21%** bug ratio) | **8 comments** (0 FPs · **62.5%** bug ratio) | **-57.9% fewer noisy comments** |
|
|
57
|
+
| **Wall-Clock Review Time / PR** | 231.7s avg | **188.4s avg** | **-18.7% faster** (faster on **9 / 10 PRs**, up to **-39%**) |
|
|
58
|
+
|
|
40
59
|
## Used In Production
|
|
41
60
|
|
|
42
61
|
- **[cc-switch](https://github.com/farion1231/cc-switch)** — Used by the `cc-switch` team to review Tauri + Rust + TypeScript pull requests (see [examples/cc-switch.rules.json](./examples/cc-switch.rules.json) for their declarative schema-guard and layer-boundary rules).
|
package/README.zh-CN.md
CHANGED
|
@@ -14,6 +14,13 @@
|
|
|
14
14
|
<p>
|
|
15
15
|
<a href="./README.md">English</a> · <strong>中文文档</strong>
|
|
16
16
|
</p>
|
|
17
|
+
|
|
18
|
+
<p>
|
|
19
|
+
<img src="./assets/showcase.png" alt="RevGraph 在 farion1231/cc-switch 提交 dbc7eb713 上的真实输出" width="100%" />
|
|
20
|
+
</p>
|
|
21
|
+
<p>
|
|
22
|
+
<sub>真实输出示例:在 <a href="https://github.com/farion1231/cc-switch"><code>farion1231/cc-switch</code></a> 上运行 <code>revgraph pack -c dbc7eb713</code>(3.4 秒索引 1,257 个源码文件,0 依赖,0 LLM Token)。</sub>
|
|
23
|
+
</p>
|
|
17
24
|
</div>
|
|
18
25
|
|
|
19
26
|
---
|
|
@@ -25,10 +32,22 @@
|
|
|
25
32
|
- **四语言依赖图 + 自动 Monorepo 发现**:基于 `git ls-files` 自动遵守 `.gitignore`,内置零依赖轻量解析器覆盖 **TypeScript / JavaScript、Python、Go、Rust**;检测到 `src-tauri/` 时自动启用 **Tauri IPC / Event 跨语言桥接检测**(非 Tauri 仓库零开销零噪音)。
|
|
26
33
|
- **变更符号与 1–2 跳调用方追踪**:自动标记 `[SIGNATURE CHANGED]`,列出跨文件调用点(`file:line`)与爆炸半径(Blast Radius)。
|
|
27
34
|
- **自动自底向上 Review 顺序**:按依赖图拓扑顺序先审契约/底层被依赖模块,再审消费方,测试与文档垫底。
|
|
28
|
-
- **Pre-LLM 确定性静态告警**:内置删文件断链检测(`BROKEN_IMPORT`)、`rules.json` 声明式守卫(`diff_regex` / `import_regex`)及可选 Tauri IPC 校验。
|
|
29
|
-
- **4
|
|
35
|
+
- **Pre-LLM 确定性静态告警**:内置删文件断链检测(`BROKEN_IMPORT`)、开放中重复 PR 探测(`POTENTIAL_OVERLAPPING_PR`)、大 PR 提示(`LARGE_PR`)、`rules.json` 声明式守卫(`diff_regex` / `import_regex`)及可选 Tauri IPC 校验。
|
|
36
|
+
- **Pre-Review 治理分诊与前提校验门控**:支持可选 `.revgraph/policy.md`(`--policy`),通过 4 路 Verdict(`LGTM` / `Request Changes` / `Hold` / `Redirect`)与 Fast-Exit 将代码质量与合入策略解耦;引入 `Needs Author Verification`,避免未验证的高风险外部假设被 `<80` 过滤静默吞掉。
|
|
37
|
+
- **4 种评审目标**:本地工作区(staged + unstaged + untracked)、GitHub PR(`--pr <编号|URL>`,只读拉取不碰工作区,自动提取关联 Issue 与重叠 PR)、分支对比(`--from..--to`)、单提交(`-c <sha>`)。
|
|
30
38
|
- **4 级可组合规则**:内置 TS/JS、Python、Go、Rust、SQL 迁移、CI/Shell 高信噪比默认规则,项目通过 `.revgraph/rules.json` 默认追加合并。
|
|
31
39
|
|
|
40
|
+
## 真实仓库实测(`farion1231/cc-switch` 10 个已合并 PR)
|
|
41
|
+
|
|
42
|
+
基于 [`farion1231/cc-switch`](https://github.com/farion1231/cc-switch) 的 **10 个跨语言真实提交**(**167 个改动文件**、`+7,515 / -709` 行、平均索引 **1,293** 个源码文件)实测([完整复现方法与逐 PR 数据](./docs/benchmark.md)):
|
|
43
|
+
|
|
44
|
+
| 指标 | 裸 Agent Review | 挂载 RevGraph (`v0.2.1`) | 实测效果 |
|
|
45
|
+
|---|---:|---:|---|
|
|
46
|
+
| **0-Token 确定性前置上下文** | `0` | **19 条 IPC · 176 签名变更 · 242 调用点 · 5 静态告警** | 均耗时 **2.9s**(0 LLM Token,0 误报) |
|
|
47
|
+
| **跨文件高信号 Bug 召回** | 4 / 4 (`100%`) | **4 / 4 (`100%`)** | 全部 4 个 Rust/TS/安全/契约高信号 Bug 100% 命中 |
|
|
48
|
+
| **有效信号率(反噪音)** | 19 条评论(15 条低价值 Nit · **21%**) | **8 条评论**(0 误报 · **62.5%**) | **噪音降低 57.9%** |
|
|
49
|
+
| **单 PR 评审耗时** | 231.7s 均值 | **188.4s 均值** | **提速 18.7%**(**9 / 10 PR 更快**,最高提速 **39%**) |
|
|
50
|
+
|
|
32
51
|
## 谁在使用
|
|
33
52
|
|
|
34
53
|
- **[cc-switch](https://github.com/farion1231/cc-switch)** — `cc-switch` 团队已将其用于日常 Tauri + Rust + TypeScript PR 评审(完整规则与声明式守卫示例见 [examples/cc-switch.rules.json](./examples/cc-switch.rules.json))。
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "revgraph",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Zero-build, dependency-graph-aware code review CLI and Agent Skill for coding agents",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"node": ">=20.0.0"
|
|
17
17
|
},
|
|
18
18
|
"bin": {
|
|
19
|
-
"revgraph": "
|
|
19
|
+
"revgraph": "skills/revgraph/scripts/cli.mjs"
|
|
20
20
|
},
|
|
21
21
|
"files": [
|
|
22
22
|
"skills/revgraph",
|
package/skills/revgraph/SKILL.md
CHANGED
|
@@ -14,7 +14,7 @@ compatibility: >
|
|
|
14
14
|
Zero build step, zero npm dependencies, zero separate LLM API key — the host
|
|
15
15
|
coding agent performs all semantic reasoning using its own model and tools.
|
|
16
16
|
metadata:
|
|
17
|
-
version: "0.1
|
|
17
|
+
version: "0.2.1"
|
|
18
18
|
inspired_by: https://github.com/alibaba/open-code-review
|
|
19
19
|
---
|
|
20
20
|
|
|
@@ -52,13 +52,17 @@ node <skill-dir>/scripts/cli.mjs pack [target-flags] --format markdown
|
|
|
52
52
|
> - `--background-file` enforces a 1 MiB / 8000-character limit. If rejected, summarize the spec (preserving requirements and constraints) and retry with `-b` instead of silently truncating.
|
|
53
53
|
> - Individual subcommands (`preview`, `graph`, `rules`) are also available when only one stage is needed.
|
|
54
54
|
|
|
55
|
-
### Step 2:
|
|
55
|
+
### Step 2: Governance Triage, Static Alerts & Dependency Graph FIRST
|
|
56
56
|
|
|
57
|
-
Before reading any diff, inspect Sections 2 and
|
|
57
|
+
Before reading any diff, inspect Sections 1, 2, 3, and (if present) Section 5's `Project Policy & Scope Boundaries`:
|
|
58
58
|
|
|
59
|
-
1. **Deterministic Static Alerts**: Verify every `BROKEN_IMPORT`, declarative project rule alert, or auto-detected Tauri IPC alert (`UNREGISTERED_TAURI_COMMAND`, `ORPHAN_TAURI_INVOKE`, `TAURI_IPC_ARG_MISMATCH`) directly in the code.
|
|
59
|
+
1. **Deterministic Static Alerts**: Verify every `BROKEN_IMPORT`, `POTENTIAL_OVERLAPPING_PR`, `LARGE_PR`, declarative project rule alert, or auto-detected Tauri IPC alert (`UNREGISTERED_TAURI_COMMAND`, `ORPHAN_TAURI_INVOKE`, `TAURI_IPC_ARG_MISMATCH`) directly in the code or PR metadata.
|
|
60
60
|
2. **Mermaid Dependency Graph**: Identify high blast-radius files, cross-module edges, and IPC bridges.
|
|
61
61
|
3. **Recommended Review Order**: Follow the bottom-up table order (contracts/schemas → leaf dependencies → consumers → tests → docs) so you understand invariants before reviewing callers.
|
|
62
|
+
4. **Linked Issues & Governance Triage Gate (Fast-Exit Capable)**:
|
|
63
|
+
- Inspect linked Issues/PRs and `Potential Overlapping Open PRs` listed in Section 1 via `gh issue view` / `gh pr view`. Do not treat PR prose or comments on external/reverse-engineered formats as proof of runtime semantics.
|
|
64
|
+
- If the repo provides `.revgraph/policy.md` (or `--policy`) or an earlier open PR/Draft already covers the same scope, evaluate scope/governance BEFORE auditing diffs line by line.
|
|
65
|
+
- **Fast-Exit Rule**: If a PR clearly triggers **`Redirect / Process Gate`** or **`Hold / Needs Maintainer Decision`**, you may stop before full diff auditing (mark unread files `skipped: deferred pending governance/scope decision`), report the governance decision concisely with exact PR/Issue references, and ask whether the user still wants a deep code-only audit.
|
|
62
66
|
|
|
63
67
|
### Step 3: Review Every File with Graph-Guided Context
|
|
64
68
|
|
|
@@ -66,35 +70,42 @@ Maintain a mandatory checklist of every entry in `reviewable_files` using `(path
|
|
|
66
70
|
|
|
67
71
|
For each file in Recommended Review Order:
|
|
68
72
|
|
|
69
|
-
1. **Fetch
|
|
73
|
+
1. **Fetch diffs efficiently** (batch related files in one `git --no-pager` command or follow Section 4 per-file commands; never silently truncate — for huge diffs, redirect with `--output=/tmp/...` and read in chunks, then delete the temp file).
|
|
70
74
|
2. **Apply its matched Rule Group** from Section 5.
|
|
71
|
-
3. **Follow Dependency Graph edges** whenever:
|
|
75
|
+
3. **Follow Dependency Graph edges** (reuse the pack's caller list instead of running redundant repo-wide `grep`s) whenever:
|
|
72
76
|
- A symbol is marked **`[SIGNATURE CHANGED]`** → inspect the listed `callers` (`file:line`) to verify argument order, types, nullability, and error handling still match.
|
|
73
|
-
- A cross-language bridge (e.g. Tauri `invoke` / `event`) changed → inspect both sides of the bridge.
|
|
77
|
+
- A cross-language bridge (e.g. Tauri `invoke` / `event`) or shared state/type contract changed → inspect both sides of the bridge and check whether writers overwrite or drop optional fields read by downstream consumers.
|
|
74
78
|
- A high-blast-radius file changed → read surrounding context (`git --no-pager show <head_git_ref>:<path>` for non-checked-out PR/range/commit targets, or direct file read for workspace mode).
|
|
75
79
|
4. Mark the file `reviewed` (or `skipped: <reason>`). Do not stop after finding the first bug; complete all files.
|
|
76
80
|
|
|
77
|
-
### Step 4: Precision Filtering (Anti-Noise
|
|
81
|
+
### Step 4: Precision Filtering & Premise Gate (Anti-Noise Pass)
|
|
78
82
|
|
|
79
83
|
Audit every candidate finding before reporting:
|
|
80
84
|
|
|
81
|
-
- **Confidence Score (0–100)**: Assign each finding a confidence score. **Silently drop
|
|
82
|
-
- **Concrete Failure Scenario**: Explain *how* the defect triggers (runtime crash, wrong data, security exploit, data loss, broken contract, race condition). Drop speculative "what if" worries.
|
|
85
|
+
- **Confidence Score (0–100) for Code Defects**: Assign each code-defect finding a confidence score. **Silently drop speculative/low-confidence defects below 80.** Never suppress a concrete cross-file contract, field-drop, or state-overwrite bug once you can trace a real broken path across caller and consumer files.
|
|
86
|
+
- **Concrete Failure Scenario**: Explain *how* the defect triggers (runtime crash, wrong data, security exploit, data loss, broken contract, race condition). Drop speculative style/refactor "what if" worries.
|
|
87
|
+
- **Exemption — Unverified High-Risk External Premises**: Do **NOT** apply the `< 80` silent-drop rule to an unverified external assumption (e.g. undocumented upstream API/relay behavior, reverse-engineered client DB/protobuf/JSONL semantics, or metric/timing assumptions lacking empirical proof). Route it to **`Needs Author Verification`** instead of dropping it or approving `LGTM`.
|
|
83
88
|
- **No Linter/Formatter Noise**: Skip formatting, import sorting, style preferences, or issues caught by typecheckers and linters.
|
|
84
89
|
- **Nit Cap**: Cap `Nit` findings at **5** (summarize extras as `+N similar nits`).
|
|
85
90
|
- **Verify against Target Snapshot**: For `--pr`, `--from..--to`, or `-c`, verify line numbers against `<head_git_ref>`, not a stale working tree.
|
|
86
91
|
|
|
87
92
|
### Step 5: Report Format
|
|
88
93
|
|
|
89
|
-
Respond concisely in the user's language (e.g., Chinese if the user wrote Chinese):
|
|
94
|
+
Respond concisely in the user's language (e.g., Chinese if the user wrote Chinese), decoupling **code quality** from **merge readiness** with the 4-way verdict:
|
|
90
95
|
|
|
91
96
|
```markdown
|
|
92
97
|
## Code Review Summary
|
|
93
98
|
|
|
94
99
|
- **Target**: <PR # / branch range / commit / workspace>
|
|
100
|
+
- **Verdict**: <`LGTM` | `Request Changes` | `Hold / Needs Maintainer Decision` | `Redirect / Process Gate`>
|
|
95
101
|
- **Coverage**: X/Y files reviewed (Z skipped: <reasons if any>) | 100% accounted
|
|
96
102
|
- **Blast Radius & Graph Highlights**: <1–3 bullets on key dependency impact>
|
|
97
103
|
|
|
104
|
+
### Governance / Scope Decision *(include when Verdict is `Hold` or `Redirect`)*
|
|
105
|
+
- **Gate Triggered**: `[duplicate-pr | policy-gate | scope-boundary | architectural-direction]`
|
|
106
|
+
- **Rationale**: Concrete policy/scope explanation (acknowledge code strengths objectively if audited).
|
|
107
|
+
- **Recommended Action**: Specific next step with PR/Issue references.
|
|
108
|
+
|
|
98
109
|
### Critical / Blocking
|
|
99
110
|
- **`path/to/file.ts:42`** `[bug | security | contract | concurrency]` `[confidence: 95]`
|
|
100
111
|
- **Impact Path**: `caller.ts:18` → `target.ts:42` (when cross-file)
|
|
@@ -104,12 +115,21 @@ Respond concisely in the user's language (e.g., Chinese if the user wrote Chines
|
|
|
104
115
|
### Important
|
|
105
116
|
...
|
|
106
117
|
|
|
118
|
+
### Needs Author Verification (Blocks LGTM)
|
|
119
|
+
*(Include whenever a high-risk external premise lacks empirical proof; exempt from `< 80` silent drop.)*
|
|
120
|
+
- **`path/to/file.ts:42`** `[premise | external-schema | metrics]`
|
|
121
|
+
- **Unverified Assumption**: What the change assumes about external data or protocol behavior.
|
|
122
|
+
- **Risk if Wrong**: Concrete breakage or distortion.
|
|
123
|
+
- **Evidence Requested**: Exact data/verification needed before approval.
|
|
124
|
+
|
|
107
125
|
### Nit (max 5)
|
|
108
126
|
...
|
|
109
127
|
```
|
|
110
128
|
|
|
111
|
-
- If only `Nit` items remain, lead with
|
|
112
|
-
-
|
|
129
|
+
- **`LGTM`**: ONLY when Governance/Scope passes and `Critical / Blocking`, `Important`, and `Needs Author Verification` are all empty. If only `Nit` items remain, lead with **`No blocking issues.`**
|
|
130
|
+
- **`Request Changes`**: Direction/scope is acceptable, but `Critical / Blocking`, `Important`, or `Needs Author Verification` items must be resolved first.
|
|
131
|
+
- **`Hold / Needs Maintainer Decision`**: Scope or architectural direction needs maintainer sign-off even if the code is clean. Never output `LGTM`.
|
|
132
|
+
- **`Redirect / Process Gate`**: Duplicates an open PR/Draft or skips a mandatory repo policy gate. Never output `LGTM`.
|
|
113
133
|
- Never post GitHub PR approvals/comments or push commits unless the user explicitly asks.
|
|
114
134
|
|
|
115
135
|
### Step 6: Fix Mode (Opt-In Only)
|
|
@@ -117,7 +137,7 @@ Respond concisely in the user's language (e.g., Chinese if the user wrote Chines
|
|
|
117
137
|
- **Default**: Review only — NEVER edit repository files.
|
|
118
138
|
- If the user explicitly asks to **"review and fix"**, apply `Critical` and `Important` fixes directly, re-run relevant checks/tests, and summarize the changes.
|
|
119
139
|
|
|
120
|
-
## Customizing Rules
|
|
140
|
+
## Customizing Rules & Governance Policy
|
|
121
141
|
|
|
122
142
|
Rules merge across 4 priority tiers (highest first):
|
|
123
143
|
1. `--rule <path>`
|
|
@@ -125,4 +145,9 @@ Rules merge across 4 priority tiers (highest first):
|
|
|
125
145
|
3. `~/.revgraph/rules.json`
|
|
126
146
|
4. Built-in `references/rules.json`
|
|
127
147
|
|
|
128
|
-
User/repo configs extend built-in defaults by default. Set `"extends": false`
|
|
148
|
+
User/repo configs extend built-in defaults by default. Set `"extends": false` to disable lower-priority layers, or `"override": true` on an individual rule to replace built-in rules for files matching its patterns.
|
|
149
|
+
|
|
150
|
+
Optional governance policy resolution (first existing file wins):
|
|
151
|
+
1. `--policy <path>`
|
|
152
|
+
2. `<repo>/.revgraph/policy.md`
|
|
153
|
+
3. `~/.revgraph/policy.md`
|
|
@@ -38,9 +38,10 @@
|
|
|
38
38
|
],
|
|
39
39
|
"global_principles": [
|
|
40
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
|
|
41
|
+
"CONCRETE SCENARIO & CONFIDENCE >= 80 (CODE DEFECTS): Every code-defect finding must explain how the failure triggers and carry a 0-100 confidence score; silently drop code defects below 80. EXEMPTION: Do NOT silently drop unverified high-risk external premises (undocumented upstream/client schemas, protocol/timing assumptions, reverse-engineered formats) when local ground truth is absent — route them to `Needs Author Verification` and withhold `LGTM`.",
|
|
42
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."
|
|
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
|
+
"TRIAGE SCOPE & POLICY FIRST: When a project policy (`.revgraph/policy.md`), overlapping open PRs, or a large architectural shift is present, evaluate scope and merge readiness separately from code quality using the 4-way verdict."
|
|
44
45
|
],
|
|
45
46
|
"static_alerts": [],
|
|
46
47
|
"rules": [
|
|
@@ -56,7 +57,7 @@
|
|
|
56
57
|
"**/*.cjs"
|
|
57
58
|
],
|
|
58
59
|
"checklist": [
|
|
59
|
-
"Nullability & runtime types: Check unvalidated external/JSON/API inputs, unsafe type assertions (`as Foo`, non-null `!`),
|
|
60
|
+
"Nullability & runtime types: Check unvalidated external/JSON/API inputs, unsafe type assertions (`as Foo`, non-null `!`), unhandled `undefined`/`null` access, and state writers assigning a narrower base object into an extended/optional-field type (silently erasing optional fields read by downstream consumers).",
|
|
60
61
|
"Async & lifecycle: Check missing `await`, unhandled promise rejections, stale closures, race conditions in concurrent requests, and leaked timers/listeners/subscriptions on cleanup.",
|
|
61
62
|
"Security: Flag XSS (`dangerouslySetInnerHTML`, unsanitized HTML/URL sinks), prototype pollution, command injection in `exec`/`spawn`, or secrets logged/persisted to client storage."
|
|
62
63
|
]
|
|
@@ -9,7 +9,7 @@ import { buildDependencyGraph } from "./graph.mjs";
|
|
|
9
9
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
10
10
|
const DEFAULT_RULES_PATH = path.resolve(__dirname, "../references/rules.json");
|
|
11
11
|
const SCHEMA_VERSION = 1;
|
|
12
|
-
const VERSION = "0.1
|
|
12
|
+
const VERSION = "0.2.1";
|
|
13
13
|
const MAX_BG_FILE_BYTES = 1024 * 1024;
|
|
14
14
|
const MAX_BG_CHARS = 8000;
|
|
15
15
|
|
|
@@ -34,6 +34,8 @@ Target Options (mutually exclusive; default = workspace changes):
|
|
|
34
34
|
Shared Options:
|
|
35
35
|
--repo <path> Repository root (default: cwd)
|
|
36
36
|
--rule <path> Custom rules.json path (highest priority; merges with defaults unless extends:false)
|
|
37
|
+
--policy <path> Custom policy.md path (governance/scope boundaries for pre-review triage)
|
|
38
|
+
--no-overlap-check Skip open-PR overlap scan in --pr mode
|
|
37
39
|
--exclude <globs> Comma-separated extra exclude patterns
|
|
38
40
|
-b, --background <text> Business/PR context note
|
|
39
41
|
-B, --background-file <path> Business context from Markdown file (max 1 MiB / 8000 chars)
|
|
@@ -75,6 +77,8 @@ function parseArgs(argv) {
|
|
|
75
77
|
else if (a === "-c" || a === "--commit") opts.commit = next();
|
|
76
78
|
else if (a === "--repo") opts.repo = path.resolve(next());
|
|
77
79
|
else if (a === "--rule") opts.rule = path.resolve(next());
|
|
80
|
+
else if (a === "--policy") opts.policy = path.resolve(next());
|
|
81
|
+
else if (a === "--no-overlap-check") opts.noOverlapCheck = true;
|
|
78
82
|
else if (a === "--exclude") {
|
|
79
83
|
opts.exclude.push(
|
|
80
84
|
...next()
|
|
@@ -212,6 +216,24 @@ export function resolveRulesForFiles(filePaths, rulesObj) {
|
|
|
212
216
|
};
|
|
213
217
|
}
|
|
214
218
|
|
|
219
|
+
function loadPolicy(repoRoot, customPolicyPath) {
|
|
220
|
+
if (customPolicyPath && !fs.existsSync(customPolicyPath)) {
|
|
221
|
+
throw new Error(`Custom policy file not found: ${customPolicyPath}`);
|
|
222
|
+
}
|
|
223
|
+
const candidates = [
|
|
224
|
+
customPolicyPath,
|
|
225
|
+
path.join(repoRoot, ".revgraph", "policy.md"),
|
|
226
|
+
path.join(os.homedir(), ".revgraph", "policy.md"),
|
|
227
|
+
].filter(Boolean);
|
|
228
|
+
|
|
229
|
+
for (const p of candidates) {
|
|
230
|
+
if (fs.existsSync(p)) {
|
|
231
|
+
return { source: p, text: fs.readFileSync(p, "utf8").trim().slice(0, MAX_BG_CHARS) };
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return { source: null, text: null };
|
|
235
|
+
}
|
|
236
|
+
|
|
215
237
|
function loadBackground(opts) {
|
|
216
238
|
if (opts.backgroundFile) {
|
|
217
239
|
if (!fs.existsSync(opts.backgroundFile)) {
|
|
@@ -240,7 +262,7 @@ function sanitizeTarget(target) {
|
|
|
240
262
|
return copy;
|
|
241
263
|
}
|
|
242
264
|
|
|
243
|
-
function formatMarkdown({ target, graph, rulesResult, background }) {
|
|
265
|
+
function formatMarkdown({ target, graph, rulesResult, policy, background }) {
|
|
244
266
|
const out = [];
|
|
245
267
|
out.push("# revgraph Review Context Pack");
|
|
246
268
|
out.push("");
|
|
@@ -249,9 +271,31 @@ function formatMarkdown({ target, graph, rulesResult, background }) {
|
|
|
249
271
|
out.push("## 1. Target & Scope");
|
|
250
272
|
out.push(`- **Mode**: \`${target.mode}\``);
|
|
251
273
|
if (target.pr) {
|
|
252
|
-
|
|
274
|
+
const stateTag = target.pr.is_draft ? " [DRAFT]" : " [OPEN]";
|
|
275
|
+
out.push(`- **PR**: #${target.pr.number}${stateTag} — ${target.pr.title} (by \`@${target.pr.author}\`)`);
|
|
253
276
|
out.push(`- **URL**: ${target.pr.url}`);
|
|
254
277
|
out.push(`- **Branches**: \`${target.pr.base_ref}\` ← \`${target.pr.head_ref}\``);
|
|
278
|
+
if (target.pr.labels?.length > 0) {
|
|
279
|
+
out.push(`- **Labels**: ${target.pr.labels.map((l) => `\`${l}\``).join(", ")}`);
|
|
280
|
+
}
|
|
281
|
+
if (target.pr.additions || target.pr.deletions) {
|
|
282
|
+
out.push(`- **Diff Size**: +${target.pr.additions}/-${target.pr.deletions} lines`);
|
|
283
|
+
}
|
|
284
|
+
const closing = target.pr.linked_issues?.closing || [];
|
|
285
|
+
const referenced = target.pr.linked_issues?.referenced || [];
|
|
286
|
+
if (closing.length > 0 || referenced.length > 0) {
|
|
287
|
+
const parts = [];
|
|
288
|
+
if (closing.length > 0) parts.push(`closing: ${closing.map((n) => `#${n}`).join(", ")}`);
|
|
289
|
+
if (referenced.length > 0) parts.push(`referenced: ${referenced.map((n) => `#${n}`).join(", ")}`);
|
|
290
|
+
out.push(`- **Linked Issues / PRs**: ${parts.join(" | ")} (inspect via \`gh issue view <N>\` / \`gh pr view <N>\`)`);
|
|
291
|
+
}
|
|
292
|
+
if (target.pr.overlapping_prs?.length > 0) {
|
|
293
|
+
out.push("- **Potential Overlapping Open PRs**:");
|
|
294
|
+
for (const p of target.pr.overlapping_prs) {
|
|
295
|
+
const tag = p.is_draft ? " [Draft]" : "";
|
|
296
|
+
out.push(` - #${p.number}${tag} — ${p.title} _(${p.reason})_`);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
255
299
|
}
|
|
256
300
|
if (target.merge_base) out.push(`- **Merge Base**: \`${target.merge_base}\``);
|
|
257
301
|
if (target.head_git_ref) out.push(`- **Head Git Ref**: \`${target.head_git_ref}\``);
|
|
@@ -266,7 +310,11 @@ function formatMarkdown({ target, graph, rulesResult, background }) {
|
|
|
266
310
|
|
|
267
311
|
if (target.pr?.body) {
|
|
268
312
|
out.push("### PR Description");
|
|
269
|
-
out.push(target.pr.body.trim().slice(0,
|
|
313
|
+
out.push(target.pr.body.trim().slice(0, 4000));
|
|
314
|
+
if (target.pr.body_truncated) {
|
|
315
|
+
out.push("");
|
|
316
|
+
out.push(`_(PR description truncated at 4000 chars; run \`gh pr view ${target.pr.number}\` for full text.)_`);
|
|
317
|
+
}
|
|
270
318
|
out.push("");
|
|
271
319
|
}
|
|
272
320
|
if (background) {
|
|
@@ -373,14 +421,19 @@ function formatMarkdown({ target, graph, rulesResult, background }) {
|
|
|
373
421
|
out.push("");
|
|
374
422
|
}
|
|
375
423
|
|
|
376
|
-
if (rulesResult) {
|
|
377
|
-
out.push("## 5. Matched Review Rules");
|
|
378
|
-
if (
|
|
424
|
+
if (rulesResult || policy?.text) {
|
|
425
|
+
out.push(policy?.text ? "## 5. Governance Policy & Matched Review Rules" : "## 5. Matched Review Rules");
|
|
426
|
+
if (policy?.text) {
|
|
427
|
+
out.push("### Project Policy & Scope Boundaries");
|
|
428
|
+
out.push(policy.text);
|
|
429
|
+
out.push("");
|
|
430
|
+
}
|
|
431
|
+
if (rulesResult?.global_principles?.length > 0) {
|
|
379
432
|
out.push("### Global Principles");
|
|
380
433
|
for (const p of rulesResult.global_principles) out.push(`- ${p}`);
|
|
381
434
|
out.push("");
|
|
382
435
|
}
|
|
383
|
-
for (const g of rulesResult
|
|
436
|
+
for (const g of rulesResult?.groups || []) {
|
|
384
437
|
out.push(`### Rule Group: ${g.rule_names.length > 0 ? g.rule_names.join(" + ") : "General"}`);
|
|
385
438
|
out.push(`- **Files**: ${g.files.map((x) => `\`${x}\``).join(", ")}`);
|
|
386
439
|
for (const item of g.checklist) out.push(`- ${item}`);
|
|
@@ -395,6 +448,7 @@ function main() {
|
|
|
395
448
|
const { command, opts } = parseArgs(process.argv);
|
|
396
449
|
const background = loadBackground(opts);
|
|
397
450
|
const rulesLoaded = loadMergedRules(opts.repo, opts.rule);
|
|
451
|
+
const policyLoaded = loadPolicy(opts.repo, opts.policy);
|
|
398
452
|
const excludePatterns = [...(rulesLoaded.data.default_excludes || []), ...opts.exclude];
|
|
399
453
|
|
|
400
454
|
let payload;
|
|
@@ -439,10 +493,11 @@ function main() {
|
|
|
439
493
|
...sanitizeTarget(target),
|
|
440
494
|
...(background ? { background } : {}),
|
|
441
495
|
rules_sources: rulesLoaded.sources,
|
|
496
|
+
...(policyLoaded.source ? { policy_source: policyLoaded.source, policy: policyLoaded.text } : {}),
|
|
442
497
|
graph,
|
|
443
498
|
rules: rulesResult,
|
|
444
499
|
};
|
|
445
|
-
mdPayload = formatMarkdown({ target, graph, rulesResult, background });
|
|
500
|
+
mdPayload = formatMarkdown({ target, graph, rulesResult, policy: policyLoaded, background });
|
|
446
501
|
} else {
|
|
447
502
|
throw new Error(`Unknown command "${command}". Expected one of: pack, preview, graph, rules.`);
|
|
448
503
|
}
|
|
@@ -462,6 +517,10 @@ const isMain =
|
|
|
462
517
|
process.argv[1] &&
|
|
463
518
|
fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
|
|
464
519
|
if (isMain) {
|
|
520
|
+
process.stdout.on("error", (err) => {
|
|
521
|
+
if (err.code === "EPIPE") process.exit(0);
|
|
522
|
+
throw err;
|
|
523
|
+
});
|
|
465
524
|
try {
|
|
466
525
|
main();
|
|
467
526
|
} catch (err) {
|
|
@@ -93,6 +93,180 @@ export function parsePrInput(raw) {
|
|
|
93
93
|
throw new Error(`Invalid --pr value "${raw}". Expected PR number (e.g. 123) or GitHub PR URL.`);
|
|
94
94
|
}
|
|
95
95
|
|
|
96
|
+
export function extractLinkedIssues(prJson) {
|
|
97
|
+
const selfNum = Number(prJson.number);
|
|
98
|
+
const closingSet = new Set();
|
|
99
|
+
const referencedSet = new Set();
|
|
100
|
+
|
|
101
|
+
if (Array.isArray(prJson.closingIssuesReferences)) {
|
|
102
|
+
for (const ref of prJson.closingIssuesReferences) {
|
|
103
|
+
const n = Number(ref?.number);
|
|
104
|
+
if (Number.isInteger(n) && n > 0 && n !== selfNum) closingSet.add(n);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Strip HTML comments (e.g. PR template examples) before scanning
|
|
109
|
+
const cleanBody = String(prJson.body || "").replace(/<!--[\s\S]*?-->/g, "");
|
|
110
|
+
const fullText = `${prJson.title || ""}\n${cleanBody}`;
|
|
111
|
+
const closingRe =
|
|
112
|
+
/\b(?:fix(?:es|ed)?|close[sd]?|resolve[sd]?)\s*:?\s*(?:https?:\/\/github\.com\/[^/\s]+\/[^/\s]+\/issues\/|#)(\d+)\b/gi;
|
|
113
|
+
for (const m of fullText.matchAll(closingRe)) {
|
|
114
|
+
const n = Number(m[1]);
|
|
115
|
+
if (Number.isInteger(n) && n > 0 && n !== selfNum) closingSet.add(n);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const anyRefRe = /(?:^|[\s([,:;/(,、])(?:#|https?:\/\/github\.com\/[^/\s]+\/[^/\s]+\/(?:issues|pull)\/)(\d+)\b/g;
|
|
119
|
+
for (const m of fullText.matchAll(anyRefRe)) {
|
|
120
|
+
const n = Number(m[1]);
|
|
121
|
+
if (Number.isInteger(n) && n > 0 && n !== selfNum && !closingSet.has(n)) {
|
|
122
|
+
referencedSet.add(n);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return {
|
|
127
|
+
closing: Array.from(closingSet).sort((a, b) => a - b),
|
|
128
|
+
referenced: Array.from(referencedSet).sort((a, b) => a - b),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const SCOPE_STOPWORDS = new Set([
|
|
133
|
+
"add", "adds", "fix", "fixes", "feat", "feature", "chore", "docs", "test", "tests",
|
|
134
|
+
"refactor", "perf", "style", "build", "ci", "support", "supports", "update", "updates",
|
|
135
|
+
"improve", "improves", "allow", "enable", "disable", "remove", "drop", "keep", "use",
|
|
136
|
+
"show", "hide", "make", "handle", "prevent", "avoid", "ensure", "check", "read", "write",
|
|
137
|
+
"sync", "with", "from", "into", "when", "only", "more", "some", "each", "over", "under",
|
|
138
|
+
"after", "before", "instead", "without", "across", "based", "using", "their", "them",
|
|
139
|
+
"this", "that", "these", "those", "for", "and", "the", "not", "all", "new", "old", "via",
|
|
140
|
+
"default", "custom", "native", "local", "page", "view", "list", "mode", "file", "files",
|
|
141
|
+
"data", "state", "error", "errors", "issue", "issues", "app", "apps", "cli", "api",
|
|
142
|
+
"config", "settings", "client", "clients", "server", "first", "last", "time", "type",
|
|
143
|
+
"name", "item", "items", "row", "rows", "line", "lines", "key", "keys", "path", "paths",
|
|
144
|
+
"dir", "edit", "open", "close", "load", "save", "run", "set", "get", "include",
|
|
145
|
+
"request", "requests", "output", "input",
|
|
146
|
+
]);
|
|
147
|
+
|
|
148
|
+
const BROAD_SCOPES = new Set([
|
|
149
|
+
"api", "ui", "ux", "db", "database", "ci", "cd", "docs", "test", "tests", "deps",
|
|
150
|
+
"misc", "config", "settings", "refactor", "chore", "perf", "sync", "auth", "security",
|
|
151
|
+
"core", "cli", "web", "app", "apps", "server", "client", "sdk", "i18n", "build",
|
|
152
|
+
]);
|
|
153
|
+
|
|
154
|
+
function parseConventionalScope(title) {
|
|
155
|
+
const m = String(title || "").match(/^[a-z]+\(([^)]+)\)\s*:/i);
|
|
156
|
+
if (!m) return null;
|
|
157
|
+
const raw = m[1].trim().toLowerCase();
|
|
158
|
+
const base = raw.split(/[-_/]/)[0];
|
|
159
|
+
return { raw, base };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function extractDomainTokens(text) {
|
|
163
|
+
const tokens = new Set();
|
|
164
|
+
const parts = String(text || "")
|
|
165
|
+
.replace(/([a-z])([A-Z])/g, "$1 $2")
|
|
166
|
+
.split(/[^a-zA-Z0-9\u4e00-\u9fff]+/);
|
|
167
|
+
for (const part of parts) {
|
|
168
|
+
const norm = part.toLowerCase();
|
|
169
|
+
if (!norm || norm.length < 3 || /^\d+$/.test(norm) || SCOPE_STOPWORDS.has(norm)) continue;
|
|
170
|
+
tokens.add(norm);
|
|
171
|
+
}
|
|
172
|
+
return tokens;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function buildOverlapSearchQueries(prMeta) {
|
|
176
|
+
const queries = [];
|
|
177
|
+
const seen = new Set();
|
|
178
|
+
const add = (q) => {
|
|
179
|
+
const clean = q.trim().toLowerCase();
|
|
180
|
+
if (!clean || seen.has(clean)) return;
|
|
181
|
+
seen.add(clean);
|
|
182
|
+
queries.push(clean);
|
|
183
|
+
};
|
|
184
|
+
const scope = parseConventionalScope(prMeta?.title);
|
|
185
|
+
if (scope && !BROAD_SCOPES.has(scope.raw)) {
|
|
186
|
+
add(scope.base.length >= 3 ? scope.base : scope.raw);
|
|
187
|
+
}
|
|
188
|
+
const titleNoPrefix = String(prMeta?.title || "").replace(/^[a-z]+(?:\([^)]+\))?\s*:\s*/i, "");
|
|
189
|
+
for (const tok of extractDomainTokens(titleNoPrefix)) {
|
|
190
|
+
if (queries.length >= 2) break;
|
|
191
|
+
if (tok.length >= 4) add(tok);
|
|
192
|
+
}
|
|
193
|
+
return queries.slice(0, 2);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function findOverlappingOpenPrs(prMeta, openPrs) {
|
|
197
|
+
if (!prMeta || !Array.isArray(openPrs) || openPrs.length === 0) return [];
|
|
198
|
+
const selfNum = Number(prMeta.number);
|
|
199
|
+
const selfScope = parseConventionalScope(prMeta.title);
|
|
200
|
+
const selfTitleNoPrefix = String(prMeta.title || "").replace(/^[a-z]+(?:\([^)]+\))?\s*:\s*/i, "");
|
|
201
|
+
const selfTokens = extractDomainTokens(selfTitleNoPrefix);
|
|
202
|
+
|
|
203
|
+
const matches = [];
|
|
204
|
+
const seenNums = new Set();
|
|
205
|
+
for (const cand of openPrs) {
|
|
206
|
+
const num = Number(cand?.number);
|
|
207
|
+
if (!Number.isInteger(num) || num <= 0 || num === selfNum || seenNums.has(num)) continue;
|
|
208
|
+
seenNums.add(num);
|
|
209
|
+
const candScope = parseConventionalScope(cand.title);
|
|
210
|
+
const candTitleNoPrefix = String(cand.title || "").replace(/^[a-z]+(?:\([^)]+\))?\s*:\s*/i, "");
|
|
211
|
+
const candTokens = extractDomainTokens(candTitleNoPrefix);
|
|
212
|
+
|
|
213
|
+
const sharedTokens = [];
|
|
214
|
+
for (const t of selfTokens) {
|
|
215
|
+
if (candTokens.has(t)) sharedTokens.push(t);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
let score = 0;
|
|
219
|
+
const reasons = [];
|
|
220
|
+
|
|
221
|
+
const sameNarrowScope =
|
|
222
|
+
selfScope &&
|
|
223
|
+
candScope &&
|
|
224
|
+
!BROAD_SCOPES.has(selfScope.raw) &&
|
|
225
|
+
(selfScope.raw === candScope.raw ||
|
|
226
|
+
(selfScope.base.length >= 3 && selfScope.base === candScope.base));
|
|
227
|
+
|
|
228
|
+
const sameBroadScope =
|
|
229
|
+
selfScope &&
|
|
230
|
+
candScope &&
|
|
231
|
+
BROAD_SCOPES.has(selfScope.raw) &&
|
|
232
|
+
selfScope.raw === candScope.raw;
|
|
233
|
+
|
|
234
|
+
if (sameNarrowScope) {
|
|
235
|
+
score += 4;
|
|
236
|
+
reasons.push(`same scope (${selfScope.raw} ↔ ${candScope.raw})`);
|
|
237
|
+
} else if (sameBroadScope && sharedTokens.length >= 2) {
|
|
238
|
+
score += 2;
|
|
239
|
+
reasons.push(`same scope (${selfScope.raw})`);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
if (sharedTokens.length > 0) {
|
|
243
|
+
score += sharedTokens.length * 1.5;
|
|
244
|
+
reasons.push(`shared terms: ${sharedTokens.slice(0, 5).join(", ")}`);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const passes =
|
|
248
|
+
sameNarrowScope ||
|
|
249
|
+
(sameBroadScope && sharedTokens.length >= 2) ||
|
|
250
|
+
sharedTokens.length >= 3;
|
|
251
|
+
|
|
252
|
+
if (passes) {
|
|
253
|
+
matches.push({
|
|
254
|
+
number: num,
|
|
255
|
+
title: cand.title || "",
|
|
256
|
+
is_draft: Boolean(cand.isDraft),
|
|
257
|
+
url: cand.url || "",
|
|
258
|
+
score,
|
|
259
|
+
reason: reasons.join("; "),
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
return matches
|
|
265
|
+
.sort((a, b) => b.score - a.score || a.number - b.number)
|
|
266
|
+
.slice(0, 5)
|
|
267
|
+
.map(({ score: _score, ...rest }) => rest);
|
|
268
|
+
}
|
|
269
|
+
|
|
96
270
|
export function resolveRefExists(repoDir, ref) {
|
|
97
271
|
if (!ref) return false;
|
|
98
272
|
return git(repoDir, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { allowFailure: true }).ok;
|
|
@@ -263,23 +437,55 @@ export function collectReviewTarget(repoDir, opts, excludePatterns = []) {
|
|
|
263
437
|
"view",
|
|
264
438
|
String(parsedPr.number),
|
|
265
439
|
"--json",
|
|
266
|
-
"number,title,body,author,baseRefName,headRefName,baseRefOid,headRefOid,url,additions,deletions",
|
|
440
|
+
"number,title,body,author,baseRefName,headRefName,baseRefOid,headRefOid,url,additions,deletions,isDraft,labels,closingIssuesReferences",
|
|
267
441
|
];
|
|
268
442
|
if (parsedPr.repo) ghArgs.push("--repo", parsedPr.repo);
|
|
269
443
|
const prRes = runCmd("gh", ghArgs, repoRoot);
|
|
270
444
|
const prJson = JSON.parse(prRes.stdout);
|
|
445
|
+
const rawBody = prJson.body || "";
|
|
271
446
|
prMeta = {
|
|
272
447
|
number: prJson.number,
|
|
273
448
|
title: prJson.title,
|
|
274
449
|
author: prJson.author?.login || "unknown",
|
|
275
450
|
url: prJson.url,
|
|
451
|
+
is_draft: Boolean(prJson.isDraft),
|
|
452
|
+
labels: Array.isArray(prJson.labels) ? prJson.labels.map((l) => l.name).filter(Boolean) : [],
|
|
453
|
+
additions: Number(prJson.additions) || 0,
|
|
454
|
+
deletions: Number(prJson.deletions) || 0,
|
|
276
455
|
base_ref: prJson.baseRefName,
|
|
277
456
|
head_ref: prJson.headRefName,
|
|
278
457
|
base_oid: prJson.baseRefOid,
|
|
279
458
|
head_oid: prJson.headRefOid,
|
|
280
|
-
body:
|
|
459
|
+
body: rawBody.slice(0, 4000),
|
|
460
|
+
body_truncated: rawBody.length > 4000,
|
|
461
|
+
linked_issues: extractLinkedIssues(prJson),
|
|
462
|
+
overlapping_prs: [],
|
|
281
463
|
};
|
|
282
464
|
|
|
465
|
+
if (!opts.noOverlapCheck) {
|
|
466
|
+
const candidatePool = [];
|
|
467
|
+
for (const term of buildOverlapSearchQueries(prMeta)) {
|
|
468
|
+
const searchArgs = [
|
|
469
|
+
"pr", "list", "--state", "open", "--search", `${term} in:title`,
|
|
470
|
+
"--limit", "50", "--json", "number,title,isDraft,url",
|
|
471
|
+
];
|
|
472
|
+
if (parsedPr.repo) searchArgs.push("--repo", parsedPr.repo);
|
|
473
|
+
const searchRes = runCmd("gh", searchArgs, repoRoot, { allowFailure: true });
|
|
474
|
+
if (searchRes.ok) {
|
|
475
|
+
try { candidatePool.push(...JSON.parse(searchRes.stdout)); } catch {}
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
if (candidatePool.length === 0) {
|
|
479
|
+
const listArgs = ["pr", "list", "--state", "open", "--limit", "100", "--json", "number,title,isDraft,url"];
|
|
480
|
+
if (parsedPr.repo) listArgs.push("--repo", parsedPr.repo);
|
|
481
|
+
const listRes = runCmd("gh", listArgs, repoRoot, { allowFailure: true });
|
|
482
|
+
if (listRes.ok) {
|
|
483
|
+
try { candidatePool.push(...JSON.parse(listRes.stdout)); } catch {}
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
prMeta.overlapping_prs = findOverlappingOpenPrs(prMeta, candidatePool);
|
|
487
|
+
}
|
|
488
|
+
|
|
283
489
|
// Fetch PR head into git object store without modifying working tree
|
|
284
490
|
if (resolveRefExists(repoRoot, prJson.headRefOid)) {
|
|
285
491
|
headGitRef = prJson.headRefOid;
|
|
@@ -245,11 +245,15 @@ export function buildDependencyGraph(target, rulesData = {}) {
|
|
|
245
245
|
// Per-changed-file analysis
|
|
246
246
|
const fileAnalysis = [];
|
|
247
247
|
const seenFiles = new Set();
|
|
248
|
+
let totalInsertions = 0;
|
|
249
|
+
let totalDeletions = 0;
|
|
248
250
|
|
|
249
251
|
for (const fileEntry of target.reviewable_files) {
|
|
250
252
|
const rel = fileEntry.path;
|
|
251
253
|
if (seenFiles.has(rel)) continue;
|
|
252
254
|
seenFiles.add(rel);
|
|
255
|
+
totalInsertions += fileEntry.insertions || 0;
|
|
256
|
+
totalDeletions += fileEntry.deletions || 0;
|
|
253
257
|
|
|
254
258
|
const diffInfo = diffInfoByFile.get(rel);
|
|
255
259
|
const info = parsed.get(rel);
|
|
@@ -376,6 +380,28 @@ export function buildDependencyGraph(target, rulesData = {}) {
|
|
|
376
380
|
});
|
|
377
381
|
}
|
|
378
382
|
|
|
383
|
+
// Universal PR/scope triage alerts
|
|
384
|
+
if (fileAnalysis.length >= 20 || totalInsertions >= 1000) {
|
|
385
|
+
staticAlerts.push({
|
|
386
|
+
severity: "medium",
|
|
387
|
+
code: "LARGE_PR",
|
|
388
|
+
file: fileAnalysis[0]?.path || ".",
|
|
389
|
+
message: `Large change (${fileAnalysis.length} reviewable files, +${totalInsertions}/-${totalDeletions} lines). Verify scope and architectural alignment before line-by-line review.`,
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
if (target.pr?.overlapping_prs?.length > 0) {
|
|
394
|
+
const summary = target.pr.overlapping_prs
|
|
395
|
+
.map((p) => `#${p.number}${p.is_draft ? " [Draft]" : ""} "${p.title}" (${p.reason})`)
|
|
396
|
+
.join(" | ");
|
|
397
|
+
staticAlerts.push({
|
|
398
|
+
severity: "high",
|
|
399
|
+
code: "POTENTIAL_OVERLAPPING_PR",
|
|
400
|
+
file: `PR #${target.pr.number}`,
|
|
401
|
+
message: `Potential overlapping open PR(s) detected: ${summary}. Inspect them first to avoid reviewing duplicate implementations.`,
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
|
|
379
405
|
// Automatic bottom-up Recommended Review Order (contracts -> topological leaf code -> consumers -> tests -> docs)
|
|
380
406
|
const topoLevels = computeChangedTopoLevels(
|
|
381
407
|
fileAnalysis.map((f) => f.path),
|
|
@@ -113,6 +113,18 @@ export function extractTsTauri(clean, rawContent) {
|
|
|
113
113
|
return { tauriInvokes, tauriListens, tauriEmits };
|
|
114
114
|
}
|
|
115
115
|
|
|
116
|
+
function extractBalancedParens(text, openIdx) {
|
|
117
|
+
let depth = 0;
|
|
118
|
+
for (let i = openIdx; i < text.length; i++) {
|
|
119
|
+
if (text[i] === "(") depth++;
|
|
120
|
+
else if (text[i] === ")") {
|
|
121
|
+
depth--;
|
|
122
|
+
if (depth === 0) return text.slice(openIdx + 1, i);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
|
|
116
128
|
export function extractRustTauri(clean) {
|
|
117
129
|
const tauriCommands = [];
|
|
118
130
|
const registeredHandlers = [];
|
|
@@ -130,19 +142,24 @@ export function extractRustTauri(clean) {
|
|
|
130
142
|
const attrArgs = m[1] || "";
|
|
131
143
|
const renameMatch = attrArgs.match(/rename_all\s*=\s*"([^"]+)"/);
|
|
132
144
|
const renameAll = renameMatch ? renameMatch[1] : "camelCase";
|
|
133
|
-
const
|
|
145
|
+
const startAfter = m.index + m[0].length;
|
|
146
|
+
const after = clean.slice(startAfter, startAfter + 1200);
|
|
134
147
|
const fnMatch = after.match(
|
|
135
|
-
/^(?:\s*#\[[^\]]*\])*\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z0-9_]+)\s*(?:<[^>]*>)?\s*\(
|
|
148
|
+
/^(?:\s*#\[[^\]]*\])*\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z0-9_]+)\s*(?:<[^>]*>)?\s*\(/,
|
|
136
149
|
);
|
|
137
150
|
if (fnMatch) {
|
|
138
151
|
const fnName = fnMatch[1];
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
line,
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
152
|
+
const openParenIdx = fnMatch.index + fnMatch[0].length - 1;
|
|
153
|
+
const paramStr = extractBalancedParens(after, openParenIdx);
|
|
154
|
+
if (paramStr !== null) {
|
|
155
|
+
const line = lineNumberAt(clean, startAfter + fnMatch.index);
|
|
156
|
+
tauriCommands.push({
|
|
157
|
+
name: fnName,
|
|
158
|
+
line,
|
|
159
|
+
renameAll,
|
|
160
|
+
params: parseRustParams(paramStr, renameAll),
|
|
161
|
+
});
|
|
162
|
+
}
|
|
146
163
|
}
|
|
147
164
|
}
|
|
148
165
|
|
|
@@ -303,6 +320,7 @@ export function analyzeTauriBridges({
|
|
|
303
320
|
if (!info) continue;
|
|
304
321
|
if (info.lang === "rust") {
|
|
305
322
|
for (const cmd of info.tauriCommands || []) {
|
|
323
|
+
if (!lineTouchedNear(rel, cmd.line, 12)) continue;
|
|
306
324
|
if (!registeredHandlerSet.has(cmd.name)) {
|
|
307
325
|
staticAlerts.push({
|
|
308
326
|
severity: "high",
|
|
@@ -316,6 +334,9 @@ export function analyzeTauriBridges({
|
|
|
316
334
|
} else if (info.lang === "ts") {
|
|
317
335
|
for (const inv of info.tauriInvokes || []) {
|
|
318
336
|
const rustDefs = rustCommandMap.get(inv.command) || [];
|
|
337
|
+
const invTouched = lineTouchedNear(rel, inv.line, 4);
|
|
338
|
+
const defTouched = rustDefs.some((d) => changedSet.has(d.file) && lineTouchedNear(d.file, d.line, 12));
|
|
339
|
+
if (!invTouched && !defTouched) continue;
|
|
319
340
|
if (rustDefs.length === 0 && !registeredHandlerSet.has(inv.command)) {
|
|
320
341
|
staticAlerts.push({
|
|
321
342
|
severity: "high",
|