mcpField
J
jira:work

jira:work

github.com/thelobbiAgent 工作流210 次安装1 天前更新
代码仓库

关于 jira:work

面向编码任务的 Jira 工作编排技能,结合问题澄清、分级执行、并行 Agent、缓存和提前退出。它按任务复杂度选择 FAST、STANDARD 或 FULL 流程,并包含更新 Jira 状态、登记工时、提交代码和关联 PR 的操作。

主要功能

  1. 01先收集澄清问题
  2. 02选择 FAST、STANDARD 或 FULL 分级
  3. 03并行执行工作流阶段
  4. 04缓存 Jira 和 Confluence 查询
  5. 05应用提前退出与恢复步骤
  6. 06更新 Jira 状态、工时记录和关联

适用场景

  1. 01实施小型文档或配置改动
  2. 02处理涉及多个文件的错误修复或小功能
  3. 03协调架构或安全工作的分析与实现
  4. 04创建提交并将 PR 关联到 Jira 问题

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/thelobbi/claude --skill jira:work

安装后在 Claude Code 中输入/jira:work确认已加载。

详细介绍

Jira 工作编排 v5.1(优化版)

高性能工作流,具备智能问题收集、分层执行、缓存和最大限度并行化。

v5.1 的主要功能:

  • ❓ 问题优先协议 - 开始前提出所有澄清问题
  • ⚡ 3 个执行层级: FAST(3-4 个 Agent)| STANDARD(6-8 个)| FULL(10-12 个)
  • 🚀 提速 40%: 尽可能并行执行阶段
  • 💾 缓存层: 对 Jira/Confluence 查询结果进行记忆化缓存
  • 🎯 智能门控: 5 个门控 → 3 组并行门控
  • 🔀 提前退出: 对简单变更跳过不必要的阶段

阶段 0:问题收集(强制)

开始任何工作之前,Claude 必须通过提问收集充分的上下文。

QUESTION-GATHERING PROTOCOL:
═════════════════════════════════════════════════════════════════════════
  ┌─────────────────────────────────────────────────────────────────────┐
  │  STEP 1: Initial Analysis (~30 seconds)                             │
  │  ─────────────────────────────────────────                          │
  │  • Parse Jira issue description                                     │
  │  • Identify ambiguous requirements                                  │
  │  • Detect missing technical details                                 │
  │  • Check for undefined acceptance criteria                          │
  └─────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
  ┌─────────────────────────────────────────────────────────────────────┐
  │  STEP 2: Generate Question Categories                               │
  │  ────────────────────────────────────                               │
  │                                                                      │
  │  📋 REQUIREMENTS QUESTIONS                                          │
  │     • What is the expected behavior?                                │
  │     • What are the acceptance criteria?                             │
  │     • Are there edge cases to consider?                             │
  │     • What should happen on errors?                                 │
  │                                                                      │
  │  🔧 TECHNICAL QUESTIONS                                             │
  │     • Which components/files are affected?                          │
  │     • Are there existing patterns to follow?                        │
  │     • What dependencies are involved?                               │
  │     • Are there performance requirements?                           │
  │                                                                      │
  │  🎨 DESIGN QUESTIONS                                                │
  │     • UI/UX requirements (if applicable)?                           │
  │     • API contract expectations?                                    │
  │     • Database schema changes needed?                               │
  │                                                                      │
  │  ⚠️ RISK QUESTIONS                                                  │
  │     • Rollback strategy if something goes wrong?                    │
  │     • Testing requirements?                                         │
  │     • Security considerations?                                      │
  │                                                                      │
  │  🔗 DEPENDENCY QUESTIONS                                            │
  │     • Are there blocking issues?                                    │
  │     • External team dependencies?                                   │
  │     • Timeline constraints?                                         │
  └─────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
  ┌─────────────────────────────────────────────────────────────────────┐
  │  STEP 3: Present Questions & Wait for Answers                       │
  │  ────────────────────────────────────────────                       │
  │  • Present grouped questions clearly                                │
  │  • Wait for user responses                                          │
  │  • Ask follow-up questions if needed                                │
  │  • Confirm understanding before proceeding                          │
  └─────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
  ┌─────────────────────────────────────────────────────────────────────┐
  │  STEP 4: Confirmation                                               │
  │  ────────────────────                                               │
  │  "Based on your answers, here's my understanding:                   │
  │   [Summary of requirements]                                         │
  │                                                                      │
  │   Is this correct? Should I proceed with implementation?"           │
  └─────────────────────────────────────────────────────────────────────┘
═════════════════════════════════════════════════════════════════════════
按层级划分的问题类别
层级最少问题数重点领域
FAST1-2仅确认(“只是更新 X,对吗?”)
STANDARD3-5需求、受影响的文件、测试方法
FULL5-10完整技术规格、架构、安全、回滚
智能生成问题
interface QuestionContext {
  issueKey: string;
  issueType: string;
  description: string;
  acceptanceCriteria: string[];
  labels: string[];
  components: string[];
}

function generateQuestions(context: QuestionContext): Question[] {
  const questions: Question[] = [];

  // Requirements gaps
  if (!context.acceptanceCriteria?.length) {
    questions.push({
      category: 'requirements',
      priority: 'high',
      question: 'What are the acceptance criteria for this issue?'
    });
  }

  // Technical ambiguity
  if (context.description.includes('should') || context.description.includes('might')) {
    questions.push({
      category: 'technical',
      priority: 'medium',
      question: 'The description mentions "should/might" - is this optional or required behavior?'
    });
  }

  // Error handling
  if (context.issueType === 'Story' && !context.description.includes('error')) {
    questions.push({
      category: 'requirements',
      priority: 'medium',
      question: 'How should the system handle error cases?'
    });
  }

  // Testing strategy
  if (!context.labels.includes('tested') && !context.labels.includes('no-tests')) {
    questions.push({
      category: 'technical',
      priority: 'low',
      question: 'What level of test coverage is expected?'
    });
  }

  // Security implications
  if (detectSecurityKeywords(context.description)) {
    questions.push({
      category: 'security',
      priority: 'high',
      question: 'Are there specific security requirements or compliance needs?'
    });
  }

  return questions;
}

