Implementation Plan for Issue ${ISSUE_NUMBER}
2026/9/12 13:03:24 网站建设 项目流程

Implementation Plan for Issue #${ISSUE_NUMBER}

【免费下载链接】agentsMulti-harness agentic plugin marketplace for Claude Code, Codex, Cursor, OpenCode, GitHub Copilot, and Google Antigravity项目地址: https://gitcode.com/GitHub_Trending/agents24/agents

Phase 1: Foundation (Day 1)

  • Set up development environment
  • Create failing test cases
  • Implement data models/schemas
  • Add necessary migrations

Phase 2: Core Logic (Day 2)

  • Implement business logic
  • Add validation layers
  • Handle edge cases
  • Add logging and monitoring

Phase 3: Integration (Day 3)

  • Wire up API endpoints
  • Update frontend components
  • Add error handling
  • Implement retry logic

Phase 4: Testing & Polish (Day 4)

  • Complete unit test coverage
  • Add integration tests
  • Performance optimization
  • Documentation updates
注意 Phase 1 中 “Create failing test cases” 排在实现之前——这正是 TDD 的红灯阶段。四个阶段分别对应“打地基”“写核心”“做集成”“收尾打磨”,每个阶段的勾选项都可以直接转成任务看板条目。 ### 6.2 增量提交策略:一个子任务一个原子提交 ```bash # After each subtask completion git add -p # Partial staging for atomic commits git commit -m "feat(auth): add user validation schema (#${ISSUE_NUMBER})" git commit -m "test(auth): add unit tests for validation (#${ISSUE_NUMBER})" git commit -m "docs(auth): update API documentation (#${ISSUE_NUMBER})"

