从“代码优先”到“意图优先”:AI 时代工程师的实战生存指南

摘要:当 AI 能够快速生成看似可用的代码时,我们工程师的核心价值是什么?答案并非更花哨的提示词技巧,而是回归工程的本质:精确定义问题,严谨约束过程,并构建可靠的反馈系统。本文将摒弃空谈,通过 4 个真实的研发案例,展示如何利用“规格 (Specs)、上下文 (Context)、智能体 (Agents)”这一新范式,将模糊的需求转化为可控、可验证、可持续迭代的软件系统,真正驾驭 AI 的力量,而不是被其反噬。

一、当 AI 写下第一行代码时,真正的挑战才刚刚开始

在 2026 年的今天,AI 辅助编程已经从一个新奇的玩具,变成了许多团队日常开发流程的一部分。我们见证了 AI 在生成代码、编写测试,甚至初步设计上的惊人能力。然而,一个普遍的误解随之而来:似乎只要掌握了“提示词工程”,就能取代资深的工程师。

现实恰恰相反。

我们越来越多地发现,如果你无法清晰地描述一个问题,AI 会欣然为你生成一个看似正确却暗藏缺陷的解决方案。AI 系统是高度字面化的执行者,它忠实地反映你输入意图的精确度或含糊度。AI 放大了我们已有的工程纪律——无论是严谨还是草率。

一个悄然的分野正在形成:

  • 一端,是把 AI 当作一个需要被精确约束、引导和验证的系统组件的工程师。他们利用 AI 作为杠杆,极大地提升了从设计到交付的效率和质量。
  • 另一端,则是过度依赖“一键生成”和“随缘调试”的开发者。他们发现自己陷入了无尽的修补工作,疲于应对 AI 生成的、那些“刚刚好能通过代码审查”却在生产环境中暴露出性能、安全或架构问题的代码。

这正是“代码优先”开发模式在 AI 时代遇到的困境。当我们把起点放在“如何写代码”时,我们已经把最关键的“做什么”和“为什么这么做”的过程交给了不可靠的直觉和临场发挥。

因此,一种新的工程范式正在浮出水面,它的核心不再是代码本身,而是代码背后的意图。这个新范式建立在三个坚实的支柱之上:

  1. 规格 (Specs):将系统的意图锚定在一个持久化的、无歧义的文档中,作为人与 AI 协作的唯一事实来源。
  2. 上下文 (Context):为 AI 提供精确的执行环境信息,包括相关的知识库、API 契约、设计约束和术语表,使其决策有据可依。
  3. 智能体 (Agents):在清晰的边界内自主执行任务的自动化单元,其行为被工具、权限和预设的禁止事项所约束,确保其不会“自由发挥”出范围。

这个从“代码优先”到“意图优先”的转变,并非要抛弃代码,而是将工程的重心前移——从关注实现细节,转向关注意图的精确表达、执行的有效约束和结果的可靠验证。这不仅是一种方法论,更是 AI 时代工程师的实战生存指南。

接下来的内容,我们将跳出纯粹的理论探讨,通过四个深入一线的真实研发场景,具体展示这套“意图驱动”的工程栈是如何在实践中运作的。

二、实战演练:四个案例看懂“意图驱动”工程

理论是灰色的,而生命之树常青。让我们深入四个典型的研发场景,看看“意图驱动”的工程范式如何从抽象理念落到实处。


案例一:推荐系统新增“冷启动召回”能力

背景与目标
一个成熟的短视频推荐系统,对于活跃用户已经有很好的推荐效果。但对于新用户(冷启动用户),由于缺乏行为数据,推荐内容相关性差,导致早期流失率偏高。目标是为推荐系统增加一个“冷启动召回”模块,当识别到用户为冷启动用户时,优先推荐近期热门、普适性高的内容,以提升早期用户留存率。

1. 锚定意图:SPEC.md

这是所有工作的起点。我们不再是口头传达或写一个模糊的需求文档,而是创建一个精确的、可被机器和人共同理解的规格文件。

# SPEC: Cold Start Recall Strategy for Recommendation System

## 1. Intent
This module aims to solve the "cold start" problem for new users of the recommendation system. When a user is identified as having insufficient interaction history, this strategy will be triggered to provide a set of high-quality, popular, and broadly appealing content. The core goal is to increase the Day-1 and Day-3 user retention rate by improving the initial content experience.