// Example question output
const exampleQuestions = `
Before I start working on ${issueKey}, I have a few questions:

**Requirements:**
1. The description mentions "user authentication" - should this support both email/password and OAuth, or just one?
2. What should happen if a user's session expires mid-action?

**Technical:**
3. Should I follow the existing auth patterns in src/auth/, or is there a new approach you prefer?
4. Are there specific performance requirements (e.g., max auth latency)?

**Testing:**
5. Should I add integration tests with the OAuth provider, or mock those?

Please answer these questions and I'll proceed with implementation.
`;
跳过条件(仅限 FAST 层级)

只有满足以下所有条件时,才可以跳过提问:

  • 问题类型为:Bug、子任务或文档
  • 描述非常具体(少于 50 个词)
  • 验收标准定义明确
  • 明确提到了需要更改的文件
  • 未检测到安全影响
function shouldSkipQuestions(context: QuestionContext): boolean {
  const skipTypes = ['Bug', 'Sub-task', 'Documentation', 'Task'];
  const hasSpecificDescription = context.description.split(' ').length < 50;
  const hasClearAC = context.acceptanceCriteria.length >= 2;
  const hasFilesMentioned = /\.(ts|js|py|go|java|rb)/.test(context.description);
  const noSecurityImplications = !detectSecurityKeywords(context.description);

  return (
    skipTypes.includes(context.issueType) &&
    hasSpecificDescription &&
    hasClearAC &&
    hasFilesMentioned &&
    noSecurityImplications
  );
}

快速开始

/jira:work <issue-key> [--tier=auto|fast|standard|full] [--skip-questions]

注意: --skip-questions 仅适用于 FAST 层级和简单变更。

层级自动选择逻辑
FAST:     docs-only | config | typo | readme | 1-2 files
STANDARD: bug-fix | minor-feature | refactor | 3-10 files
FULL:     major-feature | architectural | security | 10+ files

优化后的架构(v5.1)

┌─────────────────────────────────────────────────────────────────────────┐
│           JIRA WORK ORCHESTRATOR v5.1 - QUESTION-FIRST EXECUTION         │
│                    ⚡ Optimized for Speed ⚡                              │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                          │
│  ┌────────────────────────────────────────────────────────────────┐    │
│  │ TIER SELECTOR (runs first, ~500ms)                              │    │
│  │  Analyze: issue type, labels, files, complexity → select tier   │    │
│  └────────────────────────────────────────────────────────────────┘    │
│                              │                                          │
│            ┌─────────────────┼─────────────────┐                       │
│            ▼                 ▼                 ▼                       │
│     ┌──────────┐      ┌──────────┐      ┌──────────┐                  │
│     │   FAST   │      │ STANDARD │      │   FULL   │                  │
│     │ 3-4 agnt │      │ 6-8 agnt │      │10-12 agnt│                  │
│     │ ~2 min   │      │ ~5 min   │      │ ~10 min  │                  │
│     └──────────┘      └──────────┘      └──────────┘                  │
│                                                                          │
│  ═══════════════════════════════════════════════════════════════════   │
│                                                                          │
│                        PARALLEL EXECUTION LANES                          │
│  ┌──────────────────────────────────────────────────────────────────┐  │
│  │ LANE 1: CODE PATH          │ LANE 2: CONTEXT (cached)            │  │
│  │ ─────────────────          │ ─────────────────────               │  │
│  │ [EXPLORE]──▶[PLAN]──▶     │ [JIRA]──▶[CONFLUENCE]               │  │
│  │      │           │         │    │          │                     │  │
│  │      ▼           ▼         │    ▼          ▼                     │  │
│  │    [CODE]──▶[TEST+QG]     │ [CACHE]    [CACHE]                  │  │
│  │         \       /          │                                      │  │
│  │          ▼     ▼           │                                      │  │
│  │         [COMMIT]           │                                      │  │
│  └──────────────────────────────────────────────────────────────────┘  │
│                                                                          │
│  ═══════════════════════════════════════════════════════════════════   │
│                                                                          │
│  GATE GROUPS (Parallel)                                                  │
│  ┌───────────────┐ ┌───────────────┐ ┌───────────────┐               │
│  │   GROUP 1     │ │   GROUP 2     │ │   GROUP 3     │               │
│  │ LINT+FORMAT   │ │ SECURITY+DEPS │ │ COVERAGE+CMPLX│               │
│  │   (haiku)     │ │   (haiku)     │ │   (sonnet)    │               │
│  └───────────────┘ └───────────────┘ └───────────────┘               │
│                                                                          │
└─────────────────────────────────────────────────────────────────────────┘

分层执行模式

FAST 模式(3-4 个 Agent,约 2 分钟)

适用场景: 文档、配置、拼写错误、README、涉及 1-2 个文件的变更

// Single consolidated agent for FAST mode
Task({
  subagent_type: "general-purpose",
  model: "haiku",
  prompt: `FAST MODE: Complete ${issueKey} end-to-end:
    1. Quick context from Jira (cached if available)
    2. Make the simple change
    3. Run lint + format (auto-fix)
    4. Commit and push

    Skip: Full exploration, coverage check, complexity analysis
    Output: { completed: true, files: [], commitSha: string }`
});

