Harness AI Coding工程化实践:如何将不同项目的代码一致性提升至 96%

Harness AI Coding工程化实践:如何将不同项目的代码一致性提升至 96%

当前 AI 的编程能力总结如下: 简单项目/功能:简单项目编码影响大,AI Coding 能力 > 高级开发工程师(主要是从效率、规范度、实现方案、考虑异常等方面); 复杂项目:复杂项目更考验设计能力,AI Coding 能力 <= ...

当前 AI 的编程能力总结如下:

  • 简单项目/功能:简单项目编码影响大,AI Coding 能力 > 高级开发工程师(主要是从效率、规范度、实现方案、考虑异常等方面);

  • 复杂项目:复杂项目更考验设计能力,AI Coding 能力 <= 高级工程师。AI 因为上下文限制、注意力、领域知识专业度等存在一些短板,在综合设计能力上还达不到经验丰富的 Go 高级/专家开发工程师水平。

综上,AI 当前的 Coding 能力,其实是 <= 高级开发工程师的。跟初中级开发工程师的区别最大在于其自动化编码能力及编码速度上。但是从代码质量上其实面临的问题跟非 AI 时代初中级开发工程师面临的问题是一样的。

从非AI时代的成熟解法

既然 AI 面临的代码质量问题(破坏架构、忽略边缘条件、缺乏全局视野、风格不统一)与传统软件工程中初中级工程师面临的问题高度一致,那么软件工程几十年来积累的“团队管理与质量管控体系”,就是解决 AI Coding 问题的最佳药方。

在传统的软件工程中,资深架构师/Tech Lead 绝不会依赖初中级工程师的“自觉”来保证代码质量,而是通过一套工程化体系来对其进行约束和赋能。这套体系的核心手段包含以下 5 个维度:

  • 开发能力:
    • Code 能力:
    • 开发方法论、设计模式:
    • 架构、方案设计能力:
  • 规范约束:各种类型的开发规范。通过规范,除了能够提高开发者的代码质量之外,还能够确保全公司、全团队具有一致的开发风格、架构设计模式,有利于团队级别降低代码维护的成本。
  • 开发脚手架:固化代码架构、开发规范等,在一定程度上确保开发风格、架构模式的强一致;
  • 代码审查:
    • 自动化质量网关(各种 Lint 工具):
    • Code Review:人工的 Code Review。
  • 透彻理解产品需求:开发需要认真阅读、理解产品文档,并跟产品经理多次对齐,确保对产品功能的理解是正确的。

总结下非 AI 时代我们提高软件质量的方法:提高软件开发硬能力,将开发规范文档化,将标准规范工具化,并在交付时,进行代码审查。

在 AI 时代,上面的规范文档、脚手架、设计模式、开发方法论等,在我看来其实就是数据。解决 AI Coding 代码质量的核心途径其实就是给 AI 提供一整套高质量的数据,并且通过一种 AI 友好的方式提供给 AI 去使用。

上面也是我解决 AI Code代码质量的思路。

Harness AI Coding 实战

得益于过去写课积累的高质量知识体系。我构建了一整套标准化的 Go 应用开发体系。体系中包括:开发方法论、设计模式、开发规范、开发脚手架、架构基座、基础 Go 包等。因为过去对课程质量及代码质量要求很高,所以在梳理这些内容的时候,整个内容质量及代码质量都是很高的。即使在 AI 时代,质量仍然很高,可以理解为,目前仍然处在一个最佳实践的程度。

对 AI 来说一个高质量的数据具有一些特点:

  • 结构化:AI 对结构化数据的理解精度要远大于 Prompt。例如,你用了一大堆 Pormpt 去解释一个 JSON 结构,还不如直接把 JSON 结构示例数据喂给 AI;
  • 一致性:有些规范、设计方法和实现可能会横跨多个文档、工具或者代码仓库。要确保这些内容在全局范围一致,尽量不给 AI 带来不必要的迷惑;
  • 高质量:数据本身需要是高质量的,也就是规范、代码、设计和实现方式,都要遵循最佳实践;
  • 扩展能力:在 Code 的过程中,如果能够提供一个扩展能力很强、插拔方式简单、清晰的功能迭代方式给 AI,AI 能更好、更快的完成任务。

我做的事情其实很简单。将所有的高质量数据工具化,通过 MCP Tool、SKILL 的方式渐进式喂给 AI。

