---
roadcrew_template_name: "systemPatterns.template.md"
roadcrew_template_type: "memory-bank"
roadcrew_template_version: "1.0"
roadcrew_last_updated: "2025-11-03"
roadcrew_min_version: "1.6.0"
roadcrew_license: "See LICENSE file in .roadcrew folder"
roadcrew_copyright: "Copyright (c) 2025 North Star Holdings, LLC"
spdx_license_identifier: "LicenseRef-RoadcrewLicense-1.0"
cline_memory_bank: "systemPatterns"
---

# System Patterns

**System architecture, key technical decisions, design patterns in use, component relationships, and critical implementation paths**

Last Updated: November 3, 2025  
Architecture Version: v1.6.0

---

## Architecture Overview

### High-Level System Architecture

Roadcrew is a **spec-driven development system** that transforms product vision into working SaaS software through AI-powered automation.

```
┌─────────────────────────────────────────────────────────────────┐
│  ROADCREW-INTERNAL (Source of Truth)                            │
│  ├─ Development + Innovation                                     │
│  ├─ Command definitions (commands/ folder, 40+ commands)        │
│  ├─ Script implementations (scripts/ folder, TypeScript)        │
│  └─ Template definitions (templates/roadcrew/ for publishing)  │
└─────────────────────────────────────────────────────────────────┘
                          ↓↓
            PUBLISHING (Dual Approach)
                          ↓↓
    ┌─────────────────────────────────────┐
    │ Approach 1: File Sync (--push)      │  ← Production (proven)
    │ Approach 2: GitHub API (5-phase)    │  ← CI/CD Integration
    └─────────────────────────────────────┘
                          ↓↓
┌─────────────────────────────────────────────────────────────────┐
│  ROADCREW (Customer-Facing Public Repo)                         │
│  ├─ Published version (.roadcrew/templates/)                   │
│  ├─ Published rules (.roadcrew/rules/)                         │
│  └─ Published commands (.roadcrew/commands/)                   │
└─────────────────────────────────────────────────────────────────┘
                          ↓↓
            GIT SUBMODULE INSTALLATION
                          ↓↓
    ┌─────────────────────────────────────┐
    │ Customer Projects (Multiple)        │
    │ ├─ Git Submodule: .roadcrew/       │
    │ ├─ Local specs: context/specs/     │
    │ ├─ Local epics: context/epics/     │
    │ ├─ AI config: ai-context.yml       │
    │ └─ Commands executed locally       │
    └─────────────────────────────────────┘
```

### System Layers

- **Product Layer:** Vision → PRDs → Specs
- **Workflow Layer:** 8-stage pipeline (ANALYSIS → PLANNING → RELEASE → IMPLEMENTATION → CODE ANALYSIS → TESTING → PUBLISHING → VALIDATION)
- **Command Layer:** 40+ composable commands across 8 stages
- **Template Layer:** 8 template types (BRD, PRD, Spec, Release, Epic, Enhancement, etc.)
- **Publishing Layer:** Dual approach (file sync + GitHub API)
- **Distribution Layer:** Git submodule to customers
- **AI Context Layer:** Memory Bank + Cursor rules for AI guidance

### AI Guidance System (.cursor/rules/)

**Modern Implementation:**
- 14 modular `.mdc` rule files in `.cursor/rules/` directory
- Each rule has specific glob patterns for file types it applies to
- Some rules always apply (e.g., `alwaysApply: true` for core behavior)
- Rules organized by concern: project context, coding standards, testing, patterns, etc.

**Rule Organization:**
- `00-core-behavior.mdc` - Fundamental behaviors and processes
- `00-project-context.mdc` - Project scope and deployment context  
- `01-issue-classification.mdc` - Task profiling and classification
- `02-memory-bank.mdc` - Documentation and memory bank patterns
- `03-github.mdc` - GitHub API and authentication
- `04-coding-standards.mdc` - Code quality and type safety
- `05-documentation.mdc` - Documentation standards
- `06-testing.mdc` - Test-driven development practices
- `07-project-patterns.mdc` - Roadcrew-specific patterns
- `08-publishing.mdc` - Publishing and release process
- `09-mode-routing.mdc` - Deployment modes and AI routing