// Parallel: Basic quality check
Task({
  subagent_type: "general-purpose",
  model: "haiku",
  prompt: "Lint check only: npx eslint --fix && npx prettier --write"
});

提前退出条件:

  • 无代码变更(仅文档)→ 跳过所有质量门控
  • 仅配置变更 → 跳过覆盖率和复杂度检查
  • README/拼写错误 → 跳过除提交以外的所有步骤

STANDARD 模式(6-8 个 Agent,约 5 分钟)

适用场景: Bug 修复、小型功能、重构、涉及 3-10 个文件

PARALLEL EXECUTION GRAPH:
═════════════════════════════════════════════════════════════
  ┌─────────────────────────────────────────────────────────┐
  │  WAVE 1 (Parallel Launch - 3 agents)                    │
  │  ┌───────────┐  ┌───────────┐  ┌───────────────────┐   │
  │  │  EXPLORE  │  │   JIRA    │  │  CONFLUENCE CACHE │   │
  │  │  (haiku)  │  │  (cached) │  │     (cached)      │   │
  │  └─────┬─────┘  └─────┬─────┘  └─────────┬─────────┘   │
  │        └──────────────┼──────────────────┘              │
  │                       ▼                                  │
  │  ┌─────────────────────────────────────────────────────┐ │
  │  │  WAVE 2: PLAN+CODE (1 consolidated agent)           │ │
  │  │  - Receive context from Wave 1                      │ │
  │  │  - Plan inline (no separate planning agent)         │ │
  │  │  - Execute code changes                             │ │
  │  └─────────────────────────────────────────────────────┘ │
  │                       ▼                                  │
  │  ┌─────────────────────────────────────────────────────┐ │
  │  │  WAVE 3: TEST + QUALITY (3 parallel gate groups)    │ │
  │  │  ┌─────────┐  ┌─────────────┐  ┌─────────────────┐ │ │
  │  │  │LINT+FMT │  │SECURITY+DEPS│  │COVERAGE+COMPLEX │ │ │
  │  │  │ (haiku) │  │   (haiku)   │  │    (sonnet)     │ │ │
  │  │  └─────────┘  └─────────────┘  └─────────────────┘ │ │
  │  └─────────────────────────────────────────────────────┘ │
  │                       ▼                                  │
  │  ┌─────────────────────────────────────────────────────┐ │
  │  │  WAVE 4: COMMIT (1 agent, includes PR)              │ │
  │  └─────────────────────────────────────────────────────┘ │
  └─────────────────────────────────────────────────────────┘
═════════════════════════════════════════════════════════════
// WAVE 1: Parallel context gathering (with cache)
const [exploreResult, jiraContext, confluenceContext] = await Promise.all([
  Task({
    subagent_type: "Explore",
    model: "haiku",
    prompt: `Quick codebase analysis for ${issueKey}:
      - Identify affected files (Glob/Grep)
      - Find test files
      - Map immediate dependencies`
  }),
  getCached('jira', issueKey) || Task({
    subagent_type: "general-purpose",
    model: "haiku",
    prompt: `Fetch and cache Jira issue ${issueKey}`
  }),
  getCached('confluence', issueKey) || Task({
    subagent_type: "general-purpose",
    model: "haiku",
    prompt: "Search Confluence for related docs (cache result)"
  })
]);

// WAVE 2: Consolidated Plan+Code (single agent, inline planning)
const codeResult = await Task({
  subagent_type: "general-purpose",
  model: "sonnet",
  prompt: `Implement ${issueKey} with inline planning:
    Context: ${JSON.stringify({ exploreResult, jiraContext })}

    1. [INLINE PLAN] Quick design decisions (no separate agent)
    2. [CODE] Implement changes following plan
    3. Output: { files: [], plan: string, summary: string }`
});

// WAVE 3: 3 Gate Groups in Parallel (consolidates 5 gates)
const [lintGate, securityGate, coverageGate] = await Promise.all([
  // Group 1: Lint + Format (combines Static Analysis)
  Task({
    subagent_type: "general-purpose",
    model: "haiku",
    prompt: `GATE GROUP 1 - LINT+FORMAT:
      - ESLint with --fix
      - Prettier with --write
      Output: { passed: boolean, issues: [], autoFixed: number }`
  }),

  // Group 2: Security + Dependencies (combines 2 gates)
  Task({
    subagent_type: "general-purpose",
    model: "haiku",
    prompt: `GATE GROUP 2 - SECURITY+DEPS:
      - gitleaks (secrets)
      - npm audit (vulnerabilities)
      - Check for outdated critical deps
      Output: { passed: boolean, vulns: [], outdated: [] }`
  }),

  // Group 3: Coverage + Complexity (requires more analysis)
  Task({
    subagent_type: "general-purpose",
    model: "sonnet",
    prompt: `GATE GROUP 3 - COVERAGE+COMPLEXITY:
      - Run tests with coverage (threshold: 80%)
      - Check cyclomatic complexity (max: 10)
      - Identify complex functions
      Output: { passed: boolean, coverage: number, complexity: [] }`
  })
]);

// WAVE 4: Commit + PR (single agent)
await Task({
  subagent_type: "general-purpose",
  model: "sonnet",
  prompt: `Complete ${issueKey}:
    Quality: ${JSON.stringify({ lintGate, securityGate, coverageGate })}
    1. Commit with smart message
    2. Push to feature branch
    3. Create PR with quality report
    4. Link to Jira
    Output: { commitSha, prUrl, jiraLinked }`
});

FULL 模式(10-12 个 Agent,约 10 分钟)

适用场景: 重大功能、架构变更、安全关键变更