ai coding 工具套件

上面介绍了,我的解决思路。具体来说就是:

  1. 规范工具化;
  2. 通过脚手架生成框架代码;

规范工具化

将我课程体系中,完整的开发规范,经过梳理、再加工后,封装为  46 个工具。这些规范体系全方位覆盖了从架构设计、底层编码与组件框架开发(CLI/REST/gRPC/微前端),到测试调优、可观测与排障以及 CI/CD 交付的 Go 云原生企业级全生命周期工程化开发标准。

具体规范内容如下:

overview                Get the complete index of Go development conventions grouped by category
  architecture            Get Clean Architecture conventions: layered design, dependency rules, testability, and the miniblog reference implementation
  benchmark               Get benchmarking conventions: writing benchmarks with b.Loop, running with benchstat, profiling from benchmarks, documenting results in commits, CI regression detection
  ci                      Get CI/CD conventions: GitHub Actions pipelines, testing with -race, lint, SAST (govulncheck/CodeQL), coverage, Dependabot/Renovate, GoReleaser, AI code review
  cli                     Get CLI development conventions: command structure, flag handling, configuration layering, version embedding, exit codes, I/O patterns, signal handling, shell completion
  cobra                   Get cobra conventions: command tree, RunE hook chain, Args validators, persistent vs local flags, command groups, completions, doc generation, testing with SetArgs/SetOut
  coding                  Get the full Go coding standard: formatting, naming, imports, functions, packages, testing, and best practices
  commit                  Get commit conventions: Conventional Commits format, branching strategy, and merge request guidelines
  concurrency             Get Go concurrency conventions: goroutine ownership, channel patterns, and race avoidance
  context                 Get Go context conventions: cancellation, deadlines, and value propagation
  data-structures         Get data structures conventions: slice/map preallocation, container/heap/list/ring, strings.Builder vs bytes.Buffer, generic collections, pointer types, copy semantics
  database                Get database access conventions: transactions, connection management, and migration strategies
  dependency-injection    Get dependency injection conventions: manual constructor injection vs wire/dig/fx, constructor injection, composition root, DI library decision table
  dependency-management   Get dependency management conventions: go.mod, version selection, and vulnerability scanning
  design-patterns         Get design patterns conventions: functional options, constructors, error flow, resource management, graceful shutdown, resilience, data handling, streaming
  dev-system              Get the standardised development system design: the three-step methodology, convention catalog, and implementation strategy
  directory               Get directory structure conventions: cmd/, internal/, pkg/ layout, naming, and file organisation rules
  documentation           Get documentation conventions: godoc comments, README structure, CONTRIBUTING, CHANGELOG (Keep a Changelog), Example tests, API docs, llms.txt
  error-return            Get error return conventions: HTTP response patterns, semantic error codes, and error message security rules
  errorsx                 Get the ErrorX error package design: struct definition, API, error wrapping, and integration patterns
  grpc                    Get gRPC conventions: proto organization, server/client implementation, interceptors, status code errors, TLS/mTLS, bufconn testing, streaming RPCs
  id-generation           Get ID generation conventions: resource ID format, reference ID patterns, and generation rules
  klog                    Get klog logging conventions for Kubernetes-ecosystem components: klog.InfoS/ErrorS, log levels, structured KObj/KRef usage
  lint                    Get Go linting conventions: linter setup, static analysis, and CI integration
  logging                 Get mandatory logging rules: English-only, structured KV format, log levels, past tense, no sensitive data
  misc                    Get miscellaneous coding conventions: pointer handling with ptr package, avoiding unnecessary nil/empty checks
  modernize               Get Go modernization conventions: deprecated package migrations, language feature adoption, standard library upgrades, migration priority guide, modernize linter
  observability           Get observability conventions: metrics, distributed tracing, and the three-pillar model
  onexstack               Get the complete onexstack package catalog: all reusable packages with APIs, signatures, and usage patterns
  onexstack-reuse         MANDATORY RULE: Always check and reuse onexstack/onexstack packages BEFORE writing any new code
  performance             Get performance optimization conventions: profile before optimizing, allocation reduction, decision tree (if X bottleneck apply Y), GC tuning, hot-path optimization
  prd                     Get the PRD methodology: format, workflow, and best practices for AI-driven development
  refactoring             Get refactoring conventions: coverage-adaptive safety net, tool-driven behavior-preserving transforms (gopls Rename/Inline/Extract), atomic commits, breaking import cycles, type alias migration
  rest-api                Get REST API design conventions: URI naming, HTTP methods, versioning, error responses, and pagination
  safety                  Get Go safety conventions: nil traps, panic prevention, and defensive coding
  scaffold                Mandatory post-creation build steps after onexai create commands
  security                Get Go security conventions: input validation, SQL/command injection prevention, and secure defaults
  semver                  Get the pre-release version auto-generation rules used by onexai semver tag
  slog                    Get log/slog conventions: context-aware logging, flat key-value pairs, snake_case keys, sensitive data protection
  structs-interfaces      Get struct & interface design conventions: small interfaces, consumer-side definition, and abstraction
  testify                 Get testify conventions: assert vs require, mock expectations and matchers, suite lifecycle, advanced assertions like Eventually and JSONEq
  testing                 Get Go testing conventions: table-driven tests, coverage, and test naming
  troubleshooting         Get troubleshooting conventions: root cause methodology, debugging golden rules, common Go bugs, race detection, pprof setup, GODEBUG tracing, production debugging
  version                 Get semantic versioning conventions: MAJOR.MINOR.PATCH format, version bump rules, and onexai semver integration
  viper                   Get viper conventions: layered precedence (flag > env > file > KV > default), BindPFlag, env binding with key replacer, Unmarshal with mapstructure tags, hot reload, test isolation
  web-frontend            Get the web frontend standards: React 19 + Rsbuild + Wujie micro-frontend, monorepo layout, naming, components, stores, routing, i18n, styling, and commit rules

