Refactor agent configurations and context gathering processes across multiple workflow tools

- Removed agent references in context-gather and test-context-gather commands for clarity.
- Updated test-task-generate to streamline agent configuration references.
- Enhanced action-planning-agent documentation by removing redundant examples.
- Adjusted execute command to eliminate direct agent path references.
- Improved context-gather documentation to clarify agent autonomy and project.json integration.
- Revised test-context-gather to focus on agent delegation and coverage analysis.
- Cleaned up test-task-generate to focus on task generation rules without direct agent references.
- Implemented automatic agent assignment based on exploration file names in deep analysis phase.
- Expanded project exploration phase to include intelligent angle selection based on software type.
- Enhanced output schemas and success criteria for exploration tasks to ensure clarity and completeness.
This commit is contained in:
catlog22
2025-12-26 16:20:46 +08:00
parent a5ba7c0f6c
commit c8a914aeca
15 changed files with 751 additions and 106 deletions

View File

@@ -410,7 +410,6 @@ Task(subagent_type="{meta.agent}",
1. Read complete task JSON: {session.task_json_path}
2. Load context package: {session.context_package_path}
Follow complete execution guidelines in @.claude/agents/{meta.agent}.md
**Session Paths**:
- Workflow Dir: {session.workflow_dir}

View File

@@ -15,7 +15,6 @@ allowed-tools: Task(*), Read(*), Glob(*)
Orchestrator command that invokes `context-search-agent` to gather comprehensive project context for implementation planning. Generates standardized `context-package.json` with codebase analysis, dependencies, and conflict detection.
**Agent**: `context-search-agent` (`.claude/agents/context-search-agent.md`)
## Core Philosophy
@@ -431,6 +430,5 @@ if (historicalConflicts.length > 0 && currentRisk === "low") {
- **Detection-first**: Always check for existing package before invoking agent
- **Project.json integration**: Agent reads `.workflow/project.json` as primary source for project context, avoiding redundant analysis
- **Agent autonomy**: Agent handles all discovery logic per `.claude/agents/context-search-agent.md`
- **No redundancy**: This command is a thin orchestrator, all logic in agent
- **Plan-specific**: Use this for implementation planning; brainstorm mode uses direct agent call

View File

@@ -239,15 +239,6 @@ If conflict_risk was medium/high, modifications have been applied to:
**Agent Configuration Reference**: All TDD task generation rules, quantification requirements, Red-Green-Refactor cycle structure, quality standards, and execution details are defined in action-planning-agent.
Refer to: @.claude/agents/action-planning-agent.md for:
- TDD Task Decomposition Standards
- Red-Green-Refactor Cycle Requirements
- Quantification Requirements (MANDATORY)
- 5-Field Task JSON Schema
- IMPL_PLAN.md Structure (TDD variant)
- TODO_LIST.md Format
- TDD Execution Flow & Quality Validation
### TDD-Specific Requirements Summary
#### Task Structure Philosophy

View File

@@ -14,7 +14,7 @@ allowed-tools: Task(*), Read(*), Glob(*)
Orchestrator command that invokes `test-context-search-agent` to gather comprehensive test coverage context for test generation workflows. Generates standardized `test-context-package.json` with coverage analysis, framework detection, and source implementation context.
**Agent**: `test-context-search-agent` (`.claude/agents/test-context-search-agent.md`)
## Core Philosophy
@@ -89,7 +89,6 @@ Task(
run_in_background=false,
description="Gather test coverage context",
prompt=`
You are executing as test-context-search-agent (.claude/agents/test-context-search-agent.md).
## Execution Mode
**PLAN MODE** (Comprehensive) - Full Phase 1-3 execution
@@ -229,7 +228,7 @@ Refer to `test-context-search-agent.md` Phase 3.2 for complete `test-context-pac
## Notes
- **Detection-first**: Always check for existing test-context-package before invoking agent
- **Agent autonomy**: Agent handles all coverage analysis logic per `.claude/agents/test-context-search-agent.md`
- **No redundancy**: This command is a thin orchestrator, all logic in agent
- **Framework agnostic**: Supports Jest, Mocha, pytest, RSpec, Go testing, etc.
- **Coverage focus**: Primary goal is identifying implementation files without tests

View File

@@ -107,8 +107,6 @@ CRITICAL:
- Follow the progressive loading strategy defined in your agent specification (load context incrementally from memory-first approach)
## AGENT CONFIGURATION REFERENCE
All test task generation rules, schemas, and quality standards are defined in your agent specification:
@.claude/agents/action-planning-agent.md
Refer to your specification for:
- Test Task JSON Schema (6-field structure with test-specific metadata)

View File

@@ -806,8 +806,6 @@ Use `analysis_results.complexity` or task count to determine structure:
**Examples**:
- GOOD: `"Implement 5 commands: [cmd1, cmd2, cmd3, cmd4, cmd5]"`
- BAD: `"Implement new commands"`
- GOOD: `"5 files created: verify by ls .claude/commands/*.md | wc -l = 5"`
- BAD: `"All commands implemented successfully"`
### 3.2 Planning & Organization Standards

View File

@@ -400,7 +400,7 @@ Task(subagent_type="{meta.agent}",
1. Read complete task JSON: {session.task_json_path}
2. Load context package: {session.context_package_path}
Follow complete execution guidelines in @.claude/agents/{meta.agent}.md
**Session Paths**:
- Workflow Dir: {session.workflow_dir}

View File

@@ -15,7 +15,6 @@ allowed-tools: Task(*), Read(*), Glob(*)
Orchestrator command that invokes `context-search-agent` to gather comprehensive project context for implementation planning. Generates standardized `context-package.json` with codebase analysis, dependencies, and conflict detection.
**Agent**: `context-search-agent` (`.claude/agents/context-search-agent.md`)
## Core Philosophy
@@ -429,6 +428,6 @@ if (historicalConflicts.length > 0 && currentRisk === "low") {
- **Detection-first**: Always check for existing package before invoking agent
- **Project.json integration**: Agent reads `.workflow/project.json` as primary source for project context, avoiding redundant analysis
- **Agent autonomy**: Agent handles all discovery logic per `.claude/agents/context-search-agent.md`
- **No redundancy**: This command is a thin orchestrator, all logic in agent
- **Plan-specific**: Use this for implementation planning; brainstorm mode uses direct agent call

View File

@@ -238,14 +238,7 @@ If conflict_risk was medium/high, modifications have been applied to:
**Agent Configuration Reference**: All TDD task generation rules, quantification requirements, Red-Green-Refactor cycle structure, quality standards, and execution details are defined in action-planning-agent.
Refer to: @.claude/agents/action-planning-agent.md for:
- TDD Task Decomposition Standards
- Red-Green-Refactor Cycle Requirements
- Quantification Requirements (MANDATORY)
- 5-Field Task JSON Schema
- IMPL_PLAN.md Structure (TDD variant)
- TODO_LIST.md Format
- TDD Execution Flow & Quality Validation
### TDD-Specific Requirements Summary

View File

@@ -14,8 +14,6 @@ allowed-tools: Task(*), Read(*), Glob(*)
Orchestrator command that invokes `test-context-search-agent` to gather comprehensive test coverage context for test generation workflows. Generates standardized `test-context-package.json` with coverage analysis, framework detection, and source implementation context.
**Agent**: `test-context-search-agent` (`.claude/agents/test-context-search-agent.md`)
## Core Philosophy
- **Agent Delegation**: Delegate all test coverage analysis to `test-context-search-agent` for autonomous execution
@@ -88,7 +86,6 @@ Task(
subagent_type="test-context-search-agent",
description="Gather test coverage context",
prompt=`
You are executing as test-context-search-agent (.claude/agents/test-context-search-agent.md).
## Execution Mode
**PLAN MODE** (Comprehensive) - Full Phase 1-3 execution
@@ -228,7 +225,7 @@ Refer to `test-context-search-agent.md` Phase 3.2 for complete `test-context-pac
## Notes
- **Detection-first**: Always check for existing test-context-package before invoking agent
- **Agent autonomy**: Agent handles all coverage analysis logic per `.claude/agents/test-context-search-agent.md`
- **No redundancy**: This command is a thin orchestrator, all logic in agent
- **Framework agnostic**: Supports Jest, Mocha, pytest, RSpec, Go testing, etc.
- **Coverage focus**: Primary goal is identifying implementation files without tests

View File

@@ -106,8 +106,6 @@ CRITICAL:
- Follow the progressive loading strategy defined in your agent specification (load context incrementally from memory-first approach)
## AGENT CONFIGURATION REFERENCE
All test task generation rules, schemas, and quality standards are defined in your agent specification:
@.claude/agents/action-planning-agent.md
Refer to your specification for:
- Test Task JSON Schema (6-field structure with test-specific metadata)

View File

@@ -0,0 +1,150 @@
# Phase 1.5: Project Exploration
基于元数据,启动并行探索 Agent 收集代码信息。
## Execution
### Step 1: Intelligent Angle Selection
```javascript
// 根据软件类型选择探索角度
const ANGLE_PRESETS = {
'CLI': ['architecture', 'commands', 'algorithms', 'exceptions'],
'API': ['architecture', 'endpoints', 'data-structures', 'interfaces'],
'SDK': ['architecture', 'interfaces', 'data-structures', 'algorithms'],
'DataProcessing': ['architecture', 'algorithms', 'data-structures', 'dataflow'],
'Automation': ['architecture', 'algorithms', 'exceptions', 'dataflow']
};
// 从 metadata.category 映射到预设
function getCategoryKey(category) {
if (category.includes('CLI') || category.includes('命令行')) return 'CLI';
if (category.includes('API') || category.includes('后端')) return 'API';
if (category.includes('SDK') || category.includes('库')) return 'SDK';
if (category.includes('数据处理')) return 'DataProcessing';
if (category.includes('自动化')) return 'Automation';
return 'API'; // default
}
const categoryKey = getCategoryKey(metadata.category);
const selectedAngles = ANGLE_PRESETS[categoryKey];
console.log(`
## Exploration Plan
Software: ${metadata.software_name}
Category: ${metadata.category}${categoryKey}
Selected Angles: ${selectedAngles.join(', ')}
Launching ${selectedAngles.length} parallel explorations...
`);
```
### Step 2: Launch Parallel Agents (Direct Output)
**⚠️ CRITICAL**: Agents write output files directly.
```javascript
const explorationTasks = selectedAngles.map((angle, index) =>
Task({
subagent_type: "cli-explore-agent",
run_in_background: false,
description: `Explore: ${angle}`,
prompt: `
## Exploration Objective
为 CPCC 软著申请文档执行 **${angle}** 探索。
## Assigned Context
- **Exploration Angle**: ${angle}
- **Software Name**: ${metadata.software_name}
- **Scope Path**: ${metadata.scope_path}
- **Category**: ${metadata.category}
- **Exploration Index**: ${index + 1} of ${selectedAngles.length}
- **Output File**: ${sessionFolder}/exploration-${angle}.json
## MANDATORY FIRST STEPS
1. Run: ccw tool exec get_modules_by_depth '{}' (project structure)
2. Run: rg -l "{relevant_keyword}" --type ts (locate relevant files)
3. Analyze from ${angle} perspective
## Exploration Strategy (${angle} focus)
**Step 1: Structural Scan**
- 识别与 ${angle} 相关的模块和文件
- 分析导入/导出关系
**Step 2: Pattern Recognition**
- ${angle} 相关的设计模式
- 代码组织方式
**Step 3: Write Output**
- 输出 JSON 到指定路径
## Expected Output Schema
**File**: ${sessionFolder}/exploration-${angle}.json
\`\`\`json
{
"angle": "${angle}",
"findings": {
"structure": [
{ "component": "...", "type": "module|layer|service", "path": "...", "description": "..." }
],
"patterns": [
{ "name": "...", "usage": "...", "files": ["path1", "path2"] }
],
"key_files": [
{ "path": "src/file.ts", "relevance": 0.85, "rationale": "Core ${angle} logic" }
]
},
"insights": [
{ "observation": "...", "cpcc_section": "2|3|4|5|6|7", "recommendation": "..." }
],
"_metadata": {
"exploration_angle": "${angle}",
"exploration_index": ${index + 1},
"software_name": "${metadata.software_name}",
"timestamp": "ISO8601"
}
}
\`\`\`
## Success Criteria
- [ ] get_modules_by_depth 执行完成
- [ ] 至少识别 3 个相关文件
- [ ] patterns 包含具体代码示例
- [ ] insights 关联到 CPCC 章节 (2-7)
- [ ] JSON 输出到指定路径
- [ ] Return: 2-3 句话总结 ${angle} 发现
`
})
);
// Execute all exploration tasks in parallel
```
## Output
Session folder structure after exploration:
```
${sessionFolder}/
├── exploration-architecture.json
├── exploration-{angle2}.json
├── exploration-{angle3}.json
└── exploration-{angle4}.json
```
## Downstream Usage (Phase 2 Analysis Input)
Phase 2 agents read exploration files as context:
```javascript
// Discover exploration files by known angle pattern
const explorationData = {};
selectedAngles.forEach(angle => {
const filePath = `${sessionFolder}/exploration-${angle}.json`;
explorationData[angle] = JSON.parse(Read(filePath));
});
```

View File

@@ -5,15 +5,161 @@
> **模板参考**: [../templates/agent-base.md](../templates/agent-base.md)
> **规范参考**: [../specs/cpcc-requirements.md](../specs/cpcc-requirements.md)
## Agent 执行前置条件
## Exploration → Agent 自动分配
**每个 Agent 必须首先读取以下规范文件**
根据 Phase 1.5 生成的 exploration 文件名自动分配对应的 analysis agent。
### 映射规则
```javascript
// Agent 启动时的第一步操作
const specs = {
cpcc: Read(`${skillRoot}/specs/cpcc-requirements.md`)
// Exploration 角度 → Agent 映射(基于文件名识别,不读取内容)
const EXPLORATION_TO_AGENT = {
'architecture': 'architecture',
'commands': 'functions', // CLI 命令 → 功能模块
'endpoints': 'interfaces', // API 端点 → 接口设计
'algorithms': 'algorithms',
'data-structures': 'data_structures',
'dataflow': 'data_structures', // 数据流 → 数据结构
'interfaces': 'interfaces',
'exceptions': 'exceptions'
};
// 从文件名提取角度
function extractAngle(filename) {
// exploration-architecture.json → architecture
const match = filename.match(/exploration-(.+)\.json$/);
return match ? match[1] : null;
}
// 分配 agent
function assignAgent(explorationFile) {
const angle = extractAngle(path.basename(explorationFile));
return EXPLORATION_TO_AGENT[angle] || null;
}
// Agent 配置(用于 buildAgentPrompt
const AGENT_CONFIGS = {
architecture: {
role: '系统架构师,专注于分层设计和模块依赖',
section: '2',
output: 'section-2-architecture.md',
focus: '分层结构、模块依赖、数据流向'
},
functions: {
role: '功能分析师,专注于功能点识别和交互',
section: '3',
output: 'section-3-functions.md',
focus: '功能点枚举、模块分组、入口文件、功能交互'
},
algorithms: {
role: '算法工程师,专注于核心逻辑和复杂度分析',
section: '4',
output: 'section-4-algorithms.md',
focus: '核心算法、流程步骤、复杂度、输入输出'
},
data_structures: {
role: '数据建模师,专注于实体关系和类型定义',
section: '5',
output: 'section-5-data-structures.md',
focus: '实体定义、属性类型、关系映射、枚举'
},
interfaces: {
role: 'API设计师专注于接口契约和协议',
section: '6',
output: 'section-6-interfaces.md',
focus: 'API端点、参数校验、响应格式、时序'
},
exceptions: {
role: '可靠性工程师,专注于异常处理和恢复策略',
section: '7',
output: 'section-7-exceptions.md',
focus: '异常类型、错误码、处理模式、恢复策略'
}
};
```
### 自动发现与分配流程
```javascript
// 1. 发现所有 exploration 文件(仅看文件名)
const explorationFiles = bash(`find ${sessionFolder} -name "exploration-*.json" -type f`)
.split('\n')
.filter(f => f.trim());
// 2. 按文件名自动分配 agent
const agentAssignments = explorationFiles.map(file => {
const angle = extractAngle(path.basename(file));
const agentName = EXPLORATION_TO_AGENT[angle];
return {
exploration_file: file,
angle: angle,
agent: agentName,
output_file: AGENT_CONFIGS[agentName]?.output
};
}).filter(a => a.agent);
// 3. 补充未被 exploration 覆盖的必需 agent分配相关 exploration
const coveredAgents = new Set(agentAssignments.map(a => a.agent));
const requiredAgents = ['architecture', 'functions', 'algorithms', 'data_structures', 'interfaces', 'exceptions'];
const missingAgents = requiredAgents.filter(a => !coveredAgents.has(a));
// 相关性映射:为缺失 agent 分配最相关的 exploration
const RELATED_EXPLORATIONS = {
architecture: ['architecture', 'dataflow', 'interfaces'],
functions: ['commands', 'endpoints', 'architecture'],
algorithms: ['algorithms', 'dataflow', 'architecture'],
data_structures: ['data-structures', 'dataflow', 'architecture'],
interfaces: ['interfaces', 'endpoints', 'architecture'],
exceptions: ['exceptions', 'algorithms', 'architecture']
};
function findRelatedExploration(agent, availableFiles) {
const preferences = RELATED_EXPLORATIONS[agent] || ['architecture'];
for (const pref of preferences) {
const match = availableFiles.find(f => f.includes(`exploration-${pref}.json`));
if (match) return { file: match, angle: pref, isRelated: true };
}
// 最后兜底:任意 exploration 都比没有强
return availableFiles.length > 0
? { file: availableFiles[0], angle: extractAngle(path.basename(availableFiles[0])), isRelated: true }
: { file: null, angle: null, isRelated: false };
}
missingAgents.forEach(agent => {
const related = findRelatedExploration(agent, explorationFiles);
agentAssignments.push({
exploration_file: related.file,
angle: related.angle,
agent: agent,
output_file: AGENT_CONFIGS[agent].output,
is_related: related.isRelated // 标记为相关而非直接匹配
});
});
console.log(`
## Agent Auto-Assignment
Found ${explorationFiles.length} exploration files:
${agentAssignments.map(a => {
if (!a.exploration_file) return `- ${a.agent} agent (no exploration)`;
if (a.is_related) return `- ${a.agent} agent ← ${a.angle} (related)`;
return `- ${a.agent} agent ← ${a.angle} (direct)`;
}).join('\n')}
`);
```
---
## Agent 执行前置条件
**每个 Agent 接收 exploration 文件路径,自行读取内容**
```javascript
// Agent prompt 中包含文件路径
// Agent 启动后的操作顺序:
// 1. Read exploration 文件(如有)
// 2. Read CPCC 规范文件
// 3. 执行分析任务
```
规范文件路径(相对于 skill 根目录):
@@ -47,26 +193,90 @@ const specs = {
## 执行流程
```javascript
// 1. 准备目录
// 1. 发现 exploration 文件并自动分配 agent
const explorationFiles = bash(`find ${sessionFolder} -name "exploration-*.json" -type f`)
.split('\n')
.filter(f => f.trim());
const agentAssignments = explorationFiles.map(file => {
const angle = extractAngle(path.basename(file));
const agentName = EXPLORATION_TO_AGENT[angle];
return { exploration_file: file, angle, agent: agentName };
}).filter(a => a.agent);
// 补充必需 agent
const coveredAgents = new Set(agentAssignments.map(a => a.agent));
const requiredAgents = ['architecture', 'functions', 'algorithms', 'data_structures', 'interfaces', 'exceptions'];
requiredAgents.filter(a => !coveredAgents.has(a)).forEach(agent => {
agentAssignments.push({ exploration_file: null, angle: null, agent });
});
// 2. 准备目录
Bash(`mkdir -p ${outputDir}/sections`);
// 2. 并行启动 6 个 Agent
const results = await Promise.all([
launchAgent('architecture', metadata, outputDir),
launchAgent('functions', metadata, outputDir),
launchAgent('algorithms', metadata, outputDir),
launchAgent('data_structures', metadata, outputDir),
launchAgent('interfaces', metadata, outputDir),
launchAgent('exceptions', metadata, outputDir)
]);
// 3. 并行启动所有 Agent(传递 exploration 文件路径)
const results = await Promise.all(
agentAssignments.map(assignment =>
Task({
subagent_type: "cli-explore-agent",
run_in_background: false,
description: `Analyze: ${assignment.agent}`,
prompt: buildAgentPrompt(assignment, metadata, outputDir)
})
)
);
// 3. 收集返回信息
// 4. 收集返回信息
const summaries = results.map(r => JSON.parse(r));
// 4. 传递给 Phase 2.5
// 5. 传递给 Phase 2.5
return { summaries, cross_notes: summaries.flatMap(s => s.cross_module_notes) };
```
### Agent Prompt 构建
```javascript
function buildAgentPrompt(assignment, metadata, outputDir) {
const config = AGENT_CONFIGS[assignment.agent];
let contextSection = '';
if (assignment.exploration_file) {
const matchType = assignment.is_related ? '相关' : '直接匹配';
contextSection = `[CONTEXT]
**Exploration 文件**: ${assignment.exploration_file}
**匹配类型**: ${matchType}
首先读取此文件获取 ${assignment.angle} 探索结果作为分析上下文。
${assignment.is_related ? `注意:这是相关探索结果(非直接匹配),请提取与 ${config.focus} 相关的信息。` : ''}
`;
}
return `
${contextSection}
[SPEC]
读取规范文件:
- Read: ${skillRoot}/specs/cpcc-requirements.md
[ROLE] ${config.role}
[TASK]
分析 ${metadata.scope_path},生成 Section ${config.section}
输出: ${outputDir}/sections/${config.output}
[CPCC_SPEC]
- 内容基于代码分析,无臆测
- 图表编号: 图${config.section}-1, 图${config.section}-2...
- 每个子章节 ≥100字
- 包含文件路径引用
[FOCUS]
${config.focus}
[RETURN JSON]
{"status":"completed","output_file":"${config.output}","summary":"<50字>","cross_module_notes":[],"stats":{}}
`;
}
```
---
## Agent 提示词

View File

@@ -1,75 +1,176 @@
# Phase 2: Project Exploration
Launch parallel exploration agents based on report type.
Launch parallel exploration agents based on report type and task context.
## Execution
### Step 1: Map Exploration Angles
### Step 1: Intelligent Angle Selection
```javascript
const angleMapping = {
architecture: ["Layer Structure", "Module Dependencies", "Entry Points", "Data Flow"],
design: ["Design Patterns", "Class Relationships", "Interface Contracts", "State Management"],
methods: ["Core Algorithms", "Critical Paths", "Public APIs", "Complex Logic"],
comprehensive: ["Layer Structure", "Design Patterns", "Core Algorithms", "Data Flow"]
// Angle presets based on report type (adapted from lite-plan.md)
const ANGLE_PRESETS = {
architecture: ['layer-structure', 'module-dependencies', 'entry-points', 'data-flow'],
design: ['design-patterns', 'class-relationships', 'interface-contracts', 'state-management'],
methods: ['core-algorithms', 'critical-paths', 'public-apis', 'complex-logic'],
comprehensive: ['architecture', 'patterns', 'dependencies', 'integration-points']
};
const angles = angleMapping[config.type];
// Depth-based angle count
const angleCount = {
shallow: 2,
standard: 3,
deep: 4
};
function selectAngles(reportType, depth) {
const preset = ANGLE_PRESETS[reportType] || ANGLE_PRESETS.comprehensive;
const count = angleCount[depth] || 3;
return preset.slice(0, count);
}
const selectedAngles = selectAngles(config.type, config.depth);
console.log(`
## Exploration Plan
Report Type: ${config.type}
Depth: ${config.depth}
Selected Angles: ${selectedAngles.join(', ')}
Launching ${selectedAngles.length} parallel explorations...
`);
```
### Step 2: Launch Parallel Agents
### Step 2: Launch Parallel Agents (Direct Output)
For each angle, launch an exploration agent:
**⚠️ CRITICAL**: Agents write output files directly. No aggregation needed.
```javascript
Task({
subagent_type: "cli-explore-agent",
run_in_background: false,
description: `Explore: ${angle}`,
prompt: `
// Launch agents with pre-assigned angles
const explorationTasks = selectedAngles.map((angle, index) =>
Task({
subagent_type: "cli-explore-agent",
run_in_background: false, // ⚠️ MANDATORY: Must wait for results
description: `Explore: ${angle}`,
prompt: `
## Exploration Objective
Execute **${angle}** exploration for project analysis report.
Execute **${angle}** exploration for ${config.type} project analysis report.
## Context
- **Angle**: ${angle}
## Assigned Context
- **Exploration Angle**: ${angle}
- **Report Type**: ${config.type}
- **Depth**: ${config.depth}
- **Scope**: ${config.scope}
- **Exploration Index**: ${index + 1} of ${selectedAngles.length}
- **Output File**: ${sessionFolder}/exploration-${angle}.json
## Exploration Protocol
1. Structural Discovery (get_modules_by_depth, rg, glob)
2. Pattern Recognition (conventions, naming, organization)
3. Relationship Mapping (dependencies, integration points)
## MANDATORY FIRST STEPS (Execute by Agent)
**You (cli-explore-agent) MUST execute these steps in order:**
1. Run: ccw tool exec get_modules_by_depth '{}' (project structure)
2. Run: rg -l "{relevant_keyword}" --type ts (locate relevant files)
3. Analyze project from ${angle} perspective
## Output Format
## Exploration Strategy (${angle} focus)
**Step 1: Structural Scan** (Bash)
- get_modules_by_depth.sh → identify modules related to ${angle}
- find/rg → locate files relevant to ${angle} aspect
- Analyze imports/dependencies from ${angle} perspective
**Step 2: Semantic Analysis** (Gemini/Qwen CLI)
- How does existing code handle ${angle} concerns?
- What patterns are used for ${angle}?
- Identify key architectural decisions related to ${angle}
**Step 3: Write Output Directly**
- Consolidate ${angle} findings into JSON
- Write to output file path specified above
## Expected Output Schema
**File**: ${sessionFolder}/exploration-${angle}.json
\`\`\`json
{
"angle": "${angle}",
"findings": {
"structure": [...],
"patterns": [...],
"relationships": [...],
"key_files": [{path, relevance, rationale}]
"structure": [
{ "component": "...", "type": "module|layer|service", "description": "..." }
],
"patterns": [
{ "name": "...", "usage": "...", "files": ["path1", "path2"] }
],
"relationships": [
{ "from": "...", "to": "...", "type": "depends|imports|calls", "strength": "high|medium|low" }
],
"key_files": [
{ "path": "src/file.ts", "relevance": 0.85, "rationale": "Core ${angle} logic" }
]
},
"insights": [...]
"insights": [
{ "observation": "...", "impact": "high|medium|low", "recommendation": "..." }
],
"_metadata": {
"exploration_angle": "${angle}",
"exploration_index": ${index + 1},
"report_type": "${config.type}",
"timestamp": "ISO8601"
}
}
\`\`\`
## Success Criteria
- [ ] get_modules_by_depth.sh executed
- [ ] At least 3 relevant files identified with ${angle} rationale
- [ ] Patterns are actionable (code examples, not generic advice)
- [ ] Relationships include concrete file references
- [ ] JSON output written to ${sessionFolder}/exploration-${angle}.json
- [ ] Return: 2-3 sentence summary of ${angle} findings
`
})
```
})
);
### Step 3: Aggregate Results
Merge all exploration results into unified findings:
```javascript
const aggregatedFindings = {
structure: [], // from all angles
patterns: [], // from all angles
relationships: [], // from all angles
key_files: [], // deduplicated
insights: [] // prioritized
};
// Execute all exploration tasks in parallel
```
## Output
Save exploration results to `exploration-{angle}.json` files.
Session folder structure after exploration:
```
${sessionFolder}/
├── exploration-{angle1}.json # Agent 1 direct output
├── exploration-{angle2}.json # Agent 2 direct output
├── exploration-{angle3}.json # Agent 3 direct output (if applicable)
└── exploration-{angle4}.json # Agent 4 direct output (if applicable)
```
## Downstream Usage (Phase 3 Analysis Input)
Subsequent analysis phases MUST read exploration outputs as input:
```javascript
// Discover exploration files by known angle pattern
const explorationData = {};
selectedAngles.forEach(angle => {
const filePath = `${sessionFolder}/exploration-${angle}.json`;
explorationData[angle] = JSON.parse(Read(filePath));
});
// Pass to analysis agent
Task({
subagent_type: "analysis-agent",
prompt: `
## Analysis Input
### Exploration Data by Angle
${Object.entries(explorationData).map(([angle, data]) => `
#### ${angle}
${JSON.stringify(data, null, 2)}
`).join('\n')}
## Analysis Task
Synthesize findings from all exploration angles...
`
});
```

View File

@@ -5,16 +5,176 @@
> **规范参考**: [../specs/quality-standards.md](../specs/quality-standards.md)
> **写作风格**: [../specs/writing-style.md](../specs/writing-style.md)
## Agent 执行前置条件
## Exploration → Agent 自动分配
**每个 Agent 必须首先读取以下规范文件**
根据 Phase 2 生成的 exploration 文件名自动分配对应的 analysis agent。
### 映射规则
```javascript
// Agent 启动时的第一步操作
const specs = {
quality: Read(`${skillRoot}/specs/quality-standards.md`),
style: Read(`${skillRoot}/specs/writing-style.md`)
// Exploration 角度 → Agent 映射(基于文件名识别,不读取内容)
const EXPLORATION_TO_AGENT = {
// Architecture Report 角度
'layer-structure': 'layers',
'module-dependencies': 'dependencies',
'entry-points': 'entrypoints',
'data-flow': 'dataflow',
// Design Report 角度
'design-patterns': 'patterns',
'class-relationships': 'classes',
'interface-contracts': 'interfaces',
'state-management': 'state',
// Methods Report 角度
'core-algorithms': 'algorithms',
'critical-paths': 'paths',
'public-apis': 'apis',
'complex-logic': 'logic',
// Comprehensive 角度
'architecture': 'overview',
'patterns': 'patterns',
'dependencies': 'dependencies',
'integration-points': 'entrypoints'
};
// 从文件名提取角度
function extractAngle(filename) {
// exploration-layer-structure.json → layer-structure
const match = filename.match(/exploration-(.+)\.json$/);
return match ? match[1] : null;
}
// 分配 agent
function assignAgent(explorationFile) {
const angle = extractAngle(path.basename(explorationFile));
return EXPLORATION_TO_AGENT[angle] || null;
}
// Agent 配置(用于 buildAgentPrompt
const AGENT_CONFIGS = {
overview: {
role: '首席系统架构师',
task: '基于代码库全貌,撰写"总体架构"章节,洞察核心价值主张和顶层技术决策',
focus: '领域边界与定位、架构范式、核心技术决策、顶层模块划分',
constraint: '避免罗列目录结构重点阐述设计意图包含至少1个 Mermaid 架构图'
},
layers: {
role: '资深软件设计师',
task: '分析系统逻辑分层结构,撰写"逻辑视点与分层架构"章节',
focus: '职责分配体系、数据流向与约束、边界隔离策略、异常处理流',
constraint: '不要列举具体文件名,关注层级间契约和隔离艺术'
},
dependencies: {
role: '集成架构专家',
task: '审视系统外部连接与内部耦合,撰写"依赖管理与生态集成"章节',
focus: '外部集成拓扑、核心依赖分析、依赖注入与控制反转、供应链安全',
constraint: '禁止简单列出依赖配置,必须分析集成策略和风险控制模型'
},
dataflow: {
role: '数据架构师',
task: '追踪系统数据流转机制,撰写"数据流与状态管理"章节',
focus: '数据入口与出口、数据转换管道、持久化策略、一致性保障',
constraint: '关注数据生命周期和形态演变,不要罗列数据库表结构'
},
entrypoints: {
role: '系统边界分析师',
task: '识别系统入口设计和关键路径,撰写"系统入口与调用链"章节',
focus: '入口类型与职责、请求处理管道、关键业务路径、异常与边界处理',
constraint: '关注入口设计哲学,不要逐个列举所有端点'
},
patterns: {
role: '核心开发规范制定者',
task: '挖掘代码中的复用机制和标准化实践,撰写"设计模式与工程规范"章节',
focus: '架构级模式、通信与并发模式、横切关注点实现、抽象与复用策略',
constraint: '避免教科书式解释,必须结合项目上下文说明应用场景'
},
classes: {
role: '领域模型设计师',
task: '分析系统类型体系和领域模型,撰写"类型体系与领域建模"章节',
focus: '领域模型设计、继承与组合策略、职责分配原则、类型安全与约束',
constraint: '关注建模思想,用 UML 类图辅助说明核心关系'
},
interfaces: {
role: '契约设计专家',
task: '分析系统接口设计和抽象层次,撰写"接口契约与抽象设计"章节',
focus: '抽象层次设计、契约与实现分离、扩展点设计、版本演进策略',
constraint: '关注接口设计哲学,不要逐个列举接口方法签名'
},
state: {
role: '状态管理架构师',
task: '分析系统状态管理机制,撰写"状态管理与生命周期"章节',
focus: '状态模型设计、状态生命周期、并发与一致性、状态恢复与容错',
constraint: '关注状态管理设计决策,不要列举具体变量名'
},
algorithms: {
role: '算法架构师',
task: '分析系统核心算法设计,撰写"核心算法与计算模型"章节',
focus: '算法选型与权衡、计算模型设计、性能与可扩展性、正确性保障',
constraint: '关注算法思想,用流程图辅助说明复杂逻辑'
},
paths: {
role: '性能架构师',
task: '分析系统关键执行路径,撰写"关键路径与性能设计"章节',
focus: '关键业务路径、性能敏感区域、瓶颈识别与缓解、降级与熔断',
constraint: '关注路径设计战略考量,不要罗列所有代码执行步骤'
},
apis: {
role: 'API 设计规范专家',
task: '分析系统对外接口设计规范,撰写"API 设计与规范"章节',
focus: 'API 设计风格、命名与结构规范、版本管理策略、错误处理规范',
constraint: '关注设计规范和一致性,不要逐个列举所有 API 端点'
},
logic: {
role: '业务逻辑架构师',
task: '分析系统业务逻辑建模,撰写"业务逻辑与规则引擎"章节',
focus: '业务规则建模、决策点设计、边界条件处理、业务流程编排',
constraint: '关注业务逻辑组织方式,不要逐行解释代码逻辑'
}
};
```
### 自动发现与分配流程
```javascript
// 1. 发现所有 exploration 文件(仅看文件名)
const explorationFiles = bash(`find ${sessionFolder} -name "exploration-*.json" -type f`)
.split('\n')
.filter(f => f.trim());
// 2. 按文件名自动分配 agent
const agentAssignments = explorationFiles.map(file => {
const angle = extractAngle(path.basename(file));
const agentName = EXPLORATION_TO_AGENT[angle];
return {
exploration_file: file,
angle: angle,
agent: agentName,
output_file: `section-${agentName}.md`
};
}).filter(a => a.agent); // 过滤未映射的角度
console.log(`
## Agent Auto-Assignment
Found ${explorationFiles.length} exploration files:
${agentAssignments.map(a => `- ${a.angle}${a.agent} agent`).join('\n')}
`);
```
---
## Agent 执行前置条件
**每个 Agent 接收 exploration 文件路径,自行读取内容**
```javascript
// Agent prompt 中包含文件路径
// Agent 启动后的操作顺序:
// 1. Read exploration 文件(上下文输入)
// 2. Read 规范文件
// 3. 执行分析任务
```
规范文件路径(相对于 skill 根目录):
@@ -617,15 +777,30 @@ Task({
## 执行流程
```javascript
// 1. 根据报告类型选择 Agent 配置
const agentConfigs = getAgentConfigs(config.type);
// 1. 发现 exploration 文件并自动分配 agent
const explorationFiles = bash(`find ${sessionFolder} -name "exploration-*.json" -type f`)
.split('\n')
.filter(f => f.trim());
const agentAssignments = explorationFiles.map(file => {
const angle = extractAngle(path.basename(file));
const agentName = EXPLORATION_TO_AGENT[angle];
return { exploration_file: file, angle, agent: agentName };
}).filter(a => a.agent);
// 2. 准备目录
Bash(`mkdir "${outputDir}\\sections"`);
// 3. 并行启动所有 Agent
// 3. 并行启动所有 Agent(传递 exploration 文件路径)
const results = await Promise.all(
agentConfigs.map(agent => launchAgent(agent, config, outputDir))
agentAssignments.map(assignment =>
Task({
subagent_type: "cli-explore-agent",
run_in_background: false,
description: `Analyze: ${assignment.agent}`,
prompt: buildAgentPrompt(assignment, config, outputDir)
})
)
);
// 4. 收集简要返回信息
@@ -635,6 +810,45 @@ const summaries = results.map(r => JSON.parse(r));
return { summaries, cross_notes: summaries.flatMap(s => s.cross_module_notes) };
```
### Agent Prompt 构建
```javascript
function buildAgentPrompt(assignment, config, outputDir) {
const agentConfig = AGENT_CONFIGS[assignment.agent];
return `
[CONTEXT]
**Exploration 文件**: ${assignment.exploration_file}
首先读取此文件获取 ${assignment.angle} 探索结果作为分析上下文。
[SPEC]
读取规范文件:
- Read: ${skillRoot}/specs/quality-standards.md
- Read: ${skillRoot}/specs/writing-style.md
[ROLE] ${agentConfig.role}
[TASK]
${agentConfig.task}
输出: ${outputDir}/sections/section-${assignment.agent}.md
[STYLE]
- 严谨专业的中文技术写作,专业术语保留英文
- 完全客观的第三人称视角,严禁"我们"、"开发者"
- 段落式叙述,采用"论点-论据-结论"结构
- 善用逻辑连接词体现设计推演过程
[FOCUS]
${agentConfig.focus}
[CONSTRAINT]
${agentConfig.constraint}
[RETURN JSON]
{"status":"completed","output_file":"section-${assignment.agent}.md","summary":"<50字>","cross_module_notes":[],"stats":{}}
`;
}
```
## Output
各 Agent 写入 `sections/section-xxx.md`,返回简要 JSON 供 Phase 3.5 汇总。