chore: restore original directory structure (project under code-review-graph-main/)

This commit is contained in:
AuraK Developer
2026-08-31 13:08:20 +08:00
parent ecc55158c1
commit ecfd03a21c
404 changed files with 0 additions and 0 deletions
@@ -0,0 +1,38 @@
---
name: build-graph
description: Build or update the code review knowledge graph. Run this first to initialize, or let hooks keep it updated automatically.
argument-hint: "[full]"
---
# Build Graph
Build or incrementally update the persistent code knowledge graph for this repository.
## Steps
1. **Check graph status** by calling the `list_graph_stats_tool` MCP tool.
- If the graph has never been built (last_updated is null), proceed with a full build.
- If the graph exists, proceed with an incremental update.
2. **Build the graph** by calling the `build_or_update_graph_tool` MCP tool:
- For first-time setup: `build_or_update_graph_tool(full_rebuild=True)`
- For updates: `build_or_update_graph_tool()` (incremental by default)
3. **Verify** by calling `list_graph_stats_tool` again and report the results:
- Number of files parsed
- Number of nodes and edges created
- Languages detected
- Any errors encountered
## When to Use
- First time setting up the graph for a repository
- After major refactoring or branch switches
- If the graph seems stale or out of sync
- The graph auto-updates via hooks on edit/commit, so manual builds are rarely needed
## Notes
- The graph is stored as a SQLite database (`.code-review-graph/graph.db`) in the repo root
- Binary files, generated files, and patterns in `.code-review-graphignore` are skipped
- Supported languages: Python, TypeScript/JavaScript, Vue, Go, Rust, Java, Scala, C#, Ruby, Kotlin, Swift, PHP, Solidity, C/C++
@@ -0,0 +1,27 @@
---
name: debug-issue
description: Systematically debug issues using graph-powered code navigation
---
## Debug Issue
Use the knowledge graph to systematically trace and debug issues.
### Steps
1. Use `semantic_search_nodes_tool` to find code related to the issue.
2. Use `query_graph_tool` with `callers_of` and `callees_of` to trace call chains.
3. Use `get_flow` to see full execution paths through suspected areas.
4. Run `detect_changes_tool` to check if recent changes caused the issue.
5. Use `get_impact_radius_tool` on suspected files to see what else is affected.
### Tips
- Check both callers and callees to understand the full context.
- Look at affected flows to find the entry point that triggers the bug.
- Recent changes are the most common source of new issues.
## Token Efficiency Rules
- ALWAYS start with `get_minimal_context(task="<your task>")` before any other graph tool.
- Use `detail_level="minimal"` on all calls. Only escalate to "standard" when minimal is insufficient.
- Target: complete any review/debug/refactor task in ≤5 tool calls and ≤800 total output tokens.
@@ -0,0 +1,28 @@
---
name: explore-codebase
description: Navigate and understand codebase structure using the knowledge graph
---
## Explore Codebase
Use the code-review-graph MCP tools to explore and understand the codebase.
### Steps
1. Run `list_graph_stats` to see overall codebase metrics.
2. Run `get_architecture_overview_tool` for high-level community structure.
3. Use `list_communities_tool` to find major modules, then `get_community` for details.
4. Use `semantic_search_nodes_tool` to find specific functions or classes.
5. Use `query_graph_tool` with patterns like `callers_of`, `callees_of`, `imports_of` to trace relationships.
6. Use `list_flows` and `get_flow` to understand execution paths.
### Tips
- Start broad (stats, architecture) then narrow down to specific areas.
- Use `children_of` on a file to see all its functions and classes.
- Use `find_large_functions` to identify complex code.
## Token Efficiency Rules
- ALWAYS start with `get_minimal_context(task="<your task>")` before any other graph tool.
- Use `detail_level="minimal"` on all calls. Only escalate to "standard" when minimal is insufficient.
- Target: complete any review/debug/refactor task in ≤5 tool calls and ≤800 total output tokens.
@@ -0,0 +1,93 @@
---
name: project-review
description: Whole-project or single-feature code review (not diff-based) using graph-wide analysis and objective scoring
---
# Project Review
Review the entire codebase or a single feature/module, independent of the git diff. Two scopes, driven by the user's instruction:
- **whole-project**: "对项目代码进行全面审查", "全面审查", "整个项目" → review every source file in the graph.
- **feature**: "审查 <功能/模块> 的代码" (e.g. payment, auth) → review only the code related to the target.
**This skill is READ-ONLY.** Every finding is presented to the user for a manual fix decision. Never apply code changes, commit, or push.
## Token Efficiency Rules
- ALWAYS start with `get_minimal_context(task="project review")`. Use `detail_level="minimal"` on all calls; escalate to `"standard"` only when a metric or finding needs evidence.
## Step 0 - Parse the scope
Read the user's instruction and set scope: whole-project (contains 全面/整个项目/所有/all) or feature + target (extract the feature/module keyword). Declare both in the report header.
## Step 1 - Graph ready
1. Call `build_or_update_graph_tool()` to ensure the graph is current.
2. Call `get_minimal_context_tool(task="project review")` for stats and community overview.
## Step 2 - Architecture map
Call `get_architecture_overview_tool(detail_level="minimal")` and `list_communities_tool(detail_level="minimal")` to map the module structure.
## Step 3 - High-risk scan (whole-project)
Call `get_knowledge_gaps_tool()`, `get_hub_nodes_tool()`, `get_bridge_nodes_tool()`, `find_large_functions_tool()` and `get_surprising_connections_tool()` to locate hotspots, chokepoints, untested areas and odd coupling.
## Step 4 - Objective scoring
- whole-project: `score_review_tool(all_files=True)` scores every source file in the graph.
- feature: locate the target files with `semantic_search_nodes_tool(query=<target>)` and `query_graph_tool(pattern="children_of", target=<target>)`, then `score_review_tool(changed_files=<files>)` and `get_impact_radius_tool(changed_files=<files>)` for the blast radius.
## Step 5 - Chain decomposition
Inspect the scored code across eight categories (interface, business, data, utility, error handling, security, performance, observability) and apply the gstack CRITICAL sub-pass (SQL & Data Safety, Race Conditions, LLM Output Trust Boundary, Shell Injection, Enum Completeness). Mark each ✅ / ⚠️ / —.
## Step 6 - Manual adjudication (READ-ONLY)
Present every finding with severity (🔴 blocker / 🟡 major / 🔵 minor), confidence (1-10), file:line and a proposed fix. Group by severity and ask the user per batch: fix / skip / self-fix. 🔴 blockers cannot be batch-skipped. **Do not modify code.**
## Step 7 - Acceptance gate
Any 🔴 blocker → verdict `❌ FAIL`. Classify each finding as Ready / Needs Fix / Unusable.
## Step 7.5 - 覆盖度自检(必须执行,防"审完了"由感觉决定)
报告前完成三件事(机制未生效时禁止用 CLI 兜底继续审查):
1. **G1 深读名单完整性**:确认名单外文件是"被评估过"而非"被忽略";未被任何信号点名的文件记入 **"未深读文件清单"**,在报告中显式列出。
2. **G2 静默抽检**:调用 `coverage_tool` 取返回的 `silent_files`(未被任何信号点名的文件),随机抽 **15%** 深读;发现 ≥1 major → 该文件升级全量深读,并同社区/同类追加抽检一轮。抽检记录附入报告(抽了几份 / 几个 major / 有无升级)。
3. **G3 覆盖度计算**:调用 `coverage_tool(deep_read_files=<本轮实际深读文件>, gate="both+line")`,引擎自动计算**三重口径**(文件数口径 + 三件套质量口径):
- **全库覆盖** = `coverage_pct`(已深读文件数 / 全部源文件数)
- **高风险覆盖** = `high_risk_coverage_pct`(已深读 / 信号点名文件,文件数口径)
- **行/单元覆盖** = `line_coverage_pct` / `unit_coverage_pct`gate="both+line" 时的三件套质量口径)
- **feature(单功能)审查**:改用 `gate="line+unit"`——**只做行覆盖 ≥95% + 单元完整性无缺口**,不做全库/高风险文件数覆盖检查(`coverage_pct`/`high_risk_coverage_pct``null`,报告只渲染行/单元覆盖,不渲染全库/高风险行)。`target_reached=false` → 报告顶部标 🔴 覆盖不足。
将覆盖度结果**完整透传**到 `review_data.coverage`(直接把 `coverage_tool` 返回值全部字段传入:coverage_pct/high_risk_coverage_pct/grade/deep_read_count/total_files/high_risk_total_files/high_risk_deep_count/deep_read_weight/total_weight/target_reached/target/uncovered_files/silent_files/note),不要手挑子集,否则计数字段渲染为 0/0 或 N/A。报告会自动渲染 `## 覆盖度` 区块。
**前置健康检查**:调用 `community_health_tool`,若 `needs_postprocess=true`nodes.community_id 归属率 <90%),先 `code-review-graph postprocess` 重建社区归属再计算,否则覆盖度失真。
## Step 8 - Report
Call `generate_report_tool(review_data=<verdict, scope, metrics, findings>)` to write `code-review-report.html` and `code-review-report.md` (default `format="both"`). Pass `reviewed_files: [path, ...]` (the deep-read file array) — the report header renders it as a collapsible `<details>` list (falls back to the flat `files` string when absent).
**Archive naming (REQUIRED):** always pass `output_path="docs/reviews/{name}-review-{YYYY-MM-DD-HHMMSS}"` (e.g. `docs/reviews/evm-feature-review-2026-08-06-151522`). Omitting `output_path` writes to `<repo_root>/code-review-report.*` which is a naming violation.
## Step 8.6 - Report naming self-check (REQUIRED)
After generating, run the naming verifier (standalone script, independent of the CRG CLI):
```powershell
powershell -File "C:\Users\Administrator\.config\opencode\skills\project-review\verify-report.ps1" -Repo <repo_root>
```
- Exit 0 → pass: all reports under `docs/reviews/` carry a `-YYYY-MM-DD-HHMMSS` suffix.
- Exit 1 → stray root `code-review-report.*` detected. Fix by re-calling `generate_report_tool` with the correct `output_path`, or run with `-Fix` to auto-archive, then re-verify.
- Historic non-conforming names in `docs/reviews/` are warnings only — do not rename them.
## Output Format
`Project Review: N issues (X blocker, Y major, Z minor) — verdict: ✅ PASS / ❌ FAIL`. List each issue with severity, confidence, file:line, problem, and proposed fix.
## Token Efficiency Rules
- ALWAYS start with `get_minimal_context(task="project review")` before any other graph tool.
- Use `detail_level="minimal"` on all calls. Only escalate to `"standard"` when minimal is insufficient.
- Target: complete a project review in ≤12 tool calls and ≤1800 total output tokens.
@@ -0,0 +1,19 @@
# Unified Review — Common Mistakes
- **Skipping graph context** — always run `get_minimal_context` first; CRG
context is what makes the review token-efficient and blast-radius aware.
- **Rushing to fix** — this skill is READ-ONLY. Present findings, wait for
user decision. Never apply fixes, commit, or push.
- **Ignoring tier** — read `.code-review.yaml`. `fast` skips Layer 2/3;
`strict` requires per-item confirmation for every blocker/major.
- **Judging metrics without evidence** — `score_review_tool` outputs are
heuristics. Cite the evidence, and let the LLM confirm SQL/exception/vuln
findings before presenting them as facts.
- **Missing manual-review modules** — payment, order, inventory, permission,
distributed-lock, data-migration always require a manual review checklist.
- **Forgetting enum completeness reads OUTSIDE the diff** — grep sibling
values, then read each consumer; in-diff review alone is insufficient.
- **Batch-skipping blockers** — 🔴 blockers cannot be batch-skipped; each
needs an explicit user decision.
- **Not producing the report** — always call `generate_report_tool` at the
end and present the text report inline.
@@ -0,0 +1,12 @@
# Data Migration — Manual Review Checklist
High-risk module: schema/data migration requires human confirmation.
- [ ] Migration is idempotent and re-runnable
- [ ] Forward and rollback paths both defined and tested
- [ ] Backfill is batched / resumable for large tables
- [ ] Data type / precision changes do not silently truncate
- [ ] Nullability and default changes safe for existing rows
- [ ] Migration ordering across shards / replicas is consistent
- [ ] Application deploys compatibly with both old and new schema (expand/contract)
- [ ] Irreversible operations are flagged with a documented reason
@@ -0,0 +1,11 @@
# Distributed Lock — Manual Review Checklist
High-risk module: distributed-lock changes require architecture confirmation.
- [ ] Lock has a TTL / expiry — no permanent deadlock after crash
- [ ] Lock release is atomic and ownership-checked (compare-and-delete)
- [ ] Lock scope is correct (key includes the right entity identifiers)
- [ ] Renewal / watchdog exists for long critical sections
- [ ] Locking order is consistent across paths (no lock-ordering deadlock)
- [ ] Fencing tokens / version check prevents stale-holder writes
- [ ] Fail-open vs fail-closed behavior is intentional and documented
@@ -0,0 +1,11 @@
# Inventory Module — Manual Review Checklist
High-risk module: stock/inventory changes require human confirmation.
- [ ] Stock decrement is atomic (conditional UPDATE, not read-then-write)
- [ ] Oversell prevented: `UPDATE ... SET qty = qty - ? WHERE qty >= ?`
- [ ] Reservation vs. deduction semantics are consistent
- [ ] Concurrent orders cannot both reserve the last unit
- [ ] Restock/return increments handled correctly
- [ ] Inventory events are idempotent (retry-safe)
- [ ] Async stock updates propagate to downstream (warehouse, carts) safely
@@ -0,0 +1,12 @@
# Order Module — Manual Review Checklist
High-risk module: order lifecycle changes require human confirmation.
- [ ] State machine transitions are atomic (`WHERE status = ?` updates)
- [ ] Cancellation / timeout / expiry paths complete all side effects
- [ ] Order idempotency key prevents duplicate order creation
- [ ] Price/lock snapshot captured at order time, not at payment time
- [ ] Partial fulfillment / split-shipment handled
- [ ] Negative or inconsistent totals impossible
- [ ] Concurrent edits (cart + order) do not corrupt state
- [ ] Audit trail: every status change logged with reason
@@ -0,0 +1,14 @@
# Payment Module — Manual Review Checklist
High-risk module: payment changes require human confirmation for every
blocker/major fix.
- [ ] Callback idempotency: a duplicated webhook/callback does not double-charge
- [ ] Amounts stored as fixed-point (integers/cents), never floats
- [ ] Currency codes and precision handled correctly
- [ ] Provider signature / HMAC verification on callbacks
- [ ] Refund logic: correct reversal, no double-refund
- [ ] Failure path: payment timeout, declined, retry semantics
- [ ] Transaction boundary spans charge + order-state update
- [ ] Sensitive data (PAN, tokens) never logged or masked on output
- [ ] Ledger/journal entries are append-only and auditable
@@ -0,0 +1,11 @@
# Permission Module — Manual Review Checklist
High-risk module: authorization changes require product/human confirmation.
- [ ] Every endpoint/action enforces the intended permission — no default-allow
- [ ] Role hierarchy / scoping (tenant, org, user) is consistent
- [ ] Object-level permissions checked on read AND write
- [ ] Deny-before-allow ordering is safe
- [ ] Permission checks cannot be bypassed via IDs, query params, or bulk ops
- [ ] New permission/role values handled by all consumers (enum completeness)
- [ ] Sensitive actions audited with actor + target
@@ -0,0 +1,238 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>代码审查报告</title>
<style>
:root { --border:#d0d7de; --bg:#f6f8fa; --fg:#1f2328; --muted:#57606a;
--good:#1a7f37; --warn:#9a6700; --fail:#cf222e; --na:#57606a;
--blocker:#cf222e; --major:#9a6700; --minor:#57606a;
--critical:#cf222e; --informational:#0969da; }
* { box-sizing: border-box; }
body { font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
margin:0; padding:2rem 1rem; color:var(--fg); background:#fff; line-height:1.55; }
.wrap { max-width:960px; margin:0 auto; }
h1 { font-size:1.5rem; margin:0 0 .25rem; }
h2 { font-size:1.1rem; margin:1.5rem 0 .5rem; padding-bottom:.25rem;
border-bottom:1px solid var(--border); }
.meta { color:var(--muted); font-size:.9rem; margin-bottom:1.5rem; }
.verdict { display:inline-block; padding:.25rem .75rem; border-radius:20px;
font-weight:700; font-size:.95rem; }
.verdict.pass { background:#dafbe1; color:var(--good); }
.verdict.fail { background:#ffebe9; color:var(--fail); }
table { border-collapse:collapse; width:100%; margin:.75rem 0; }
th,td { border:1px solid var(--border); padding:.45rem .6rem; text-align:left;
font-size:.9rem; vertical-align:top; }
th { background:var(--bg); }
.grade.good { color:var(--good); font-weight:600; }
.grade.warn { color:var(--warn); font-weight:600; }
.grade.fail { color:var(--fail); font-weight:600; }
.grade.na { color:var(--na); }
.issue { margin:.6rem 0; padding:.65rem .8rem; border:1px solid var(--border);
border-radius:6px; background:#fff; }
.issue .tag { display:inline-block; padding:.1rem .5rem; border-radius:10px;
font-size:.75rem; font-weight:700; color:#fff; margin-right:.5rem; }
.tag.blocker, .tag.critical { background:var(--blocker); }
.tag.major, .tag.warn { background:var(--major); }
.tag.minor, .tag.informational { background:var(--minor); }
.issue .cat { font-weight:600; }
.issue .loc { color:var(--muted); font-size:.85rem; margin-top:.2rem; }
.issue .fix { margin-top:.35rem; font-size:.88rem; background:var(--bg);
padding:.4rem .6rem; border-radius:4px; }
.muted { color:var(--muted); font-size:.85rem; }
code { background:var(--bg); padding:.1rem .3rem; border-radius:4px;
font-size:.88em; }
details.reviewed { margin:.5rem 0; border:1px solid var(--border);
border-radius:6px; padding:.4rem .8rem; }
details.reviewed summary { cursor:pointer; font-weight:600; }
details.reviewed ul { margin:.4rem 0 0; padding-left:1.2rem; }
details.reviewed li { margin:.15rem 0; }
</style>
</head>
<body>
<div class="wrap" id="app"></div>
<script>
const data = {{REPORT_DATA}};
function esc(s) {
return String(s ?? "").replace(/[&<>"']/g, c => ({
"&":"&amp;", "<":"&lt;", ">":"&gt;", '"':"&quot;", "'":"&#39;"
})[c]);
}
function verdictClass(v) {
v = String(v || "").toUpperCase();
return v.includes("PASS") ? "pass" : "fail";
}
// Collapsible list of the reviewed files (native <details>/<summary>, no JS).
// Accepts an array OR a comma-separated string (agents pass both). Falls
// back to the flat ``files`` string when nothing structured is given.
function renderReviewedFiles(data) {
let arr = data.reviewed_files;
if (typeof arr === "string") {
arr = arr.split(",").map(s => s.trim()).filter(Boolean);
}
if (!Array.isArray(arr) || !arr.length) {
return data.files ? `<p><b>文件:</b> ${esc(data.files)}</p>` : "";
}
return `<details class="reviewed">
<summary>审查文件 (${arr.length}) <span class="muted">点击展开/收起</span></summary>
<ul>${arr.map(f => `<li><code>${esc(f)}</code></li>`).join("")}</ul>
</details>`;
}
const metricLabels = {
sql_risk: "SQL 注入风险",
exception_coverage: "异常分支覆盖",
redundancy_rate: "代码冗余率",
high_risk_density: "高风险场景密度",
vulnerability_risk: "漏洞风险",
};
const gradeLabels = { good: "良好", warn: "警告", fail: "不合格", na: "不适用" };
const sevLabels = {
blocker: "🔴 阻塞", critical: "🔴 严重",
major: "🟡 主要", warn: "🟡 主要",
minor: "🔵 次要", informational: "🔵 次要",
};
let html = `<h1>代码审查报告</h1>
<div class="meta">
<span class="verdict ${verdictClass(data.verdict)}">${esc(data.verdict || "无结论")}</span>
&nbsp; 档位: <code>${esc(data.tier || "standard")}</code>
&nbsp; 范围: <code>${esc(data.scope || "change-level")}</code>
${data.baseline ? `&nbsp; 基线: <code>${esc(data.baseline)}</code>` : ""}
</div>`;
if (data.quality_score != null) html += `<p><b>PR 质量分:</b> ${esc(data.quality_score)}/10</p>`;
if (data.timestamp) html += `<p class="muted">生成时间: ${esc(data.timestamp)}</p>`;
html += renderReviewedFiles(data);
if (data.summary) html += `<p>${esc(data.summary)}</p>`;
const cov = data.coverage || {};
// The coverage section renders whenever file-count coverage OR line/unit
// coverage was computed. gate="line+unit" (feature reviews) returns
// coverage_pct=null, so the 全库/高风险 rows are skipped and only the
// line/unit rows + spot-check render.
if (cov && (cov.coverage_pct != null || cov.line_coverage_pct != null)) {
const isLineOnly = cov.coverage_pct == null;
const covOk = cov.target_reached;
const covCls = covOk ? "good" : "fail";
const covStatus = covOk ? "✅ 达标" : "🔴 覆盖不足";
const oTarget = cov.overall_target ?? cov.target ?? "N/A";
const hTarget = cov.high_risk_target ?? cov.target ?? "N/A";
html += `<h2>覆盖度</h2>
<p><span class="verdict ${covCls}">${covStatus}</span></p>`;
if (!isLineOnly) {
html += `<p><b>全库覆盖:</b> ${esc(cov.coverage_pct ?? "N/A")}% — 已深读 ${esc(cov.deep_read_count ?? "N/A")}/${esc(cov.total_files ?? "N/A")}(目标 ${esc(oTarget)}%</p>
<p><b>高风险覆盖:</b> ${esc(cov.high_risk_coverage_pct ?? "N/A")}% — 已深读 ${esc(cov.high_risk_deep_count ?? "N/A")}/${esc(cov.high_risk_total_files ?? "N/A")}(目标 ${esc(hTarget)}%</p>`;
}
html += renderLineUnit(cov);
html += renderSpotCheck(data.spot_check);
if (!isLineOnly && (cov.uncovered_files || []).length) {
html += `<p class="muted"><b>未深读文件:</b> ${esc(cov.uncovered_files.length)} 个(静默文件 ${esc((cov.silent_files || []).length)} 个)</p>`;
}
}
// Line / unit coverage (three-piece suite items 1-2). Fail-closed: a
// missing line/unit coverage renders "未执行 🔴" so reviews that skipped
// gate="both+line" or the three-piece data are visible, never silent green.
function renderLineUnit(cov) {
const linePct = cov.line_coverage_pct;
const unitPct = cov.unit_coverage_pct;
const lineTarget = cov.line_target ?? 95.0;
const unitTarget = cov.unit_target ?? 100.0;
const lineGap = (cov.line_gap_files || []).length;
const unitGap = (cov.unit_gap_files || []).length;
const missing = (cov.missing_data_files || []).length;
let s = "";
if (linePct == null || unitPct == null) {
s += `<p><b>行覆盖:</b> 未执行 🔴 <span class="muted">(coverage_tool 未用 gate="both+line" 或未传三件套数据)</span></p>`;
} else {
const lineOk = linePct >= lineTarget && lineGap === 0;
const unitOk = unitPct >= unitTarget && unitGap === 0;
s += `<p><b>行覆盖:</b> ${esc(linePct)}% — 目标 ${esc(lineTarget)}%(缺口 ${esc(lineGap)} 文件)${lineOk ? "✅" : "🔴"}</p>`;
s += `<p><b>单元覆盖:</b> ${esc(unitPct)}% — 目标 ${esc(unitTarget)}%(缺口 ${esc(unitGap)} 文件)${unitOk ? "✅" : "🔴"}</p>`;
}
if (missing) {
s += `<p class="muted"><b>三件套数据缺失:</b> ${esc(missing)} 个文件(缺 read_ranges/语义单元,已按 fail-closed 计为缺口)</p>`;
}
return s;
}
// Anti-fake spot check (three-piece suite item 3). Fail-closed: a
// missing/incomplete spot_check renders "未执行 🔴" so reviews that
// skipped the sampled re-read are visible instead of silently green.
function renderSpotCheck(spot) {
if (!spot) {
return `<p><b>防伪抽验:</b> 未执行 🔴 <span class="muted">(主代理未回读任何语义单元;Step 5.5 应执行每组抽 2 文件 × 2-3 单元并落盘 spot_check)</span></p>`;
}
const groups = spot.groups_sampled;
const files = spot.files_sampled;
const units = spot.units_sampled;
const fake = spot.fake_read_found || 0;
const rereread = spot.groups_rereread || [];
if (!units) {
return `<p><b>防伪抽验:</b> 未执行 🔴 <span class="muted">(spot_check 已上报但单元数为 0)</span></p>`;
}
const mark = (fake || rereread.length) ? "🔴 发现假读" : "✅";
let s = `<p><b>防伪抽验:</b> 抽样 ${esc(files)} 文件 / ${esc(units)} 单元 / ${esc(groups)} 组,假读 ${esc(fake)} ${mark}</p>`;
if (rereread.length) {
s += `<p class="muted">因假读重读组:${esc(rereread.join(", "))}</p>`;
}
return s;
}
const metrics = data.metrics || {};
const mkeys = Object.keys(metrics);
if (mkeys.length) {
html += `<h2>客观指标</h2><table><tr><th>指标</th><th>数值</th><th>评级</th><th>说明</th></tr>`;
for (const k of mkeys) {
const m = metrics[k] || {};
const g = m.grade || "na";
const label = metricLabels[k] || k;
const gradeText = gradeLabels[g] || g;
html += `<tr>
<td>${esc(label)}</td>
<td>${esc(m.value ?? "N/A")}</td>
<td class="grade ${esc(g)}">${esc(gradeText)}</td>
<td class="muted">${esc(m.note || "")}</td>
</tr>`;
}
html += `</table>`;
}
const issues = data.issues || [];
html += `<h2>问题清单 (${issues.length})</h2>`;
if (!issues.length) {
html += `<p class="muted">未发现问题。</p>`;
}
for (const i of issues) {
const sev = (i.severity || "minor").toLowerCase();
const sevLabel = sevLabels[sev] || i.severity;
html += `<div class="issue">
<span class="tag ${esc(sev)}">${esc(sevLabel)}</span>
<span class="cat">${esc(i.category)}</span>
${esc(i.message || "")}
${i.confidence != null ? `<span class="muted">(置信度 ${esc(i.confidence)}/10)</span>` : ""}
${i.location ? `<div class="loc">→ ${esc(i.location)}</div>` : ""}
${i.fix ? `<div class="fix"><b>修复建议:</b> ${esc(i.fix)}</div>` : ""}
</div>`;
}
const manual = data.manual_review || [];
if (manual.length) {
html += `<h2>需要人工审查</h2><ul>`;
for (const m of manual) html += `<li>${esc(m)}</li>`;
html += `</ul>`;
}
const judged = data.llm_judged || [];
if (judged.length) {
html += `<p class="muted"><b>需 LLM 判断的指标:</b> ${judged.map(esc).join(", ")}</p>`;
}
document.getElementById("app").innerHTML = html;
</script>
</body>
</html>
@@ -0,0 +1,82 @@
# Unified Review — Generic Checklist
Reference for the Layer-1 chain decomposition and gstack CRITICAL sub-pass.
Load the language-specific checklist when available (`java-spring.md`,
`python-django.md`, `python-fastapi.md`, `node-express.md`, `go-gin.md`,
`csharp-dotnet.md`, `rust.md`, `php-laravel.md`, `ruby-rails.md`); otherwise
use this generic list.
## Layer 1 — eight categories
For each changed area mark ✅ Clean / ⚠️ Issues Found / — N/A.
1. **Interface** — parameter validation, response conventions, HTTP status
codes, rate limiting, API versioning, protocol correctness
2. **Business** — logic aligns with requirements, state machine correctness,
idempotency design, distributed locks
3. **Data** — SQL injection, query performance, index usage, transaction
boundaries, cache invalidation
4. **Utility** — input validity, no side effects, error return values,
date/time timezone handling
5. **Error handling** — exception classification, fallback logic, error
message sanitization, retry with backoff
6. **Security** — AuthN/AuthZ, sensitive data masking, permission control,
CSRF/XSS prevention
7. **Performance** — N+1 queries, caching strategy, connection pooling,
batch operations, blocking in async paths
8. **Observability** — structured logging with correlation IDs, metrics,
health checks
## gstack CRITICAL sub-pass (highest severity)
### SQL & Data Safety
- String interpolation in SQL — use parameterized queries
- TOCTOU check-then-set — use atomic `WHERE` + update
- Bypassing model validations for direct DB writes
- N+1 queries — missing eager loading
### Race Conditions & Concurrency
- Read-check-write without uniqueness constraint / duplicate-key retry
- find-or-create without a unique DB index
- Status transitions not atomic (`WHERE old_status = ? UPDATE ...`)
- Unsafe HTML rendering on user-controlled data
### LLM Output Trust Boundary
- LLM-generated values (emails, URLs, names) written to DB without format
validation
- Structured tool output accepted without type/shape checks
- LLM-generated URLs fetched without an allowlist (SSRF)
- LLM output stored in knowledge bases without sanitization (stored prompt
injection)
### Shell Injection
- `subprocess` with `shell=True` AND interpolated command strings
- `os.system()` with variable interpolation
- `eval()`/`exec()` on LLM-generated code without sandboxing
### Enum & Value Completeness
- New enum/status/tier values: read (not just grep) every consumer that
switches/filters/displays the value
- Check allowlists and `case`/`if-elsif` chains for fall-through
## Suppressions — do NOT flag
- Harmless redundancy that aids readability
- "Add a comment explaining a threshold" — thresholds drift
- Consistency-only changes
- Anything already addressed in the diff
## Severity
- 🔴 **blocker** — must fix before merge (injection, secrets, missing
transaction, auth bypass) → verdict FAIL
- 🟡 **major** — should fix before merge (missing validation, missing
fallback, N+1, unmasked data)
- 🔵 **minor** — can optimize later (naming, duplicate code, comments)
## Confidence calibration
- 9-10 verified by reading specific code
- 7-8 high-confidence pattern match
- 5-6 medium — show with caveat
- 3-4 low — move to appendix
- 1-2 speculation — suppress unless severity would be P0
Every finding: `[SEVERITY] (confidence: N/10) file:line — problem → fix`.
@@ -0,0 +1,13 @@
# API Contract Specialist
Focus: API and interface contract changes in the diff.
- [ ] Breaking changes to public endpoints (paths, params, response shape)
- [ ] Versioning compatibility (deprecations, fallbacks)
- [ ] Request/response validation matches the schema
- [ ] Error response shape is consistent
- [ ] Authentication/authorization behavior unchanged for existing consumers
- [ ] Renamed/moved functions: all callers updated
Output JSON lines:
`{"severity":"CRITICAL|INFORMATIONAL","confidence":N,"path":"file","line":N,"category":"api-contract","summary":"...","fix":"...","source":"api-contract"}`
@@ -0,0 +1,15 @@
# Data Migration Specialist
Focus: database schema and data migrations in the diff.
- [ ] Migration idempotent and re-runnable
- [ ] Forward + rollback paths defined
- [ ] Backfill batched / resumable
- [ ] Type/precision changes do not truncate data
- [ ] Nullability/default changes safe for existing rows
- [ ] Application deploy compatible with old + new schema (expand/contract)
Insurance specialist — always runs, even when silent.
Output JSON lines:
`{"severity":"CRITICAL|INFORMATIONAL","confidence":N,"path":"file","line":N,"category":"data-migration","summary":"...","fix":"...","source":"data-migration"}`
@@ -0,0 +1,16 @@
# Maintainability Specialist
Focus: code quality and maintainability issues.
- [ ] Dead code / unreachable branches / unused variables
- [ ] Magic numbers → named constants
- [ ] Overcomplicated abstractions (indirection without payoff)
- [ ] Copy-paste blocks that should be shared (only when it aids clarity)
- [ ] Functions too large / doing too much
- [ ] Stale comments contradicting the code
Suppress: harmless redundancy that aids readability, comment-on-threshold
requests, consistency-only changes.
Output JSON lines:
`{"severity":"CRITICAL|INFORMATIONAL","confidence":N,"path":"file","line":N,"category":"maintainability","summary":"...","fix":"...","source":"maintainability"}`
@@ -0,0 +1,14 @@
# Performance Specialist
Focus: performance and resource efficiency in the diff.
- [ ] N+1 queries — missing eager loading
- [ ] Unindexed lookups in hot loops
- [ ] O(n×m) lookups in views/loops
- [ ] Blocking calls in async paths (sync subprocess, requests, sleep)
- [ ] Connection pool exhaustion, unbounded retries
- [ ] Bundle/asset size regressions (frontend)
- [ ] Redundant recomputation / missing caching
Output JSON lines:
`{"severity":"CRITICAL|INFORMATIONAL","confidence":N,"path":"file","line":N,"category":"performance","summary":"...","fix":"...","source":"performance"}`
@@ -0,0 +1,18 @@
# Red Team Specialist (conditional)
Focus: find what the primary and specialist reviewers MISSED. Only dispatched
when the diff is large (>200 lines) or a specialist found a critical issue.
Think like an attacker and a chaos engineer:
- [ ] Cross-cutting concerns the specialist checklists do not cover
- [ ] Integration boundary failures (service-to-service, module-to-module)
- [ ] Failure modes: what breaks in production under load, restart, partial
failure
- [ ] Silent data corruption paths (wrong results without errors)
- [ ] Error handling that swallows failures
- [ ] Trust boundary violations
- [ ] Race conditions and edge cases the primary review missed
Be adversarial. No compliments — just the problems. Tag findings with
`"source":"red-team"`. Output `NO FINDINGS` when nothing new is found.
@@ -0,0 +1,17 @@
# Security Specialist
Focus: security vulnerabilities in the diff.
- [ ] SQL injection (string interpolation, parameterized queries)
- [ ] AuthN/AuthZ bypasses, missing permission checks
- [ ] XSS (unsafe HTML rendering on user data)
- [ ] Sensitive data exposure / missing masking in logs and responses
- [ ] SSRF (fetching user/LLM-controlled URLs without allowlist)
- [ ] Command injection (`shell=True` + interpolation)
- [ ] Hardcoded secrets / credentials
- [ ] CSRF / missing rate limiting on auth endpoints
Insurance specialist — always runs, even when silent.
Output JSON lines:
`{"severity":"CRITICAL|INFORMATIONAL","confidence":N,"path":"file","line":N,"category":"security","summary":"...","fix":"...","source":"security"}`
@@ -0,0 +1,14 @@
# Testing Specialist
Focus: test coverage gaps and tests that would catch the issues found.
- [ ] Every changed function has at least a happy-path test
- [ ] Negative/error paths tested (invalid input, failure branches)
- [ ] Edge cases mirror the happy-path structure
- [ ] If the fix for a finding can be caught by a test, propose a minimal
`test_stub` (framework-detected: jest/vitest/rspec/pytest/go-test)
- [ ] Integration coverage for critical flows (DB, external calls)
- [ ] No assertion-only tests that pass trivially
Output JSON lines:
`{"severity":"CRITICAL|INFORMATIONAL","confidence":N,"path":"file","line":N,"category":"testing","summary":"...","fix":"...","test_stub":"...","source":"testing"}`
@@ -0,0 +1,28 @@
---
name: refactor-safely
description: Plan and execute safe refactoring using dependency analysis
---
## Refactor Safely
Use the knowledge graph to plan and execute refactoring with confidence.
### Steps
1. Use `refactor_tool` with mode="suggest" for community-driven refactoring suggestions.
2. Use `refactor_tool` with mode="dead_code" to find unreferenced code.
3. For renames, use `refactor_tool` with mode="rename" to preview all affected locations.
4. Use `apply_refactor_tool` with the refactor_id to apply renames.
5. After changes, run `detect_changes_tool` to verify the refactoring impact.
### Safety Checks
- Always preview before applying (rename mode gives you an edit list).
- Check `get_impact_radius_tool` before major refactors.
- Use `get_affected_flows_tool` to ensure no critical paths are broken.
- Run `find_large_functions` to identify decomposition targets.
## Token Efficiency Rules
- ALWAYS start with `get_minimal_context(task="<your task>")` before any other graph tool.
- Use `detail_level="minimal"` on all calls. Only escalate to "standard" when minimal is insufficient.
- Target: complete any review/debug/refactor task in ≤5 tool calls and ≤800 total output tokens.
@@ -0,0 +1,29 @@
---
name: review-changes
description: Perform a structured code review using change detection and impact
---
## Review Changes
Perform a thorough, risk-aware code review using the knowledge graph.
### Steps
1. Run `detect_changes_tool` to get risk-scored change analysis.
2. Run `get_affected_flows_tool` to find impacted execution paths.
3. For each high-risk function, run `query_graph_tool` with pattern="tests_for" to check test coverage.
4. Run `get_impact_radius_tool` to understand the blast radius.
5. For any untested changes, suggest specific test cases.
### Output Format
Provide findings grouped by risk level (high/medium/low) with:
- What changed and why it matters
- Test coverage status
- Suggested improvements
- Overall merge recommendation
## Token Efficiency Rules
- ALWAYS start with `get_minimal_context(task="<your task>")` before any other graph tool.
- Use `detail_level="minimal"` on all calls. Only escalate to "standard" when minimal is insufficient.
- Target: complete any review/debug/refactor task in ≤5 tool calls and ≤800 total output tokens.
@@ -0,0 +1,46 @@
---
name: review-delta
description: Review only changes since last commit using impact analysis. Token-efficient delta review with automatic blast-radius detection.
argument-hint: "[file or function name]"
---
# Review Delta
Perform a focused, token-efficient code review of only the changed code and its blast radius.
**Token optimization:** Before starting, call `get_docs_section_tool(section_name="review-delta")` for the optimized workflow. Use ONLY changed nodes + 2-hop neighbors in context.
## Steps
1. **Ensure the graph is current** by calling `build_or_update_graph_tool()` (incremental update).
2. **Get review context** by calling `get_review_context_tool()`. This returns:
- Changed files (auto-detected from git diff)
- Impacted nodes and files (blast radius)
- Source code snippets for changed areas
- Review guidance (test coverage gaps, wide impact warnings, inheritance concerns)
3. **Analyze the blast radius** by reviewing the `impacted_nodes` and `impacted_files` in the context. Focus on:
- Functions whose callers changed (may need signature/behavior verification)
- Classes with inheritance changes (Liskov substitution concerns)
- Files with many dependents (high-risk changes)
4. **Perform the review** using the context. For each changed file:
- Review the source snippet for correctness, style, and potential bugs
- Check if impacted callers/dependents need updates
- Verify test coverage using `query_graph_tool(pattern="tests_for", target=<function_name>)`
- Flag any untested changed functions
5. **Report findings** in a structured format:
- **Summary**: One-line overview of the changes
- **Risk level**: Low / Medium / High (based on blast radius)
- **Issues found**: Bugs, style issues, missing tests
- **Blast radius**: List of impacted files/functions
- **Recommendations**: Actionable suggestions
## Advantages Over Full-Repo Review
- Only sends changed + impacted code to the model (5-10x fewer tokens)
- Automatically identifies blast radius without manual file searching
- Provides structural context (who calls what, inheritance chains)
- Flags untested functions automatically
@@ -0,0 +1,66 @@
---
name: review-pr
description: Review a PR or branch diff using the knowledge graph for full structural context. Outputs a structured review with blast-radius analysis.
argument-hint: "[PR number or branch name]"
---
# Review PR
Perform a comprehensive code review of a pull request or branch diff using the knowledge graph.
**Token optimization:** Before starting, call `get_docs_section_tool(section_name="review-pr")` for the optimized workflow. Never include full files unless explicitly asked.
## Steps
1. **Identify the changes** for the PR:
- If a PR number or branch is provided, use `git diff main...<branch>` to get changed files
- Otherwise auto-detect from the current branch vs main/master
2. **Update the graph** by calling `build_or_update_graph_tool(base="main")` to ensure the graph reflects the current state.
3. **Get the full review context** by calling `get_review_context_tool(base="main")`:
- This uses `main` (or the specified base branch) as the diff base
- Returns all changed files across all commits in the PR
4. **Analyze impact** by calling `get_impact_radius_tool(base="main")`:
- Review the blast radius across the entire PR
- Identify high-risk areas (widely depended-upon code)
5. **Deep-dive each changed file**:
- Read the full source of files with significant changes
- Use `query_graph_tool(pattern="callers_of", target=<func>)` for high-risk functions
- Use `query_graph_tool(pattern="tests_for", target=<func>)` to verify test coverage
- Check for breaking changes in public APIs
6. **Generate structured review output**:
```
## PR Review: <title>
### Summary
<1-3 sentence overview>
### Risk Assessment
- **Overall risk**: Low / Medium / High
- **Blast radius**: X files, Y functions impacted
- **Test coverage**: N changed functions covered / M total
### File-by-File Review
#### <file_path>
- Changes: <description>
- Impact: <who depends on this>
- Issues: <bugs, style, concerns>
### Missing Tests
- <function_name> in <file> - no test coverage found
### Recommendations
1. <actionable suggestion>
2. <actionable suggestion>
```
## Tips
- For large PRs, focus on the highest-impact files first (most dependents)
- Use `semantic_search_nodes_tool` to find related code the PR might have missed
- Check if renamed/moved functions have updated all callers
@@ -0,0 +1,69 @@
---
name: unified-review
description: Three-layer unified code review fusing CRG graph context with ai-code-review scoring methodology and gstack-review fix-first workflow
---
# Unified Review
Perform a three-layer, read-only code review that fuses:
- **CRG graph context** (blast radius, test gaps, affected flows)
- **ai-code-review methodology** (Layer-1 chain decomposition, Layer-2 quantitative scoring, Layer-3 acceptance)
- **gstack-review workflow** (confidence calibration, fix-first, specialist subagents, review-log persistence)
**This skill is READ-ONLY.** Every finding is presented to the user for a manual fix decision. Never apply code changes, commit, or push.
## Token Efficiency Rules
- ALWAYS start with `get_minimal_context(task="unified review")`. Use `detail_level="minimal"` on all calls; escalate to `"standard"` only when a metric or finding needs evidence.
## Step 0 - Scope and tier
Read `.code-review.yaml` at the repo root (default tier `standard`). Tiers: `fast` (Layer-1 + blockers only), `standard` (all layers), `strict` (full + every blocker/major fix needs per-item user confirmation). Single-invocation overrides: `快速审查` → fast, `严格审查` → strict.
Detect the project language/framework and the review scope (change/file/service/chain level). Declare both in the report header.
## Step 1 - Graph context (CRG)
1. Call `build_or_update_graph_tool()` to ensure the graph is current.
2. Call `get_review_context_tool()` for changed files, blast radius, source snippets and review guidance.
3. Call `detect_changes_tool()` for risk-scored change analysis, test gaps and affected flows.
## Step 2 - Layer 1: Chain decomposition (ai-code-review)
Inspect the changed code across eight categories: interface, business, data, utility, error handling, security, performance, observability. Mark each `✅ Clean / ⚠️ Issues Found / — N/A`. Apply the gstack CRITICAL categories as a sub-pass: SQL & Data Safety, Race Conditions & Concurrency, LLM Output Trust Boundary, Shell Injection, and Enum & Value Completeness. Enum completeness requires reading code OUTSIDE the diff (Grep for sibling values, then Read each consumer).
## Step 3 - Layer 2: Quantitative scoring
Call `score_review_tool()` for the objective metrics (SQL risk, exception coverage, redundancy, high-risk density, vulnerability heuristic). The remaining metrics (requirement coverage, logic alignment, trust boundaries) are judged by you from the requirements doc or a generic baseline; without a requirements doc halve their weight in the verdict.
## Step 4 - Specialist dispatch (gstack, diff >= 50 lines)
When the diff has 50+ changed lines, dispatch specialist subagents in parallel via the Agent/task tool, each with a fresh context and its own checklist: testing, maintainability, security, performance, data-migration, api-contract. Security and data-migration always run (insurance). Collect each specialist's JSON findings.
## Step 5 - Merge and dedupe
Call `dedupe_findings_tool(findings=<all raw findings>)` to merge by fingerprint (`path:line:category`), boost multi-source confidence (+1, cap 10), route low-confidence findings to the appendix, and compute the PR quality score.
## Step 6 - Manual adjudication (READ-ONLY)
Present every merged finding with its severity (🔴 blocker / 🟡 major / 🔵 minor), confidence (1-10), file:line and a proposed fix. Group by severity and ask the user per batch: fix / skip / self-fix. 🔴 blockers cannot be batch-skipped. Record skipped findings for prior-review suppression on the next run. **Do not modify code.**
## Step 7 - Acceptance gate (ai-code-review)
Any 🔴 blocker → verdict `❌ FAIL` regardless of other scores. Classify each finding as Ready / Needs Fix / Unusable. Verify the change does not deviate from requirements or architecture conventions.
## Step 8 - Report
Call `generate_report_tool(review_data=<collected verdict, metrics, findings, tier, scope>)` to write `code-review-report.html` and `code-review-report.md` (default `format="both"`). Pass `reviewed_files: [path, ...]` (changed/reviewed files) so the report header lists them in a collapsible `<details>` list. Also present the text report inline.
## Step 9 - Persistence (optional)
If the `gstack-review-log` binary is available, record the review outcome (status, counts, quality score, per-finding actions). If it is unavailable, skip silently.
## Output Format
`Unified Review: N issues (X blocker, Y major, Z minor) — verdict: ✅ PASS / ❌ FAIL`. List each issue with severity, confidence, file:line, problem, and proposed fix. List manual-review items (payment, order, inventory, permission, distributed-lock, data-migration) explicitly.
## Token Efficiency Rules
- ALWAYS start with `get_minimal_context(task="unified review")` before any other graph tool.
- Use `detail_level="minimal"` on all calls. Only escalate to `"standard"` when minimal is insufficient.
- Target: complete a unified review in ≤8 tool calls and ≤1200 total output tokens.
@@ -0,0 +1,19 @@
# Unified Review — Common Mistakes
- **Skipping graph context** — always run `get_minimal_context` first; CRG
context is what makes the review token-efficient and blast-radius aware.
- **Rushing to fix** — this skill is READ-ONLY. Present findings, wait for
user decision. Never apply fixes, commit, or push.
- **Ignoring tier** — read `.code-review.yaml`. `fast` skips Layer 2/3;
`strict` requires per-item confirmation for every blocker/major.
- **Judging metrics without evidence** — `score_review_tool` outputs are
heuristics. Cite the evidence, and let the LLM confirm SQL/exception/vuln
findings before presenting them as facts.
- **Missing manual-review modules** — payment, order, inventory, permission,
distributed-lock, data-migration always require a manual review checklist.
- **Forgetting enum completeness reads OUTSIDE the diff** — grep sibling
values, then read each consumer; in-diff review alone is insufficient.
- **Batch-skipping blockers** — 🔴 blockers cannot be batch-skipped; each
needs an explicit user decision.
- **Not producing the report** — always call `generate_report_tool` at the
end and present the text report inline.
@@ -0,0 +1,12 @@
# Data Migration — Manual Review Checklist
High-risk module: schema/data migration requires human confirmation.
- [ ] Migration is idempotent and re-runnable
- [ ] Forward and rollback paths both defined and tested
- [ ] Backfill is batched / resumable for large tables
- [ ] Data type / precision changes do not silently truncate
- [ ] Nullability and default changes safe for existing rows
- [ ] Migration ordering across shards / replicas is consistent
- [ ] Application deploys compatibly with both old and new schema (expand/contract)
- [ ] Irreversible operations are flagged with a documented reason
@@ -0,0 +1,11 @@
# Distributed Lock — Manual Review Checklist
High-risk module: distributed-lock changes require architecture confirmation.
- [ ] Lock has a TTL / expiry — no permanent deadlock after crash
- [ ] Lock release is atomic and ownership-checked (compare-and-delete)
- [ ] Lock scope is correct (key includes the right entity identifiers)
- [ ] Renewal / watchdog exists for long critical sections
- [ ] Locking order is consistent across paths (no lock-ordering deadlock)
- [ ] Fencing tokens / version check prevents stale-holder writes
- [ ] Fail-open vs fail-closed behavior is intentional and documented
@@ -0,0 +1,11 @@
# Inventory Module — Manual Review Checklist
High-risk module: stock/inventory changes require human confirmation.
- [ ] Stock decrement is atomic (conditional UPDATE, not read-then-write)
- [ ] Oversell prevented: `UPDATE ... SET qty = qty - ? WHERE qty >= ?`
- [ ] Reservation vs. deduction semantics are consistent
- [ ] Concurrent orders cannot both reserve the last unit
- [ ] Restock/return increments handled correctly
- [ ] Inventory events are idempotent (retry-safe)
- [ ] Async stock updates propagate to downstream (warehouse, carts) safely
@@ -0,0 +1,12 @@
# Order Module — Manual Review Checklist
High-risk module: order lifecycle changes require human confirmation.
- [ ] State machine transitions are atomic (`WHERE status = ?` updates)
- [ ] Cancellation / timeout / expiry paths complete all side effects
- [ ] Order idempotency key prevents duplicate order creation
- [ ] Price/lock snapshot captured at order time, not at payment time
- [ ] Partial fulfillment / split-shipment handled
- [ ] Negative or inconsistent totals impossible
- [ ] Concurrent edits (cart + order) do not corrupt state
- [ ] Audit trail: every status change logged with reason
@@ -0,0 +1,14 @@
# Payment Module — Manual Review Checklist
High-risk module: payment changes require human confirmation for every
blocker/major fix.
- [ ] Callback idempotency: a duplicated webhook/callback does not double-charge
- [ ] Amounts stored as fixed-point (integers/cents), never floats
- [ ] Currency codes and precision handled correctly
- [ ] Provider signature / HMAC verification on callbacks
- [ ] Refund logic: correct reversal, no double-refund
- [ ] Failure path: payment timeout, declined, retry semantics
- [ ] Transaction boundary spans charge + order-state update
- [ ] Sensitive data (PAN, tokens) never logged or masked on output
- [ ] Ledger/journal entries are append-only and auditable
@@ -0,0 +1,11 @@
# Permission Module — Manual Review Checklist
High-risk module: authorization changes require product/human confirmation.
- [ ] Every endpoint/action enforces the intended permission — no default-allow
- [ ] Role hierarchy / scoping (tenant, org, user) is consistent
- [ ] Object-level permissions checked on read AND write
- [ ] Deny-before-allow ordering is safe
- [ ] Permission checks cannot be bypassed via IDs, query params, or bulk ops
- [ ] New permission/role values handled by all consumers (enum completeness)
- [ ] Sensitive actions audited with actor + target
@@ -0,0 +1,238 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>代码审查报告</title>
<style>
:root { --border:#d0d7de; --bg:#f6f8fa; --fg:#1f2328; --muted:#57606a;
--good:#1a7f37; --warn:#9a6700; --fail:#cf222e; --na:#57606a;
--blocker:#cf222e; --major:#9a6700; --minor:#57606a;
--critical:#cf222e; --informational:#0969da; }
* { box-sizing: border-box; }
body { font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
margin:0; padding:2rem 1rem; color:var(--fg); background:#fff; line-height:1.55; }
.wrap { max-width:960px; margin:0 auto; }
h1 { font-size:1.5rem; margin:0 0 .25rem; }
h2 { font-size:1.1rem; margin:1.5rem 0 .5rem; padding-bottom:.25rem;
border-bottom:1px solid var(--border); }
.meta { color:var(--muted); font-size:.9rem; margin-bottom:1.5rem; }
.verdict { display:inline-block; padding:.25rem .75rem; border-radius:20px;
font-weight:700; font-size:.95rem; }
.verdict.pass { background:#dafbe1; color:var(--good); }
.verdict.fail { background:#ffebe9; color:var(--fail); }
table { border-collapse:collapse; width:100%; margin:.75rem 0; }
th,td { border:1px solid var(--border); padding:.45rem .6rem; text-align:left;
font-size:.9rem; vertical-align:top; }
th { background:var(--bg); }
.grade.good { color:var(--good); font-weight:600; }
.grade.warn { color:var(--warn); font-weight:600; }
.grade.fail { color:var(--fail); font-weight:600; }
.grade.na { color:var(--na); }
.issue { margin:.6rem 0; padding:.65rem .8rem; border:1px solid var(--border);
border-radius:6px; background:#fff; }
.issue .tag { display:inline-block; padding:.1rem .5rem; border-radius:10px;
font-size:.75rem; font-weight:700; color:#fff; margin-right:.5rem; }
.tag.blocker, .tag.critical { background:var(--blocker); }
.tag.major, .tag.warn { background:var(--major); }
.tag.minor, .tag.informational { background:var(--minor); }
.issue .cat { font-weight:600; }
.issue .loc { color:var(--muted); font-size:.85rem; margin-top:.2rem; }
.issue .fix { margin-top:.35rem; font-size:.88rem; background:var(--bg);
padding:.4rem .6rem; border-radius:4px; }
.muted { color:var(--muted); font-size:.85rem; }
code { background:var(--bg); padding:.1rem .3rem; border-radius:4px;
font-size:.88em; }
details.reviewed { margin:.5rem 0; border:1px solid var(--border);
border-radius:6px; padding:.4rem .8rem; }
details.reviewed summary { cursor:pointer; font-weight:600; }
details.reviewed ul { margin:.4rem 0 0; padding-left:1.2rem; }
details.reviewed li { margin:.15rem 0; }
</style>
</head>
<body>
<div class="wrap" id="app"></div>
<script>
const data = {{REPORT_DATA}};
function esc(s) {
return String(s ?? "").replace(/[&<>"']/g, c => ({
"&":"&amp;", "<":"&lt;", ">":"&gt;", '"':"&quot;", "'":"&#39;"
})[c]);
}
function verdictClass(v) {
v = String(v || "").toUpperCase();
return v.includes("PASS") ? "pass" : "fail";
}
// Collapsible list of the reviewed files (native <details>/<summary>, no JS).
// Accepts an array OR a comma-separated string (agents pass both). Falls
// back to the flat ``files`` string when nothing structured is given.
function renderReviewedFiles(data) {
let arr = data.reviewed_files;
if (typeof arr === "string") {
arr = arr.split(",").map(s => s.trim()).filter(Boolean);
}
if (!Array.isArray(arr) || !arr.length) {
return data.files ? `<p><b>文件:</b> ${esc(data.files)}</p>` : "";
}
return `<details class="reviewed">
<summary>审查文件 (${arr.length}) <span class="muted">点击展开/收起</span></summary>
<ul>${arr.map(f => `<li><code>${esc(f)}</code></li>`).join("")}</ul>
</details>`;
}
const metricLabels = {
sql_risk: "SQL 注入风险",
exception_coverage: "异常分支覆盖",
redundancy_rate: "代码冗余率",
high_risk_density: "高风险场景密度",
vulnerability_risk: "漏洞风险",
};
const gradeLabels = { good: "良好", warn: "警告", fail: "不合格", na: "不适用" };
const sevLabels = {
blocker: "🔴 阻塞", critical: "🔴 严重",
major: "🟡 主要", warn: "🟡 主要",
minor: "🔵 次要", informational: "🔵 次要",
};
let html = `<h1>代码审查报告</h1>
<div class="meta">
<span class="verdict ${verdictClass(data.verdict)}">${esc(data.verdict || "无结论")}</span>
&nbsp; 档位: <code>${esc(data.tier || "standard")}</code>
&nbsp; 范围: <code>${esc(data.scope || "change-level")}</code>
${data.baseline ? `&nbsp; 基线: <code>${esc(data.baseline)}</code>` : ""}
</div>`;
if (data.quality_score != null) html += `<p><b>PR 质量分:</b> ${esc(data.quality_score)}/10</p>`;
if (data.timestamp) html += `<p class="muted">生成时间: ${esc(data.timestamp)}</p>`;
html += renderReviewedFiles(data);
if (data.summary) html += `<p>${esc(data.summary)}</p>`;
const cov = data.coverage || {};
// The coverage section renders whenever file-count coverage OR line/unit
// coverage was computed. gate="line+unit" (feature reviews) returns
// coverage_pct=null, so the 全库/高风险 rows are skipped and only the
// line/unit rows + spot-check render.
if (cov && (cov.coverage_pct != null || cov.line_coverage_pct != null)) {
const isLineOnly = cov.coverage_pct == null;
const covOk = cov.target_reached;
const covCls = covOk ? "good" : "fail";
const covStatus = covOk ? "✅ 达标" : "🔴 覆盖不足";
const oTarget = cov.overall_target ?? cov.target ?? "N/A";
const hTarget = cov.high_risk_target ?? cov.target ?? "N/A";
html += `<h2>覆盖度</h2>
<p><span class="verdict ${covCls}">${covStatus}</span></p>`;
if (!isLineOnly) {
html += `<p><b>全库覆盖:</b> ${esc(cov.coverage_pct ?? "N/A")}% — 已深读 ${esc(cov.deep_read_count ?? "N/A")}/${esc(cov.total_files ?? "N/A")}(目标 ${esc(oTarget)}%</p>
<p><b>高风险覆盖:</b> ${esc(cov.high_risk_coverage_pct ?? "N/A")}% — 已深读 ${esc(cov.high_risk_deep_count ?? "N/A")}/${esc(cov.high_risk_total_files ?? "N/A")}(目标 ${esc(hTarget)}%</p>`;
}
html += renderLineUnit(cov);
html += renderSpotCheck(data.spot_check);
if (!isLineOnly && (cov.uncovered_files || []).length) {
html += `<p class="muted"><b>未深读文件:</b> ${esc(cov.uncovered_files.length)} 个(静默文件 ${esc((cov.silent_files || []).length)} 个)</p>`;
}
}
// Line / unit coverage (three-piece suite items 1-2). Fail-closed: a
// missing line/unit coverage renders "未执行 🔴" so reviews that skipped
// gate="both+line" or the three-piece data are visible, never silent green.
function renderLineUnit(cov) {
const linePct = cov.line_coverage_pct;
const unitPct = cov.unit_coverage_pct;
const lineTarget = cov.line_target ?? 95.0;
const unitTarget = cov.unit_target ?? 100.0;
const lineGap = (cov.line_gap_files || []).length;
const unitGap = (cov.unit_gap_files || []).length;
const missing = (cov.missing_data_files || []).length;
let s = "";
if (linePct == null || unitPct == null) {
s += `<p><b>行覆盖:</b> 未执行 🔴 <span class="muted">(coverage_tool 未用 gate="both+line" 或未传三件套数据)</span></p>`;
} else {
const lineOk = linePct >= lineTarget && lineGap === 0;
const unitOk = unitPct >= unitTarget && unitGap === 0;
s += `<p><b>行覆盖:</b> ${esc(linePct)}% — 目标 ${esc(lineTarget)}%(缺口 ${esc(lineGap)} 文件)${lineOk ? "✅" : "🔴"}</p>`;
s += `<p><b>单元覆盖:</b> ${esc(unitPct)}% — 目标 ${esc(unitTarget)}%(缺口 ${esc(unitGap)} 文件)${unitOk ? "✅" : "🔴"}</p>`;
}
if (missing) {
s += `<p class="muted"><b>三件套数据缺失:</b> ${esc(missing)} 个文件(缺 read_ranges/语义单元,已按 fail-closed 计为缺口)</p>`;
}
return s;
}
// Anti-fake spot check (three-piece suite item 3). Fail-closed: a
// missing/incomplete spot_check renders "未执行 🔴" so reviews that
// skipped the sampled re-read are visible instead of silently green.
function renderSpotCheck(spot) {
if (!spot) {
return `<p><b>防伪抽验:</b> 未执行 🔴 <span class="muted">(主代理未回读任何语义单元;Step 5.5 应执行每组抽 2 文件 × 2-3 单元并落盘 spot_check)</span></p>`;
}
const groups = spot.groups_sampled;
const files = spot.files_sampled;
const units = spot.units_sampled;
const fake = spot.fake_read_found || 0;
const rereread = spot.groups_rereread || [];
if (!units) {
return `<p><b>防伪抽验:</b> 未执行 🔴 <span class="muted">(spot_check 已上报但单元数为 0)</span></p>`;
}
const mark = (fake || rereread.length) ? "🔴 发现假读" : "✅";
let s = `<p><b>防伪抽验:</b> 抽样 ${esc(files)} 文件 / ${esc(units)} 单元 / ${esc(groups)} 组,假读 ${esc(fake)} ${mark}</p>`;
if (rereread.length) {
s += `<p class="muted">因假读重读组:${esc(rereread.join(", "))}</p>`;
}
return s;
}
const metrics = data.metrics || {};
const mkeys = Object.keys(metrics);
if (mkeys.length) {
html += `<h2>客观指标</h2><table><tr><th>指标</th><th>数值</th><th>评级</th><th>说明</th></tr>`;
for (const k of mkeys) {
const m = metrics[k] || {};
const g = m.grade || "na";
const label = metricLabels[k] || k;
const gradeText = gradeLabels[g] || g;
html += `<tr>
<td>${esc(label)}</td>
<td>${esc(m.value ?? "N/A")}</td>
<td class="grade ${esc(g)}">${esc(gradeText)}</td>
<td class="muted">${esc(m.note || "")}</td>
</tr>`;
}
html += `</table>`;
}
const issues = data.issues || [];
html += `<h2>问题清单 (${issues.length})</h2>`;
if (!issues.length) {
html += `<p class="muted">未发现问题。</p>`;
}
for (const i of issues) {
const sev = (i.severity || "minor").toLowerCase();
const sevLabel = sevLabels[sev] || i.severity;
html += `<div class="issue">
<span class="tag ${esc(sev)}">${esc(sevLabel)}</span>
<span class="cat">${esc(i.category)}</span>
${esc(i.message || "")}
${i.confidence != null ? `<span class="muted">(置信度 ${esc(i.confidence)}/10)</span>` : ""}
${i.location ? `<div class="loc">→ ${esc(i.location)}</div>` : ""}
${i.fix ? `<div class="fix"><b>修复建议:</b> ${esc(i.fix)}</div>` : ""}
</div>`;
}
const manual = data.manual_review || [];
if (manual.length) {
html += `<h2>需要人工审查</h2><ul>`;
for (const m of manual) html += `<li>${esc(m)}</li>`;
html += `</ul>`;
}
const judged = data.llm_judged || [];
if (judged.length) {
html += `<p class="muted"><b>需 LLM 判断的指标:</b> ${judged.map(esc).join(", ")}</p>`;
}
document.getElementById("app").innerHTML = html;
</script>
</body>
</html>
@@ -0,0 +1,82 @@
# Unified Review — Generic Checklist
Reference for the Layer-1 chain decomposition and gstack CRITICAL sub-pass.
Load the language-specific checklist when available (`java-spring.md`,
`python-django.md`, `python-fastapi.md`, `node-express.md`, `go-gin.md`,
`csharp-dotnet.md`, `rust.md`, `php-laravel.md`, `ruby-rails.md`); otherwise
use this generic list.
## Layer 1 — eight categories
For each changed area mark ✅ Clean / ⚠️ Issues Found / — N/A.
1. **Interface** — parameter validation, response conventions, HTTP status
codes, rate limiting, API versioning, protocol correctness
2. **Business** — logic aligns with requirements, state machine correctness,
idempotency design, distributed locks
3. **Data** — SQL injection, query performance, index usage, transaction
boundaries, cache invalidation
4. **Utility** — input validity, no side effects, error return values,
date/time timezone handling
5. **Error handling** — exception classification, fallback logic, error
message sanitization, retry with backoff
6. **Security** — AuthN/AuthZ, sensitive data masking, permission control,
CSRF/XSS prevention
7. **Performance** — N+1 queries, caching strategy, connection pooling,
batch operations, blocking in async paths
8. **Observability** — structured logging with correlation IDs, metrics,
health checks
## gstack CRITICAL sub-pass (highest severity)
### SQL & Data Safety
- String interpolation in SQL — use parameterized queries
- TOCTOU check-then-set — use atomic `WHERE` + update
- Bypassing model validations for direct DB writes
- N+1 queries — missing eager loading
### Race Conditions & Concurrency
- Read-check-write without uniqueness constraint / duplicate-key retry
- find-or-create without a unique DB index
- Status transitions not atomic (`WHERE old_status = ? UPDATE ...`)
- Unsafe HTML rendering on user-controlled data
### LLM Output Trust Boundary
- LLM-generated values (emails, URLs, names) written to DB without format
validation
- Structured tool output accepted without type/shape checks
- LLM-generated URLs fetched without an allowlist (SSRF)
- LLM output stored in knowledge bases without sanitization (stored prompt
injection)
### Shell Injection
- `subprocess` with `shell=True` AND interpolated command strings
- `os.system()` with variable interpolation
- `eval()`/`exec()` on LLM-generated code without sandboxing
### Enum & Value Completeness
- New enum/status/tier values: read (not just grep) every consumer that
switches/filters/displays the value
- Check allowlists and `case`/`if-elsif` chains for fall-through
## Suppressions — do NOT flag
- Harmless redundancy that aids readability
- "Add a comment explaining a threshold" — thresholds drift
- Consistency-only changes
- Anything already addressed in the diff
## Severity
- 🔴 **blocker** — must fix before merge (injection, secrets, missing
transaction, auth bypass) → verdict FAIL
- 🟡 **major** — should fix before merge (missing validation, missing
fallback, N+1, unmasked data)
- 🔵 **minor** — can optimize later (naming, duplicate code, comments)
## Confidence calibration
- 9-10 verified by reading specific code
- 7-8 high-confidence pattern match
- 5-6 medium — show with caveat
- 3-4 low — move to appendix
- 1-2 speculation — suppress unless severity would be P0
Every finding: `[SEVERITY] (confidence: N/10) file:line — problem → fix`.
@@ -0,0 +1,13 @@
# API Contract Specialist
Focus: API and interface contract changes in the diff.
- [ ] Breaking changes to public endpoints (paths, params, response shape)
- [ ] Versioning compatibility (deprecations, fallbacks)
- [ ] Request/response validation matches the schema
- [ ] Error response shape is consistent
- [ ] Authentication/authorization behavior unchanged for existing consumers
- [ ] Renamed/moved functions: all callers updated
Output JSON lines:
`{"severity":"CRITICAL|INFORMATIONAL","confidence":N,"path":"file","line":N,"category":"api-contract","summary":"...","fix":"...","source":"api-contract"}`
@@ -0,0 +1,15 @@
# Data Migration Specialist
Focus: database schema and data migrations in the diff.
- [ ] Migration idempotent and re-runnable
- [ ] Forward + rollback paths defined
- [ ] Backfill batched / resumable
- [ ] Type/precision changes do not truncate data
- [ ] Nullability/default changes safe for existing rows
- [ ] Application deploy compatible with old + new schema (expand/contract)
Insurance specialist — always runs, even when silent.
Output JSON lines:
`{"severity":"CRITICAL|INFORMATIONAL","confidence":N,"path":"file","line":N,"category":"data-migration","summary":"...","fix":"...","source":"data-migration"}`
@@ -0,0 +1,16 @@
# Maintainability Specialist
Focus: code quality and maintainability issues.
- [ ] Dead code / unreachable branches / unused variables
- [ ] Magic numbers → named constants
- [ ] Overcomplicated abstractions (indirection without payoff)
- [ ] Copy-paste blocks that should be shared (only when it aids clarity)
- [ ] Functions too large / doing too much
- [ ] Stale comments contradicting the code
Suppress: harmless redundancy that aids readability, comment-on-threshold
requests, consistency-only changes.
Output JSON lines:
`{"severity":"CRITICAL|INFORMATIONAL","confidence":N,"path":"file","line":N,"category":"maintainability","summary":"...","fix":"...","source":"maintainability"}`
@@ -0,0 +1,14 @@
# Performance Specialist
Focus: performance and resource efficiency in the diff.
- [ ] N+1 queries — missing eager loading
- [ ] Unindexed lookups in hot loops
- [ ] O(n×m) lookups in views/loops
- [ ] Blocking calls in async paths (sync subprocess, requests, sleep)
- [ ] Connection pool exhaustion, unbounded retries
- [ ] Bundle/asset size regressions (frontend)
- [ ] Redundant recomputation / missing caching
Output JSON lines:
`{"severity":"CRITICAL|INFORMATIONAL","confidence":N,"path":"file","line":N,"category":"performance","summary":"...","fix":"...","source":"performance"}`
@@ -0,0 +1,18 @@
# Red Team Specialist (conditional)
Focus: find what the primary and specialist reviewers MISSED. Only dispatched
when the diff is large (>200 lines) or a specialist found a critical issue.
Think like an attacker and a chaos engineer:
- [ ] Cross-cutting concerns the specialist checklists do not cover
- [ ] Integration boundary failures (service-to-service, module-to-module)
- [ ] Failure modes: what breaks in production under load, restart, partial
failure
- [ ] Silent data corruption paths (wrong results without errors)
- [ ] Error handling that swallows failures
- [ ] Trust boundary violations
- [ ] Race conditions and edge cases the primary review missed
Be adversarial. No compliments — just the problems. Tag findings with
`"source":"red-team"`. Output `NO FINDINGS` when nothing new is found.
@@ -0,0 +1,17 @@
# Security Specialist
Focus: security vulnerabilities in the diff.
- [ ] SQL injection (string interpolation, parameterized queries)
- [ ] AuthN/AuthZ bypasses, missing permission checks
- [ ] XSS (unsafe HTML rendering on user data)
- [ ] Sensitive data exposure / missing masking in logs and responses
- [ ] SSRF (fetching user/LLM-controlled URLs without allowlist)
- [ ] Command injection (`shell=True` + interpolation)
- [ ] Hardcoded secrets / credentials
- [ ] CSRF / missing rate limiting on auth endpoints
Insurance specialist — always runs, even when silent.
Output JSON lines:
`{"severity":"CRITICAL|INFORMATIONAL","confidence":N,"path":"file","line":N,"category":"security","summary":"...","fix":"...","source":"security"}`
@@ -0,0 +1,14 @@
# Testing Specialist
Focus: test coverage gaps and tests that would catch the issues found.
- [ ] Every changed function has at least a happy-path test
- [ ] Negative/error paths tested (invalid input, failure branches)
- [ ] Edge cases mirror the happy-path structure
- [ ] If the fix for a finding can be caught by a test, propose a minimal
`test_stub` (framework-detected: jest/vitest/rspec/pytest/go-test)
- [ ] Integration coverage for critical flows (DB, external calls)
- [ ] No assertion-only tests that pass trivially
Output JSON lines:
`{"severity":"CRITICAL|INFORMATIONAL","confidence":N,"path":"file","line":N,"category":"testing","summary":"...","fix":"...","test_stub":"...","source":"testing"}`