code-overhaul-review

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Code Overhaul Review

代码全面审查

Audit this codebase for maintenance, modernization, and overhaul. For every issue, state concrete tradeoffs, lead with an opinionated recommendation, and ask for input before assuming direction.
Health check, not feature review. Goal: identify highest-leverage changes for reliability, performance, maintainability, and dev velocity — then execute in disciplined order.
Stack detection: At the start of Step 0, scan the repo for language markers (*.swift/Xcode projects, go.mod, package.json/tsconfig). For each stack detected, apply the matching addendum from the Language-Specific Addendums section below IN ADDITION to the generic section. For monorepos, apply multiple addendums and note which findings apply to which module/package.
对该代码库进行维护、现代化改造及全面审计。针对每个问题,说明具体的权衡取舍,先给出明确的建议,在确定方向前征求用户意见。
本次是健康检查,而非功能评审。目标:识别对可靠性、性能、可维护性及开发效率影响最大的变更,然后按规范顺序执行。
技术栈检测: 在步骤0开始时,扫描代码库中的语言标记(*.swift/Xcode项目、go.mod、package.json/tsconfig)。对于检测到的每个技术栈,除通用规则外,还需应用下方「特定语言补充规则」中的对应内容。对于单仓项目,需应用多个补充规则,并注明哪些发现适用于哪个模块/包。

Priority hierarchy

优先级层级

Context low? Step 0 > Impact/effort matrix > Test diagram > Recommendations > Rest. Never skip Step 0 or the matrix.
上下文信息不足?优先执行:步骤0 > 影响/投入矩阵 > 测试流程图 > 建议 > 其他内容。切勿跳过步骤0或矩阵分析。

Engineering preferences

工程偏好

  • DRY — flag repetition aggressively.
  • Well-tested non-negotiable; too many > too few.
  • "Engineered enough" — not fragile, not over-abstracted.
  • More edge cases, not fewer; thoughtfulness > speed.
  • Explicit over clever.
  • Minimal diff: fewest new abstractions and files touched.
  • Performance is a feature. Profile before and after.
  • Prefer platform/stdlib over third-party when feasible.
  • Deprecation warnings are bugs. Fix proactively.
  • Build time matters. Justify anything that slows it.
  • DRY原则——严格标记重复代码。
  • 充分测试是硬性要求;宁多勿少。
  • 「足够工程化」——既不脆弱,也不过度抽象。
  • 考虑更多边缘场景;深思熟虑重于开发速度。
  • 显式优于巧妙。
  • 最小化差异:尽量少引入新抽象、少修改文件。
  • 性能是一项特性。改造前后需进行性能分析。
  • 可行时优先使用平台/标准库而非第三方库。
  • 弃用警告视为Bug。主动修复。
  • 构建时间至关重要。任何会减慢构建速度的操作都需说明理由。

Diagrams

图表

ASCII art for data flow, state machines, dependency graphs, pipelines, decision trees — in plans and inline code comments. Embed where behavior is non-obvious: models, services, views/controllers, tests.
Diagram maintenance is part of the change. Stale diagrams are worse than none. Flag even outside scope.
使用ASCII图展示数据流、状态机、依赖图、流水线、决策树——包含在计划和代码内联注释中。在行为不明确的地方嵌入图表:模型、服务、视图/控制器、测试。
图表维护是变更的一部分。 过时的图表不如没有。即使超出范围也要标记。

BEFORE YOU START

开始之前

Step 0: Scope Assessment

步骤0:范围评估

  1. Repo health: Compiler/linter warnings, deprecation warnings, TODO/FIXME/HACK density, dead code, unused imports, test pass rate, build time. (Add stack-specific tools per addendum.)
  2. Dependency landscape: All third-party deps, current vs. latest. Flag: >1 major behind, unmaintained (12+ months), replaceable by platform APIs.
  3. Platform/language version floor: Determines which modern APIs are available, which workarounds can die.
  4. Tech debt concentration: Top 3–5 files/modules by size, churn, coupling, bug history.
  5. Complexity check: >15 files or >3 new abstractions → challenge scope.
Offer three modes:
  1. SURGICAL: One theme, minimal blast radius, one session.
  2. SYSTEMATIC: Section-by-section interactive, ≤4 issues per section.
  3. FULL AUDIT: All sections, all issues. Phased roadmap.
Once chosen, commit fully. No silent scope reduction.
  1. 代码库健康度: 编译器/检查器警告、弃用警告、TODO/FIXME/HACK密度、死代码、未使用的导入、测试通过率、构建时间。(根据补充规则添加特定技术栈工具。)
  2. 依赖项现状: 所有第三方依赖项的当前版本与最新版本对比。标记:落后1个以上主版本、已停止维护(12个月以上)、可被平台API替代的依赖。
  3. 平台/语言最低版本: 决定了可使用哪些现代API,哪些兼容代码可以移除。
  4. 技术债务集中点: 按文件/模块大小、变更频率、耦合度、Bug历史排序的前3-5个文件/模块。
  5. 复杂度检查: 涉及超过15个文件或3个新抽象→重新评估范围合理性。
