Files
APAW/.kilo/rules/orchestrator-self-evolution.md
NW defe57d53a feat: merge infrastructure skills and workflows from TenerifeProp
Add MCP-based infrastructure skills:
- mcp-integration: Playwright + GitMCP
- e2e-testing: Cypress + AntV + Slack
- search-integration: Brave + Tavily + Markitdown
- security-scanner: CVE Search + MCP Validator
- knowledge-base: Docfork + Wikipedia + ArXiv
- prompt-manager: version control + DevTrends
- api-catalog: MCP server registry
- agent-architect-mcp: patterns + OpenAPI converter

Add workflow commands:
- feature.md: full feature pipeline
- hotfix.md: urgent bug fix workflow

Add rules:
- orchestrator-self-evolution.md
- sdet-engineer.md

Add audit:
- WORKFLOW_AUDIT.md

Source: UniqueSoft/TenerifeProp
2026-05-06 23:04:14 +01:00

14 KiB

Orchestrator Self-Evolution Rule

Auto-expansion protocol when no solution found in existing capabilities.

Trigger Condition

Orchestrator initiates self-evolution when:

  1. No Agent Match: Task requirements don't match any existing agent capabilities
  2. No Skill Match: Required domain knowledge not covered by existing skills
  3. No Workflow Match: Complex multi-step task needs new workflow pattern
  4. Capability Gap: @capability-analyst reports critical gaps

Evolution Protocol

Step 1: Create Research Milestone

Post to Gitea:

def create_evolution_milestone(gap_description, required_capabilities):
    """Create milestone for evolution tracking"""
    
    milestone = gitea.create_milestone(
        repo="UniqueSoft/APAW",
        title=f"[Evolution] {gap_description}",
        description=f"""## Capability Gap Analysis
    
**Trigger**: No matching capability found
**Required**: {required_capabilities}
**Date**: {timestamp()}

## Evolution Tasks

- [ ] Research existing solutions
- [ ] Design new agent/skill/workflow
- [ ] Implement component
- [ ] Update orchestrator permissions
- [ ] Verify access
- [ ] Register in capability-index.yaml
- [ ] Document in KILO_SPEC.md
- [ ] Close milestone with results

## Expected Outcome

After completion, orchestrator will have access to new capabilities.
"""
    )
    
    return milestone['id'], milestone['number']

Step 2: Run Research Workflow

def run_evolution_research(milestone_id, gap_description):
    """Run comprehensive research for gap filling"""
    
    # Create research issue
    issue = gitea.create_issue(
        repo="UniqueSoft/APAW",
        title=f"[Research] {gap_description}",
        body=f"""## Research Scope

**Milestone**: #{milestone_id}
**Gap**: {gap_description}

## Research Tasks

### 1. Existing Solutions Analysis
- [ ] Search git history for similar patterns
- [ ] Check external resources and best practices
- [ ] Analyze if enhancement is better than new component

### 2. Component Design
- [ ] Decide: Agent vs Skill vs Workflow
- [ ] Define required capabilities
- [ ] Specify permission requirements
- [ ] Plan integration points

### 3. Implementation Plan
- [ ] File locations
- [ ] Dependencies
- [ ] Update requirements: orchestrator.md, capability-index.yaml
- [ ] Test plan

## Decision Matrix

| If | Then |
|----|----|
| Specialized knowledge needed | Create SKILL |
| Autonomous execution needed | Create AGENT |
| Multi-step process needed | Create WORKFLOW |
| Enhancement to existing | Modify existing |

---
**Status**: 🔄 Research Phase
""",
        labels=["evolution", "research", f"milestone:{milestone_id}"]
    )
    
    return issue['number']

Step 3: Execute Research with Agents

def execute_evolution_research(issue_number, gap_description, required_capabilities):
    """Execute research using specialized agents"""
    
    # 1. History search
    history_result = Task(
        subagent_type="history-miner",
        prompt=f"""Search git history for:
1. Similar capability implementations
2. Past solutions to: {gap_description}
3. Related patterns that could be extended
Return findings for gap analysis."""
    )
    
    # 2. Capability analysis
    gap_analysis = Task(
        subagent_type="capability-analyst",
        prompt=f"""Analyze capability gap:

**Gap**: {gap_description}
**Required**: {required_capabilities}

Output:
1. Gap classification (critical/partial/integration/skill)
2. Recommendation: create new or enhance existing
3. Component type: agent/skill/workflow
4. Required capabilities and permissions
5. Integration points with existing system"""
    )
    
    # 3. Design new component
    if gap_analysis.recommendation == "create_new":
        design_result = Task(
            subagent_type="agent-architect",
            prompt=f"""Design new component for:

**Gap**: {gap_description}
**Type**: {gap_analysis.component_type}
**Required Capabilities**: {required_capabilities}

Create complete definition:
1. YAML frontmatter (model, mode, permissions)
2. Role definition
3. Behavior guidelines
4. Task tool invocation table
5. Integration requirements"""
        )
    
    # Post research results
    post_comment(issue_number, f"""## ✅ Research Complete

### Findings:

**History Search**: {history_result.summary}
**Gap Analysis**: {gap_analysis.classification}
**Recommendation**: {gap_analysis.recommendation}

### Design:

```yaml
{design_result.yaml_frontmatter}

Implementation Required:

  • Type: {gap_analysis.component_type}
  • Model: {design_result.model}
  • Permissions: {design_result.permissions}

Next: Implementation Phase """)

