{"id":"5355c9be-21de-417a-a02e-dc51abf4b52a","entityType":"agent","slug":"clawhub-nameused-code-reviewer","name":"Code Reviewer","canonicalUrl":"https://www.xpersona.co/agent/clawhub-nameused-code-reviewer","canonicalPath":"/agent/clawhub-nameused-code-reviewer","generatedAt":"2026-10-11T00:31:36.971Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-10-10T21:52:39.587Z","emptyReason":null},"description":"本技能从 6 个维度对代码进行全面审核：安全性、性能、代码质量、错误处理、测试和文档。适用于审核代码变更、Pull Request 或整个代码库（支持所有主流编程语言）。触发词包括：「帮我 review 这段代码」「检查安全问题」「审查这个 PR」「找出代码中的 Bug」，或用户请求代码质量分析时使用。技能内置自... Skill: Code Reviewer Owner: nameused Summary: 本技能从 6 个维度对代码进行全面审核：安全性、性能、代码质量、错误处理、测试和文档。适用于审核代码变更、Pull Request 或整个代码库（支持所有主流编程语言）。触发词包括：「帮我 review 这段代码」「检查安全问题」「审查这个 PR」「找出代码中的 Bug」，或用户请求代码质量分析时使用。技能内置自... Tags: latest:1.0.1 Version history: v1.0.1 | 2026-06-20T13:41:13.597Z | user - Refactored all documentation and instructions from English to Chinese for improved localization. - Updated descriptions, workflows, re","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 1.2K downloads reported by the source. Last updated 10/10/2026.","installCommand":"clawhub skill install s174vwx6k6f5w6srbr5x7yc9x5890txq:code-reviewer","sourceUrl":"https://clawhub.ai/nameused/code-reviewer","homepage":"https://clawhub.ai/nameused/skills/code-reviewer","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/nameused/code-reviewer","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/nameused/skills/code-reviewer","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":62,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"本技能从 6 个维度对代码进行全面审核：安全性、性能、代码质量、错误处理、测试和文档。适用于审核代码变更、Pull Request 或整个代码库（支持所有主流编程语言）。触发词包括：「帮我 review 这段代码」「检查安全问题」「审查这个 PR」「找出代码中的 Bug」，或用户请求代码质量分析时使用。技能内置自..."},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-10T21:52:39.587Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-10T21:52:39.587Z","emptyReason":null},"stars":null,"forks":null,"downloads":1249,"packageName":null,"latestVersion":"1.0.1","tractionLabel":"1.2K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-10T21:52:39.524Z","emptyReason":null},"lastUpdatedAt":"2026-10-10T21:52:39.587Z","lastCrawledAt":"2026-10-10T21:52:39.524Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-11T21:52:39.524Z","lastVerifiedAt":null,"highlights":[{"version":"1.0.1","createdAt":"2026-06-20T13:41:13.597Z","changelog":"- Refactored all documentation and instructions from English to Chinese for improved localization. - Updated descriptions, workflows, report generation steps, and best practice guidelines with Chinese text and terminology. - No changes to scripts or core review workflow logic; functionality and structure remain the same. - Maintains full feature parity, including automated/deterministic analysis, report generation, and cross-platform support.","fileCount":10,"zipByteSize":35053},{"version":"1.0.0","createdAt":"2026-06-20T00:36:41.756Z","changelog":"Initial release of the code-reviewer skill: - Provides comprehensive code reviews across Security, Performance, Code Quality, Error Handling, Testing, and Documentation. - Supports reviews for code changes, pull requests, and entire codebases in any programming language. - Utilizes automated scripts for deterministic analysis and merges with contextual, AI-driven review. - Produces classified findings with severity levels and offers bilingual (English/Chinese) HTML report generation. - Summarizes actionable insights, prioritized fixes, and positive highlights for users.","fileCount":10,"zipByteSize":34872}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s174vwx6k6f5w6srbr5x7yc9x5890txq:code-reviewer","setupComplexity":"low","setupSteps":["Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-nameused-code-reviewer/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-nameused-code-reviewer/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-nameused-code-reviewer/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-nameused-code-reviewer/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-nameused-code-reviewer/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-nameused-code-reviewer/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-11T00:31:36.969Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-nameused-code-reviewer/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-nameused-code-reviewer/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-nameused-code-reviewer/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-nameused-code-reviewer/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-10-10T21:52:39.587Z","emptyReason":null},"readme":"Skill: Code Reviewer\n\nOwner: nameused\n\nSummary: 本技能从 6 个维度对代码进行全面审核：安全性、性能、代码质量、错误处理、测试和文档。适用于审核代码变更、Pull Request 或整个代码库（支持所有主流编程语言）。触发词包括：「帮我 review 这段代码」「检查安全问题」「审查这个 PR」「找出代码中的 Bug」，或用户请求代码质量分析时使用。技能内置自...\n\nTags: latest:1.0.1\n\nVersion history:\n\nv1.0.1 | 2026-06-20T13:41:13.597Z | user\n\n- Refactored all documentation and instructions from English to Chinese for improved localization.\n- Updated descriptions, workflows, report generation steps, and best practice guidelines with Chinese text and terminology.\n- No changes to scripts or core review workflow logic; functionality and structure remain the same.\n- Maintains full feature parity, including automated/deterministic analysis, report generation, and cross-platform support.\n\nv1.0.0 | 2026-06-20T00:36:41.756Z | auto\n\nInitial release of the code-reviewer skill:\n\n- Provides comprehensive code reviews across Security, Performance, Code Quality, Error Handling, Testing, and Documentation.\n- Supports reviews for code changes, pull requests, and entire codebases in any programming language.\n- Utilizes automated scripts for deterministic analysis and merges with contextual, AI-driven review.\n- Produces classified findings with severity levels and offers bilingual (English/Chinese) HTML report generation.\n- Summarizes actionable insights, prioritized fixes, and positive highlights for users.\n\nArchive index:\n\nArchive v1.0.1: 10 files, 35053 bytes\n\nFiles: references/best-practices.md (7526b), references/checklist.md (5909b), references/security-rules.md (7362b), references/severity-guide.md (6356b), scripts/analyze_complexity.py (12963b), scripts/generate_report.py (25597b), scripts/scan_patterns.py (14582b), skill-card.md (2121b), SKILL.md (11484b), _meta.json (132b)\n\nFile v1.0.1:SKILL.md\n\n---\r\nname: code-reviewer\r\ndescription: \"本技能从 6 个维度对代码进行全面审核：安全性、性能、代码质量、错误处理、测试和文档。适用于审核代码变更、Pull Request 或整个代码库（支持所有主流编程语言）。触发词包括：「帮我 review 这段代码」「检查安全问题」「审查这个 PR」「找出代码中的 Bug」，或用户请求代码质量分析时使用。技能内置自动化分析脚本、安全规则库、各语言最佳实践文档，并可生成可视化 HTML 审核报告。\"\r\n---\r\n\r\n# 代码审核助手（Code Reviewer）\r\n\r\n## 概述\r\n\r\n通过自动化静态分析与 AI 上下文推理相结合的方式，对代码进行全面、多维度的审核。覆盖六大审核维度，支持所有主流编程语言，输出带严重性分级的可执行问题列表和可视化 HTML 报告。\r\n\r\n## 适用场景\r\n\r\n- 审核 Pull Request 或代码变更（diff）\r\n- 对现有代码库进行安全或质量审计\r\n- 合并前代码质量检查（Pre-merge gate）\r\n- 对不熟悉的代码进行入门级审核\r\n- 安全漏洞评估\r\n- 性能瓶颈定位\r\n\r\n## 审核工作流\r\n\r\n每次代码审核均遵循以下 4 阶段工作流，各阶段依次递进。\r\n\r\n### 第一阶段：确定范围与计划\r\n\r\n确定审核对象和方式：\r\n\r\n1. 确认审核范围：单文件、目录、git diff 还是 PR。若用户提供 git diff 或 PR，仅审核变更行及其上下文；若审核整个代码库，询问用户目标目录。\r\n2. 根据文件扩展名检测编程语言，参考 `references/best-practices.md` 中各语言专属规则。\r\n3. 确定审核深度：快速扫描（仅关注严重/高危）或全面审核（覆盖所有严重级别）。默认执行全面审核，除非用户明确要求快速扫描。\r\n4. 检查自动化分析脚本是否可用。如果 Python 可用，优先使用脚本进行确定性分析。\r\n\r\n### 第二阶段：自动化分析\r\n\r\n在进行上下文推理之前，运行内置脚本获取确定性的基线问题。\r\n\r\n**步骤 1：复杂度分析**\r\n\r\n对目标代码运行复杂度分析器：\r\n\r\n```bash\r\npython scripts/analyze_complexity.py <目标路径> --format json\r\n```\r\n\r\n检测内容：过长函数（>50 行）、高圈复杂度（>10）、深层嵌套（>4 层）、参数过多（>5 个）。结果以 JSON 格式输出。\r\n\r\n**步骤 2：模式扫描**\r\n\r\n运行模式扫描器检测安全漏洞和代码质量问题：\r\n\r\n```bash\r\npython scripts/scan_patterns.py <目标路径> --format json\r\n```\r\n\r\n检测内容：SQL 注入、命令注入、硬编码密钥、eval 使用、弱哈希算法、XSS、空 catch 块、TODO/FIXME 标记，以及 20+ 其他反模式。结果以 JSON 格式输出。\r\n\r\n**步骤 3：合并结果**\r\n\r\n将两个脚本的 JSON 输出合并为一个问题列表，按（文件、行号、类型）去重。\r\n\r\n若 Python 不可用，跳过本阶段直接进入第三阶段，对照 `references/security-rules.md` 和 `references/checklist.md` 手动检查代码中的等价问题。\r\n\r\n### 第三阶段：上下文审核\r\n\r\n阅读代码并进行自动化工具无法完成的上下文推理，这是审核的核心价值所在。\r\n\r\n按需加载以下参考文档：\r\n- `references/checklist.md` — 6 维度全面检查清单\r\n- `references/security-rules.md` — OWASP Top 10、各语言安全模式、密钥检测正则\r\n- `references/best-practices.md` — 各语言惯用写法与反模式\r\n- `references/severity-guide.md` — 严重性分级标准与示例\r\n\r\n对第二阶段的每个问题进行确认或排除误报，然后检查模式匹配无法发现的问题：\r\n\r\n**安全性（参考 `references/security-rules.md`）：**\r\n- 业务逻辑漏洞（如订单中的负数数量、转账中的竞态条件）\r\n- 特定业务操作缺少授权检查\r\n- 不安全的数据流（source → sink 分析）\r\n- 信任边界违规\r\n\r\n**性能（参考 `references/checklist.md` 第 2 节）：**\r\n- 算法效率问题（错误的数据结构、不必要的计算）\r\n- 资源泄漏（未关闭的连接、孤立的事件监听器）\r\n- 可扩展性隐患（无限增长、锁竞争）\r\n\r\n**代码质量（参考 `references/best-practices.md`）：**\r\n- SOLID 原则违反\r\n- 设计模式误用或缺失\r\n- 命名清晰度与一致性\r\n- 抽象层级是否适当\r\n\r\n**错误处理（参考 `references/checklist.md` 第 4 节）：**\r\n- 关键业务流程中未处理的错误路径\r\n- 泄露内部状态的错误消息\r\n- 瞬态错误缺少重试/降级机制\r\n- 错误传播不当（被吞噬、重新包装或丢失上下文）\r\n\r\n**测试（参考 `references/checklist.md` 第 5 节）：**\r\n- 核心业务逻辑缺少测试\r\n- 边界情况和错误路径未被测试覆盖\r\n- 测试隔离问题（共享状态、顺序依赖）\r\n- Mock 质量（过度 Mock 或 Mock 不足）\r\n\r\n**文档（参考 `references/checklist.md` 第 6 节）：**\r\n- 公共接口缺少 API 文档\r\n- 注释与代码不符（过时注释）\r\n- 非显而易见的设计决策缺少架构决策记录\r\n\r\n### 第四阶段：报告与建议\r\n\r\n生成最终审核输出。\r\n\r\n**步骤 1：对所有问题进行分级**（参考 `references/severity-guide.md`）：\r\n- 严重（Critical）：远程代码执行、SQL 注入、绕过认证、硬编码生产环境密钥\r\n- 高危（High）：数据泄露、XSS、缺少鉴权、反序列化漏洞\r\n- 中危（Medium）：弱加密、N+1 查询、高复杂度、空 catch 块\r\n- 低危（Low）：死代码、命名问题、魔法数字、调试打印语句\r\n- 提示（Info）：建议、替代方案、正向反馈\r\n\r\n**步骤 2：生成 HTML 报告**（可选，当用户需要可视化报告时）：\r\n\r\n```bash\r\n# 双语报告，带切换按钮（默认）\r\npython scripts/generate_report.py <findings.json> --project \"<项目名称>\" --output review-report.html\r\n\r\n# 仅中文\r\npython scripts/generate_report.py <findings.json> --lang zh --output review-report.html\r\n\r\n# 仅英文\r\npython scripts/generate_report.py <findings.json> --lang en --output review-report.html\r\n```\r\n\r\n或通过管道直接传入：\r\n```bash\r\necho '<combined-json>' | python scripts/generate_report.py - --lang zh --output review-report.html\r\n```\r\n\r\n报告包含：严重性统计卡片、分类汇总表格、可交互过滤的问题列表（含代码片段）、暗色主题，以及**双语支持**（`--lang zh|en|both`）。默认 `--lang both` 时，右上角提供切换按钮，无需刷新即可在中英文间即时切换。\r\n\r\n**步骤 3：在对话中输出摘要：**\r\n\r\n向用户呈现简洁摘要：\r\n1. 总体评估（1-2 句话）：代码是否可以合并？风险等级如何？\r\n2. 优先列出严重/高危问题，包含文件:行号、问题描述和修复建议\r\n3. 中危/低危问题按分类汇总（不逐条列举，除非用户要求）\r\n4. 正向反馈：指出哪些地方写得好\r\n5. 行动清单：区分合并前必须修复的问题与可作为后续跟进事项的问题\r\n\r\n## 审核维度\r\n\r\n| 维度 | 覆盖内容 | 主要参考 |\r\n|------|---------|---------|\r\n| 安全性 | OWASP Top 10、注入、认证、密钥、加密 | `references/security-rules.md` |\r\n| 性能 | 数据库查询、算法、内存、并发 | `references/checklist.md` §2 |\r\n| 代码质量 | 复杂度、命名、重复代码、架构 | `references/best-practices.md` |\r\n| 错误处理 | 覆盖率、质量、容错能力 | `references/checklist.md` §4 |\r\n| 测试 | 覆盖率、质量、可维护性 | `references/checklist.md` §5 |\r\n| 文档 | 代码级和项目级文档 | `references/checklist.md` §6 |\r\n\r\n## 问题格式\r\n\r\n每个问题应包含以下字段以保持一致性：\r\n\r\n```\r\n- 严重性（Severity）：Critical（严重）| High（高危）| Medium（中危）| Low（低危）| Info（提示）\r\n- 分类（Category）：Security（安全）| Performance（性能）| Code Quality（质量）| Error Handling（错误处理）| Testing（测试）| Documentation（文档）\r\n- 文件（File）：path/to/file.ext\r\n- 行号（Line）：<行号>\r\n- 规则（Rule）：<规则 ID 或简称>\r\n- 描述（Message）：<问题说明，一句话>\r\n- 建议（Suggestion）：<修复方式，一句话>\r\n- 代码片段（Snippet）：<有问题的代码行，如适用>\r\n```\r\n\r\n## 内置资源\r\n\r\n### scripts/（脚本）\r\n\r\n- **`analyze_complexity.py`** — 分析圈复杂度、函数长度、嵌套深度和参数数量。Python 代码使用 AST 精确解析，大括号语言（JS/TS/Java/Go/C/C++/PHP/Ruby）使用正则启发式分析。输出格式：JSON 或文本。\r\n\r\n- **`scan_patterns.py`** — 扫描 30+ 种安全和质量反模式，包括 SQL 注入、命令注入、硬编码密钥、eval 使用、弱哈希、XSS、空 catch 块、TODO 标记、魔法数字等。输出格式：JSON 或文本。\r\n\r\n- **`generate_report.py`** — 从 JSON 问题数据生成自包含 HTML 报告。功能：严重性统计卡片、分类汇总表格、交互式过滤、代码片段展示、暗色主题，**双语支持**（中文/英文，通过 `--lang zh|en|both` 实时切换）。支持从文件或 stdin 读取数据。\r\n\r\n### references/（参考文档）\r\n\r\n- **`checklist.md`** — 6 维度全面代码审核检查清单，包含 80+ 具体检查项。第三阶段系统性核查时使用。\r\n\r\n- **`security-rules.md`** — OWASP Top 10 速查表、各语言安全模式（JS/TS、Python、Java、Go、PHP、C/C++、Rust）、密钥检测正则表达式，以及安全问题的严重性分级。\r\n\r\n- **`best-practices.md`** — 各语言惯用最佳实践与常见反模式，覆盖 JavaScript/TypeScript、Python、Java、Go，以及通用原则（SOLID、Clean Code、API 设计、版本控制规范）。\r\n\r\n- **`severity-guide.md`** — 详细严重性分级指南，包含各级别（Critical 至 Info）的判定标准、代码示例和决策流程。\r\n\r\n### assets/（资产）\r\n\r\n本技能不使用此目录。HTML 报告由 `scripts/generate_report.py` 动态生成。\r\n\r\n## 平台兼容性\r\n\r\n本技能设计为跨平台运行：\r\n\r\n- **WorkBuddy**：完整支持，包括脚本执行\r\n- **Claude Code**：完整支持，包括本地文件访问和脚本执行\r\n- **Coze（扣子）**：SKILL.md 指令和参考文档在云端环境中完全可用；脚本在 Coze 沙盒中执行。技能遵循标准 SKILL.md 格式（兼容 Claude Skills 规范），Coze 的技能加载器可直接识别。\r\n\r\n在无本地文件访问权限的纯云端环境中，自动化脚本（第二阶段）可能不可用。此时跳过第二阶段，直接进入第三阶段，对照参考文档手动完成所有检查。\r\n\r\n## 高质量审核建议\r\n\r\n1. **始终确认误报**：基于模式的检测结果可能有误。在上报问题之前，务必阅读实际代码上下文。\r\n2. **按影响范围排优先级**：未经认证端点上的严重漏洞，比内部工具中的低危问题重要得多。\r\n3. **提供可执行的修复方案**：不只说\"这里有问题\"，要展示正确的做法。\r\n4. **认可写得好的代码**：指出代码中优雅的实现、良好的设计模式和周全的错误处理。审核不应该只有负面反馈。\r\n5. **考虑代码库背景**：历史遗留代码、时间压力和团队约定都是重要因素。不要在一个有 10 年历史的代码库里对每个风格问题都挂红灯。\r\n6. **跟踪后续事项**：对于不阻塞合并的中危/低危问题，建议创建跟踪 issue 留作后续清理。\n\nFile v1.0.1:_meta.json\n\n{\n  \"ownerId\": \"kn77qvnxzvd6mty516h2m09kan891gd9\",\n  \"slug\": \"code-reviewer\",\n  \"version\": \"1.0.1\",\n  \"publishedAt\": 1781962873597\n}\n\nFile v1.0.1:references/best-practices.md\n\n# Language-Specific Best Practices\n\n## JavaScript / TypeScript\n\n### Modern Syntax\n- Use `const` by default, `let` when reassignment needed, never `var`\n- Use arrow functions for callbacks and short functions; use `function` for methods and constructors\n- Use template literals over string concatenation\n- Use destructuring for object/array extraction\n- Use spread operator instead of `Object.assign` for immutability\n- Use optional chaining (`?.`) and nullish coalescing (`??`) instead of manual checks\n\n### TypeScript Specific\n- Enable `strict: true` in tsconfig.json\n- Avoid `any` type - use `unknown` when type is truly unknown, then narrow\n- Use `interface` for object shapes, `type` for unions and intersections\n- Use `enum` or union types for fixed value sets\n- Prefer `readonly` for immutable properties\n- Use generics for reusable components/functions\n- Enable `noUncheckedIndexedAccess` for safer array/object access\n\n### Async Patterns\n- Use `async/await` over `.then()` chains for readability\n- Always handle promise rejections (try/catch or .catch())\n- Use `Promise.all()` for parallel operations, not sequential awaits\n- Avoid fire-and-forget async calls (always await or handle)\n- Use `AbortController` for cancellable fetch requests\n\n### Node.js\n- Use `path.join()` / `path.resolve()` instead of string concatenation for paths\n- Use `fs.promises` (async) over `fs` (sync) in server code\n- Validate input with Zod / Joi / express-validator at API boundaries\n- Use `crypto.randomUUID()` for ID generation, not `Math.random()`\n- Set `helmet()` middleware for security headers\n- Use `express-rate-limit` for API rate limiting\n\n### Common Anti-Patterns\n- Mutating function arguments\n- Comparing with `==` instead of `===`\n- Using `forEach` when `map`/`filter`/`reduce` is intended\n- Async function without await inside (missing `await` keyword)\n- `any` type in TypeScript (loss of type safety)\n- Empty catch blocks (`catch (e) {}`)\n\n---\n\n## Python\n\n### Modern Syntax (3.9+)\n- Use type hints on all function signatures (`def foo(x: int) -> str:`)\n- Use `from __future__ import annotations` for forward references\n- Use f-strings for string formatting (not `%` or `.format()`)\n- Use `pathlib.Path` instead of `os.path` for path manipulation\n- Use dataclasses or Pydantic for data containers\n- Use `match` statement for complex pattern matching (3.10+)\n- Use `walrus operator` (`:=`) for assignment expressions where it improves readability\n\n### Error Handling\n- Catch specific exceptions, not bare `except:` or `except Exception:`\n- Use context managers (`with` statements) for resource management\n- Raise exceptions with meaningful messages and proper exception types\n- Use custom exception hierarchies for application-specific errors\n- Never use `except: pass` - at minimum log the error\n\n### Security\n- Use `secrets` module for tokens/passwords, not `random`\n- Use `bcrypt` or `argon2-cffi` for password hashing\n- Use parameterized queries with `psycopg2` / `SQLAlchemy` (never string concat)\n- Use `yaml.safe_load()` not `yaml.load()`\n- Use `subprocess.run()` with `shell=False` (list arguments, not string)\n- Validate and sanitize all user input (use Pydantic or marshmallow)\n\n### Code Organization\n- One class per file for major classes\n- Group related functions into modules\n- Use `__all__` to define public API\n- Use `if __name__ == \"__main__\":` guard for script entry points\n- Keep `__init__.py` files minimal (re-exports only)\n\n### Common Anti-Patterns\n- Mutable default arguments (`def foo(items=[])`)\n- Bare `except:` clauses\n- Global variables for state management\n- `import *` (use explicit imports)\n- Comparing to `None` with `==` (use `is None`)\n- Using `type()` for type checking (use `isinstance()`)\n\n---\n\n## Java\n\n### Modern Java (11+)\n- Use `var` for local variable type inference when type is obvious\n- Use `record` for immutable data carriers (Java 16+)\n- Use `switch` expressions with `->` and `yield` (Java 14+)\n- Use `Optional<T>` for return types that may be absent (never as field type)\n- Use `Stream API` for collection processing over manual loops\n- Use `text blocks` (`\"\"\"...\"\"\"`) for multi-line strings (Java 15+)\n\n### Spring Framework\n- Use constructor injection over `@Autowired` field injection\n- Use `@Transactional` at service layer, not controller\n- Use `@RestController` + `@RequestMapping` for REST APIs\n- Use `@Validated` / `@Valid` for request body validation\n- Use `@ExceptionHandler` / `@ControllerAdvice` for global error handling\n- Use `ResponseEntity<T>` for HTTP responses with proper status codes\n- Use `@ConfigurationProperties` over `@Value` for grouped config\n\n### Common Anti-Patterns\n- `NullPointerException` from unchecked method chains\n- Raw types (`List` instead of `List<String>`)\n- `instanceof` chains (use polymorphism or sealed classes)\n- `Thread.sleep()` in tests (use `Awaitility`)\n- Catching `Exception` or `Throwable` broadly\n- Using `Date` / `Calendar` (use `java.time.*`)\n\n---\n\n## Go\n\n### Idiomatic Go\n- Return errors as last return value, always check them\n- Use `errors.Is()` and `errors.As()` for error comparison (not `==`)\n- Use `context.Context` as first parameter in all functions that do I/O\n- Use goroutines with proper cancellation (`ctx.Done()`)\n- Use `sync.Mutex` / `sync.RWMutex` for shared state protection\n- Use channels for goroutine communication, mutexes for state protection\n- Prefer composition over inheritance (embed structs, don't subclass)\n- Keep interfaces small (single-method interfaces are ideal)\n\n### Error Handling\n- Wrap errors with context: `fmt.Errorf(\"doing X: %w\", err)`\n- Use `errors.New()` for static errors, `fmt.Errorf()` for formatted\n- Define sentinel errors: `var ErrNotFound = errors.New(\"not found\")`\n- Check errors immediately, don't ignore them (`_ = someFunc()` is a smell)\n\n### Common Anti-Patterns\n- Ignoring errors (`result, _ := doSomething()`)\n- Starting goroutines without a way to stop them\n- Global mutable state without synchronization\n- Interface pollution (defining interfaces before multiple implementations exist)\n- `panic()` in library code (return errors instead)\n- `init()` side effects (keep init minimal)\n\n---\n\n## General (All Languages)\n\n### SOLID Principles\n- **S**ingle Responsibility: Each class/function has one reason to change\n- **O**pen/Closed: Open for extension, closed for modification\n- **L**iskov Substitution: Subtypes must be substitutable for base types\n- **I**nterface Segregation: Many specific interfaces > one general interface\n- **D**ependency Inversion: Depend on abstractions, not concretions\n\n### Clean Code\n- Functions should be small and do one thing\n- Function names should be verbs, variable names should be nouns\n- Avoid negative conditions (`if (!isNotValid)` is hard to read)\n- Avoid deep nesting (use guard clauses / early returns)\n- Comments should explain WHY, not WHAT\n- Remove commented-out code (use version control)\n\n### Version Control\n- Commit messages: imperative mood, subject under 50 chars, body under 72\n- One logical change per commit\n- No secrets in commit history (use `.gitignore` and `git-secrets`)\n- Branch names: `feature/`, `bugfix/`, `hotfix/` prefixes\n\n### API Design\n- REST: Use proper HTTP methods (GET/POST/PUT/PATCH/DELETE)\n- Use plural nouns for resource paths (`/users`, not `/user`)\n- Return appropriate HTTP status codes (not 200 for everything)\n- Version APIs (`/api/v1/`) to allow breaking changes\n- Paginate list endpoints (cursor-based preferred over offset)\n- Use consistent naming (camelCase or snake_case, not mixed)\n\nFile v1.0.1:references/checklist.md\n\n# Code Review Checklist\n\n## 1. Security\n\n### Injection Attacks\n- [ ] SQL queries use parameterized statements / prepared statements (no string concatenation)\n- [ ] No OS command execution with user input (`os.system`, `exec`, `Runtime.exec`, `child_process.exec`)\n- [ ] Template engines use auto-escaping (no `dangerouslySetInnerHTML`, `{!! !!}`, `innerHTML` with user data)\n- [ ] No eval on user input (`eval()`, `Function()`, `new Function()`)\n\n### Authentication & Authorization\n- [ ] Passwords hashed with bcrypt/scrypt/argon2 (not MD5/SHA1/plaintext)\n- [ ] JWT tokens validated for signature, expiry, and issuer\n- [ ] Authorization checks present on every protected route/endpoint\n- [ ] No hardcoded credentials, API keys, or tokens in source code\n- [ ] Secrets loaded from environment variables or secret managers\n\n### Data Exposure\n- [ ] Sensitive data not logged (passwords, tokens, PII, credit card numbers)\n- [ ] API responses do not leak internal field names or stack traces\n- [ ] HTTPS enforced; no mixed content\n- [ ] CORS configured restrictively (no `Access-Control-Allow-Origin: *` on sensitive endpoints)\n\n### File Operations\n- [ ] File paths validated against traversal attacks (no `../` in user-controlled paths)\n- [ ] Upload restrictions: file type, size, and content validation\n- [ ] Download paths restricted to allowed directories\n\n### Dependencies\n- [ ] No known vulnerable dependencies (checked via `npm audit` / `pip audit` / `snyk`)\n- [ ] Dependency versions pinned (no floating `*` or `latest`)\n\n---\n\n## 2. Performance\n\n### Database\n- [ ] No N+1 query patterns (queries inside loops)\n- [ ] Database indexes exist for frequently queried columns\n- [ ] Pagination applied to list endpoints (no unbounded `SELECT *`)\n- [ ] ORM queries select only needed columns (no `SELECT *` when only 2 fields used)\n\n### Algorithms & Data Structures\n- [ ] No O(n^2) or worse inside hot paths / loops\n- [ ] Appropriate data structures used (Set for lookups instead of Array.includes)\n- [ ] No unnecessary re-computation of the same value inside loops\n\n### Memory\n- [ ] No memory leaks (event listeners removed, intervals cleared, connections closed)\n- [ ] Large collections streamed rather than loaded entirely into memory\n- [ ] No unnecessary object retention in long-lived scopes (closures, globals, singletons)\n\n### Concurrency\n- [ ] Async operations not blocking the event loop (no sync I/O in async contexts)\n- [ ] Database connections released properly (try/finally or using context managers)\n- [ ] Race conditions addressed (proper locking / atomic operations)\n\n---\n\n## 3. Code Quality\n\n### Readability\n- [ ] Variable/function names are descriptive and self-documenting\n- [ ] Functions do one thing (Single Responsibility)\n- [ ] No dead code (unused variables, functions, imports, unreachable code)\n- [ ] No magic numbers / strings (use named constants)\n- [ ] Consistent naming convention (camelCase / snake_case per language convention)\n\n### Complexity\n- [ ] Functions under 50 lines (refactor if longer)\n- [ ] Cyclomatic complexity under 10 per function (use `scripts/analyze_complexity.py`)\n- [ ] Nesting depth under 4 levels (extract early returns / guard clauses)\n- [ ] Parameter count under 5 (use parameter objects if more)\n\n### Duplication\n- [ ] No copy-pasted code blocks (DRY principle)\n- [ ] Shared logic extracted into reusable functions/modules\n- [ ] No duplicated string literals / magic constants\n\n### Architecture\n- [ ] Proper separation of concerns (controller/service/repository layers)\n- [ ] No business logic in presentation layer (views/templates/controllers)\n- [ ] Dependencies injected (not hard-wired / globally accessed)\n- [ ] No circular dependencies between modules\n\n---\n\n## 4. Error Handling\n\n### Coverage\n- [ ] External calls wrapped in try/catch (network, file, database, subprocess)\n- [ ] Promise rejections handled (no unhandled `.then()` without `.catch()`)\n- [ ] Error states tested (not just happy path)\n- [ ] No empty catch blocks (`catch {}` or `except: pass`)\n\n### Quality\n- [ ] Errors logged with context (what operation, what input, what failed)\n- [ ] Custom error types used for domain errors (not generic Error/Exception)\n- [ ] Error messages user-friendly (no stack traces or internal details exposed)\n- [ ] Errors not swallowed silently (at minimum logged)\n\n### Resilience\n- [ ] Retry logic for transient failures (network, rate limits)\n- [ ] Circuit breakers / timeouts for external service calls\n- [ ] Graceful degradation when optional services unavailable\n- [ ] Idempotency for retry-safe operations\n\n---\n\n## 5. Testing\n\n### Coverage\n- [ ] Unit tests exist for business logic\n- [ ] Integration tests exist for API endpoints\n- [ ] Edge cases tested (empty input, null, boundary values, large input)\n- [ ] Error paths tested (not just happy path)\n\n### Quality\n- [ ] Tests are independent (no shared mutable state, no order dependency)\n- [ ] Test names describe the scenario and expected outcome\n- [ ] No flaky tests (time-dependent, race conditions, external service calls)\n- [ ] Mocks/stubs used for external dependencies (not real DB/API calls in unit tests)\n- [ ] Test data is realistic and representative\n\n### Maintainability\n- [ ] Test setup is minimal and clear (Arrange-Act-Assert pattern)\n- [ ] No test logic duplication (use test factories/builders)\n- [ ] Tests run fast (unit tests under 1s each)\n\n---\n\n## 6. Documentation\n\n### Code Level\n- [ ] Public API functions/classes documented (JSDoc, docstrings, GoDoc)\n- [ ] Complex algorithms explained with comments (why, not what)\n- [ ] TODO/FIXME comments include issue numbers and context\n- [ ] No outdated comments (comments that contradict the code)\n\n### Project Level\n- [ ] README exists with setup/run/test instructions\n- [ ] Environment variables documented (`.env.example`)\n- [ ] API changes reflected in API documentation (OpenAPI/Swagger)\n- [ ] Breaking changes noted in CHANGELOG\n\nFile v1.0.1:references/security-rules.md\n\n# Security Vulnerability Detection Rules\n\n## OWASP Top 10 Quick Reference\n\n### A01 - Broken Access Control\n| Pattern | Indicators | Languages |\n|---------|-----------|-----------|\n| Missing auth check | Route handler without auth middleware | All |\n| IDOR | Direct object reference from user input without ownership check | All |\n| Privilege escalation | Role check missing before sensitive operation | All |\n| Force browsing | No authorization on API endpoints | All |\n\n**Detection patterns:**\n- Route definitions without `auth` / `requireAuth` / `@login_required` / `@Authorized`\n- `req.params.id` / `request.getParameter(\"id\")` used directly in DB query without ownership validation\n- `isAdmin` check only on frontend, not backend\n\n### A02 - Cryptographic Failures\n| Pattern | Indicators | Languages |\n|---------|-----------|-----------|\n| Weak hashing | MD5, SHA1 used for passwords | All |\n| Hardcoded secrets | API keys in source code | All |\n| No encryption | Sensitive data stored/transmitted in plaintext | All |\n| Weak randomness | `Math.random()` / `random.random()` for security tokens | All |\n\n**Detection patterns (regex):**\n```\n# Hardcoded API keys\n(api[_-]?key|secret|token|password)\\s*[:=]\\s*['\"][A-Za-z0-9]{16,}['\"]\n\n# Weak hash algorithms\n\\b(MD5|SHA1|md5|sha1)\\b.*password\n\n# Insecure random\n\\b(Math\\.random|random\\.random)\\(\\).*token|session|password|key\n```\n\n### A03 - Injection\n| Pattern | Indicators | Languages |\n|---------|-----------|-----------|\n| SQL Injection | String concatenation in SQL queries | All |\n| Command Injection | User input in shell commands | All |\n| LDAP Injection | String concat in LDAP queries | All |\n| Template Injection | User input in template engine | All |\n\n**Detection patterns:**\n```\n# SQL injection\n(SELECT|INSERT|UPDATE|DELETE|DROP).*\\+.*\\$_(GET|POST|REQUEST)\nquery\\s*\\+\\s*['\"].*['\"]\\s*\\+\nexecute\\s*\\(\\s*['\"].*\\{.*\\}.*['\"]\\s*\\)\n\n# Command injection\n(os\\.system|subprocess\\.call|exec|child_process\\.exec)\\s*\\(.*\\+.*(input|req|param)\n```\n\n### A04 - Insecure Design\n- Missing rate limiting on authentication endpoints\n- No account lockout after failed login attempts\n- Predictable URL patterns for sensitive resources\n- Missing input validation (length, type, format, range)\n\n### A05 - Security Misconfiguration\n- Debug mode enabled in production (`DEBUG=True`)\n- Detailed error pages in production (stack traces exposed)\n- Default credentials not changed\n- Unnecessary features enabled (directory listing, HTTP methods)\n\n### A07 - Identification & Authentication Failures\n- Weak password policy (no minimum length, complexity)\n- Session ID in URL parameters\n- Session fixation (session not regenerated after login)\n- No session timeout\n\n### A08 - Software & Data Integrity Failures\n- Unsigned software updates\n- Deserialization of untrusted data (`pickle.loads`, `yaml.load` without SafeLoader)\n- Dependencies from untrusted sources\n\n### A09 - Logging & Monitoring Failures\n- Security events not logged (login, logout, password change, privilege changes)\n- Logs not protected against tampering\n- No alerting on suspicious activities\n\n### A10 - Server-Side Request Forgery (SSRF)\n- User-controlled URLs fetched server-side without validation\n- No allowlist for outbound HTTP requests\n- Internal IP ranges not blocked (`127.0.0.1`, `10.x`, `172.16-31.x`, `169.254.x`)\n\n---\n\n## Language-Specific Security Patterns\n\n### JavaScript / TypeScript / Node.js\n- `eval()` with any non-literal argument\n- `child_process.exec` with string concatenation\n- `dangerouslySetInnerHTML` with dynamic content\n- `req.query` / `req.body` used in MongoDB queries without sanitization (NoSQL injection)\n- `crypto.createHash('md5')` or `crypto.createHash('sha1')` for passwords\n- `res.header('Access-Control-Allow-Origin', '*')` with credentials\n- `express.static` without proper path restrictions\n- Prototype pollution: `Object.assign` / spread operator with user input\n- `new Function()` with user input\n- `vm.runInNewContext()` with untrusted code\n\n### Python\n- `pickle.loads()` with untrusted data\n- `yaml.load()` without `Loader=yaml.SafeLoader`\n- `os.system()` / `subprocess.call(shell=True)` with user input\n- `eval()` / `exec()` with user input\n- `django.core.serializers` deserialization without validation\n- `SECRET_KEY` hardcoded in settings\n- `DEBUG = True` in production settings\n- `makemigrations` with sensitive data in initial migrations\n- `random` module used for security-sensitive operations (use `secrets`)\n\n### Java\n- `Runtime.getRuntime().exec()` with user input\n- `Statement` instead of `PreparedStatement` for SQL\n- `ObjectInputStream.readObject()` on untrusted data\n- `XMLReader` without disabling external entities (XXE)\n- `Spring` `@RequestMapping` without CSRF protection\n- Hardcoded `DataSource` credentials\n- `System.setProperty(\"com.sun.jndi.ldap.object.trustURLCodebase\", \"true\")`\n\n### Go\n- `text/template` instead of `html/template` for HTML output\n- `exec.Command` with user input as shell string\n- `database/sql` with `fmt.Sprintf` for query construction\n- `crypto/md5` or `crypto/sha1` for password hashing\n- `ioutil.ReadFile` on user-controlled paths without validation\n\n### PHP\n- `mysql_query()` with string concatenation (use PDO prepared statements)\n- `eval()`, `assert()`, `preg_replace` with `/e` modifier\n- `unserialize()` on user input\n- `$_GET` / `$_POST` / `$_REQUEST` used directly in SQL queries\n- `file_get_contents()` on user-controlled URLs (SSRF)\n- `extract()` on `$_GET` / `$_POST` (variable injection)\n\n### C / C++\n- `strcpy`, `strcat`, `sprintf` (use `strncpy`, `strncat`, `snprintf`)\n- `gets()` (removed in C11, but legacy code may still use it)\n- `system()` / `popen()` with user input\n- `memcpy` without bounds checking\n- Format string vulnerabilities: `printf(user_input)` instead of `printf(\"%s\", user_input)`\n- Buffer overflow: stack-allocated buffers with unchecked input size\n\n### Rust\n- `unsafe` blocks without safety justification comments\n- `Command::new()` with user input without validation\n- Raw pointer dereference without bounds checking\n- `std::mem::transmute` misuse\n\n---\n\n## Secret Detection Patterns\n\n### API Keys & Tokens\n```\n# AWS\nAKIA[0-9A-Z]{16}\naws_secret_access_key\\s*[:=]\\s*['\"][A-Za-z0-9/+=]{40}['\"]\n\n# GitHub\ngh[pousr]_[A-Za-z0-9]{36}\ngithub_token\\s*[:=]\\s*['\"][A-Za-z0-9]{40}['\"]\n\n# Google\nAIza[0-9A-Za-z\\-_]{35}\nya29\\.[0-9A-Za-z\\-_]+\n\n# Slack\nxox[baprs]-[0-9A-Za-z-]+\n\n# Stripe\nsk_live_[0-9a-zA-Z]{24}\nrk_live_[0-9a-zA-Z]{24}\n\n# Generic\n(api[_-]?key|secret|token|password|passwd|pwd)\\s*[:=]\\s*['\"][^\\s'\"]{12,}['\"]\n-----BEGIN (RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----\n```\n\n### Database Connection Strings\n```\n(mongodb|postgresql|postgres|mysql|redis)://[^\\s'\"]*:[^\\s'\"]*@\n```\n\n---\n\n## Severity Classification for Security Issues\n\n| Severity | Criteria | Examples |\n|----------|----------|---------|\n| **Critical** | Remote code execution, SQL injection, auth bypass, hardcoded prod secrets | `eval(user_input)`, `os.system(req.query.cmd)` |\n| **High** | Sensitive data exposure, privilege escalation, SSRF, deserialization flaws | `pickle.loads(request_data)`, missing auth on admin endpoints |\n| **Medium** | Missing rate limiting, weak crypto, information disclosure | `md5(password)`, `DEBUG=True` in config |\n| **Low** | Missing security headers, overly permissive CORS, minor info leak | `X-Frame-Options` missing, verbose error messages |\n\nFile v1.0.1:references/severity-guide.md\n\n# Severity Classification Guide\n\n## Overview\n\nEvery finding in a code review must be assigned a severity level. This guide defines the criteria for each level and provides examples to ensure consistent classification.\n\n## Severity Levels\n\n### Critical\n\n**Definition:** Issues that allow attackers to execute arbitrary code, access unauthorized data, or cause system compromise. Must be fixed before merge/deploy.\n\n**Criteria:**\n- Remote Code Execution (RCE)\n- SQL Injection with user-controllable input\n- Authentication/Authorization bypass\n- Hardcoded production credentials/secrets\n- Deserialization of untrusted data leading to RCE\n- Path traversal allowing arbitrary file read/write\n- SSRF leading to internal network access\n\n**Example:**\n```javascript\n// CRITICAL: SQL Injection - user input directly in query\napp.get('/users', (req, res) => {\n    db.query(\"SELECT * FROM users WHERE name = '\" + req.query.name + \"'\");\n});\n\n// CRITICAL: Command Injection\nconst { exec } = require('child_process');\nexec(`ls ${req.query.dir}`, (err, stdout) => { ... });\n\n// CRITICAL: Hardcoded production database credentials\nconst DB_PASSWORD = \"prod_db_p@ssw0rd_2024\";\n```\n\n**Action Required:** Block merge. Fix immediately.\n\n---\n\n### High\n\n**Definition:** Issues that could lead to data breaches, privilege escalation, or significant security weaknesses under certain conditions. Should be fixed before merge.\n\n**Criteria:**\n- Sensitive data exposure (PII, tokens, passwords in logs/responses)\n- Missing authentication on sensitive endpoints\n- Insecure deserialization (may not directly lead to RCE)\n- Cross-Site Scripting (XSS) with user impact\n- Missing input validation leading to unexpected behavior\n- Race conditions in security-sensitive code\n- Use of deprecated/insecure cryptographic functions for sensitive data\n\n**Example:**\n```python\n# HIGH: Sensitive data logged\nlogger.info(f\"User login attempt: email={user.email}, password={password}\")\n\n# HIGH: Missing auth on admin endpoint\n@app.route('/admin/users/delete', methods=['POST'])\ndef delete_user():\n    User.query.filter_by(id=request.json['id']).delete()\n    db.session.commit()\n\n# HIGH: XSS via dangerouslySetInnerHTML\n<div dangerouslySetInnerHTML={{ __html: userProvidedContent }} />\n```\n\n**Action Required:** Strong recommendation to fix before merge. Justify any exceptions.\n\n---\n\n### Medium\n\n**Definition:** Issues that degrade code quality, maintainability, or introduce minor security/performance concerns. Should be fixed but may not block merge if tracked.\n\n**Criteria:**\n- Weak password hashing (MD5/SHA1 for passwords)\n- Missing rate limiting on authentication endpoints\n- Debug mode enabled in configuration files\n- N+1 query patterns\n- Functions with high cyclomatic complexity (>15)\n- Missing error handling for external calls\n- Overly permissive CORS configuration\n- Missing input length/format validation (non-security context)\n\n**Example:**\n```javascript\n// MEDIUM: N+1 query pattern\nusers.forEach(user => {\n    const orders = await db.query(`SELECT * FROM orders WHERE user_id = ${user.id}`);\n});\n\n// MEDIUM: Missing rate limiting on login\napp.post('/login', loginHandler); // No rate limit middleware\n\n// MEDIUM: Weak hashing\nconst hashedPassword = crypto.createHash('md5').update(password).digest('hex');\n```\n\n**Action Required:** Should fix in this PR or create a tracked follow-up issue.\n\n---\n\n### Low\n\n**Definition:** Minor improvements to code quality, readability, or maintainability. Good to fix but not urgent.\n\n**Criteria:**\n- Naming inconsistencies (variable/function names)\n- Missing or incomplete code comments/documentation\n- Dead code (unused imports, variables, functions)\n- Code duplication (small blocks)\n- Magic numbers / strings\n- Missing security headers (non-critical)\n- Overly verbose implementation (can be simplified)\n- Missing `.gitignore` entries for generated files\n\n**Example:**\n```javascript\n// LOW: Dead code - unused import\nimport _ from 'lodash';  // never used in this file\n\n// LOW: Magic number\nif (retryCount > 3) { ... }  // What does 3 mean? Use MAX_RETRIES constant\n\n// LOW: Naming inconsistency\nconst usrData = getUserData();  // should be userData or just userData\n```\n\n**Action Required:** Suggestion. Fix if convenient, otherwise note for future cleanup.\n\n---\n\n### Info\n\n**Definition:** Observations, suggestions, and positive notes that don't require changes.\n\n**Criteria:**\n- Architectural suggestions for future consideration\n- Alternative approaches worth considering\n- Positive callouts (well-written code, good patterns)\n- Questions about design decisions (not issues, just curiosity)\n- Notes about technology updates or deprecations to be aware of\n- Style preferences (not violations, just alternatives)\n\n**Example:**\n```\n// INFO: Consider using a Set for O(1) lookups if this list grows large\nconst allowedUsers = ['alice', 'bob', 'charlie'];\n\n// INFO: Good use of the repository pattern here - clean separation\n\n// INFO: React 18's useTransition hook could improve UX for this heavy render\n```\n\n**Action Required:** No action needed. For the author's consideration.\n\n---\n\n## Severity Matrix\n\n| Dimension | Critical | High | Medium | Low | Info |\n|-----------|----------|------|--------|-----|------|\n| **Security** | RCE, SQLi, Auth bypass | Data exposure, XSS | Weak crypto, no rate limit | Missing headers | Security best practice tip |\n| **Performance** | - | Unbounded memory growth | N+1 queries, O(n^2) in hot path | Unnecessary computation | Algorithm optimization tip |\n| **Code Quality** | - | - | High complexity, deep nesting | Dead code, naming | Alternative pattern suggestion |\n| **Error Handling** | - | Unhandled critical path errors | Empty catch blocks | Missing error context | Custom error type suggestion |\n| **Testing** | - | No tests on critical paths | Missing edge case tests | Test naming | Test organization tip |\n| **Documentation** | - | - | Missing API docs on public interface | Missing inline comments | Doc improvement suggestion |\n\n## Decision Flow\n\n1. **Can this be exploited by an attacker to compromise the system?** → Critical\n2. **Can this lead to data breach or unauthorized access?** → High\n3. **Does this degrade security/performance/quality significantly?** → Medium\n4. **Is this a minor quality or readability issue?** → Low\n5. **Is this an observation or suggestion?** → Info\n\nFile v1.0.1:skill-card.md\n\n## Description:\n\nCode Reviewer helps review code changes, pull requests, or repositories across security, performance, code quality, error handling, testing, and documentation, with optional static analysis and HTML reporting.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[nameused](https://clawhub.ai/user/nameused)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nDevelopers and engineers use this skill to review pull requests, diffs, files, or repositories and receive prioritized findings with remediation guidance. It can combine deterministic script output with checklist-driven reasoning for security, performance, quality, error handling, test, and documentation review.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: The optional HTML report can execute injected browser code when generated from untrusted finding data.\n\nMitigation: Open generated HTML reports cautiously for untrusted repositories or findings, or fix the escaping issue before using that report path.\n\n## Reference(s):\n\n- [Code Review Checklist](artifact/references/checklist.md)\n- [Security Rules](artifact/references/security-rules.md)\n- [Language-Specific Best Practices](artifact/references/best-practices.md)\n- [Severity Guide](artifact/references/severity-guide.md)\n- [ClawHub Skill Page](https://clawhub.ai/nameused/skills/code-reviewer)\n\n## Skill Output:\n\n**Output Type(s):** [Text, Markdown, Code, Shell commands, Guidance]\n\n**Output Format:** [Markdown with structured findings, optional JSON inputs, inline shell commands, and optional HTML report files]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [Findings are grouped by severity and category; optional HTML reports should be treated cautiously for untrusted input.]\n\n## Skill Version(s):\n\n1.0.1 (source: release evidence)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.\n\nArchive v1.0.0: 10 files, 34872 bytes\n\nFiles: references/best-practices.md (7526b), references/checklist.md (5909b), references/security-rules.md (7362b), references/severity-guide.md (6356b), scripts/analyze_complexity.py (12963b), scripts/generate_report.py (25597b), scripts/scan_patterns.py (14582b), skill-card.md (2722b), SKILL.md (11821b), _meta.json (132b)\n\nFile v1.0.0:SKILL.md\n\n---\r\nname: code-reviewer\r\ndescription: \"This skill performs comprehensive code reviews across 6 dimensions: Security, Performance, Code Quality, Error Handling, Testing, and Documentation. It should be used when reviewing code changes, pull requests, or entire codebases in any programming language. Triggers include requests like 'review this code', 'check for security issues', 'audit this PR', 'find bugs in this code', or when a user asks for code quality analysis. The skill includes automated analysis scripts, security rule databases, language-specific best practices, and generates visual HTML reports.\"\r\nagent_created: true\r\n---\r\n\r\n# Code Reviewer\r\n\r\n## Overview\r\n\r\nPerform comprehensive, multi-dimensional code reviews using a combination of automated static analysis and contextual AI reasoning. The skill covers six review dimensions across all major programming languages and produces actionable findings with severity classification and visual HTML reports.\r\n\r\n## When to Use\r\n\r\n- Reviewing a pull request or code diff\r\n- Auditing an existing codebase for security or quality issues\r\n- Pre-merge code quality gate\r\n- Onboarding review of unfamiliar code\r\n- Security vulnerability assessment\r\n- Performance bottleneck identification\r\n\r\n## Review Workflow\r\n\r\nFollow this 4-phase workflow for every code review. Each phase builds on the previous one.\r\n\r\n### Phase 1: Scope & Plan\r\n\r\nDetermine what to review and how:\r\n\r\n1. Identify the review scope: single file, directory, git diff, or PR. If the user provides a git diff or PR, review only changed lines plus their surrounding context. If reviewing a full codebase, ask the user to specify the target directory.\r\n2. Detect the programming language(s) by file extension. Refer to `references/best-practices.md` for language-specific rules.\r\n3. Determine review depth: quick scan (focus on Critical/High only) or full review (all severities). Default to full review unless the user requests a quick scan.\r\n4. Check if automated analysis scripts are available. If Python is available, use the scripts for deterministic analysis.\r\n\r\n### Phase 2: Automated Analysis\r\n\r\nRun the bundled scripts to get deterministic, baseline findings before applying contextual reasoning.\r\n\r\n**Step 1: Complexity Analysis**\r\n\r\nExecute the complexity analyzer on the target code:\r\n\r\n```bash\r\npython scripts/analyze_complexity.py <target-path> --format json\r\n```\r\n\r\nThis detects: long functions (>50 lines), high cyclomatic complexity (>10), deep nesting (>4 levels), excessive parameters (>5). Results are output as JSON.\r\n\r\n**Step 2: Pattern Scanning**\r\n\r\nExecute the pattern scanner to detect security vulnerabilities and code quality issues:\r\n\r\n```bash\r\npython scripts/scan_patterns.py <target-path> --format json\r\n```\r\n\r\nThis detects: SQL injection, command injection, hardcoded secrets, eval usage, weak hashing, XSS, empty catch blocks, TODO/FIXME markers, and 20+ other patterns. Results are output as JSON.\r\n\r\n**Step 3: Merge Results**\r\n\r\nCombine the JSON outputs from both scripts into a single findings list. Deduplicate by (file, line, type).\r\n\r\nIf Python is not available, skip this phase and proceed to Phase 3, performing the equivalent checks manually by reading the code against the patterns in `references/security-rules.md` and `references/checklist.md`.\r\n\r\n### Phase 3: Contextual Review\r\n\r\nRead the code and apply contextual reasoning that automated tools cannot. This is the core value of the review.\r\n\r\nLoad the appropriate reference files as needed:\r\n- `references/checklist.md` - comprehensive 6-dimension checklist\r\n- `references/security-rules.md` - OWASP Top 10, language-specific security patterns, secret detection regex\r\n- `references/best-practices.md` - language-specific idioms and anti-patterns\r\n- `references/severity-guide.md` - severity classification criteria with examples\r\n\r\nReview each finding from Phase 2 to confirm or dismiss false positives. Then examine the code for issues that pattern matching cannot detect:\r\n\r\n**Security (refer to `references/security-rules.md`):**\r\n- Business logic flaws (e.g., negative quantity in order, race conditions in transfers)\r\n- Missing authorization checks on specific business operations\r\n- Insecure data flow (source → sink analysis)\r\n- Trust boundary violations\r\n\r\n**Performance (refer to `references/checklist.md` Section 2):**\r\n- Algorithmic inefficiencies (wrong data structure, unnecessary computation)\r\n- Resource leaks (unclosed connections, orphaned event listeners)\r\n- Scalability concerns (unbounded growth, lock contention)\r\n\r\n**Code Quality (refer to `references/best-practices.md`):**\r\n- SOLID principle violations\r\n- Design pattern misuse or absence\r\n- Naming clarity and consistency\r\n- Abstraction level appropriateness\r\n\r\n**Error Handling (refer to `references/checklist.md` Section 4):**\r\n- Unhandled error paths in critical workflows\r\n- Error messages that leak internal state\r\n- Missing retry/fallback for transient failures\r\n- Improper error propagation (swallowed, re-wrapped, or lost context)\r\n\r\n**Testing (refer to `references/checklist.md` Section 5):**\r\n- Missing tests for critical business logic\r\n- Untested edge cases and error paths\r\n- Test isolation issues (shared state, order dependencies)\r\n- Mock quality (over-mocking, under-mocking)\r\n\r\n**Documentation (refer to `references/checklist.md` Section 6):**\r\n- Missing API documentation on public interfaces\r\n- Outdated comments contradicting code\r\n- Missing architectural decision records for non-obvious choices\r\n\r\n### Phase 4: Report & Recommendations\r\n\r\nProduce the final review output.\r\n\r\n**Step 1: Classify all findings** using `references/severity-guide.md`:\r\n- Critical: RCE, SQLi, auth bypass, hardcoded prod secrets\r\n- High: data exposure, XSS, missing auth, deserialization flaws\r\n- Medium: weak crypto, N+1 queries, high complexity, empty catch blocks\r\n- Low: dead code, naming, magic numbers, debug prints\r\n- Info: suggestions, alternative approaches, positive callouts\r\n\r\n**Step 2: Generate HTML report** (optional, when the user wants a visual report):\r\n\r\n```bash\r\n# Bilingual report with toggle (default)\r\npython scripts/generate_report.py <findings.json> --project \"<project-name>\" --output review-report.html\r\n\r\n# Chinese only\r\npython scripts/generate_report.py <findings.json> --lang zh --output review-report.html\r\n\r\n# English only\r\npython scripts/generate_report.py <findings.json> --lang en --output review-report.html\r\n```\r\n\r\nOr pipe directly:\r\n```bash\r\necho '<combined-json>' | python scripts/generate_report.py - --lang zh --output review-report.html\r\n```\r\n\r\nThe report includes: severity summary cards, category breakdown table, filterable findings list with code snippets, dark-mode styling, and **bilingual support** (`--lang zh|en|both`). When `--lang both` (default), a toggle button in the top-right corner lets users switch between Chinese and English instantly without reloading.\r\n\r\n**Step 3: Summarize in conversation:**\r\n\r\nPresent a concise summary to the user:\r\n1. Overall assessment (1-2 sentences): Is the code safe to merge? What's the risk level?\r\n2. Critical/High findings first, with file:line, issue description, and suggested fix\r\n3. Medium/Low findings grouped by category (don't list each individually unless asked)\r\n4. Positive callouts: what was done well\r\n5. Action items: prioritized list of what to fix before merge vs. what can be tracked as follow-up\r\n\r\n## Review Dimensions\r\n\r\n| Dimension | What It Covers | Primary Reference |\r\n|-----------|---------------|-------------------|\r\n| Security | OWASP Top 10, injection, auth, secrets, crypto | `references/security-rules.md` |\r\n| Performance | DB queries, algorithms, memory, concurrency | `references/checklist.md` §2 |\r\n| Code Quality | Complexity, naming, duplication, architecture | `references/best-practices.md` |\r\n| Error Handling | Coverage, quality, resilience | `references/checklist.md` §4 |\r\n| Testing | Coverage, quality, maintainability | `references/checklist.md` §5 |\r\n| Documentation | Code-level and project-level docs | `references/checklist.md` §6 |\r\n\r\n## Finding Format\r\n\r\nEvery finding should include these fields for consistency:\r\n\r\n```\r\n- Severity: Critical | High | Medium | Low | Info\r\n- Category: Security | Performance | Code Quality | Error Handling | Testing | Documentation\r\n- File: path/to/file.ext\r\n- Line: <line number>\r\n- Rule: <rule ID or short name>\r\n- Message: <what's wrong, in one sentence>\r\n- Suggestion: <how to fix it, in one sentence>\r\n- Snippet: <the problematic code line, if applicable>\r\n```\r\n\r\n## Bundled Resources\r\n\r\n### scripts/\r\n\r\n- **`analyze_complexity.py`** - Analyzes cyclomatic complexity, function length, nesting depth, and parameter count. Supports Python (via AST) and brace-based languages (JS/TS/Java/Go/C/C++/PHP/Ruby) via regex heuristics. Output: JSON or text.\r\n\r\n- **`scan_patterns.py`** - Scans for 30+ security and quality anti-patterns including SQL injection, command injection, hardcoded secrets, eval, weak hashing, XSS, empty catch blocks, TODO markers, magic numbers, and more. Output: JSON or text.\r\n\r\n- **`generate_report.py`** - Generates a self-contained HTML report from JSON findings. Features: severity summary cards, category breakdown table, interactive severity filtering, code snippets, dark mode design, **bilingual support** (Chinese/English with live toggle via `--lang zh|en|both`). Reads from files or stdin.\r\n\r\n### references/\r\n\r\n- **`checklist.md`** - Comprehensive 6-dimension code review checklist with 80+ individual checks. Use as a systematic verification list during Phase 3.\r\n\r\n- **`security-rules.md`** - OWASP Top 10 quick reference, language-specific security patterns (JS/TS, Python, Java, Go, PHP, C/C++, Rust), secret detection regex patterns, and severity classification for security issues.\r\n\r\n- **`best-practices.md`** - Language-specific idiomatic best practices and common anti-patterns for JavaScript/TypeScript, Python, Java, Go, and general principles (SOLID, Clean Code, API Design, VCS conventions).\r\n\r\n- **`severity-guide.md`** - Detailed severity classification guide with criteria, code examples, and a decision flow for each level (Critical through Info).\r\n\r\n### assets/\r\n\r\nNot used in this skill. The HTML report is generated dynamically by `scripts/generate_report.py`.\r\n\r\n## Platform Compatibility\r\n\r\nThis skill is designed to work across multiple platforms:\r\n\r\n- **WorkBuddy**: Full support including script execution\r\n- **Claude Code**: Full support including local file access and script execution\r\n- **Coze (扣子)**: SKILL.md instructions and references work in cloud environment. Scripts execute in Coze's sandbox. The skill follows the standard SKILL.md format that Coze's skill loader expects (compatible with Claude Skills specification).\r\n\r\nWhen running in a cloud-only environment without local file access, the automated scripts (Phase 2) may be unavailable. In that case, skip to Phase 3 and perform all checks manually by reading code against the reference files.\r\n\r\n## Tips for High-Quality Reviews\r\n\r\n1. **Always confirm false positives**: Pattern-based findings can be wrong. Read the actual code context before reporting.\r\n2. **Prioritize by impact**: A Critical finding in an unauthenticated endpoint matters more than a Low finding in an internal tool.\r\n3. **Provide actionable fixes**: Don't just say \"this is wrong\" - show the correct approach.\r\n4. **Acknowledge good code**: Call out well-written code, good patterns, and thoughtful error handling. Reviews shouldn't be purely negative.\r\n5. **Consider the codebase context**: Legacy code, time constraints, and team conventions matter. Don't flag every style issue in a 10-year-old codebase.\r\n6. **Track follow-ups**: For Medium/Low issues that don't block merge, suggest creating tracked issues for future cleanup.\n\nFile v1.0.0:_meta.json\n\n{\n  \"ownerId\": \"kn77qvnxzvd6mty516h2m09kan891gd9\",\n  \"slug\": \"code-reviewer\",\n  \"version\": \"1.0.0\",\n  \"publishedAt\": 1781915801756\n}\n\nFile v1.0.0:references/best-practices.md\n\n# Language-Specific Best Practices\n\n## JavaScript / TypeScript\n\n### Modern Syntax\n- Use `const` by default, `let` when reassignment needed, never `var`\n- Use arrow functions for callbacks and short functions; use `function` for methods and constructors\n- Use template literals over string concatenation\n- Use destructuring for object/array extraction\n- Use spread operator instead of `Object.assign` for immutability\n- Use optional chaining (`?.`) and nullish coalescing (`??`) instead of manual checks\n\n### TypeScript Specific\n- Enable `strict: true` in tsconfig.json\n- Avoid `any` type - use `unknown` when type is truly unknown, then narrow\n- Use `interface` for object shapes, `type` for unions and intersections\n- Use `enum` or union types for fixed value sets\n- Prefer `readonly` for immutable properties\n- Use generics for reusable components/functions\n- Enable `noUncheckedIndexedAccess` for safer array/object access\n\n### Async Patterns\n- Use `async/await` over `.then()` chains for readability\n- Always handle promise rejections (try/catch or .catch())\n- Use `Promise.all()` for parallel operations, not sequential awaits\n- Avoid fire-and-forget async calls (always await or handle)\n- Use `AbortController` for cancellable fetch requests\n\n### Node.js\n- Use `path.join()` / `path.resolve()` instead of string concatenation for paths\n- Use `fs.promises` (async) over `fs` (sync) in server code\n- Validate input with Zod / Joi / express-validator at API boundaries\n- Use `crypto.randomUUID()` for ID generation, not `Math.random()`\n- Set `helmet()` middleware for security headers\n- Use `express-rate-limit` for API rate limiting\n\n### Common Anti-Patterns\n- Mutating function arguments\n- Comparing with `==` instead of `===`\n- Using `forEach` when `map`/`filter`/`reduce` is intended\n- Async function without await inside (missing `await` keyword)\n- `any` type in TypeScript (loss of type safety)\n- Empty catch blocks (`catch (e) {}`)\n\n---\n\n## Python\n\n### Modern Syntax (3.9+)\n- Use type hints on all function signatures (`def foo(x: int) -> str:`)\n- Use `from __future__ import annotations` for forward references\n- Use f-strings for string formatting (not `%` or `.format()`)\n- Use `pathlib.Path` instead of `os.path` for path manipulation\n- Use dataclasses or Pydantic for data containers\n- Use `match` statement for complex pattern matching (3.10+)\n- Use `walrus operator` (`:=`) for assignment expressions where it improves readability\n\n### Error Handling\n- Catch specific exceptions, not bare `except:` or `except Exception:`\n- Use context managers (`with` statements) for resource management\n- Raise exceptions with meaningful messages and proper exception types\n- Use custom exception hierarchies for application-specific errors\n- Never use `except: pass` - at minimum log the error\n\n### Security\n- Use `secrets` module for tokens/passwords, not `random`\n- Use `bcrypt` or `argon2-cffi` for password hashing\n- Use parameterized queries with `psycopg2` / `SQLAlchemy` (never string concat)\n- Use `yaml.safe_load()` not `yaml.load()`\n- Use `subprocess.run()` with `shell=False` (list arguments, not string)\n- Validate and sanitize all user input (use Pydantic or marshmallow)\n\n### Code Organization\n- One class per file for major classes\n- Group related functions into modules\n- Use `__all__` to define public API\n- Use `if __name__ == \"__main__\":` guard for script entry points\n- Keep `__init__.py` files minimal (re-exports only)\n\n### Common Anti-Patterns\n- Mutable default arguments (`def foo(items=[])`)\n- Bare `except:` clauses\n- Global variables for state management\n- `import *` (use explicit imports)\n- Comparing to `None` with `==` (use `is None`)\n- Using `type()` for type checking (use `isinstance()`)\n\n---\n\n## Java\n\n### Modern Java (11+)\n- Use `var` for local variable type inference when type is obvious\n- Use `record` for immutable data carriers (Java 16+)\n- Use `switch` expressions with `->` and `yield` (Java 14+)\n- Use `Optional<T>` for return types that may be absent (never as field type)\n- Use `Stream API` for collection processing over manual loops\n- Use `text blocks` (`\"\"\"...\"\"\"`) for multi-line strings (Java 15+)\n\n### Spring Framework\n- Use constructor injection over `@Autowired` field injection\n- Use `@Transactional` at service layer, not controller\n- Use `@RestController` + `@RequestMapping` for REST APIs\n- Use `@Validated` / `@Valid` for request body validation\n- Use `@ExceptionHandler` / `@ControllerAdvice` for global error handling\n- Use `ResponseEntity<T>` for HTTP responses with proper status codes\n- Use `@ConfigurationProperties` over `@Value` for grouped config\n\n### Common Anti-Patterns\n- `NullPointerException` from unchecked method chains\n- Raw types (`List` instead of `List<String>`)\n- `instanceof` chains (use polymorphism or sealed classes)\n- `Thread.sleep()` in tests (use `Awaitility`)\n- Catching `Exception` or `Throwable` broadly\n- Using `Date` / `Calendar` (use `java.time.*`)\n\n---\n\n## Go\n\n### Idiomatic Go\n- Return errors as last return value, always check them\n- Use `errors.Is()` and `errors.As()` for error comparison (not `==`)\n- Use `context.Context` as first parameter in all functions that do I/O\n- Use goroutines with proper cancellation (`ctx.Done()`)\n- Use `sync.Mutex` / `sync.RWMutex` for shared state protection\n- Use channels for goroutine communication, mutexes for state protection\n- Prefer composition over inheritance (embed structs, don't subclass)\n- Keep interfaces small (single-method interfaces are ideal)\n\n### Error Handling\n- Wrap errors with context: `fmt.Errorf(\"doing X: %w\", err)`\n- Use `errors.New()` for static errors, `fmt.Errorf()` for formatted\n- Define sentinel errors: `var ErrNotFound = errors.New(\"not found\")`\n- Check errors immediately, don't ignore them (`_ = someFunc()` is a smell)\n\n### Common Anti-Patterns\n- Ignoring errors (`result, _ := doSomething()`)\n- Starting goroutines without a way to stop them\n- Global mutable state without synchronization\n- Interface pollution (defining interfaces before multiple implementations exist)\n- `panic()` in library code (return errors instead)\n- `init()` side effects (keep init minimal)\n\n---\n\n## General (All Languages)\n\n### SOLID Principles\n- **S**ingle Responsibility: Each class/function has one reason to change\n- **O**pen/Closed: Open for extension, closed for modification\n- **L**iskov Substitution: Subtypes must be substitutable for base types\n- **I**nterface Segregation: Many specific interfaces > one general interface\n- **D**ependency Inversion: Depend on abstractions, not concretions\n\n### Clean Code\n- Functions should be small and do one thing\n- Function names should be verbs, variable names should be nouns\n- Avoid negative conditions (`if (!isNotValid)` is hard to read)\n- Avoid deep nesting (use guard clauses / early returns)\n- Comments should explain WHY, not WHAT\n- Remove commented-out code (use version control)\n\n### Version Control\n- Commit messages: imperative mood, subject under 50 chars, body under 72\n- One logical change per commit\n- No secrets in commit history (use `.gitignore` and `git-secrets`)\n- Branch names: `feature/`, `bugfix/`, `hotfix/` prefixes\n\n### API Design\n- REST: Use proper HTTP methods (GET/POST/PUT/PATCH/DELETE)\n- Use plural nouns for resource paths (`/users`, not `/user`)\n- Return appropriate HTTP status codes (not 200 for everything)\n- Version APIs (`/api/v1/`) to allow breaking changes\n- Paginate list endpoints (cursor-based preferred over offset)\n- Use consistent naming (camelCase or snake_case, not mixed)\n\nFile v1.0.0:references/checklist.md\n\n# Code Review Checklist\n\n## 1. Security\n\n### Injection Attacks\n- [ ] SQL queries use parameterized statements / prepared statements (no string concatenation)\n- [ ] No OS command execution with user input (`os.system`, `exec`, `Runtime.exec`, `child_process.exec`)\n- [ ] Template engines use auto-escaping (no `dangerouslySetInnerHTML`, `{!! !!}`, `innerHTML` with user data)\n- [ ] No eval on user input (`eval()`, `Function()`, `new Function()`)\n\n### Authentication & Authorization\n- [ ] Passwords hashed with bcrypt/scrypt/argon2 (not MD5/SHA1/plaintext)\n- [ ] JWT tokens validated for signature, expiry, and issuer\n- [ ] Authorization checks present on every protected route/endpoint\n- [ ] No hardcoded credentials, API keys, or tokens in source code\n- [ ] Secrets loaded from environment variables or secret managers\n\n### Data Exposure\n- [ ] Sensitive data not logged (passwords, tokens, PII, credit card numbers)\n- [ ] API responses do not leak internal field names or stack traces\n- [ ] HTTPS enforced; no mixed content\n- [ ] CORS configured restrictively (no `Access-Control-Allow-Origin: *` on sensitive endpoints)\n\n### File Operations\n- [ ] File paths validated against traversal attacks (no `../` in user-controlled paths)\n- [ ] Upload restrictions: file type, size, and content validation\n- [ ] Download paths restricted to allowed directories\n\n### Dependencies\n- [ ] No known vulnerable dependencies (checked via `npm audit` / `pip audit` / `snyk`)\n- [ ] Dependency versions pinned (no floating `*` or `latest`)\n\n---\n\n## 2. Performance\n\n### Database\n- [ ] No N+1 query patterns (queries inside loops)\n- [ ] Database indexes exist for frequently queried columns\n- [ ] Pagination applied to list endpoints (no unbounded `SELECT *`)\n- [ ] ORM queries select only needed columns (no `SELECT *` when only 2 fields used)\n\n### Algorithms & Data Structures\n- [ ] No O(n^2) or worse inside hot paths / loops\n- [ ] Appropriate data structures used (Set for lookups instead of Array.includes)\n- [ ] No unnecessary re-computation of the same value inside loops\n\n### Memory\n- [ ] No memory leaks (event listeners removed, intervals cleared, connections closed)\n- [ ] Large collections streamed rather than loaded entirely into memory\n- [ ] No unnecessary object retention in long-lived scopes (closures, globals, singletons)\n\n### Concurrency\n- [ ] Async operations not blocking the event loop (no sync I/O in async contexts)\n- [ ] Database connections released properly (try/finally or using context managers)\n- [ ] Race conditions addressed (proper locking / atomic operations)\n\n---\n\n## 3. Code Quality\n\n### Readability\n- [ ] Variable/function names are descriptive and self-documenting\n- [ ] Functions do one thing (Single Responsibility)\n- [ ] No dead code (unused variables, functions, imports, unreachable code)\n- [ ] No magic numbers / strings (use named constants)\n- [ ] Consistent naming convention (camelCase / snake_case per language convention)\n\n### Complexity\n- [ ] Functions under 50 lines (refactor if longer)\n- [ ] Cyclomatic complexity under 10 per function (use `scripts/analyze_complexity.py`)\n- [ ] Nesting depth under 4 levels (extract early returns / guard clauses)\n- [ ] Parameter count under 5 (use parameter objects if more)\n\n### Duplication\n- [ ] No copy-pasted code blocks (DRY principle)\n- [ ] Shared logic extracted into reusable functions/modules\n- [ ] No duplicated string literals / magic constants\n\n### Architecture\n- [ ] Proper separation of concerns (controller/service/repository layers)\n- [ ] No business logic in presentation layer (views/templates/controllers)\n- [ ] Dependencies injected (not hard-wired / globally accessed)\n- [ ] No circular dependencies between modules\n\n---\n\n## 4. Error Handling\n\n### Coverage\n- [ ] External calls wrapped in try/catch (network, file, database, subprocess)\n- [ ] Promise rejections handled (no unhandled `.then()` without `.catch()`)\n- [ ] Error states tested (not just happy path)\n- [ ] No empty catch blocks (`catch {}` or `except: pass`)\n\n### Quality\n- [ ] Errors logged with context (what operation, what input, what failed)\n- [ ] Custom error types used for domain errors (not generic Error/Exception)\n- [ ] Error messages user-friendly (no stack traces or internal details exposed)\n- [ ] Errors not swallowed silently (at minimum logged)\n\n### Resilience\n- [ ] Retry logic for transient failures (network, rate limits)\n- [ ] Circuit breakers / timeouts for external service calls\n- [ ] Graceful degradation when optional services unavailable\n- [ ] Idempotency for retry-safe operations\n\n---\n\n## 5. Testing\n\n### Coverage\n- [ ] Unit tests exist for business logic\n- [ ] Integration tests exist for API endpoints\n- [ ] Edge cases tested (empty input, null, boundary values, large input)\n- [ ] Error paths tested (not just happy path)\n\n### Quality\n- [ ] Tests are independent (no shared mutable state, no order dependency)\n- [ ] Test names describe the scenario and expected outcome\n- [ ] No flaky tests (time-dependent, race conditions, external service calls)\n- [ ] Mocks/stubs used for external dependencies (not real DB/API calls in unit tests)\n- [ ] Test data is realistic and representative\n\n### Maintainability\n- [ ] Test setup is minimal and clear (Arrange-Act-Assert pattern)\n- [ ] No test logic duplication (use test factories/builders)\n- [ ] Tests run fast (unit tests under 1s each)\n\n---\n\n## 6. Documentation\n\n### Code Level\n- [ ] Public API functions/classes documented (JSDoc, docstrings, GoDoc)\n- [ ] Complex algorithms explained with comments (why, not what)\n- [ ] TODO/FIXME comments include issue numbers and context\n- [ ] No outdated comments (comments that contradict the code)\n\n### Project Level\n- [ ] README exists with setup/run/test instructions\n- [ ] Environment variables documented (`.env.example`)\n- [ ] API changes reflected in API documentation (OpenAPI/Swagger)\n- [ ] Breaking changes noted in CHANGELOG\n\nFile v1.0.0:references/security-rules.md\n\n# Security Vulnerability Detection Rules\n\n## OWASP Top 10 Quick Reference\n\n### A01 - Broken Access Control\n| Pattern | Indicators | Languages |\n|---------|-----------|-----------|\n| Missing auth check | Route handler without auth middleware | All |\n| IDOR | Direct object reference from user input without ownership check | All |\n| Privilege escalation | Role check missing before sensitive operation | All |\n| Force browsing | No authorization on API endpoints | All |\n\n**Detection patterns:**\n- Route definitions without `auth` / `requireAuth` / `@login_required` / `@Authorized`\n- `req.params.id` / `request.getParameter(\"id\")` used directly in DB query without ownership validation\n- `isAdmin` check only on frontend, not backend\n\n### A02 - Cryptographic Failures\n| Pattern | Indicators | Languages |\n|---------|-----------|-----------|\n| Weak hashing | MD5, SHA1 used for passwords | All |\n| Hardcoded secrets | API keys in source code | All |\n| No encryption | Sensitive data stored/transmitted in plaintext | All |\n| Weak randomness | `Math.random()` / `random.random()` for security tokens | All |\n\n**Detection patterns (regex):**\n```\n# Hardcoded API keys\n(api[_-]?key|secret|token|password)\\s*[:=]\\s*['\"][A-Za-z0-9]{16,}['\"]\n\n# Weak hash algorithms\n\\b(MD5|SHA1|md5|sha1)\\b.*password\n\n# Insecure random\n\\b(Math\\.random|random\\.random)\\(\\).*token|session|password|key\n```\n\n### A03 - Injection\n| Pattern | Indicators | Languages |\n|---------|-----------|-----------|\n| SQL Injection | String concatenation in SQL queries | All |\n| Command Injection | User input in shell commands | All |\n| LDAP Injection | String concat in LDAP queries | All |\n| Template Injection | User input in template engine | All |\n\n**Detection patterns:**\n```\n# SQL injection\n(SELECT|INSERT|UPDATE|DELETE|DROP).*\\+.*\\$_(GET|POST|REQUEST)\nquery\\s*\\+\\s*['\"].*['\"]\\s*\\+\nexecute\\s*\\(\\s*['\"].*\\{.*\\}.*['\"]\\s*\\)\n\n# Command injection\n(os\\.system|subprocess\\.call|exec|child_process\\.exec)\\s*\\(.*\\+.*(input|req|param)\n```\n\n### A04 - Insecure Design\n- Missing rate limiting on authentication endpoints\n- No account lockout after failed login attempts\n- Predictable URL patterns for sensitive resources\n- Missing input validation (length, type, format, range)\n\n### A05 - Security Misconfiguration\n- Debug mode enabled in production (`DEBUG=True`)\n- Detailed error pages in production (stack traces exposed)\n- Default credentials not changed\n- Unnecessary features enabled (directory listing, HTTP methods)\n\n### A07 - Identification & Authentication Failures\n- Weak password policy (no minimum length, complexity)\n- Session ID in URL parameters\n- Session fixation (session not regenerated after login)\n- No session timeout\n\n### A08 - Software & Data Integrity Failures\n- Unsigned software updates\n- Deserialization of untrusted data (`pickle.loads`, `yaml.load` without SafeLoader)\n- Dependencies from untrusted sources\n\n### A09 - Logging & Monitoring Failures\n- Security events not logged (login, logout, password change, privilege changes)\n- Logs not protected against tampering\n- No alerting on suspicious activities\n\n### A10 - Server-Side Request Forgery (SSRF)\n- User-controlled URLs fetched server-side without validation\n- No allowlist for outbound HTTP requests\n- Internal IP ranges not blocked (`127.0.0.1`, `10.x`, `172.16-31.x`, `169.254.x`)\n\n---\n\n## Language-Specific Security Patterns\n\n### JavaScript / TypeScript / Node.js\n- `eval()` with any non-literal argument\n- `child_process.exec` with string concatenation\n- `dangerouslySetInnerHTML` with dynamic content\n- `req.query` / `req.body` used in MongoDB queries without sanitization (NoSQL injection)\n- `crypto.createHash('md5')` or `crypto.createHash('sha1')` for passwords\n- `res.header('Access-Control-Allow-Origin', '*')` with credentials\n- `express.static` without proper path restrictions\n- Prototype pollution: `Object.assign` / spread operator with user input\n- `new Function()` with user input\n- `vm.runInNewContext()` with untrusted code\n\n### Python\n- `pickle.loads()` with untrusted data\n- `yaml.load()` without `Loader=yaml.SafeLoader`\n- `os.system()` / `subprocess.call(shell=True)` with user input\n- `eval()` / `exec()` with user input\n- `django.core.serializers` deserialization without validation\n- `SECRET_KEY` hardcoded in settings\n- `DEBUG = True` in production settings\n- `makemigrations` with sensitive data in initial migrations\n- `random` module used for security-sensitive operations (use `secrets`)\n\n### Java\n- `Runtime.getRuntime().exec()` with user input\n- `Statement` instead of `PreparedStatement` for SQL\n- `ObjectInputStream.readObject()` on untrusted data\n- `XMLReader` without disabling external entities (XXE)\n- `Spring` `@RequestMapping` without CSRF protection\n- Hardcoded `DataSource` credentials\n- `System.setProperty(\"com.sun.jndi.ldap.object.trustURLCodebase\", \"true\")`\n\n### Go\n- `text/template` instead of `html/template` for HTML output\n- `exec.Command` with user input as shell string\n- `database/sql` with `fmt.Sprintf` for query construction\n- `crypto/md5` or `crypto/sha1` for password hashing\n- `ioutil.ReadFile` on user-controlled paths without validation\n\n### PHP\n- `mysql_query()` with string concatenation (use PDO prepared statements)\n- `eval()`, `assert()`, `preg_replace` with `/e` modifier\n- `unserialize()` on user input\n- `$_GET` / `$_POST` / `$_REQUEST` used directly in SQL queries\n- `file_get_contents()` on user-controlled URLs (SSRF)\n- `extract()` on `$_GET` / `$_POST` (variable injection)\n\n### C / C++\n- `strcpy`, `strcat`, `sprintf` (use `strncpy`, `strncat`, `snprintf`)\n- `gets()` (removed in C11, but legacy code may still use it)\n- `system()` / `popen()` with user input\n- `memcpy` without bounds checking\n- Format string vulnerabilities: `printf(user_input)` instead of `printf(\"%s\", user_input)`\n- Buffer overflow: stack-allocated buffers with unchecked input size\n\n### Rust\n- `unsafe` blocks without safety justification comments\n- `Command::new()` with user input without validation\n- Raw pointer dereference without bounds checking\n- `std::mem::transmute` misuse\n\n---\n\n## Secret Detection Patterns\n\n### API Keys & Tokens\n```\n# AWS\nAKIA[0-9A-Z]{16}\naws_secret_access_key\\s*[:=]\\s*['\"][A-Za-z0-9/+=]{40}['\"]\n\n# GitHub\ngh[pousr]_[A-Za-z0-9]{36}\ngithub_token\\s*[:=]\\s*['\"][A-Za-z0-9]{40}['\"]\n\n# Google\nAIza[0-9A-Za-z\\-_]{35}\nya29\\.[0-9A-Za-z\\-_]+\n\n# Slack\nxox[baprs]-[0-9A-Za-z-]+\n\n# Stripe\nsk_live_[0-9a-zA-Z]{24}\nrk_live_[0-9a-zA-Z]{24}\n\n# Generic\n(api[_-]?key|secret|token|password|passwd|pwd)\\s*[:=]\\s*['\"][^\\s'\"]{12,}['\"]\n-----BEGIN (RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----\n```\n\n### Database Connection Strings\n```\n(mongodb|postgresql|postgres|mysql|redis)://[^\\s'\"]*:[^\\s'\"]*@\n```\n\n---\n\n## Severity Classification for Security Issues\n\n| Severity | Criteria | Examples |\n|----------|----------|---------|\n| **Critical** | Remote code execution, SQL injection, auth bypass, hardcoded prod secrets | `eval(user_input)`, `os.system(req.query.cmd)` |\n| **High** | Sensitive data exposure, privilege escalation, SSRF, deserialization flaws | `pickle.loads(request_data)`, missing auth on admin endpoints |\n| **Medium** | Missing rate limiting, weak crypto, information disclosure | `md5(password)`, `DEBUG=True` in config |\n| **Low** | Missing security headers, overly permissive CORS, minor info leak | `X-Frame-Options` missing, verbose error messages |\n\nFile v1.0.0:references/severity-guide.md\n\n# Severity Classification Guide\n\n## Overview\n\nEvery finding in a code review must be assigned a severity level. This guide defines the criteria for each level and provides examples to ensure consistent classification.\n\n## Severity Levels\n\n### Critical\n\n**Definition:** Issues that allow attackers to execute arbitrary code, access unauthorized data, or cause system compromise. Must be fixed before merge/deploy.\n\n**Criteria:**\n- Remote Code Execution (RCE)\n- SQL Injection with user-controllable input\n- Authentication/Authorization bypass\n- Hardcoded production credentials/secrets\n- Deserialization of untrusted data leading to RCE\n- Path traversal allowing arbitrary file read/write\n- SSRF leading to internal network access\n\n**Example:**\n```javascript\n// CRITICAL: SQL Injection - user input directly in query\napp.get('/users', (req, res) => {\n    db.query(\"SELECT * FROM users WHERE name = '\" + req.query.name + \"'\");\n});\n\n// CRITICAL: Command Injection\nconst { exec } = require('child_process');\nexec(`ls ${req.query.dir}`, (err, stdout) => { ... });\n\n// CRITICAL: Hardcoded production database credentials\nconst DB_PASSWORD = \"prod_db_p@ssw0rd_2024\";\n```\n\n**Action Required:** Block merge. Fix immediately.\n\n---\n\n### High\n\n**Definition:** Issues that could lead to data breaches, privilege escalation, or significant security weaknesses under certain conditions. Should be fixed before merge.\n\n**Criteria:**\n- Sensitive data exposure (PII, tokens, passwords in logs/responses)\n- Missing authentication on sensitive endpoints\n- Insecure deserialization (may not directly lead to RCE)\n- Cross-Site Scripting (XSS) with user impact\n- Missing input validation leading to unexpected behavior\n- Race conditions in security-sensitive code\n- Use of deprecated/insecure cryptographic functions for sensitive data\n\n**Example:**\n```python\n# HIGH: Sensitive data logged\nlogger.info(f\"User login attempt: email={user.email}, password={password}\")\n\n# HIGH: Missing auth on admin endpoint\n@app.route('/admin/users/delete', methods=['POST'])\ndef delete_user():\n    User.query.filter_by(id=request.json['id']).delete()\n    db.session.commit()\n\n# HIGH: XSS via dangerouslySetInnerHTML\n<div dangerouslySetInnerHTML={{ __html: userProvidedContent }} />\n```\n\n**Action Required:** Strong recommendation to fix before merge. Justify any exceptions.\n\n---\n\n### Medium\n\n**Definition:** Issues that degrade code quality, maintainability, or introduce minor security/performance concerns. Should be fixed but may not block merge if tracked.\n\n**Criteria:**\n- Weak password hashing (MD5/SHA1 for passwords)\n- Missing rate limiting on authentication endpoints\n- Debug mode enabled in configuration files\n- N+1 query patterns\n- Functions with high cyclomatic complexity (>15)\n- Missing error handling for external calls\n- Overly permissive CORS configuration\n- Missing input length/format validation (non-security context)\n\n**Example:**\n```javascript\n// MEDIUM: N+1 query pattern\nusers.forEach(user => {\n    const orders = await db.query(`SELECT * FROM orders WHERE user_id = ${user.id}`);\n});\n\n// MEDIUM: Missing rate limiting on login\napp.post('/login', loginHandler); // No rate limit middleware\n\n// MEDIUM: Weak hashing\nconst hashedPassword = crypto.createHash('md5').update(password).digest('hex');\n```\n\n**Action Required:** Should fix in this PR or create a tracked follow-up issue.\n\n---\n\n### Low\n\n**Definition:** Minor improvements to code quality, readability, or maintainability. Good to fix but not urgent.\n\n**Criteria:**\n- Naming inconsistencies (variable/function names)\n- Missing or incomplete code comments/documentation\n- Dead code (unused imports, variables, functions)\n- Code duplication (small blocks)\n- Magic numbers / strings\n- Missing security headers (non-critical)\n- Overly verbose implementation (can be simplified)\n- Missing `.gitignore` entries for generated files\n\n**Example:**\n```javascript\n// LOW: Dead code - unused import\nimport _ from 'lodash';  // never used in this file\n\n// LOW: Magic number\nif (retryCount > 3) { ... }  // What does 3 mean? Use MAX_RETRIES constant\n\n// LOW: Naming inconsistency\nconst usrData = getUserData();  // should be userData or just userData\n```\n\n**Action Required:** Suggestion. Fix if convenient, otherwise note for future cleanup.\n\n---\n\n### Info\n\n**Definition:** Observations, suggestions, and positive notes that don't require changes.\n\n**Criteria:**\n- Architectural suggestions for future consideration\n- Alternative approaches worth considering\n- Positive callouts (well-written code, good patterns)\n- Questions about design decisions (not issues, just curiosity)\n- Notes about technology updates or deprecations to be aware of\n- Style preferences (not violations, just alternatives)\n\n**Example:**\n```\n// INFO: Consider using a Set for O(1) lookups if this list grows large\nconst allowedUsers = ['alice', 'bob', 'charlie'];\n\n// INFO: Good use of the repository pattern here - clean separation\n\n// INFO: React 18's useTransition hook could improve UX for this heavy render\n```\n\n**Action Required:** No action needed. For the author's consideration.\n\n---\n\n## Severity Matrix\n\n| Dimension | Critical | High | Medium | Low | Info |\n|-----------|----------|------|--------|-----|------|\n| **Security** | RCE, SQLi, Auth bypass | Data exposure, XSS | Weak crypto, no rate limit | Missing headers | Security best practice tip |\n| **Performance** | - | Unbounded memory growth | N+1 queries, O(n^2) in hot path | Unnecessary computation | Algorithm optimization tip |\n| **Code Quality** | - | - | High complexity, deep nesting | Dead code, naming | Alternative pattern suggestion |\n| **Error Handling** | - | Unhandled critical path errors | Empty catch blocks | Missing error context | Custom error type suggestion |\n| **Testing** | - | No tests on critical paths | Missing edge case tests | Test naming | Test organization tip |\n| **Documentation** | - | - | Missing API docs on public interface | Missing inline comments | Doc improvement suggestion |\n\n## Decision Flow\n\n1. **Can this be exploited by an attacker to compromise the system?** → Critical\n2. **Can this lead to data breach or unauthorized access?** → High\n3. **Does this degrade security/performance/quality significantly?** → Medium\n4. **Is this a minor quality or readability issue?** → Low\n5. **Is this an observation or suggestion?** → Info\n\nFile v1.0.0:skill-card.md\n\n## Description: <br>\nThis skill performs comprehensive code reviews across 6 dimensions: Security, Performance, Code Quality, Error Handling, Testing, and Documentation. <br>\n\nThis skill is ready for commercial/non-commercial use. <br>\n\n## Publisher: <br>\n[nameused](https://clawhub.ai/user/nameused) <br>\n\n### License/Terms of Use: <br>\nMIT-0 <br>\n\n\n## Use Case: <br>\nDevelopers and engineers use this skill to review pull requests, code changes, or codebases for security, performance, quality, error handling, testing, and documentation issues. It combines local static-analysis scripts with contextual review guidance to produce actionable findings and optional reports. <br>\n\n### Deployment Geography for Use: <br>\nGlobal <br>\n\n## Known Risks and Mitigations: <br>\nRisk: The agent reads the code paths selected for review, which can expose proprietary source code or sensitive snippets to the reviewing workflow. <br>\nMitigation: Use explicit target paths and run reviews only on code the user intends the agent to inspect. <br>\nRisk: Generated HTML reports may contain code snippets and findings from the scanned codebase. <br>\nMitigation: Treat generated reports as sensitive review artifacts and share or store them according to the codebase's confidentiality requirements. <br>\nRisk: The skill can run local Python analysis scripts against user-selected paths. <br>\nMitigation: Review the target path and command before execution; the security evidence reports no hidden exfiltration, persistence, or destructive behavior. <br>\n\n\n## Reference(s): <br>\n- [ClawHub skill page](https://clawhub.ai/nameused/code-reviewer) <br>\n- [Best Practices](artifact/references/best-practices.md) <br>\n- [Code Review Checklist](artifact/references/checklist.md) <br>\n- [Security Vulnerability Detection Rules](artifact/references/security-rules.md) <br>\n- [Severity Classification Guide](artifact/references/severity-guide.md) <br>\n\n\n## Skill Output: <br>\n**Output Type(s):** [text, markdown, code, shell commands, configuration, guidance] <br>\n**Output Format:** [Markdown review summary, JSON script findings, and optional self-contained HTML report] <br>\n**Output Parameters:** [1D] <br>\n**Other Properties Related to Output:** [May include severity-classified findings, affected file and line references, snippets, fix recommendations, and bilingual HTML report output.] <br>\n\n## Skill Version(s): <br>\n1.0.0 (source: ClawHub release evidence) <br>\n\n## Ethical Considerations: <br>\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment. <br>","readmeExcerpt":"Skill: Code Reviewer Owner: nameused Summary: 本技能从 6 个维度对代码进行全面审核：安全性、性能、代码质量、错误处理、测试和文档。适用于审核代码变更、Pull Request 或整个代码库（支持所有主流编程语言）。触发词包括：「帮我 review 这段代码」「检查安全问题」「审查这个 PR」「找出代码中的 Bug」，或用户请求代码质量分析时使用。技能内置自... Tags: latest:1.0.1 Version history: v1.0.1 | 2026-06-20T13:41:13.597Z | user - Refactored all documentation and instructions from English to Chinese for improved localization. - Updated descriptions, workflows, re","codeSnippets":[],"executableExamples":[{"language":"text","snippet":"# Hardcoded API keys\n(api[_-]?key|secret|token|password)\\s*[:=]\\s*['\"][A-Za-z0-9]{16,}['\"]\n\n# Weak hash algorithms\n\\b(MD5|SHA1|md5|sha1)\\b.*password\n\n# Insecure random\n\\b(Math\\.random|random\\.random)\\(\\).*token|session|password|key"},{"language":"text","snippet":"# SQL injection\n(SELECT|INSERT|UPDATE|DELETE|DROP).*\\+.*\\$_(GET|POST|REQUEST)\nquery\\s*\\+\\s*['\"].*['\"]\\s*\\+\nexecute\\s*\\(\\s*['\"].*\\{.*\\}.*['\"]\\s*\\)\n\n# Command injection\n(os\\.system|subprocess\\.call|exec|child_process\\.exec)\\s*\\(.*\\+.*(input|req|param)"},{"language":"text","snippet":"# AWS\nAKIA[0-9A-Z]{16}\naws_secret_access_key\\s*[:=]\\s*['\"][A-Za-z0-9/+=]{40}['\"]\n\n# GitHub\ngh[pousr]_[A-Za-z0-9]{36}\ngithub_token\\s*[:=]\\s*['\"][A-Za-z0-9]{40}['\"]\n\n# Google\nAIza[0-9A-Za-z\\-_]{35}\nya29\\.[0-9A-Za-z\\-_]+\n\n# Slack\nxox[baprs]-[0-9A-Za-z-]+\n\n# Stripe\nsk_live_[0-9a-zA-Z]{24}\nrk_live_[0-9a-zA-Z]{24}\n\n# Generic\n(api[_-]?key|secret|token|password|passwd|pwd)\\s*[:=]\\s*['\"][^\\s'\"]{12,}['\"]\n-----BEGIN (RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----"},{"language":"text","snippet":"(mongodb|postgresql|postgres|mysql|redis)://[^\\s'\"]*:[^\\s'\"]*@"},{"language":"javascript","snippet":"// CRITICAL: SQL Injection - user input directly in query\napp.get('/users', (req, res) => {\n    db.query(\"SELECT * FROM users WHERE name = '\" + req.query.name + \"'\");\n});\n\n// CRITICAL: Command Injection\nconst { exec } = require('child_process');\nexec(`ls ${req.query.dir}`, (err, stdout) => { ... });\n\n// CRITICAL: Hardcoded production database credentials\nconst DB_PASSWORD = \"prod_db_p@ssw0rd_2024\";"},{"language":"python","snippet":"# HIGH: Sensitive data logged\nlogger.info(f\"User login attempt: email={user.email}, password={password}\")\n\n# HIGH: Missing auth on admin endpoint\n@app.route('/admin/users/delete', methods=['POST'])\ndef delete_user():\n    User.query.filter_by(id=request.json['id']).delete()\n    db.session.commit()\n\n# HIGH: XSS via dangerouslySetInnerHTML\n<div dangerouslySetInnerHTML={{ __html: userProvidedContent }} />"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\r\nname: code-reviewer\r\ndescription: \"本技能从 6 个维度对代码进行全面审核：安全性、性能、代码质量、错误处理、测试和文档。适用于审核代码变更、Pull Request 或整个代码库（支持所有主流编程语言）。触发词包括：「帮我 review 这段代码」「检查安全问题」「审查这个 PR」「找出代码中的 Bug」，或用户请求代码质量分析时使用。技能内置自动化分析脚本、安全规则库、各语言最佳实践文档，并可生成可视化 HTML 审核报告。\"\r\n---\r\n\r\n# 代码审核助手（Code Reviewer）\r\n\r\n## 概述\r\n\r\n通过自动化静态分析与 AI 上下文推理相结合的方式，对代码进行全面、多维度的审核。覆盖六大审核维度，支持所有主流编程语言，输出带严重性分级的可执行问题列表和可视化 HTML 报告。\r\n\r\n## 适用场景\r\n\r\n- 审核 Pull Request 或代码变更（diff）\r\n- 对现有代码库进行安全或质量审计\r\n- 合并前代码质量检查（Pre-merge gate）\r\n- 对不熟悉的代码进行入门级审核\r\n- 安全漏洞评估\r\n- 性能瓶颈定位\r\n\r\n## 审核工作流\r\n\r\n每次代码审核均遵循以下 4 阶段工作流，各阶段依次递进。\r\n\r\n### 第一阶段：确定范围与计划\r\n\r\n确定审核对象和方式：\r\n\r\n1. 确认审核范围：单文件、目录、git diff 还是 PR。若用户提供 git diff 或 PR，仅审核变更行及其上下文；若审核整个代码库，询问用户目标目录。\r\n2. 根据文件扩展名检测编程语言，参考 `references/best-practices.md` 中各语言专属规则。\r\n3. 确定审核深度：快速扫描（仅关注严重/高危）或全面审核（覆盖所有严重级别）。默认执行全面审核，除非用户明确要求快速扫描。\r\n4. 检查自动化分析脚本是否可用。如果 Python 可用，优先使用脚本进行确定性分析。\r\n\r\n### 第二阶段：自动化分析\r\n\r\n在进行上下文推理之前，运行内置脚本获取确定性的基线问题。\r\n\r\n**步骤 1：复杂度分析**\r\n\r\n对目标代码运行复杂度分析器：\r\n\r\n```bash\r\npython scripts/analyze_complexity.py <目标路径> --format json\r\n```\r\n\r\n检测内容：过长函数（>50 行）、高圈复杂度（>10）、深层嵌套（>4 层）、参数过多（>5 个）。结果以 JSON 格式输出。\r\n\r\n**步骤 2：模式扫描**\r\n\r\n运行模式扫描器检测安全漏洞和代码质量问题：\r\n\r\n```bash\r\npython scripts/scan_patterns.py <目标路径> --format json\r\n```\r\n\r\n检测内容：SQL 注入、命令注入、硬编码密钥、eval 使用、弱哈希算法、XSS、空 catch 块、TODO/FIXME 标记，以及 20+ 其他反模式。结果以 JSON 格式输出。\r\n\r\n**步骤 3：合并结果**\r\n\r\n将两个脚本的 JSON 输出合并为一个问题列表，按（文件、行号、类型）去重。\r\n\r\n若 Python 不可用，跳过本阶段直接进入第三阶段，对照 `references/security-rules.md` 和 `references/checklist.md` 手动检查代码中的等价问题。\r\n\r\n### 第三阶段：上下文审核\r\n\r\n阅读代码并进行自动化工具无法完成的上下文推理，这是审核的核心价值所在。\r\n\r\n按需加载以下参考文档：\r\n- `references/checklist.md` — 6 维度全面检查清单\r\n- `references/security-rules.md` — OWASP Top 10、各语言安全模式、密钥检测正则\r\n- `references/best-practices.md` — 各语言惯用写法与反模式\r\n- `references/severity-guide.md` — 严重性分级标准与示例\r\n\r\n对第二阶段的每个问题进行确认或排除误报，然后检查模式匹配无法发现的问题：\r\n\r\n**安全性（参考 `references/security-rules.md`）：**\r\n- 业务逻辑漏洞（如订单中的负数数量、转账中的竞态条件）\r\n- 特定业务操作缺少授权检查\r\n- 不安全的数据流（source → sink 分析）\r\n- 信任边界违规\r\n\r\n**性能（参考 `references/checklist.md` 第 2 节）：**\r\n- 算法效率问题（错误的数据结构、不必要的计算）\r\n- 资源泄漏（未关闭的连接、孤立的事件监听器）\r\n- 可扩展性隐患（无限增长、锁竞争）\r\n\r\n**代码质量（参考 `references/best-practices.md`）：**\r\n- SOLID 原则违反\r\n- 设计模式误用或缺失\r\n- 命名清晰度与一致性\r\n- 抽象层级是否适当\r\n\r\n**错误处理（参考 `references/checklist.md` 第 4 节）：**\r\n- 关键业务流程中未处理的错误路径\r\n- 泄露内部状态的错误消息\r\n- 瞬态错误缺少重试/降级机制\r\n- 错误传播不当（被吞噬、重新包装或丢失上下文）\r\n\r\n**测试（参考 `references/checklist.md` 第 5 节）：**\r\n- 核心业务逻辑缺少测试\r\n- 边界情况和错误路径未被测试覆盖\r\n- 测试隔离问题（共享状态、顺序依赖）\r\n- Mock 质量（过度 Mock 或 Mock 不足）\r\n\r\n**文档（参考 `references/checklist.md` 第 6 节）：**\r\n- 公共接口缺少 API 文档\r\n- 注释与代码不符（过时注释）\r\n- 非显而易见的设计决策缺少架构决策记录\r\n\r\n### 第四阶段：报告与建议\r\n\r\n生成最终审核输出。\r\n\r\n**步骤 1：对所有问题进行分级**（参考 `references/severity-guide.md`）：\r\n- 严重（Critical）：远程代码执行、SQL 注入、绕过认证、硬编码生产环境密钥\r\n- 高危（High）：数据泄露、XSS、缺少鉴权、反序列化漏洞\r\n- 中危（Medium）：弱加密、N+1 查询、高复杂度、空 catch 块\r\n- 低危（Low）：死代码、命名问题、魔法数字、调试打印语句\r\n- 提示（Info）：建议、替代方案、正向反馈\r\n\r\n**步骤 2：生成 HTML 报告**（可选，当用户需要可视化报告时）：\r\n\r\n```bash\r\n# 双语报告，带切换按钮（默认）\r\npython scripts/generate_report.py <findings.json> --project \"<项目名称>\" --output review-report.html\r\n\r\n# 仅中文\r\npython scripts/generate_report.py <findings.json> --lang zh --output review-report.html\r\n\r\n# "},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn77qvnxzvd6mty516h2m09kan891gd9\",\n  \"slug\": \"code-reviewer\",\n  \"version\": \"1.0.1\",\n  \"publishedAt\": 1781962873597\n}"},{"path":"references/best-practices.md","content":"# Language-Specific Best Practices\n\n## JavaScript / TypeScript\n\n### Modern Syntax\n- Use `const` by default, `let` when reassignment needed, never `var`\n- Use arrow functions for callbacks and short functions; use `function` for methods and constructors\n- Use template literals over string concatenation\n- Use destructuring for object/array extraction\n- Use spread operator instead of `Object.assign` for immutability\n- Use optional chaining (`?.`) and nullish coalescing (`??`) instead of manual checks\n\n### TypeScript Specific\n- Enable `strict: true` in tsconfig.json\n- Avoid `any` type - use `unknown` when type is truly unknown, then narrow\n- Use `interface` for object shapes, `type` for unions and intersections\n- Use `enum` or union types for fixed value sets\n- Prefer `readonly` for immutable properties\n- Use generics for reusable components/functions\n- Enable `noUncheckedIndexedAccess` for safer array/object access\n\n### Async Patterns\n- Use `async/await` over `.then()` chains for readability\n- Always handle promise rejections (try/catch or .catch())\n- Use `Promise.all()` for parallel operations, not sequential awaits\n- Avoid fire-and-forget async calls (always await or handle)\n- Use `AbortController` for cancellable fetch requests\n\n### Node.js\n- Use `path.join()` / `path.resolve()` instead of string concatenation for paths\n- Use `fs.promises` (async) over `fs` (sync) in server code\n- Validate input with Zod / Joi / express-validator at API boundaries\n- Use `crypto.randomUUID()` for ID generation, not `Math.random()`\n- Set `helmet()` middleware for security headers\n- Use `express-rate-limit` for API rate limiting\n\n### Common Anti-Patterns\n- Mutating function arguments\n- Comparing with `==` instead of `===`\n- Using `forEach` when `map`/`filter`/`reduce` is intended\n- Async function without await inside (missing `await` keyword)\n- `any` type in TypeScript (loss of type safety)\n- Empty catch blocks (`catch (e) {}`)\n\n---\n\n## Python\n\n### Modern Syntax (3.9+)\n- Use type hints on all function signatures (`def foo(x: int) -> str:`)\n- Use `from __future__ import annotations` for forward references\n- Use f-strings for string formatting (not `%` or `.format()`)\n- Use `pathlib.Path` instead of `os.path` for path manipulation\n- Use dataclasses or Pydantic for data containers\n- Use `match` statement for complex pattern matching (3.10+)\n- Use `walrus operator` (`:=`) for assignment expressions where it improves readability\n\n### Error Handling\n- Catch specific exceptions, not bare `except:` or `except Exception:`\n- Use context managers (`with` statements) for resource management\n- Raise exceptions with meaningful messages and proper exception types\n- Use custom exception hierarchies for application-specific errors\n- Never use `except: pass` - at minimum log the error\n\n### Security\n- Use `secrets` module for tokens/passwords, not `random`\n- Use `bcrypt` or `argon2-cffi` for password hashing\n- Use parameterized queries with `psycopg2` / `SQLAlchemy` (never string conc"},{"path":"references/checklist.md","content":"# Code Review Checklist\n\n## 1. Security\n\n### Injection Attacks\n- [ ] SQL queries use parameterized statements / prepared statements (no string concatenation)\n- [ ] No OS command execution with user input (`os.system`, `exec`, `Runtime.exec`, `child_process.exec`)\n- [ ] Template engines use auto-escaping (no `dangerouslySetInnerHTML`, `{!! !!}`, `innerHTML` with user data)\n- [ ] No eval on user input (`eval()`, `Function()`, `new Function()`)\n\n### Authentication & Authorization\n- [ ] Passwords hashed with bcrypt/scrypt/argon2 (not MD5/SHA1/plaintext)\n- [ ] JWT tokens validated for signature, expiry, and issuer\n- [ ] Authorization checks present on every protected route/endpoint\n- [ ] No hardcoded credentials, API keys, or tokens in source code\n- [ ] Secrets loaded from environment variables or secret managers\n\n### Data Exposure\n- [ ] Sensitive data not logged (passwords, tokens, PII, credit card numbers)\n- [ ] API responses do not leak internal field names or stack traces\n- [ ] HTTPS enforced; no mixed content\n- [ ] CORS configured restrictively (no `Access-Control-Allow-Origin: *` on sensitive endpoints)\n\n### File Operations\n- [ ] File paths validated against traversal attacks (no `../` in user-controlled paths)\n- [ ] Upload restrictions: file type, size, and content validation\n- [ ] Download paths restricted to allowed directories\n\n### Dependencies\n- [ ] No known vulnerable dependencies (checked via `npm audit` / `pip audit` / `snyk`)\n- [ ] Dependency versions pinned (no floating `*` or `latest`)\n\n---\n\n## 2. Performance\n\n### Database\n- [ ] No N+1 query patterns (queries inside loops)\n- [ ] Database indexes exist for frequently queried columns\n- [ ] Pagination applied to list endpoints (no unbounded `SELECT *`)\n- [ ] ORM queries select only needed columns (no `SELECT *` when only 2 fields used)\n\n### Algorithms & Data Structures\n- [ ] No O(n^2) or worse inside hot paths / loops\n- [ ] Appropriate data structures used (Set for lookups instead of Array.includes)\n- [ ] No unnecessary re-computation of the same value inside loops\n\n### Memory\n- [ ] No memory leaks (event listeners removed, intervals cleared, connections closed)\n- [ ] Large collections streamed rather than loaded entirely into memory\n- [ ] No unnecessary object retention in long-lived scopes (closures, globals, singletons)\n\n### Concurrency\n- [ ] Async operations not blocking the event loop (no sync I/O in async contexts)\n- [ ] Database connections released properly (try/finally or using context managers)\n- [ ] Race conditions addressed (proper locking / atomic operations)\n\n---\n\n## 3. Code Quality\n\n### Readability\n- [ ] Variable/function names are descriptive and self-documenting\n- [ ] Functions do one thing (Single Responsibility)\n- [ ] No dead code (unused variables, functions, imports, unreachable code)\n- [ ] No magic numbers / strings (use named constants)\n- [ ] Consistent naming convention (camelCase / snake_case per language convention)\n\n### Complexity\n- [ ] Functions under 50 lines"},{"path":"references/security-rules.md","content":"# Security Vulnerability Detection Rules\n\n## OWASP Top 10 Quick Reference\n\n### A01 - Broken Access Control\n| Pattern | Indicators | Languages |\n|---------|-----------|-----------|\n| Missing auth check | Route handler without auth middleware | All |\n| IDOR | Direct object reference from user input without ownership check | All |\n| Privilege escalation | Role check missing before sensitive operation | All |\n| Force browsing | No authorization on API endpoints | All |\n\n**Detection patterns:**\n- Route definitions without `auth` / `requireAuth` / `@login_required` / `@Authorized`\n- `req.params.id` / `request.getParameter(\"id\")` used directly in DB query without ownership validation\n- `isAdmin` check only on frontend, not backend\n\n### A02 - Cryptographic Failures\n| Pattern | Indicators | Languages |\n|---------|-----------|-----------|\n| Weak hashing | MD5, SHA1 used for passwords | All |\n| Hardcoded secrets | API keys in source code | All |\n| No encryption | Sensitive data stored/transmitted in plaintext | All |\n| Weak randomness | `Math.random()` / `random.random()` for security tokens | All |\n\n**Detection patterns (regex):**\n```\n# Hardcoded API keys\n(api[_-]?key|secret|token|password)\\s*[:=]\\s*['\"][A-Za-z0-9]{16,}['\"]\n\n# Weak hash algorithms\n\\b(MD5|SHA1|md5|sha1)\\b.*password\n\n# Insecure random\n\\b(Math\\.random|random\\.random)\\(\\).*token|session|password|key\n```\n\n### A03 - Injection\n| Pattern | Indicators | Languages |\n|---------|-----------|-----------|\n| SQL Injection | String concatenation in SQL queries | All |\n| Command Injection | User input in shell commands | All |\n| LDAP Injection | String concat in LDAP queries | All |\n| Template Injection | User input in template engine | All |\n\n**Detection patterns:**\n```\n# SQL injection\n(SELECT|INSERT|UPDATE|DELETE|DROP).*\\+.*\\$_(GET|POST|REQUEST)\nquery\\s*\\+\\s*['\"].*['\"]\\s*\\+\nexecute\\s*\\(\\s*['\"].*\\{.*\\}.*['\"]\\s*\\)\n\n# Command injection\n(os\\.system|subprocess\\.call|exec|child_process\\.exec)\\s*\\(.*\\+.*(input|req|param)\n```\n\n### A04 - Insecure Design\n- Missing rate limiting on authentication endpoints\n- No account lockout after failed login attempts\n- Predictable URL patterns for sensitive resources\n- Missing input validation (length, type, format, range)\n\n### A05 - Security Misconfiguration\n- Debug mode enabled in production (`DEBUG=True`)\n- Detailed error pages in production (stack traces exposed)\n- Default credentials not changed\n- Unnecessary features enabled (directory listing, HTTP methods)\n\n### A07 - Identification & Authentication Failures\n- Weak password policy (no minimum length, complexity)\n- Session ID in URL parameters\n- Session fixation (session not regenerated after login)\n- No session timeout\n\n### A08 - Software & Data Integrity Failures\n- Unsigned software updates\n- Deserialization of untrusted data (`pickle.loads`, `yaml.load` without SafeLoader)\n- Dependencies from untrusted sources\n\n### A09 - Logging & Monitoring Failures\n- Security events not logged (login, logout, password change, privile"}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":"本技能从 6 个维度对代码进行全面审核：安全性、性能、代码质量、错误处理、测试和文档。适用于审核代码变更、Pull Request 或整个代码库（支持所有主流编程语言）。触发词包括：「帮我 review 这段代码」「检查安全问题」「审查这个 PR」「找出代码中的 Bug」，或用户请求代码质量分析时使用。技能内置自... Skill: Code Reviewer Owner: nameused Summary: 本技能从 6 个维度对代码进行全面审核：安全性、性能、代码质量、错误处理、测试和文档。适用于审核代码变更、Pull Request 或整个代码库（支持所有主流编程语言）。触发词包括：「帮我 review 这段代码」「检查安全问题」「审查这个 PR」「找出代码中的 Bug」，或用户请求代码质量分析时使用。技能内置自... Tags: latest:1.0.1 Version history: v1.0.1 | 2026-06-20T13:41:13.597Z | user - Refactored all documentation and instructions from English to Chinese for improved localization. - Updated descriptions, workflows, re","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":758,"uniquenessScore":65,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-10T21:52:39.587Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-10T21:52:39.587Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-11T00:31:36.971Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}