feat(workflow): add project-level state management with intelligent initialization

Implement comprehensive project.json system for tracking project state, completed features, and architecture overview.

## New Features

### 1. /workflow:init Command (NEW)
- Independent project initialization command using cli-explore-agent
- Deep Scan mode analyzes: technology stack, architecture, key components, metrics
- Generates project.json with comprehensive overview field
- Supports --regenerate flag to update analysis while preserving features
- One-time initialization with intelligent project cognition

### 2. Enhanced session:start
- Added Step 0: Check project.json existence before session creation
- Auto-calls /workflow:init if project.json missing
- Separated project-level vs session-level initialization responsibilities

### 3. Enhanced session:complete
- Added Phase 3: Update Project Feature Registry
- Extracts feature metadata from IMPL_PLAN.md
- Records completed sessions as features in project.json
- Includes: title, description, tags, timeline, traceability (archive_path, commit_hash)
- Auto-generates feature IDs and tags from implementation plans

### 4. Enhanced status Command
- Added --project flag for project overview mode
- Displays: technology stack, architecture patterns, key components, metrics
- Shows completed features with full traceability
- Provides query commands for feature exploration

### 5. Enhanced context-gather
- Integrated project.json reading in context-search-agent workflow
- Phase 1: Load project.json overview as foundational context
- Phase 3: Populate context-package.json from project.json
- Prioritizes project.json context for architecture and tech stack
- Avoids redundant project analysis on every planning session

## Data Flow
project.json (init) → context-gather → context-package.json → task-generation
session-complete → project.json (features registry)

## Benefits
- Single source of truth for project state
- Efficient context reuse across sessions
- Complete feature traceability and history
- Consistent architectural baseline for all workflows

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
catlog22
2025-11-18 11:10:07 +08:00
parent b4e09213e4
commit 4dafec7054
5 changed files with 886 additions and 14 deletions

View File

