# Code Generation Workflow - MANDATORY

## Applies To: ALL MODES
**This workflow applies to MSP Mode, Development Mode, and Normal Mode.**

All modes use agents extensively to preserve context space. Code generation follows the same quality standards regardless of mode.

---

## Critical Rule: NO CODE BYPASSES REVIEW

**All code generated by the Coding Agent MUST be reviewed by the Code Review Agent before being presented to the user or deployed to production.**

This is non-negotiable and applies to:
- New code implementations
- Code modifications
- Bug fixes
- Refactoring
- Script creation
- Configuration files with code logic
- Any executable code in any language

**Regardless of which mode you're in** - the quality standards are the same.

## Standard Workflow

```
User Request
    ↓
Main Claude (orchestrates)
    ↓
┌─────────────────────────────────┐
│ 1. Launch Coding Agent          │
│    - Understand requirements    │
│    - Research environment       │
│    - Design solution            │
│    - Implement completely       │
│    - Return code                │
└─────────────────────────────────┘
    ↓
┌─────────────────────────────────┐
│ 2. Launch Code Review Agent     │
│    - Verify spec compliance     │
│    - Check security             │
│    - Verify quality             │
│    - Fix minor issues           │
│    - Escalate major issues      │
└─────────────────────────────────┘
    ↓
    Decision Point
    ↓
┌──────────────┬──────────────────┐
│ APPROVED ✅  │ REJECTED ❌      │
│              │                  │
│ Present to   │ Send back to     │
│ user with    │ Coding Agent     │
│ review       │ with detailed    │
│ notes        │ feedback         │
└──────────────┴──────────────────┘
                      ↓
               (loop back to step 1)
```

## Execution Pattern

### Pattern 1: Sequential Agent Chain (Typical)

```javascript
// Main Claude orchestrates:

// Step 1: Code generation
const codingResult = await Task({
  subagent_type: "general-purpose",
  prompt: `You are the Coding Agent (see D:\ClaudeTools\.claude\agents\coding.md).

Requirements:
${userRequirements}

Environment:
${environmentContext}

Implement this completely with no shortcuts.`,
  description: "Generate production code"
});

// Step 2: Code review (MANDATORY - always happens)
const reviewResult = await Task({
  subagent_type: "general-purpose",
  prompt: `You are the Code Review Agent (see D:\ClaudeTools\.claude\agents\code-review.md).

Review this code for production readiness:

${codingResult}

Original specification:
${userRequirements}

Approve if production-ready, or escalate with detailed notes if issues found.`,
  description: "Review code for approval"
});

// Step 3: Handle review decision
if (reviewResult.status === "APPROVED") {
  // Present to user with review notes
  presentToUser(codingResult, reviewResult.notes);
} else if (reviewResult.status === "REQUIRES_REVISION") {
  // Loop back to Coding Agent with feedback
  // (repeat until approved)
}
```

### Pattern 2: Multiple Review Cycles (If Needed)

```
Attempt 1:
  Coding Agent → Code Review Agent → REJECTED (security issue)
    ↓
Attempt 2:
  Coding Agent (with feedback) → Code Review Agent → REJECTED (missing edge case)
    ↓
Attempt 3:
  Coding Agent (with feedback) → Code Review Agent → APPROVED ✅
    ↓
  Present to User
```

**Maximum 3 cycles** - If not approved after 3 attempts, escalate to user for clarification.

## What Gets Presented to User

When code is approved:

```markdown
## Implementation Complete ✅

[Brief description of what was implemented]

### Code Review Status
**Reviewed by:** Code Review Agent
**Status:** APPROVED for production
**Review Notes:**
- [Strengths identified]
- [Minor fixes applied]
- [Any recommendations]

### Files Modified/Created
- `path/to/file.py` - [description]
- `path/to/test.py` - [description]

### Dependencies Added
- package==version (reason)

### Environment Requirements
- Runtime: Python 3.9+
- OS: Windows/Linux/macOS
- Permissions: [any special permissions]

### Usage
[How to use the code]

### Testing
[How to test/verify]

---

[CODE BLOCKS HERE]
```

## What NEVER Happens

❌ **NEVER** present code directly from Coding Agent to user
❌ **NEVER** skip review "because it's simple"
❌ **NEVER** skip review "because we're in a hurry"
❌ **NEVER** skip review "because user trusts us"
❌ **NEVER** present unapproved code as "draft" without review

## Exceptions: NONE

There are **no exceptions** to this workflow.

Even for:
- "Quick fixes"
- "One-liner changes"
- "Just configuration"
- "Emergency patches"
- "User explicitly asked to skip review"

**All code gets reviewed. Period.**

## Quality Gates

Code Review Agent checks:
- ✅ Specification compliance
- ✅ Security (no vulnerabilities)
- ✅ Error handling (comprehensive)
- ✅ Input validation (all inputs)
- ✅ Best practices (language-specific)
- ✅ Environment compatibility
- ✅ Performance (no obvious issues)
- ✅ Completeness (no TODOs/stubs)

**If any gate fails → REJECTED → Back to Coding Agent**

## Review Cycle Handling

### Cycle 1: Initial Review
- Coding Agent produces code
- Code Review Agent reviews
- If rejected: Detailed feedback provided

### Cycle 2: Revision
- Coding Agent fixes issues from feedback
- Code Review Agent reviews again
- If rejected: More specific feedback

### Cycle 3: Final Attempt
- Coding Agent addresses remaining issues
- Code Review Agent reviews
- If still rejected: Escalate to user

### Escalation to User
After 3 cycles without approval:

```markdown
## Code Implementation - Requires User Input

After 3 review cycles, the code has remaining issues that need your guidance:

**Remaining Issues:**
[List of issues that couldn't be resolved]

**Options:**
1. Relax requirement: [specific requirement to relax]
2. Accept with known limitations: [what limitations]
3. Provide more context: [what's unclear]
4. Change approach: [alternative approach]

**Current Code Status:** Not approved for production
```

## Integration with MSP Mode

When in MSP Mode:
- Code Review Agent checks `environmental_insights` for known constraints
- Review findings logged to database for learning
- Client-specific requirements verified
- Infrastructure compatibility checked

## Monitoring & Metrics

Track (future):
- Average review cycles per implementation
- Common rejection reasons
- Time saved by catching issues pre-production
- Security vulnerabilities prevented

## Training & Improvement

- All rejections logged with reasons
- Patterns analyzed to improve Coding Agent
- Environmental insights updated from review findings
- Review criteria refined based on production issues

---

## Summary

**The Rule:** Coding Agent → Code Review Agent → User

**No Exceptions:** Every single time, no matter what

**Result:** Only production-ready, reviewed, secure code reaches the user

**Benefit:** Quality, security, and reliability guaranteed

---

**This workflow is immutable. Code quality is not negotiable.**