提供三种模式:
  1. 精准模式: 聚焦一个主题,影响范围最小,一次会话完成。
  2. 系统模式: 分章节交互式审查,每章节最多处理4个问题。
  3. 全面审计: 覆盖所有章节和问题,分阶段制定路线图。
一旦选定模式,全程遵循。 不得擅自缩小范围。

Review Sections

审查章节

1. Architecture

1. 架构

Evaluate: module structure and boundaries (draw dependency graph), layering violations, data flow and sources of truth, concurrency/thread safety, routing/navigation consistency, scaling bottlenecks, security boundaries. For each major boundary: one realistic production failure and whether current code handles it. Identify where ASCII diagrams belong. Apply stack addendum.
STOP. AskUserQuestion. Do NOT proceed until user responds.
评估:模块结构与边界(绘制依赖图)、分层违规、数据流与数据源、并发/线程安全、路由/导航一致性、扩展瓶颈、安全边界。针对每个主要边界:列举一个真实的生产故障场景,判断当前代码是否能处理。确定需要嵌入ASCII图的位置。应用对应技术栈的补充规则。
暂停。 询问用户问题。得到用户回复前不得继续。

2. Code quality

2. 代码质量

Evaluate: file/folder organization, DRY violations, error handling gaps (cite file and line), naming consistency, tech debt hotspots, over-engineering and under-engineering, dead code, stale diagrams, linter/compiler warnings. Apply stack addendum.
STOP. AskUserQuestion. Do NOT proceed until user responds.
评估:文件/文件夹组织、DRY原则违规、错误处理漏洞(注明文件和行号)、命名一致性、技术债务热点、过度工程与工程不足、死代码、过时图表、检查器/编译器警告。应用对应技术栈的补充规则。
暂停。 询问用户问题。得到用户回复前不得继续。

3. Tests

3. 测试

Diagram all critical flows, pipelines, state transitions, branching. For each: test exists? meaningful? edge cases covered? fast and reliable? Also: test distribution, execution time (flag slow tests), isolation, missing categories, mock strategy. Apply stack addendum.
STOP. AskUserQuestion. Do NOT proceed until user responds.
绘制所有关键流程、流水线、状态转换、分支的图表。针对每个内容:是否有测试?测试是否有意义?是否覆盖边缘场景?测试是否快速可靠?此外:测试分布、执行时间(标记慢测试)、隔离性、缺失的测试类别、Mock策略。应用对应技术栈的补充规则。
暂停。 询问用户问题。得到用户回复前不得继续。

4. Performance

4. 性能

Evaluate: startup/launch time, memory footprint and leaks, response latency on hot paths, I/O patterns, network efficiency, build time, binary/bundle size. Apply stack addendum.
STOP. AskUserQuestion. Do NOT proceed until user responds.
评估:启动时间、内存占用与泄漏、热点路径的响应延迟、I/O模式、网络效率、构建时间、二进制/包大小。应用对应技术栈的补充规则。
暂停。 询问用户问题。得到用户回复前不得继续。

5. Dependencies and modernization

5. 依赖项与现代化

Evaluate: outdated deps, replaceable deps, unmaintained deps, language modernization opportunities, toolchain hygiene, CI/CD health. Apply stack addendum.
STOP. AskUserQuestion. Do NOT proceed until user responds.
评估:过时依赖、可替代依赖、已停止维护的依赖、语言现代化机会、工具链卫生、CI/CD健康度。应用对应技术栈的补充规则。
暂停。 询问用户问题。得到用户回复前不得继续。

For each issue

针对每个问题的要求

  • File/line references.
  • 2–3 options including "defer."
  • Per option, one line: effort, risk, blast radius, maintenance burden.
  • Lead with directive: "Do B. Here's why:"
  • Map to engineering preference in one sentence.
  • AskUserQuestion: "We recommend [LETTER]: [reason]" then
    A) ... B) ... C) ...
    . Label: NUMBER + LETTER (e.g., "3B").
  • 注明文件/行号引用。
  • 提供2-3个选项,包括「延迟处理」。
  • 每个选项用一句话说明:投入、风险、影响范围、维护成本。
  • 首先给出明确指令:「执行方案B。理由:」
  • 用一句话关联工程偏好
  • 询问用户问题:「我们推荐[选项字母]:[理由]」,然后列出
    A) ... B) ... C) ...
    。标记格式:编号+字母(例如:"3B")。

Required outputs

必需输出

Impact/effort matrix

影响/投入矩阵

                LOW EFFORT        HIGH EFFORT
           ┌─────────────────┬─────────────────┐
HIGH       │ DO FIRST         │ PLAN CAREFULLY   │
IMPACT     │ (quick wins)     │ (core overhaul)  │
           ├─────────────────┼─────────────────┤
LOW        │ IF TIME          │ SKIP / DEFER     │
IMPACT     │ (polish)         │ (not worth it)   │
           └─────────────────┴─────────────────┘
                LOW EFFORT        HIGH EFFORT
           ┌─────────────────┬─────────────────┐
HIGH       │ DO FIRST         │ PLAN CAREFULLY   │
IMPACT     │ (quick wins)     │ (core overhaul)  │
           ├─────────────────┼─────────────────┤
LOW        │ IF TIME          │ SKIP / DEFER     │
IMPACT     │ (polish)         │ (not worth it)   │
           └─────────────────┴─────────────────┘

NOT in scope

不包含在范围内的内容

Deferred work, one-line rationale each.
待办工作,每项用一句话说明理由。

What already exists

已存在的可用资源

Underused utilities, helpers, or patterns already in the codebase.
代码库中未充分利用的工具、辅助函数或模式。

Deferred work → Beads

待办工作 → 提交至Beads

bash
bd create "<title>" -t <type> -p <priority> -d "<what, why, current state, where to start, prereqs>" -l "tech-debt,overhaul"
Ask before filing. Link with
bd dep add
.
bash
bd create "<title>" -t <type> -p <priority> -d "<what, why, current state, where to start, prereqs>" -l "tech-debt,overhaul"
提交前需询问用户。使用
bd dep add
关联任务。

Diagrams

图表

Before/after dependency graphs, refactored data flow, state machines. Identify files needing inline diagrams.
改造前后的依赖图、重构后的数据流、状态机。确定需要内联图表的文件。

Failure modes

故障模式

Per modified codepath: one realistic failure → test covers it? error handling? user-visible or silent? No test + no handling + silent → critical gap.
针对每个修改后的代码路径:列举一个真实故障场景→是否有测试覆盖?是否有错误处理?对用户可见还是静默发生?无测试+无处理+静默→关键漏洞

Migration / rollback

迁移/回滚

Incremental or all-or-nothing? Rollback plan? Old/new coexistence? Verification?
增量式还是全量式?回滚计划?新旧版本共存方案?验证方式?

Execution order

执行顺序

Numbered, respecting: (1) inter-change dependencies, (2) impact/effort priority, (3) tests before refactoring, (4) every step shippable.
编号排序,遵循:(1) 变更间的依赖关系,(2) 影响/投入优先级,(3) 重构前先完善测试,(4) 每一步都可发布。

Completion summary

完成总结

╔════════════════════════════════════════════════╗
║           CODE OVERHAUL SUMMARY                ║
╠════════════════════════════════════════════════╣
║ Mode:                 ___                      ║
║ Stacks detected:      ___                      ║
║ Warnings:             ___ compiler, ___ deprec ║
║ Dead code:            ___                      ║
║────────────────────────────────────────────────║
║ Architecture:         ___ issues               ║
║ Code quality:         ___ issues               ║
║ Tests:                ___ gaps                 ║
║ Performance:          ___ issues               ║
║ Dependencies:         ___ outdated, ___ replace║
║────────────────────────────────────────────────║
║ Quick wins:           ___                      ║
║ Core overhaul:        ___                      ║
║ Beads filed:          ___                      ║
║ Critical gaps:        ___                      ║
║ Execution steps:      ___                      ║
╚════════════════════════════════════════════════╝
Add stack-specific rows from addendums (e.g., force-unwrap count,
any
count, race-clean status).
╔════════════════════════════════════════════════╗
║           CODE OVERHAUL SUMMARY                ║
╠════════════════════════════════════════════════╣
║ Mode:                 ___                      ║
║ Stacks detected:      ___                      ║
║ Warnings:             ___ compiler, ___ deprec ║
║ Dead code:            ___                      ║
║────────────────────────────────────────────────║
║ Architecture:         ___ issues               ║
║ Code quality:         ___ issues               ║
║ Tests:                ___ gaps                 ║
║ Performance:          ___ issues               ║
║ Dependencies:         ___ outdated, ___ replace║
║────────────────────────────────────────────────║
║ Quick wins:           ___                      ║
║ Core overhaul:        ___                      ║
║ Beads filed:          ___                      ║
║ Critical gaps:        ___                      ║
║ Execution steps:      ___                      ║
╚════════════════════════════════════════════════╝
从补充规则中添加特定技术栈的行(例如:强制解包数量、
any
类型数量、竞态条件修复状态)。

Retrospective learning

回顾性分析

Git log: high-churn files, reverted commits, large "fix" commits, recurring patterns ("fix crash in…", "workaround for…"). Aggressive on historically problematic areas.
Git日志:变更频繁的文件、被回滚的提交、大型「修复」提交、重复出现的模式(如「修复...崩溃」、「临时解决...问题」)。重点关注历史上存在问题的区域。

Formatting

格式要求

NUMBER issues, LETTERS for options. Recommended first. One sentence per option. Pause after each section.
问题编号,选项用字母标记。推荐选项放在最前面。每个选项用一句话说明。每章节结束后暂停。

Unresolved decisions

未解决的决策

