Skip to content

Commit b502ebc

Browse files
author
catlog22
committed
feat: add workflow-research-agent for targeted external research and update analyze-with-file documentation
1 parent 97ed2ef commit b502ebc

4 files changed

Lines changed: 194 additions & 11 deletions

File tree

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
---
2+
name: workflow-research-agent
3+
description: External research agent — web search for API details, design patterns, best practices, and technology validation. Returns structured markdown, does NOT write files.
4+
tools: Read, WebSearch, WebFetch, Bash
5+
---
6+
7+
# External Research Agent
8+
9+
## Role
10+
You perform targeted external research using web search to gather API details, design patterns, architecture approaches, best practices, and technology evaluations. You synthesize findings into structured, actionable markdown for downstream analysis workflows.
11+
12+
Spawned by: analyze-with-file (Phase 2), brainstorm-with-file, or any workflow needing external context.
13+
14+
**CRITICAL**: Return structured markdown only. Do NOT write any files unless explicitly instructed in the prompt.
15+
16+
## Process
17+
18+
1. **Parse research objective** — Understand the topic, focus area, and what the caller needs
19+
2. **Plan queries** — Design 3-5 focused search queries targeting the objective
20+
3. **Execute searches** — Use `WebSearch` for general research, `WebFetch` for specific documentation pages
21+
4. **Cross-reference** — If codebase files are provided in prompt, `Read` them to ground research in actual code context
22+
5. **Synthesize findings** — Extract key insights, patterns, and recommendations from search results
23+
6. **Return structured output** — Markdown-formatted research findings
24+
25+
## Research Modes
26+
27+
### Detail Verification (default for analyze)
28+
Focus: verify assumptions, check best practices, validate technology choices, confirm patterns.
29+
Queries target: benchmarks, production postmortems, known issues, compatibility matrices, official docs.
30+
31+
### API Research (for implementation planning)
32+
Focus: concrete API details, library versions, integration patterns, configuration options.
33+
Queries target: official documentation, API references, migration guides, changelog entries.
34+
35+
### Design Research (for brainstorm/architecture)
36+
Focus: design alternatives, architecture patterns, competitive analysis, UX patterns.
37+
Queries target: design systems, pattern libraries, case studies, comparison articles.
38+
39+
## Execution
40+
41+
### Query Strategy
42+
```
43+
1. Parse topic → extract key technologies, patterns, concepts
44+
2. Generate 3-5 queries:
45+
- Q1: "{technology} best practices {year}"
46+
- Q2: "{pattern} vs {alternative} comparison"
47+
- Q3: "{technology} known issues production"
48+
- Q4: "{specific API/library} documentation {version}"
49+
- Q5: "{domain} architecture patterns"
50+
3. Execute queries via WebSearch
51+
4. For promising results, WebFetch full content for detail extraction
52+
5. Synthesize across all sources
53+
```
54+
55+
### Codebase Grounding
56+
When the prompt includes `codebase_context` (file paths, patterns, tech stack):
57+
- Read referenced files to understand actual usage
58+
- Compare external best practices against current implementation
59+
- Flag gaps between current code and recommended patterns
60+
61+
## Output Format
62+
63+
Return structured markdown (do NOT write files):
64+
65+
```markdown
66+
## Research: {topic}
67+
68+
### Key Findings
69+
- **{Finding 1}**: {detail} (confidence: HIGH|MEDIUM|LOW, source: {url_or_reference})
70+
- **{Finding 2}**: {detail} (confidence: HIGH|MEDIUM|LOW, source: {url_or_reference})
71+
72+
### Technology / API Details
73+
- **{Library/API}**: version {X}, {key capabilities}
74+
- Integration: {how to integrate}
75+
- Caveats: {known issues or limitations}
76+
77+
### Best Practices
78+
- {Practice 1}: {rationale} (source: {reference})
79+
- {Practice 2}: {rationale} (source: {reference})
80+
81+
### Recommended Approach
82+
{Prescriptive recommendation with rationale — "use X" not "consider X or Y" when evidence is strong}
83+
84+
### Alternatives Considered
85+
| Option | Pros | Cons | Verdict |
86+
|--------|------|------|---------|
87+
| {A} | ... | ... | Recommended / Viable / Avoid |
88+
89+
### Pitfalls & Known Issues
90+
- {Issue 1}: {mitigation} (source: {reference})
91+
92+
### Codebase Gaps (if codebase_context provided)
93+
- {Gap}: current code does {X}, best practice recommends {Y}
94+
95+
### Sources
96+
- {source title}: {url} — {key takeaway}
97+
```
98+
99+
## Error Handling
100+
- If WebSearch returns no results for a query: note "no results" and proceed with remaining queries
101+
- If WebFetch fails for a URL: skip and note the intended lookup
102+
- If all searches fail: return "research unavailable — proceed with codebase-only analysis" and list the queries that were attempted
103+
- If codebase files referenced in prompt don't exist: proceed with external research only
104+
105+
## Constraints
106+
- Be prescriptive ("use X") not exploratory ("consider X or Y") when evidence is strong
107+
- Assign confidence levels (HIGH/MEDIUM/LOW) to all findings
108+
- Cite sources for claims — include URLs
109+
- Keep output under 200 lines
110+
- Do NOT write any files — return structured markdown only
111+
- Do NOT fabricate URLs or sources — only cite actual search results
112+
- Bash calls MUST use `run_in_background: false` (subagent cannot receive hook callbacks)

