OneKey PR Code Review
输出语言: 中文
Review Scope
- Base branch:
x
- Diff:
git fetch origin && git diff origin/x...HEAD (triple-dot)
Workflow
- Checkout —
gh pr checkout <PR_NUMBER> (skip if already on branch)
- Scope —
git diff origin/x...HEAD --stat to see change scope
- Triage — Determine which review modules apply (see triage table)
- Primary Review — Read each changed file, apply relevant checks from
references/
- Codex Cross-Review — If Codex available, run full parallel review (see below)
- PR Comment Analysis — Fetch all existing PR comments (bot + human), analyze with local codebase context (see below)
- Merge Findings — Combine primary + Codex + PR comment findings, deduplicate, annotate confidence
- Score — Rate the PR across 4 dimensions (see Scoring System). This step is MANDATORY — every report MUST include the scoring table.
- Report — Generate structured report using the unified format. Follow the template exactly — every section is required.
- GH Comment — Post qualifying findings as inline PR comments immediately (do not wait for confirmation)
Codex Cross-Review Integration
Check if Codex is available by confirming the codex:codex-rescue subagent type can be dispatched. If uncertain, invoke /codex:setup to check readiness.
If available:
- Dispatch a full independent review to Codex via
Agent(subagent_type="codex:codex-rescue"):Agent(
subagent_type = "codex:codex-rescue",
prompt = "Review this PR diff for the OneKey crypto wallet monorepo. Focus on:
- Security vulnerabilities (secret leakage, auth bypass, supply-chain risks)
- Runtime bugs (race conditions, null safety, memory leaks)
- Architecture violations (import hierarchy, cross-platform issues)
- Code quality (hooks safety, error handling, performance)
Report each finding with: file:line, severity (Critical/High/Medium/Low), description, fix suggestion.
Diff:
${FULL_DIFF}"
)
- Parse Agent result for structured findings
- Merge into primary review:
- Both found same issue → Mark
{Cross-validated ✅}, auto-promote to 🔵 High confidence
- Codex-only finding → Include with tag
[Codex], review manually to assign confidence
- Primary-only finding → Include normally
- Add a Codex 交叉验证摘要 table in the report (see report template)
If unavailable: Skip silently. Set "Codex 交叉验证: ⏭️ 未启用" in the report header. Do NOT mention Codex anywhere else.
PR Comment Analysis
Collect ALL existing comments on the PR — bot and human — then analyze each with your local codebase context. You have full source access, type system, and dependency graph; most commenters only saw the diff. Use this asymmetry.
Fetching All Comments
Use gh api to get full user metadata (including type field for bot detection):
# Top-level PR reviews (review bodies)
gh api repos/{owner}/{repo}/pulls/{pr_number}/reviews \
--jq '[.[] | select(.body != "") | {author: .user.login, is_bot: (.user.type == "Bot"), body: .body, state: .state, association: .author_association}]'
# Inline review comments (file:line annotations)
gh api repos/{owner}/{repo}/pulls/{pr_number}/comments \
--jq '[.[] | {author: .user.login, is_bot: (.user.type == "Bot"), path: .path, line: .line, body: .body, association: .author_association}]'
# General PR comments (issue-level)
gh api repos/{owner}/{repo}/issues/{pr_number}/comments \
--jq '[.[] | {author: .user.login, is_bot: (.user.type == "Bot"), body: .body, association: .author_association}]'
Bot detection — use the user.type == "Bot" field from GitHub API, not hardcoded username lists. This automatically covers any bot (current and future) without maintenance.
If no comments exist, set "PR 评论分析: ⏭️ 无评论" in the report header and skip this section.
Analysis Framework
For each substantive comment (skip empty approvals, CI status badges, pure formatting):
| Verdict |
Meaning |
Action |
| ✅ Confirmed |
Comment identifies a real issue |
Include in findings, tag source [<author>] |
| 🔍 Enriched |
Real issue, but analysis is shallow or fix is wrong |
Include with deeper fix guidance from your codebase knowledge |
| ❌ Noise |
Not an issue given full codebase context |
Note in "评论误报分析" with brief explanation of why |
| 📋 Already Covered |
Your primary review caught it |
Cross-validate, boost confidence |
Your local advantages — use them aggressively:
- Full source — trace data flow across files, not just the diff
- Type system — run
tsc, verify types end-to-end
- Architecture — you know OneKey's import hierarchy and platform patterns
- Dependencies —
yarn info, changelogs, actual vulnerability reachability
- Runtime reasoning — state flows, async lifecycles, race conditions
When someone flags something vague, dig into the source to confirm or refute. When a comment misses context (e.g., a function is safely guarded upstream), explain why. When a comment is right, amplify with richer context.
Cross-Validation Rules
- Comment + primary review agree → Mark
{Cross-validated ✅}, promote to 🔵 High
- Comment-only finding you confirm → Include at appropriate confidence with
[<author>] tag
- Comment-only finding you can't confirm or refute → Include as ⚪ Low with note
- Comment you refute with evidence → Add to "评论误报分析" section
Security Comment Special Handling
For security-related comments (from bots like Snyk/Dependabot or from human reviewers):
- Vulnerability reports — check if the vulnerable code path is actually reachable in OneKey's usage
- License issues — verify against OneKey's license policy
- Dependency alerts — check if the flagged version is actually used (not just in lockfile)
Triage: Which Checks to Run
Run git diff origin/x...HEAD --name-only and match:
| Changed Files Match |
Load |
package.json, lockfiles, node_modules patches, patches/*.patch |
[security-and-supply-chain.md] — full supply-chain review |
**/auth/**, **/vault/**, **/signing/**, **/crypto/**, manifest.json, **/manifest/*.js |
[security-and-supply-chain.md] — full security review |
Any .ts/.tsx with business logic |
[code-quality-patterns.md] — hooks, race conditions, null safety |
.android.ts(x), .ios.ts(x), .native.ts(x), .desktop.ts(x), .ext.ts(x), .web.ts(x), native modules, BigNumber usage |
[onekey-platform-patterns.md] — platform crashes & numeric safety |
Shell scripts (.sh), CI workflows (.yml) |
[onekey-platform-patterns.md] — build & CI section |
Always check regardless of file type:
- Accidental file commits (
.DS_Store, .env, node_modules)
- Import hierarchy violations (see below)
- Avoidable reimplementation when stable existing helpers, hooks, services, or components already cover the same behavior (see below)
- PR description matches actual changes
- Run relevant commands from [quick-commands.md]
Import Hierarchy (ALWAYS verify)
@onekeyhq/shared <- FORBIDDEN to import from other OneKey packages
↓
@onekeyhq/components <- ONLY imports shared
↓
@onekeyhq/core <- ONLY imports shared
↓
@onekeyhq/kit-bg <- imports shared, core (NEVER components or kit)
↓
@onekeyhq/kit <- imports shared, components, kit-bg
↓
apps/* <- imports all
# Quick hierarchy violation check on changed files
git diff origin/x...HEAD --name-only | grep -E '\.tsx?$' | \
while IFS= read -r f; do [ -f "$f" ] && grep -l "from.*@onekeyhq" "$f" 2>/dev/null; done | \
while IFS= read -r f; do echo "=== $f ==="; grep "from.*@onekeyhq" "$f"; done
Existing Implementation Reuse (ALWAYS verify)
For newly added helpers, hooks, services, components, constants, formatters, validators, or business logic:
- Search the codebase for existing implementations with the same intent before accepting the new code.
- Prefer established OneKey APIs, components, hooks, utilities, and service methods over local reimplementation.
- Flag reimplementation only when the existing abstraction is semantically equivalent, stable, and does not introduce worse coupling.
- In each reuse finding, include the existing file/function to reuse and explain why it covers the new behavior.
File Risk Classification
| Risk |
Patterns |
Action |
| Critical |
**/vault/**, **/signing/**, **/crypto/**, **/core/src/**, hardware wallet SDK |
Line-by-line review |
| High |
**/auth/**, API endpoints, state management, package.json, manifest.json |
Deep review |
| Medium |
UI components, platform-specific code, background services |
Standard review |
| Low |
Comments, type-only, formatting, tests, docs |
Scan for anomalies |
Scoring System
MANDATORY — every report must include this scoring table, no exceptions.
Rate the PR on 4 dimensions (1-10 each):
| Dimension |
Weight |
What to evaluate |
| 🔒 安全性 |
35% |
Secret leakage, auth bypass, supply-chain risk, input validation |
| 💎 代码质量 |
30% |
Hooks safety, error handling, race conditions, null safety, DRY, reuse of existing implementations |
| 🏛️ 架构合理性 |
20% |
Import hierarchy, separation of concerns, cross-platform consistency |
| ✅ 完整性 |
15% |
Edge cases handled, test coverage, migration paths, docs |
Total Score = weighted average, rounded to 1 decimal.
| Score |
Verdict |
Action |
| 8.0 - 10.0 |
✅ 可直接合入 |
No blockers, minor suggestions only |
| 5.0 - 7.9 |
⚠️ 需修改后复审 |
Has issues that should be fixed before merge |
| < 5.0 |
❌ 建议打回重做 |
Fundamental issues in security or architecture |
Scoring anchors — to keep scores consistent:
- Start at 8 for each dimension, deduct for issues found
- A single P0 security issue → Security capped at 3
- A single P0 crash/runtime bug → Code Quality capped at 5
- Import hierarchy violation → Architecture capped at 4
Confidence Levels
MANDATORY — every finding must use exactly one of these three emoji tags. Do NOT use percentages, do NOT use plain text like "高/中/低" without the emoji. Always use this exact format:
| Tag |
Meaning |
When to use |
| 🔵 High |
Confirmed, verifiable from code |
Clear bug, obvious violation, reproducible |
| 🟠 Medium |
Likely issue, needs context |
Pattern suggests problem, might be intentional |
| ⚪ Low |
Possible issue, needs human check |
Heuristic match, depends on business logic |
Cross-validated findings (primary + Codex agree, or primary + PR comment agree) → automatically 🔵 High.
Auto-Fix Patches
MANDATORY for these categories — if a finding matches one of these, you MUST include a diff patch:
console.error/warn/log → project logger (defaultLogger)
- Missing optional chaining on nullable refs
- Import hierarchy violations
- Missing cleanup in useEffect
- BigNumber type coercion (
Number(decimals))
- Missing type in union type definitions
Format — always use this exact structure:
**Auto-fix:**
\```diff
- old code
+ new code
\```
For other findings where the fix is unambiguous and doesn't require business context, also include auto-fix. When in doubt, include it — it's more useful to have a suggested fix than not.
Do NOT generate auto-fix for:
- Logic changes requiring business context understanding
- Security fixes needing architectural decisions
- Performance optimizations with tradeoffs
GH CLI Inline Comments
After generating the report, if there are findings that meet the comment threshold, post them immediately. Do not ask "是否确认?" and do not wait for a follow-up message. New conversations have no memory of a verbal "以后都自动发" — this section is the source of truth.
Comment threshold: P0 (any confidence) OR P1 with 🔵 High confidence. This means:
- All P0 findings (regardless of confidence)
- All P1 findings with 🔵 High confidence (cross-validated or confirmed from code)
- Excludes: P2 findings, and P1 with 🟠 Medium or ⚪ Low confidence
- List the qualifying findings that warrant PR comments
- Post them in the same turn as the report, using
ManagePullRequest post_comment (path + line) when available, otherwise:
# Inline comment on specific file:line
gh api repos/{owner}/{repo}/pulls/{pr_number}/comments \
--field body="**[P1] 问题标题**: 描述...
**建议修复:**
\`\`\`suggestion
修复代码
\`\`\`
_— Auto-review by Claude_" \
--field path="path/to/file.tsx" \
--field line=42 \
--field side="RIGHT" \
--field commit_id="$(git rev-parse HEAD)"
Rules:
- Always post qualifying findings in the same turn as the review report
- Only post findings meeting the comment threshold (see above)
- Include auto-fix in
suggestion block when available
- Maximum 5 inline comments per PR
- GitHub can only attach review comments to lines in the PR diff; if the real site is unchanged, comment on the nearest changed line and name the unchanged site in the body
- If an existing inline thread already states the same issue, reply to that thread instead of opening a duplicate
Unified Report Format
CRITICAL: Follow this template exactly. Every section marked [REQUIRED] must appear in every report. Do not skip or reorder sections.
# PR #NUMBER 代码审查报告
## 审查概要 [REQUIRED]
- **变更范围**: X 个文件, +Y / -Z 行
- **风险等级**: Critical / High / Medium / Low
- **涉及平台**: Extension / Mobile / Desktop / Web
- **Codex 交叉验证**: ✅ 已启用 / ⏭️ 未启用
- **PR 评论分析**: ✅ 已分析 (N 条评论, 其中 M 条来自 Bot) / ⏭️ 无评论
## 评分 [REQUIRED — NEVER SKIP THIS SECTION]
| 维度 | 得分 | 说明 |
|------|------|------|
| 🔒 安全性 | X/10 | 简要说明 |
| 💎 代码质量 | X/10 | 简要说明 |
| 🏛️ 架构合理性 | X/10 | 简要说明 |
| ✅ 完整性 | X/10 | 简要说明 |
| **总分** | **X.X/10** | **✅ 可直接合入 / ⚠️ 需修改后复审 / ❌ 建议打回** |
## Codex 交叉验证摘要 [REQUIRED if Codex was used, OMIT if not]
| 发现 | Primary | Codex | 状态 |
|------|---------|-------|------|
| 问题描述 | Yes/No | Yes/No | 交叉验证 / 仅 Primary / 仅 Codex |
## PR 评论分析 [REQUIRED if comments exist, OMIT if none]
| 来源 | 类型 | 发现 | 判定 | 说明 |
|------|------|------|------|------|
| Snyk | 🤖 Bot | 依赖漏洞 CVE-XXXX | ✅ Confirmed | 漏洞路径在 OneKey 中可达 |
| @reviewer | 👤 Human | 缺少 null check | 🔍 Enriched | 实际需要在上游 hook 中处理 |
| Devin | 🤖 Bot | 变量命名建议 | ❌ Noise | 命名符合项目规范 |
### 评论误报分析 [OMIT if no noise findings]
- **[来源] 误报**: 具体说明为什么这不是问题(引用源码上下文)
## 发现的问题 [REQUIRED]
### [P0] [🔵 High] 问题标题 {Cross-validated ✅}
**文件**: `path/to/file.tsx:42`
**类型**: 安全 / 构建 / 运行时 / 性能 / 规范
**描述**: 问题是什么,为什么有风险
**Auto-fix:**
\```diff
- old code
+ new code
\```
---
### [P1] [🟠 Medium] 问题标题
**文件**: `path/to/file.tsx:18`
**类型**: 运行时
**描述**: ...
**修复建议**: ...
---
## 修改清单 [REQUIRED]
| 优先级 | 置信度 | 文件 | 类型 | 描述 | Auto-fix |
|--------|--------|------|------|------|----------|
| P0 | 🔵 High | file1.tsx:42 | 安全 | 描述 | ✅ |
| P1 | 🟠 Medium | file2.tsx:18 | 运行时 | 描述 | — |
## 测试建议 [REQUIRED]
1. 测试场景
2. 测试场景
## GH 评论操作 [REQUIRED if qualifying findings exist, OMIT if none]
以下问题(P0 任意置信度,或 P1 + 🔵 High 置信度)建议直接评论到 PR:
- [ ] 问题1 — `file.tsx:42`
- [ ] 问题2 — `file.tsx:88`
> 达标问题已在本回合直接发为 inline comments,无需再确认。
Priority Definitions
MANDATORY — every finding must carry exactly one P0–P2 tag as its priority. Do NOT use 高/中/低 or Critical/High/Medium/Low as finding priority labels.
| Priority |
Criteria |
Action |
| P0 |
Security vulnerability, key/fund exposure, data loss, crash, runtime bug affecting users, build failure |
Blocker — must fix before merge |
| P1 |
Edge-case bug, concurrency risk, robustness gap, maintainability problem |
Should fix before merge |
| P2 |
Nice-to-have, minor inconsistency, nit (naming, comments, style) |
Follow-up / optional |
Historical PR threads may still use the legacy 5-tier scale; when analyzing them, map old P1 → P0, old P2 → P1, old P3/P4 → P2.
Review Discipline
- Read the code — don't just grep. Read each changed file to understand intent.
- No false positives — only report issues you're confident about. Uncertain? Lower the confidence.
- No style nitpicks — focus on security, correctness, architecture, performance.
- Context matters — understand why the code was written this way before suggesting changes.
- Reuse first — before accepting new abstractions or duplicated business logic, search for existing local implementations and flag unnecessary reimplementation with concrete reuse targets.
- Prioritize — 3 high-quality findings beats 20 marginal complaints.
- Score honestly — the score reflects reality, not diplomacy.
- Auto-fix aggressively — when the fix is clear, always include a diff patch. Reviewers prefer actionable suggestions.
Reference Files
- references/security-and-supply-chain.md — PII leakage, AuthN/AuthZ, supply-chain, manifest permissions
- references/code-quality-patterns.md — Hooks, race conditions, null safety, concurrent requests, error handling
- references/onekey-platform-patterns.md — Android/iOS crashes, Fabric, BigNumber, build/CI
- references/quick-commands.md — Bash one-liners for automated checking
1---2name: 1k-code-review-pr-23description: Review OneKey PRs and diffs for security, correctness, concurrency, React/RN pitfalls, and repository-specific regressions. Use for code review or 审查 PR.4---56# OneKey PR Code Review78**输出语言**: 中文910## Review Scope1112- Base branch: `x`13- Diff: `git fetch origin && git diff origin/x...HEAD` (triple-dot)1415## Workflow16171. **Checkout** — `gh pr checkout <PR_NUMBER>` (skip if already on branch)182. **Scope** — `git diff origin/x...HEAD --stat` to see change scope193. **Triage** — Determine which review modules apply (see triage table)204. **Primary Review** — Read each changed file, apply relevant checks from `references/`215. **Codex Cross-Review** — If Codex available, run full parallel review (see below)226. **PR Comment Analysis** — Fetch all existing PR comments (bot + human), analyze with local codebase context (see below)237. **Merge Findings** — Combine primary + Codex + PR comment findings, deduplicate, annotate confidence248. **Score** — Rate the PR across 4 dimensions (see Scoring System). **This step is MANDATORY — every report MUST include the scoring table.**259. **Report** — Generate structured report using the unified format. **Follow the template exactly — every section is required.**2610. **GH Comment** — Post qualifying findings as inline PR comments immediately (do not wait for confirmation)2728## Codex Cross-Review Integration2930Check if Codex is available by confirming the `codex:codex-rescue` subagent type can be dispatched. If uncertain, invoke `/codex:setup` to check readiness.3132**If available:**331. Dispatch a full independent review to Codex via `Agent(subagent_type="codex:codex-rescue")`:34 ```35 Agent(36 subagent_type = "codex:codex-rescue",37 prompt = "Review this PR diff for the OneKey crypto wallet monorepo. Focus on:38 - Security vulnerabilities (secret leakage, auth bypass, supply-chain risks)39 - Runtime bugs (race conditions, null safety, memory leaks)40 - Architecture violations (import hierarchy, cross-platform issues)41 - Code quality (hooks safety, error handling, performance)42 Report each finding with: file:line, severity (Critical/High/Medium/Low), description, fix suggestion.4344 Diff:45 ${FULL_DIFF}"46 )47 ```482. Parse Agent result for structured findings493. Merge into primary review:50 - **Both found same issue** → Mark `{Cross-validated ✅}`, auto-promote to 🔵 High confidence51 - **Codex-only finding** → Include with tag `[Codex]`, review manually to assign confidence52 - **Primary-only finding** → Include normally534. Add a **Codex 交叉验证摘要** table in the report (see report template)5455**If unavailable:** Skip silently. Set "Codex 交叉验证: ⏭️ 未启用" in the report header. Do NOT mention Codex anywhere else.5657## PR Comment Analysis5859Collect ALL existing comments on the PR — bot and human — then analyze each with your local codebase context. You have full source access, type system, and dependency graph; most commenters only saw the diff. Use this asymmetry.6061### Fetching All Comments6263Use `gh api` to get full user metadata (including `type` field for bot detection):6465```bash66# Top-level PR reviews (review bodies)67gh api repos/{owner}/{repo}/pulls/{pr_number}/reviews \68 --jq '[.[] | select(.body != "") | {author: .user.login, is_bot: (.user.type == "Bot"), body: .body, state: .state, association: .author_association}]'6970# Inline review comments (file:line annotations)71gh api repos/{owner}/{repo}/pulls/{pr_number}/comments \72 --jq '[.[] | {author: .user.login, is_bot: (.user.type == "Bot"), path: .path, line: .line, body: .body, association: .author_association}]'7374# General PR comments (issue-level)75gh api repos/{owner}/{repo}/issues/{pr_number}/comments \76 --jq '[.[] | {author: .user.login, is_bot: (.user.type == "Bot"), body: .body, association: .author_association}]'77```7879**Bot detection** — use the `user.type == "Bot"` field from GitHub API, not hardcoded username lists. This automatically covers any bot (current and future) without maintenance.8081If no comments exist, set "PR 评论分析: ⏭️ 无评论" in the report header and skip this section.8283### Analysis Framework8485For each substantive comment (skip empty approvals, CI status badges, pure formatting):8687| Verdict | Meaning | Action |88|---------|---------|--------|89| **✅ Confirmed** | Comment identifies a real issue | Include in findings, tag source `[<author>]` |90| **🔍 Enriched** | Real issue, but analysis is shallow or fix is wrong | Include with deeper fix guidance from your codebase knowledge |91| **❌ Noise** | Not an issue given full codebase context | Note in "评论误报分析" with brief explanation of why |92| **📋 Already Covered** | Your primary review caught it | Cross-validate, boost confidence |9394**Your local advantages — use them aggressively:**95- **Full source** — trace data flow across files, not just the diff96- **Type system** — run `tsc`, verify types end-to-end97- **Architecture** — you know OneKey's import hierarchy and platform patterns98- **Dependencies** — `yarn info`, changelogs, actual vulnerability reachability99- **Runtime reasoning** — state flows, async lifecycles, race conditions100101When someone flags something vague, dig into the source to confirm or refute. When a comment misses context (e.g., a function is safely guarded upstream), explain why. When a comment is right, amplify with richer context.102103### Cross-Validation Rules104105- Comment + primary review agree → Mark `{Cross-validated ✅}`, promote to 🔵 High106- Comment-only finding you confirm → Include at appropriate confidence with `[<author>]` tag107- Comment-only finding you can't confirm or refute → Include as ⚪ Low with note108- Comment you refute with evidence → Add to "评论误报分析" section109110### Security Comment Special Handling111112For security-related comments (from bots like Snyk/Dependabot or from human reviewers):113- **Vulnerability reports** — check if the vulnerable code path is actually reachable in OneKey's usage114- **License issues** — verify against OneKey's license policy115- **Dependency alerts** — check if the flagged version is actually used (not just in lockfile)116117## Triage: Which Checks to Run118119Run `git diff origin/x...HEAD --name-only` and match:120121| Changed Files Match | Load |122|---------------------|------|123| `package.json`, lockfiles, `node_modules` patches, `patches/*.patch` | [security-and-supply-chain.md] — full supply-chain review |124| `**/auth/**`, `**/vault/**`, `**/signing/**`, `**/crypto/**`, `manifest.json`, `**/manifest/*.js` | [security-and-supply-chain.md] — full security review |125| Any `.ts`/`.tsx` with business logic | [code-quality-patterns.md] — hooks, race conditions, null safety |126| `.android.ts(x)`, `.ios.ts(x)`, `.native.ts(x)`, `.desktop.ts(x)`, `.ext.ts(x)`, `.web.ts(x)`, native modules, `BigNumber` usage | [onekey-platform-patterns.md] — platform crashes & numeric safety |127| Shell scripts (`.sh`), CI workflows (`.yml`) | [onekey-platform-patterns.md] — build & CI section |128129**Always check** regardless of file type:130- Accidental file commits (`.DS_Store`, `.env`, `node_modules`)131- Import hierarchy violations (see below)132- Avoidable reimplementation when stable existing helpers, hooks, services, or components already cover the same behavior (see below)133- PR description matches actual changes134- Run relevant commands from [quick-commands.md]135136## Import Hierarchy (ALWAYS verify)137138```139@onekeyhq/shared <- FORBIDDEN to import from other OneKey packages140 ↓141@onekeyhq/components <- ONLY imports shared142 ↓143@onekeyhq/core <- ONLY imports shared144 ↓145@onekeyhq/kit-bg <- imports shared, core (NEVER components or kit)146 ↓147@onekeyhq/kit <- imports shared, components, kit-bg148 ↓149apps/* <- imports all150```151152```bash153# Quick hierarchy violation check on changed files154git diff origin/x...HEAD --name-only | grep -E '\.tsx?$' | \155 while IFS= read -r f; do [ -f "$f" ] && grep -l "from.*@onekeyhq" "$f" 2>/dev/null; done | \156 while IFS= read -r f; do echo "=== $f ==="; grep "from.*@onekeyhq" "$f"; done157```158159## Existing Implementation Reuse (ALWAYS verify)160161For newly added helpers, hooks, services, components, constants, formatters, validators, or business logic:162- Search the codebase for existing implementations with the same intent before accepting the new code.163- Prefer established OneKey APIs, components, hooks, utilities, and service methods over local reimplementation.164- Flag reimplementation only when the existing abstraction is semantically equivalent, stable, and does not introduce worse coupling.165- In each reuse finding, include the existing file/function to reuse and explain why it covers the new behavior.166167## File Risk Classification168169| Risk | Patterns | Action |170|------|----------|--------|171| **Critical** | `**/vault/**`, `**/signing/**`, `**/crypto/**`, `**/core/src/**`, hardware wallet SDK | Line-by-line review |172| **High** | `**/auth/**`, API endpoints, state management, `package.json`, `manifest.json` | Deep review |173| **Medium** | UI components, platform-specific code, background services | Standard review |174| **Low** | Comments, type-only, formatting, tests, docs | Scan for anomalies |175176## Scoring System177178**MANDATORY** — every report must include this scoring table, no exceptions.179180Rate the PR on 4 dimensions (1-10 each):181182| Dimension | Weight | What to evaluate |183|-----------|--------|-----------------|184| **🔒 安全性** | 35% | Secret leakage, auth bypass, supply-chain risk, input validation |185| **💎 代码质量** | 30% | Hooks safety, error handling, race conditions, null safety, DRY, reuse of existing implementations |186| **🏛️ 架构合理性** | 20% | Import hierarchy, separation of concerns, cross-platform consistency |187| **✅ 完整性** | 15% | Edge cases handled, test coverage, migration paths, docs |188189**Total Score** = weighted average, rounded to 1 decimal.190191| Score | Verdict | Action |192|-------|---------|--------|193| **8.0 - 10.0** | ✅ 可直接合入 | No blockers, minor suggestions only |194| **5.0 - 7.9** | ⚠️ 需修改后复审 | Has issues that should be fixed before merge |195| **< 5.0** | ❌ 建议打回重做 | Fundamental issues in security or architecture |196197**Scoring anchors** — to keep scores consistent:198- Start at 8 for each dimension, deduct for issues found199- A single P0 security issue → Security capped at 3200- A single P0 crash/runtime bug → Code Quality capped at 5201- Import hierarchy violation → Architecture capped at 4202203## Confidence Levels204205**MANDATORY** — every finding must use exactly one of these three emoji tags. Do NOT use percentages, do NOT use plain text like "高/中/低" without the emoji. Always use this exact format:206207| Tag | Meaning | When to use |208|-----|---------|-------------|209| **🔵 High** | Confirmed, verifiable from code | Clear bug, obvious violation, reproducible |210| **🟠 Medium** | Likely issue, needs context | Pattern suggests problem, might be intentional |211| **⚪ Low** | Possible issue, needs human check | Heuristic match, depends on business logic |212213Cross-validated findings (primary + Codex agree, or primary + PR comment agree) → automatically **🔵 High**.214215## Auto-Fix Patches216217**MANDATORY for these categories** — if a finding matches one of these, you MUST include a diff patch:218- `console.error/warn/log` → project logger (`defaultLogger`)219- Missing optional chaining on nullable refs220- Import hierarchy violations221- Missing cleanup in useEffect222- BigNumber type coercion (`Number(decimals)`)223- Missing type in union type definitions224225**Format — always use this exact structure:**226```markdown227**Auto-fix:**228\```diff229- old code230+ new code231\```232```233234For other findings where the fix is unambiguous and doesn't require business context, also include auto-fix. When in doubt, include it — it's more useful to have a suggested fix than not.235236Do NOT generate auto-fix for:237- Logic changes requiring business context understanding238- Security fixes needing architectural decisions239- Performance optimizations with tradeoffs240241## GH CLI Inline Comments242243After generating the report, if there are findings that meet the comment threshold, **post them immediately**. Do not ask "是否确认?" and do not wait for a follow-up message. New conversations have no memory of a verbal "以后都自动发" — this section is the source of truth.244245**Comment threshold**: P0 (any confidence) OR P1 with 🔵 High confidence. This means:246- All P0 findings (regardless of confidence)247- All P1 findings with 🔵 High confidence (cross-validated or confirmed from code)248- Excludes: P2 findings, and P1 with 🟠 Medium or ⚪ Low confidence2492501. List the qualifying findings that warrant PR comments2512. Post them in the same turn as the report, using `ManagePullRequest` `post_comment` (path + line) when available, otherwise:252253```bash254# Inline comment on specific file:line255gh api repos/{owner}/{repo}/pulls/{pr_number}/comments \256 --field body="**[P1] 问题标题**: 描述...257258**建议修复:**259\`\`\`suggestion260修复代码261\`\`\`262263_— Auto-review by Claude_" \264 --field path="path/to/file.tsx" \265 --field line=42 \266 --field side="RIGHT" \267 --field commit_id="$(git rev-parse HEAD)"268```269270**Rules:**271- Always post qualifying findings in the same turn as the review report272- Only post findings meeting the comment threshold (see above)273- Include auto-fix in `suggestion` block when available274- Maximum 5 inline comments per PR275- GitHub can only attach review comments to lines in the PR diff; if the real site is unchanged, comment on the nearest changed line and name the unchanged site in the body276- If an existing inline thread already states the same issue, reply to that thread instead of opening a duplicate277278## Unified Report Format279280**CRITICAL: Follow this template exactly. Every section marked [REQUIRED] must appear in every report. Do not skip or reorder sections.**281282```markdown283# PR #NUMBER 代码审查报告284285## 审查概要 [REQUIRED]286- **变更范围**: X 个文件, +Y / -Z 行287- **风险等级**: Critical / High / Medium / Low288- **涉及平台**: Extension / Mobile / Desktop / Web289- **Codex 交叉验证**: ✅ 已启用 / ⏭️ 未启用290- **PR 评论分析**: ✅ 已分析 (N 条评论, 其中 M 条来自 Bot) / ⏭️ 无评论291292## 评分 [REQUIRED — NEVER SKIP THIS SECTION]293294| 维度 | 得分 | 说明 |295|------|------|------|296| 🔒 安全性 | X/10 | 简要说明 |297| 💎 代码质量 | X/10 | 简要说明 |298| 🏛️ 架构合理性 | X/10 | 简要说明 |299| ✅ 完整性 | X/10 | 简要说明 |300| **总分** | **X.X/10** | **✅ 可直接合入 / ⚠️ 需修改后复审 / ❌ 建议打回** |301302## Codex 交叉验证摘要 [REQUIRED if Codex was used, OMIT if not]303304| 发现 | Primary | Codex | 状态 |305|------|---------|-------|------|306| 问题描述 | Yes/No | Yes/No | 交叉验证 / 仅 Primary / 仅 Codex |307308## PR 评论分析 [REQUIRED if comments exist, OMIT if none]309310| 来源 | 类型 | 发现 | 判定 | 说明 |311|------|------|------|------|------|312| Snyk | 🤖 Bot | 依赖漏洞 CVE-XXXX | ✅ Confirmed | 漏洞路径在 OneKey 中可达 |313| @reviewer | 👤 Human | 缺少 null check | 🔍 Enriched | 实际需要在上游 hook 中处理 |314| Devin | 🤖 Bot | 变量命名建议 | ❌ Noise | 命名符合项目规范 |315316### 评论误报分析 [OMIT if no noise findings]317- **[来源] 误报**: 具体说明为什么这不是问题(引用源码上下文)318319## 发现的问题 [REQUIRED]320321### [P0] [🔵 High] 问题标题 {Cross-validated ✅}322**文件**: `path/to/file.tsx:42`323**类型**: 安全 / 构建 / 运行时 / 性能 / 规范324**描述**: 问题是什么,为什么有风险325**Auto-fix:**326\```diff327- old code328+ new code329\```330331---332333### [P1] [🟠 Medium] 问题标题334**文件**: `path/to/file.tsx:18`335**类型**: 运行时336**描述**: ...337**修复建议**: ...338339---340341## 修改清单 [REQUIRED]342343| 优先级 | 置信度 | 文件 | 类型 | 描述 | Auto-fix |344|--------|--------|------|------|------|----------|345| P0 | 🔵 High | file1.tsx:42 | 安全 | 描述 | ✅ |346| P1 | 🟠 Medium | file2.tsx:18 | 运行时 | 描述 | — |347348## 测试建议 [REQUIRED]3491. 测试场景3502. 测试场景351352## GH 评论操作 [REQUIRED if qualifying findings exist, OMIT if none]353以下问题(P0 任意置信度,或 P1 + 🔵 High 置信度)建议直接评论到 PR:354- [ ] 问题1 — `file.tsx:42`355- [ ] 问题2 — `file.tsx:88`356357> 达标问题已在本回合直接发为 inline comments,无需再确认。358```359360## Priority Definitions361362**MANDATORY** — every finding must carry exactly one `P0`–`P2` tag as its priority. Do NOT use 高/中/低 or Critical/High/Medium/Low as finding priority labels.363364| Priority | Criteria | Action |365|----------|----------|--------|366| **P0** | Security vulnerability, key/fund exposure, data loss, crash, runtime bug affecting users, build failure | Blocker — must fix before merge |367| **P1** | Edge-case bug, concurrency risk, robustness gap, maintainability problem | Should fix before merge |368| **P2** | Nice-to-have, minor inconsistency, nit (naming, comments, style) | Follow-up / optional |369370Historical PR threads may still use the legacy 5-tier scale; when analyzing them, map old P1 → P0, old P2 → P1, old P3/P4 → P2.371372## Review Discipline373374- **Read the code** — don't just grep. Read each changed file to understand intent.375- **No false positives** — only report issues you're confident about. Uncertain? Lower the confidence.376- **No style nitpicks** — focus on security, correctness, architecture, performance.377- **Context matters** — understand why the code was written this way before suggesting changes.378- **Reuse first** — before accepting new abstractions or duplicated business logic, search for existing local implementations and flag unnecessary reimplementation with concrete reuse targets.379- **Prioritize** — 3 high-quality findings beats 20 marginal complaints.380- **Score honestly** — the score reflects reality, not diplomacy.381- **Auto-fix aggressively** — when the fix is clear, always include a diff patch. Reviewers prefer actionable suggestions.382383## Reference Files384385- [references/security-and-supply-chain.md](references/security-and-supply-chain.md) — PII leakage, AuthN/AuthZ, supply-chain, manifest permissions386- [references/code-quality-patterns.md](references/code-quality-patterns.md) — Hooks, race conditions, null safety, concurrent requests, error handling387- [references/onekey-platform-patterns.md](references/onekey-platform-patterns.md) — Android/iOS crashes, Fabric, BigNumber, build/CI388- [references/quick-commands.md](references/quick-commands.md) — Bash one-liners for automated checking