## 2. User Stories
- **As a new user**, when I first open the app, I want to see content that is generally interesting and popular, so that I can quickly find value and am motivated to continue exploring.
- **As a system operator**, I want to be able to configure the definition of a "cold start user" (e.g., registered within 24 hours and less than 5 interactions), so that I can adapt the strategy to different user growth phases.
- **As a system operator**, I want to be able to remotely update the pool of "popular content" without redeploying the service, so that the cold start content remains fresh and relevant.

## 3. Constraints & Non-Functional Requirements
- **Performance**: The latency of this recall strategy must not exceed 50ms (p99).
- **Data Source**: The popular content pool must be sourced from the `event-tracking-service` and processed by the `offline-data-pipeline`. The data schema is defined in `[doc/schema/popular_content.proto]`. Direct database access is forbidden.
- **Isolation**: This module must be implemented as an independent strategy within the `recall-service`. Its failure must not affect other recall strategies (e.g., collaborative filtering, deep learning models). A circuit breaker must be in place.
- **Scalability**: The system must support up to 1,000 QPS for cold start user requests.

## 4. Verification
- **Unit Test**: The user identification logic must have at least 95% test coverage.
- **Integration Test**: A test case must verify that when a user meets the cold start criteria, the returned content list is sourced from the designated popular content pool.
- **A/B Test**: An online A/B test will be conducted. The experimental group (with the cold start strategy) should show a statistically significant increase in Day-1 retention rate of at least 2% compared to the control group.
2. 供给养料:CONTEXT.md (或 CLAUDE.md)

这个文件是喂给 AI Agent 的“弹药”。它清晰地定义了 Agent 在执行任务时可以依赖的知识、工具和接口。

# CONTEXT: Environment for Cold Start Recall Module

## 1. Knowledge Sources
- **System Architecture**: The overall architecture of the recommendation system is detailed in `[doc/arch/recommendation_system.md]`. The `recall-service` is the entry point for all recall strategies.
- **Service API**: The gRPC interface for the `recall-service` is defined in `[api/recall_service.proto]`. The method to implement is `rpc GetColdStartCandidates(...)`.
- **Data Schema**: The data structure for the popular content pool is `PopularContentItem`, defined in `[doc/schema/popular_content.proto]`.
- **Coding Style**: All Go code must follow the guidelines outlined in `[CONTRIBUTING.md]` and be formatted with `gofmt`.

## 2. Interface Contracts
- **User Profile Service**: To get user registration time and interaction count, call `user-profile-service.GetUserProfile(userId)`. See `[api/user_profile.proto]`.
- **Popular Content Provider**: The popular content is stored in a Redis cache. The access library is available at `[internal/lib/popular_content_cache]`. Do not connect to Redis directly.

## 3. Terminology
- **Cold Start User**: A user registered within the last 24 hours with fewer than 5 meaningful interactions (like, share, comment).
- **Popular Content Pool**: A curated list of content items with high engagement metrics (e.g., completion rate, interaction rate) in the last 72 hours, updated every 4 hours.
3. 划定边界:AGENTS.md

这个文件像是给 AI Agent 的“紧箍咒”。它明确了 Agent 能做什么、不能做什么,以及最终需要交付什么。

# AGENTS: Configuration for Cold Start Module Implementation

## 1. Tool Boundary
- **Allowed Tools**:
  - `file_reader`: For reading files specified in the CONTEXT.
  - `code_writer`: For generating Go code.
  - `test_runner`: For executing unit and integration tests.
  - `linter`: For checking code style.
- **Tool Configuration**:
  - `code_writer` must place all new code within the `recall-service/strategy/cold_start/` directory.

## 2. Prohibitions
- **Forbidden Actions**:
  - Do not modify any files outside the `recall-service` directory.
  - Do not introduce new external dependencies without updating the `go.mod` file and getting human approval.
  - Do not implement any direct database or Redis connections. Use the provided library `internal/lib/popular_content_cache`.
  - Do not hardcode any business logic parameters (e.g., the "24 hours" or "5 interactions" thresholds). These must be loaded from the central configuration service.

## 3. Deliverables
- **Primary Deliverable**: A merge request containing the implementation of the `GetColdStartCandidates` gRPC method, along with corresponding unit and integration tests.
- **Secondary Deliverable**: A `README.md` file within the module directory explaining the configuration parameters and how to manually trigger a refresh of the popular content cache for testing purposes.
4. 建立反馈:运行时回路