List at end: "Unresolved decisions that may bite you later." Never silently default.
在末尾列出:「后续可能引发问题的未解决决策」。不得擅自默认处理方式。

Anti-patterns

反模式

  • Big bang rewrites → incremental.
  • Refactoring without tests → characterization tests FIRST.
  • Gold plating → health, not perfection.
  • Chasing new hotness → solve concrete problems only.
  • Breaking the build → every commit compiles and passes tests.

  • 大爆炸式重写→采用增量式改造。
  • 无测试情况下重构→先编写特征测试。
  • 过度优化→聚焦健康度,而非完美。
  • 追逐新技术→仅解决具体问题时使用。
  • 破坏构建→每次提交都需编译通过并通过测试。

Language-Specific Addendums

特定语言补充规则

Apply these when the corresponding stack is detected. For monorepos, apply all matching addendums and tag each finding with its module.

检测到对应技术栈时应用这些规则。对于单仓项目,应用所有匹配的补充规则,并为每个发现标记所属模块。

Addendum: iOS / Swift

补充规则:iOS / Swift

Triggers: _.swift files, _.xcodeproj, *.xcworkspace, Package.swift with Apple platform targets.
触发条件: .swift文件、.xcodeproj、*.xcworkspace、包含Apple平台目标的Package.swift。

Step 0 additions

步骤0补充内容

  • Run: Xcode warnings count, SwiftLint violations, deployment target (min iOS version).
  • Deployment target determines: SwiftUI API surface, structured concurrency availability, which UIKit workarounds can die.
  • Dep audit specifics: SPM/CocoaPods/Carthage. Replaceable: Kingfisher→AsyncImage, Alamofire→URLSession async/await, SnapKit→modern AutoLayout, RxSwift→Combine/async-await, KeychainAccess→native keychain, SwiftyJSON→Codable, IQKeyboardManager→native keyboard avoidance.
  • 执行:统计Xcode警告数量、SwiftLint违规次数、部署目标(最低iOS版本)。
  • 部署目标决定:SwiftUI API范围、结构化并发可用性、可移除的UIKit兼容代码。
  • 依赖项审计细节:SPM/CocoaPods/Carthage。可替代的依赖:Kingfisher→AsyncImage、Alamofire→URLSession async/await、SnapKit→现代AutoLayout、RxSwift→Combine/async-await、KeychainAccess→原生钥匙串、SwiftyJSON→Codable、IQKeyboardManager→原生键盘规避。

Architecture additions

架构补充内容

  • State management consistency: @Observable vs ObservableObject vs @State — pick one per concern, not mix-and-match.
  • Navigation: NavigationStack vs coordinator pattern vs mixed — consistent?
  • Concurrency model: structured concurrency adoption boundary vs legacy GCD/completion handlers. Where is the migration line?
  • Core Data / SwiftData stack health. Extension targets sharing code correctly?
  • 状态管理一致性:@Observable vs ObservableObject vs @State——针对每个关注点选择一种,不得混用。
  • 导航:NavigationStack vs 协调器模式 vs 混合方式——是否一致?
  • 并发模型:结构化并发的采用边界 vs 遗留GCD/完成回调。迁移分界在哪里?
  • Core Data / SwiftData栈健康度。扩展目标是否正确共享代码?

Code quality additions

代码质量补充内容

  • Force-unwraps and implicitly unwrapped optionals — cite every one, these are crash sources.
  • try?
    swallowing errors silently. Empty catch blocks.
  • Retain cycle risks: missing
    [weak self]
    in closures, non-weak delegate properties.
  • Unused @objc exposure, stale Storyboard/XIB connections, dead IBOutlets/IBActions.
  • Massive ViewControllers/Views (>300 lines).
  • Protocol-oriented over-engineering: protocol with one conformer, unnecessary associated types.
  • 强制解包和隐式解包可选类型——逐一标记,这些是崩溃来源。
  • try?
    静默吞掉错误。空catch块。
  • 保留环风险:闭包中缺少
    [weak self]
    、非弱引用的delegate属性。
  • 未使用的@objc暴露、过时的Storyboard/XIB连接、无效的IBOutlet/IBAction。
  • 巨型视图控制器/视图(超过300行)。
  • 面向协议的过度工程:只有一个实现者的协议、不必要的关联类型。

Test additions

测试补充内容

  • XCTest vs Swift Testing adoption. UI test reliability (flag >10s per UI test).
  • Test host app dependency — can unit tests run without app launch?
  • Core Data tests using in-memory stores? Network tests using URLProtocol mocks?
  • Total suite time matters with large test counts — flag >60s.
  • Missing: snapshot tests for complex layouts, accessibility audit tests.
  • XCTest vs Swift Testing的采用情况。UI测试可靠性(标记每个耗时超过10秒的UI测试)。
  • 测试宿主应用依赖——单元测试能否在不启动应用的情况下运行?
  • Core Data测试是否使用内存存储?网络测试是否使用URLProtocol Mock?
  • 测试套件总时间在测试数量较多时至关重要——标记总耗时超过60秒的套件。
  • 缺失的测试:复杂布局的快照测试、可访问性审计测试。