这些规范内容很多,全部喂给 AI 会有很大的 Context 消耗。但这其实不是问题,解决方案如下:

  • 在日常 Code 中,AI 更倾向于基于已有代码规范,开发风格和架构,来生成新的代码。所以,我们要做的时,在需要的时候,渐进式的喂给 AI 这些规范:
    • 开发新项目时,要开发出符合代码规范的项目;
    • 可以阶段性的铜鼓哦定向的 /review 命令来将项目再规范化。其实就是避免频繁的优化,而是阶段性的一次性优化。可以使用 onexai review 工具强制Review你的代码并自动修复。Review的时候,可以指定规范等级;
    • 其他情况,交给 AI 自行判断,使用哪个规范即可。onexai rag 提供了基于语义的规范查找方式。

onexai 的所有工具,都会自动转换为 MCP Tool,并连接至 Claude Code 等 AI IDE工具。

在告知 AI 开发规范的时候,其实是通过 onexai convention overview 来告知的。而非通过全量的规范。convention overview 工具输出内容如下:

Every convention below is available as an MCP tool. MCP tool name is `convention_<subcommand>`: the underscore joins `convention` to the subcommand, and hyphens inside the subcommand are preserved (never rewritten as `_`). For example Error Return → `convention_error-return`, Dependency Injection → `convention_dependency-injection`.
> Invoke the exact MCP tool name from the table (or the equivalent CLI form `onexai convention <subcommand>`).

## Convention Levels (规范级别)

Each convention document marks its rules with one or more levels. Levels are
NOT a command-level classification — a single convention may contain 强制,
建议, and 参考 rules together.

| Level | Label | Description |
|---|---|---|
| **Mandatory** | 强制 | Must be followed in all projects. Only affects product function. Exceptions require formal review approval. Existing projects: phased improvement. New projects: enforced from design stage. |
| **Recommended** | 建议 | Follow unless there is a justified reason not to. Existing projects: adopt incrementally. New projects: default follow, exceptions require review. |
| **Reference** | 参考 | Guidance only, not hard requirements. Adopt flexibly per project context. |

## Conventions by Category (按类别)

### Core Principles

| MCP tool | Convention | CLI command |
|---|---|---|
| `convention_onexstack` | OneXStack Package Catalog | `onexai convention onexstack` |
| `convention_onexstack-reuse` | OneXStack Reuse-First Principle | `onexai convention onexstack-reuse` |

### Coding Standards