交付不是结束,而是新一轮反馈的开始。

  • 度量 (Metrics):为冷启动策略的调用次数p99 延迟缓存命中率下游服务调用成功率建立 Grafana 监控仪表盘。
  • 告警 (Alerting):当策略延迟超过 80ms,或对 user-profile-service 的调用失败率连续 5 分钟超过 1% 时,通过 PagerDuty/Lark 发出告警。
  • 灰度与开关 (Canary & Feature Flag):新策略通过功能开关包裹。上线时,首先在 1% 的流量上开启(仅针对新注册用户),观察核心指标(如留存率、崩溃率)无负向影响后,逐步扩大流量至 100%。该开关必须能在 1 分钟内远程关闭。
  • 回滚策略 (Rollback Plan):如果出现严重问题(如导致推荐服务整体延迟飙升),立即关闭功能开关。如果问题与代码逻辑强相关,则触发自动化回滚流程,将 recall-service 部署回上一个稳定版本。

通过这样一套组合拳,我们把一个模糊的“优化新用户体验”需求,转化成了一个结构化、可控、可验证的工程任务。AI Agent 在这个框架内,不再是一个充满不确定性的“黑盒”,而是一个高效、可靠的“执行引擎”。它被精确的意图所引导,被丰富的上下文所滋养,被清晰的边界所约束,其产出最终被闭环的反馈系统所检验。


案例二:前端页面“白屏”线上诊断与修复

背景与目标
线上监控系统突然告警,核心的“商品详情页”在某些环境下(特别是 iOS 17.x + Chrome 浏览器)出现高概率的白屏问题。用户反馈激增,严重影响交易转化率。目标是快速诊断出问题根源,并提供一个安全的修复方案,尽快恢复线上服务。

这是一个被动的、救火式的场景,但“意图驱动”的思维同样适用,它能帮助我们在混乱中建立秩序。

1. 锚定意图:SPEC.md (诊断与修复版)

在这种紧急情况下,SPEC.md 的作用不是定义新功能,而是定义问题、约束修复范围和明确验证标准。它是一个动态的、由人类工程师主导创建的“战情板”。

# SPEC: Urgent - Blank Screen Diagnosis & Fix for Product Detail Page (PDP)

## 1. Intent
The primary intent is to diagnose the root cause of the blank screen issue occurring on the Product Detail Page (PDP) for users on iOS 17.x with Chrome browser. A secondary intent is to implement a minimal, safe, and immediate fix to restore page functionality. This is a "stop-the-bleeding" operation; major refactoring is out of scope.

## 2. Problem Hypothesis
- **H1: JS Bundle Loading Failure**. A specific JavaScript chunk might be failing to load or parse only on this environment combination.
- **H2: Rendering Error**. A recently deployed React component (`NewReviewComponent` was deployed 2 hours ago) might have a rendering issue specific to Chrome on iOS.
- **H3: API Data Format Incompatibility**. The data from `api/pdp/details` might have changed, causing a frontend parsing error that is not properly handled.

## 3. Constraints & Non-Functional Requirements
- **Scope of Fix**: The fix must be confined to the frontend codebase (`webapp-pdp` repository). No backend changes are permitted in this immediate action.
- **Safety**: The proposed fix must include a feature flag (`ENABLE_PDP_BLANK_SCREEN_FIX`). The fix will be rolled out to 0% of users initially and manually ramped up.
- **Performance**: The fix should not increase the Page Load Time by more than 5%.
- **Urgency**: A diagnosis report is expected within 30 minutes. A proposed fix (code + PR) is expected within 90 minutes.

## 4. Verification
- **Diagnosis Validation**: The root cause must be reproducible in a controlled environment (e.g., BrowserStack or a physical device). The Sentry error logs must correlate with the identified cause.
- **Fix Validation**:
  - The fix must resolve the blank screen issue on the target environment (iOS 17.x + Chrome).
  - It must not introduce any regressions on other major platforms (Desktop Chrome, Android Chrome, iOS Safari). A regression test suite must pass.
  - After the fix is deployed, the rate of "PDP Blank Screen" errors in Sentry must drop by at least 99%.
2. 供给养料:CONTEXT.md

为诊断 Agent 提供精准的工具和信息入口,是快速定位问题的关键。

# CONTEXT: Environment for PDP Blank Screen Diagnosis