.claude/commands/workflow/analyze-with-file.md

Lines changed: 81 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@ allowed-tools: TodoWrite(*), Agent(*), AskUserQuestion(*), Read(*), Grep(*), Glo
1010
When `--yes` or `-y`: Auto-confirm exploration decisions, use recommended analysis angles.
1111

1212
<purpose>
13-
Interactive collaborative analysis workflow combining codebase exploration (cli-explore-agent) with CLI-assisted analysis (Gemini/Codex). Produces a documented discussion timeline with evolving understanding, decision trails, and actionable conclusions.
13+
Interactive collaborative analysis workflow combining codebase exploration (cli-explore-agent), external research (workflow-research-agent), and CLI-assisted analysis (Gemini/Codex). Produces a documented discussion timeline with evolving understanding, decision trails, and actionable conclusions.
1414

1515
Invoked when user needs deep, multi-perspective analysis of a topic or codebase question — e.g., architecture review, implementation analysis, concept exploration, or decision evaluation.
1616

17-
Produces: `discussion.md` (evolving analysis document with TOC, rounds, narrative synthesis), `explorations.json`/`perspectives.json` (structured findings), `conclusions.json` (final synthesis with recommendations). All artifacts stored in `.workflow/.analysis/{session-id}/`.
17+
Produces: `discussion.md` (evolving analysis document with TOC, rounds, narrative synthesis), `explorations.json`/`perspectives.json` (structured findings), `research.json` (external research findings), `conclusions.json` (final synthesis with recommendations). All artifacts stored in `.workflow/.analysis/{session-id}/`.
1818
</purpose>
1919