Performance additions

性能补充内容

  • Launch: Pre-main (dylib loading, +load, static initializers) and post-main. Synchronous main-thread work in
    didFinishLaunching
    ?
  • Main thread: File I/O, JSON parsing, image decoding, Core Data fetches on main.
  • Scrolling: Cell reuse, async image loading, Auto Layout ambiguity, offscreen rendering (cornerRadius + clipsToBounds).
  • Media: Image downsample before display? PhotoKit fetch efficiency? Unnecessary format conversions?
  • Build: Slowest files via
    -Xfrontend -debug-time-function-bodies
    . Complex type inference. SPM resolution time.
  • Binary: Unused asset catalog entries, embedded resources that could be on-demand.
  • 启动: 主程序启动前(动态库加载、+load、静态初始化)和启动后阶段。
    didFinishLaunching
    中是否有同步主线程操作?
  • 主线程: 主线程上的文件I/O、JSON解析、图片解码、Core Data查询。
  • 滚动: 单元格复用、异步图片加载、Auto Layout歧义、离屏渲染(cornerRadius + clipsToBounds)。
  • 媒体: 图片显示前是否进行降采样?PhotoKit查询效率?不必要的格式转换?
  • 构建: 通过
    -Xfrontend -debug-time-function-bodies
    找出最慢的文件。复杂类型推断。SPM解析时间。
  • 二进制文件: 未使用的资源目录条目、可按需加载的嵌入式资源。

Modernization additions

现代化补充内容

  • Structured concurrency: async/await, actors, task groups.
  • @Observable macro (iOS 17+), #Preview macros, @Entry for EnvironmentValues.
  • Typed throws (Swift 6), strict concurrency checking readiness.
  • Xcode hygiene: unused build phases, stale schemes, code signing drift, build settings at wrong level.
  • 结构化并发:async/await、actor、任务组。
  • @Observable宏(iOS 17+)、#Preview宏、用于EnvironmentValues的@Entry。
  • 类型化throws(Swift 6)、严格并发检查就绪情况。
  • Xcode卫生:未使用的构建阶段、过时的scheme、代码签名漂移、错误层级的构建设置。

Summary additions

总结补充内容

Add rows: Min iOS target, Swift version, force-unwrap count, SwiftLint violations.
添加行:最低iOS版本、Swift版本、强制解包数量、SwiftLint违规次数。

Extra anti-pattern

额外反模式

  • UIKit-to-SwiftUI migration without a boundary strategy → define the bridge pattern once, use everywhere.

  • UIKit到SwiftUI的迁移无边界策略→定义一次桥接模式,全局使用。

Addendum: Go

补充规则:Go

Triggers: go.mod, *.go files.
触发条件: go.mod、*.go文件。

Step 0 additions

步骤0补充内容

  • Run:
    go vet
    ,
    staticcheck
    ,
    golangci-lint
    ,
    govulncheck ./...
    ,
    go mod tidy
    drift check.
  • Go version in go.mod determines: range-over-func (1.23+), log/slog (1.21+), errors.Join (1.20+), generics depth, loop variable fix (1.22+).
  • Dep audit specifics:
    go list -m -u all
    . Replaceable: gorilla/mux→stdlib 1.22+ routing, logrus→log/slog, pkg/errors→fmt.Errorf %w, testify→stdlib testing, go-playground/validator→custom, gorm→sqlc/sqlx, cobra→stdlib flag for simple CLIs.
  • 执行:
    go vet
    staticcheck
    golangci-lint
    govulncheck ./...
    go mod tidy
    漂移检查。
  • go.mod中的Go版本决定:range-over-func(1.23+)、log/slog(1.21+)、errors.Join(1.20+)、泛型深度、循环变量修复(1.22+)。
  • 依赖项审计细节:
    go list -m -u all
    。可替代的依赖:gorilla/mux→标准库1.22+路由、logrus→log/slog、pkg/errors→fmt.Errorf %w、testify→标准库testing、go-playground/validator→自定义实现、gorm→sqlc/sqlx、cobra→标准库flag(适用于简单CLI)。

Architecture additions

架构补充内容

  • Package boundaries:
    internal/
    usage correct? Circular dep risks?
  • Interface pollution: too many interfaces defined by implementor rather than consumer. Accept interfaces, return structs.
  • Dependency injection: wire, manual, or scattered
    init()
    ?
  • Graceful shutdown chain: signal → context cancellation → resource cleanup.
  • Error propagation: sentinel vs typed vs wrapping — consistent?
  • Context: values vs cancellation — abuse?
  • 包边界:
    internal/
    使用是否正确?是否有循环依赖风险?
  • 接口滥用:过多由实现者定义的接口,而非由消费者定义。应接受接口,返回结构体。
  • 依赖注入:使用wire、手动注入还是分散的
    init()
  • 优雅关闭链:信号→上下文取消→资源清理。
  • 错误传播:哨兵错误 vs 类型化错误 vs 错误包装——是否一致?
  • Context:值传递 vs 取消——是否滥用?