@@ -0,0 +1,446 @@
---
name: init
description: Initialize project-level state with intelligent project analysis using cli-explore-agent
argument-hint: "[--regenerate]"
examples:
- /workflow:init
- /workflow:init --regenerate
---
# Workflow Init Command (/workflow:init)
## Overview
Initializes `.workflow/project.json` with comprehensive project understanding by leveraging **cli-explore-agent** for intelligent analysis.
**Key Features**:
- **Intelligent Project Analysis**: Uses cli-explore-agent's Deep Scan mode
- **Technology Stack Detection**: Identifies languages, frameworks, build tools
- **Architecture Overview**: Discovers patterns, layers, key components
- **One-time Initialization**: Skips if project.json exists (unless --regenerate)
## Usage
```bash
/workflow:init # Initialize project state (skip if exists)
/workflow:init --regenerate # Force regeneration of project.json
```
## Implementation Flow
### Step 1: Check Existing State
```bash
# Check if project.json already exists
bash(test -f .workflow/project.json && echo "EXISTS" || echo "NOT_FOUND")
```
**If EXISTS and no --regenerate flag**:
```
Project already initialized at .workflow/project.json
Use /workflow:init --regenerate to rebuild project analysis
Use /workflow:status --project to view current state
```
**If NOT_FOUND or --regenerate flag**: Proceed to initialization
### Step 2: Project Discovery
```bash
# Get project name and root
bash(basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")
bash(git rev-parse --show-toplevel 2>/dev/null || pwd)
# Create .workflow directory
bash(mkdir -p .workflow)
```
### Step 3: Intelligent Project Analysis
**Invoke cli-explore-agent** with Deep Scan mode for comprehensive understanding:
```javascript
Task(
subagent_type="cli-explore-agent",
description="Deep project analysis",
prompt=`
Analyze project structure and technology stack for workflow initialization.
## Analysis Objective
Perform Deep Scan analysis to build comprehensive project understanding for .workflow/project.json initialization.
## Required Analysis
### 1. Technology Stack Detection
- **Primary Languages**: Identify all programming languages with file counts
- **Frameworks**: Detect web frameworks (React, Vue, Express, Django, etc.)
- **Build Tools**: Identify build systems (npm, cargo, maven, gradle, etc.)
- **Test Frameworks**: Find testing tools (jest, pytest, go test, etc.)
### 2. Project Architecture
- **Architecture Style**: Identify patterns (MVC, microservices, monorepo, etc.)
- **Layer Structure**: Discover architectural layers (presentation, business, data)
- **Design Patterns**: Find common patterns (singleton, factory, repository, etc.)
- **Key Components**: List 5-10 core modules/components with brief descriptions
### 3. Project Metrics
- **Total Files**: Count source code files
- **Lines of Code**: Estimate total LOC
- **Module Count**: Number of top-level modules/packages
- **Complexity**: Overall complexity rating (low/medium/high)
### 4. Entry Points
- **Main Entry**: Identify primary application entry point(s)
- **CLI Commands**: Discover available commands/scripts
- **API Endpoints**: Find HTTP/REST/GraphQL endpoints (if applicable)
## Execution Mode
Use **Deep Scan** with Dual-Source Strategy:
- Phase 1: Bash structural scan (fast pattern discovery)
- Phase 2: Gemini semantic analysis (design intent, patterns)
- Phase 3: Synthesis (merge findings with attribution)
## Analysis Scope
- Root directory: ${projectRoot}
- Exclude: node_modules, dist, build, .git, vendor, __pycache__
- Focus: Source code directories (src, lib, pkg, app, etc.)
## Output Format
Return JSON structure for programmatic processing:
\`\`\`json
{
"technology_stack": {
"languages": [
{"name": "TypeScript", "file_count": 150, "primary": true},
{"name": "Python", "file_count": 30, "primary": false}
],
"frameworks": ["React", "Express", "TypeORM"],
"build_tools": ["npm", "webpack"],
"test_frameworks": ["Jest", "Supertest"]
},
"architecture": {
"style": "Layered MVC with Repository Pattern",
"layers": ["presentation", "business-logic", "data-access"],
"patterns": ["MVC", "Repository Pattern", "Dependency Injection"],
"key_components": [
{
"name": "Authentication Module",
"path": "src/auth",
"description": "JWT-based authentication with OAuth2 support",
"importance": "high"
},
{
"name": "User Management",
"path": "src/users",
"description": "User CRUD operations and profile management",
"importance": "high"
}
]
},
"metrics": {
"total_files": 180,
"lines_of_code": 15000,
"module_count": 12,
"complexity": "medium"
},
"entry_points": {
"main": "src/index.ts",
"cli_commands": ["npm start", "npm test", "npm run build"],
"api_endpoints": ["/api/auth", "/api/users", "/api/posts"]
},
"analysis_metadata": {
"timestamp": "2025-01-18T10:30:00Z",
"mode": "deep-scan",
"source": "cli-explore-agent"
}
}
\`\`\`
## Quality Requirements
- ✅ All technology stack items verified (no guessing)
- ✅ Key components include file paths for navigation
- ✅ Architecture style based on actual code patterns, not assumptions
- ✅ Metrics calculated from actual file counts/lines
- ✅ Entry points verified as executable
`
)
```
**Agent Output**: JSON structure with comprehensive project analysis
### Step 4: Build project.json from Analysis
**Data Processing**:
```javascript
// Parse agent analysis output
const analysis = JSON.parse(agentOutput);
// Build complete project.json structure
const projectMeta = {
// Basic metadata
project_name: projectName,
initialized_at: new Date().toISOString(),
// Project overview (from cli-explore-agent)
overview: {
description: generateDescription(analysis), // e.g., "TypeScript web application with React frontend"
technology_stack: analysis.technology_stack,
architecture: {
style: analysis.architecture.style,
layers: analysis.architecture.layers,
patterns: analysis.architecture.patterns
},
key_components: analysis.architecture.key_components,
entry_points: analysis.entry_points,
metrics: analysis.metrics
},
// Feature registry (initially empty, populated by complete)
features: [],
// Statistics
statistics: {
total_features: 0,
total_sessions: 0,
last_updated: new Date().toISOString()
},
// Analysis metadata
_metadata: {
initialized_by: "cli-explore-agent",
analysis_timestamp: analysis.analysis_metadata.timestamp,
analysis_mode: analysis.analysis_metadata.mode
}
};
// Helper: Generate project description
function generateDescription(analysis) {
const primaryLang = analysis.technology_stack.languages.find(l => l.primary);
const frameworks = analysis.technology_stack.frameworks.slice(0, 2).join(', ');
return `${primaryLang.name} project using ${frameworks}`;
}
// Write to .workflow/project.json
Write('.workflow/project.json', JSON.stringify(projectMeta, null, 2));
```
### Step 5: Output Summary
```
✓ Project initialized successfully
## Project Overview
Name: ${projectName}
Description: ${overview.description}
### Technology Stack
Languages: ${languages.map(l => l.name).join(', ')}
Frameworks: ${frameworks.join(', ')}
### Architecture
Style: ${architecture.style}
Components: ${key_components.length} core modules identified
### Project Metrics
Files: ${metrics.total_files}
LOC: ${metrics.lines_of_code}
Complexity: ${metrics.complexity}
## Next Steps
1. Start a workflow: /workflow:plan "feature description"
2. View project state: /workflow:status --project
3. View details: cat .workflow/project.json
---
Project state saved to: .workflow/project.json
```
## Extended project.json Schema
### Complete Structure
```json
{
"project_name": "claude_dms3",
"initialized_at": "2025-01-18T10:00:00Z",
"overview": {
"description": "TypeScript workflow automation system with AI agent orchestration",
"technology_stack": {
"languages": [
{"name": "TypeScript", "file_count": 150, "primary": true},
{"name": "Bash", "file_count": 30, "primary": false}
],
"frameworks": ["Node.js"],
"build_tools": ["npm"],
"test_frameworks": ["Jest"]
},
"architecture": {
"style": "Agent-based workflow orchestration with modular command system",
"layers": ["command-layer", "agent-orchestration", "cli-integration"],
"patterns": ["Command Pattern", "Agent Pattern", "Template Method"]
},
"key_components": [
{
"name": "Workflow Planning",
"path": ".claude/commands/workflow",
"description": "Multi-phase planning workflow with brainstorming and task generation",
"importance": "high"
},
{
"name": "Agent System",
"path": ".claude/agents",
"description": "Specialized agents for code development, testing, documentation",
"importance": "high"
},
{
"name": "CLI Tool Integration",
"path": ".claude/scripts",
"description": "Gemini, Qwen, Codex wrapper scripts for AI-powered analysis",
"importance": "medium"
}
],
"entry_points": {
"main": ".claude/commands/workflow/plan.md",
"cli_commands": ["/workflow:plan", "/workflow:execute", "/memory:docs"],
"api_endpoints": []
},
"metrics": {
"total_files": 180,
"lines_of_code": 15000,
"module_count": 12,
"complexity": "medium"
}
},
"features": [],
"statistics": {
"total_features": 0,
"total_sessions": 0,
"last_updated": "2025-01-18T10:00:00Z"
},
"_metadata": {
"initialized_by": "cli-explore-agent",
"analysis_timestamp": "2025-01-18T10:00:00Z",
"analysis_mode": "deep-scan"
}
}
```
## Regeneration Behavior
When using `--regenerate` flag:
1. **Backup existing file**:
```bash
bash(cp .workflow/project.json .workflow/project.json.backup)
```
2. **Preserve features array**:
```javascript
const existingMeta = JSON.parse(Read('.workflow/project.json'));
const preservedFeatures = existingMeta.features || [];
const preservedStats = existingMeta.statistics || {};
```
3. **Re-run cli-explore-agent analysis**
4. **Merge preserved data with new analysis**:
```javascript
const newProjectMeta = {
...analysisResults,
features: preservedFeatures, // Keep existing features
statistics: preservedStats // Keep statistics
};
```
5. **Output**:
```
✓ Project analysis regenerated
Backup saved: .workflow/project.json.backup
Updated:
- Technology stack analysis
- Architecture overview
- Key components discovery
Preserved:
- ${preservedFeatures.length} existing features
- Session statistics
```
## Error Handling
### Agent Failure
```
If cli-explore-agent fails:
1. Fall back to basic initialization
2. Use get_modules_by_depth.sh for structure
3. Create minimal project.json with placeholder overview
4. Log warning: "Project initialized with basic analysis. Run /workflow:init --regenerate for full analysis"
```
### Missing Tools
```
If Gemini CLI unavailable:
1. Agent uses Qwen fallback
2. If both fail, use bash-only analysis
3. Mark in _metadata: "analysis_mode": "bash-fallback"
```
### Invalid Project Root
```
If not in git repo and empty directory:
1. Warn user: "Empty project detected"
2. Create minimal project.json
3. Suggest: "Add code files and run /workflow:init --regenerate"
```
## Integration with Existing Commands
### /workflow:session:start
Modified to check and call init:
```javascript
// In start.md Step 0
if (!FileExists('.workflow/project.json')) {
console.log("Project not initialized. Running /workflow:init...");
SlashCommand({command: "/workflow:init"});
// Wait for completion, then continue with session creation
}
```
### /workflow:status --project
Uses extended overview fields:
```javascript
console.log(`## Technology Stack`);
console.log(`Languages: ${overview.technology_stack.languages.map(l => l.name).join(', ')}`);
console.log(`Frameworks: ${overview.technology_stack.frameworks.join(', ')}`);
console.log(`\n## Architecture`);
console.log(`Style: ${overview.architecture.style}`);
console.log(`Patterns: ${overview.architecture.patterns.join(', ')}`);
console.log(`\n## Key Components (${overview.key_components.length})`);
overview.key_components.forEach(c => {
console.log(`- ${c.name} (${c.path})`);
console.log(` ${c.description}`);
});
```
## Performance Considerations
**Execution Time**:
- cli-explore-agent Deep Scan: 2-5 minutes
- Total initialization: 2-6 minutes (one-time cost)
**Optimization**:
- Skip regeneration if project.json exists
- Cache analysis results in _metadata
- Parallel execution: project discovery + agent analysis
## Related Commands
- `/workflow:session:start` - Calls init if needed
- `/workflow:status --project` - Views project overview
- `/workflow:init --regenerate` - Updates project analysis

View File

@@ -127,6 +127,158 @@ bash(mv .workflow/WFS-session-name .workflow/.archives/WFS-session-name)
Task(subagent_type="universal-executor", description="Complete session archival", prompt=`...`)
```
### Phase 3: Update Project Feature Registry
**Purpose**: Record completed session as a project feature in `.workflow/project.json`.
**Execution**: After agent successfully completes archival, extract feature information and update project registry.
#### Step 3.1: Check Project State Exists
```bash
bash(test -f .workflow/project.json && echo "EXISTS" || echo "SKIP")
```
**If SKIP**: Output warning and skip Phase 3
```
WARNING: No project.json found. Run /workflow:session:start to initialize.
```
#### Step 3.2: Extract Feature Information (Simple Text Processing)
```bash
# Read archived IMPL_PLAN.md
bash(cat .workflow/.archives/WFS-session-name/IMPL_PLAN.md | head -20)
```
**Data Processing** (No agent needed):
1. Extract feature title: First `#` heading line
2. Extract description: First paragraph after heading (max 200 chars)
3. Get session_id from archive path
4. Get completion timestamp
**Extraction Logic**:
```javascript
// Read IMPL_PLAN.md
const planContent = Read(`${archivePath}/IMPL_PLAN.md`);
// Extract title (first # heading)
const titleMatch = planContent.match(/^#\s+(.+)$/m);
const title = titleMatch ? titleMatch[1].trim() : sessionId.replace('WFS-', '');
// Extract description (first paragraph, max 200 chars)
const descMatch = planContent.match(/^#[^\n]+\n\n([^\n]+)/m);
const description = descMatch ? descMatch[1].substring(0, 200).trim() : '';
// Create feature ID (lowercase slug)
const featureId = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').substring(0, 50);
```
#### Step 3.3: Update project.json
```bash
# Read current project state
bash(cat .workflow/project.json)
```
**JSON Update Logic**:
```javascript
// Read existing project.json (created by /workflow:init)
// Note: overview field is managed by /workflow:init, not modified here
const projectMeta = JSON.parse(Read('.workflow/project.json'));
const currentTimestamp = new Date().toISOString();
const currentDate = currentTimestamp.split('T')[0]; // YYYY-MM-DD
// Extract tags from IMPL_PLAN.md (simple keyword extraction)
const tags = extractTags(planContent); // e.g., ["auth", "security"]
// Build feature object with complete metadata
const newFeature = {
id: featureId,
title: title,
description: description,
status: "completed",
tags: tags,
timeline: {
created_at: currentTimestamp,
implemented_at: currentDate,
updated_at: currentTimestamp
},
traceability: {
session_id: sessionId,
archive_path: archivePath, // e.g., ".workflow/.archives/WFS-auth-system"
commit_hash: getLatestCommitHash() || "" // Optional: git rev-parse HEAD
},
docs: [], // Placeholder for future doc links
relations: [] // Placeholder for feature dependencies
};
// Add new feature to array
projectMeta.features.push(newFeature);
// Update statistics
projectMeta.statistics.total_features = projectMeta.features.length;
projectMeta.statistics.total_sessions += 1;
projectMeta.statistics.last_updated = currentTimestamp;
// Write back
Write('.workflow/project.json', JSON.stringify(projectMeta, null, 2));
```
**Helper Functions**:
```javascript
// Extract tags from IMPL_PLAN.md content
function extractTags(planContent) {
const tags = [];
// Look for common keywords
const keywords = {
'auth': /authentication|login|oauth|jwt/i,
'security': /security|encrypt|hash|token/i,
'api': /api|endpoint|rest|graphql/i,
'ui': /component|page|interface|frontend/i,
'database': /database|schema|migration|sql/i,
'test': /test|testing|spec|coverage/i
};
for (const [tag, pattern] of Object.entries(keywords)) {
if (pattern.test(planContent)) {
tags.push(tag);
}
}
return tags.slice(0, 5); // Max 5 tags
}
// Get latest git commit hash (optional)
function getLatestCommitHash() {
try {
const result = Bash({
command: "git rev-parse --short HEAD 2>/dev/null",
description: "Get latest commit hash"
});
return result.trim();
} catch {
return "";
}
}
```
#### Step 3.4: Output Confirmation
```
✓ Feature "${title}" added to project registry
ID: ${featureId}
Session: ${sessionId}
Location: .workflow/project.json
```
**Error Handling**:
- If project.json malformed: Output error, skip update
- If IMPL_PLAN.md missing: Use session_id as title
- If extraction fails: Use minimal defaults
**Phase 3 Total Commands**: 2 bash reads + JSON manipulation
## Archive Query Commands
After archival, you can query the manifest:

