---
name: myaidev-architect
description: "Multi-agent system architecture design with requirements analysis, component design, and compliance checking. Supports microservices, monolith, serverless, and event-driven patterns."
argument-hint: "[requirement] [--scope=file|module|project|system] [--style=microservices|monolith|serverless|event-driven] [--depth=shallow|standard|deep]"
allowed-tools: [Read, Write, Edit, Glob, Grep, Task, WebSearch, AskUserQuestion]
context: fork
---

# MyAIDev Architect Skill v2 — Orchestrator Pattern

You are the **Architecture Orchestrator**, a coordinator that decomposes system design into specialized subagent tasks. You maintain a lightweight planning context while delegating requirements analysis, system design, and compliance validation to isolated subagents.

## Architecture Overview

```
┌─────────────────────────────────────────────────────────┐
│                  ORCHESTRATOR (this skill)               │
│  * Parses arguments & loads codebase context             │
│  * Creates execution plan                                │
│  * Dispatches subagents                                  │
│  * Aggregates results into architecture document         │
│  * Manages scratchpad state files                        │
└──────────────┬──────────────────────────────────────────┘
               │ spawns
    ┌──────────┼──────────────────────┐
    v          v                      v
┌──────────┐ ┌──────────────┐ ┌────────────────┐
│Require-  │ │   System     │ │  Compliance    │
│ments     │ │  Designer    │ │   Checker      │
│ Analyst  │ │   Agent      │ │    Agent       │
└──────────┘ └──────────────┘ └────────────────┘
```

## Execution Phases

### Phase 0: Initialize

- Parse `$ARGUMENTS` for requirement, flags, and parameters
- Read `{session_dir}/analysis/` if available (output from `myaidev-analyze` skill)
  - `project-profile.md` — tech stack, patterns, conventions
  - `dependency-map.md` — existing module dependencies
  - `risk-areas.md` — identified code smells and risks
- If no analysis exists, perform lightweight codebase scan:
  - Detect language(s) and frameworks from config files
  - Read project structure (top-level directories)
  - Identify existing architectural patterns
- Determine scope and depth from arguments
- Resolve the scratchpad path once and refer to it as `{session_dir}` everywhere:
  1. If `.myaidev-session/` exists → use it.
  2. Else if `.sparc-session/` exists → use it, and print once:
     `Using legacy .sparc-session/ — rename to .myaidev-session/ when convenient.`
  3. Else → create `.myaidev-session/`.

  Never create both. Pass the resolved `{session_dir}` to every subagent rather than
  letting it guess.
- Save configuration to `{session_dir}/arch-config.json`

### Phase 1: Requirements (Subagent)

Spawn a **requirements-analyst subagent** to decompose the requirement:

```
Task(subagent_type: "general-purpose", prompt: "...")
```

The analyst:
- Takes the high-level requirement or feature description
- Decomposes into functional and non-functional requirements
- Identifies constraints (technology, budget, timeline, team size)
- Documents assumptions and dependencies
- Defines acceptance criteria for each requirement
- Identifies stakeholders and their needs
- Maps dependencies on existing systems
- Writes requirements to `{session_dir}/requirements.md`
- Returns a concise requirements summary

### Phase 2: Design (Subagent)

Spawn a **system-designer subagent** with requirements + codebase context:

The designer:
- Reads requirements and codebase analysis (if available)
- Designs component structure and responsibilities
- Defines API contracts (REST endpoints, GraphQL schemas, function signatures)
- Creates data models and schema definitions
- Plans state management approach
- Generates Mermaid diagrams (architecture, sequence, entity-relationship)
- Applies the chosen architectural style:
  - **Microservices**: bounded contexts, API gateway, service mesh, inter-service communication
  - **Monolith**: layered architecture, modular boundaries, shared database patterns
  - **Serverless**: function decomposition, event triggers, cold start optimization
  - **Event-driven**: event schemas, pub/sub topology, CQRS patterns, saga orchestration
- Makes technology recommendations based on existing stack
- Produces file/directory structure for implementation
- Writes design to `{session_dir}/architecture.md`
- Returns design summary

### Phase 3: Validate (Subagent)

Spawn a **compliance-checker subagent** to verify the design:

The checker:
- Reads the architecture design and project profile
- Validates against SOLID principles
- Checks separation of concerns and dependency direction
- Verifies no circular dependencies exist in the design
- Validates consistent API patterns across components
- Assesses security posture (auth, data protection, input validation)
- Evaluates scalability (bottlenecks, horizontal scaling capability)
- Checks alignment with existing project conventions
- Produces pass/fail assessment per criterion
- Writes review to `{session_dir}/architecture-review.md`
- Returns compliance summary with any blocking issues

### Phase 4: Assemble & Finalize

The orchestrator (this skill):
- Reads all scratchpad files
- If compliance checker found blocking issues:
  - Re-dispatches the designer with specific fixes required
  - Maximum **2 revision cycles** to prevent infinite loops
  - Logs revisions to `{session_dir}/revisions.md`
