Refactor API calls to use csrfFetch for enhanced security across multiple views, including loop-monitor, mcp-manager, memory, prompt-history, rules-manager, session-detail, and skills-manager. Additionally, add Phase 1 and Phase 2 documentation for session initialization and orchestration loop in the ccw-loop-b skill.

This commit is contained in:
catlog22
2026-02-07 10:54:12 +08:00
parent f7dfbc0512
commit 92b0d175a7
49 changed files with 2003 additions and 480 deletions

View File

@@ -0,0 +1,168 @@
# Worker: COMPLETE
Session finalization worker. Aggregate results, generate summary, cleanup.
## Purpose
- Aggregate all worker results into comprehensive summary
- Verify completeness of tasks
- Generate commit message suggestion
- Offer expansion options
- Mark loop as completed
## Preconditions
- `state.status === 'running'`
## Execution
### Step 1: Read All Worker Outputs
```javascript
const workerOutputs = {}
for (const action of ['init', 'develop', 'debug', 'validate']) {
const outputPath = `${workersDir}/${action}.output.json`
if (fs.existsSync(outputPath)) {
workerOutputs[action] = JSON.parse(Read(outputPath))
}
}
```
### Step 2: Aggregate Statistics
```javascript
const stats = {
duration: Date.now() - new Date(state.created_at).getTime(),
iterations: state.current_iteration,
tasks_completed: state.skill_state.completed_tasks.length,
tasks_total: state.skill_state.completed_tasks.length + state.skill_state.pending_tasks.length,
files_changed: collectAllFilesChanged(workerOutputs),
test_passed: workerOutputs.validate?.summary?.passed || 0,
test_total: workerOutputs.validate?.summary?.total || 0,
coverage: workerOutputs.validate?.coverage || 'N/A'
}
```
### Step 3: Generate Summary
```javascript
Write(`${progressDir}/summary.md`, `# CCW Loop-B Session Summary
**Loop ID**: ${loopId}
**Task**: ${state.description}
**Mode**: ${state.mode}
**Started**: ${state.created_at}
**Completed**: ${getUtc8ISOString()}
**Duration**: ${formatDuration(stats.duration)}
---
## Results
| Metric | Value |
|--------|-------|
| Iterations | ${stats.iterations} |
| Tasks Completed | ${stats.tasks_completed}/${stats.tasks_total} |
| Tests | ${stats.test_passed}/${stats.test_total} |
| Coverage | ${stats.coverage} |
| Files Changed | ${stats.files_changed.length} |
## Files Changed
${stats.files_changed.map(f => `- \`${f}\``).join('\n') || '- None'}
## Worker Summary
${Object.entries(workerOutputs).map(([action, output]) => `
### ${action}
- Status: ${output.status}
- Summary: ${output.summary}
`).join('\n')}
## Recommendations
${generateRecommendations(stats, state)}
---
*Generated by CCW Loop-B at ${getUtc8ISOString()}*
`)
```
### Step 4: Generate Commit Suggestion
```javascript
const commitSuggestion = {
message: generateCommitMessage(state.description, stats),
files: stats.files_changed,
ready_for_pr: stats.test_passed > 0 && stats.tasks_completed === stats.tasks_total
}
```
### Step 5: Update State
```javascript
state.status = 'completed'
state.completed_at = getUtc8ISOString()
state.skill_state.phase = 'complete'
state.skill_state.workers_completed.push('complete')
saveState(loopId, state)
```
## Output Format
```
WORKER_RESULT:
- action: complete
- status: success
- summary: Loop completed. {tasks_completed} tasks, {test_passed} tests pass
- files_changed: []
- next_suggestion: null
- loop_back_to: null
DETAILED_OUTPUT:
SESSION_SUMMARY:
achievements: [...]
files_changed: [...]
test_results: { passed: N, total: N }
COMMIT_SUGGESTION:
message: "feat: ..."
files: [...]
ready_for_pr: true
EXPANSION_OPTIONS:
1. [test] Add more test cases
2. [enhance] Feature enhancements
3. [refactor] Code refactoring
4. [doc] Documentation updates
```
## Helper Functions
```javascript
function formatDuration(ms) {
const seconds = Math.floor(ms / 1000)
const minutes = Math.floor(seconds / 60)
const hours = Math.floor(minutes / 60)
if (hours > 0) return `${hours}h ${minutes % 60}m`
if (minutes > 0) return `${minutes}m ${seconds % 60}s`
return `${seconds}s`
}
function generateRecommendations(stats, state) {
const recs = []
if (stats.tasks_completed < stats.tasks_total) recs.push('- Complete remaining tasks')
if (stats.test_passed < stats.test_total) recs.push('- Fix failing tests')
if (stats.coverage !== 'N/A' && parseFloat(stats.coverage) < 80) recs.push(`- Improve coverage (${stats.coverage}%)`)
if (recs.length === 0) recs.push('- Consider code review', '- Update documentation')
return recs.join('\n')
}
```
## Error Handling
| Error | Recovery |
|-------|----------|
| Missing worker outputs | Generate partial summary |
| State write failed | Retry, then report |

View File

@@ -0,0 +1,148 @@
# Worker: DEBUG
Problem diagnosis worker. Hypothesis-driven debugging with evidence tracking.
## Purpose
- Locate error source and understand failure mechanism
- Generate testable hypotheses ranked by likelihood
- Collect evidence and evaluate against criteria
- Document root cause and fix recommendations
## Preconditions
- Issue exists (test failure, bug report, blocked task)
- `state.status === 'running'`
## Mode Detection
```javascript
const debugPath = `${progressDir}/debug.md`
const debugExists = fs.existsSync(debugPath)
const debugMode = debugExists ? 'continue' : 'explore'
```
## Execution
### Mode: Explore (First Debug)
#### Step E1: Understand Problem
```javascript
// From test failures, blocked tasks, or user description
const bugDescription = state.skill_state.findings?.[0]
|| state.description
```
#### Step E2: Search Codebase
```javascript
const searchResults = mcp__ace_tool__search_context({
project_root_path: '.',
query: `code related to: ${bugDescription}`
})
```
#### Step E3: Generate Hypotheses
```javascript
const hypotheses = [
{
id: 'H1',
description: 'Most likely cause',
testable_condition: 'What to check',
confidence: 'high | medium | low',
evidence: [],
mechanism: 'Detailed explanation of how this causes the bug'
},
// H2, H3...
]
```
#### Step E4: Create Understanding Document
```javascript
Write(`${progressDir}/debug.md`, `# Debug Understanding
**Loop ID**: ${loopId}
**Bug**: ${bugDescription}
**Started**: ${getUtc8ISOString()}
---
## Hypotheses
${hypotheses.map(h => `
### ${h.id}: ${h.description}
- Confidence: ${h.confidence}
- Testable: ${h.testable_condition}
- Mechanism: ${h.mechanism}
`).join('\n')}
## Evidence
[To be collected]
## Root Cause
[Pending investigation]
`)
```
### Mode: Continue (Previous Debug Exists)
#### Step C1: Review Previous Findings
```javascript
const previousDebug = Read(`${progressDir}/debug.md`)
// Continue investigation based on previous findings
```
#### Step C2: Apply Fix and Verify
```javascript
// If root cause identified, apply fix
// Record fix in progress document
```
## Output Format
```
WORKER_RESULT:
- action: debug
- status: success
- summary: Root cause: {description}
- files_changed: []
- next_suggestion: develop
- loop_back_to: develop
DETAILED_OUTPUT:
ROOT_CAUSE_ANALYSIS:
hypothesis: "H1: {description}"
confidence: high
evidence: [...]
mechanism: "Detailed explanation"
FIX_RECOMMENDATIONS:
1. {specific fix action}
2. {verification step}
```
## Clarification Mode
If insufficient information:
```
CLARIFICATION_NEEDED:
Q1: Can you reproduce the issue? | Options: [Yes, No, Sometimes] | Recommended: [Yes]
Q2: When did this start? | Options: [Recent change, Always, Unknown] | Recommended: [Recent change]
```
## Error Handling
| Error | Recovery |
|-------|----------|
| Insufficient info | Output CLARIFICATION_NEEDED |
| All hypotheses rejected | Generate new hypotheses |
| >5 iterations | Suggest escalation |

View File

@@ -0,0 +1,123 @@
# Worker: DEVELOP
Code implementation worker. Execute pending tasks, record changes.
## Purpose
- Execute next pending development task
- Implement code changes following project conventions
- Record progress to markdown and NDJSON log
- Update task status in state
## Preconditions
- `state.skill_state.pending_tasks.length > 0`
- `state.status === 'running'`
## Execution
### Step 1: Find Pending Task
```javascript
const tasks = state.skill_state.pending_tasks
const currentTask = tasks.find(t => t.status === 'pending')
if (!currentTask) {
// All tasks done
return WORKER_RESULT with next_suggestion: 'validate'
}
currentTask.status = 'in_progress'
```
### Step 2: Find Existing Patterns
```javascript
// Use ACE search_context to find similar implementations
const patterns = mcp__ace_tool__search_context({
project_root_path: '.',
query: `implementation patterns for: ${currentTask.description}`
})
// Study 3+ similar features/components
// Follow existing conventions
```
### Step 3: Implement Task
```javascript
// Use appropriate tools:
// - ACE search_context for finding patterns
// - Read for loading files
// - Edit/Write for making changes
const filesChanged = []
// ... implementation logic ...
```
### Step 4: Record Changes
```javascript
// Append to progress document
const progressEntry = `
### Task ${currentTask.id} - ${currentTask.description} (${getUtc8ISOString()})
**Files Changed**:
${filesChanged.map(f => `- \`${f}\``).join('\n')}
**Summary**: [implementation description]
**Status**: COMPLETED
---
`
const existingProgress = Read(`${progressDir}/develop.md`)
Write(`${progressDir}/develop.md`, existingProgress + progressEntry)
```
### Step 5: Update State
```javascript
currentTask.status = 'completed'
state.skill_state.completed_tasks.push(currentTask)
state.skill_state.pending_tasks = tasks.filter(t => t.status === 'pending')
saveState(loopId, state)
```
## Output Format
```
WORKER_RESULT:
- action: develop
- status: success
- summary: Implemented: {task_description}
- files_changed: ["file1.ts", "file2.ts"]
- next_suggestion: develop | validate
- loop_back_to: null
DETAILED_OUTPUT:
tasks_completed: [T1]
tasks_remaining: [T2, T3]
metrics:
lines_added: 180
lines_removed: 15
```
## Clarification Mode
If task is ambiguous, output:
```
CLARIFICATION_NEEDED:
Q1: [question about implementation approach] | Options: [A, B] | Recommended: [A]
Q2: [question about scope] | Options: [A, B, C] | Recommended: [B]
```
## Error Handling
| Error | Recovery |
|-------|----------|
| Pattern unclear | Output CLARIFICATION_NEEDED |
| Task blocked | Mark blocked, suggest debug |
| Partial completion | Set loop_back_to: "develop" |

View File

@@ -0,0 +1,115 @@
# Worker: INIT
Session initialization worker. Parse requirements, create execution plan.
## Purpose
- Parse task description and project context
- Break task into development phases
- Generate initial task list
- Create progress document structure
## Preconditions
- `state.status === 'running'`
- `state.skill_state.phase === 'init'` or first run
## Execution
### Step 1: Read Project Context
```javascript
// MANDATORY FIRST STEPS (already in prompt)
// 1. Read role definition
// 2. Read .workflow/project-tech.json
// 3. Read .workflow/project-guidelines.json
```
### Step 2: Analyze Task
```javascript
// Use ACE search_context to find relevant patterns
const searchResults = mcp__ace_tool__search_context({
project_root_path: '.',
query: `code related to: ${state.description}`
})
// Parse task into 3-7 development tasks
const tasks = analyzeAndDecompose(state.description, searchResults)
```
### Step 3: Create Task Breakdown
```javascript
const breakdown = tasks.map((t, i) => ({
id: `T${i + 1}`,
description: t.description,
priority: t.priority || i + 1,
status: 'pending',
files: t.relatedFiles || []
}))
```
### Step 4: Initialize Progress Document
```javascript
const progressPath = `${progressDir}/develop.md`
Write(progressPath, `# Development Progress
**Loop ID**: ${loopId}
**Task**: ${state.description}
**Started**: ${getUtc8ISOString()}
---
## Task List
${breakdown.map((t, i) => `${i + 1}. [ ] ${t.description}`).join('\n')}
---
## Progress Timeline
`)
```
### Step 5: Update State
```javascript
state.skill_state.pending_tasks = breakdown
state.skill_state.phase = 'init'
state.skill_state.workers_completed.push('init')
saveState(loopId, state)
```
## Output Format
```
WORKER_RESULT:
- action: init
- status: success
- summary: Initialized with {N} development tasks
- files_changed: []
- next_suggestion: develop
- loop_back_to: null
DETAILED_OUTPUT:
TASK_BREAKDOWN:
- T1: {description}
- T2: {description}
...
EXECUTION_PLAN:
1. Develop (T1-T2)
2. Validate
3. Complete
```
## Error Handling
| Error | Recovery |
|-------|----------|
| Task analysis failed | Create single generic task |
| Project context missing | Proceed without context |
| State write failed | Retry once, then report |

View File

@@ -0,0 +1,132 @@
# Worker: VALIDATE
Testing and verification worker. Run tests, check coverage, quality gates.
## Purpose
- Detect test framework and run tests
- Measure code coverage
- Check quality gates (lint, types, security)
- Generate validation report
- Determine pass/fail status
## Preconditions
- Code exists to validate
- `state.status === 'running'`
## Execution
### Step 1: Detect Test Framework
```javascript
const packageJson = JSON.parse(Read('package.json') || '{}')
const testScript = packageJson.scripts?.test || 'npm test'
const coverageScript = packageJson.scripts?.['test:coverage']
```
### Step 2: Run Tests
```javascript
const testResult = await Bash({
command: testScript,
timeout: 300000 // 5 minutes
})
const testResults = parseTestOutput(testResult.stdout, testResult.stderr)
```
### Step 3: Run Coverage (if available)
```javascript
let coverageData = null
if (coverageScript) {
const coverageResult = await Bash({ command: coverageScript, timeout: 300000 })
coverageData = parseCoverageReport(coverageResult.stdout)
}
```
### Step 4: Quality Checks
```javascript
// Lint check
const lintResult = await Bash({ command: 'npm run lint 2>&1 || true' })
// Type check
const typeResult = await Bash({ command: 'npx tsc --noEmit 2>&1 || true' })
```
### Step 5: Generate Validation Report
```javascript
Write(`${progressDir}/validate.md`, `# Validation Report
**Loop ID**: ${loopId}
**Validated**: ${getUtc8ISOString()}
## Test Results
| Metric | Value |
|--------|-------|
| Total | ${testResults.total} |
| Passed | ${testResults.passed} |
| Failed | ${testResults.failed} |
| Pass Rate | ${((testResults.passed / testResults.total) * 100).toFixed(1)}% |
## Coverage
${coverageData ? `Overall: ${coverageData.overall}%` : 'N/A'}
## Quality Checks
- Lint: ${lintResult.exitCode === 0 ? 'PASS' : 'FAIL'}
- Types: ${typeResult.exitCode === 0 ? 'PASS' : 'FAIL'}
## Failed Tests
${testResults.failures?.map(f => `- ${f.name}: ${f.error}`).join('\n') || 'None'}
`)
```
### Step 6: Save Structured Results
```javascript
Write(`${workersDir}/validate.output.json`, JSON.stringify({
action: 'validate',
timestamp: getUtc8ISOString(),
summary: { total: testResults.total, passed: testResults.passed, failed: testResults.failed },
coverage: coverageData?.overall || null,
quality: { lint: lintResult.exitCode === 0, types: typeResult.exitCode === 0 }
}, null, 2))
```
## Output Format
```
WORKER_RESULT:
- action: validate
- status: success
- summary: {passed}/{total} tests pass, coverage {N}%
- files_changed: []
- next_suggestion: complete | develop
- loop_back_to: develop (if tests fail)
DETAILED_OUTPUT:
TEST_RESULTS:
unit_tests: { passed: 98, failed: 0 }
integration_tests: { passed: 15, failed: 0 }
coverage: "95%"
QUALITY_CHECKS:
lint: PASS
types: PASS
```
## Error Handling
| Error | Recovery |
|-------|----------|
| Tests don't run | Check config, report error |
| All tests fail | Suggest debug action |
| Coverage tool missing | Skip coverage, tests only |
| Timeout | Increase timeout or split tests |