# Product Requirements Document: Roadcrew Submodule Isolation

> **Status:** Draft  
> **Version:** 1.0  
> **Date:** 2025-01-23  
> **Owner:** Roadcrew Product Team

---

## Problem Statement

### Current Issues

**Namespace Conflicts:**
- Roadcrew creates folders (`context/`, `config/`, `memory-bank/releases/`, `docs/`, `scripts/`, `templates/`) that collide with existing project structures
- Real-world impact: taxbuddy had to uninstall Roadcrew due to conflicts
- ai-launch-kit experienced "a mess" from overlapping folder structures

**Command Visibility:**
- Cursor IDE slash commands only work from root `.cursor/commands/`
- Commands in `.roadcrew/commands/` submodule are invisible to Cursor chat
- Forces all command code to live at project root, causing maintenance issues

**Update Conflicts:**
- No clear boundary between "Roadcrew files" vs "project files"
- `git submodule update` risks overwriting project customizations
- Difficult to distinguish upstream templates from local modifications

### Business Impact

- **Customer Churn:** Projects abandoning Roadcrew due to conflicts (taxbuddy)
- **Support Burden:** Confusion about which files to edit, update conflicts
- **Adoption Friction:** Teams hesitant to install due to namespace collision risk
- **Template Standardization:** Cannot enforce spec-driven standards when structure is unclear

---

## Solution Overview

### Core Concept

**Isolation Model:**
- `.roadcrew/` submodule = **Read-only upstream** (templates, scripts, documentation)
- Project root = **User workspace** (project-specific content, generated outputs)
- Commands bridge the gap (installed to root, reference submodule)

**Installation Flow:**
1. Add Roadcrew as git submodule: `git submodule add https://github.com/org/roadcrew .roadcrew`
2. Run install script: `npm run roadcrew:install` or `node .roadcrew/install.js`
3. Script copies commands from `.roadcrew/commands/` → `.cursor/commands/`
4. Commands reference `.roadcrew/templates/`, `.roadcrew/scripts/`
5. User creates their own `context/`, `memory-bank/releases/` folders at root

---

## Development Modes

### Mode 0: Roadcrew Template Repository

**Purpose:** The upstream source repository containing all Roadcrew templates, commands, scripts, and documentation. This is the repository that developers work on to build and maintain Roadcrew itself.

**Use Case:** 
- Core Roadcrew development
- Template maintenance and updates
- Command development and testing
- Self-hosting (dogfooding Roadcrew to manage Roadcrew)

**Structure:**
```
roadcrew/                              # Template repository (github.com/org/roadcrew)
├── .cursor/
│   └── commands/                      # Active commands for developing roadcrew
│
├── .github/
│   └── workflows/                     # CI/CD pipelines
│
├── .submodule/                        # What gets deployed in Mode 1
│   ├── commands/                      # ALL commands (free + gated premium)
│   │   ├── advance-release.md
│   │   ├── analyze-repo.md
│   │   ├── complete-release.md
│   │   ├── enrich-release.md          # FREE: manual, PREMIUM: --ai flag
│   │   ├── guide-release.md
│   │   ├── scope-release.md           # FREE: basic, PREMIUM: --toc flag
│   │   ├── sync-release-status.md
│   │   ├── validate-release.md
│   │   └── ... (all other commands)
│   │
│   ├── templates/                     # Document templates (all free tier)
│   │   ├── vision.template.md
│   │   ├── epic.template.md
│   │   ├── spec.template.md
│   │   ├── current-release.template.md
│   │   └── ... (all templates)
│   │
│   ├── scripts/                       # Utility scripts for commands
│   │   ├── utils/
│   │   │   ├── github.ts              # GitHub API helpers
│   │   │   ├── markdown-parser.ts
│   │   │   ├── license-validator.ts   # Premium feature gating
│   │   │   └── ... (other utils)
│   │   └── lib/
│   │
│   ├── ai-context.template.yml        # AI context template
│   ├── install.js                     # Installation script for Mode 1
│   ├── package.json                   # Dependencies (minimal for free tier)
│   └── README.md                      # Quick reference + links to online docs
│
├── config/                            # Configuration files
│   ├── reports/                       # Analysis reports (gitignored)
│   │   ├── exemplars/                 # Code example files
│   │   └── YYYY-MM-DD-HHMMSS.md      # Timestamped reports from /analyze-repo
│   ├── schema/                        # Database/data schemas
│   └── tech-stack.md                  # Auto-generated tech stack
│
├── docs/                              # Roadcrew documentation
│   ├── feedback/                      # Feedback documentation
│   └── tests/                         # Test documentation
│
├── memory-bank/releases/                        # Release planning (dogfooding)
│   ├── vision.md                  # Roadcrew's own vision
│   ├── tech-stack.md                  # Roadcrew's tech stack
│   ├── context/                       # Roadcrew's strategic docs
│   │   ├── brds/                      # Business requirements (e.g., monetization-strategy.md)
│   │   ├── prds/                      # Product requirements
│   │   └── specs/                     # Technical specifications
│   ├── current-release.md             # Current release planning
│   ├── future-releases.md             # Future roadmap
│   ├── minor-release.md               # Minor release tracking
│   └── past-releases.md               # Release history
│
├── scripts/                           # Build and utility scripts
│   └── utils/                         # Shared utilities
│
├── templates/                         # Template overrides/customizations
│
├── .cursorrules.md                    # Cursor IDE rules for development
├── .env.local                         # Local environment variables
├── .gitignore                         # Git ignore rules
├── ai-context.yml                     # AI context configuration
├── CHANGELOG.md                       # Version history
├── eslint.config.js                   # ESLint configuration
├── eslintrc.json                      # ESLint rules (legacy)
├── LICENSE                            # License file
├── package.json                       # Node.js dependencies
├── README.md                          # Project documentation
└── tsconfig.json                      # TypeScript configuration
```