git add -p允许把同一个文件的不同 hunk 分开暂存,从而实现“逻辑上原子”的提交;提交信息使用 Conventional Commits 风格(feat/test/docs前缀),并在括号内标注受影响模块、在末尾用(#编号)关联 Issue——这样 GitHub 会自动把这些提交串到对应 Issue 的时间线上。

七、第五步:测试驱动开发(TDD)

7.1 单元测试(Jest 示例)

命令以“Issue #123 用户认证”为例,展示了 bug 修复型测试的标准写法:

// Jest example for bug fix describe("Issue #123: User authentication", () => { let authService; beforeEach(() => { authService = new AuthService(); jest.clearAllMocks(); }); test("should handle expired tokens gracefully", async () => { // Arrange const expiredToken = generateExpiredToken(); // Act const result = await authService.validateToken(expiredToken); // Assert expect(result.valid).toBe(false); expect(result.error).toBe("TOKEN_EXPIRED"); expect(mockLogger.warn).toHaveBeenCalledWith("Token validation failed", { reason: "expired", tokenId: expect.any(String), }); }); test("should refresh token automatically when near expiry", async () => { // Test implementation }); });

这个例子体现了三个值得吸收的测试技巧:

  • Arrange-Act-Assert 三段式:构造过期 token → 调用被测方法 → 断言返回结果。
  • 断言行为而不只断言返回值:除了检查result.valid === false,还断言了mockLogger.warn被以特定参数调用,把“副作用发生了”也纳入测试。
  • expect.any(String):对不确定具体值的字段用类型匹配器,避免脆弱断言。

7.2 集成测试(Pytest 示例)

# Pytest integration test import pytest from app import create_app from database import db class TestIssue123Integration: @pytest.fixture def client(self): app = create_app('testing') with app.test_client() as client: with app.app_context(): db.create_all() yield client db.drop_all() def test_full_authentication_flow(self, client): # Register user response = client.post('/api/register', json={ 'email': 'test@example.com', 'password': 'secure123' }) assert response.status_code == 201 # Login response = client.post('/api/login', json={ 'email': 'test@example.com', 'password': 'secure123' }) assert response.status_code == 200 token = response.json['access_token'] # Access protected resource response = client.get('/api/profile', headers={'Authorization': f'Bearer {token}'}) assert response.status_code == 200

fixture 中使用db.create_all()/db.drop_all()在每次测试前后重建数据库,保证测试彼此隔离;测试用例则完整走了一遍“注册 → 登录 → 携带 token 访问受保护资源”的真实业务流程。

7.3 端到端测试(Playwright 示例)

// Playwright E2E test import { test, expect } from "@playwright/test"; test.describe("Issue #123: Authentication Flow", () => { test("user can complete full authentication cycle", async ({ page }) => { // Navigate to login await page.goto("/login"); // Fill credentials await page.fill('[data-testid="email-input"]', "user@example.com"); await page.fill('[data-testid="password-input"]', "password123"); // Submit and wait for navigation await Promise.all([ page.waitForNavigation(), page.click('[data-testid="login-button"]'), ]); // Verify successful login await expect(page).toHaveURL("/dashboard"); await expect(page.locator('[data-testid="user-menu"]')).toBeVisible(); }); });

E2E 层的关键点是page.waitForNavigation()page.click()的并发等待——点击触发的导航可能因为异步渲染而在断言前尚未完成,Promise.all可以避免这类竞态导致的 flaky 测试。

八、第六步:代码实现模式(Code Implementation Patterns)

8.1 Bug 修复模式:修复前 vs 修复后

命令用“折扣计算”这个经典例子演示了修复的正确姿势:

// Before (buggy code) function calculateDiscount(price, discountPercent) { return price * discountPercent; // Bug: Missing division by 100 } // After (fixed code with validation) function calculateDiscount(price, discountPercent) { // Validate inputs if (typeof price !== "number" || price < 0) { throw new Error("Invalid price"); } if ( typeof discountPercent !== "number" || discountPercent < 0 || discountPercent > 100 ) { throw new Error("Invalid discount percentage"); } // Fix: Properly calculate discount const discount = price * (discountPercent / 100); // Return with proper rounding return Math.round(discount * 100) / 100; }

修复不是只补上“除以 100”这一处,而是同时补齐输入校验(类型与取值范围)与浮点舍入(保留两位小数)——这体现了“修复一次,顺带消除整类问题”的专业姿态。

8.2 功能实现模式:带架构的 Python 实现

# Implementing new feature with proper architecture from typing import Optional, List from dataclasses import dataclass from datetime import datetime @dataclass class FeatureConfig: """Configuration for Issue #123 feature""" enabled: bool = False rate_limit: int = 100 timeout_seconds: int = 30 class IssueFeatureService: """Service implementing Issue #123 requirements""" def __init__(self, config: FeatureConfig): self.config = config self._cache = {} self._metrics = MetricsCollector() async def process_request(self, request_data: dict) -> dict: """Main feature implementation""" # Check feature flag if not self.config.enabled: raise FeatureDisabledException("Feature #123 is disabled") # Rate limiting if not self._check_rate_limit(request_data['user_id']): raise RateLimitExceededException() try: # Core logic with instrumentation with self._metrics.timer('feature_123_processing'): result = await self._process_core(request_data) # Cache successful results self._cache[request_data['id']] = result # Log success logger.info(f"Successfully processed request for Issue #123", extra={'request_id': request_data['id']}) return result except Exception as e: # Error handling self._metrics.increment('feature_123_errors') logger.error(f"Error in Issue #123 processing: {str(e)}") raise

这个示例浓缩了一套生产级功能实现骨架:配置驱动FeatureConfigdataclass给出默认值)、特性开关enabled为 False 时直接拒绝)、限流保护(按 user_id 校验)、埋点与日志timer统计耗时、increment统计错误数、结构化日志携带request_id)、缓存成功结果,以及异常不吞掉(记录后raise重新抛出)。这些关注点与当前仓库中“production-ready”的实现理念一致——例如 plugins/team-collaboration/agents/dx-optimizer.md 中 DX 优化目标强调的可观测性与低摩擦开发流程。