## 1. Knowledge Sources
- **Deployment History**: The last 5 deployments to the `webapp-pdp` service are logged in `[CICD/deployment-logs.json]`. The latest deployment included changes for `TICKET-1234` (NewReviewComponent).
- **Monitoring Dashboards**:
  - Sentry Dashboard for Frontend Errors: `[link-to-sentry-pdp-errors]`
  - Grafana Dashboard for Page Performance: `[link-to-grafana-pdp-performance]`
- **Code Repository**: The relevant codebase is in the `webapp-pdp` Git repository. The component in question is located at `src/components/reviews/NewReviewComponent.tsx`.
- **On-call Handbook**: The troubleshooting guide for frontend issues is at `[doc/oncall/frontend_playbook.md]`.

## 2. Interface Contracts & Tools
- **Logging Tool**: Use the `sentry_cli` to query for errors. Example: `sentry_cli query --project webapp-pdp --environment production --query "release:1.2.5 AND browser.name:Chrome AND os.name:'iOS 17'"`
- **Live Debugging Tool**: An Agent with access to a BrowserStack/Playwright tool can be used to simulate the user environment. The tool wrapper is `[tools/browser_session.py]`.
- **Feature Flag Service**: The interface for creating and managing feature flags is `[internal/lib/feature_flags]`.

## 3. Terminology
- **PDP**: Product Detail Page.
- **Blank Screen Error**: Defined as a session where the user lands on the PDP URL, but the main React component (`PdpRoot`) fails to mount, and no critical content is rendered within 10 seconds.
3. 划定边界:AGENTS.md

这里的 Agent 更像是一个“诊断助理”,在人的指导下执行具体的信息收集和分析任务。

# AGENTS: Configuration for PDP Diagnosis Assistant

## 1. Tool Boundary
- **Allowed Tools**:
  - `sentry_cli`: To query and analyze error logs.
  - `git_reader`: To inspect recent code changes (`git log -p -S NewReviewComponent`).
  - `browser_session`: To attempt to reproduce the issue on BrowserStack.
- **Prohibitions**:
  - Do not execute any write operations on the codebase. This agent is for diagnosis only.
  - Do not make any changes to the production environment, including feature flags.

## (After Diagnosis - For Repair Agent)
## 1. Tool Boundary
- **Allowed Tools**: `code_writer`, `test_runner`, `feature_flag_cli`.
## 2. Prohibitions
- Do not introduce logic outside of the `NewReviewComponent.tsx` file or a new safe-guard component.
- The fix must be wrapped in the `ENABLE_PDP_BLANK_SCREEN_FIX` feature flag.

## 3. Deliverables
- **Phase 1 (Diagnosis)**: A summary report identifying the root cause, supported by Sentry logs and code snippets.
- **Phase 2 (Repair)**: A pull request with the proposed fix and passing regression tests.
4. 建立反馈:运行时回路

修复上线后的监控,是确保问题真正解决且没有引入新问题的关键。

  • 度量 (Metrics)
    • 核心指标:紧密监控 Sentry 中“PDP Blank Screen”错误的发生率,目标是降至接近于零。
    • 守护指标:监控 PDP 页面的加载时间LCP (Largest Contentful Paint)转化率以及 NewReviewComponent 组件的渲染成功率,确保修复没有带来负面影响。
  • 告警 (Alerting):为“PDP Blank Screen”错误率设置一个极低的告警阈值。同时,为新功能开关 ENABLE_PDP_BLANK_SCREEN_FIX 的流量比例设置一个变更告警,任何未经授权的调整都会触发通知。
  • 灰度与开关 (Canary & Feature Flag):修复上线后,首先只对内部测试账号开启功能开关 ENABLE_PDP_BLANK_SCREEN_FIX,验证无误后,再逐步放开到 1%, 10%, 50%, 100% 的受影响用户(iOS 17.x + Chrome)。
  • 回滚策略 (Rollback Plan):最快的回滚就是关闭功能开关。这可以在 1 分钟内将所有用户切回旧的、未经修复的逻辑(虽然有白屏风险,但影响范围可控)。如果修复本身导致了更严重的问题(例如全站崩溃),则立即触发代码库的回滚。

在这个场景中,“意图驱动”的框架将一场混乱的线上救火,变成了一次有组织、有纪律的“外科手术”。通过快速创建SPEC.md,我们为 AI 和人类工程师设定了共同的战场地图和作战目标。AI Agent 在严格的CONTEXTAGENTS约束下,高效地执行信息收集和初步修复,而人类则专注于最关键的决策:确认根因、评估修复方案的风险、控制发布节奏。这正是人机协作在复杂工程场景中最理想的模式。


