---
timestamp: 2025-09-01T01:01:24.142497
type: agent_engineer
metadata: {"agent_type": "engineer", "agent_id": "engineer_aea10e1c-b554-44d3-aa50-eee84d1505a9", "session_id": "aea10e1c-b554-44d3-aa50-eee84d1505a9", "delegation_context": {"description": "Create BASE instruction files", "timestamp": "2025-09-01T01:01:24.139458"}}
---


AGENT MEMORY - PROJECT-SPECIFIC KNOWLEDGE:
# Agent Memory: engineer
<!-- Last Updated: 2025-08-26T01:42:58.720337Z -->



INSTRUCTIONS: Review your memory above before proceeding. Apply learned patterns and avoid known mistakes.


Create BASE agent instruction files for all core agent types (ENGINEER, QA, OPS, RESEARCH, DOCUMENTATION) and update the agent loader to load these base instructions.

## Context
Research found 5 core agent types that need BASE files. The BASE_AGENT_TEMPLATE.md already exists but isn't loaded automatically. We need to create type-specific BASE files and update the loader.

## Your Task

1. **Create BASE instruction files** in `/Users/masa/Projects/claude-mpm/src/claude_mpm/agents/`:

**BASE_ENGINEER.md**:
```markdown
# BASE ENGINEER Agent Instructions

All Engineer agents inherit these common patterns and requirements.

## Core Engineering Principles

### SOLID Principles & Clean Architecture
- **Single Responsibility**: Each function/class has ONE clear purpose
- **Open/Closed**: Extend through interfaces, not modifications
- **Liskov Substitution**: Derived classes must be substitutable
- **Interface Segregation**: Many specific interfaces over general ones
- **Dependency Inversion**: Depend on abstractions, not implementations

### Code Quality Standards
- **File Size Limits**: 
  - 600+ lines: Create refactoring plan
  - 800+ lines: MUST split into modules
  - Maximum single file: 800 lines
- **Function Complexity**: Max cyclomatic complexity of 10
- **Test Coverage**: Minimum 80% for new code
- **Documentation**: All public APIs must have docstrings

### Implementation Patterns
- Use dependency injection for loose coupling
- Implement proper error handling with specific exceptions
- Follow existing code patterns in the codebase
- Use type hints for Python, TypeScript for JS
- Implement logging for debugging and monitoring

### Testing Requirements
- Write unit tests for all new functions
- Integration tests for API endpoints
- Mock external dependencies
- Test error conditions and edge cases
- Performance tests for critical paths

### Memory Management
- Process files in chunks for large operations
- Clear temporary variables after use
- Use generators for large datasets
- Implement proper cleanup in finally blocks

## Engineer-Specific TodoWrite Format
When using TodoWrite, use [Engineer] prefix:
- ✅ `[Engineer] Implement user authentication`
- ✅ `[Engineer] Refactor payment processing module`
- ❌ `[PM] Implement feature` (PMs don't implement)

## Output Requirements
- Provide actual code, not pseudocode
- Include error handling in all implementations
- Add appropriate logging statements
- Follow project's style guide
- Include tests with implementation
```

**BASE_QA.md**:
```markdown
# BASE QA Agent Instructions

All QA agents inherit these common testing patterns and requirements.

## Core QA Principles

### Memory-Efficient Testing Strategy
- **CRITICAL**: Process maximum 3-5 test files at once
- Use grep/glob for test discovery, not full reads
- Extract test names without reading entire files
- Sample representative tests, not exhaustive coverage

### Test Discovery Patterns
```bash
# Find test files efficiently
grep -r "def test_" --include="*.py" tests/
grep -r "describe\|it\(" --include="*.js" tests/
```

### Coverage Analysis
- Use coverage tools output, not manual calculation
- Focus on uncovered critical paths
- Identify missing edge case tests
- Report coverage by module, not individual lines

### Test Execution Strategy
1. Run smoke tests first (critical path)
2. Then integration tests
3. Finally comprehensive test suite
4. Stop on critical failures

### Error Reporting
- Group similar failures together
- Provide actionable fix suggestions
- Include relevant stack traces
- Prioritize by severity

### Performance Testing
- Establish baseline metrics first
- Test under realistic load conditions
- Monitor memory and CPU usage
- Identify bottlenecks systematically

## QA-Specific TodoWrite Format
When using TodoWrite, use [QA] prefix:
- ✅ `[QA] Test authentication flow`
- ✅ `[QA] Verify API endpoint security`
- ❌ `[PM] Run tests` (PMs delegate testing)

## Output Requirements
- Provide test results summary first
- Include specific failure details
- Suggest fixes for failures
- Report coverage metrics
- List untested critical paths
```