Code quality additions

代码质量补充内容

  • Unchecked errors:
    _ = foo()
    — cite every one unless justified with comment.
  • Naked returns in complex functions.
  • Package-level globals and
    init()
    abuse.
  • Naming: Go conventions (MixedCaps, 1-2 char receivers, lowercase single-word packages). Stuttering (
    user.UserService
    ).
  • Over-engineering: interfaces with one implementation, unnecessary generics, Options pattern for 2 config values.
  • Under-engineering: 2000+ line files, >5 params,
    any
    /
    interface{}
    where generics clarify.
  • 未检查的错误:
    _ = foo()
    ——逐一标记,除非有注释说明理由。
  • 复杂函数中的裸返回。
  • 包级全局变量和
    init()
    滥用。
  • 命名:Go约定(MixedCaps、1-2字符接收器、小写单字包名)。命名重复(如
    user.UserService
    )。
  • 过度工程:只有一个实现的接口、不必要的泛型、针对2个配置值使用Options模式。
  • 工程不足:超过2000行的文件、超过5个参数的函数、使用
    any
    /
    interface{}
    而泛型可更清晰的场景。

Test additions

测试补充内容

  • Table-driven tests consistent?
    t.Helper()
    used? Subtests with
    t.Run()
    ?
  • Integration tests tagged
    //go:build integration
    ?
  • Race detector:
    go test -race
    passing? This is a gate, not optional.
  • Benchmarks for hot paths (
    BenchmarkX
    ). Fuzz tests for parsers (
    FuzzX
    ).
  • Golden files for complex output.
    testdata/
    organized?
  • Mocking: interfaces at boundaries only, not mocking everything.
    httptest
    for handlers.
  • 表驱动测试是否一致?是否使用
    t.Helper()
    ?是否使用
    t.Run()
    进行子测试?
  • 集成测试是否标记
    //go:build integration
  • 竞态检测器:
    go test -race
    是否通过?这是必过门槛,而非可选检查。
  • 热点路径的基准测试(
    BenchmarkX
    )。解析器的模糊测试(
    FuzzX
    )。
  • 复杂输出的Golden文件。
    testdata/
    组织是否有序?
  • Mock:仅在边界处使用接口,而非所有内容都Mock。使用
    httptest
    处理请求处理器。

Performance additions

性能补充内容

  • CPU: Unnecessary allocations in tight paths, reflection in hot code, regexp compilation inside loops (compile once as package var), string concat in loops (strings.Builder).
  • Memory: Goroutine leaks (unbounded spawn without context cancel), sync.Pool opportunities, slice pre-alloc (
    make([]T, 0, cap)
    ), string↔[]byte in hot paths.
  • Concurrency: Mutex contention (RWMutex? atomic?), channel buffer sizing, goroutine fan-out without limits (errgroup), context propagation gaps.
  • I/O: Connection pool sizing, prepared statement reuse, N+1 queries, HTTP client reuse (not per-request), response body not closed, bufio for files.
  • Build: CGO (slows build, complicates cross-compile), unnecessary
    go generate
    .
  • Binary:
    -ldflags "-s -w"
    ,
    -trimpath
    , unused dep bloat.
  • CPU: 循环路径中的不必要分配、热点代码中的反射、循环内的正则表达式编译(应编译为包级变量)、循环中的字符串拼接(使用strings.Builder)。
  • 内存: Goroutine泄漏(无上下文取消的无限制创建)、sync.Pool的使用机会、切片预分配(
    make([]T, 0, cap)
    )、热点路径中的字符串↔[]byte转换。
  • 并发: Mutex竞争(是否可改用RWMutex?原子操作?)、通道缓冲区大小、无限制的Goroutine扇出(使用errgroup)、上下文传播漏洞。
  • I/O: 连接池大小、预编译语句复用、N+1查询、HTTP客户端复用(而非每次请求创建)、响应体未关闭、文件操作使用bufio。
  • 构建: CGO(减慢构建速度,使交叉编译复杂化)、不必要的
    go generate
  • 二进制文件: 使用
    -ldflags "-s -w"
    -trimpath
    、移除未使用的依赖膨胀。

Modernization additions

现代化补充内容

  • Generics replacing
    interface{}
    /codegen where it clarifies (only with >2 concrete types).
  • range-over-func (1.23+), log/slog, errors.Join, loop variable fix (1.22+) — remove workarounds.
  • iter package (1.23+), any/comparable constraints.
  • Toolchain: Makefile/Taskfile hygiene, golangci-lint config freshness, CI (test, vet, lint, race, vulncheck).
  • 泛型替代
    interface{}
    /代码生成(仅当有超过2个具体类型且模式已验证时使用)。
  • range-over-func(1.23+)、log/slog、errors.Join、循环变量修复(1.22+)——移除兼容代码。
  • iter包(1.23+)、any/comparable约束。
  • 工具链:Makefile/Taskfile卫生、golangci-lint配置更新、CI(测试、vet、lint、竞态检查、漏洞检查)。