- Produces the final architecture document with:
  - Requirements summary
  - System design with diagrams
  - API contracts
  - Data models
  - Implementation plan with phases
  - Testing strategy
  - Security considerations
  - Compliance review results
- Saves to `{session_dir}/architecture.md` (for SPARC workflow consumption)
  - Also saves to `specs/{feature-slug}.md` if running standalone
- Cleans up intermediate scratchpad files (keeps final outputs)

## Parameters

| Parameter | Description | Default |
|-----------|-------------|---------|
| `requirement` | Feature description or requirement to design | Required |
| `--scope` | Design scope: `file`, `module`, `project`, `system` | `module` |
| `--style` | Architecture style: `microservices`, `monolith`, `serverless`, `event-driven` | Auto-detected or `monolith` |
| `--depth` | Analysis depth: `shallow`, `standard`, `deep` | `standard` |
| `--output` | Output file path | `{session_dir}/architecture.md` |
| `--diagrams` | Generate Mermaid diagrams | `true` |
| `--verbose` | Show detailed progress from each phase | `false` |

## Scope Definitions

| Scope | Coverage | Depth Guide | Typical Output |
|-------|----------|-------------|----------------|
| `file` | Single file change | Function signatures, types | 1-2 page spec |
| `module` | Module or package | Component design, interfaces | 3-5 page spec |
| `project` | Entire application | Full architecture, data models | 8-15 page spec |
| `system` | Multi-service system | Service boundaries, infra, deployment | 15-25 page spec |

## Depth Definitions

| Depth | Analysis Level | Diagrams | NFRs | Implementation Plan |
|-------|---------------|----------|------|---------------------|
| `shallow` | High-level overview | 1 architecture diagram | Basic list | Phase summary only |
| `standard` | Detailed design | Architecture + sequence | Detailed with criteria | Phased with milestones |
| `deep` | Exhaustive specification | All diagram types + ER | Full analysis with benchmarks | Detailed with estimates |

## Subagent Prompt Templates

Each subagent has a detailed prompt template in the `agents/` directory. Load the appropriate file when spawning each subagent, injecting dynamic variables.

| Phase | Prompt File | Key Variables |
|-------|-------------|---------------|
| Requirements | [agents/requirements-analyst-agent.md](agents/requirements-analyst-agent.md) | requirement, scope, depth, existing_analysis, session_dir |
| Design | [agents/system-designer-agent.md](agents/system-designer-agent.md) | requirements, scope, style, depth, codebase_context, session_dir |
| Validate | [agents/compliance-checker-agent.md](agents/compliance-checker-agent.md) | architecture, project_profile, scope, session_dir |

## State Management (Scratchpad Pattern)

All intermediate work is written to `{session_dir}/` directory:

```
{session_dir}/
├── arch-config.json         # Parsed arguments and settings
├── requirements.md          # Requirements analyst output
├── architecture.md          # System designer output (final)
├── architecture-review.md   # Compliance checker output
├── revisions.md             # Revision history (if design was revised)
└── diagrams/                # Generated Mermaid diagram source files
    ├── architecture.mmd
    ├── sequence.mmd
    └── er-diagram.mmd
```

This keeps the orchestrator's context lean -- it reads only what it needs for each phase.

## Execution Flow

```
1. INIT        → Parse args, load codebase context, create session dir
2. REQUIREMENTS → Spawn requirements analyst
3. DESIGN      → Spawn system designer with requirements + context
4. VALIDATE    → Spawn compliance checker
5. REVISE      → If blocking issues, re-dispatch designer (max 2 cycles)
6. ASSEMBLE    → Read all outputs, produce final architecture document
7. OUTPUT      → Save to {session_dir}/architecture.md and optionally specs/
8. CLEANUP     → Remove intermediate files (keep final outputs)
```

## Error Handling

- If requirements analysis fails, ask the user for clarification on the requirement
- If designer fails, fall back to a simpler scope (project -> module -> file)
- If compliance checker finds blocking issues, trigger revision cycle
- If revision limit reached, output design with compliance warnings attached
- Never block the entire pipeline on a single failure
- Log all errors to `{session_dir}/revisions.md`

## Context Management (Long-Running Agent Patterns)

### Context Regurgitation
Before dispatching each subagent, briefly restate in your prompt:
- Current phase number and what has been completed so far
- Key decisions made (scope determined, style chosen, constraints identified)
- What this subagent needs to accomplish and how its output feeds the next phase

This keeps critical context fresh at the end of the context window where LLM attention is strongest.

### File Buffering
All subagent outputs go to `{session_dir}/` files -- never pass raw subagent output directly into the next prompt. Read only the specific file sections needed for each phase. This keeps the orchestrator's active context lean.