案例三:数据导入管道吞吐扩容与幂等保障

背景与目标
一个数据导入服务(data-importer-service)负责接收业务方发送的用户行为日志,并将其写入 Kafka。随着业务量增长,该服务的处理吞吐量已接近瓶颈,高峰期出现消息积压和延迟。此外,由于业务方重试机制不完善,偶尔会发送重复消息,导致下游数据分析不准。目标是:1) 将服务的吞吐能力提升一倍;2) 为服务增加幂等性保障,确保重复消息在 1 小时内不会被重复写入。

1. 锚定意图:SPEC.md

对于这样一个涉及性能和可靠性的后端改造,SPEC.md 必须极其精确地定义非功能性指标和行为契约。

# SPEC: Throughput Scaling and Idempotency for data-importer-service

## 1. Intent
This project aims to refactor the `data-importer-service` to double its message processing throughput and introduce an idempotency layer to prevent duplicate message ingestion. This will solve the current performance bottlenecks and improve data quality for downstream consumers.

## 2. User Stories
- **As a data engineer**, I want the service to handle at least 20,000 messages per second (up from the current 10,000 mps) without the end-to-end latency exceeding 200ms, so that the data pipeline can keep up with business growth.
- **As a downstream data analyst**, I want to be confident that the data in the Kafka topic `user-behavior-logs` is free from duplicates caused by upstream retries within a 1-hour window, so that my analytical reports are accurate.
- **As an SRE**, I want the service's resource usage (CPU, memory) to remain stable and predictable after the refactoring, with CPU utilization staying below 70% under peak load.

## 3. Constraints & Non-Functional Requirements
- **Throughput**: Target throughput: 20,000 messages/sec.
- **Latency**: p99 latency from message reception to Kafka acknowledgement must be < 200ms.
- **Idempotency**:
  - A unique `message_id` from the incoming request payload must be used as the idempotency key.
  - The idempotency check must be effective for at least 1 hour.
  - A distributed cache (Redis) must be used for storing idempotency keys. The TTL for each key should be set to 1 hour.
- **Concurrency Model**: The existing single-goroutine processing model must be refactored to a worker pool model. The number of workers should be configurable.
- **Technology Stack**:
  - The service must remain in Go.
  - Use the standard `sarama` library for Kafka interaction.
  - Use the `go-redis` library for Redis interaction. No raw TCP connections.
- **Failure Mode**: If the Redis cache for idempotency is unavailable, the service should enter a "fail-open" mode (i.e., bypass the idempotency check) and raise a critical alert. This is to prioritize data availability over strict idempotency in case of a cache failure.

## 4. Verification
- **Load Test**: A load test environment must be set up. The service must sustain 20,000 mps for 30 minutes with latency and resource usage within the defined limits.
- **Idempotency Test**: An integration test must be written to send the same message twice within a few seconds. It must verify that the message is written to Kafka only once.
- **Failure Test**: A test must simulate Redis being unavailable and verify that the service continues to process messages and an alert is triggered.
- **Staged Rollout**: The new version will be deployed alongside the old one. Traffic will be gradually shifted from the old to the new deployment over 24 hours, closely monitoring performance and error metrics.
2. 供给养料:CONTEXT.md

为了让 AI Agent 能理解现有的架构并做出正确的改造,提供详细的“上下文”至关重要。

# CONTEXT: Environment for data-importer-service Refactoring

## 1. Knowledge Sources
- **Current Architecture**: The existing architecture and code structure are documented in `[doc/architecture/data_importer_v1.md]`. The core logic is in `main.go` which uses a single-threaded channel-based approach.
- **Codebase**: The full source code is in the `data-importer-service` repository.
- **Infrastructure Details**:
  - The service runs on a Kubernetes cluster. Resource limits are defined in `[k8s/deployment.yaml]`.
  - The Redis cluster connection string is available as the environment variable `REDIS_ADDR`.
  - The Kafka broker list is available as the environment variable `KAFKA_BROKERS`.
- **Best Practices**: The company's best practices for building high-throughput Go services are documented in `[engineering/best-practices/golang-high-performance.md]`.