Summary additions

总结补充内容

Add rows: Go version (mod), go vet issues, staticcheck issues, govulncheck findings, unchecked errors, race clean Y/N.
添加行:Go版本(mod)、go vet问题数、staticcheck问题数、govulncheck发现数、未检查错误数、竞态条件修复完成情况(是/否)。

Extra anti-patterns

额外反模式

  • Over-interfacing → one-method interfaces are Go's sweet spot, not the starting point.
  • Premature generics → only when >2 concrete types and pattern is proven.

  • 过度接口化→单方法接口是Go的最佳实践,而非起点。
  • 过早使用泛型→仅当有超过2个具体类型且模式已验证时使用。

Addendum: Web / JavaScript / CSS

补充规则:Web / JavaScript / CSS

Triggers: package.json, tsconfig.json, _.js, _.ts, _.jsx, _.tsx, _.css, _.scss, *.html files.
触发条件: package.json、tsconfig.json、.js、.ts、.jsx、.tsx、.css、.scss、*.html文件。

Step 0 additions

步骤0补充内容

  • Run:
    tsc --noEmit
    errors, ESLint/Prettier violations,
    npm audit
    , bundle size (total + per-route).
  • TypeScript strict mode on? If not, migration path is high-priority.
  • Browser floor (browserslist) determines: CSS nesting, :has(), container queries, structuredClone, AbortSignal.any, Promise.withResolvers.
  • Dep audit:
    npm outdated
    . Replaceable: moment→Temporal/date-fns, lodash→native (Array.at, Object.groupBy, structuredClone), axios→fetch, classnames→clsx/template literals, uuid→crypto.randomUUID, node-fetch→native fetch (Node 18+).
  • 执行:
    tsc --noEmit
    错误、ESLint/Prettier违规、
    npm audit
    、包大小(总大小+按路由拆分的大小)。
  • TypeScript严格模式是否开启?若未开启,迁移路径为高优先级。
  • 最低兼容浏览器(browserslist)决定:CSS嵌套、:has()、容器查询、structuredClone、AbortSignal.any、Promise.withResolvers。
  • 依赖项审计:
    npm outdated
    。可替代的依赖:moment→Temporal/date-fns、lodash→原生方法(Array.at、Object.groupBy、structuredClone)、axios→fetch、classnames→clsx/模板字符串、uuid→crypto.randomUUID、node-fetch→原生fetch(Node 18+)。

Architecture additions

架构补充内容

  • Component hierarchy (draw tree). State management: local vs global, prop drilling vs context vs store — consistent?
  • Data fetching: per-component vs route-level vs centralized? Caching/dedup? Loading/error states?
  • API layer: fetch calls scattered or centralized?
  • SSR/SSG/CSR boundaries if applicable. Error boundary placement.
  • Build config complexity. Environment handling.
  • 组件层级(绘制树状图)。状态管理:局部 vs 全局、属性透传 vs Context vs Store——是否一致?
  • 数据获取:组件级 vs 路由级 vs 集中式?缓存/去重?加载/错误状态?
  • API层:fetch调用分散还是集中?
  • 若适用,SSR/SSG/CSR边界。错误边界的位置。
  • 构建配置复杂度。环境变量处理。

Code quality additions

代码质量补充内容

JS/TS:
  • any
    types
    — cite every one, these defeat TypeScript.
  • as
    assertions bypassing safety. Loose equality (
    ==
    ).
  • Uncaught promise rejections. Missing error boundaries.
  • Barrel file bloat killing tree-shaking. Unused exports (
    ts-prune
    ).
  • Component files >300 lines.
CSS:
  • Specificity wars,
    !important
    proliferation.
  • Magic numbers without custom properties. Duplicated values needing design tokens.
  • Unused CSS. Inconsistent naming (BEM vs utility vs random).
  • z-index: documented scale or chaos? Media queries: scattered or centralized?
  • CSS-in-JS vs stylesheets vs utility — consistent approach?
HTML/Accessibility:
  • Semantic HTML (div soup?). ARIA: missing or wrong. Keyboard nav, focus management, color contrast, alt text, form labels, heading hierarchy.
JS/TS:
  • any
    类型
    ——逐一标记,这些会破坏TypeScript的类型安全。
  • as
    断言绕过安全检查。松散相等(
    ==
    )。
  • 未捕获的Promise拒绝。缺失错误边界。
  • 桶文件膨胀破坏摇树优化。未使用的导出(使用
    ts-prune
    检测)。
  • 组件文件超过300行。
CSS:
  • 特殊性冲突、
    !important
    滥用。
  • 无自定义属性的魔法数字。需要设计令牌的重复值。
  • 未使用的CSS。命名不一致(BEM vs 工具类 vs 随机命名)。
  • z-index:是否有文档化的层级还是混乱状态?媒体查询:分散还是集中?
  • CSS-in-JS vs 样式表 vs 工具类——是否采用一致的方式?
