analyze-code

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Code Analysis (Zoom In)

代码分析(深度剖析)

Perform a code-level quality analysis of this project. Follow the procedural workflow below; use the rubric sections as reference when interpreting findings.
对该项目进行代码级质量分析。遵循以下流程步骤;解读结果时参考评分标准部分。

Ground Rules

基本原则

  • Assessment only: no code changes, pushes, workflow/release triggers
  • No side effects: no installs/config edits/machine mutation; no paid API calls (mock or skip); dry-run or mock anything that publishes/deploys; verify commands exist and are spelled correctly, not their effect
  • Reproduce before reporting: every finding needs repro or concrete trace, a file:line reference, and a concrete fix
  • Probe validation gaps: construct an invalid state locally, check tooling/CI catches it
  • 仅评估:不修改代码、不推送代码、不触发工作流/发布流程
  • 无副作用:不安装/配置编辑/修改机器;不调用付费API(模拟或跳过);对任何发布/部署操作进行试运行或模拟;仅验证命令是否存在及拼写正确,不验证其执行效果
  • 先复现再报告:每个问题都需要复现步骤或具体追踪信息、文件:行号引用,以及具体的修复方案
  • 探查验证漏洞:在本地构造无效状态,检查工具/CI是否能检测到

Repo Shape

仓库类型

Emphasize different risk categories depending on what the repo is:
ShapeEmphasize
App/serviceauthZ per route (ownership on account-scoped routes), auth token lifecycle (expiry/single-use/timing/enumeration), quota races, SSRF in fetchers/ingestion, prompt injection from untrusted content reaching an LLM, SQLi, CORS/rate limits
CI library/actionsscript injection (untrusted context in
run:
), SHA pinning, egress, permission ceilings — a bad action ships unsafe CI to every consumer
Content/docs siteXSS (
set:html
/
innerHTML
, export paths), command validity in guides, currency of claims, link rot
Package index/tapartifact checksum re-verification vs upstream, update-automation payload trust (dispatch payload -> file rewrite = RCE surface), version freshness
根据仓库类型侧重不同风险类别:
类型侧重方向
应用/服务路由级授权(账户范围路由的权限归属)、授权令牌生命周期(过期/单次使用/时序/枚举)、配额竞争、获取器/摄入环节的SSRF、不可信内容传入LLM导致的提示注入、SQL注入、CORS/速率限制
CI库/动作脚本注入(
run:
中的不可信上下文)、SHA固定、出口控制、权限上限——有问题的动作会将不安全的CI推送给所有使用者
内容/文档站点XSS(
set:html
/
innerHTML
、导出路径)、指南中的命令有效性、声明时效性、链接失效
包索引/源工件校验和与上游重新验证、更新自动化负载信任(调度负载→文件重写=远程代码执行面)、版本新鲜度

Usage

使用方法

When asked to analyze code quality:
当被要求分析代码质量时:

1. Static analysis

1. 静态分析

Run project-appropriate static checks (skip tools not present in the repo):
bash
uv run lintro chk          # Python/JS/TS/YAML/etc. when lintro is configured
bunx tsc --noEmit          # TypeScript projects with tsconfig
cargo clippy -- -D warnings  # Rust projects
semgrep --config=auto .    # Security/quality patterns (install if missing)
Record every finding with file path and line number.
运行适合项目的静态检查(跳过仓库中未配置的工具):
bash
uv run lintro chk          # Python/JS/TS/YAML/etc. when lintro is configured
bunx tsc --noEmit          # TypeScript projects with tsconfig
cargo clippy -- -D warnings  # Rust projects
semgrep --config=auto .    # Security/quality patterns (install if missing)
记录每个问题的文件路径和行号。

2. Security scan

2. 安全扫描

Search for common vulnerability patterns:
bash
undefined
搜索常见漏洞模式:
bash
undefined

Hardcoded secrets (adjust paths as needed)

Hardcoded secrets (adjust paths as needed)

rg -n '(api[_-]?key|secret|password|token)\s*=\s*["\x27][^"\x27]+["\x27]' --glob '!*.{lock,sum}'
rg -n '(api[_-]?key|secret|password|token)\s*=\s*["\x27][^"\x27]+["\x27]' --glob '!*.{lock,sum}'

Dangerous subprocess usage

Dangerous subprocess usage

rg -n 'shell\s*=\s*True' --type py
rg -n 'shell\s*=\s*True' --type py

SQL injection risk (string interpolation in queries)

SQL injection risk (string interpolation in queries)

rg -n '(execute|query)\s*(\sf["\x27]|.format\s(' --type py
rg -n '(execute|query)\s*(\sf["\x27]|.format\s(' --type py

Dependency vulnerabilities

Dependency vulnerabilities