## 2. Interface Contracts
- **Incoming Request**: The service exposes an HTTP endpoint that accepts a POST request with a JSON body. The schema is: `{"message_id": "string", "payload": "object"}`.
- **Kafka Producer**: The `sarama.AsyncProducer` is used. The configuration details are in `[internal/kafka/producer.go]`.
- **Redis Client**: A shared Redis client instance should be initialized at startup. See `[internal/redis/client.go]` for the standard setup.

## 3. Terminology
- **MPS**: Messages Per Second.
- **Idempotency Key**: The `message_id` field from the incoming JSON payload.
- **Worker Pool**: A concurrency pattern where a fixed number of goroutines (workers) pull tasks from a shared channel to process them in parallel.
3. 划定边界:AGENTS.md

这里的 AI Agent 被赋予了重构代码的权限,因此其边界和交付物必须被严格定义。

# AGENTS: Configuration for data-importer-service Refactoring Agent

## 1. Tool Boundary
- **Allowed Tools**: `code_reader`, `code_writer`, `test_runner`, `go_mod_updater`.
- **Tool Configuration**:
  - `code_writer` is permitted to refactor `main.go` and files within the `internal/` directory.
  - `go_mod_updater` can be used to add the `go-redis` dependency.

## 2. Prohibitions
- **Forbidden Actions**:
  - Do not change the public HTTP interface of the service.
  - Do not change the Kafka topic name (`user-behavior-logs`).
  - Do not use any third-party libraries for the worker pool implementation; use standard Go concurrency primitives (goroutines, channels).
  - Do not hardcode the worker pool size; it must be configurable via an environment variable `WORKER_COUNT`.

## 3. Deliverables
- **Primary Deliverable**: A pull request with the refactored Go code that implements the worker pool and idempotency logic.
- **Secondary Deliverables**:
  - Updated `k8s/deployment.yaml` with the new `WORKER_COUNT` environment variable.
  - A new load test script (`tests/load_test.js` using k6).
  - An updated `README.md` explaining the new architecture, configuration options, and performance metrics.
4. 建立反馈:运行时回路

对于这类基础服务,运行时的可观测性是生命线。

  • 度量 (Metrics)
    • 吞吐与延迟:在仪表盘上并排展示入口 QPSKafka 写入 RPS (Rate Per Second)端到端 p99 延迟
    • 幂等性:监控重复消息被拒绝的数量。这个指标的稳定增长(非零)是正常的,但突然的尖峰可能意味着上游系统存在问题。
    • 资源:监控每个 Pod 的 CPU 使用率内存使用量Goroutine 数量
    • 依赖:监控对 Redis 的调用延迟错误率
  • 告警 (Alerting)
    • 当“入口 QPS”与“Kafka 写入 RPS”的差距持续超过 5% 时,告警(可能消息积压)。
    • 当幂等性检查因为 Redis 故障而进入“fail-open”模式时,发出最高级别告警
    • 当 Goroutine 数量异常增长时,告警(可能存在协程泄漏)。
  • 灰度与开关 (Canary & Feature Flag):这次不是简单的功能开关,而是采用蓝绿部署金丝雀发布。例如,部署 data-importer-service-v2,然后通过调整上游负载均衡或服务网格(如 Istio)的权重,将 1% 的流量切到 v2。在 24 小时内,持续观察 v2 的各项指标是否优于或等于 v1,然后逐步增加流量权重,最终完全替代 v1。
  • 回滚策略 (Rollback Plan):如果 v2 版本在线上真实流量下表现出任何不稳定(如性能不达标、崩溃、数据错误),立即将流量 100% 切回 v1 版本。由于 v1 和 v2 并行运行,回滚只是一个流量切换操作,可以在一分钟内完成,风险极低。

这个案例展示了“意图驱动”范式如何处理复杂的后端重构。通过将性能指标、可靠性契约和技术约束预先置入 SPEC.mdCONTEXT.md,我们为 AI Agent 提供了一个清晰的“改造蓝图”,使其能够生成不仅在功能上正确,而且在架构和性能上都符合要求的代码。这远比让人和 AI 在一堆旧代码里反复拉扯、试错要高效和安全得多。


案例四:服务端接口“延迟超标”的定位与重构

背景与目标
核心服务 order-servicePOST /v1/orders/create 接口,其 p99 延迟在过去两周内从 150ms 缓慢上升至 450ms,已多次触发告警。该接口是用户下单的唯一入口,性能下降直接影响用户体验和商业成功率。目标是:1) 精准定位导致延迟增加的性能瓶颈;2) 对瓶颈代码进行重构,将接口 p99 延迟恢复到 200ms 以下。