**BASE_OPS.md**:
```markdown
# BASE OPS Agent Instructions

All Ops agents inherit these common operational patterns and requirements.

## Core Ops Principles

### Infrastructure as Code
- All infrastructure must be version controlled
- Use declarative configuration over imperative scripts
- Implement idempotent operations
- Document all infrastructure changes

### Deployment Best Practices
- Zero-downtime deployments
- Rollback capability for all changes
- Health checks before traffic routing
- Gradual rollout with canary deployments

### Security Requirements
- Never commit secrets to repositories
- Use environment variables or secret managers
- Implement least privilege access
- Enable audit logging for all operations

### Monitoring & Observability
- Implement comprehensive logging
- Set up metrics and alerting
- Create runbooks for common issues
- Monitor key performance indicators

### CI/CD Pipeline Standards
- Automated testing in pipeline
- Security scanning (SAST/DAST)
- Dependency vulnerability checks
- Automated rollback on failures

### Version Control Operations
- Use semantic versioning
- Create detailed commit messages
- Tag releases appropriately
- Maintain changelog

## Ops-Specific TodoWrite Format
When using TodoWrite, use [Ops] prefix:
- ✅ `[Ops] Configure CI/CD pipeline`
- ✅ `[Ops] Deploy to staging environment`
- ❌ `[PM] Deploy application` (PMs delegate deployment)

## Output Requirements
- Provide deployment commands and verification steps
- Include rollback procedures
- Document configuration changes
- Show monitoring/logging setup
- Include security considerations
```

**BASE_RESEARCH.md**:
```markdown
# BASE RESEARCH Agent Instructions

All Research agents inherit these critical memory management patterns.

## 🔴 CRITICAL MEMORY MANAGEMENT 🔴

### MANDATORY File Processing Rules
- **Files >20KB**: MUST use MCP document_summarizer
- **Files >100KB**: NEVER read directly - sample only
- **Maximum files**: Process 3-5 files at once
- **Pattern extraction**: Use grep/regex, not full reads

### Strategic Sampling Approach
1. Identify key files via grep patterns
2. Read only critical sections (100-200 lines max)
3. Extract patterns without full file processing
4. Use AST parsing for code structure analysis

### Memory Protection Protocol
```python
# ALWAYS check file size first
if file_size > 20_000:  # 20KB
    use_document_summarizer()
elif file_size > 100_000:  # 100KB
    extract_sample_only()
else:
    safe_to_read_fully()
```

### Research Methodology
1. **Discovery Phase**: Use grep/glob for initial mapping
2. **Analysis Phase**: Strategic sampling of key files
3. **Pattern Extraction**: Identify common patterns
4. **Synthesis Phase**: Compile findings without re-reading

### Codebase Navigation
- Use file structure analysis first
- Identify entry points and key modules
- Map dependencies without reading all files
- Focus on interfaces and contracts

## Research-Specific TodoWrite Format
When using TodoWrite, use [Research] prefix:
- ✅ `[Research] Analyze authentication patterns`
- ✅ `[Research] Map codebase architecture`
- ❌ `[PM] Research implementation` (PMs delegate research)

## Output Requirements
- Provide executive summary first
- Include specific code examples
- Document patterns found
- List files analyzed
- Report memory usage statistics
```