FULL MODE EXECUTION:
═════════════════════════════════════════════════════════════
  WAVE 1: Deep Analysis (4 parallel agents)
  ├── EXPLORE: Deep codebase analysis
  ├── JIRA: Full issue context + linked issues
  ├── CONFLUENCE: Architecture docs, ADRs
  └── SECURITY-PRE: Pre-implementation security review

  WAVE 2: Architecture Planning (2 agents)
  ├── PLAN: Detailed implementation plan with DAG
  └── TEST-PLAN: Test strategy and scenarios

  WAVE 3: Implementation (2-4 agents based on subtasks)
  └── CODE: Parallel subtask execution

  WAVE 4: Comprehensive Quality (3 gate groups + deep security)
  ├── LINT+FORMAT
  ├── SECURITY+DEPS (with SAST)
  ├── COVERAGE+COMPLEXITY
  └── DEEP-SECURITY: Full vulnerability analysis

  WAVE 5: Finalization (2 agents)
  ├── COMMIT: Smart commit + PR
  └── DOCUMENT: Confluence tech doc generation
═════════════════════════════════════════════════════════════

缓存层(v5.0 新增)

interface WorkflowCache {
  jira: Map<string, JiraIssue>;      // TTL: 5 minutes
  confluence: Map<string, Page[]>;    // TTL: 10 minutes
  fileAnalysis: Map<string, Analysis>; // TTL: until file modified
  gateResults: Map<string, GateResult>; // TTL: until code changed
}

// Cache-aware fetch pattern
async function getCached<T>(type: keyof WorkflowCache, key: string): Promise<T | null> {
  const cache = workflowCache[type];
  const entry = cache.get(key);

  if (entry && !isExpired(entry)) {
    return entry.value;
  }
  return null; // Cache miss - will fetch fresh
}

// Pre-warm cache at session start
async function prewarmCache(issueKey: string): Promise<void> {
  // Parallel cache warming (runs during tier selection)
  await Promise.all([
    fetchAndCache('jira', issueKey),
    fetchAndCache('confluence', getProjectKey(issueKey))
  ]);
}

缓存优势:

  • 重新处理同一问题:提速 50%(Jira/Confluence 已缓存)
  • 同一会话处理多个问题:提速 30%(共享项目上下文)
  • 文件未更改:跳过重复分析

提前退出优化

// Tier determines which gates can be skipped
const earlyExitRules = {
  FAST: {
    skip: ['coverage', 'complexity', 'deepSecurity', 'confluence-doc'],
    require: ['lint']
  },
  STANDARD: {
    skip: ['deepSecurity', 'confluence-doc'],
    require: ['lint', 'security', 'coverage']
  },
  FULL: {
    skip: [],
    require: ['all']
  }
};

// File-type based skips
const fileTypeSkips = {
  'docs': ['coverage', 'complexity'],  // .md, .txt, .rst
  'config': ['coverage'],               // .json, .yaml, .toml
  'test': ['complexity']                // *.test.*, *.spec.*
};

// Apply early exit logic
function shouldSkipGate(gate: string, tier: Tier, files: string[]): boolean {
  // Check tier rules
  if (earlyExitRules[tier].skip.includes(gate)) return true;

  // Check file-type rules
  const fileTypes = detectFileTypes(files);
  if (fileTypes.every(ft => fileTypeSkips[ft]?.includes(gate))) return true;

  return false;
}

失败恢复与上下文优化(v5.0)

目的: 避免 Agent 在难以找到答案或搜索失败时浪费上下文。

搜索超时限制
const SEARCH_LIMITS = {
  // Maximum attempts before giving up
  maxSearchAttempts: 3,

  // Time limits per search type
  timeouts: {
    glob: 5000,        // 5 seconds
    grep: 10000,       // 10 seconds
    explore: 30000,    // 30 seconds
    jiraFetch: 10000,  // 10 seconds
    confluence: 15000  // 15 seconds
  },

  // Context budget per phase (tokens)
  contextBudget: {
    EXPLORE: 5000,
    PLAN: 3000,
    CODE: 15000,
    TEST: 5000,
    QUALITY: 3000,
    FIX: 8000,
    COMMIT: 2000
  }
};
负缓存(失败搜索记忆化)
interface NegativeCache {
  failedSearches: Map<string, {
    query: string;
    timestamp: number;
    reason: string;
    ttl: number;  // Don't retry for this duration
  }>;
}

// Prevent repeating failed searches
async function searchWithNegativeCache(query: string, searchFn: () => Promise<any>): Promise<any> {
  const cacheKey = hashQuery(query);
  const cached = negativeCache.get(cacheKey);

  if (cached && !isExpired(cached)) {
    // Return early with fallback instead of re-trying
    return {
      found: false,
      reason: cached.reason,
      suggestion: 'Try alternative search pattern'
    };
  }

  try {
    const result = await withTimeout(searchFn(), SEARCH_LIMITS.timeouts.grep);
    return result;
  } catch (error) {
    // Cache the failure to prevent retry storms
    negativeCache.set(cacheKey, {
      query,
      timestamp: Date.now(),
      reason: error.message,
      ttl: 5 * 60 * 1000  // Don't retry for 5 minutes
    });
    throw error;
  }
}
上下文检查点
interface PhaseCheckpoint {
  phase: string;
  issueKey: string;
  timestamp: string;
  artifacts: {
    filesIdentified: string[];
    planSummary?: string;
    codeChanges?: string[];
    testResults?: any;
    qualityScore?: number;
  };
  contextUsed: number;  // Tokens consumed
  canResume: boolean;
}