九、第七步:Pull Request 创建(PR Creation)

9.1 提交前的自检清单

# Run all tests locally npm test -- --coverage npm run lint npm run type-check # Check for console logs and debug code git diff --staged | grep -E "console\.(log|debug)" # Verify no sensitive data git diff --staged | grep -E "(password|secret|token|key)" -i # Update documentation npm run docs:generate

准备阶段的四类检查:测试/静态检查(coverage、lint、type-check)、调试残留扫描(console.log/debug)、敏感信息扫描(password/secret/token/key)、文档同步。其中后两条直接作用于git diff --staged,把“要提交的内容”过滤一遍,防止密钥误入仓库。

9.2 用 GitHub CLI 创建高质量 PR

# Create PR with comprehensive description gh pr create \ --title "Fix #${ISSUE_NUMBER}: Clear description of the fix" \ --body "$(cat <<EOF ## Summary Fixes #${ISSUE_NUMBER} by implementing proper error handling in the authentication flow. ## Changes Made - Added validation for expired tokens - Implemented automatic token refresh - Added comprehensive error messages - Updated unit and integration tests ## Testing - [x] All existing tests pass - [x] Added new unit tests (coverage: 95%) - [x] Manual testing completed - [x] E2E tests updated and passing ## Performance Impact - No significant performance changes - Memory usage remains constant - API response time: ~50ms (unchanged) ## Screenshots/Demo [Include if UI changes] ## Checklist - [x] Code follows project style guidelines - [x] Self-review completed - [x] Documentation updated - [x] No new warnings introduced - [x] Breaking changes documented (if any) EOF )" \ --base main \ --head feature/issue-${ISSUE_NUMBER} \ --assignee @me \ --label "bug,needs-review"

一次gh pr create就完成了五件事:标题携带Fix #编号(GitHub 会自动关联 Issue)、正文用 here-doc 写入结构化模板、指定--base main--head分支、--assignee @me指派给自己、--label打上bug,needs-review标签。PR 描述里的 Checklist 全部预勾选,明确告知 reviewer “这些已经做了”。

这里也与本仓库的 plugins/git-pr-workflows/commands/pr-enhance.md 形成了互补:issue命令负责端到端解决 Issue,pr-enhance则专注于把已有 PR 的评审体验打磨到极致(自动生成变更摘要、风险评分、评审清单、超大 PR 拆分建议等)。

9.3 用 PR 模板自动关联 Issue

# .github/pull_request_template.md --- name: Pull Request about: Create a pull request to merge your changes --- ## Related Issue Closes #___ ## Type of Change - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] Documentation update ## How Has This Been Tested? <!-- Describe the tests that you ran --> ## Review Checklist - [ ] My code follows the style guidelines - [ ] I have performed a self-review - [ ] I have commented my code in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective - [ ] New and existing unit tests pass locally

Closes #___作为必填首字段,是让“PR 合并即自动关闭 Issue”的机制性保障——只要 PR 描述中包含Closes #<编号>,GitHub 在合并时会自动关闭对应 Issue 并留下关联记录。

十、第八步:实施后验证与 Issue 关闭协议(Post-Implementation Verification)

10.1 部署验证

# Check deployment status gh run list --workflow=deploy # Monitor for errors post-deployment curl -s https://api.example.com/health | jq . # Verify fix in production ./scripts/verify_issue_123_fix.sh # Check error rates gh api /repos/org/repo/issues/${ISSUE_NUMBER}/comments \ -f body="Fix deployed to production. Monitoring error rates..."

这组命令把“合并 PR”和“问题真正解决”区分开:用gh run list确认部署流水线跑完、用curl健康检查确认服务存活、用专门的验证脚本复现修复场景、最后用gh api在 Issue 上留一条“已部署、正在监控错误率”的评论,实现全链路留痕。

10.2 Issue 关闭协议