return {
    'type': gap_analysis.component_type,
    'design': design_result,
    'permissions_needed': design_result.permissions
}

### Step 4: Implement New Component

```python
def implement_evolution_component(issue_number, milestone_id, design):
    """Create new agent/skill/workflow based on research"""
    
    component_type = design['type']
    
    if component_type == 'agent':
        # Create agent file
        agent_file = f".kilo/agents/{design['design']['name']}.md"
        write_file(agent_file, design['design']['content'])
        
        # Update orchestrator permissions
        update_orchestrator_permissions(design['design']['name'])
        
        # Update capability index
        update_capability_index(
            agent_name=design['design']['name'],
            capabilities=design['design']['capabilities']
        )
        
    elif component_type == 'skill':
        # Create skill directory
        skill_dir = f".kilo/skills/{design['design']['name']}"
        create_directory(skill_dir)
        write_file(f"{skill_dir}/SKILL.md", design['design']['content'])
        
    elif component_type == 'workflow':
        # Create workflow file
        workflow_file = f".kilo/workflows/{design['design']['name']}.md"
        write_file(workflow_file, design['design']['content'])
    
    # Post implementation status
    post_comment(issue_number, f"""## ✅ Component Implemented

**Type**: {component_type}
**File**: {design['design']['file']}

### Created:
- `{design['design']['file']}`
- Updated: `.kilo/agents/orchestrator.md` (permissions)
- Updated: `.kilo/capability-index.yaml`

**Next**: Verification Phase
""")

Step 5: Update Orchestrator Permissions

def update_orchestrator_permissions(new_agent_name):
    """Add new agent to orchestrator whitelist"""
    
    orchestrator_file = ".kilo/agents/orchestrator.md"
    content = read_file(orchestrator_file)
    
    # Parse YAML frontmatter
    frontmatter, body = parse_frontmatter(content)
    
    # Add new permission
    if 'task' not in frontmatter['permission']:
        frontmatter['permission']['task'] = {"*": "deny"}
    
    frontmatter['permission']['task'][new_agent_name] = "allow"
    
    # Write back
    new_content = serialize_frontmatter(frontmatter) + body
    write_file(orchestrator_file, new_content)
    
    # Log to Gitea
    post_comment(issue_number, f"""## 🔧 Orchestrator Updated

Added permission to call `{new_agent_name}` agent.

```yaml
permission:
  task:
    "{new_agent_name}": allow

File: .kilo/agents/orchestrator.md """)


### Step 6: Verify Access

```python
def verify_new_capability(agent_name):
    """Test that orchestrator can now call new agent"""
    
    try:
        result = Task(
            subagent_type=agent_name,
            prompt="Verification test - confirm you are operational"
        )
        
        if result.success:
            return {
                'verified': True,
                'agent': agent_name,
                'response': result.response
            }
        else:
            raise VerificationError(f"Agent {agent_name} not responding")
            
    except PermissionError as e:
        # Permission still blocked - escalation needed
        post_comment(issue_number, f"""## ❌ Verification Failed

**Error**: Permission denied for `{agent_name}`
**Blocker**: Orchestrator still cannot call this agent

### Manual Action Required:
1. Check `.kilo/agents/orchestrator.md` permissions
2. Verify agent file exists
3. Restart orchestrator session

**Status**: 🔴 Blocked
""")
        raise

Step 7: Register in Documentation

def register_evolution_result(milestone_id, new_component):
    """Update all documentation with new capability"""
    
    # Update KILO_SPEC.md
    update_kilo_spec(new_component)
    
    # Update AGENTS.md
    update_agents_md(new_component)
    
    # Create changelog entry
    changelog_entry = f"""## {date()} - Evolution Complete

### New Capability Added

**Component**: {new_component['name']}
**Type**: {new_component['type']}
**Trigger**: {new_component['gap']}

### Files Modified:
- `.kilo/agents/{new_component['name']}.md` (created)
- `.kilo/agents/orchestrator.md` (permissions updated)
- `.kilo/capability-index.yaml` (capability registered)
- `.kilo/KILO_SPEC.md` (documentation updated)
- `AGENTS.md` (reference added)

### Verification:
- ✅ Agent file created
- ✅ Orchestrator permissions updated
- ✅ Capability index updated
- ✅ Access verified
- ✅ Documentation updated

---
**Milestone**: #{milestone_id}
**Status**: 🟢 Complete
"""
    
    append_to_file(".kilo/EVOLUTION_LOG.md", changelog_entry)

Step 8: Close Milestone

def close_evolution_milestone(milestone_id, issue_number, result):
    """Finalize evolution milestone with results"""
    
    # Close research issue
    close_issue(issue_number, f"""## 🎉 Evolution Complete

