docs: Generate ARCHITECTURE.md and EXAMPLES.md

Generated system design and usage examples documentation based on project
context and provided templates.

ARCHITECTURE.md provides an overview of the system's architecture,
including core principles, structure, module map, interactions, design patterns,
API overview, data flow, security, and scalability.

EXAMPLES.md offers end-to-end usage examples, covering quick start, core use cases,
advanced scenarios, testing examples, and best practices.
This commit is contained in:
catlog22
2025-11-23 11:23:21 +08:00
parent f09c6e2a7a
commit 73fed4893b
2 changed files with 303 additions and 1224 deletions

View File

@@ -1,567 +1,170 @@
# 🏗️ Claude Code Workflow (CCW) - Architecture Overview
# Architecture: Claude_dms3 System Architecture
This document provides a high-level overview of CCW's architecture, design principles, and system components.
## Related Files
- `workflow-architecture.md` - Core system, session, and task architecture.
- `intelligent-tools-strategy.md` - Describes tool selection, prompt structure, and execution modes.
- `mcp-tool-strategy.md` - Details triggering mechanisms for external tools like Exa.
- `action-planning-agent.md` - Explains the role and process of the planning agent.
- `code-developer.md` - Explains the role and process of the code implementation agent.
---
## Summary
The Claude_dms3 project is a sophisticated CLI-based system designed for autonomous software engineering. It leverages a "JSON-only data model" for task state management, "directory-based session management," and a "unified file structure" to organize workflows. The system employs multiple specialized AI agents (e.g., action-planning-agent, code-developer) and integrates external tools (Gemini, Qwen, Codex, Exa) through a "universal prompt template" and "intelligent tool selection strategy." Its core philosophy emphasizes incremental progress, context-driven execution, and strict quality standards, supported by a hierarchical task system with dynamic decomposition.
## 📋 Table of Contents
## Key Findings
1. **JSON-Only Data Model for Task State**: The system's task state is stored exclusively in JSON files (`.task/IMPL-*.json`), which are the single source of truth. All markdown documents are read-only generated views, eliminating bidirectional sync complexity. (`workflow-architecture.md`)
2. **Directory-Based Session Management**: Workflow sessions are managed through a simple directory structure (`.workflow/active/` for active, `.workflow/archives/` for completed), where the location of a session directory determines its state. (`workflow-architecture.md`)
3. **Hierarchical Task Structure with Flow Control**: Tasks are organized hierarchically (max 2 levels: IMPL-N, IMPL-N.M) and include a `flow_control` field within their JSON schema to define sequential `pre_analysis` and `implementation_approach` steps with dependency management. (`workflow-architecture.md`)
4. **Intelligent Tool Selection and Universal Prompt Template**: The system dynamically selects AI models (Gemini, Qwen, Codex) based on the task type (analysis vs. implementation) and uses a consistent "Universal Prompt Template" structure for all CLI tools, standardizing interaction and context passing. (`intelligent-tools-strategy.md`)
5. **Agent-Based Execution**: Specialized agents like the `action-planning-agent` (for generating plans and tasks) and `code-developer` (for implementing code and tests) process tasks based on provided context packages, ensuring clear separation of concerns and automated execution. (`action-planning-agent.md`, `code-developer.md`)
6. **Quantification Requirements**: A mandatory rule enforces explicit counts and enumerations in all task specifications, requirements, and acceptance criteria to eliminate ambiguity and ensure measurable outcomes. (`action-planning-agent.md`)
- [Design Philosophy](#design-philosophy)
- [System Architecture](#system-architecture)
- [Core Components](#core-components)
- [Data Flow](#data-flow)
- [Multi-Agent System](#multi-agent-system)
- [CLI Tool Integration](#cli-tool-integration)
- [Session Management](#session-management)
- [Memory System](#memory-system)
## Detailed Analysis
---
### 1. System Overview
The Claude_dms3 system is a CLI-driven, multi-agent orchestrator for software development. Its core principles revolve around **autonomy, consistency, and traceability**. The architectural style can be described as an **Agent-Oriented Architecture** interacting with external LLM-based tools, governed by a **Command-Query Responsibility Segregation (CQRS)**-like approach where JSON files are the command/state store and markdown files are generated views.
## 🎯 Design Philosophy
**Core Principles**:
* **JSON-Only Data Model**: `.task/IMPL-*.json` files are the single source of truth for task states, ensuring consistency and avoiding synchronization issues. (`workflow-architecture.md`)
* **Context-Driven Execution**: Agents and tools operate with rich context, including session metadata, analysis results, and project-specific artifacts, passed via "context packages." (`action-planning-agent.md`, `code-developer.md`)
* **Incremental Progress**: The `code-developer` agent, for instance, emphasizes small, testable changes. (`code-developer.md`)
* **Quantification**: Explicit counts and measurable acceptance criteria are mandatory in task definitions. (`action-planning-agent.md`)
CCW is built on several core design principles that differentiate it from traditional AI-assisted development tools:
**Technology Stack**:
* **Core**: Shell scripting (Bash/PowerShell), `jq` for JSON processing, `find`, `grep`, `rg` for file system operations.
* **AI Models**: Gemini (primary for analysis), Qwen (fallback for analysis), Codex (for implementation and testing).
* **External Tools**: Exa (for code context and web search).
### 1. **Context-First Architecture**
- Pre-defined context gathering eliminates execution uncertainty
- Agents receive the correct information *before* implementation
- Context is loaded dynamically based on task requirements
### 2. System Structure
The system follows a layered architecture, conceptually:
### 2. **JSON-First State Management**
- Task states live in `.task/IMPL-*.json` files as the single source of truth
- Markdown documents are read-only generated views
- Eliminates state drift and synchronization complexity
- Enables programmatic orchestration
```
+--------------------------+
| User Interface | (CLI Commands: /cli:chat, /workflow:plan, etc.)
+------------+-------------+
|
v
+------------+-------------+
| Command Layer | (Parses user input, prepares context for agents)
+------------+-------------+
|
v
+------------+-------------+
| Agent Orchestration | (Selects & coordinates agents, manages workflow sessions)
+------------+-------------+
|
v
+------------+-------------+ +-------------------+
| Specialized AI Agents |<----> External AI Tools |
| (action-planning, code- | | (Gemini, Qwen, |
| developer, test-fix) | | Codex, Exa) |
+------------+-------------+ +-------------------+
^
| (Reads/Writes Task JSONs)
+------------+-------------+
| Data / State Layer | (JSON-only task files, workflow-session.json)
+--------------------------+
```
### 3. **Autonomous Multi-Phase Orchestration**
- Commands chain specialized sub-commands and agents
- Automates complex workflows with zero user intervention
- Each phase validates its output before proceeding
### 3. Module Map
### 4. **Multi-Model Strategy**
- Leverages unique strengths of different AI models
- Gemini for analysis and exploration
- Codex for implementation
- Qwen for architecture and planning
| Module / Component | Layer | Responsibilities | Dependencies |
| :-------------------------- | :------------------- | :---------------------------------------------------- | :-------------------------------------------------------------------------------- |
| **User Interface** | Presentation | User command input, display of CLI output. | Command Layer |
| **Command Layer** | Application | Parse user commands, prepare context for agents. | Agent Orchestration, Data Layer |
| **Agent Orchestration** | Application | Manage workflow sessions, select and invoke agents. | Specialized AI Agents, Data Layer, External AI Tools |
| `action-planning-agent` | Specialized AI Agent | Create implementation plans, generate task JSONs. | External AI Tools (Exa), Data Layer |
| `code-developer` | Specialized AI Agent | Implement code, write tests, follow tech stack. | External AI Tools (Exa, Codex), Data Layer |
| `workflow-architecture` | Core System Logic | Defines system-wide conventions for data model, session, and task management. | N/A (foundational) |
| `intelligent-tools-strategy`| Core System Logic | Defines tool selection logic, prompt templates. | External AI Tools (Gemini, Qwen, Codex) |
| `mcp-tool-strategy` | Core System Logic | Defines conditions for triggering Exa tools. | External AI Tools (Exa) |
| **Data / State Layer** | Persistence | Store task definitions (`.task/*.json`), session metadata (`workflow-session.json`). | Specialized AI Agents, Agent Orchestration |
| **External AI Tools** | External Service | Provide LLM capabilities (analysis, code gen, search).| Specialized AI Agents |
### 5. **Hierarchical Memory System**
- 4-layer documentation system (CLAUDE.md files)
- Provides context at the appropriate level of abstraction
- Prevents information overload
### 4. Module Interactions
### 6. **Specialized Role-Based Agents**
- Suite of agents mirrors a real software team
- Each agent has specific responsibilities
- Agents collaborate to complete complex tasks
**Core Data Flow (Workflow Execution Example)**:
---
## 🏛️ System Architecture
1. **User Initiates Workflow**: User executes a CLI command (e.g., `/workflow:plan "Implement feature X"`).
2. **Command Layer Processes**: The command layer translates the user's request into a structured input for the agent orchestration.
3. **Agent Orchestration Invokes Planning Agent**: The system determines that a planning task is needed and invokes the `action-planning-agent`.
4. **Planning Agent's Context Assessment**: The `action-planning-agent` receives a "context package" (JSON) containing session metadata, analysis results (if any), and an inventory of brainstorming artifacts. It can optionally use MCP tools (Exa) for further context enhancement. (`action-planning-agent.md`)
5. **Planning Agent Generates Tasks**: Based on the context, the `action-planning-agent` generates:
* Multiple task JSON files (`.task/IMPL-*.json`) adhering to a 5-field schema and quantification requirements.
* An overall `IMPL_PLAN.md` document.
* A `TODO_LIST.md` for progress tracking.
All these are stored in the respective session directory within `.workflow/active/WFS-[topic-slug]`. (`action-planning-agent.md`)
6. **User/System Initiates Implementation**: Once planning is complete, the user or system might trigger an implementation phase (e.g., `/cli:execute IMPL-1`).
7. **Agent Orchestration Invokes Code Developer**: The `code-developer` agent is invoked for the specified task.
8. **Code Developer's Context Assessment**: The `code-developer` receives the task's JSON (which includes `flow_control` for `pre_analysis` steps and `implementation_approach`) and assesses the context, potentially loading tech stack guidelines. It can use local search tools (`rg`, `find`) and MCP tools (Exa) for further information gathering. (`code-developer.md`)
9. **Code Developer Executes Task**: The `code-developer` executes the `implementation_approach` steps sequentially, respecting `depends_on` relationships and using external AI tools (Codex for implementation, Gemini/Qwen for analysis). It performs incremental changes, ensuring code quality and test pass rates. (`code-developer.md`)
10. **Task Completion and Summary**: Upon successful completion of a task, the `code-developer` updates the `TODO_LIST.md` and generates a detailed summary (`.summaries/IMPL-*-summary.md`) within the session directory. (`code-developer.md`)
**Dependency Graph (High-Level)**:
```mermaid
graph TB
subgraph "User Interface Layer"
CLI[Slash Commands]
CHAT[Natural Language]
end
subgraph "Orchestration Layer"
WF[Workflow Engine]
SM[Session Manager]
TM[Task Manager]
end
subgraph "Agent Layer"
AG1[@code-developer]
AG2[@test-fix-agent]
AG3[@ui-design-agent]
AG4[@cli-execution-agent]
AG5[More Agents...]
end
subgraph "Tool Layer"
GEMINI[Gemini CLI]
QWEN[Qwen CLI]
CODEX[Codex CLI]
BASH[Bash/System]
end
subgraph "Data Layer"
JSON[Task JSON Files]
MEM[CLAUDE.md Memory]
STATE[Session State]
end
CLI --> WF
CHAT --> WF
WF --> SM
WF --> TM
SM --> STATE
TM --> JSON
WF --> AG1
WF --> AG2
WF --> AG3
WF --> AG4
AG1 --> GEMINI
AG1 --> QWEN
AG1 --> CODEX
AG2 --> BASH
AG3 --> GEMINI
AG4 --> CODEX
GEMINI --> MEM
QWEN --> MEM
CODEX --> JSON
graph TD
User[User Input/CLI] --> CommandLayer
CommandLayer --> AgentOrchestration
AgentOrchestration --> PlanningAgent
AgentOrchestration --> CodeDeveloper
AgentOrchestration --> OtherAgents[Other Specialized Agents]
PlanningAgent --> DataLayer[Data Layer: .task/*.json, workflow-session.json]
PlanningAgent --> ExternalTools[External AI Tools: Gemini, Qwen, Codex, Exa]
CodeDeveloper --> DataLayer
CodeDeveloper --> ExternalTools
OtherAgents --> DataLayer
OtherAgents --> ExternalTools
DataLayer --> AgentOrchestration
ExternalTools --> AgentOrchestration
```
---
## 🔧 Core Components
### 1. **Workflow Engine**
The workflow engine orchestrates complex development processes through multiple phases:
- **Planning Phase**: Analyzes requirements and generates implementation plans
- **Execution Phase**: Coordinates agents to implement tasks
- **Verification Phase**: Validates implementation quality
- **Testing Phase**: Generates and executes tests
- **Review Phase**: Performs code review and quality analysis
**Key Features**:
- Multi-phase orchestration
- Automatic session management
- Context propagation between phases
- Quality gates at each phase transition
### 2. **Session Manager**
Manages isolated workflow contexts:
```
.workflow/
├── active/ # Active sessions
│ ├── WFS-user-auth/ # User authentication session
│ ├── WFS-payment/ # Payment integration session
│ └── WFS-dashboard/ # Dashboard redesign session
└── archives/ # Completed sessions
└── WFS-old-feature/ # Archived session
```
**Capabilities**:
- Directory-based session tracking
- Session state persistence
- Parallel session support
- Session archival and resumption
### 3. **Task Manager**
Handles hierarchical task structures:
```json
{
"id": "IMPL-1.2",
"title": "Implement JWT authentication",
"status": "pending",
"meta": {
"type": "feature",
"agent": "code-developer"
},
"context": {
"requirements": ["JWT authentication", "OAuth2 support"],
"focus_paths": ["src/auth", "tests/auth"],
"acceptance": ["JWT validation works", "OAuth flow complete"]
},
"flow_control": {
"pre_analysis": [...],
"implementation_approach": {...}
}
}
```
**Features**:
- JSON-first data model
- Hierarchical task decomposition (max 2 levels)
- Dynamic subtask creation
- Dependency tracking
### 4. **Memory System**
Four-layer hierarchical documentation:
```
CLAUDE.md (Project root - high-level overview)
├── src/CLAUDE.md (Source layer - module summaries)
│ ├── auth/CLAUDE.md (Module layer - component details)
│ │ └── jwt/CLAUDE.md (Component layer - implementation details)
```
**Memory Commands**:
- `/memory:update-full` - Complete project rebuild
- `/memory:update-related` - Incremental updates for changed modules
- `/memory:load` - Quick context loading for specific tasks
---
## 🔄 Data Flow
### Typical Workflow Execution Flow
```mermaid
sequenceDiagram
participant User
participant CLI
participant Workflow
participant Agent
participant Tool
participant Data
User->>CLI: /workflow:plan "Feature description"
CLI->>Workflow: Initialize planning workflow
Workflow->>Data: Create session
Workflow->>Agent: @action-planning-agent
Agent->>Tool: gemini-wrapper analyze
Tool->>Data: Update CLAUDE.md
Agent->>Data: Generate IMPL-*.json
Workflow->>User: Plan complete
User->>CLI: /workflow:execute
CLI->>Workflow: Start execution
Workflow->>Data: Load tasks from JSON
Workflow->>Agent: @code-developer
Agent->>Tool: Read context
Agent->>Tool: Implement code
Agent->>Data: Update task status
Workflow->>User: Execution complete
```
### Context Flow
```mermaid
graph LR
A[User Request] --> B[Context Gathering]
B --> C[CLAUDE.md Memory]
B --> D[Task JSON]
B --> E[Session State]
C --> F[Agent Context]
D --> F
E --> F
F --> G[Tool Execution]
G --> H[Implementation]
H --> I[Update State]
```
---
## 🤖 Multi-Agent System
### Agent Specialization
CCW uses specialized agents for different types of tasks:
| Agent | Responsibility | Tools Used |
|-------|---------------|------------|
| **@code-developer** | Code implementation | Gemini, Qwen, Codex, Bash |
| **@test-fix-agent** | Test generation and fixing | Codex, Bash |
| **@ui-design-agent** | UI design and prototyping | Gemini, Claude Vision |
| **@action-planning-agent** | Task planning and decomposition | Gemini |
| **@cli-execution-agent** | Autonomous CLI task handling | Codex, Gemini, Qwen |
| **@cli-explore-agent** | Codebase exploration | ripgrep, find |
| **@context-search-agent** | Context gathering | Grep, Glob |
| **@doc-generator** | Documentation generation | Gemini, Qwen |
| **@memory-bridge** | Memory system updates | Gemini, Qwen |
| **@universal-executor** | General task execution | All tools |
### Agent Communication
Agents communicate through:
1. **Shared Session State**: All agents can read/write session JSON
2. **Task JSON Files**: Tasks contain context for agent handoffs
3. **CLAUDE.md Memory**: Shared project knowledge base
4. **Flow Control**: Pre-analysis and implementation approach definitions
---
## 🛠️ CLI Tool Integration
### Three CLI Tools
CCW integrates three external AI tools, each optimized for specific tasks:
#### 1. **Gemini CLI** - Deep Analysis
- **Strengths**: Pattern recognition, architecture understanding, comprehensive analysis
- **Use Cases**:
- Codebase exploration
- Architecture analysis
- Bug diagnosis
- Memory system updates
#### 2. **Qwen CLI** - Architecture & Planning
- **Strengths**: System design, code generation, architectural planning
- **Use Cases**:
- Architecture design
- System planning
- Code generation
- Refactoring strategies
#### 3. **Codex CLI** - Autonomous Development
- **Strengths**: Self-directed implementation, error fixing, test generation
- **Use Cases**:
- Feature implementation
- Bug fixes
- Test generation
- Autonomous development
### Tool Selection Strategy
CCW automatically selects the best tool based on task type:
```
Analysis Task → Gemini CLI
Planning Task → Qwen CLI
Implementation Task → Codex CLI
```
Users can override with `--tool` parameter:
```bash
/cli:analyze --tool codex "Analyze authentication flow"
```
---
## 📦 Session Management
### Session Lifecycle
```mermaid
stateDiagram-v2
[*] --> Creating: /workflow:session:start
Creating --> Active: Session initialized
Active --> Paused: User pauses
Paused --> Active: /workflow:session:resume
Active --> Completed: /workflow:session:complete
Completed --> Archived: Move to archives/
Archived --> [*]
```
### Session Structure
```
.workflow/active/WFS-feature-name/
├── workflow-session.json # Session metadata
├── .task/ # Task JSON files
│ ├── IMPL-1.json
│ ├── IMPL-1.1.json
│ └── IMPL-2.json
├── .chat/ # Chat logs
├── brainstorming/ # Brainstorm artifacts
│ ├── guidance-specification.md
│ └── system-architect/analysis.md
└── artifacts/ # Generated files
├── IMPL_PLAN.md
└── verification-report.md
```
---
## 💾 Memory System
### Hierarchical CLAUDE.md Structure
The memory system maintains project knowledge across four layers:
#### **Layer 1: Project Root**
```markdown
# Project Overview
- High-level architecture
- Technology stack
- Key design decisions
- Entry points
```
#### **Layer 2: Source Directory**
```markdown
# Source Code Structure
- Module summaries
- Dependency relationships
- Common patterns
```
#### **Layer 3: Module Directory**
```markdown
# Module Details
- Component responsibilities
- API interfaces
- Internal structure
```
#### **Layer 4: Component Directory**
```markdown
# Component Implementation
- Function signatures
- Implementation details
- Usage examples
```
### Memory Update Strategies
#### Full Update (`/memory:update-full`)
- Rebuilds entire project documentation
- Uses layer-based execution (Layer 3 → 1)
- Batch processing (4 modules/agent)
- Fallback mechanism (gemini → qwen → codex)
#### Incremental Update (`/memory:update-related`)
- Updates only changed modules
- Analyzes git changes
- Efficient for daily development
#### Quick Load (`/memory:load`)
- No file updates
- Task-specific context gathering
- Returns JSON context package
- Fast context injection
---
## 🔐 Quality Assurance
### Quality Gates
CCW enforces quality at multiple levels:
1. **Planning Phase**:
- Requirements coverage check
- Dependency validation
- Task specification quality assessment
2. **Execution Phase**:
- Context validation before implementation
- Pattern consistency checks
- Test generation
3. **Review Phase**:
- Code quality analysis
- Security review
- Architecture review
### Verification Commands
- `/workflow:action-plan-verify` - Validates plan quality before execution
- `/workflow:tdd-verify` - Verifies TDD cycle compliance
- `/workflow:review` - Post-implementation review
---
## 🚀 Performance Optimizations
### 1. **Lazy Loading**
- Files created only when needed
- On-demand document generation
- Minimal upfront cost
### 2. **Parallel Execution**
- Independent tasks run concurrently
- Multi-agent parallel brainstorming
- Batch processing for memory updates
### 3. **Context Caching**
- CLAUDE.md acts as knowledge cache
- Reduces redundant analysis
- Faster context retrieval
### 4. **Atomic Session Management**
- Ultra-fast session switching (<10ms)
- Simple file marker system
- No database overhead
---
## 📊 Scalability
### Horizontal Scalability
- **Multiple Sessions**: Run parallel workflows for different features
- **Team Collaboration**: Session-based isolation prevents conflicts
- **Incremental Updates**: Only update affected modules
### Vertical Scalability
- **Hierarchical Tasks**: Efficient task decomposition (max 2 levels)
- **Selective Context**: Load only relevant context for each task
- **Batch Processing**: Process multiple modules per agent invocation
---
## 🔮 Extensibility
### Adding New Agents
Create agent definition in `.claude/agents/`:
```markdown
# Agent Name
## Role
Agent description
## Tools Available
- Tool 1
- Tool 2
## Prompt
Agent instructions...
```
### Adding New Commands
Create command in `.claude/commands/`:
```bash
#!/usr/bin/env bash
# Command implementation
```
### Custom Workflows
Combine existing commands to create custom workflows:
```bash
/workflow:brainstorm:auto-parallel "Topic"
/workflow:plan
/workflow:action-plan-verify
/workflow:execute
/workflow:review
```
---
## 🎓 Best Practices
### For Users
1. **Keep Memory Updated**: Run `/memory:update-related` after major changes
2. **Use Quality Gates**: Run `/workflow:action-plan-verify` before execution
3. **Session Management**: Complete sessions with `/workflow:session:complete`
4. **Tool Selection**: Let CCW auto-select tools unless you have specific needs
### For Developers
1. **Follow JSON-First**: Never modify markdown documents directly
2. **Agent Context**: Provide complete context in task JSON
3. **Error Handling**: Implement graceful fallbacks
4. **Testing**: Test agents independently before integration
---
## 📚 Further Reading
- [Getting Started Guide](GETTING_STARTED.md) - Quick start tutorial
- [Command Reference](COMMAND_REFERENCE.md) - All available commands
- [Command Specification](COMMAND_SPEC.md) - Detailed command specs
- [Workflow Diagrams](WORKFLOW_DIAGRAMS.md) - Visual workflow representations
- [Contributing Guide](CONTRIBUTING.md) - How to contribute
- [Examples](EXAMPLES.md) - Real-world use cases
---
**Last Updated**: 2025-11-20
**Version**: 5.8.1
### 5. Design Patterns
* **Agent-Oriented Programming**: The system is composed of autonomous, specialized agents that interact to achieve complex goals. Each agent (e.g., `action-planning-agent`, `code-developer`) has a defined role, input, and output.
* **Single Source of Truth**: The "JSON-only data model" for task states is a strict application of this pattern, simplifying data consistency.
* **Command Pattern**: CLI commands abstract complex operations, encapsulating requests as objects to be passed to agents.
* **Strategy Pattern**: The "Intelligent Tools Selection Strategy" dynamically chooses the appropriate AI model (Gemini, Qwen, Codex) based on the task's needs.
* **Template Method Pattern**: The "Universal Prompt Template" and various task-specific templates provide a skeletal structure for commands, allowing agents to fill in details.
* **Observer Pattern (Implicit)**: Changes in `.task/*.json` or `workflow-session.json` (the state) implicitly trigger updates in derived views like `TODO_LIST.md`.
* **Context Object Pattern**: The "context package" passed to agents bundles all relevant information needed for task execution.
### 6. Aggregated API Overview
The system's "API" is primarily its command-line interface and the structured inputs/outputs (JSON files) that agents process. There are no traditional RESTful APIs exposed in the public sense within the core system, but rather internal "tool calls" made by agents to external AI services.
**Key "API" (CLI Commands) Categories**:
* **Workflow Management**: `workflow:plan`, `workflow:execute`, `workflow:status`, `workflow:session:*`
* **CLI Utilities**: `cli:analyze`, `cli:chat`, `cli:codex-execute`
* **Memory Management**: `memory:load`, `memory:update`
* **Task Management**: `task:breakdown`, `task:create`, `task:replan`
* **Brainstorming**: `workflow:brainstorm:*`
* **UI Design**: `workflow:ui-design:*`
**Internal API (Agent Inputs/Outputs)**:
* **Context Package (Input to Agents)**: A JSON object containing `session_id`, `session_metadata`, `analysis_results`, `artifacts_inventory`, `context_package`, `mcp_capabilities`, `mcp_analysis`. (`action-planning-agent.md`)
* **Task JSON (`.task/IMPL-*.json`)**: Standardized 6-field JSON schema (`id`, `title`, `status`, `meta`, `context`, `flow_control`). (`workflow-architecture.md`)
* **`flow_control` object**: Contains `pre_analysis` (context gathering) and `implementation_approach` (implementation steps) arrays, with support for variable references and dependency management. (`workflow-architecture.md`)
### 7. Data Flow
The data flow is highly structured and context-rich, moving between the command layer, agent orchestration, specialized agents, and external AI tools. A typical flow for implementing a feature involves:
1. **Plan Generation**: User request -> Command Layer -> Agent Orchestration -> `action-planning-agent`.
2. **Context Loading**: `action-planning-agent` loads `context package` (session state, existing analysis, artifacts).
3. **Task & Plan Output**: `action-planning-agent` writes `.task/IMPL-*.json`, `IMPL_PLAN.md`, `TODO_LIST.md`.
4. **Task Execution**: Agent Orchestration selects an `IMPL-N` task -> `code-developer` agent.
5. **Pre-Analysis**: `code-developer` executes `flow_control.pre_analysis` steps (e.g., `bash()` commands, `Read()`, `Glob()`, `Grep()`, `mcp__exa__*()` calls, `gemini` for pattern analysis).
6. **Implementation**: `code-developer` executes `flow_control.implementation_approach` steps (e.g., `codex` for code generation, `bash()` for tests, `gemini` for quality review). Outputs from earlier steps feed into later ones via `[variable_name]` references.
7. **Status Update**: `code-developer` updates task status in `.task/IMPL-*.json`, `TODO_LIST.md`, and generates `.summaries/IMPL-*-summary.md`.
### 8. Security and Scalability
**Security**:
* **Strict Permission Framework**: Each CLI execution requires explicit user authorization. `analysis` mode is read-only, `write` and `auto` modes require explicit `--approval-mode yolo` (Gemini/Qwen) or `--skip-git-repo-check -s danger-full-access` (Codex). This prevents unauthorized modifications. (`intelligent-tools-strategy.md`)
* **No File Modifications in Analysis Mode**: By design, analysis agents cannot modify the file system, reducing risk. (`intelligent-tools-strategy.md`)
* **Context Scope Limitation**: Use of `cd` and `--include-directories` limits the context provided to agents, preventing agents from accessing unrelated parts of the codebase. (`intelligent-tools-strategy.md`)
* **Quantification Requirements**: The strict quantification and explicit listing of modification points provide transparency and auditability for agent actions. (`action-planning-agent.md`)
**Scalability**:
* **On-Demand Resource Creation**: Directories and files (like subtask JSONs) are created only when needed, avoiding unnecessary resource allocation. (`workflow-architecture.md`)
* **Distributed AI Processing**: Leveraging external AI services (Gemini, Qwen, Codex) offloads heavy computational tasks, allowing the core CLI system to remain lightweight and orchestrate.
* **Hierarchical Task Decomposition**: The ability to break down complex problems into smaller, manageable subtasks (max 2 levels) inherently supports handling larger projects by distributing work. (`workflow-architecture.md`)
* **Task Complexity Classification**: The system classifies tasks (simple, medium, complex) and applies appropriate timeout allocations and strategies, ensuring efficient resource utilization. (`workflow-architecture.md`)
* **Session Management**: The directory-based session management allows for multiple concurrent workflows by separating their states. (`workflow-architecture.md`)

View File

@@ -1,117 +1,67 @@
# 📖 Claude Code Workflow - Real-World Examples
# EXAMPLES: Claude_dms3 Usage Examples
This document provides practical, real-world examples of using CCW for common development tasks.
## Related Files
- `GETTING_STARTED.md` - Initial setup and quick start guide.
- `EXAMPLES.md` (root) - Comprehensive real-world examples across various development phases.
- `.claude/skills/command-guide/guides/examples.md` - Specific command usage examples across different modes.
---
## Introduction
This document provides practical, end-to-end examples demonstrating the core usage of the Claude_dms3 system. It covers everything from quick start guides to complex development workflows, illustrating how specialized AI agents and integrated tools can automate and streamline software engineering tasks.
## 📋 Table of Contents
**Prerequisites**: Ensure Claude_dms3 is installed and configured as per the [Installation Guide](INSTALL.md) and that you have a basic understanding of the core concepts explained in [GETTING_STARTED.md](GETTING_STARTED.md).
- [Quick Start Examples](#quick-start-examples)
- [Web Development](#web-development)
- [API Development](#api-development)
- [Testing & Quality Assurance](#testing--quality-assurance)
- [Refactoring](#refactoring)
- [UI/UX Design](#uiux-design)
- [Bug Fixes](#bug-fixes)
- [Documentation](#documentation)
- [DevOps & Automation](#devops--automation)
- [Complex Projects](#complex-projects)
## Quick Start Example
---
Let's create a "Hello World" web application using a simple Express API.
## 🚀 Quick Start Examples
### Example 1: Simple Express API
**Objective**: Create a basic Express.js API with CRUD operations
### Step 1: Create an Execution Plan
Tell Claude_dms3 what you want to build. The system will analyze your request and automatically generate a detailed, executable task plan.
```bash
# Option 1: Lite workflow (fastest)
/workflow:lite-plan "Create Express API with CRUD endpoints for users (GET, POST, PUT, DELETE)"
/workflow:plan "Create a simple Express API that returns Hello World at the root path"
```
# Option 2: Full workflow (more structured)
/workflow:plan "Create Express API with CRUD endpoints for users"
* **Explanation**: The `/workflow:plan` command initiates a fully automated planning process. This includes context gathering from your project, analysis by AI agents to determine the best implementation path, and the generation of specific task files (in `.json` format) in a new workflow session (`.workflow/active/WFS-create-a-simple-express-api/`).
### Step 2: Execute the Plan
Once the plan is created, command the AI agents to start working.
```bash
/workflow:execute
```
**What CCW does**:
1. Analyzes your project structure
2. Creates Express app setup
3. Implements CRUD routes
4. Adds error handling middleware
5. Creates basic tests
* **Explanation**: Claude_dms3's agents, such as `@code-developer`, will begin executing the planned tasks one by one. This involves creating files, writing code, and installing necessary dependencies to fulfill the "Hello World" API request.
**Result**:
```
src/
├── app.js # Express app setup
├── routes/
│ └── users.js # User CRUD routes
├── controllers/
│ └── userController.js
└── tests/
└── users.test.js
```
### Example 2: React Component
**Objective**: Create a React login form component
### Step 3: Check the Status (Optional)
Monitor the progress of the current workflow at any time.
```bash
/workflow:lite-plan "Create a React login form component with email and password fields, validation, and submit handling"
/workflow:status
```
**What CCW does**:
1. Creates LoginForm component
2. Adds form validation (email format, password requirements)
3. Implements state management
4. Adds error display
5. Creates component tests
* **Explanation**: This command provides an overview of task completion, the currently executing task, and the upcoming steps in the workflow.
**Result**:
```jsx
// components/LoginForm.jsx
import React, { useState } from 'react';
## Core Use Cases
export function LoginForm({ onSubmit }) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [errors, setErrors] = useState({});
### 1. Full-Stack Todo Application Development
**Objective**: Build a complete todo application with a React frontend and an Express backend, including user authentication, real-time updates, and dark mode.
// ... validation and submit logic
}
```
---
## 🌐 Web Development
### Example 3: Full-Stack Todo Application
**Objective**: Build a complete todo application with React frontend and Express backend
#### Phase 1: Planning with Brainstorming
#### Phase 1: Planning with Multi-Agent Brainstorming
Utilize brainstorming to analyze the complex requirements from multiple perspectives before implementation.
```bash
# Multi-perspective analysis
# Multi-perspective analysis for the full-stack application
/workflow:brainstorm:auto-parallel "Full-stack todo application with user authentication, real-time updates, and dark mode"
# Review brainstorming artifacts
# Then create implementation plan
# Review brainstorming artifacts, then create the implementation plan
/workflow:plan
# Verify plan quality
# Verify the plan quality
/workflow:action-plan-verify
```
**Brainstorming generates**:
- System architecture analysis
- UI/UX design recommendations
- Data model design
- Security considerations
- API design patterns
#### Phase 2: Implementation
Execute the generated plan to build the application components.
```bash
# Execute the plan
@@ -121,45 +71,22 @@ export function LoginForm({ onSubmit }) {
/workflow:status
```
**What CCW implements**:
**Backend** (`server/`):
- Express server setup
- MongoDB/PostgreSQL integration
- JWT authentication
- RESTful API endpoints
- WebSocket for real-time updates
- Input validation middleware
**Frontend** (`client/`):
- React app with routing
- Authentication flow
- Todo CRUD operations
- Real-time updates via WebSocket
- Dark mode toggle
- Responsive design
#### Phase 3: Testing
Generate and execute comprehensive tests for the implemented features.
```bash
# Generate comprehensive tests
/workflow:test-gen WFS-todo-application
/workflow:test-gen WFS-todo-application # WFS-todo-application is the session ID
# Execute test tasks
/workflow:execute
# Run iterative test-fix cycle
# Run an iterative test-fix cycle if needed
/workflow:test-cycle-execute
```
**Tests created**:
- Unit tests for components
- Integration tests for API
- E2E tests for user flows
- Authentication tests
- WebSocket connection tests
#### Phase 4: Quality Review
#### Phase 4: Quality Review & Completion
Review the implemented solution for security, architecture, and overall quality, then complete the session.
```bash
# Security review
@@ -170,654 +97,203 @@ export function LoginForm({ onSubmit }) {
# General quality review
/workflow:review
```
**Complete session**:
```bash
# Complete the session
/workflow:session:complete
```
---
### Example 4: E-commerce Product Catalog
**Objective**: Build product catalog with search, filters, and pagination
### 2. RESTful API with Authentication
**Objective**: Create a RESTful API with JWT authentication and role-based access control for a `posts` resource.
```bash
# Start with UI design exploration
/workflow:ui-design:explore-auto --prompt "Modern e-commerce product catalog with grid layout, filters sidebar, and search bar" --targets "catalog,product-card" --style-variants 3
# Review designs in compare.html
# Sync selected designs
/workflow:ui-design:design-sync --session <session-id> --selected-prototypes "catalog-v2,product-card-v1"
# Create implementation plan
/workflow:plan
# Execute
/workflow:execute
```
**Features implemented**:
- Product grid with responsive layout
- Search functionality with debounce
- Category/price/rating filters
- Pagination with infinite scroll option
- Product card with image, title, price, rating
- Sort options (price, popularity, newest)
---
## 🔌 API Development
### Example 5: RESTful API with Authentication
**Objective**: Create RESTful API with JWT authentication and role-based access control
```bash
# Detailed planning
# Initiate detailed planning for the API
/workflow:plan "RESTful API with JWT authentication, role-based access control (admin, user), and protected endpoints for posts resource"
# Verify plan
# Verify the plan for consistency and completeness
/workflow:action-plan-verify
# Execute
# Execute the implementation plan
/workflow:execute
```
**Implementation includes**:
* **Implementation includes**:
* **Authentication Endpoints**: `POST /api/auth/register`, `POST /api/auth/login`, `POST /api/auth/refresh`, `POST /api/auth/logout`.
* **Protected Resources**: `GET /api/posts` (public), `GET /api/posts/:id` (public), `POST /api/posts` (authenticated), `PUT /api/posts/:id` (authenticated, owner or admin), `DELETE /api/posts/:id` (authenticated, owner or admin).
* **Middleware**: `authenticate` (verifies JWT token), `authorize(['admin'])` (role-based access), `validateRequest` (input validation), `errorHandler` (centralized error handling).
**Authentication**:
```javascript
// routes/auth.js
POST /api/auth/register
POST /api/auth/login
POST /api/auth/refresh
POST /api/auth/logout
```
**Protected Resources**:
```javascript
// routes/posts.js
GET /api/posts # Public
GET /api/posts/:id # Public
POST /api/posts # Authenticated
PUT /api/posts/:id # Authenticated (owner or admin)
DELETE /api/posts/:id # Authenticated (owner or admin)
```
**Middleware**:
- `authenticate` - Verifies JWT token
- `authorize(['admin'])` - Role-based access
- `validateRequest` - Input validation
- `errorHandler` - Centralized error handling
### Example 6: GraphQL API
**Objective**: Convert REST API to GraphQL
### 3. Test-Driven Development (TDD)
**Objective**: Implement user authentication (login, registration, password reset) using a TDD approach.
```bash
# Analyze existing REST API
/cli:analyze "Analyze REST API structure in src/routes/"
# Plan GraphQL migration
/workflow:plan "Migrate REST API to GraphQL with queries, mutations, and subscriptions for posts and users"
# Execute migration
/workflow:execute
```
**GraphQL schema created**:
```graphql
type Query {
posts(limit: Int, offset: Int): [Post!]!
post(id: ID!): Post
user(id: ID!): User
}
type Mutation {
createPost(input: CreatePostInput!): Post!
updatePost(id: ID!, input: UpdatePostInput!): Post!
deletePost(id: ID!): Boolean!
}
type Subscription {
postCreated: Post!
postUpdated: Post!
}
```
---
## 🧪 Testing & Quality Assurance
### Example 7: Test-Driven Development (TDD)
**Objective**: Implement user authentication using TDD approach
```bash
# Start TDD workflow
# Start the TDD workflow for user authentication
/workflow:tdd-plan "User authentication with email/password login, registration, and password reset"
# Execute (Red-Green-Refactor cycles)
# Execute the TDD cycles (Red-Green-Refactor)
/workflow:execute
# Verify TDD compliance
# Verify TDD compliance (optional)
/workflow:tdd-verify
```
**TDD cycle tasks created**:
* **TDD cycle tasks created**: Claude_dms3 will create tasks in cycles (e.g., Registration, Login, Password Reset), where each cycle involves writing a failing test, implementing the feature to pass the test, and then refactoring the code.
**Cycle 1: Registration**
1. `IMPL-1.1` - Write failing test for user registration
2. `IMPL-1.2` - Implement registration to pass test
3. `IMPL-1.3` - Refactor registration code
## Advanced & Integration Examples
**Cycle 2: Login**
1. `IMPL-2.1` - Write failing test for login
2. `IMPL-2.2` - Implement login to pass test
3. `IMPL-2.3` - Refactor login code
**Cycle 3: Password Reset**
1. `IMPL-3.1` - Write failing test for password reset
2. `IMPL-3.2` - Implement password reset
3. `IMPL-3.3` - Refactor password reset
### Example 8: Adding Tests to Existing Code
**Objective**: Generate comprehensive tests for existing authentication module
```bash
# Create test generation workflow from existing code
/workflow:test-gen WFS-authentication-implementation
# Execute test tasks
/workflow:execute
# Run test-fix cycle until all tests pass
/workflow:test-cycle-execute --max-iterations 5
```
**Tests generated**:
- Unit tests for each function
- Integration tests for auth flow
- Edge case tests (invalid input, expired tokens, etc.)
- Security tests (SQL injection, XSS, etc.)
- Performance tests (load testing, rate limiting)
**Test coverage**: Aims for 80%+ coverage
---
## 🔄 Refactoring
### Example 9: Monolith to Microservices
**Objective**: Refactor monolithic application to microservices architecture
### 1. Monolith to Microservices Refactoring
**Objective**: Refactor a monolithic application into a microservices architecture with an API gateway, service discovery, and message queue.
#### Phase 1: Analysis
Perform deep architecture analysis and multi-role brainstorming.
```bash
# Deep architecture analysis
# Deep architecture analysis to create a migration strategy
/cli:mode:plan --tool gemini "Analyze current monolithic architecture and create microservices migration strategy"
# Multi-role brainstorming
# Multi-role brainstorming for microservices design
/workflow:brainstorm:auto-parallel "Migrate monolith to microservices with API gateway, service discovery, and message queue" --count 5
```
#### Phase 2: Planning
Create a detailed migration plan based on the analysis.
```bash
# Create detailed migration plan
# Create a detailed migration plan for the first phase
/workflow:plan "Phase 1 microservices migration: Extract user service and auth service from monolith"
# Verify plan
# Verify the plan
/workflow:action-plan-verify
```
#### Phase 3: Implementation
Execute the migration plan and review the architecture.
```bash
# Execute migration
# Execute the migration tasks
/workflow:execute
# Review architecture
# Review the new microservices architecture
/workflow:review --type architecture
```
**Microservices created**:
```
services/
├── user-service/
│ ├── src/
│ ├── Dockerfile
│ └── package.json
├── auth-service/
│ ├── src/
│ ├── Dockerfile
│ └── package.json
├── api-gateway/
│ ├── src/
│ └── config/
└── docker-compose.yml
```
### 2. Real-Time Chat Application
**Objective**: Build a real-time chat application with WebSocket, message history, and file sharing.
### Example 10: Code Optimization
**Objective**: Optimize database queries for performance
#### Complete Workflow
This example combines brainstorming, UI design, planning, implementation, testing, and review.
```bash
# Analyze current performance
/cli:mode:code-analysis "Analyze database query performance in src/repositories/"
# 1. Brainstorm for comprehensive feature specification
/workflow:brainstorm:auto-parallel "Real-time chat application with WebSocket, message history, file upload, user presence, typing indicators" --count 5
# Create optimization plan
/workflow:plan "Optimize database queries with indexing, query optimization, and caching"
# 2. UI Design exploration
/workflow:ui-design:explore-auto --prompt "Modern chat interface with message list, input box, user sidebar, file preview" --targets "chat-window,message-bubble,user-list" --style-variants 2
# Execute optimizations
/workflow:execute
```
# 3. Sync selected designs (assuming a session ID from the UI design step)
/workflow:ui-design:design-sync --session <session-id>
**Optimizations implemented**:
- Database indexing strategy
- N+1 query elimination
- Query result caching (Redis)
- Connection pooling
- Pagination for large datasets
- Database query monitoring
---
## 🎨 UI/UX Design
### Example 11: Design System Creation
**Objective**: Create a complete design system for a SaaS application
```bash
# Extract design from local reference images
/workflow:ui-design:imitate-auto --input "design-refs/*.png"
# Or import from existing code
/workflow:ui-design:imitate-auto --input "./src/components"
# Or create from scratch
/workflow:ui-design:explore-auto --prompt "Modern SaaS design system with primary components: buttons, inputs, cards, modals, navigation" --targets "button,input,card,modal,navbar" --style-variants 3
```
**Design system includes**:
- Color palette (primary, secondary, accent, neutral)
- Typography scale (headings, body, captions)
- Spacing system (4px grid)
- Component library:
- Buttons (primary, secondary, outline, ghost)
- Form inputs (text, select, checkbox, radio)
- Cards (basic, elevated, outlined)
- Modals (small, medium, large)
- Navigation (sidebar, topbar, breadcrumbs)
- Animation patterns
- Responsive breakpoints
**Output**:
```
design-system/
├── tokens/
│ ├── colors.json
│ ├── typography.json
│ └── spacing.json
├── components/
│ ├── Button.jsx
│ ├── Input.jsx
│ └── ...
└── documentation/
└── design-system.html
```
### Example 12: Responsive Landing Page
**Objective**: Design and implement a marketing landing page
```bash
# Design exploration
/workflow:ui-design:explore-auto --prompt "Modern SaaS landing page with hero section, features grid, pricing table, testimonials, and CTA" --targets "hero,features,pricing,testimonials" --style-variants 2 --layout-variants 3 --device-type responsive
# Select best designs and sync
/workflow:ui-design:design-sync --session <session-id> --selected-prototypes "hero-v2,features-v1,pricing-v3"
# Implement
# 4. Plan the implementation
/workflow:plan
# 5. Verify the plan
/workflow:action-plan-verify
# 6. Execute the implementation
/workflow:execute
# 7. Generate tests for the application
/workflow:test-gen <session-id>
# 8. Execute the generated tests
/workflow:execute
# 9. Review the security and architecture
/workflow:review --type security
/workflow:review --type architecture
# 10. Complete the session
/workflow:session:complete
```
**Sections implemented**:
- Hero section with animated background
- Feature cards with icons
- Pricing comparison table
- Customer testimonials carousel
- FAQ accordion
- Contact form
- Responsive navigation
- Dark mode support
## Testing Examples
---
## 🐛 Bug Fixes
### Example 13: Quick Bug Fix
**Objective**: Fix login button not working on mobile
### 1. Adding Tests to Existing Code
**Objective**: Generate comprehensive tests for an existing authentication module.
```bash
# Analyze bug
/cli:mode:bug-diagnosis "Login button click event not firing on mobile Safari"
# Create a test generation workflow for the authentication implementation
/workflow:test-gen WFS-authentication-implementation # WFS-authentication-implementation is the session ID
# Claude analyzes and implements fix
# Execute the test tasks (generate and run tests)
/workflow:execute
# Run a test-fix cycle until all tests pass
/workflow:test-cycle-execute --max-iterations 5
```
**Fix implemented**:
```javascript
// Before
button.onclick = handleLogin;
* **Tests generated**: Unit tests for each function, integration tests for the auth flow, edge case tests (invalid input, expired tokens), security tests (SQL injection, XSS), and performance tests.
// After (adds touch event support)
button.addEventListener('click', handleLogin);
button.addEventListener('touchend', (e) => {
e.preventDefault();
handleLogin(e);
});
```
### Example 14: Complex Bug Investigation
**Objective**: Debug memory leak in React application
### 2. Bug Fixing - Complex Bug Investigation
**Objective**: Debug a memory leak in a React application caused by uncleared event listeners.
#### Investigation
Start a dedicated session for thorough investigation.
```bash
# Start session for thorough investigation
# Start a new session for memory leak investigation
/workflow:session:start "Memory Leak Investigation"
# Deep bug analysis
# Perform deep bug analysis using Gemini
/cli:mode:bug-diagnosis --tool gemini "Memory leak in React components - event listeners not cleaned up"
# Create fix plan
# Create a fix plan based on the analysis
/workflow:plan "Fix memory leaks in React components: cleanup event listeners and cancel subscriptions"
```
#### Implementation
Execute the fixes and generate tests to prevent regression.
```bash
# Execute fixes
# Execute the memory leak fixes
/workflow:execute
# Generate tests to prevent regression
# Generate tests to prevent future regressions
/workflow:test-gen WFS-memory-leak-investigation
# Execute tests
# Execute the generated tests
/workflow:execute
```
**Issues found and fixed**:
1. Missing cleanup in `useEffect` hooks
2. Event listeners not removed
3. Uncancelled API requests on unmount
4. Large state objects not cleared
---
## 📝 Documentation
### Example 15: API Documentation Generation
**Objective**: Generate comprehensive API documentation
```bash
# Analyze existing API
/memory:load "Generate API documentation for all endpoints"
# Create documentation
/workflow:plan "Generate OpenAPI/Swagger documentation for REST API with examples and authentication info"
# Execute
/workflow:execute
```
**Documentation includes**:
- OpenAPI 3.0 specification
- Interactive Swagger UI
- Request/response examples
- Authentication guide
- Rate limiting info
- Error codes reference
### Example 16: Project README Generation
**Objective**: Create comprehensive README for open-source project
```bash
# Update project memory first
/memory:update-full --tool gemini
# Generate README
/workflow:plan "Create comprehensive README.md with installation, usage, examples, API reference, and contributing guidelines"
/workflow:execute
```
**README sections**:
- Project overview
- Features
- Installation instructions
- Quick start guide
- Usage examples
- API reference
- Configuration
- Contributing guidelines
- License
---
## ⚙️ DevOps & Automation
### Example 17: CI/CD Pipeline Setup
**Objective**: Set up GitHub Actions CI/CD pipeline
```bash
/workflow:plan "Create GitHub Actions workflow for Node.js app with linting, testing, building, and deployment to AWS"
/workflow:execute
```
**Pipeline created**:
```yaml
# .github/workflows/ci-cd.yml
name: CI/CD
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run tests
run: npm test
build:
needs: test
runs-on: ubuntu-latest
steps:
- name: Build
run: npm run build
deploy:
needs: build
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- name: Deploy to AWS
run: npm run deploy
```
### Example 18: Docker Containerization
**Objective**: Dockerize full-stack application
```bash
# Plan containerization
/workflow:plan "Dockerize full-stack app with React frontend, Express backend, PostgreSQL database, and Redis cache using docker-compose"
# Execute
/workflow:execute
# Review
/workflow:review --type architecture
```
**Created files**:
```
├── docker-compose.yml
├── frontend/
│ └── Dockerfile
├── backend/
│ └── Dockerfile
├── .dockerignore
└── README.docker.md
```
---
## 🏗️ Complex Projects
### Example 19: Real-Time Chat Application
**Objective**: Build real-time chat with WebSocket, message history, and file sharing
#### Complete Workflow
```bash
# 1. Brainstorm
/workflow:brainstorm:auto-parallel "Real-time chat application with WebSocket, message history, file upload, user presence, typing indicators" --count 5
# 2. UI Design
/workflow:ui-design:explore-auto --prompt "Modern chat interface with message list, input box, user sidebar, file preview" --targets "chat-window,message-bubble,user-list" --style-variants 2
# 3. Sync designs
/workflow:ui-design:design-sync --session <session-id>
# 4. Plan implementation
/workflow:plan
# 5. Verify plan
/workflow:action-plan-verify
# 6. Execute
/workflow:execute
# 7. Generate tests
/workflow:test-gen <session-id>
# 8. Execute tests
/workflow:execute
# 9. Review
/workflow:review --type security
/workflow:review --type architecture
# 10. Complete
/workflow:session:complete
```
**Features implemented**:
- WebSocket server (Socket.io)
- Real-time messaging
- Message persistence (MongoDB)
- File upload (S3/local storage)
- User authentication
- Typing indicators
- Read receipts
- User presence (online/offline)
- Message search
- Emoji support
- Mobile responsive
### Example 20: Data Analytics Dashboard
**Objective**: Build interactive dashboard with charts and real-time data
```bash
# Brainstorm data viz approach
/workflow:brainstorm:auto-parallel "Data analytics dashboard with real-time metrics, interactive charts, filters, and export functionality"
# Plan implementation
/workflow:plan "Analytics dashboard with Chart.js/D3.js, real-time data updates via WebSocket, date range filters, and CSV export"
# Execute
/workflow:execute
```
**Dashboard features**:
- Real-time metric cards (users, revenue, conversions)
- Line charts (trends over time)
- Bar charts (comparisons)
- Pie charts (distributions)
- Data tables with sorting/filtering
- Date range picker
- Export to CSV/PDF
- Responsive grid layout
- Dark mode
- WebSocket updates every 5 seconds
---
## 💡 Tips for Effective Examples
### Best Practices
1. **Start with clear objectives**
- Define what you want to build
- List key features
- Specify technologies if needed
2. **Use appropriate workflow**
- Simple tasks: `/workflow:lite-plan`
- Complex features: `/workflow:brainstorm``/workflow:plan`
- Existing code: `/workflow:test-gen` or `/cli:analyze`
3. **Leverage quality gates**
- Run `/workflow:action-plan-verify` before execution
- Use `/workflow:review` after implementation
- Generate tests with `/workflow:test-gen`
4. **Maintain memory**
- Update memory after major changes
- Use `/memory:load` for quick context
- Keep CLAUDE.md files up to date
5. **Complete sessions**
- Always run `/workflow:session:complete`
- Generates lessons learned
- Archives session for reference
---
## 🔗 Related Resources
- [Getting Started Guide](GETTING_STARTED.md) - Basics
- [Architecture](ARCHITECTURE.md) - How it works
- [Command Reference](COMMAND_REFERENCE.md) - All commands
- [FAQ](FAQ.md) - Common questions
- [Contributing](CONTRIBUTING.md) - How to contribute
---
## 📬 Share Your Examples
Have a great example to share? Contribute to this document!
See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
---
**Last Updated**: 2025-11-20
**Version**: 5.8.1
## Best Practices & Troubleshooting
### Best Practices for Effective Usage
1. **Start with clear objectives**: Define what you want to build, list key features, and specify technologies.
2. **Use appropriate workflow**:
* Simple tasks: `/workflow:lite-plan`
* Complex features: `/workflow:brainstorm``/workflow:plan`
* Existing code: `/workflow:test-gen` or `/cli:analyze`
3. **Leverage quality gates**:
* Run `/workflow:action-plan-verify` before execution.
* Use `/workflow:review` after implementation.
* Generate tests with `/workflow:test-gen`.
4. **Maintain memory**:
* Update memory after major changes with `/memory:update-full` or `/memory:update-related`.
* Use `/memory:load` for quick, task-specific context.
5. **Complete sessions**: Always run `/workflow:session:complete` to generate lessons learned and archive the session.
### Troubleshooting Common Issues
* **Problem: Prompt shows "No active session found"**
* **Reason**: You haven't started a workflow session, or the current session is complete.
* **Solution**: Use `/workflow:session:start "Your task description"` to start a new session.
* **Problem: Command execution fails or gets stuck**
* **Reason**: Could be a network issue, AI model limitation, or the task is too complex.
* **Solution**:
1. First, try `/workflow:status` to check the current state.
2. Check log files in the `.workflow/WFS-<session-name>/.chat/` directory for detailed error messages.
3. If the task is too complex, break it down into smaller tasks and use `/workflow:plan` to create a new plan.
## Conclusion
This document provides a foundational understanding of how to leverage Claude_dms3 for various software development tasks, from initial planning to complex refactoring and comprehensive testing. By following these examples and best practices, users can effectively harness the power of AI-driven automation to enhance their development workflows.