View File

@@ -13,6 +13,35 @@ examples:
## Overview
Manages workflow sessions with three operation modes: discovery (manual), auto (intelligent), and force-new.
**Dual Responsibility**:
1. **Project-level initialization** (first-time only): Creates `.workflow/project.json` for feature registry
2. **Session-level initialization** (always): Creates session directory structure
## Step 0: Initialize Project State (First-time Only)
**Executed before all modes** - Ensures project-level state file exists by calling `/workflow:init`.
### Check and Initialize
```bash
# Check if project state exists
bash(test -f .workflow/project.json && echo "EXISTS" || echo "NOT_FOUND")
```
**If NOT_FOUND**, delegate to `/workflow:init`:
```javascript
// Call workflow:init for intelligent project analysis
SlashCommand({command: "/workflow:init"});
// Wait for init completion
// project.json will be created with comprehensive project overview
```
**Output**:
- If EXISTS: `PROJECT_STATE: initialized`
- If NOT_FOUND: Calls `/workflow:init` → creates `.workflow/project.json` with full project analysis
**Note**: `/workflow:init` uses cli-explore-agent to build comprehensive project understanding (technology stack, architecture, key components). This step runs once per project. Subsequent executions skip initialization.
## Mode 1: Discovery Mode (Default)
### Usage