# Add resolution comment gh issue comment ${ISSUE_NUMBER} \ --body "Fixed in PR #${PR_NUMBER}. The issue was caused by improper token validation. Solution implements proper expiry checking with automatic refresh." # Close with reference gh issue close ${ISSUE_NUMBER} \ --comment "Resolved via #${PR_NUMBER}"

关闭 Issue 不是简单点一下按钮:先评论根因与修复方案(让未来检索到该 Issue 的人立刻明白前因后果),再用--comment "Resolved via #${PR_NUMBER}"关闭并留下指向 PR 的引用。这种“关闭即留痕”的做法,让 Issue 从“待办”变成“可检索的知识资产”。

十一、三个完整参考示例

示例 1:生产环境严重 bug 修复(P0 Hotfix 全流程)

目标:修复影响所有用户的认证故障。

# 1. Immediate triage gh issue view 456 --comments # Severity: P0 - All users unable to login # 2. Create hotfix branch git checkout -b hotfix/issue-456-auth-failure # 3. Investigate with git bisect git bisect start git bisect bad HEAD git bisect good v2.1.0 # Found: Commit abc123 introduced the regression # 4. Implement fix with test echo 'test("validates token expiry correctly", () => { const token = { exp: Date.now() / 1000 - 100 }; expect(isTokenValid(token)).toBe(false); });' >> auth.test.js # 5. Fix the code echo 'function isTokenValid(token) { return token && token.exp > Date.now() / 1000; }' >> auth.js # 6. Create and merge PR gh pr create --title "Hotfix #456: Fix token validation logic" \ --body "Critical fix for authentication failure" \ --label "hotfix,priority:critical"

这个示例把整条方法论压缩成了一个可照抄的最小闭环:分诊确认 P0 → 建 hotfix 分支 → bisect 定位到abc123引入回归 → 先写失败测试(exp已过期时应判定无效)→ 修复实现(校验exp是否大于当前时间戳)→ 创建带关键标签的 PR。其中Date.now() / 1000是 Unix 秒级时间戳的取法,与 JWT 中exp的标准单位一致。

示例 2:带子任务的功能实现

目标:实现用户资料自定义功能。

# Task breakdown in issue comment """ Implementation Plan for #789: 1. Database schema updates 2. API endpoint creation 3. Frontend components 4. Testing and documentation """ # Phase 1: Schema class UserProfile(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) theme = db.Column(db.String(50), default='light') language = db.Column(db.String(10), default='en') timezone = db.Column(db.String(50)) # Phase 2: API Implementation @app.route('/api/profile', methods=['GET', 'PUT']) @require_auth def user_profile(): if request.method == 'GET': profile = UserProfile.query.filter_by( user_id=current_user.id ).first_or_404() return jsonify(profile.to_dict()) elif request.method == 'PUT': profile = UserProfile.query.filter_by( user_id=current_user.id ).first_or_404() data = request.get_json() profile.theme = data.get('theme', profile.theme) profile.language = data.get('language', profile.language) profile.timezone = data.get('timezone', profile.timezone) db.session.commit() return jsonify(profile.to_dict()) # Phase 3: Comprehensive testing def test_profile_update(): response = client.put('/api/profile', json={'theme': 'dark'}, headers=auth_headers) assert response.status_code == 200 assert response.json['theme'] == 'dark'

示例展示了功能型 Issue 的分层落地:先建数据模型(带默认值的theme/language、可空timezone),再实现 GET/PUT 端点(first_or_404保证不存在时报 404,data.get(key, 现值)实现字段级部分更新),最后补上对“更新主题色”的断言测试。@require_auth装饰器把鉴权横切到端点之上。

示例 3:复杂性能问题调查与修复

目标:解决慢查询性能问题。