// Checkpoint after each phase to prevent re-work
async function checkpointPhase(phase: string, result: any): Promise<void> {
  const checkpoint: PhaseCheckpoint = {
    phase,
    issueKey: currentIssue,
    timestamp: new Date().toISOString(),
    artifacts: extractArtifacts(result),
    contextUsed: estimateTokens(result),
    canResume: true
  };

  // Save to session storage (survives agent restarts)
  await sessionStorage.set(`checkpoint:${currentIssue}:${phase}`, checkpoint);
}

// Resume from last checkpoint if context was lost
async function resumeFromCheckpoint(issueKey: string): Promise<PhaseCheckpoint | null> {
  const phases = ['COMMIT', 'FIX', 'QUALITY', 'TEST', 'CODE', 'PLAN', 'EXPLORE'];

  for (const phase of phases) {
    const checkpoint = await sessionStorage.get(`checkpoint:${issueKey}:${phase}`);
    if (checkpoint?.canResume) {
      return checkpoint;  // Resume from most recent valid checkpoint
    }
  }
  return null;
}
升级处理模式
STRUGGLE DETECTION & ESCALATION:
═════════════════════════════════════════════════════════════════════════
  ┌─────────────────────────────────────────────────────────────────────┐
  │  LEVEL 1: Agent Self-Recovery (automatic)                          │
  │  ─────────────────────────────────────────                          │
  │  • 3 search attempts with query refinement                          │
  │  • Broaden search pattern on failure                                │
  │  • Try alternative file patterns                                    │
  │  • Timeout: 30 seconds total                                        │
  └───────────────────────────┬─────────────────────────────────────────┘
                              │ (if still failing)
                              ▼
  ┌─────────────────────────────────────────────────────────────────────┐
  │  LEVEL 2: Strategy Pivot (automatic)                               │
  │  ─────────────────────────────────                                  │
  │  • Switch from Grep to Glob (or vice versa)                         │
  │  • Use Task(Explore) agent for deeper search                        │
  │  • Check registry for known patterns                                │
  │  • Consult project structure cache                                  │
  └───────────────────────────┬─────────────────────────────────────────┘
                              │ (if still failing)
                              ▼
  ┌─────────────────────────────────────────────────────────────────────┐
  │  LEVEL 3: Graceful Degradation (automatic)                         │
  │  ─────────────────────────────────────────                          │
  │  • Proceed with partial context                                     │
  │  • Log what's missing for manual review                             │
  │  • Mark result as "low confidence"                                  │
  │  • Add TODO comments for missing context                            │
  └───────────────────────────┬─────────────────────────────────────────┘
                              │ (if critical blocker)
                              ▼
  ┌─────────────────────────────────────────────────────────────────────┐
  │  LEVEL 4: Human Escalation (requires intervention)                 │
  │  ───────────────────────────────────────────────                    │
  │  • Pause workflow with clear status                                 │
  │  • Present what was tried and what failed                           │
  │  • Request specific information needed                              │
  │  • Checkpoint state for resume after input                          │
  └─────────────────────────────────────────────────────────────────────┘
═════════════════════════════════════════════════════════════════════════
重试预算与熔断器
interface RetryBudget {
  maxRetries: number;
  currentRetries: number;
  backoffMs: number[];
  circuitOpen: boolean;
  lastFailure?: Date;
}

const retryBudgets: Record<string, RetryBudget> = {
  jiraApi: { maxRetries: 3, currentRetries: 0, backoffMs: [1000, 2000, 4000], circuitOpen: false },
  confluence: { maxRetries: 2, currentRetries: 0, backoffMs: [2000, 5000], circuitOpen: false },
  githubApi: { maxRetries: 3, currentRetries: 0, backoffMs: [1000, 2000, 4000], circuitOpen: false },
  codeSearch: { maxRetries: 3, currentRetries: 0, backoffMs: [500, 1000, 2000], circuitOpen: false }
};

// Circuit breaker pattern
async function withCircuitBreaker<T>(
  service: string,
  operation: () => Promise<T>
): Promise<T | null> {
  const budget = retryBudgets[service];

  // Check if circuit is open (too many recent failures)
  if (budget.circuitOpen) {
    const timeSinceFailure = Date.now() - (budget.lastFailure?.getTime() || 0);
    if (timeSinceFailure < 60000) {  // 1 minute cooldown
      return null;  // Skip this service, use fallback
    }
    budget.circuitOpen = false;  // Reset circuit
  }

  for (let attempt = 0; attempt < budget.maxRetries; attempt++) {
    try {
      const result = await operation();
      budget.currentRetries = 0;  // Reset on success
      return result;
    } catch (error) {
      budget.currentRetries++;
      budget.lastFailure = new Date();

      if (attempt < budget.maxRetries - 1) {
        await sleep(budget.backoffMs[attempt]);
      }
    }
  }

  // Open circuit after exhausting retries
  budget.circuitOpen = true;
  return null;
}
回退策略
const FALLBACK_STRATEGIES = {
  // When Jira API fails
  jiraUnavailable: {
    action: 'useLocalContext',
    steps: [
      'Parse issue key from branch name',
      'Extract context from commit messages',
      'Use cached issue data if available',
      'Proceed with minimal context, mark as draft'
    ]
  },

  // When Confluence search fails
  confluenceUnavailable: {
    action: 'skipDocumentation',
    steps: [
      'Skip Confluence search in EXPLORE',
      'Skip doc generation in COMMIT',
      'Add TODO for manual documentation',
      'Continue with code-only workflow'
    ]
  },

  // When codebase search fails
  searchFailed: {
    action: 'broaden',
    steps: [
      'Try parent directory',
      'Use simpler glob pattern (*.ts instead of **/*.service.ts)',
      'Search by keyword instead of path',
      'Fall back to git log for file history'
    ]
  },

  // When quality gates timeout
  gateTimeout: {
    action: 'partialCheck',
    steps: [
      'Run only fast gates (lint, format)',
      'Skip slow gates (coverage, complexity)',
      'Mark PR as "needs-full-review"',
      'Schedule async quality check'
    ]
  }
};