1. 锚定意图:SPEC.md

性能优化任务的 SPEC.md 核心在于量化目标、划定改造范围、并明确性能度量的标准

# SPEC: Performance Optimization for create-order API

## 1. Intent
This project aims to diagnose and resolve the performance degradation of the `POST /v1/orders/create` endpoint in the `order-service`. The goal is to reduce the p99 latency back to under 200ms by identifying and refactoring the primary performance bottleneck.

## 2. Performance Target
- **Primary Metric**: p99 latency of `POST /v1/orders/create` must be <= 200ms under the production load profile.
- **Secondary Metric**: The success rate of the API must remain >= 99.99%. The CPU utilization of the `order-service` should not increase by more than 10% after the optimization.

## 3. Scope and Constraints
- **Analysis First**: No code changes are to be made until a performance analysis report, including a flame graph and data from profiling, is generated and approved by a human engineer. The report must pinpoint the function(s) contributing most to the latency.
- **Minimalist Refactoring**: The refactoring should be targeted and minimal, directly addressing the identified bottleneck. Broad, sweeping changes to the application's architecture are out of scope for this task.
- **No Interface Changes**: The public contract of the API (request/response schema) must not be changed.
- **Dependency Interaction**: The optimization should focus on the service's internal logic. If the bottleneck is identified as a slow downstream dependency (e.g., a slow SQL query or a call to another service), the immediate action is to optimize the interaction (e.g., add caching, switch to batching), not to refactor the downstream service itself.

## 4. Verification
- **Benchmark Test**: A pre-refactoring benchmark test must be created to replicate the current 450ms p99 latency. After refactoring, the same benchmark must show a p99 latency below 200ms.
- **Code Review**: The refactored code must be reviewed to ensure it doesn't introduce race conditions, deadlocks, or other concurrency issues.
- **Canary Release**: The optimized version will be deployed as a canary. Traffic will be gradually shifted, and a dashboard will compare the latency and error rates of the canary vs. the stable version in real-time.
2. 供给养料:CONTEXT.md

为 AI Agent 提供性能分析工具的入口和解读方法,是这个场景的关键。

# CONTEXT: Environment for order-service Performance Analysis

## 1. Knowledge Sources
- **Service Codebase**: The source code for `order-service` is available in the `order-service` repository. The controller logic for the endpoint is in `[src/controllers/order_controller.go]`.
- **Performance Monitoring**:
  - APM Tracing Dashboard (e.g., Jaeger/SkyWalking): `[link-to-apm-traces-for-create-order]`
  - Profiling Data Storage: Production profiles (CPU, memory, mutex) are periodically collected and stored in `[s3://profiling-data/order-service/]`.
- **Tooling Documentation**:
  - **Go Profiling**: How to generate and interpret Go profiles (`pprof`) is documented in `[engineering/docs/go-profiling.md]`.
  - **Flame Graphs**: The guide to generating flame graphs from `pprof` data is available at `[engineering/docs/flamegraphs.md]`.

## 2. Interface Contracts & Tools
- **Profiling Tool (`pprof`)**: The service exposes `pprof` endpoints at `/debug/pprof/`. An Agent can trigger a 30-second CPU profile using a tool wrapper: `profiler_cli collect --service order-service --type cpu --duration 30s`.
- **Analysis Tool**: The `go tool pprof` command can be used to analyze the collected profile. A common command for identifying hot spots is `go tool pprof -top [profile_file]`.
- **Visualization Tool**: A tool `flamegraph_generator` is available to convert a profile file into an SVG flame graph. `flamegraph_generator --input [profile_file] --output report.svg`.

## 3. Terminology
- **Flame Graph**: A visualization of profiled software, allowing the most frequent code-paths to be identified quickly and accurately.
- **Bottleneck**: A function or a piece of code that consumes a disproportionately large amount of resources (CPU time, memory) and limits the overall performance.
3. 划定边界:AGENTS.md

这个任务被清晰地分为两个阶段:诊断和重构。AI Agent 在每个阶段的角色和权限都不同。

# AGENTS: Configuration for order-service Optimization

## Phase 1: Diagnosis Agent
## 1. Tool Boundary
- **Allowed Tools**: `profiler_cli`, `go_tool_pprof_analyzer`, `flamegraph_generator`.
- **Prohibitions**:
  - No write access to any file. This is a read-only analysis phase.