uv run pip-audit # Python with uv (pip-audit in dev deps) bun audit # JavaScript/TypeScript with bun

Cross-check results against the Security Best Practices rubric below.
uv run pip-audit # Python with uv (pip-audit in dev deps) bun audit # JavaScript/TypeScript with bun

对照下方的安全最佳实践评分标准交叉检查结果。

3. Workflow & supply-chain security

3. 工作流与供应链安全

Search for CI/CD and supply-chain risk patterns:
bash
undefined
搜索CI/CD和供应链风险模式:
bash
undefined

Untrusted GitHub context interpolated directly into a run: block

Untrusted GitHub context interpolated directly into a run: block

rg -n '${{\s*github.(event|head_ref)' .github/workflows/ .github/actions/ action.yml action.yaml
rg -n '${{\s*github.(event|head_ref)' .github/workflows/ .github/actions/ action.yml action.yaml

pull_request_target usage (runs with write-scoped secrets against untrusted code)

pull_request_target usage (runs with write-scoped secrets against untrusted code)

rg -n 'pull_request_target' .github/workflows/ .github/actions/ action.yml action.yaml
rg -n 'pull_request_target' .github/workflows/ .github/actions/ action.yml action.yaml

Actions pinned to a tag/branch instead of a commit SHA

Actions pinned to a tag/branch instead of a commit SHA

rg -n -P 'uses:\s*[^@]+@(?![0-9a-fA-F]{40}\b)' .github/workflows/ .github/actions/ action.yml action.yaml
rg -n -P 'uses:\s*[^@]+@(?![0-9a-fA-F]{40}\b)' .github/workflows/ .github/actions/ action.yml action.yaml

Write-scoped token permissions

Write-scoped token permissions

rg -n 'permissions:' -A 3 .github/workflows/ .github/actions/ action.yml action.yaml

Prose checks (no single command catches these — inspect manually): injection via PR
titles/branches/bodies flowing into a shell step, cache poisoning between workflow
runs, and whether release automation can be triggered from a non-release commit or
by an untrusted actor.
rg -n 'permissions:' -A 3 .github/workflows/ .github/actions/ action.yml action.yaml

散文式检查(无单一命令可检测——需手动检查):PR标题/分支/正文注入到shell步骤、工作流运行之间的缓存中毒,以及发布自动化是否可从非发布提交或由不可信角色触发。

4. Code smell detection

4. 代码坏味道检测

Use ripgrep and manual inspection for structural issues:
bash
undefined
使用ripgrep和手动检查结构问题:
bash
undefined

Long functions (heuristic: functions with many lines — inspect top hits)

Long functions (heuristic: functions with many lines — inspect top hits)

rg -n -U '^\s*(@\w+.\n\s)(async\s+)?def\s+\w+' -t py rg -n '^\s(pub(([^)]))?\s+)?(async\s+)?(unsafe\s+)?(const\s+)?fn\s+\w+' -t rust rg -n '^\s(export\s+)?(default\s+)?(async\s+)?function\s+\w+' -t ts -t js rg -n '^\s*(export\s+)?(const|let|var)\s+\w+\s*=\s*(async\s+)?(' -t ts -t js
rg -n -U '^\s*(@\w+.\n\s)(async\s+)?def\s+\w+' -t py rg -n '^\s(pub(([^)]))?\s+)?(async\s+)?(unsafe\s+)?(const\s+)?fn\s+\w+' -t rust rg -n '^\s(export\s+)?(default\s+)?(async\s+)?function\s+\w+' -t ts -t js rg -n '^\s*(export\s+)?(const|let|var)\s+\w+\s*=\s*(async\s+)?(' -t ts -t js

Dead code / unused imports (lint tools often catch these; supplement with:)

Dead code / unused imports (lint tools often catch these; supplement with:)

rg -n '# (noqa|type: ignore|allow dead_code)' # existing suppressions worth reviewing rg -n 'TODO|FIXME|HACK|XXX' # deferred cleanup
rg -n '# (noqa|type: ignore|allow dead_code)' # existing suppressions worth reviewing rg -n 'TODO|FIXME|HACK|XXX' # deferred cleanup

Cross-file duplication (same pattern in 3+ files with minor variations)

Cross-file duplication (same pattern in 3+ files with minor variations)

bunx jscpd --min-tokens 50 . # or replace
.
with the repo's actual source roots

Evaluate hits against the Code Smells rubric (long methods, dead code, duplication,
magic numbers, etc.). Duplication findings must name the files involved, the shared
pattern, and a suggested extraction point.
bunx jscpd --min-tokens 50 . # or replace
.
with the repo's actual source roots