**Key Characteristics:**
- **`.submodule/`** contains everything that gets deployed to Mode 1 instances
- **`memory-bank/releases/`** consolidates all planning docs (replaces separate `context/` folder)
- **`config/analysis/`** replaces scattered analysis outputs
- **Dogfooding:** Uses Roadcrew commands to manage its own development
- **Dual command sets:** `.cursor/commands/` for active development, `.submodule/commands/` for distribution

**Folder Purpose Clarification:**

| Folder | Purpose | Git Tracked | Deployed to Mode 1 |
|--------|---------|-------------|-------------------|
| `.cursor/commands/` | Active commands for Roadcrew dev | ✅ | ❌ |
| `.submodule/commands/` | Command source for distribution | ✅ | ✅ (copied) |
| `.submodule/templates/` | Template source for distribution | ✅ | ✅ (referenced) |
| `.submodule/scripts/` | Utility scripts used by commands | ✅ | ✅ (referenced) |
| `.submodule/README.md` | Quick reference + online doc links | ✅ | ✅ |
| `memory-bank/releases/` | Roadcrew's own planning | ✅ | ❌ (Mode 1 creates own) |
| `config/analysis/` | Analysis outputs | ❌ (gitignored) | ❌ |

**Premium Feature Gating Strategy:**

All commands ship in `.submodule/commands/` but premium features are gated via API key validation:

| Command | Free Tier | Premium Tier (Starter/Enterprise) |
|---------|-----------|-----------------------------------|
| `/enrich-release` | Manual copy/paste enrichment | `--ai` flag for AI-powered enrichment |
| `/scope-release` | Basic assignment rules | `--toc` flag for Theory of Constraints routing |
| `/analyze-repo` | Local analysis only | Multi-repo coordination (Enterprise) |
| `/release-flow` | ❌ Not available | ✅ One-command release automation |
| All others | ✅ Fully functional | ✅ Enhanced with agent automation |

**Upgrade Experience:**
```bash
# Free user tries premium feature
$ /enrich-release --ai

❌ Premium feature: ai-enrichment
   Requires: Starter tier ($49/mo)
   Try 14-day free trial: https://roadcrew.dev/trial
   Set ROADCREW_API_KEY to use this feature
```

**Key Design Decisions:**
1. **`.submodule/` folder** = Exact copy of what Mode 1 installations receive
2. **Consolidated `memory-bank/releases/`** = Combines context, planning, and vision in one place
3. **`config/analysis/`** = Single location for all generated analysis (replaces `.analysis/` and `config/repo-analysis/`)
4. **Dogfooding** = Roadcrew uses its own commands for self-management

**Installation Flow (for Mode 1 users):**
```bash
# User adds roadcrew as submodule
git submodule add https://github.com/org/roadcrew .roadcrew

# The .roadcrew/ folder contains the .submodule/ contents
# User runs install script
node .roadcrew/install.js
```

---

## Deployment Modes

Roadcrew supports two deployment architectures based on organizational structure:

### Mode 1: Submodule Mode (Monorepo / Single Project)

**Use Case:** Single repository with application code and Roadcrew together.

**Structure:**
```
my-saas-app/
├── .roadcrew/                       # Git submodule (contains .submodule/ contents)
│   ├── commands/                    # Command source files
│   ├── templates/                   # Document templates
│   ├── scripts/                     # Utility scripts
│   ├── ai-context.template.yml      # AI context template
│   ├── install.js                   # Installation script
│   ├── package.json                 # Dependencies
│   └── README.md                    # Quick reference + online doc links
│
├── .cursor/commands/                # Installed commands (copied from .roadcrew/commands/)
│   ├── advance-release.md
│   ├── enrich-release.md
│   ├── scope-release.md
│   └── ... (all commands)
│
├── context/                         # Project's vision/specs (user creates)
│   ├── vision.md
│   └── specs/
│
├── memory-bank/releases/                      # Project's releases (user creates)
│   ├── current-release.md
│   ├── future-releases.md
│   └── past-releases.md
│
├── config/                          # Generated configs
│   └── tech-stack.md
│
├── src/                             # Application code
└── package.json
```

**Characteristics:**
- **Roadcrew installed as git submodule** (`.roadcrew/` contains `.submodule/` contents from Mode 0)
- **Commands copied to `.cursor/commands/`** during installation (Cursor IDE requires root location)
- **Commands reference `.roadcrew/templates/` and `.roadcrew/scripts/`**
- **User creates own `context/` and `memory-bank/releases/`** at project root
- **Commands operate on local files** (`./context/`, `./memory-bank/releases/`)
- **GitHub issues created in same repo**
- **Single project focus** (free tier or Starter tier)
- **Premium features gated** via API key validation within commands

**Installation:**
```bash
# Add submodule
git submodule add https://github.com/org/roadcrew .roadcrew

# Run install script (copies commands, creates folders)
npm run roadcrew:install

# Or directly
node .roadcrew/install.js
```

**What install.js Does:**
1. Creates project folders: `context/`, `memory-bank/releases/`, `config/`
2. Copies commands: `.roadcrew/commands/` → `.cursor/commands/`
3. Updates `.gitignore` (adds `.analysis/`)
4. Creates starter files from templates
5. Displays next steps