## 2. Deliverables
- A performance analysis report in Markdown format, which must include:
  1. The SVG flame graph.
  2. The output of `go tool pprof -top`.
  3. A summary identifying the top 3 functions contributing to the latency, with a hypothesis on why they are slow.

---
## Phase 2: Refactoring Agent (Requires Human Approval to Start)
## 1. Tool Boundary
- **Allowed Tools**: `code_reader`, `code_writer`, `benchmark_runner`.
- **Prohibitions**:
  - Do not modify files outside of the functions identified in the diagnosis report.
  - Do not alter the API's request or response structure.
  - Do not introduce new libraries without human review.

## 2. Deliverables
- A pull request containing the refactored code.
- The PR description must include the "before" and "after" results from the benchmark test.
4. 建立反馈:运行时回路

性能优化的最终检验场永远是生产环境。

  • 度量 (Metrics)
    • A/B 比较仪表盘:创建一个 Grafana 仪表盘,并排显示金丝雀 (canary) 版本稳定 (stable) 版本的 p99/p95/p50 延迟、QPS 和错误率。这可以最直观地看到优化的效果。
    • 资源消耗:在同一个仪表盘上,比较两个版本的 CPU 和内存使用率。
    • 业务指标:监控订单创建的成功率转化率,确保性能优化没有以牺牲业务功能为代价。
  • 告警 (Alerting)
    • 为金丝雀版本的延迟或错误率设置比稳定版更灵敏的告警,一旦出现劣化立即通知。
    • 如果金丝雀版本的资源消耗超出预期(例如,CPU 飙升 30%),也需要告警。
  • 灰度与开关 (Canary & Feature Flag):这是典型的金丝雀发布场景。将优化后的新版本部署为一个独立的 deployment (canary)。通过服务网格或负载均衡器,先将 1% 的实时流量导入 canary。如果在一小时内,所有核心指标都优于或持平于 stable 版本,则逐步将流量增加到 5%, 20%, 50%,最终 100%。
  • 回滚策略 (Rollback Plan):如果 canary 版本在任何流量阶段表现出问题,最快的止损方法就是将导入 canary 的流量调回 0,所有用户将无缝切回 stable 版本。这使得回滚操作的风险和成本都降到了最低。

在这个案例中,我们再次看到了“意图驱动”框架如何将一个复杂的、探索性的任务(性能调优)变得结构化。我们没有让 AI 直接“修复性能问题”,而是引导它先成为一个“性能分析师”,使用 pprof 和火焰图等专业工具提交一份诊断报告。在人类确认了瓶颈之后,再授权 AI 切换为“外科医生”角色,在严格的范围内进行精确重构。整个过程由数据和度量驱动,每一步都可验证,每一步都可回滚。

三、结论:从执行者到设计者,重塑工程师的核心价值

这四个案例——从功能开发、线上救火,到后端重构和性能优化——共同指向了一个清晰的未来:在 AI 时代,工程师的核心竞争力正在从“写代码”本身,转移到更高维度的“设计系统意图”上。

我们不再是逐行编码的工匠,而是系统行为的设计师、AI 协作的指挥官和最终结果的验证者。我们的价值体现在:

  • 定义问题的能力:能否将一个模糊的业务需求,转化为一个精确、无歧义、可验证的 SPEC.md
  • 构建上下文的能力:能否为 AI 提供解决问题所需的所有“养料”,包括架构文档、接口契约、最佳实践和关键工具?
  • 设定边界的能力:能否为 AI Agent 划定清晰的工作范围和禁止事项,确保其在产生价值的同时不带来灾难?
  • 建立反馈闭环的能力:能否设计出覆盖从开发、测试到生产环境的完整度量和验证体系,确保系统的每一个变更都可观测、可控制、可回滚?

“意图驱动”的工程范式,正是支撑这种角色转变的基础设施。它要求我们回归工程的基本功:严谨的思考、清晰的沟通和对结果的敬畏

AI 并没有让工程纪律变得不重要,恰恰相反,它以前所未有的方式放大了纪律的价值。那些能够掌握“意图驱动”思想,并将其融入日常工作的团队,将在 AI 带来的新一轮生产力革命中获得决定性的优势。

而这场变革,现在才刚刚开始。是时候拿起“规格、上下文、智能体”这套新工具,重新审视和打磨我们手中的每一个项目了。

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