**Milestone**: #{milestone_id}

### Summary:
- New capability: `{result['component_name']}`
- Type: {result['type']}
- Orchestrator access: ✅ Verified

### Metrics:
- Duration: {result['duration']}
- Agents involved: history-miner, capability-analyst, agent-architect
- Files modified: {len(result['files'])}

**Evolution logged to**: `.kilo/EVOLUTION_LOG.md`
""")
    
    # Close milestone
    close_milestone(milestone_id, f"""Evolution complete. New capability '{result['component_name']}' registered and accessible.

- Issue: #{issue_number}
- Verification: PASSED
- Orchestrator access: CONFIRMED
""")

Complete Evolution Flow

[Task Requires Unknown Capability]
            ↓
1. Create Evolution Milestone → Gitea milestone + research issue
            ↓
2. Run History Search → @history-miner checks git history
            ↓
3. Analyze Gap → @capability-analyst classifies gap
            ↓
4. Design Component → @agent-architect creates spec
            ↓
5. Decision: Agent/Skill/Workflow?
            ↓
    ┌───────┼───────┐
    ↓       ↓       ↓
 [Agent] [Skill] [Workflow]
    ↓       ↓       ↓
6. Create File → .kilo/agents/{name}.md (or skill/workflow)
            ↓
7. Update Orchestrator → Add to permission whitelist
            ↓
8. Update capability-index.yaml → Register capabilities
            ↓
9. Verify Access → Task tool test call
            ↓
10. Update Documentation → KILO_SPEC.md, AGENTS.md, EVOLUTION_LOG.md
            ↓
11. Close Milestone → Record in Gitea with results
            ↓
[Orchestrator Now Has New Capability]

Gitea Milestone Structure

milestone:
  title: "[Evolution] {gap_description}"
  state: open
  
  issues:
    - title: "[Research] {gap_description}"
      labels: [evolution, research]
      tasks:
        - History search
        - Gap analysis
        - Component design
    
    - title: "[Implement] {component_name}"
      labels: [evolution, implementation]
      tasks:
        - Create agent/skill/workflow file
        - Update orchestrator permissions
        - Update capability index
    
    - title: "[Verify] {component_name}"
      labels: [evolution, verification]
      tasks:
        - Test orchestrator access
        - Update documentation
        - Close milestone

  timeline:
    - 2026-04-06: Milestone created
    - 2026-04-06: Research complete
    - 2026-04-06: Implementation done
    - 2026-04-06: Verification passed
    - 2026-04-06: Milestone closed

Evolution Log Format

.kilo/EVOLUTION_LOG.md:

# Orchestrator Evolution Log

Timeline of capability expansions through self-modification.

## Entry: 2026-04-06T22:15:00+01:00

### Gap
Task required NLP processing capability not available.

### Research
- Milestone: #42
- Issue: #43
- Analysis: Critical gap - no NLP agent exists

### Implementation
- Created: `.kilo/agents/nlp-processor.md`
- Model: `ollama-cloud/nemotron-3-super`
- Permissions: read, edit, task

### Verification
- Test call: ✅ Success
- Orchestrator access: ✅ Confirmed
- Capability index: ✅ Registered

### Files Modified
- .kilo/agents/nlp-processor.md (new)
- .kilo/agents/orchestrator.md (permission added)
- .kilo/capability-index.yaml (registered)
- .kilo/KILO_SPEC.md (documented)

### Metrics
- Duration: 15 minutes
- Agents used: history-miner, capability-analyst, agent-architect
- Tokens consumed: ~25,000

---

Orchestrator Behavior Change

Add to orchestrator.md Behavior Guidelines:

## Self-Evolution Policy

When task requirements exceed current capabilities:

1. **Detect Gap**: If no agent/skill/workflow matches task
2. **Create Milestone**: Document the evolution attempt in Gitea
3. **Run Research**: Invoke capability-analyst + agent-architect
4. **Implement**: Create new agent/skill/workflow
5. **Self-Modify**: Add new permission to own whitelist
6. **Verify**: Test access to new capability
7. **Register**: Update all documentation
8. **Log**: Record in EVOLUTION_LOG.md
9. **Close**: Mark milestone complete with results

### Evolution Triggers

- Task type not in capability Routing Map
- capability-analyst reports critical gap
- Repeated task failures for same reason
- User requests new specialized capability

### Self-Modification Rules

1. ONLY modify own permission whitelist
2. NEVER modify other agents' definitions
3. ALWAYS create milestone before changes
4. ALWAYS verify access after changes
5. ALWAYS log results to EVOLUTION_LOG.md

Prohibited Self-Evolution Actions

  • DO NOT create agents without capability-analyst approval
  • DO NOT skip verification step
  • DO NOT modify other agents without permission
  • DO NOT close milestone without verification
  • DO NOT evolve for single-use scenarios
  • DO NOT create duplicate capabilities