**Updating Roadcrew:**
```bash
# Pull latest submodule, reinstall commands
npm run roadcrew:update

# Equivalent to:
git submodule update --remote .roadcrew
node .roadcrew/install.js
```

---

### Mode 2: Multi-Repo Orchestration (Microservices / Multi-Project Org)

**Use Case:** Organization with separate repos (frontend, backend, database) coordinated from central roadcrew repo.

**Structure:**
```
github.com/org/
├── roadcrew/                      # Central planning repo (fork/clone of Mode 0)
│   ├── .cursor/commands/         # Commands at root (NOT using .submodule/)
│   ├── .submodule/                # Exists but not used (part of template)
│   ├── memory-bank/releases/                # Org-wide planning (Mode 0 structure)
│   │   ├── vision.md         # Org-wide vision
│   │   ├── context/              # Org-wide strategic docs
│   │   │   ├── brds/
│   │   │   ├── prds/
│   │   │   └── specs/
│   │   ├── current-release.md    # Cross-service release coordination
│   │   ├── frontend-v2.md        # Frontend release plan
│   │   ├── backend-v3.md         # Backend release plan
│   │   └── database-v1.md        # Database release plan
│   ├── config/
│   │   ├── repos.yml             # Multi-repo configuration
│   │   └── tech-stack-*.md       # Per-repo tech stacks
│   ├── templates/                # Org-wide custom templates
│   └── scripts/                  # Utility scripts
│
├── frontend/                      # Service repo (no roadcrew)
│   └── src/
├── backend/                       # Service repo (no roadcrew)
│   └── src/
└── database/                      # Service repo (no roadcrew)
    └── migrations/
```

**Characteristics:**
- **Roadcrew as standalone repository** (fork or clone of Mode 0 template repo, NOT submodule)
- **Uses Mode 0 structure directly** (commands at `.cursor/commands/`, not via `.submodule/`)
- **Commands operate across multiple repos** via GitHub API
- **Release files map to target repositories** via `config/repos.yml`
- **Centralized planning, distributed execution**
- **Multi-project coordination**
- **Enterprise tier only** (gated by licensing)

**Configuration (config/repos.yml):**
```yaml
organization: myorg

# GitHub API settings
github:
  token_env: GH_TOKEN
  base_url: https://api.github.com

# Project mappings
projects:
  frontend:
    repo: myorg/frontend
    release_file: memory-bank/releases/frontend-v2.md
    tech_stack: config/tech-stack-frontend.md
    default_labels: [frontend, release]
    
  backend:
    repo: myorg/backend
    release_file: memory-bank/releases/backend-v3.md
    tech_stack: config/tech-stack-backend.md
    default_labels: [backend, release]
    
  database:
    repo: myorg/database
    release_file: memory-bank/releases/database-v1.md
    tech_stack: config/tech-stack-database.md
    default_labels: [database, release]
```

**Command Usage:**
```bash
# In roadcrew repo
/scope-release --project frontend
# → Reads memory-bank/releases/frontend-v2.md
# → Creates issues in github.com/myorg/frontend via API

/analyze-repo --project backend --repo-path ../backend
# → Analyzes ../backend codebase
# → Updates config/tech-stack-backend.md

/enrich-release --project database
# → Enriches memory-bank/releases/database-v1.md using database specs
```

**Command Behavior Differences:**

| Aspect | Submodule Mode | Multi-Repo Mode |
|--------|----------------|-----------------|
| File paths | Local (`./memory-bank/releases/current-release.md`) | Mapped (`config/repos.yml` lookup) |
| GitHub issues | Created in local repo | Created in remote repo via API |
| Tech stack | Single `memory-bank/techContext.md` | Multiple `config/tech-stack-*.md` |
| Project selection | Implicit (current repo) | Explicit (`--project <name>` flag) |
| API requirements | Optional (local git) | Required (cross-repo operations) |

**Detection Logic:**
```javascript
// Commands auto-detect mode
function getDeploymentMode() {
  const hasReposConfig = fs.existsSync('config/repos.yml');
  const isSubmodule = fs.existsSync('.roadcrew');
  
  if (hasReposConfig) return 'multi-repo';
  if (isSubmodule) return 'submodule';
  return 'standalone'; // Independent repo managing itself
}
```

---

## Technical Design

### Folder Structure (After)

```
user-project/
├── .roadcrew/                    # Git submodule (upstream, read-only)
│   ├── commands/                 # Command source code
│   │   ├── scope-release.js
│   │   ├── enrich-release.js
│   │   └── analyze-repo.js
│   ├── templates/                # Document templates
│   │   ├── vision.template.md
│   │   ├── epic.template.md
│   │   └── current-release.template.md
│   ├── scripts/                  # Utility scripts
│   │   └── lib/
│   ├── docs/                     # Roadcrew documentation
│   │   ├── commands.md
│   │   └── getting-started.md
│   ├── install.js                # Installation script
│   ├── package.json
│   └── README.md
│
├── .cursor/
│   └── commands/                 # Installed commands (git-tracked)
│       ├── scope-release.js      # Copied from .roadcrew/commands/
│       ├── enrich-release.js
│       └── analyze-repo.js
│
├── context/                      # User's project context
│   ├── vision.md            # User edits this
│   ├── prds/
│   └── specs/
│
├── memory-bank/releases/                   # User's release planning
│   ├── current-release.md       # User edits this
│   ├── future-releases.md
│   └── past-releases.md
│
├── config/                       # User's project config
│   └── tech-stack.md            # Generated by analyze-repo
│
├── .analysis/                    # Generated outputs (gitignored)
│   └── repo-analysis/
│
├── templates/                    # Optional: User overrides
│   └── custom-epic.md           # User's custom template
│
├── .ai-context.md               # User's project context
├── .cursorrules.md              # User's workflow rules
└── package.json
```