对照代码坏味道评分标准评估结果(长方法、死代码、重复代码、魔法数字等)。重复代码问题必须指出涉及的文件、共享模式,以及建议的提取点。

5. Rate and report findings

5. 评级并报告结果

Lead with a TLDR verdict (one or two sentences: is this codebase in good shape, needs attention, or has critical issues).
For each issue, assign severity:
  • Critical — security vulnerabilities, data loss risk, broken auth, exploitable injection
  • Should Fix — bugs, missing error handling, significant smells, vulnerable dependencies
  • Nice to Have — style, minor duplication, documentation gaps
Include file paths, line numbers, concrete repro/trace evidence, and a concrete fix suggestion for each finding. End with a prioritized fix list ordered by impact. When this analysis runs as part of a full audit alongside
analyze-project
, merge into that skill's single fix list instead of reporting a separate one.
Cadence: run codebase-wide every ~20 PRs or monthly; prioritize cross-file duplication, then idiom upgrades, then style polish; file findings via the
issue
skill.

先给出TLDR结论(一两句话:代码库状态良好、需要关注,还是存在严重问题)。
为每个问题分配严重程度:
  • 严重 — 安全漏洞、数据丢失风险、认证失效、可利用的注入漏洞
  • 应修复 — 错误、缺失的错误处理、严重的代码坏味道、有漏洞的依赖
  • 建议优化 — 风格问题、轻微重复代码、文档缺口
每个问题需包含文件路径、行号、具体的复现/追踪证据,以及具体的修复建议。最后给出按影响优先级排序的修复列表。当此分析作为完整审计的一部分与
analyze-project
一起运行时,合并到该技能的单一修复列表中,而非单独报告。
频率:每约20个PR或每月进行一次全代码库分析;优先处理跨文件重复代码,然后是语法升级,最后是风格优化;通过
issue
技能提交问题。

Reference — Implementation Quality

参考 — 实现质量

  • Best practices adherence for the language/framework used
  • Scalability and performance considerations
  • Error handling—are failures handled gracefully and consistently?
  • Resource management—are connections, file handles, streams properly closed?
  • Concurrency/async correctness—race conditions, deadlocks, proper cleanup
  • Type safety—is the type system leveraged well or worked around with
    any
    /casts?
  • Dependency health—outdated, redundant, or vulnerable dependencies
  • Hand-rolled utilities that duplicate existing stdlib/crate/package functionality
  • Logging/observability—can issues be diagnosed in production?
  • 遵循所用语言/框架的最佳实践
  • 可扩展性和性能考量
  • 错误处理——故障是否被优雅且一致地处理?
  • 资源管理——连接、文件句柄、流是否被正确关闭?
  • 并发/异步正确性——竞态条件、死锁、正确的清理
  • 类型安全——是否充分利用类型系统,还是用
    any
    /类型转换规避?
  • 依赖健康——过时、冗余或有漏洞的依赖
  • 手动实现的工具重复了现有标准库/ crate/包的功能
  • 日志/可观测性——生产环境中能否诊断问题?

Reference — Code Smells

参考 — 代码坏味道

  • Long methods/functions that do too much
  • God classes or modules with too many responsibilities
  • Feature envy—code that uses another module's data more than its own
  • Primitive obsession—overuse of primitives instead of domain types
  • Shotgun surgery—a single change requiring edits across many files
  • Dead code, unreachable branches, or unused imports/variables
  • Deeply nested conditionals or callbacks
  • Magic numbers and hardcoded strings that should be constants
  • Duplicated logic that violates DRY
  • Inappropriate intimacy—modules tightly coupled to each other's internals
  • 过长的方法/函数,职责过多
  • 上帝类或模块,承担过多职责
  • 特性羡慕——代码使用其他模块的数据多于自身模块
  • 原始类型痴迷——过度使用原始类型而非领域类型
  • 霰弹式修改——单个变更需要编辑多个文件
  • 死代码、不可达分支、未使用的导入/变量
  • 深度嵌套的条件判断或回调
  • 魔法数字和应设为常量的硬编码字符串
  • 违反DRY原则的重复逻辑
  • 不当亲密——模块之间过度耦合内部实现

LLM-Typical Idiomatic Smells

LLM典型的非惯用坏味道

Code that compiles and passes linters but uses generic cross-language patterns instead of the target language's constructs:
  • Manual loops where built-ins exist (
    any()
    ,
    all()
    ,
    .find()
    ,
    .get()
    ,
    .collect()
    )
  • Defensive flag-and-break variables instead of expression-based flow
  • Over-cloning or owned
    String
    parameters to dodge borrow reasoning (Rust)
  • os.path
    mixed with
    pathlib
    in one codebase (Python)
  • Hand-rolled utilities duplicating stdlib/ecosystem solutions
  • Copy-pasted logic across 3+ files that should be a shared helper
  • Nested if/else unwrapping where dedicated syntax exists (
    let-else
    ,
    ?
    ,
    .ok_or()
    )