**Key Improvement:** Replaces monolithic `.cursorrules.md` file with composable, concern-specific rules for better maintainability and customer customization.

---

## Key Technical Decisions

### Decision 1: Git Submodule Distribution (Not npm Package)

**Context:**
Roadcrew needs customer installation mechanism that provides version control and safety.

**Decision:**
Distribute via git submodule (`.roadcrew/`), not npm package (`npm install @tailwind/roadcrew`)

**Rationale:**
- **Version Control:** Customers pin exact commit/tag, not SemVer range
- **Immutability:** `.roadcrew/` contents never change once checked out
- **Safety:** No surprise updates breaking customer code
- **Simplicity:** Git already required for SaaS projects
- **Cost:** Eliminates npm registry management

**Alternatives Considered:**
- ❌ npm package: Too coupled, forces customer updates, registry management overhead
- ❌ Monorepo merge: Complex, breaks customer independence
- ❌ Direct fork: No updates possible, quickly stale

**Consequences:**
- ✅ Customers have full control over update timing
- ✅ Clear version boundaries (can pin to specific releases)
- ⚠️ Git submodule UX is awkward (commands are confusing)
- ⚠️ Slightly larger clones (640 files = ~30s on first pull)

---

### Decision 2: Dual Publishing Approach (File Sync + GitHub API)

**Context:**
Publishing to customer-facing repo needs to work in multiple scenarios (manual releases, CI/CD automation, emergency fixes).

**Decision:**
Two parallel publishing methods: file sync (--push) + GitHub API (5-phase)

**Approach 1: File Sync (--push)**
- Direct copy from `dist/scripts/` → `roadcrew` repo
- Uses: `publish-dist.mjs --push`
- Best for: Manual releases, emergency fixes
- Characteristics: Fast, reliable, proven
- Used for: Production v1.6.0 release (640 files, 4.46MB)

**Approach 2: GitHub API (5-Phase Workflow)**
- Programmatic: create branch → batch updates → commit → PR → cleanup
- Uses: `scripts/core/publish-api.ts`
- Best for: CI/CD automation, team workflows
- Characteristics: Flexible, handles large distributions, rate-limit aware
- Can be integrated into GitHub Actions

**Rationale:**
- **Flexibility:** Different teams need different publishing approaches
- **Resilience:** If one fails, use the other (no single point of failure)
- **Safety:** Can test API approach before trusting it for production
- **Scalability:** API approach better for 1000+ file distributions
- **Validation:** Both approaches tested and working

**Alternatives Considered:**
- ❌ Single approach only: Too inflexible, risky if that approach breaks

**Consequences:**
- ✅ Both production and CI/CD needs covered
- ✅ Flexibility for different team setups
- ⚠️ Maintaining two approaches adds complexity (testing, documentation)
- ⚠️ Rate limit handling required for API approach

---

### Decision 3: {{VARIABLES}} in Templates (Not Hardcoding)

**Context:**
Templates need to be customer-safe with no internal values leaking.

**Decision:**
All templates use `{{VARIABLE_NAME}}` placeholders for customer-specific values

**Examples:**
```yaml
# ✅ CORRECT
repo: {{GITHUB_REPO_URL}}
project_name: {{PROJECT_NAME}}
tech_stack: {{TECH_STACK}}

# ❌ WRONG (hardcoded)
repo: https://github.com/acme-corp/app
project_name: acme-app
```

**Rationale:**
- **Customer Safety:** Hardcoded values never leak to customers
- **No Manual Editing:** Customers don't edit YAML/Markdown directly
- **Automation:** `/onboard` command can validate and replace all variables
- **Consistency:** Same pattern everywhere (no special cases)
- **Validation:** Can check all {{}} replaced before publishing

**How It Works:**
1. Customer runs `/onboard` command
2. Command asks for `PROJECT_NAME`, `GITHUB_REPO_URL`, `TECH_STACK`, etc.
3. Templates get filled with actual customer values
4. Customer commits completed config files