-- 1. Identify slow query from issue report EXPLAIN ANALYZE SELECT u.*, COUNT(o.id) as order_count FROM users u LEFT JOIN orders o ON u.id = o.user_id WHERE u.created_at > '2024-01-01' GROUP BY u.id; -- Execution Time: 3500ms -- 2. Create optimized index CREATE INDEX idx_users_created_orders ON users(created_at) INCLUDE (id); CREATE INDEX idx_orders_user_lookup ON orders(user_id); -- 3. Verify improvement -- Execution Time: 45ms (98% improvement)
// 4. Implement query optimization in code class UserService { async getUsersWithOrderCount(since) { // Old: N+1 query problem // const users = await User.findAll({ where: { createdAt: { [Op.gt]: since }}}); // for (const user of users) { // user.orderCount = await Order.count({ where: { userId: user.id }}); // } // New: Single optimized query const result = await sequelize.query( ` SELECT u.*, COUNT(o.id) as order_count FROM users u LEFT JOIN orders o ON u.id = o.user_id WHERE u.created_at > :since GROUP BY u.id `, { replacements: { since }, type: QueryTypes.SELECT, }, ); return result; } }

这条调查链路很有代表性:先用EXPLAIN ANALYZE量化慢查询(3500ms),再通过建索引优化执行计划(降到 45ms),最后在代码层根治 N+1 问题——旧实现“查用户再循环数订单”会产生 N+1 次查询,新实现用一条带LEFT JOIN+GROUP BY的聚合查询替代。注意索引 SQL 中的INCLUDE (id)是覆盖索引语法,用于让索引本身包含所需列、避免回表。

十二、交付物清单与成功标准(Output Format & Success Criteria)

命令要求在 Issue 解决成功后,交付一份完整的结构化总结:

  1. Resolution Summary:对根因与修复方案的清晰说明
  2. Code Changes:所有修改文件的链接与说明
  3. Test Results:覆盖率报告与测试执行摘要
  4. Pull Request:已创建的 PR 链接(带 Issue 关联)
  5. Verification Steps:供 QA / 评审者复现验证的步骤
  6. Documentation Updates:对 README、API 文档或 wiki 的改动
  7. Performance Impact:如适用,提供修复前后的指标对比
  8. Rollback Plan:上线后出问题时的回滚步骤

与之对应的成功标准(Success Criteria)是:

  • Issue 被彻底调查,根因得到确认
  • 修复实现具备全面的测试覆盖
  • 按团队规范创建 PR
  • 所有 CI/CD 检查通过
  • Issue 被正确关闭并引用 PR
  • 知识被沉淀,可供未来参考

十三、小结:把一次 Issue 修复变成可复用的知识资产

从 plugins/team-collaboration/commands/issue.md 的定义可以看出,/team-collaboration:issue不只是“修 bug 的提示词”,而是一套可执行、可验收、可沉淀的工程方法论。它与同插件的 plugins/team-collaboration/agents/dx-optimizer.md(负责降低团队摩擦、优化开发体验)、plugins/team-collaboration/commands/standup-notes.md(负责站会与协作透明度)共同构成“团队协作”闭环:一边把 Issue 高效转化为合入的代码,一边让进展与知识在团队内可见。

在运用这套流程时,需要留意命令文档中反复强调的前提:ghCLI 需要先完成认证并具备目标仓库权限;git bisect依赖一个能自动判定好坏的测试脚本;各语言测试示例(Jest / Pytest / Playwright)需要对应测试框架已配置。把该命令接入日常开发时,建议搭配 docs/usage.md 中的命令调用规范,以及 docs/architecture.md 中的插件设计原则(单一职责、可组合、上下文高效)来理解其定位。安装与使用方式回顾:

# 安装插件(含 agents、commands、skills) /plugin marketplace add wshobson/agents /plugin install team-collaboration # 调用 Issue 解析命令 /team-collaboration:issue 456 /team-collaboration:issue https://github.com/org/repo/issues/456

【免费下载链接】agentsMulti-harness agentic plugin marketplace for Claude Code, Codex, Cursor, OpenCode, GitHub Copilot, and Google Antigravity项目地址: https://gitcode.com/GitHub_Trending/agents24/agents

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询