// Apply fallback when primary strategy fails
async function withFallback<T>(
  primary: () => Promise<T>,
  fallbackKey: keyof typeof FALLBACK_STRATEGIES,
  fallbackFn: () => Promise<T>
): Promise<{ result: T; usedFallback: boolean }> {
  try {
    const result = await withTimeout(primary(), 30000);
    return { result, usedFallback: false };
  } catch (error) {
    console.log(`Primary failed, using fallback: ${fallbackKey}`);
    const result = await fallbackFn();
    return { result, usedFallback: true };
  }
}
上下文预算强制执行
// Track context usage per phase
class ContextBudgetTracker {
  private usage: Map<string, number> = new Map();
  private readonly totalBudget = 100000;  // tokens

  consume(phase: string, tokens: number): boolean {
    const current = this.usage.get(phase) || 0;
    const phaseBudget = SEARCH_LIMITS.contextBudget[phase];

    if (current + tokens > phaseBudget) {
      console.warn(`Phase ${phase} exceeding budget: ${current + tokens}/${phaseBudget}`);
      return false;  // Deny consumption
    }

    this.usage.set(phase, current + tokens);
    return true;
  }

  getRemaining(): number {
    const used = Array.from(this.usage.values()).reduce((a, b) => a + b, 0);
    return this.totalBudget - used;
  }

  shouldCheckpoint(): boolean {
    return this.getRemaining() < 25000;  // 25% remaining
  }

  shouldCompress(): boolean {
    return this.getRemaining() < 10000;  // 10% remaining
  }
}

// Enforce budget during agent execution
const budgetTracker = new ContextBudgetTracker();

async function executeWithBudget(phase: string, operation: () => Promise<any>): Promise<any> {
  if (budgetTracker.shouldCheckpoint()) {
    await checkpointPhase(phase, { partial: true });
  }

  if (budgetTracker.shouldCompress()) {
    await compressContext();  // Summarize and discard old messages
  }

  const result = await operation();
  budgetTracker.consume(phase, estimateTokens(result));
  return result;
}
摘要:快速缓解措施参考
问题检测方式缓解措施
搜索耗时过长30 秒后超时扩大匹配模式,尝试其他方案
同一搜索反复失败命中负缓存使用回退方案跳过,不要重试
上下文即将耗尽预算跟踪器创建检查点并压缩上下文
API 持续失败熔断器已打开使用缓存数据或跳过
Agent 陷入循环重试次数 > 3升级给人工处理
阶段未完成缺少产物从检查点恢复
结果置信度低使用了回退方案标记以供审查,并添加 TODO

子 Agent 通信协议

消息格式
interface AgentMessage {
  id: string;
  from: string;        // Agent identifier
  to: string;          // Target agent or "orchestrator"
  phase: string;       // Current workflow phase
  type: "result" | "request" | "error" | "status";
  payload: any;
  timestamp: string;
}
结果交接模式
// Phase N agent completes and reports
const phaseResult = {
  phase: "CODE",
  status: "complete",
  artifacts: {
    filesModified: ["src/api/handler.ts", "src/utils/parser.ts"],
    linesAdded: 245,
    linesRemoved: 12
  },
  nextPhaseInput: {
    filesToTest: ["src/api/handler.ts"],
    coverageTargets: ["handler", "parser"]
  }
};

// Orchestrator receives and forwards to Phase N+1
orchestrator.handoff("TEST", phaseResult.nextPhaseInput);
错误升级处理
// Agent encounters blocking error
if (error.severity === "critical") {
  return {
    type: "error",
    escalate: true,
    message: "Security vulnerability detected - blocking commit",
    requiresHumanReview: true
  };
}

Agent 注册表(优化版 v5.0)

FAST 模式(3-4 个 Agent)
阶段Agent模型用途
1fast-implementerhaiku端到端:获取→编码→提交
1lint-gatehaiku快速检查 + 格式化(并行)
2*fix-agentsonnet仅在检查失败时运行
STANDARD 模式(6-8 个 Agent)
阶段Agent模型用途
1explore-agenthaiku代码库分析
1jira-fetchhaiku问题上下文(已缓存)
1confluence-fetchhaiku文档搜索(已缓存)
2plan-code-agentsonnet整合计划 + 实施
3lint-format-gatehaiku检查组 1
3security-deps-gatehaiku检查组 2
3coverage-complex-gatesonnet检查组 3
4commit-pr-agentsonnet提交 + PR + Jira 链接
FULL 模式(10-12 个 Agent)
阶段Agent模型用途
1deep-exploresonnet全面的代码库分析
1jira-fullhaiku问题 + 关联问题
1confluence-archsonnet架构文档、ADR
1security-presonnet实施前安全审查
2architect-planneropus详细实施计划
2test-strategistsonnet测试规划和场景
3code-agent (x2-4)sonnet并行实施子任务
4gate-group-1haiku检查 + 格式化
4gate-group-2haiku安全 + 依赖项
4gate-group-3sonnet覆盖率 + 复杂度
4deep-securitysonnet完整 SAST 分析
5commit-pr-agentsonnet智能提交 + 全面的 PR
5confluence-docsonnet生成技术文档

性能对比