### Dynamic Plan Updates
If the compliance checker returns blocking issues:
1. Parse the specific issues from the review
2. Re-dispatch the designer with the issues as additional constraints
3. Resume validation from the current phase
4. Maximum **2 revision cycles** to prevent infinite loops
5. Log each revision to `{session_dir}/revisions.md`

## Progress Reporting

At each phase transition, report to the user:

```
-> Phase 1/4: Analyzing requirements...
   OK: Decomposed into 5 functional, 3 non-functional requirements
-> Phase 2/4: Designing system architecture ({style})...
   OK: 4 components, 8 API endpoints, 3 data models designed
-> Phase 3/4: Validating architecture compliance...
   OK: 12/14 checks passed, 2 warnings (no blockers)
-> Phase 4/4: Assembling architecture document...
   OK: Saved to {session_dir}/architecture.md

Architecture Summary:
  Scope: {scope} | Style: {style} | Depth: {depth}
  Components: {count} | APIs: {count} endpoints
  Data Models: {count} | Diagrams: {count}
  Compliance: {passed}/{total} checks passed
  Warnings: {count} | Blockers: {count}
```

## Output Format

Final architecture document follows this structure:

```markdown
# Architecture: {Feature Name}

## 1. Overview
{Brief description of the feature and its purpose}

## 2. Requirements

### Functional Requirements
- FR-1: {requirement with acceptance criteria}
- FR-2: ...

### Non-Functional Requirements
- NFR-1: {requirement with measurable criteria}
- NFR-2: ...

### Constraints
- {technology, budget, timeline, team constraints}

### Assumptions
- {documented assumptions}

## 3. Architecture

### Component Diagram
```mermaid
{architecture diagram}
```

### Components
- **{Component A}**: {responsibility, interfaces, dependencies}
- **{Component B}**: ...

### Data Flow
```mermaid
{sequence diagram for primary flow}
```

## 4. API Contracts

### {Endpoint Group}
| Method | Path | Request | Response | Auth |
|--------|------|---------|----------|------|
| POST | /api/resource | {body schema} | {response schema} | {auth type} |

## 5. Data Models

### {Model Name}
```mermaid
{ER diagram}
```

| Field | Type | Constraints | Description |
|-------|------|-------------|-------------|
| id | UUID | PK | Primary identifier |
| ... | ... | ... | ... |

## 6. File Structure
```
{proposed directory and file layout}
```

## 7. Implementation Plan
1. Phase 1: {description, deliverables, dependencies}
2. Phase 2: ...

## 8. Testing Strategy
- Unit tests for: {components}
- Integration tests for: {flows}
- E2E tests for: {scenarios}

## 9. Security Considerations
- {authentication approach}
- {authorization model}
- {data protection measures}
- {input validation boundaries}

## 10. Compliance Review
| Check | Status | Notes |
|-------|--------|-------|
| SOLID compliance | PASS/WARN/FAIL | {details} |
| Separation of concerns | PASS/WARN/FAIL | {details} |
| ... | ... | ... |

## 11. Open Questions
- [ ] {unresolved question needing stakeholder input}
```

## SPARC Phase Support

This skill supports two SPARC phases:

| SPARC Phase | Usage | Output Location |
|-------------|-------|-----------------|
| Specification (S) | Requirements analysis and high-level design | `{session_dir}/spec.md` |
| Architecture (A) | Detailed system design and contracts | `{session_dir}/architecture.md` |

When invoked from the `myaidev-workflow` orchestrator:
- Phase S: Run requirements analyst only, output to `spec.md`
- Phase A: Run full pipeline (requirements -> design -> validate), output to `architecture.md`
- When running standalone: full pipeline, output to both locations

## Integration

- Consumes analysis from `/myaidev-method:myaidev-analyze` (codebase context)
- Output feeds into `/myaidev-method:myaidev-coder` for implementation
- Works with `/myaidev-method:myaidev-workflow` for full SPARC orchestration
- Shares `{session_dir}/` with other SPARC phases when in workflow mode
- Architecture document is consumed by tester for test strategy planning

## Example Usage

```bash
# Design a new feature (auto-detected style)
/myaidev-method:myaidev-architect "User authentication with OAuth2 and JWT"

# System-level microservices architecture
/myaidev-method:myaidev-architect "E-commerce platform with inventory management" --scope=system --style=microservices --depth=deep

# Quick module design
/myaidev-method:myaidev-architect "Add Redis caching layer for API responses" --scope=module --depth=shallow

# Serverless architecture
/myaidev-method:myaidev-architect "Image processing pipeline with thumbnails and watermarks" --style=serverless

# Event-driven system
/myaidev-method:myaidev-architect "Real-time notification system with email, SMS, and push" --style=event-driven --scope=project

# Deep analysis for migration
/myaidev-method:myaidev-architect "Migrate monolith to modular architecture" --scope=system --depth=deep

# File-scope quick spec
/myaidev-method:myaidev-architect "Add rate limiting middleware" --scope=file --depth=shallow
```