### Command Path Resolution

**Override Pattern:**
Commands check for user customizations first, fall back to Roadcrew defaults.

```javascript
// Example: scope-release.js command
function getTemplatePath(templateName) {
  const userTemplate = `./templates/${templateName}`;
  const roadcrewTemplate = `./.roadcrew/templates/${templateName}`;
  
  return fs.existsSync(userTemplate) 
    ? userTemplate 
    : roadcrewTemplate;
}

// Usage
const epicTemplate = getTemplatePath('epic.template.md');
const currentRelease = './memory-bank/releases/current-release.md'; // Always user's file
```

**Path Reference Rules:**
- **Templates:** `.roadcrew/templates/` (with override check)
- **Scripts/Utilities:** `.roadcrew/scripts/`
- **User Content:** `./context/`, `./memory-bank/releases/` (project root)
- **Generated Output:** `./.analysis/` (project root)

### Multi-Repo Command Implementation

**Enhanced Command Signature:**
```javascript
// All commands support optional --project flag
/scope-release --project frontend
/enrich-release --project backend
/analyze-repo --project database --repo-path ../database
```

**Project Resolution Logic:**
```javascript
// commands/lib/project-resolver.js
const yaml = require('js-yaml');
const fs = require('fs');

function resolveProject(projectFlag) {
  const mode = getDeploymentMode();
  
  if (mode === 'submodule') {
    // Submodule mode: ignore --project flag, use local files
    return {
      mode: 'submodule',
      releaseFile: './memory-bank/releases/current-release.md',
      contextPath: './context/',
      repo: null, // Local repo
      createIssuesLocally: true
    };
  }
  
  if (mode === 'multi-repo') {
    // Multi-repo mode: require --project flag
    if (!projectFlag) {
      throw new Error('Multi-repo mode requires --project flag. Example: /scope-release --project frontend');
    }
    
    const config = yaml.load(fs.readFileSync('config/repos.yml', 'utf-8'));
    const project = config.projects[projectFlag];
    
    if (!project) {
      throw new Error(`Project '${projectFlag}' not found in config/repos.yml`);
    }
    
    return {
      mode: 'multi-repo',
      projectName: projectFlag,
      releaseFile: project.release_file,
      contextPath: './context/', // Shared context
      repo: project.repo,
      techStack: project.tech_stack,
      defaultLabels: project.default_labels || [],
      createIssuesViaAPI: true
    };
  }
}
```

**GitHub API Integration:**
```javascript
// commands/lib/github-api.js
const { Octokit } = require('@octokit/rest');

async function createIssueInRepo(repo, issueData) {
  const token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN;
  
  if (!token) {
    throw new Error('GH_TOKEN required for multi-repo mode');
  }
  
  const octokit = new Octokit({ auth: token });
  const [owner, repoName] = repo.split('/');
  
  const response = await octokit.issues.create({
    owner,
    repo: repoName,
    title: issueData.title,
    body: issueData.body,
    labels: issueData.labels,
    assignees: issueData.assignees
  });
  
  return response.data;
}
```

**Example: scope-release command (multi-repo aware):**
```javascript
// commands/scope-release.js
async function scopeRelease(argv) {
  const project = resolveProject(argv.project);
  
  // Read release file (mapped by repos.yml if multi-repo)
  const releaseContent = fs.readFileSync(project.releaseFile, 'utf-8');
  const epics = parseRelease(releaseContent);
  
  for (const epic of epics) {
    for (const issue of epic.issues) {
      const issueData = {
        title: issue.title,
        body: formatIssueBody(issue),
        labels: [...project.defaultLabels, `epic-${epic.number}`],
        assignees: determineAssignees(issue.classification)
      };
      
      if (project.createIssuesViaAPI) {
        // Multi-repo: Create via API in remote repo
        const created = await createIssueInRepo(project.repo, issueData);
        console.log(`✓ Created #${created.number} in ${project.repo}`);
      } else {
        // Submodule: Create locally using gh CLI
        const created = await createLocalIssue(issueData);
        console.log(`✓ Created #${created.number}`);
      }
    }
  }
}
```

**analyze-repo for Multi-Repo:**
```javascript
// commands/analyze-repo.js
async function analyzeRepo(argv) {
  const project = resolveProject(argv.project);
  
  // Determine repo path
  const repoPath = argv.repoPath || '.'; // Allow --repo-path for external repos
  
  // Run analysis
  const analysis = await runRepoAnalysis(repoPath);
  
  // Save to project-specific tech-stack file
  const outputFile = project.techStack || 'memory-bank/techContext.md';
  fs.writeFileSync(outputFile, formatTechStack(analysis));
  
  console.log(`✓ Updated ${outputFile}`);
}
```

### Installation Script

**Script Location:** `.roadcrew/install.js`

**What it does:**
1. Creates required folders at root (if missing)
2. Copies commands from `.roadcrew/commands/` → `.cursor/commands/`
3. Adds `.analysis/` to `.gitignore`
4. Creates example `.ai-context.md` from template
5. Displays post-install instructions

**Example install.js:**
```javascript
#!/usr/bin/env node
const fs = require('fs-extra');
const path = require('path');