**Alternatives Considered:**
- ❌ Hardcoded values: Leaks internal details, unsafe
- ❌ Environment variables: Harder for customers to understand and configure

**Consequences:**
- ✅ Completely safe (no data leaks)
- ✅ Easy customer customization
- ⚠️ Requires tooling to validate and replace all variables
- ⚠️ Must update command when adding new templates

---

## Design Patterns In Use

### Pattern 1: 8-Stage Workflow

**Where used:**
- All feature development
- All release planning
- All command definitions

**Purpose:**
Define clear, measurable stages that AI and humans can understand and execute

**Implementation notes:**
```
ANALYSIS
  ↓ (Understand current state)
PLANNING
  ↓ (Define what to build)
RELEASE
  ↓ (Prepare version)
IMPLEMENTATION
  ↓ (Write code)
CODE ANALYSIS
  ↓ (Review quality)
TESTING
  ↓ (Verify correctness)
PUBLISHING
  ↓ (Ship to customers)
VALIDATION
  ↓ (Verify live)
```

**Why 8 stages (not 3 or 10)?**
- **3 stages:** Too vague (analyze/execute/done)
- **8 stages:** Matches natural SaaS workflow + quality gates
- **10+:** Too granular (micromanagement)

**Example:**
```
Command: /create-spec
  Operates in: PLANNING stage
  Reads: epics from context/epics/
  Produces: specs in context/specs/
  Updates: ai-context.yml with spec reference
  Output: Ready for IMPLEMENTATION stage
```

---

### Pattern 2: Composable Commands

**Where used:**
- All 40+ commands in commands/ folder
- Each operates across 8 workflow stages

**Purpose:**
Enable flexible workflows - users can chain commands or use subsets

**Implementation notes:**
- Commands DON'T assume previous commands ran
- Each command validates its inputs independently
- Can use `/onboard` standalone without `/analyze-repo`
- Can chain `/create-spec` → `/create-epic` → `/scope-release`

**Example:**
```
Standalone: /onboard works alone
Chained: /create-spec → /create-epic → /scope-release
Subset: /analyze-repo without /onboard
```

---

### Pattern 3: Template System ({{VARIABLES}})

**Where used:**
- All 8 template types (BRD, PRD, Spec, Release, Epic, Enhancement, etc.)
- Memory Bank templates (6 files)
- Cursor rules templates

**Purpose:**
Ensure templates are customer-safe and fully customizable

**Implementation notes:**
- Every customer-specific value is `{{VARIABLE}}`
- `/onboard` command replaces all variables
- Validation checks all `{{}}` are replaced
- Template location: `templates/roadcrew/` (published to customers)

**Example:**
```markdown
# {{PROJECT_NAME}} - Technical Specification

**GitHub Repository:** {{GITHUB_REPO_URL}}
**Tech Stack:** {{TECH_STACK}}
**Active Release:** {{ACTIVE_RELEASE}}
```

---

## Component Relationships

### Component A: Commands (roadcrew-internal/commands/)

**Depends on:**
- Templates (for command documentation)
- Scripts (for execution logic)
- Context files (specs, epics for input)

**Used by:**
- Customers (via Cursor chat)
- CI/CD workflows
- Internal testing

**Responsibilities:**
- Define workflow steps (8 stages)
- Guide users through processes
- Execute transformations (vision → specs → code)
- Update project state

**Key exports:**
- 40+ command files
- Each command has markdown documentation
- Each command references a corresponding script

---

### Component B: Scripts (roadcrew-internal/scripts/)

**Depends on:**
- Templates (for content generation)
- GitHub API (@octokit/rest)
- File system (fs module)
- YAML parser (js-yaml)

**Used by:**
- Commands (call scripts via spawn)
- GitHub Actions (CI/CD)
- Publishing workflows

**Responsibilities:**
- Implement command logic (TypeScript)
- Call GitHub API
- Read/write files
- Validate configurations
- Generate documentation

**Key exports:**
- `scripts/core/publish-api.ts` (GitHub API publishing)
- `scripts/core/template-validator.ts` (validate templates)
- `scripts/core/command-executor.ts` (run commands)