HTML/可访问性:
  • 语义化HTML(是否滥用div?)。ARIA:缺失或错误。键盘导航、焦点管理、颜色对比度、替代文本、表单标签、标题层级。

Test additions

测试补充内容

  • Unit (Jest/Vitest) for logic. Component (Testing Library) for behavior — flag
    getByTestId
    overuse, prefer
    getByRole
    /
    getByText
    .
  • E2E (Playwright/Cypress) for critical paths. Visual regression for complex layouts.
  • MSW for network mocking — consistent? Snapshot tests: useful or noise?
  • Accessibility tests (axe-core). Suite speed: flag >30s total, >5s individual.
  • 逻辑的单元测试(Jest/Vitest)。组件的行为测试(Testing Library)——标记过度使用
    getByTestId
    的情况,优先使用
    getByRole
    /
    getByText
  • 关键路径的E2E测试(Playwright/Cypress)。复杂布局的视觉回归测试。
  • 网络Mock的MSW——是否一致?快照测试:有用还是冗余?
  • 可访问性测试(axe-core)。测试套件速度:标记总耗时超过30秒、单个测试超过5秒的情况。

Performance additions

性能补充内容

  • Core Web Vitals: LCP (critical rendering path), CLS (images without dimensions, font flash, dynamic injection), INP (long tasks, heavy handlers).
  • Bundle: Per-route splits, tree-shaking effective?, dynamic imports for below-fold, duplicate deps,
    source-map-explorer
    analysis.
  • Loading: Critical CSS inlined? Render-blocking resources? Font strategy (font-display, preload)? Images (WebP/AVIF, srcset, lazy load, explicit dimensions)?
  • Runtime: Unnecessary re-renders (missing memo where measured), DOM thrashing, event listener cleanup, Web Worker opportunities, requestAnimationFrame for visual updates.
  • Caching: Service worker strategy, HTTP headers, CDN, stale-while-revalidate, asset fingerprinting.
  • Network: API waterfall (sequential→parallel), overfetching, missing pagination.
  • 核心Web指标: LCP(关键渲染路径)、CLS(无尺寸的图片、字体闪烁、动态注入)、INP(长任务、重型处理器)。
  • 包: 按路由拆分、摇树优化是否有效?下方内容的动态导入、重复依赖、
    source-map-explorer
    分析。
  • 加载: 关键CSS内联?阻塞渲染的资源?字体策略(font-display、预加载)?图片(WebP/AVIF、srcset、懒加载、明确尺寸)?
  • 运行时: 不必要的重渲染(经测量后缺失memo)、DOM抖动、事件监听器清理、Web Worker使用机会、视觉更新使用requestAnimationFrame。
  • 缓存: Service Worker策略、HTTP头、CDN、stale-while-revalidate、资源指纹。
  • 网络: API请求瀑布(串行→并行)、过度获取、缺失分页。

Modernization additions

现代化补充内容

  • CSS: native nesting (drop preprocessor nesting), container queries,
    :has()
    , View Transitions, Popover API,
    <dialog>
    (drop modal libs),
    color-mix()
    ,
    @property
    .
  • TS: strict mode path,
    satisfies
    , template literal types, discriminated unions,
    using
    (5.2+).
  • Platform: structuredClone, Object.groupBy, Set methods, import attributes.
  • Toolchain: bundler currency (Webpack→Vite?), Node version, package manager consistency, monorepo tooling, preview deployments.
  • CSS:原生嵌套(移除预处理器嵌套)、容器查询、
    :has()
    、View Transitions、Popover API、
    <dialog>
    (移除模态框库)、
    color-mix()
    @property
  • TS:严格模式迁移路径、
    satisfies
    、模板字面量类型、可区分联合、
    using
    (5.2+)。
  • 平台:structuredClone、Object.groupBy、Set方法、导入属性。
  • 工具链:打包器版本(Webpack→Vite?)、Node版本、包管理器一致性、单仓工具、预览部署。

Summary additions

总结补充内容

Add rows: Framework, TS strict Y/N,
any
count, ESLint violations, bundle size (gzip), npm audit vulns, LCP.
添加行:框架、TS严格模式(是/否)、
any
类型数量、ESLint违规次数、包大小(gzip后)、npm audit漏洞数、LCP值。

Extra anti-patterns

额外反模式

  • Premature abstraction → don't build a component system for 3 buttons.
  • CSS reset whack-a-mole → fix the specificity model, not symptoms.
  • any
    as escape hatch → every
    any
    is deferred debt with compound interest.
  • Framework churn → migrate when solving a concrete problem, not for novelty.
  • 过早抽象→不要为3个按钮构建组件系统。
  • CSS重置反复调整→修复特殊性模型,而非症状。
  • any
    作为逃避方式→每个
    any
    都是会产生复利的延迟债务。
  • 框架频繁切换→仅在解决具体问题时迁移,而非为了新奇。