async function install() {
  console.log('📦 Installing Roadcrew...\n');
  
  // 1. Create project folders
  const folders = ['context', 'milestones', 'config', '.cursor/commands'];
  folders.forEach(folder => {
    fs.ensureDirSync(folder);
    console.log(`✓ Created ${folder}/`);
  });
  
  // 2. Copy commands
  const commandsSource = path.join(__dirname, 'commands');
  const commandsDest = '.cursor/commands';
  
  const commands = fs.readdirSync(commandsSource);
  commands.forEach(file => {
    fs.copyFileSync(
      path.join(commandsSource, file),
      path.join(commandsDest, file)
    );
    console.log(`✓ Installed command: /${file.replace('.js', '')}`);
  });
  
  // 3. Create .ai-context.md from template
  if (!fs.existsSync('.ai-context.md')) {
    fs.copyFileSync(
      path.join(__dirname, 'templates/ai-context.template.md'),
      '.ai-context.md'
    );
    console.log('✓ Created .ai-context.md');
  }
  
  // 4. Update .gitignore
  const gitignore = fs.existsSync('.gitignore') 
    ? fs.readFileSync('.gitignore', 'utf-8') 
    : '';
  
  if (!gitignore.includes('.analysis/')) {
    fs.appendFileSync('.gitignore', '\n# Roadcrew outputs\n.analysis/\n');
    console.log('✓ Updated .gitignore');
  }
  
  console.log('\n✅ Roadcrew installed successfully!\n');
  console.log('Next steps:');
  console.log('1. Edit memory-bank/activeContext.md (legacy: context/vision.md) (your product vision)');
  console.log('2. Run /analyze-repo in Cursor chat');
  console.log('3. Run /guide-release to start first release\n');
}

install().catch(console.error);
```

**NPM Script (in user's package.json):**
```json
{
  "scripts": {
    "roadcrew:install": "node .roadcrew/install.js",
    "roadcrew:update": "git submodule update --remote && npm run roadcrew:install"
  }
}
```

---

## User Experience

### First-Time Setup

**1. Add Roadcrew submodule:**
```bash
git submodule add https://github.com/org/roadcrew .roadcrew
```

**2. Install commands:**
```bash
npm run roadcrew:install
```

**Output:**
```
📦 Installing Roadcrew...

✓ Created context/
✓ Created memory-bank/releases/
✓ Created config/
✓ Created .cursor/commands/
✓ Installed command: /scope-release
✓ Installed command: /enrich-release
✓ Installed command: /analyze-repo
✓ Installed command: /guide-release
✓ Created .ai-context.md
✓ Updated .gitignore

✅ Roadcrew installed successfully!