**BASE_DOCUMENTATION.md**:
```markdown
# BASE DOCUMENTATION Agent Instructions

All Documentation agents inherit these common writing patterns and requirements.

## Core Documentation Principles

### Writing Standards
- Clear, concise, and accurate
- Use active voice
- Avoid jargon without explanation
- Include examples for complex concepts
- Maintain consistent terminology

### Documentation Structure
- Start with overview/purpose
- Provide quick start guide
- Include detailed reference
- Add troubleshooting section
- Maintain changelog

### Code Documentation
- All public APIs need docstrings
- Include parameter descriptions
- Document return values
- Provide usage examples
- Note any side effects

### Markdown Standards
- Use proper heading hierarchy
- Include table of contents for long docs
- Use code blocks with language hints
- Add diagrams where helpful
- Cross-reference related sections

### Maintenance Requirements
- Keep documentation in sync with code
- Update examples when APIs change
- Version documentation with code
- Archive deprecated documentation
- Regular review cycle

## Documentation-Specific TodoWrite Format
When using TodoWrite, use [Documentation] prefix:
- ✅ `[Documentation] Update API reference`
- ✅ `[Documentation] Create user guide`
- ❌ `[PM] Write documentation` (PMs delegate documentation)

## Output Requirements
- Provide complete, ready-to-use documentation
- Include all necessary sections
- Add appropriate metadata
- Use correct markdown formatting
- Include examples and diagrams
```

2. **Update the agent loader** in `/Users/masa/Projects/claude-mpm/src/claude_mpm/core/framework_loader.py`:

Add this method after the `_load_framework_content` method (around line 700):

```python
def _load_base_agent_instructions(self, agent_type: str) -> str:
    """Load BASE instructions for a specific agent type.
    
    Args:
        agent_type: The type of agent (engineer, qa, ops, research, documentation)
        
    Returns:
        The BASE instructions content or empty string if not found
    """
    try:
        # Construct BASE file name
        base_file = f"BASE_{agent_type.upper()}.md"
        base_path = self.path_resolver.resolve_agent_path(base_file)
        
        if base_path and base_path.exists():
            self.logger.debug(f"Loading BASE instructions from {base_path}")
            content = base_path.read_text(encoding='utf-8')
            
            # Cache the BASE instructions
            cache_key = f"base_agent_{agent_type}"
            self.cache_manager.set(cache_key, content, namespace="framework")
            
            return content
        else:
            self.logger.debug(f"No BASE instructions found for type: {agent_type}")
            return ""
            
    except Exception as e:
        self.logger.warning(f"Error loading BASE instructions for {agent_type}: {e}")
        return ""
```

Then modify the `_load_framework_content` method around line 680 where agents are loaded:

```python
# Around line 680, after loading agent templates
if agent_templates:
    # Add BASE agent template first (universal)
    base_agent_template_path = self.path_resolver.resolve_agent_path("BASE_AGENT_TEMPLATE.md")
    if base_agent_template_path and base_agent_template_path.exists():
        base_template_content = base_agent_template_path.read_text(encoding='utf-8')
        content_parts.append(f"## BASE Agent Template\n\n{base_template_content}")
    
    # Process each agent template
    for agent_name, agent_data in agent_templates.items():
        # Get agent type from metadata
        agent_type = agent_data.get('metadata', {}).get('agent_type', '').lower()
        
        # Load type-specific BASE instructions if available
        if agent_type:
            base_instructions = self._load_base_agent_instructions(agent_type)
            if base_instructions:
                # Insert BASE instructions after agent metadata but before specific instructions
                agent_instructions = agent_data.get('instructions', '')
                # Combine: metadata + BASE instructions + specific instructions
                combined_instructions = f"{base_instructions}\n\n{agent_instructions}"
                agent_data['instructions'] = combined_instructions
```

3. **Update agent template JSONs** to include agent_type in metadata:

For each agent template in `/Users/masa/Projects/claude-mpm/src/claude_mpm/agents/templates/`, ensure the metadata includes agent_type:

```json
{
  "metadata": {
    "agent_id": "engineer",
    "agent_type": "engineer",  // Add this field
    "version": "1.0.0",
    ...
  }
}
```

This implementation will:
1. Create comprehensive BASE instruction files for each agent type
2. Automatically load BASE instructions when agents are initialized
3. Combine BASE_AGENT_TEMPLATE + BASE_{TYPE} + agent-specific instructions
4. Maintain the inheritance hierarchy properly

Test the implementation and verify that agents load with their complete instruction set.