---

### Component C: Templates (templates/roadcrew/)

**Depends on:**
- Scripts (for variable replacement)
- Customers (for customization)

**Used by:**
- Commands (reference templates)
- Installation process (/onboard)
- Publishing workflow (distributed to customers)

**Responsibilities:**
- Define standard formats
- Provide placeholders ({{VARIABLES}})
- Enable customer customization
- Support multiple contexts (planning, execution, memory-bank)

**Key exports:**
- Planning templates (BRD, PRD, Spec)
- Execution templates (Release, Epic, Enhancement)
- Memory Bank templates (6 files)
- Cursor rules templates

---

### Component D: Publishing (internal → roadcrew repo → customers)

**Internal → Roadcrew (Publishing)**
- Source: roadcrew-internal/dist/ (640 files)
- Target: roadcrew/main (customer-facing repo)
- Method: File sync (--push) or GitHub API (5-phase)

**Roadcrew → Customers (Distribution)**
- Mechanism: Git submodule (`.roadcrew/`)
- Update method: `git submodule update --remote .roadcrew`
- Control: Customers decide when to update

---

## Critical Implementation Paths

### Path 1: Create Feature Spec

**Purpose:** Transform epic into technical specification

**Entry point:** `/create-spec` command in Cursor

**Steps:**

1. Customer describes feature in natural language
2. Command reads epics from `context/epics/`
3. Validates feature requirements
4. Generates skeleton in `context/specs/`
5. Fills in:
   - Overview
   - Acceptance criteria
   - Files to modify
   - Test plan
   - API changes (if any)
6. Customer customizes spec
7. Command updates `ai-context.yml` with spec reference
8. Ready for IMPLEMENTATION stage

**Exit conditions:** Spec complete, all sections filled, AI context updated

**Error handling:** 
- Missing epic → error with guidance
- Incomplete spec → validation hints
- Variable validation → check all {{}} replaced

---

### Path 2: Publishing Distribution

**Purpose:** Ship Roadcrew updates to customers

**Entry point:** `publish-dist.mjs --push` (manual) or GitHub Actions (automated)

**Steps:**

1. Build TypeScript: `npm run build` → dist/
2. Validate all files present
3. Choose approach:
   - **File Sync:** Direct copy dist/ → roadcrew repo
   - **GitHub API:** Create branch → batch updates (50 files) → commit → PR
4. Add rate limit delays (1s between batches)
5. Verify 640 files published (4.46MB)
6. Create release notes
7. Customers update: `git submodule update --remote .roadcrew`

**Exit conditions:** All files published, PR merged or sync complete

**Error handling:**
- Rate limit exceeded → delay and retry
- File missing → halt and report
- Network failure → retry with exponential backoff

---

### Path 3: Memory Bank Maintenance

**Purpose:** Keep living documentation current and accurate

**Entry point:** Monthly schedule (3rd of each month)

**Steps:**

1. Update `memory-bank/activeContext.md`:
   - Current work focus
   - Recent changes (last month)
   - Next steps
   - Active decisions
   - Learnings & gotchas
2. Update `memory-bank/progress.md`:
   - Completed work
   - In-progress items
   - Metrics & KPIs
   - Evolution of decisions
3. Update `memory-bank/techContext.md`:
   - Dependency version changes
   - Performance metrics
   - New tools/patterns
4. Validate all cross-references
5. Commit and push to dev

**Exit conditions:** All 6 files current, cross-references validated, committed

**Error handling:**
- Outdated information → flag for review
- Broken references → fix before commit
- Missing data → note as TBD

---

## Related Documents

- **Project Brief:** See `memory-bank/projectbrief.md` for scope and requirements
- **Product Context:** See `memory-bank/productContext.md` for problems and UX goals
- **Tech Context:** See `memory-bank/techContext.md` for technology stack
- **Active Context:** See `memory-bank/activeContext.md` for current work
- **Progress:** See `memory-bank/progress.md` for status and milestones

---

**Note:** This document captures HOW the system is built. Reference this when implementing features, debugging issues, or planning architecture changes.