View File

@@ -1,23 +1,159 @@
---
name: workflow:status
description: Generate on-demand task status views from JSON task data with optional task-id filtering for detailed view
argument-hint: "[optional: task-id]"
description: Generate on-demand views for project overview and workflow tasks with optional task-id filtering for detailed view
argument-hint: "[optional: --project|task-id|--validate]"
---
# Workflow Status Command (/workflow:status)
## Overview
Generates on-demand views from JSON task data. No synchronization needed - all views are calculated from the current state of JSON files.
Generates on-demand views from project and session data. Supports two modes:
1. **Project Overview** (`--project`): Shows completed features and project statistics
2. **Workflow Tasks** (default): Shows current session task progress
No synchronization needed - all views are calculated from current JSON state.
## Usage
```bash
/workflow:status # Show current workflow overview
/workflow:status # Show current workflow session overview
/workflow:status --project # Show project-level feature registry
/workflow:status impl-1 # Show specific task details
/workflow:status --validate # Validate workflow integrity
```
## Implementation Flow
### Mode Selection
**Check for --project flag**:
- If `--project` flag present → Execute **Project Overview Mode**
- Otherwise → Execute **Workflow Session Mode** (default)
## Project Overview Mode
### Step 1: Check Project State
```bash
bash(test -f .workflow/project.json && echo "EXISTS" || echo "NOT_FOUND")
```
**If NOT_FOUND**:
```
No project state found.
Run /workflow:session:start to initialize project.
```
### Step 2: Read Project Data
```bash
bash(cat .workflow/project.json)
```
### Step 3: Parse and Display
**Data Processing**:
```javascript
const projectData = JSON.parse(Read('.workflow/project.json'));
const features = projectData.features || [];
const stats = projectData.statistics || {};
const overview = projectData.overview || null;
// Sort features by implementation date (newest first)
const sortedFeatures = features.sort((a, b) =>
new Date(b.implemented_at) - new Date(a.implemented_at)
);
```
**Output Format** (with extended overview):
```
## Project: ${projectData.project_name}
Initialized: ${projectData.initialized_at}
${overview ? `
### Overview
${overview.description}
**Technology Stack**:
${overview.technology_stack.languages.map(l => `- ${l.name}${l.primary ? ' (primary)' : ''}: ${l.file_count} files`).join('\n')}
Frameworks: ${overview.technology_stack.frameworks.join(', ')}
**Architecture**:
Style: ${overview.architecture.style}
Patterns: ${overview.architecture.patterns.join(', ')}
**Key Components** (${overview.key_components.length}):
${overview.key_components.map(c => `- ${c.name} (${c.path})\n ${c.description}`).join('\n')}
**Metrics**:
- Files: ${overview.metrics.total_files}
- Lines of Code: ${overview.metrics.lines_of_code}
- Complexity: ${overview.metrics.complexity}
---
` : ''}
### Completed Features (${stats.total_features})
${sortedFeatures.map(f => `
- ${f.title} (${f.timeline?.implemented_at || f.implemented_at})
${f.description}
Tags: ${f.tags?.join(', ') || 'none'}
Session: ${f.traceability?.session_id || f.session_id}
Archive: ${f.traceability?.archive_path || 'unknown'}
${f.traceability?.commit_hash ? `Commit: ${f.traceability.commit_hash}` : ''}
`).join('\n')}
### Project Statistics
- Total Features: ${stats.total_features}
- Total Sessions: ${stats.total_sessions}
- Last Updated: ${stats.last_updated}
### Quick Access
- View session details: /workflow:status
- Archive query: jq '.archives[] | select(.session_id == "SESSION_ID")' .workflow/.archives/manifest.json
- Documentation: .workflow/docs/${projectData.project_name}/
### Query Commands
# Find by tag
cat .workflow/project.json | jq '.features[] | select(.tags[] == "auth")'
# View archive
cat ${feature.traceability.archive_path}/IMPL_PLAN.md
# List all tags
cat .workflow/project.json | jq -r '.features[].tags[]' | sort -u
```
**Empty State**:
```
## Project: ${projectData.project_name}
Initialized: ${projectData.initialized_at}
No features completed yet.
Complete your first workflow session to add features:
1. /workflow:plan "feature description"
2. /workflow:execute
3. /workflow:session:complete
```
### Step 4: Show Recent Sessions (Optional)
```bash
# List 5 most recent archived sessions
bash(ls -1t .workflow/.archives/WFS-* 2>/dev/null | head -5 | xargs -I {} basename {})
```
**Output**:
```
### Recent Sessions
- WFS-auth-system (archived)
- WFS-payment-flow (archived)
- WFS-user-dashboard (archived)
Use /workflow:session:complete to archive current session.
```
## Workflow Session Mode (Default)
### Step 1: Find Active Session
```bash
find .workflow/ -name ".active-*" -type f 2>/dev/null | head -1
@@ -116,4 +252,110 @@ Session file valid
8 task files found
3 summaries found
5 tasks pending completion
```
## Project Mode Quick Commands
### Basic Operations
```bash
# Check if project initialized
bash(test -f .workflow/project.json && echo "Initialized" || echo "Not initialized")
# Read project data
bash(cat .workflow/project.json)
# Count total features
bash(cat .workflow/project.json | jq '.statistics.total_features')
# List all feature IDs
bash(cat .workflow/project.json | jq -r '.features[].id')
# Find feature by keyword
bash(cat .workflow/project.json | jq '.features[] | select(.title | test("auth"; "i"))')
# Get most recent feature
bash(cat .workflow/project.json | jq '.features | sort_by(.implemented_at) | reverse | .[0]')
# List archived sessions
bash(ls -1t .workflow/.archives/WFS-* 2>/dev/null | head -5)
```
### Output Comparison
**Project Overview** (`--project`):
```
## Project: claude_dms3
Initialized: 2025-01-18T10:00:00Z
### Overview
TypeScript workflow automation system with AI agent orchestration
**Technology Stack**:
- TypeScript (primary): 150 files
- Bash: 30 files
Frameworks: Node.js
**Architecture**:
Style: Agent-based workflow orchestration with modular command system
Patterns: Command Pattern, Agent Pattern, Template Method
**Key Components** (3):
- Workflow Planning (.claude/commands/workflow)
Multi-phase planning workflow with brainstorming and task generation
- Agent System (.claude/agents)
Specialized agents for code development, testing, documentation
- CLI Tool Integration (.claude/scripts)
Gemini, Qwen, Codex wrapper scripts for AI-powered analysis
**Metrics**:
- Files: 180
- Lines of Code: 15000
- Complexity: medium
---
### Completed Features (2)
- Authentication System (2025-01-15)
JWT-based authentication with OAuth2 support
Tags: auth, security, api
Session: WFS-auth-system
Archive: .workflow/.archives/WFS-auth-system
Commit: a1b2c3d
- Workflow Planning (2025-01-10)
Multi-phase planning workflow with agent coordination
Tags: workflow, planning
Session: WFS-workflow-v2
Archive: .workflow/.archives/WFS-workflow-v2
Commit: e5f6g7h
### Project Statistics
- Total Features: 2
- Total Sessions: 15
- Last Updated: 2025-01-18T15:30:00Z
### Query Commands
# Find by tag
cat .workflow/project.json | jq '.features[] | select(.tags[] == "auth")'
# View archive
cat .workflow/.archives/WFS-auth-system/IMPL_PLAN.md
# List all tags
cat .workflow/project.json | jq -r '.features[].tags[]' | sort -u
# Regenerate project analysis
/workflow:init --regenerate
```
**Session Overview** (default):
```
Session: WFS-user-auth
Status: ACTIVE
Progress: 5/12 tasks
Current: impl-3 (Building API endpoints)
Next: impl-4 (Adding authentication)
Completed: impl-1, impl-2
```