┌────────────────────────────────────────────────────────────────┐
│              v4.2 vs v5.0 PERFORMANCE COMPARISON               │
├────────────────────────────────────────────────────────────────┤
│                                                                 │
│  AGENT COUNT REDUCTION                                          │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ v4.2: 13-18 agents (all tasks)                           │  │
│  │ v5.0: 3-4 (FAST) | 6-8 (STANDARD) | 10-12 (FULL)        │  │
│  │                                                           │  │
│  │ Average reduction: 40% fewer agents                       │  │
│  └──────────────────────────────────────────────────────────┘  │
│                                                                 │
│  EXECUTION TIME                                                 │
│  ┌────────────────────────────────────────────────────────┐    │
│  │         v4.2          │         v5.0                   │    │
│  ├───────────────────────┼────────────────────────────────┤    │
│  │ Simple bug: ~8 min    │ FAST: ~2 min (-75%)           │    │
│  │ Feature: ~12 min      │ STANDARD: ~5 min (-58%)       │    │
│  │ Major: ~15 min        │ FULL: ~10 min (-33%)          │    │
│  └────────────────────────────────────────────────────────┘    │
│                                                                 │
│  GATE CONSOLIDATION                                             │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ v4.2: 5 separate gates (5 agents)                        │  │
│  │ v5.0: 3 gate groups (3 agents, parallel)                 │  │
│  │                                                           │  │
│  │ Group 1: Static Analysis + Formatting                    │  │
│  │ Group 2: Security Scanner + Dependency Health            │  │
│  │ Group 3: Test Coverage + Complexity Analyzer             │  │
│  └──────────────────────────────────────────────────────────┘  │
│                                                                 │
│  CACHING BENEFITS                                               │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ Same issue re-run: 50% faster                            │  │
│  │ Same session/project: 30% faster                         │  │
│  │ Unchanged files: Skip redundant analysis                 │  │
│  └──────────────────────────────────────────────────────────┘  │
│                                                                 │
│  COST REDUCTION (API calls)                                     │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ FAST mode: ~70% fewer API calls                          │  │
│  │ STANDARD mode: ~45% fewer API calls                      │  │
│  │ haiku preference: Lower cost per agent                   │  │
│  └──────────────────────────────────────────────────────────┘  │
│                                                                 │
└────────────────────────────────────────────────────────────────┘

每次运行的 Agent 总数(v5.0):

  • FAST:3-4 个 Agent
  • STANDARD:6-8 个 Agent
  • FULL:10-12 个 Agent

与 v4.2 对比: 所有任务类型原本需要 13-18 个 Agent

Jira 集成

此命令会自动:

  • 将问题转换为“In Progress”状态
  • 添加进度评论
  • 记录工作时间
  • 创建智能提交
  • 将 PR 关联到问题

Confluence 集成(高级)

该工作流与 Confluence 集成,用于处理文档:

自动生成文档
// After successful commit, generate Confluence page
Task({
  subagent_type: "general-purpose",
  model: "sonnet",
  prompt: `Create Confluence documentation for ${issueKey}:
    1. Generate technical design document
    2. Document API changes (if any)
    3. Create/update runbook entries
    4. Add architecture diagrams (mermaid)

    Use mcp__MCP_DOCKER__confluence_create_page`
});
使用的 Confluence 功能
功能用途触发条件
页面创建自动创建技术文档COMMIT 阶段之后
页面更新更新现有文档页面已存在时
搜索在 EXPLORE 阶段查找相关文档mcp__MCP_DOCKER__confluence_search
附件质量报告、图表QUALITY 阶段之后
标签对文档进行分类自动添加标签
插入宏嵌入 Jira 问题、代码块技术文档
文档模板
// Technical Design Document Template
const techDocTemplate = {
  title: `[${issueKey}] Technical Design - ${summary}`,
  space: projectSpace,
  labels: ["tech-doc", "auto-generated", projectKey],
  sections: [
    "Overview", "Problem Statement", "Solution Architecture",
    "API Changes", "Database Changes", "Testing Strategy",
    "Quality Metrics", "Deployment Notes"
  ]
};
EXPLORE 阶段中的 Confluence 搜索
// Search for related documentation
Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: `Search Confluence for context:
    Use mcp__MCP_DOCKER__confluence_search with query "${issueKey} OR ${component}"
    1. Find related architecture docs
    2. Locate existing runbooks
    3. Check for similar implementations
    4. Gather ADRs (Architecture Decision Records)`
});

GitHub 集成(高级)

该工作流与 GitHub 深度集成:

分支策略
// Create feature branch with Jira issue key
Task({
  subagent_type: "general-purpose",
  model: "haiku",
  prompt: `Create feature branch:
    git checkout -b feature/${issueKey.toLowerCase()}-${slugify(summary)}
    git push -u origin feature/${issueKey}-description`
});
拉取请求功能
// Create PR with full quality integration
Task({
  subagent_type: "general-purpose",
  model: "sonnet",
  prompt: `Create comprehensive PR for ${issueKey}:

    1. Create PR: gh pr create --title "${issueKey}: ${summary}"
    2. Add quality report to description
    3. Add labels: gh pr edit --add-label "quality-passed"
    4. Request reviewers: gh pr edit --add-reviewer "@team/code-owners"
    5. Link to Jira in description
    6. Post status check via gh api`
});
使用的 GitHub 功能
功能用途命令
创建分支功能分支git checkout -b
创建 PR附带质量报告gh pr create
状态检查质量门状态gh api /statuses
标签对 PR 进行分类gh pr edit --add-label
审查者自动分配gh pr edit --add-reviewer
项目在看板中跟踪gh project item-add
Actions触发工作流gh workflow run
发布版本自动生成说明gh release create
GitHub Actions 集成
// Trigger quality workflow on PR
Task({
  subagent_type: "general-purpose",
  model: "haiku",
  prompt: `Trigger GitHub Actions workflow:
    gh workflow run quality-gates.yml \\
      --ref feature/${issueKey} \\
      -f issue_key=${issueKey}`
});
带质量报告的 PR 描述
## Summary
${summary}