| MCP tool | Convention | CLI command |
|---|---|---|
| `convention_benchmark` | Benchmarking Conventions | `onexai convention benchmark` |
| `convention_cli` | CLI Development Conventions | `onexai convention cli` |
| `convention_cobra` | Cobra Conventions | `onexai convention cobra` |
| `convention_coding` | Go Coding Standard | `onexai convention coding` |
| `convention_concurrency` | Concurrency Conventions | `onexai convention concurrency` |
| `convention_context` | Context Usage Conventions | `onexai convention context` |
| `convention_data-structures` | Data Structures Conventions | `onexai convention data-structures` |
| `convention_database` | Database Access Conventions | `onexai convention database` |
| `convention_dependency-management` | Dependency Management Conventions | `onexai convention dependency-management` |
| `convention_design-patterns` | Design Patterns Conventions | `onexai convention design-patterns` |
| `convention_documentation` | Documentation Conventions | `onexai convention documentation` |
| `convention_id-generation` | ID Generation Conventions | `onexai convention id-generation` |
| `convention_klog` | KLog Conventions | `onexai convention klog` |
| `convention_lint` | Linting Conventions | `onexai convention lint` |
| `convention_logging` | Logging Conventions | `onexai convention logging` |
| `convention_modernize` | Modernize Conventions | `onexai convention modernize` |
| `convention_observability` | Observability: Metrics & Tracing | `onexai convention observability` |
| `convention_performance` | Performance Optimization Conventions | `onexai convention performance` |
| `convention_refactoring` | Refactoring Conventions | `onexai convention refactoring` |
| `convention_safety` | Safety & Defensive Coding | `onexai convention safety` |
| `convention_security` | Security Conventions | `onexai convention security` |
| `convention_slog` | Slog Conventions | `onexai convention slog` |
| `convention_structs-interfaces` | Structs & Interfaces Design | `onexai convention structs-interfaces` |
| `convention_testify` | Testify Conventions | `onexai convention testify` |
| `convention_testing` | Testing Conventions | `onexai convention testing` |
| `convention_troubleshooting` | Troubleshooting Conventions | `onexai convention troubleshooting` |
| `convention_viper` | Viper Conventions | `onexai convention viper` |

### API & Error Handling

| MCP tool | Convention | CLI command |
|---|---|---|
| `convention_error-return` | Error Return Conventions | `onexai convention error-return` |
| `convention_errorsx` | ErrorX Package Design | `onexai convention errorsx` |
| `convention_grpc` | gRPC Conventions | `onexai convention grpc` |
| `convention_rest-api` | REST API Conventions | `onexai convention rest-api` |

### Architecture & Design

| MCP tool | Convention | CLI command |
|---|---|---|
| `convention_architecture` | Architecture Conventions | `onexai convention architecture` |
| `convention_dependency-injection` | Dependency Injection Conventions | `onexai convention dependency-injection` |
| `convention_directory` | Directory Structure Conventions | `onexai convention directory` |

### Operations

| MCP tool | Convention | CLI command |
|---|---|---|
| `convention_ci` | CI/CD Conventions | `onexai convention ci` |
| `convention_commit` | Commit Conventions | `onexai convention commit` |
| `convention_semver` | Semver Pre-release Rules | `onexai convention semver` |
| `convention_version` | Versioning Conventions | `onexai convention version` |

### Platform & Development

| MCP tool | Convention | CLI command |
|---|---|---|
| `convention_dev-system` | Development System Design | `onexai convention dev-system` |
| `convention_misc` | Miscellaneous Conventions | `onexai convention misc` |

### AI & Methodology

| MCP tool | Convention | CLI command |
|---|---|---|
| `convention_prd` | PRD Methodology | `onexai convention prd` |

### Scaffold & Tooling

| MCP tool | Convention | CLI command |
|---|---|---|
| `convention_scaffold` | Scaffold Post-Creation Steps | `onexai convention scaffold` |

### Web Frontend

| MCP tool | Convention | CLI command |


|---|---|---|
| `convention_web-frontend` | Web Frontend Development Standards | `onexai convention web-frontend` |

通过脚手架生成框架代码

上面是规范。大家在开发中,都知道规范是文档化的,需要一个有更强约束力的工程化手段,来确保规范的落地。

onexai create 命令中集成了 20 个脚手架命令,这些脚手架命令从目录结构、代码架构设计、代码实现方式和风格、代码开发规范、代码引用包等方方面面,都保持高度的一致,甚至完全的一致。

这 20 个脚手架命令分别用来生成以下代码: