feat: Add orchestrator template and roles for executor and planner

- Created a new orchestrator template for Codex skill design, detailing structure and execution phases.
- Introduced the executor role with responsibilities for task execution, including routing to backends and handling implementation.
- Added the planner role for requirement breakdown, issue creation, and task dispatching, ensuring a structured planning process.
This commit is contained in:
catlog22
2026-02-16 00:17:15 +08:00
parent dc03862ca7
commit a4fff6a591
36 changed files with 4168 additions and 2589 deletions

View File

@@ -0,0 +1,215 @@
# Agent Role Template
Template for generating per-agent role definition files.
## Purpose
| Phase | Usage |
|-------|-------|
| Phase 0 | Read to understand agent role file structure |
| Phase 3 | Apply with agent-specific content |
---
## Template
```markdown
---
name: {{agent_name}}
description: |
{{description}}
color: {{color}}
skill: {{parent_skill_name}}
---
# {{agent_display_name}}
{{description_paragraph}}
## Core Capabilities
{{#each capabilities}}
{{@index}}. **{{this.name}}**: {{this.description}}
{{/each}}
## Execution Process
### Step 1: Context Loading
**MANDATORY**: Execute these steps FIRST before any other action.
1. Read this role definition file (already done if you're reading this)
2. Read: `.workflow/project-tech.json` — understand project technology stack
3. Read: `.workflow/project-guidelines.json` — understand project conventions
4. Parse the TASK ASSIGNMENT from the spawn message for:
- **Goal**: What to achieve
- **Scope**: What's allowed and forbidden
- **Context**: Relevant background information
- **Deliverables**: Expected output format
- **Quality bar**: Success criteria
### Step 2: {{primary_action_name}}
{{primary_action_detail}}
\`\`\`javascript
// {{primary_action_description}}
{{primary_action_code}}
\`\`\`
### Step 3: {{secondary_action_name}}
{{secondary_action_detail}}
\`\`\`javascript
// {{secondary_action_description}}
{{secondary_action_code}}
\`\`\`
### Step 4: Output Delivery
Produce structured output following this EXACT template:
\`\`\`text
Summary:
- One-sentence completion summary
Findings:
- Finding 1: [specific description with file:line references]
- Finding 2: [specific description]
Proposed changes:
- File: [path/to/file]
- Change: [specific modification description]
- Risk: [low/medium/high] - [impact description]
Tests:
- Test cases: [list of needed test cases]
- Commands: [test commands to verify]
Open questions:
1. [Question needing clarification, if any]
2. [Question needing clarification, if any]
\`\`\`
**Important**: If there are open questions that block progress, prepend output with:
\`\`\`
CLARIFICATION_NEEDED:
Q1: [question] | Options: [A, B, C] | Recommended: [A]
Q2: [question] | Options: [A, B] | Recommended: [B]
\`\`\`
## Key Reminders
**ALWAYS**:
- Read role definition file as FIRST action (Step 1)
- Follow structured output template EXACTLY
- Stay within the assigned Scope boundaries
- Include file:line references in Findings
- Report open questions via CLARIFICATION_NEEDED format
- Provide actionable, specific deliverables
**NEVER**:
- Modify files outside the assigned Scope
- Skip context loading (Step 1)
- Produce unstructured or free-form output
- Make assumptions about unclear requirements (ask instead)
- Exceed the defined Quality bar without explicit approval
- Ignore the Goal/Scope/Deliverables from TASK ASSIGNMENT
## Error Handling
| Scenario | Action |
|----------|--------|
| Cannot access required file | Report in Open questions, continue with available data |
| Task scope unclear | Output CLARIFICATION_NEEDED, provide best-effort findings |
| Unexpected error | Report error details in Summary, include partial results |
| Quality bar not achievable | Report gap in Summary, explain constraints |
```
---
## Template Variants by Responsibility Type
### Exploration Agent
**Step 2**: Codebase Discovery
```javascript
// Search for relevant code patterns
const files = Glob("src/**/*.{ts,js,tsx,jsx}")
const matches = Grep(targetPattern, files)
// Trace call chains, identify entry points
```
**Step 3**: Pattern Analysis
```javascript
// Analyze discovered patterns
// Cross-reference with project conventions
// Identify similar implementations
```
### Implementation Agent
**Step 2**: Code Implementation
```javascript
// Implement changes according to plan
// Follow existing code patterns
// Maintain backward compatibility
```
**Step 3**: Self-Validation
```javascript
// Run relevant tests
// Check for syntax/type errors
// Verify changes match acceptance criteria
```
### Analysis Agent
**Step 2**: Multi-Dimensional Analysis
```javascript
// Analyze from assigned perspective (security/perf/quality/etc.)
// Collect evidence with file:line references
// Classify findings by severity
```
**Step 3**: Recommendation Generation
```javascript
// Propose fixes for each finding
// Assess risk and effort
// Prioritize by impact
```
### Testing Agent
**Step 2**: Test Design
```javascript
// Identify test scenarios from requirements
// Design test cases with expected results
// Map to test frameworks
```
**Step 3**: Test Execution & Validation
```javascript
// Run tests
// Collect pass/fail results
// Iterate on failures
```
---
## Variable Reference
| Variable | Source | Description |
|----------|--------|-------------|
| `{{agent_name}}` | config.name | Agent identifier (lowercase, hyphenated) |
| `{{agent_display_name}}` | Derived from name | Human-readable title |
| `{{description}}` | config.description | Short description (1-3 lines) |
| `{{description_paragraph}}` | config.description | Full paragraph description |
| `{{color}}` | Auto-assigned | Terminal color for output |
| `{{parent_skill_name}}` | codexSkillConfig.name | Parent skill identifier |
| `{{capabilities}}` | Inferred from responsibility | Array of capability objects |
| `{{primary_action_name}}` | Derived from responsibility | Step 2 title |
| `{{primary_action_detail}}` | Generated or from source | Step 2 content |
| `{{secondary_action_name}}` | Derived from responsibility | Step 3 title |
| `{{secondary_action_detail}}` | Generated or from source | Step 3 content |

View File

@@ -0,0 +1,414 @@
# Command Pattern Template
Pre-built Codex command patterns for common agent interaction scenarios.
## Purpose
| Phase | Usage |
|-------|-------|
| Phase 0 | Read to understand available command patterns |
| Phase 2 | Select appropriate patterns for orchestrator |
| Phase 3 | Apply patterns to agent definitions |
---
## Pattern 1: Explore (Parallel Fan-out)
**Use When**: Multi-angle codebase exploration needed.
```javascript
// ==================== Explore Pattern ====================
// Step 1: Define exploration angles
const angles = ["architecture", "dependencies", "patterns", "testing"]
// Step 2: Create parallel exploration agents
const agents = angles.map(angle =>
spawn_agent({
message: `
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS (Agent Execute)
1. **Read role definition**: ~/.codex/agents/cli-explore-agent.md (MUST read first)
2. Read: .workflow/project-tech.json
---
Goal: Execute ${angle} exploration for ${task_description}
Scope:
- Include: All source files relevant to ${angle}
- Exclude: node_modules, dist, build artifacts
Context:
- Task: ${task_description}
- Angle: ${angle}
Deliverables:
- Structured findings following output template
- File:line references for key discoveries
- Open questions for unclear areas
Quality bar:
- At least 3 relevant files identified
- Findings backed by concrete evidence
`
})
)
// Step 3: Batch wait
const results = wait({ ids: agents, timeout_ms: 600000 })
// Step 4: Aggregate
const findings = agents.map((id, i) => ({
angle: angles[i],
result: results.status[id].completed
}))
// Step 5: Cleanup
agents.forEach(id => close_agent({ id }))
```
## Pattern 2: Analyze (Multi-Perspective)
**Use When**: Code analysis from multiple dimensions needed.
```javascript
// ==================== Analyze Pattern ====================
const perspectives = [
{ name: "security", focus: "OWASP Top 10, injection, auth bypass" },
{ name: "performance", focus: "O(n²), memory leaks, blocking I/O" },
{ name: "maintainability", focus: "complexity, coupling, duplication" }
]
const agents = perspectives.map(p =>
spawn_agent({
message: `
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS (Agent Execute)
1. **Read role definition**: ~/.codex/agents/cli-explore-agent.md (MUST read first)
---
Goal: Analyze ${targetModule} from ${p.name} perspective
Focus: ${p.focus}
Scope:
- Include: ${targetPaths}
- Exclude: Test files, generated code
Deliverables:
- Severity-classified findings (Critical/High/Medium/Low)
- File:line references for each finding
- Remediation recommendations
Quality bar:
- Every finding must have evidence (code reference)
- Remediation must be actionable
`
})
)
const results = wait({ ids: agents, timeout_ms: 600000 })
// Merge findings by severity
const merged = {
critical: [], high: [], medium: [], low: []
}
agents.forEach((id, i) => {
const parsed = parseFindings(results.status[id].completed)
Object.keys(merged).forEach(sev => merged[sev].push(...(parsed[sev] || [])))
})
agents.forEach(id => close_agent({ id }))
```
## Pattern 3: Implement (Sequential Delegation)
**Use When**: Code implementation following a plan.
```javascript
// ==================== Implement Pattern ====================
const implementAgent = spawn_agent({
message: `
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS (Agent Execute)
1. **Read role definition**: ~/.codex/agents/code-developer.md (MUST read first)
2. Read: .workflow/project-tech.json
3. Read: .workflow/project-guidelines.json
---
Goal: Implement ${featureDescription}
Scope:
- Include: ${targetPaths}
- Exclude: Unrelated modules
- Constraints: No breaking changes, follow existing patterns
Context:
- Plan: ${planContent}
- Dependencies: ${dependencies}
- Existing patterns: ${patterns}
Deliverables:
- Working implementation following plan
- Updated/new test files
- Summary of changes with file:line references
Quality bar:
- All existing tests pass
- New code follows project conventions
- No TypeScript errors
- Backward compatible
`
})
const result = wait({ ids: [implementAgent], timeout_ms: 900000 })
// Check for open questions (might need clarification)
if (result.status[implementAgent].completed.includes('CLARIFICATION_NEEDED')) {
// Handle clarification via send_input
const answers = getUserAnswers(result)
send_input({ id: implementAgent, message: `## ANSWERS\n${answers}\n\n## CONTINUE\nProceed with implementation.` })
const final = wait({ ids: [implementAgent], timeout_ms: 900000 })
}
close_agent({ id: implementAgent })
```
## Pattern 4: Validate (Test-Fix Cycle)
**Use When**: Running tests and fixing failures iteratively.
```javascript
// ==================== Validate Pattern ====================
const validateAgent = spawn_agent({
message: `
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS (Agent Execute)
1. **Read role definition**: ~/.codex/agents/test-fix-agent.md (MUST read first)
---
Goal: Validate ${component} — run tests, fix failures, iterate
Scope:
- Include: ${testPaths}
- Exclude: Unrelated test suites
Context:
- Recent changes: ${changedFiles}
- Test framework: ${testFramework}
Deliverables:
- All tests passing (or documented blocked tests)
- Fix summary with file:line references
- Coverage report
Quality bar:
- Pass rate >= 95%
- No new test regressions
- Max 5 fix iterations
`
})
const round1 = wait({ ids: [validateAgent], timeout_ms: 600000 })
// Check if more iterations needed
let iteration = 1
while (
iteration < 5 &&
round1.status[validateAgent].completed.includes('TESTS_FAILING')
) {
send_input({
id: validateAgent,
message: `## ITERATION ${iteration + 1}\nContinue fixing remaining failures. Focus on:\n${remainingFailures}`
})
const roundN = wait({ ids: [validateAgent], timeout_ms: 300000 })
iteration++
}
close_agent({ id: validateAgent })
```
## Pattern 5: Review (Multi-Dimensional)
**Use When**: Code review from multiple dimensions.
```javascript
// ==================== Review Pattern ====================
const dimensions = [
{ name: "correctness", agent: "cli-explore-agent" },
{ name: "security", agent: "cli-explore-agent" },
{ name: "performance", agent: "cli-explore-agent" },
{ name: "style", agent: "cli-explore-agent" }
]
const agents = dimensions.map(d =>
spawn_agent({
message: `
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS (Agent Execute)
1. **Read role definition**: ~/.codex/agents/${d.agent}.md (MUST read first)
---
Goal: Review ${targetCode} for ${d.name}
Scope: ${changedFiles}
Deliverables: Findings with severity, file:line, remediation
`
})
)
const results = wait({ ids: agents, timeout_ms: 600000 })
// Aggregate review findings
const review = {
approved: true,
findings: [],
blockers: []
}
agents.forEach((id, i) => {
const parsed = parseReview(results.status[id].completed)
review.findings.push(...parsed.findings)
if (parsed.blockers.length > 0) {
review.approved = false
review.blockers.push(...parsed.blockers)
}
})
agents.forEach(id => close_agent({ id }))
```
## Pattern 6: Deep Interact (Merged Explore + Plan)
**Use When**: Exploration and planning are tightly coupled.
```javascript
// ==================== Deep Interact Pattern ====================
const agent = spawn_agent({
message: `
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS (Agent Execute)
1. **Read role definition**: ~/.codex/agents/cli-explore-agent.md (MUST read first)
2. **Also read**: ~/.codex/agents/cli-lite-planning-agent.md (dual role)
---
### Phase A: Exploration
Goal: Explore codebase for ${task_description}
Output: Structured findings + CLARIFICATION_NEEDED questions (if any)
### Phase B: Planning (activated after clarification)
Goal: Generate implementation plan based on exploration + answers
Output: Structured plan following plan schema
Deliverables:
- Phase A: exploration findings (Summary/Findings/Open questions)
- Phase B: implementation plan (after receiving clarification answers)
`
})
// Phase A: Exploration
const exploration = wait({ ids: [agent], timeout_ms: 600000 })
if (exploration.status[agent].completed.includes('CLARIFICATION_NEEDED')) {
const answers = getUserAnswers(exploration)
// Phase B: Planning (same agent, preserved context)
send_input({
id: agent,
message: `
## CLARIFICATION ANSWERS
${answers}
## PROCEED TO PHASE B
Generate implementation plan based on your exploration findings and these answers.
`
})
const plan = wait({ ids: [agent], timeout_ms: 900000 })
}
close_agent({ id: agent })
```
## Pattern 7: Two-Phase (Clarify → Execute)
**Use When**: Task requires explicit clarification before execution.
```javascript
// ==================== Two-Phase Pattern ====================
// Phase 1: Clarification
const agent = spawn_agent({
message: `
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS (Agent Execute)
1. **Read role definition**: ~/.codex/agents/${agentType}.md (MUST read first)
---
### PHASE: CLARIFICATION ONLY
Goal: Understand ${task_description} and identify unclear points
Output ONLY:
1. Your understanding of the task (2-3 sentences)
2. CLARIFICATION_NEEDED questions (if any)
3. Recommended approach (1-2 sentences)
DO NOT execute any changes yet.
`
})
const clarification = wait({ ids: [agent], timeout_ms: 300000 })
// Collect user confirmation/answers
const userResponse = processUserInput(clarification)
// Phase 2: Execution
send_input({
id: agent,
message: `
## USER CONFIRMATION
${userResponse}
## PROCEED TO EXECUTION
Now execute the task with full implementation.
Output: Complete deliverable following structured output template.
`
})
const execution = wait({ ids: [agent], timeout_ms: 900000 })
close_agent({ id: agent })
```
---
## Pattern Selection Guide
| Scenario | Recommended Pattern | Reason |
|----------|-------------------|--------|
| Explore codebase from N angles | Pattern 1: Explore | Parallel fan-out, independent angles |
| Analyze code quality | Pattern 2: Analyze | Multi-perspective, severity classification |
| Implement from plan | Pattern 3: Implement | Sequential, plan-driven |
| Run tests + fix | Pattern 4: Validate | Iterative send_input loop |
| Code review | Pattern 5: Review | Multi-dimensional, aggregated verdict |
| Explore then plan | Pattern 6: Deep Interact | Context preservation, merged phases |
| Complex/unclear task | Pattern 7: Two-Phase | Clarify first, reduce rework |
| Simple one-shot task | Standard (no pattern) | spawn → wait → close |

View File

@@ -0,0 +1,306 @@
# Orchestrator Template
Template for the generated Codex orchestrator document.
## Purpose
| Phase | Usage |
|-------|-------|
| Phase 0 | Read to understand orchestrator output structure |
| Phase 2 | Apply with skill-specific content |
---
## Template
```markdown
---
name: {{skill_name}}
description: |
{{description}}
agents: {{agent_count}}
phases: {{phase_count}}
---
# {{skill_display_name}}
{{one_paragraph_description}}
## Architecture Overview
\`\`\`
{{architecture_diagram}}
\`\`\`
## Agent Registry
| Agent | Role File | Responsibility | New/Existing |
|-------|-----------|----------------|--------------|
{{#each agents}}
| `{{this.name}}` | `{{this.role_file}}` | {{this.responsibility}} | {{this.status}} |
{{/each}}
## Phase Execution
{{#each phases}}
### Phase {{this.index}}: {{this.name}}
{{this.description}}
{{#if this.is_parallel}}
#### Parallel Fan-out
\`\`\`javascript
// Create parallel agents
const agentIds = [
{{#each this.agents}}
spawn_agent({
message: \`
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS (Agent Execute)
1. **Read role definition**: {{this.role_file}} (MUST read first)
2. Read: .workflow/project-tech.json
3. Read: .workflow/project-guidelines.json
---
Goal: {{this.goal}}
Scope:
- Include: {{this.scope_include}}
- Exclude: {{this.scope_exclude}}
Context:
{{this.context}}
Deliverables:
{{this.deliverables}}
Quality bar:
{{this.quality_bar}}
\`
}),
{{/each}}
]
// Batch wait
const results = wait({
ids: agentIds,
timeout_ms: {{this.timeout_ms}}
})
// Handle timeout
if (results.timed_out) {
const completed = agentIds.filter(id => results.status[id]?.completed)
const pending = agentIds.filter(id => !results.status[id]?.completed)
// Use completed results, log pending
}
// Aggregate results
const phaseResults = agentIds.map(id => results.status[id].completed)
// Cleanup
agentIds.forEach(id => close_agent({ id }))
\`\`\`
{{/if}}
{{#if this.is_standard}}
#### Standard Execution
\`\`\`javascript
const agentId = spawn_agent({
message: \`
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS (Agent Execute)
1. **Read role definition**: {{this.agent.role_file}} (MUST read first)
2. Read: .workflow/project-tech.json
3. Read: .workflow/project-guidelines.json
---
Goal: {{this.goal}}
Scope:
- Include: {{this.scope_include}}
- Exclude: {{this.scope_exclude}}
Context:
{{this.context}}
Deliverables:
{{this.deliverables}}
Quality bar:
{{this.quality_bar}}
\`
})
const result = wait({ ids: [agentId], timeout_ms: {{this.timeout_ms}} })
if (result.timed_out) {
// Timeout handling: continue wait or urge convergence
send_input({ id: agentId, message: "Please finalize and output current findings." })
const retry = wait({ ids: [agentId], timeout_ms: 60000 })
}
close_agent({ id: agentId })
\`\`\`
{{/if}}
{{#if this.is_deep_interaction}}
#### Deep Interaction (Multi-round)
\`\`\`javascript
const agent = spawn_agent({
message: \`
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS (Agent Execute)
1. **Read role definition**: {{this.agent.role_file}} (MUST read first)
---
### Phase A: {{this.initial_goal}}
Output: Findings + Open Questions (CLARIFICATION_NEEDED format)
### Phase B: {{this.followup_goal}} (after clarification)
Output: Complete deliverable
\`
})
// Round 1: Initial exploration
const round1 = wait({ ids: [agent], timeout_ms: {{this.timeout_ms}} })
// Check for clarification needs
if (round1.status[agent].completed.includes('CLARIFICATION_NEEDED')) {
// Parse questions, collect user answers
const answers = collectUserAnswers(round1.status[agent].completed)
// Round 2: Continue with answers
send_input({
id: agent,
message: \`
## CLARIFICATION ANSWERS
\${answers}
## NEXT STEP
Proceed with Phase B.
\`
})
const round2 = wait({ ids: [agent], timeout_ms: {{this.followup_timeout_ms}} })
}
close_agent({ id: agent })
\`\`\`
{{/if}}
{{#if this.is_pipeline}}
#### Pipeline (Sequential Chain)
\`\`\`javascript
{{#each this.stages}}
// Stage {{this.index}}: {{this.name}}
const stage{{this.index}}Agent = spawn_agent({
message: \`
## TASK ASSIGNMENT
### MANDATORY FIRST STEPS (Agent Execute)
1. **Read role definition**: {{this.role_file}} (MUST read first)
---
Goal: {{this.goal}}
{{#if this.previous_output}}
## PREVIOUS STAGE OUTPUT
\${stage{{this.previous_index}}Result}
{{/if}}
Deliverables: {{this.deliverables}}
\`
})
const stage{{this.index}}Result = wait({ ids: [stage{{this.index}}Agent], timeout_ms: {{this.timeout_ms}} })
close_agent({ id: stage{{this.index}}Agent })
{{/each}}
\`\`\`
{{/if}}
{{/each}}
## Result Aggregation
\`\`\`javascript
// Merge results from all phases
const finalResult = {
{{#each phases}}
phase{{this.index}}: phase{{this.index}}Results,
{{/each}}
}
// Output summary
console.log(\`
## Skill Execution Complete
{{#each phases}}
### Phase {{this.index}}: {{this.name}}
Status: \${phase{{this.index}}Results.status}
{{/each}}
\`)
\`\`\`
## Lifecycle Management
### Timeout Handling
| Timeout Scenario | Action |
|-----------------|--------|
| Single agent timeout | send_input to urge convergence, retry wait |
| Parallel partial timeout | Use completed results if >= 70%, close pending |
| All agents timeout | Log error, abort with partial state |
### Cleanup Protocol
\`\`\`javascript
// Track all agents created during execution
const allAgentIds = []
// ... (agents added during phase execution) ...
// Final cleanup (end of orchestrator or on error)
allAgentIds.forEach(id => {
try { close_agent({ id }) } catch { /* already closed */ }
})
\`\`\`
## Error Handling
| Scenario | Resolution |
|----------|------------|
| Agent produces invalid output | Retry with clarified instructions via send_input |
| Agent timeout | Urge convergence, retry, or abort |
| Missing role file | Log error, skip agent or use fallback |
| Partial results | Proceed with available data, log gaps |
```
---
## Variable Reference
| Variable | Source | Description |
|----------|--------|-------------|
| `{{skill_name}}` | codexSkillConfig.name | Skill identifier |
| `{{skill_display_name}}` | Derived from name | Human-readable title |
| `{{description}}` | codexSkillConfig.description | Skill description |
| `{{agent_count}}` | codexSkillConfig.agents.length | Number of agents |
| `{{phase_count}}` | codexSkillConfig.phases.length | Number of phases |
| `{{architecture_diagram}}` | Generated from phase/agent topology | ASCII flow diagram |
| `{{agents}}` | codexSkillConfig.agents | Array of agent configs |
| `{{phases}}` | codexSkillConfig.phases | Array of phase configs |
| `{{phases[].is_parallel}}` | phase.interaction_model === "parallel_fanout" | Boolean |
| `{{phases[].is_standard}}` | phase.interaction_model === "standard" | Boolean |
| `{{phases[].is_deep_interaction}}` | phase.interaction_model === "deep_interaction" | Boolean |
| `{{phases[].is_pipeline}}` | phase.interaction_model === "pipeline" | Boolean |
| `{{phases[].timeout_ms}}` | Phase-specific timeout | Default: 300000 |