**Jira Issue:** [${issueKey}](https://jira.company.com/browse/${issueKey})

## Quality Report
| Gate | Score | Status |
|------|-------|--------|
| Static Analysis | ${staticScore} | ${staticStatus} |
| Test Coverage | ${coverage}% | ${coverageStatus} |
| Security | ${securityScore} | ${securityStatus} |
| Complexity | ${complexityScore} | ${complexityStatus} |
| Dependencies | ${depsScore} | ${depsStatus} |

**Overall:** ${qualityScore}/100 (Grade: ${grade})

## Confluence Docs
- [Technical Design](${confluenceLink})
GitHub 提交状态 API
// Post quality results as commit status
Task({
  subagent_type: "general-purpose",
  model: "haiku",
  prompt: `Update GitHub commit status:
    gh api --method POST /repos/{owner}/{repo}/statuses/{sha} \\
      -f state="${allPassed ? 'success' : 'failure'}" \\
      -f description="Quality Score: ${qualityScore}/100" \\
      -f context="quality-gates/curator"`
});

完整工作流集成图

┌─────────────────────────────────────────────────────────────────────────────┐
│                         JIRA WORK ORCHESTRATOR v4.2.0                        │
│              Integrated with Confluence, GitHub, and Curator                 │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│  ┌───────────┐                                                               │
│  │   JIRA    │◀──────────────────────────────────────────────────────────┐  │
│  │  Arbiter  │                                                            │  │
│  └─────┬─────┘                                                            │  │
│        │                                                                   │  │
│        ▼                                                                   │  │
│  ┌───────────────────────────────────────────────────────────────────┐   │  │
│  │  PHASE 1: EXPLORE                                                  │   │  │
│  │  ┌──────────┐    ┌──────────────┐    ┌──────────────┐            │   │  │
│  │  │ Jira API │    │  Confluence  │    │   Codebase   │            │   │  │
│  │  │  Fetch   │    │   Search     │    │   Analysis   │            │   │  │
│  │  └──────────┘    └──────────────┘    └──────────────┘            │   │  │
│  └───────────────────────────────────────────────────────────────────┘   │  │
│        │                                                                   │  │
│        ▼                                                                   │  │
│  ┌───────────────────────────────────────────────────────────────────┐   │  │
│  │  PHASE 2-4: PLAN → CODE → TEST                                    │   │  │
│  └───────────────────────────────────────────────────────────────────┘   │  │
│        │                                                                   │  │
│        ▼                                                                   │  │
│  ┌───────────────────────────────────────────────────────────────────┐   │  │
│  │  PHASE 5: QUALITY GATES (Curator)                                 │   │  │
│  │  ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐         │   │  │
│  │  │ Static │ │Coverage│ │Security│ │Complex │ │  Deps  │         │   │  │
│  │  └────────┘ └────────┘ └────────┘ └────────┘ └────────┘         │   │  │
│  └───────────────────────────────────────────────────────────────────┘   │  │
│        │                                                                   │  │
│        ▼                                                                   │  │
│  ┌───────────────────────────────────────────────────────────────────┐   │  │
│  │  PHASE 6-7: FIX → COMMIT                                          │   │  │
│  │  ┌──────────────┐    ┌───────────────────────────────────────┐   │   │  │
│  │  │  Auto-Fix    │    │          GitHub Integration           │   │   │  │
│  │  │   Agent      │───▶│  Branch → Commit → PR → Status Check  │   │   │  │
│  │  └──────────────┘    └───────────────────────────────────────┘   │   │  │
│  └───────────────────────────────────────────────────────────────────┘   │  │
│        │                                                                   │  │
│        ▼                                                                   │  │
│  ┌───────────────────────────────────────────────────────────────────┐   │  │
│  │  POST-COMMIT: Documentation                                        │───┘  │
│  │  ┌──────────────────┐    ┌──────────────────┐                     │      │
│  │  │    Confluence    │    │      Jira        │                     │      │
│  │  │  - Tech Docs     │    │  - Comment       │                     │      │
│  │  │  - Runbooks      │    │  - Link PR       │                     │      │
│  │  └──────────────────┘    └──────────────────┘                     │      │
│  └───────────────────────────────────────────────────────────────────┘      │
│                                                                              │
└──────────────────────────────────────────────────────────────────────────────┘

相关命令

Jira 命令
  • /jira:status - 检查当前工作会话状态
  • /jira:sync - 将更改与 Jira 同步
  • /jira:pr - 创建拉取请求
  • /jira:commit - 创建智能提交
Confluence 命令
  • /confluence-publish - 将技术文档发布到 Confluence
  • /atlassian-sync - 与 Jira/Confluence 同步
GitHub 命令
  • 通过 gh cli 创建 PR 并附上质量报告
  • 通过 gh api 更新提交状态
  • 通过 gh workflow run 触发工作流
质量门禁命令(来自 Curator)
  • /quality-check - 运行全部 5 项质量门禁
  • /quality-fix - 尽可能自动修复问题
  • /coverage-check - 检查测试覆盖率(最低 80%)
  • /security-scan - 执行安全漏洞扫描
  • /complexity-audit - 检查代码复杂度
  • /dependency-audit - 检查依赖项健康状况

质量门禁阈值

门禁指标阈值
静态分析错误0
测试覆盖率行覆盖率≥ 80%
安全扫描器严重/高危 CVE0
复杂度圈复杂度≤ 10
复杂度认知复杂度≤ 15
依赖项严重漏洞0

评论

支持 Markdown