Next steps:
1. Edit memory-bank/activeContext.md (legacy: context/vision.md) (your product vision)
2. Run /analyze-repo in Cursor chat
3. Run /guide-release to start first release
```

**3. User workflow:**
```bash
# In Cursor chat
/analyze-repo
/guide-release
/advance-release
/scope-release --current
```

### Updating Roadcrew

**Update to latest version:**
```bash
npm run roadcrew:update
```

**What happens:**
1. `git submodule update --remote` pulls latest `.roadcrew/`
2. Reinstalls commands (overwrites `.cursor/commands/`)
3. User's `context/`, `memory-bank/releases/` untouched
4. Templates updated (user overrides in `./templates/` preserved)

---

## Migration Path

### For Existing Projects (taxbuddy, ai-launch-kit)

**Current state:**
- Roadcrew files mixed with project files
- Conflicts with existing folder structures
- Uninstalled or "messy" integration

**Migration steps:**

1. **Remove old Roadcrew installation:**
```bash
# Backup user-created content
cp -r context context-backup
cp -r milestones milestones-backup
rm -rf .roadcrew  # If exists
```

2. **Install as submodule:**
```bash
git submodule add https://github.com/org/roadcrew .roadcrew
npm run roadcrew:install
```

3. **Restore user content:**
```bash
# Merge backups with new structure
cp -r context-backup/* context/
cp -r milestones-backup/* memory-bank/releases/
```

4. **Test commands:**
```bash
# In Cursor chat
/analyze-repo
```

**Breaking changes:**
- Command paths change (scripts now reference `.roadcrew/`)
- Folder structure reorganized (namespace isolation)
- Installation required (can't just git clone)

### For New Projects

**Clean installation:**
```bash
git init my-project
cd my-project
git submodule add https://github.com/org/roadcrew .roadcrew
npm init -y
npm run roadcrew:install
```

**Zero conflicts** - user starts with empty root, Roadcrew isolated.

---

## Future Extensibility

### Premium Features Architecture

**Architecture supports premium extensions:**

```
.cursor/commands/
├── scope-release.js              # Free (local execution)
├── scope-release-cloud.js        # Premium (API-backed)
├── analyze-multi-repo.js         # Premium (consulting)
└── ai-enrich-advanced.js         # Premium (enhanced AI)
```

**Premium command example:**
```javascript
// scope-release-cloud.js
async function scopeReleaseCloud() {
  const apiKey = await getApiKey(); // From config
  const response = await fetch('https://api.roadcrew.dev/scope-release', {
    headers: { 'Authorization': `Bearer ${apiKey}` }
  });
  // Premium features: multi-repo, analytics, team sync
}
```

**Enables:**
- Freemium model (core free, premium features paid)
- Consulting packages (custom commands installed same way)
- Future SaaS offerings (hosted automation, team features)

---

### AI Agent Execution Architecture

**Use Case:** AI agents autonomously execute Roadcrew commands without human intervention.

**Example Workflow:**
```
1. Human: Updates memory-bank/activeContext.md (legacy: context/vision.md)
2. AI Agent: Detects change, runs /advance-release
3. AI Agent: Runs /enrich-release (consumes tokens)
4. AI Agent: Runs /validate-release
5. AI Agent: Notifies human for /scope-release approval
6. Human: Approves
7. AI Agent: Runs /scope-release, creates GitHub issues
```

**Technical Requirements:**

**1. Agent Configuration:**
```yaml
# config/agent-config.yml (premium feature)
ai_agent:
  enabled: true                           # Premium tier only
  provider: anthropic                     # anthropic | openai
  model: claude-sonnet-4.5
  
  # Token tracking
  max_tokens_per_month: 100000
  token_warning_threshold: 0.8            # Alert at 80%
  cost_center: "product-team"
  
  # Automation rules
  auto_commands:
    - advance-release                     # Fully automated
    - enrich-release                      # Fully automated
    - validate-release                    # Fully automated
  
  approval_required:
    - scope-release                       # Human approval needed
    - complete-release                    # Human approval needed
  
  # Execution limits
  max_retries: 3
  timeout_seconds: 300
  rate_limit_per_hour: 10
```

**2. Token Usage Tracking:**
```javascript
// commands/lib/token-tracker.js
class TokenTracker {
  async trackUsage(commandName, metadata) {
    const usage = {
      timestamp: new Date().toISOString(),
      command: commandName,
      project: metadata.project,
      model: metadata.model,
      input_tokens: metadata.input_tokens,
      output_tokens: metadata.output_tokens,
      total_tokens: metadata.input_tokens + metadata.output_tokens,
      estimated_cost: calculateCost(metadata),
      user: metadata.user || 'ai-agent'
    };
    
    // Write to usage log
    await this.appendToLog('.analysis/token-usage.jsonl', usage);
    
    // Check quota
    const monthlyUsage = await this.getMonthlyUsage();
    if (monthlyUsage.total_tokens > config.max_tokens_per_month) {
      throw new Error('Monthly token quota exceeded');
    }
    
    return usage;
  }
  
  async getMonthlyUsage() {
    // Aggregate usage from .analysis/token-usage.jsonl
    const logs = await this.readUsageLog();
    const thisMonth = logs.filter(isCurrentMonth);
    
    return {
      total_tokens: sum(thisMonth.map(l => l.total_tokens)),
      total_cost: sum(thisMonth.map(l => l.estimated_cost)),
      by_command: groupBy(thisMonth, 'command'),
      by_project: groupBy(thisMonth, 'project')
    };
  }
}
```

**3. Command Instrumentation:**
```javascript
// Example: enrich-release.js with token tracking
async function enrichRelease(argv) {
  const tracker = new TokenTracker();
  const startTokens = getTokenCount(); // From AI provider API
  
  try {
    // Execute command logic
    const result = await enrichReleaseLogic(argv);
    
    // Track token usage
    const endTokens = getTokenCount();
    await tracker.trackUsage('enrich-release', {
      project: argv.project,
      model: 'claude-sonnet-4.5',
      input_tokens: result.prompt_tokens,
      output_tokens: result.completion_tokens,
      user: argv.agent ? 'ai-agent' : process.env.USER
    });
    
    return result;
  } catch (error) {
    // Log error but still track tokens consumed
    await tracker.trackUsage('enrich-release', {
      project: argv.project,
      error: error.message,
      partial_tokens: endTokens - startTokens
    });
    throw error;
  }
}
```

**4. Usage Monitoring Dashboard:**
```bash
# New command: /usage-report
/usage-report --month 2025-01

# Output:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 TOKEN USAGE REPORT - January 2025
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Total Usage:
  Tokens: 87,450 / 100,000 (87.5%)
  Cost: $4.37 / $5.00
  Status: ⚠️  Warning (approaching limit)

By Command:
  enrich-release:   45,230 tokens ($2.26)
  scope-release:    12,100 tokens ($0.61)
  analyze-repo:     8,520 tokens ($0.43)

By Project:
  frontend:         32,100 tokens ($1.61)
  backend:          28,900 tokens ($1.45)
  database:         26,450 tokens ($1.32)

By User:
  ai-agent:         65,340 tokens ($3.27)  74.7%
  john@org.com:     22,110 tokens ($1.11)  25.3%
```

**5. Cost Calculation:**
```javascript
// Token cost estimation (as of 2025)
const TOKEN_COSTS = {
  'claude-sonnet-4.5': {
    input: 0.000003,   // $3 per 1M tokens
    output: 0.000015   // $15 per 1M tokens
  },
  'gpt-4-turbo': {
    input: 0.00001,
    output: 0.00003
  }
};

function calculateCost(metadata) {
  const model = TOKEN_COSTS[metadata.model];
  if (!model) return 0;
  
  return (
    (metadata.input_tokens * model.input) +
    (metadata.output_tokens * model.output)
  );
}
```

**6. Quota Enforcement:**
```javascript
// Pre-flight check before expensive operations
async function checkQuota(commandName) {
  const usage = await tracker.getMonthlyUsage();
  const config = loadAgentConfig();
  
  const percentUsed = usage.total_tokens / config.max_tokens_per_month;
  
  if (percentUsed >= 1.0) {
    throw new Error(
      `Monthly quota exceeded (${usage.total_tokens}/${config.max_tokens_per_month} tokens). ` +
      `Upgrade plan or wait until next month.`
    );
  }
  
  if (percentUsed >= config.token_warning_threshold) {
    console.warn(
      `⚠️  ${Math.round(percentUsed * 100)}% of monthly quota used ` +
      `(${usage.total_tokens}/${config.max_tokens_per_month} tokens)`
    );
  }
}
```

**7. Agent Execution Log:**
```jsonl
// .analysis/agent-execution.jsonl
{"timestamp":"2025-01-23T10:30:00Z","command":"enrich-release","project":"frontend","status":"success","duration_ms":45230,"tokens":12400}
{"timestamp":"2025-01-23T10:35:00Z","command":"validate-release","project":"frontend","status":"success","duration_ms":2100,"tokens":450}
{"timestamp":"2025-01-23T10:36:00Z","command":"scope-release","project":"frontend","status":"pending_approval","tokens":0}
```

**Free vs Premium Tiers:**

| Feature | Free | Premium |
|---------|------|---------|
| Manual command execution | ✅ | ✅ |
| Premium command execution | ❌ | ✅ |
| AI agent automation | ❌ | ✅ |
| Token usage tracking | ❌ | ✅ |
| Usage reports/dashboard | ❌ | ✅ |
| Token quota | N/A | Configurable |
| Cost attribution | ❌ | ✅ (by project/user) |
| Rate limiting | N/A | ✅ |
| Usage alerts | ❌ | ✅ |

### Starter Tier Premium Features (Workflow Automation + TOC)

**Feature Gating via License Validation:**

Starter tier adds premium flags to existing commands, gated by API key validation:

**Gated Commands:**
1. **`/release-flow`** - NEW: One-command release orchestration
   - Chains: advance → validate → scope automatically
   - Saves 30-60 minutes per release
   - Requires valid API key

2. **`/enrich-release --ai`** - Existing command, premium flag
   - Free mode: Manual enrichment (copy/paste from specs)
   - Premium mode: AI reads specs, generates issue details
   - Requires valid API key for `--ai` flag

3. **`/scope-release --toc`** - Existing command, premium flag
   - Free mode: Manual assignment or basic rules
   - Premium mode: AI classification (1-10) + TOC routing
   - Requires valid API key for `--toc` flag

4. **`/watch-milestone`** - NEW: Progress tracking
   - Monitors GitHub issue completion
   - Updates milestone files
   - Sends notifications (Slack, email)
   - Requires valid API key

**License Validation Implementation:**
```javascript
// commands/lib/license-validator.js
const fetch = require('node-fetch');

async function hasValidLicense(featureName) {
  const apiKey = process.env.ROADCREW_API_KEY;
  
  if (!apiKey) {
    return false;
  }
  
  try {
    const response = await fetch('https://api.roadcrew.dev/validate', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        feature: featureName,
        version: require('../../package.json').version
      })
    });
    
    if (!response.ok) {
      return false;
    }
    
    const data = await response.json();
    return data.valid && data.tier !== 'free';
    
  } catch (error) {
    console.error('License validation failed:', error.message);
    return false;
  }
}

function requireLicense(featureName, tierRequired = 'starter') {
  const isValid = await hasValidLicense(featureName);
  
  if (!isValid) {
    console.error(`\n❌ Premium feature: ${featureName}`);
    console.error(`   Requires: ${tierRequired} tier ($49/mo)`);
    console.error(`   Visit: https://roadcrew.dev/pricing`);
    console.error(`   Set ROADCREW_API_KEY to use this feature\n`);
    process.exit(1);
  }
}

module.exports = { hasValidLicense, requireLicense };
```

**Usage in Commands:**
```javascript
// commands/enrich-release.js
const { requireLicense } = require('./lib/license-validator');

async function enrichRelease(argv) {
  // Check if using premium flag
  if (argv.ai) {
    await requireLicense('ai-enrichment', 'starter');
  }
  
  // Rest of existing logic...
  if (argv.ai) {
    // Call API for AI-powered enrichment
    const enriched = await fetch('https://api.roadcrew.dev/enrich', {
      headers: { 'Authorization': `Bearer ${process.env.ROADCREW_API_KEY}` },
      body: JSON.stringify({ specs, issues })
    });
  } else {
    // Free tier: manual enrichment
    console.log('Manual enrichment mode. Use --ai for AI-powered enrichment.');
  }
}
```
```javascript
// commands/scope-release.js
const { requireLicense } = require('./lib/license-validator');

async function scopeRelease(argv) {
  // Check if using TOC flag
  if (argv.toc) {
    await requireLicense('toc-assignment', 'starter');
    
    // Call API for AI classification and TOC routing
    const classified = await fetch('https://api.roadcrew.dev/classify', {
      headers: { 'Authorization': `Bearer ${process.env.ROADCREW_API_KEY}` },
      body: JSON.stringify({ issues, assignmentRules })
    });
  } else {
    // Free tier: basic assignment
    console.log('Basic assignment mode. Use --toc for Theory of Constraints optimization.');
  }
}
```

**Free vs Premium Behavior:**

| Command | Free (No API Key) | Premium (Valid API Key) |
|---------|-------------------|-------------------------|
| `/enrich-release` | Manual copy/paste | `/enrich-release --ai` (AI-powered) |
| `/scope-release` | Basic assignment | `/scope-release --toc` (TOC routing) |
| `/release-flow` | Not available | Full automation |
| `/watch-milestone` | Not available | Progress tracking |

**Conversion Triggers:**
- After 3 manual releases: "Try `/release-flow` - 14-day free trial"
- After manual assignment: "Use `--toc` flag for intelligent routing"
- On `--ai` or `--toc` without key: Upgrade prompt with trial link

**Implementation Requirements:**
- [ ] Token tracking infrastructure (.analysis/token-usage.jsonl)
- [ ] Agent configuration schema (config/agent-config.yml)
- [ ] Quota enforcement in all AI-powered commands
- [ ] Usage reporting command (/usage-report)
- [ ] Cost calculation utilities (per provider/model)
- [ ] Alert system for quota thresholds
- [ ] API endpoint for usage data (premium SaaS feature)

**Security Considerations:**
- Token usage logs contain no sensitive data (PII, credentials)
- Agent config validated on load (schema enforcement)
- Quota checks prevent runaway costs
- Rate limiting prevents abuse
- Audit trail for all agent executions

---

## Success Criteria

### Must Have (MVP)

**Submodule Mode:**
- [ ] Zero namespace conflicts with host projects
- [ ] Commands work via Cursor slash commands (`/scope-release`)
- [ ] `git submodule update` pulls latest without breaking user content
- [ ] Install script completes in <10 seconds
- [ ] Documentation updated (getting-started.md, commands.md)
- [ ] Migration guide for existing users (taxbuddy, ai-launch-kit)

**Multi-Repo Mode:**
- [ ] `config/repos.yml` schema defined and documented
- [ ] Commands support `--project` flag
- [ ] GitHub API integration for cross-repo issue creation
- [ ] Per-project tech-stack files (`config/tech-stack-*.md`)
- [ ] Org-level `GH_TOKEN` required and validated
- [ ] Error handling for missing projects in config

### Quality Metrics

**Submodule Mode:**
- [ ] Install success rate: 95%+ (no manual intervention)
- [ ] Update success rate: 95%+ (no conflicts, no data loss)
- [ ] Command resolution time: <100ms (path lookups fast)
- [ ] User content preserved: 100% (no overwrites on update)

**Multi-Repo Mode:**
- [ ] Command detection: 100% accurate (submodule vs multi-repo)
- [ ] API issue creation: <2 seconds per issue
- [ ] Cross-repo validation: 95%+ (correct repo targeting)
- [ ] Config validation: Clear errors for malformed repos.yml

### User Validation

**Submodule Mode:**
- [ ] taxbuddy successfully migrates and reinstalls
- [ ] ai-launch-kit resolves folder conflicts
- [ ] 3 new projects install cleanly without issues
- [ ] User feedback: "Installation was smooth" (qualitative)

**Multi-Repo Mode:**
- [ ] Test with 3-repo org (frontend, backend, database)
- [ ] Validate issue creation in correct repos
- [ ] Verify release coordination across services
- [ ] User feedback: "Multi-repo setup was clear"

---

## Technical Requirements

### Command Implementation

**All commands must:**
1. Reference `.roadcrew/templates/` with override pattern
2. Read user content from project root (`./context/`, `./memory-bank/releases/`)
3. Write outputs to project root (`.analysis/`, `config/`)
4. Handle missing `.roadcrew/` gracefully (error message)

**Example error handling:**
```javascript
if (!fs.existsSync('.roadcrew')) {
  console.error('❌ Roadcrew not installed. Run: npm run roadcrew:install');
  process.exit(1);
}
```

### Installation Script Requirements

**Must:**
- Create folders only if missing (don't overwrite)
- Copy commands (overwrite on update)
- Update .gitignore safely (check before appending)
- Exit with clear error if prerequisites missing (git, npm)

**Must NOT:**
- Overwrite user's `.ai-context.md` if exists
- Delete user content in `context/`, `memory-bank/releases/`
- Modify files outside documented scope

---

## Dependencies

### Prerequisites

- Git (submodule support)
- Node.js >= 16 (for install script)
- Cursor IDE (for slash commands)

### Roadcrew Internal

- Update all command paths to reference `.roadcrew/`
- Create install.js script
- Update documentation (README.md, docs/getting-started.md)
- Create migration guide (docs/migration.md)

---

## Risks & Mitigations

| Risk | Impact | Mitigation |
|------|--------|------------|
| Users edit `.roadcrew/` files directly | High - conflicts on update | Clear docs: "Never edit .roadcrew/", use overrides |
| Install script fails mid-execution | Medium - partial install | Idempotent script (safe to re-run) |
| Command path resolution breaks | High - commands unusable | Comprehensive tests, fallback paths |
| Existing users lose content during migration | Critical - data loss | Migration guide with backup steps |
| Premium commands conflict with free | Medium - user confusion | Namespace premium commands clearly |
| **Multi-repo: Wrong repo targeted** | **High - issues in wrong project** | **Validation: confirm repo before creating issues** |
| **Multi-repo: GH_TOKEN lacks permissions** | **High - API failures** | **Pre-flight token validation, clear error messages** |
| **Multi-repo: repos.yml misconfigured** | **Medium - commands fail** | **Schema validation on command start** |
| **Multi-repo: Rate limit exceeded** | **Medium - partial issue creation** | **Batch with delays, resume from checkpoint** |

---

## Open Questions

1. **Submodule vs npm package?** (Decision: Submodule for now, npm later if needed)
2. **Auto-install on git clone?** (Decision: Manual install, prevents surprise changes)
3. **Version pinning?** (Decision: User controls via `git submodule update --remote`)
4. **Windows compatibility?** (Decision: Test install.js on Windows, use cross-platform fs-extra)

---

## Timeline

**Phase 1: Core Implementation (Week 1)**
- Create install.js script
- Update all commands to reference `.roadcrew/`
- Test on clean project

**Phase 2: Migration & Testing (Week 2)**
- Write migration guide
- Test with taxbuddy, ai-launch-kit
- Fix edge cases

**Phase 3: Documentation & Launch (Week 3)**
- Update README.md, getting-started.md
- Create video walkthrough
- Announce to existing users

---

## Related Documents

- Technical Spec: TBD (implementation details)
- Migration Guide: `docs/migration.md` (to be created)
- Getting Started: `.roadcrew/docs/getting-started.md` (to be updated)
- Commands Reference: `.roadcrew/docs/commands.md` (to be updated)