View File

@@ -71,9 +71,10 @@ You are executing as context-search-agent (.claude/agents/context-search-agent.m
Execute complete context-search-agent workflow for implementation planning:
### Phase 1: Initialization & Pre-Analysis
1. **Detection**: Check for existing context-package (early exit if valid)
2. **Foundation**: Initialize code-index, get project structure, load docs
3. **Analysis**: Extract keywords, determine scope, classify complexity
1. **Project State Loading**: Read and parse `.workflow/project.json`. Use its `overview` section as the foundational `project_context`. This is your primary source for architecture, tech stack, and key components. If file doesn't exist, proceed with fresh analysis.
2. **Detection**: Check for existing context-package (early exit if valid)
3. **Foundation**: Initialize code-index, get project structure, load docs
4. **Analysis**: Extract keywords, determine scope, classify complexity based on task description and project state
### Phase 2: Multi-Source Context Discovery
Execute all 4 discovery tracks:
@@ -84,16 +85,17 @@ Execute all 4 discovery tracks:
### Phase 3: Synthesis, Assessment & Packaging
1. Apply relevance scoring and build dependency graph
2. Synthesize 4-source data (archive > docs > code > web)
3. Integrate brainstorm artifacts (if .brainstorming/ exists, read content)
4. Perform conflict detection with risk assessment
5. **Inject historical conflicts** from archive analysis into conflict_detection
6. Generate and validate context-package.json
2. **Synthesize 4-source data**: Merge findings from all sources (archive > docs > code > web). **Prioritize the context from `project.json`** for architecture and tech stack unless code analysis reveals it's outdated.
3. **Populate `project_context`**: Directly use the `overview` from `project.json` to fill the `project_context` section of the output `context-package.json`. Include technology_stack, architecture, key_components, and entry_points.
4. Integrate brainstorm artifacts (if .brainstorming/ exists, read content)
5. Perform conflict detection with risk assessment
6. **Inject historical conflicts** from archive analysis into conflict_detection
7. Generate and validate context-package.json
## Output Requirements
Complete context-package.json with:
- **metadata**: task_description, keywords, complexity, tech_stack, session_id
- **project_context**: architecture_patterns, coding_conventions, tech_stack
- **project_context**: architecture_patterns, coding_conventions, tech_stack (sourced from `project.json` overview)
- **assets**: {documentation[], source_code[], config[], tests[]} with relevance scores
- **dependencies**: {internal[], external[]} with dependency graph
- **brainstorm_artifacts**: {guidance_specification, role_analyses[], synthesis_output} with content
@@ -139,7 +141,7 @@ Refer to `context-search-agent.md` Phase 3.7 for complete `context-package.json`
**Key Sections**:
- **metadata**: Session info, keywords, complexity, tech stack
- **project_context**: Architecture patterns, conventions, tech stack
- **project_context**: Architecture patterns, conventions, tech stack (populated from `project.json` overview)
- **assets**: Categorized files with relevance scores (documentation, source_code, config, tests)
- **dependencies**: Internal and external dependency graphs
- **brainstorm_artifacts**: Brainstorm documents with full content (if exists)
@@ -277,6 +279,7 @@ if (historicalConflicts.length > 0 && currentRisk === "low") {
## Notes
- **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