2020
<conventions>
@@ -80,8 +80,9 @@ All `AskUserQuestion` calls MUST comply:
8080
| 1 | Session variables | Dimensions, focus areas, analysis depth |
8181
| 2 | `exploration-codebase.json` | Shared Layer 1 discovery (files, modules, patterns) — always created |
8282
| 2 | `explorations/*.json` | Per-perspective Layer 2-3 deep-dives (multi-perspective only, max 4) |
83-
| 2 | `explorations.json` | Single perspective aggregated findings (Layer 1 + CLI analysis) |
84-
| 2 | `perspectives.json` | Multi-perspective findings (Layer 1 shared + per-perspective deep-dives) with synthesis |
83+
| 2 | `research.json` | External research findings (best practices, API details, known issues) — from workflow-research-agent |
84+
| 2 | `explorations.json` | Single perspective aggregated findings (Layer 1 + CLI analysis + research) |
85+
| 2 | `perspectives.json` | Multi-perspective findings (Layer 1 shared + per-perspective deep-dives + research) with synthesis |
8586
| 2 | Updated `discussion.md` | Round 1 + Initial Intent Coverage Check + Current Understanding replaced |
8687
| 3 | Updated `discussion.md` | Round 2-N: feedback, insights, narrative synthesis; TOC + Current Understanding updated each round |
8788
| 4 | `conclusions.json` | Final synthesis with recommendations (incl. steps[] + review_status) |
@@ -177,6 +178,52 @@ Schema: {relevant_files: [{path, annotation, dimensions[]}], patterns[], module_
177178
})
178179
```
179180

181+
**Phase A2 — External Research** (parallel with Phase A, runs when topic involves technologies/patterns/APIs):
182+
183+
Determine if external research would add value — skip for purely internal codebase questions (e.g., "how does module X work"), run for topics involving technology choices, best practices, architecture patterns, API usage, or comparison with industry standards.
184+
185+
```javascript
186+
// External research — runs in PARALLEL with Phase A codebase exploration
187+
// Skip if topic is purely internal codebase navigation
188+
const needsResearch = dimensions.some(d =>
189+
['architecture', 'comparison', 'decision', 'performance', 'security'].includes(d)
190+
) || topic_or_question.match(/best practice|pattern|vs|compare|approach|standard|library|framework/i)
191+
192+
if (needsResearch) {
193+
Agent({
194+
subagent_type: "workflow-research-agent",
195+
run_in_background: false,
196+
description: `Research: ${topicSlug}`,
197+
prompt: `
198+
## Research Objective
199+
Topic: ${topic_or_question}
200+
Mode: detail-verification
201+
Dimensions: ${dimensions.join(', ')}
202+
203+
## Focus
204+
${dimensions.includes('architecture') ? '- Architecture patterns and best practices for this domain' : ''}
205+
${dimensions.includes('performance') ? '- Performance benchmarks and optimization patterns' : ''}
206+
${dimensions.includes('security') ? '- Security best practices and known vulnerabilities' : ''}
207+
${dimensions.includes('comparison') ? '- Technology comparison and trade-off analysis' : ''}
208+
${dimensions.includes('decision') ? '- Decision frameworks and industry recommendations' : ''}
209+
- Verify assumptions about technologies/patterns involved
210+
- Known issues and pitfalls in this area
211+
- Recommended approaches with evidence
212+
213+
## Codebase Context (from Phase A if available)
214+
Tech stack: ${techStack || 'detect from project files'}
215+
Key patterns observed: ${sharedDiscovery?.patterns?.join(', ') || 'pending Phase A results'}
216+
217+
## Output
218+
Return structured markdown per your output format.
219+
Do NOT write files.
220+
`
221+
})
222+
// Parse research agent output → save to ${sessionFolder}/research.json
223+
// Schema: {topic, mode, findings[], best_practices[], alternatives[], pitfalls[], sources[], _metadata}
224+
}
225+
```
226+
180227
**Phase B — Perspective Deep-Dive** (parallel, only for multi-perspective, max 4):
181228
Each perspective agent receives shared Layer 1 results, performs only Layer 2-3 on its relevant subset.
182229
Skip if single-perspective (single mode proceeds directly to Step 2 CLI analysis with Layer 1 results).
@@ -262,9 +309,12 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')} | Do NOT re-discover files — us
262309
```
263310
264311
**Step 3: Aggregate Findings**
265-
- Consolidate explorations + CLI results
312+
- Consolidate explorations + CLI results + research findings (if research.json exists)
313+
- Merge research best_practices[] and pitfalls[] into discussion points
314+
- Cross-reference: flag gaps where codebase patterns diverge from research best practices
266315
- Multi: Extract synthesis (convergent themes, conflicting views, unique contributions)
267316
- Write to `explorations.json` (single) or `perspectives.json` (multi)
317+
- If research.json exists, add `external_research` section to explorations/perspectives with: key findings, best practices, codebase gaps
268318
269319
**Step 4: Update discussion.md** — Append Round 1 with sources, key findings, discussion points, open questions
270320
@@ -281,17 +331,29 @@ CONSTRAINTS: Focus on ${dimensions.join(', ')} | Do NOT re-discover files — us
281331
- `patterns[]`, `module_map`: {}
282332
- `questions_for_user[]`, `_metadata`
283333
284-
**explorations.json Schema** (single — Layer 1 + CLI analysis merged):
334+
**research.json Schema** (external research findings):
335+
- `topic`, `mode` (detail-verification|api-research|design-research), `timestamp`
336+
- `findings[]`: {finding, detail, confidence, source_url}
337+
- `best_practices[]`: {practice, rationale, source}
338+
- `alternatives[]`: {option, pros, cons, verdict}
339+
- `pitfalls[]`: {issue, mitigation, source}
340+
- `codebase_gaps[]`: {gap, current_approach, recommended_approach}
341+
- `sources[]`: {title, url, key_takeaway}
342+
- `_metadata`: {queries_executed, results_found}
343+
344+
**explorations.json Schema** (single — Layer 1 + CLI analysis + research merged):
285345
- `session_id`, `timestamp`, `topic`, `dimensions[]`
286346
- `sources[]`: {type, file/summary}
287347
- `key_findings[]`, `code_anchors[]`: {file, lines, snippet, significance}
288348
- `call_chains[]`: {entry, chain, files}
289349
- `discussion_points[]`, `open_questions[]`
290350
- `technical_solutions[]`: {round, solution, problem, rationale, alternatives, status: proposed|validated|rejected, evidence_refs[], next_action}
351+
- `external_research`: {findings[], best_practices[], codebase_gaps[], sources[]} — merged from research.json if available
291352
292-
**perspectives.json Schema** (multi — Layer 1 shared + per-perspective Layer 2-3):
353+
**perspectives.json Schema** (multi — Layer 1 shared + per-perspective Layer 2-3 + research):
293354
- `shared_discovery`: {relevant_files[], patterns[], module_map}
294355
- `perspectives[]`: [{name, tool, findings, insights, questions, code_anchors[], call_chains[]}]
356+
- `external_research`: {findings[], best_practices[], codebase_gaps[], sources[]} — merged from research.json if available
295357
- `synthesis`: {convergent_themes, conflicting_views, unique_contributions}
296358
297359
| Condition | Action |
@@ -334,8 +396,8 @@ const priorContext = `
334396
335397
3. **Gather Feedback** (AskUserQuestion, single-select, header: "分析反馈"):
336398
- **继续深入**: Direction correct — deepen automatically or user specifies direction (combines agree+deepen and agree+suggest)
399+
- **外部研究**: Need external research on specific technology/pattern/best practice (spawns workflow-research-agent)
337400
- **调整方向**: Different focus or specific questions to address
338-
- **补充信息**: User has additional context, constraints, or corrections to provide
339401
- **分析完成**: Sufficient -> exit to Phase 4
340402
341403
4. **Process Response** (always record user choice + impact to discussion.md):
@@ -347,9 +409,14 @@ const priorContext = `
347409
- **"Other" is auto-provided** by AskUserQuestion — covers user-specified custom direction (no need for separate "suggest next step" option)
348410
- Execute selected direction -> merge new code_anchors/call_chains -> record confirmed assumptions + deepen angle
349411
350-
**调整方向** -> AskUserQuestion (header: "新方向", user selects or provides custom via "Other") -> new CLI exploration -> Record Decision (old vs new direction, reason, impact)
412+
**外部研究** -> Spawn workflow-research-agent for targeted research:
413+
- AskUserQuestion (header: "研究主题", freetext via "Other"): What specific technology/pattern/approach needs external research?
414+
- Spawn research agent with topic + current codebase context (from explorations.json)
415+
- Merge research findings into explorations.json `external_research` section
416+
- Update research.json with new findings (append, don't overwrite)
417+
- Record research findings as Key Findings in discussion.md
351418
352-
**补充信息** -> Capture user input, integrate into context, answer questions via CLI/analysis if needed -> Record corrections/additions + updated understanding
419+
**调整方向** -> AskUserQuestion (header: "新方向", user selects or provides custom via "Other") -> new CLI exploration -> Record Decision (old vs new direction, reason, impact)
353420
354421
**分析完成** -> Exit loop -> Record why concluding
355422
@@ -579,6 +646,8 @@ ${implScope.map((item, i) => `${i+1}. **${item.objective}** [${item.priority}]
579646
| E005 | error | No relevant findings from exploration — broaden search, ask user for clarification | cli_exploration |
580647
| E006 | warning | Session folder conflict — append timestamp suffix | session_init |
581648
| E007 | error | Gemini unavailable — fallback to Codex or manual analysis | cli_exploration |
649+
| E008 | warning | Research agent WebSearch failed — continue with codebase-only analysis, note limitation | cli_exploration |
650+
| E009 | warning | Research findings conflict with codebase patterns — flag as codebase_gaps for user review | cli_exploration |
582651
583652
</error_codes>
584653
@@ -588,6 +657,8 @@ ${implScope.map((item, i) => `${i+1}. **${item.objective}** [${item.priority}]
588657
- [ ] Dimensions identified and user preferences captured (Phase 1)
589658
- [ ] discussion.md initialized with TOC, Current Understanding, metadata
590659
- [ ] Codebase exploration completed with code_anchors and call_chains (Phase 2)
660+
- [ ] External research executed if topic warrants it (architecture/comparison/decision/performance/security dimensions)
661+
- [ ] Research findings merged into explorations/perspectives with codebase_gaps flagged
591662
- [ ] CLI analysis executed and findings aggregated
592663
- [ ] Initial Intent Coverage Check appended to discussion.md
593664
- [ ] Interactive discussion rounds documented with narrative synthesis (Phase 3)

assets/wechat-group-qr.png

-57.3 KB
Loading

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "claude-code-workflow",
3-
"version": "7.2.11",
3+
"version": "7.2.13",
44
"description": "JSON-driven multi-agent development framework with intelligent CLI orchestration (Gemini/Qwen/Codex), context-first architecture, and automated workflow execution",
55
"type": "module",
66
"main": "ccw/dist/index.js",

0 commit comments

Comments
 (0)