When filing idiom findings, name the preferred replacement directly — language-standard skills cover general style but not every smell above. Examples:
  • Manual loop →
    any()
    /
    all()
    (Python),
    .find()
    /
    .some()
    (JS/TS), iterator chains with
    .collect()
    (Rust)
  • os.path
    vs
    pathlib
    → standardize on
    pathlib.Path
    (Python)
  • Nested unwrap chains →
    let-else
    ,
    ?
    ,
    .ok_or()
    (Rust)
  • Defensive flag-and-break → early return or expression-based flow
  • Over-cloning → prefer
    &str
    / borrows over owned
    String
    parameters (Rust)
  • Hand-rolled utility → name the stdlib module or ecosystem crate/function to use
  • Copy-pasted logic → name the shared module or helper to extract into (see duplication section above)
For general language style, see
stand-py
,
stand-rust
, and
stand-ts
.
代码可编译且通过检查,但使用通用跨语言模式而非目标语言的构造:
  • 已有内置函数却手动实现循环(
    any()
    all()
    .find()
    .get()
    .collect()
  • 使用防御性标志和break变量而非基于表达式的流程
  • 过度克隆或使用所有权
    String
    参数以规避借用逻辑(Rust)
  • 同一代码库中混合使用
    os.path
    pathlib
    (Python)
  • 手动实现的工具重复了标准库/生态系统解决方案
  • 3个以上文件中复制粘贴的逻辑应改为共享助手
  • 嵌套的if/else解包,而存在专用语法(
    let-else
    ?
    .ok_or()
提交语法问题时,直接指明首选的替代方案——语言标准技能涵盖通用风格,但不包括上述所有坏味道。示例:
  • 手动循环 →
    any()
    /
    all()
    (Python)、
    .find()
    /
    .some()
    (JS/TS)、带
    .collect()
    的迭代器链(Rust)
  • os.path
    vs
    pathlib
    → 统一使用
    pathlib.Path
    (Python)
  • 嵌套解包链 →
    let-else
    ?
    .ok_or()
    (Rust)
  • 防御性标志和break → 提前返回或基于表达式的流程
  • 过度克隆 → 优先使用
    &str
    / 借用而非所有权
    String
    参数(Rust)
  • 手动实现的工具 → 指定要使用的标准库模块或生态系统crate/函数
  • 复制粘贴的逻辑 → 指定要提取到的共享模块或助手(见上方重复代码部分)
通用语言风格,请参考
stand-py
stand-rust
stand-ts

Reference — Security Best Practices

参考 — 安全最佳实践

  • OWASP Top 10 exposure: injection (SQL, command, XSS), broken auth, SSRF, etc.
  • Secrets management—no hardcoded credentials, tokens, or API keys in source
  • Input validation and sanitization at system boundaries
  • Proper use of cryptography—no weak algorithms, correct key/IV handling
  • Dependency vulnerabilities—known CVEs in direct or transitive dependencies
  • Least privilege—are permissions, scopes, and roles appropriately scoped?
  • Secure defaults—are features opt-in safe (e.g., CORS, CSP, cookie flags)?
  • Sensitive data handling—PII/secrets not leaked in logs, errors, or responses
  • OWASP Top 10风险暴露:注入(SQL、命令、XSS)、认证失效、SSRF等
  • 密钥管理——源代码中无硬编码凭据、令牌或API密钥
  • 系统边界处的输入验证和清理
  • 加密的正确使用——无弱算法、正确处理密钥/IV
  • 依赖漏洞——直接或传递依赖中的已知CVE
  • 最小权限原则——权限、范围和角色是否适当限定?
  • 安全默认值——功能是否默认安全(如CORS、CSP、Cookie标志)?
  • 敏感数据处理——PII/密钥不会泄露到日志、错误或响应中

Reference — Testing (code-level)

参考 — 测试(代码级)

  • Test quality—flag any "nothing burger" tests that don't meaningfully validate behavior
  • Use of parameterization where appropriate
  • Coverage of edge cases and failure modes
  • Are tests isolated and deterministic?
  • Do tests cover the right layer (unit vs integration vs e2e)?
For deeper test-suite analysis, use the
analyze-tests
skill.
  • 测试质量——标记任何未有效验证行为的“无效”测试
  • 适当使用参数化
  • 边缘情况和故障模式的覆盖
  • 测试是否隔离且具有确定性?
  • 测试是否覆盖了正确的层级(单元测试vs集成测试vs端到端测试)?
如需更深入的测试套件分析,请使用
analyze-tests
技能。