---
roadcrew_template_name: "analyze-repo.md"
roadcrew_template_type: "command"
roadcrew_template_version: "v1.0"
execution_mode: "auto-execute"
roadcrew_last_updated: "2025-10-25"
roadcrew_min_version: "1.5.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"
---

# Analyze Repository

Analyze the repository to detect project characteristics and create timestamped analysis report.

## What This Command Does

1. Scans project files for deployment method, schema, and CI/CD configuration
2. Detects versions of all technologies
3. Creates timestamped analysis report in `docs/reports/` with descriptive name (`repo-YYYY-MM-DD-HHMMSS.md`)
4. Updates `memory-bank/techContext.md` with latest detected configuration

## Usage

Run this command when:
- Initial setup of roadcrew
- After major infrastructure changes
- Before starting a new release
- When config files are out of sync
- Analyzing external repositories from a standalone roadcrew instance
- Comparing tech stacks across multiple organization repositories

## Parameters

### `--repo` (optional)

Specify an external repository path to analyze:

```bash
# Analyze current directory (default)
/analyze-repo

# Analyze external repository by absolute path
/analyze-repo --repo=/path/to/external/repo

# Analyze external repository by relative path
/analyze-repo --repo=../saas-starter-kit

# Analyze repository in home directory
/analyze-repo --repo=~/workspace/project
```

**Supported path types:**
- Absolute paths: `/Users/you/projects/my-app`
- Relative paths: `../my-other-project`, `./subfolder/project`
- Tilde expansion: `~/workspace/client-app`

**Path validation:**
- Path must exist
- Path must be a directory
- Path must be a git repository (contain `.git` folder)

### `--type` (optional)

Specify the repository type to provide context-aware analysis:

```bash
# Analyze a generator/template repository
/analyze-repo --type=generator

# Analyze an application generated from a template
/analyze-repo --type=generated

# Analyze a standard repository (default)
/analyze-repo --type=standard
/analyze-repo  # same as --type=standard
```

**Repository Types:**

- **`generator`** - Template/starter kit repositories (e.g., ai-saas-launch-kit)
  - Focus: Template structure, customization points, generator scripts
  - Analysis: Template variables, placeholder detection, generator configuration
  - Output: Generator-specific recommendations (template maintenance, version compatibility)

- **`generated`** - Applications created from generators (e.g., patriot-heavy)
  - Focus: Application-specific code, customizations from template
  - Analysis: Identifies parent generator, tracks divergence from template
  - Output: Application-specific recommendations (feature additions, custom code)

- **`standard`** - Regular repositories (default)
  - Focus: Standard tech stack analysis
  - Analysis: Standard deployment, schema, CI/CD detection
  - Output: General recommendations

**Combined Usage:**

```bash
# Analyze generator repository
/analyze-repo --repo=../ai-saas-launch-kit --type=generator

# Analyze generated application
/analyze-repo --repo=../patriot-heavy --type=generated

# Analyze with explicit standard type
/analyze-repo --repo=../custom-project --type=standard
```

## Process

### 1. Compile Detection Utilities

**⚠️ IMPORTANT: Always compile TypeScript utilities before use.**

Run the ensure-built helper to automatically compile if needed:
```bash
npm run ensure-built
```

Or manually compile with:
```bash
npm run build
```

This compiles TypeScript source files from `scripts/utils/*.ts` to JavaScript in `dist/scripts/utils/*.js`.

**What `ensure-built` does:**
- Checks if detection utilities are already compiled in `dist/`
- If missing: automatically runs `npm run build`
- If present: skips build (no wasted time)
- Shows clear success/error messages

**Why compile first?**
- Avoids network-dependent TypeScript runtimes (`npx tsx`, `ts-node`)
- Works in sandboxed/offline environments
- Ensures consistent execution across different environments
- `dist/` is gitignored (build artifacts, not source)

**If compilation fails:**
- Check that `node_modules` is installed: `npm install`
- Check TypeScript is installed: `npm list typescript`
- Review TypeScript errors in output

**If `dist/` doesn't exist:**
- Run `npm run ensure-built` (recommended) or `npm run build`
- Never import from `scripts/utils/*.ts` directly

### 2. Detect or Determine Repository Type

**A) Use explicit `--type` flag if provided:**
```javascript
const repoType = args.type || 'standard'; // 'generator', 'generated', or 'standard'
```

**B) Auto-detect repository type if not specified:**

Check for generator indicators:
```javascript
// Generator indicators
const generatorIndicators = [
  'template.json',
  'generator.config.js',
  '.template/',
  'scripts/generate.js',
  'TEMPLATE.md'
];

// Generated app indicators  
const generatedIndicators = [
  '.generator-info.json',
  'GENERATED_FROM.md',
  // Reference to parent template in package.json
  (pkg) => pkg.template?.source || pkg.generatedFrom
];

// Check for indicators
const hasGeneratorIndicators = generatorIndicators.some(file => 
  fs.existsSync(path.join(repoPath, file))
);

const hasGeneratedIndicators = generatedIndicators.some(indicator => {
  if (typeof indicator === 'string') {
    return fs.existsSync(path.join(repoPath, indicator));
  }
  // Function indicator
  const pkg = JSON.parse(fs.readFileSync(path.join(repoPath, 'package.json'), 'utf8'));
  return indicator(pkg);
});

// Determine type
let detectedType = 'standard';
if (hasGeneratorIndicators) detectedType = 'generator';
if (hasGeneratedIndicators) detectedType = 'generated';

// Use detected type if no explicit type provided
const repoType = args.type || detectedType;

console.log(`Repository Type: ${repoType}${args.type ? ' (explicit)' : ' (auto-detected)'}`);
```

### 3. Validate Instance Folder Structure (for 'generated' type)

**Check if this is an instance repository missing required folders:**

```bash
# Only check if repository type is 'generated' (an instance)
if [ "$REPO_TYPE" = "generated" ]; then
  echo ""
  echo "Checking instance folder structure..."
  
  MISSING_FOLDERS=()
  
  # Check for required folders
  if [ ! -d "context" ]; then
    MISSING_FOLDERS+=("context/")
  fi
  
  if [ ! -d "context/specs" ]; then
    MISSING_FOLDERS+=("memory-bank/requirements/specs/")
  fi
  
  if [ ! -d "milestones" ]; then
    MISSING_FOLDERS+=("memory-bank/releases/")
  fi
  
  # If any folders are missing, suggest initialization
  if [ ${#MISSING_FOLDERS[@]} -gt 0 ]; then
    echo ""
    echo "⚠️  WARNING: Missing required folders for instance repository:"
    for folder in "${MISSING_FOLDERS[@]}"; do
      echo "  - $folder"
    done
    echo ""
    echo "💡 Recommendation: Run the instance initialization script:"
    echo "   ./scripts/init-instance.sh"
    echo ""
    echo "This will:"
    echo "  ✅ Create missing folders"
    echo "  ✅ Copy templates for vision and release planning"
    echo "  ✅ Clean out roadcrew example content"
    echo "  ✅ Set up .gitkeep files"
    echo ""
    echo "Would you like to continue with analysis anyway? [Y/n]"
    read -p "> " CONTINUE
    
    if [ "$CONTINUE" = "n" ] || [ "$CONTINUE" = "N" ]; then
      echo "Exiting. Please run ./scripts/init-instance.sh first."
      exit 0
    fi
  else
    echo "✅ All required instance folders present"
  fi
fi
```

**Skip this validation for:**
- `generator` type (roadcrew platform itself)
- `standard` type (regular repos)

### 4. Import and Run Detection Utilities

Import the **compiled** detection scripts from `dist/`:
```javascript
// Import from project root (where code will be executed)
import { detectDeployment } from './dist/scripts/utils/detect-deployment.js';
import { detectSchema } from './dist/scripts/utils/detect-schema.js';
import { detectCICD } from './dist/scripts/utils/detect-cicd.js';

// Default behavior - analyze current directory
const repoPath = args.repo || process.cwd();
const deployment = detectDeployment(repoPath);
const schema = await detectSchema(repoPath);
const cicd = detectCICD(repoPath);

// Pass repository type to detection functions for context-aware analysis
const deployment = detectDeployment(repoPath, { type: repoType });
const schema = await detectSchema(repoPath, { type: repoType });
const cicd = detectCICD(repoPath, { type: repoType });
```

**Parameters:**
- `repoPath` (optional): Path to repository to analyze
  - Defaults to `process.cwd()` if not provided
  - Can be absolute path: `/Users/you/projects/my-app`
  - Can be relative path: `../my-other-project`
  - Can use tilde: `~/workspace/client-app`
  
- `options.type` (optional): Repository type context
  - `'generator'` - Template/starter kit analysis
  - `'generated'` - Generated application analysis
  - `'standard'` - Standard repository analysis (default)

### 5. Perform Type-Specific Analysis

Based on repository type, gather additional context:

**For Generator Repositories (`--type=generator`):**

```javascript
const generatorAnalysis = {
  templateStructure: {
    placeholders: findPlaceholders(repoPath), // e.g., {{PROJECT_NAME}}, {{AUTHOR}}
    configFiles: findTemplateConfigs(repoPath), // template.json, generator.config.js
    generatorScripts: findGeneratorScripts(repoPath) // scripts/generate.js, etc.
  },
  customizationPoints: {
    variableFiles: [], // Files with template variables
    configurableComponents: [], // Components designed for customization
    exampleContent: [] // Example/demo content to be replaced
  },
  generatorMetadata: {
    version: pkg.version,
    targetFrameworks: pkg.peerDependencies,
    generatorDependencies: pkg.dependencies
  }
};

console.log('Generator Analysis:');
console.log(`  Template Variables: ${generatorAnalysis.templateStructure.placeholders.length}`);
console.log(`  Customization Points: ${generatorAnalysis.customizationPoints.variableFiles.length} files`);
```

**For Generated Repositories (`--type=generated`):**

```javascript
const generatedAnalysis = {
  parentGenerator: {
    source: pkg.generatedFrom?.source || pkg.template?.source,
    version: pkg.generatedFrom?.version || pkg.template?.version,
    generatedDate: pkg.generatedFrom?.date
  },
  customizations: {
    modifiedFiles: await findModifiedFiles(repoPath), // Files diverged from template
    addedFiles: await findAddedFiles(repoPath), // Files not in template
    customFeatures: [] // Features added beyond template
  },
  templateCompliance: {
    upToDate: false, // Compare with latest generator version
    divergenceScore: 0, // % of template files modified
    suggestedUpdates: [] // Updates from generator
  }
};

console.log('Generated App Analysis:');
console.log(`  Parent Generator: ${generatedAnalysis.parentGenerator.source}@${generatedAnalysis.parentGenerator.version}`);
console.log(`  Custom Files: ${generatedAnalysis.customizations.addedFiles.length}`);
console.log(`  Modified Files: ${generatedAnalysis.customizations.modifiedFiles.length}`);
```

**For Standard Repositories (`--type=standard`):**

```javascript
// No additional type-specific analysis
// Proceed with standard tech stack detection
```

### 6. Detect Versions

For each detected technology, extract version information:

**From package.json:**
- Node.js version (from `engines.node`)
- npm/yarn version
- All dependencies with versions
- All devDependencies with versions

**From lock files:**
- Exact installed versions from package-lock.json or yarn.lock

**From config files:**
- Database version (from docker-compose.yml, Dockerfile, or connection strings)
- Runtime versions (Node, Python, etc.)

**From CI/CD:**
- Action versions from .github/workflows/*.yml
- Docker image versions

### 7. Display Detected Configuration

Show detected configuration in a clear format:

**Standard Output (all types):**
```
Detected Configuration:

Repository Type: {{repoType}} ({{explicit/auto-detected}})
Path: {{repoPath}}

Deployment:
  Method: github-actions (confidence: 0.95)
  Platform: GitHub Actions
  Evidence: .github/workflows/deploy.yml

Database:
  ORM: Prisma v5.8.0
  Database: PostgreSQL v16
  Models: 12 (User, Post, Comment, ...)
  Evidence: prisma/schema.prisma

CI/CD:
  Platform: GitHub Actions
  Workflows: 3 (tests.yml, lint.yml, deploy.yml)
  Test Frameworks: Jest v29.7.0, Playwright v1.40.0
  Linters: ESLint v8.56.0, Prettier v3.1.1

Runtime:
  Node.js: v20.10.0
  Package Manager: npm v10.2.3

Key Dependencies:
  - next: v14.0.4
  - react: v18.2.0
  - typescript: v5.3.3
```

**Additional Output for Generator Repositories:**
```
Generator-Specific Analysis:

Template Structure:
  Template Variables: 15 placeholders found
  Config Files: template.json, generator.config.js
  Generator Scripts: scripts/generate.js, scripts/customize.js

Customization Points:
  Variable Files: 23 files with {{placeholders}}
  Configurable Components: 8 components
  Example Content: 5 demo files to replace

Generator Metadata:
  Version: v2.1.0
  Target Framework: Next.js 14+
  Compatible Node: >=18.0.0
```

**Additional Output for Generated Repositories:**
```
Generated App Analysis:

Parent Generator:
  Source: ai-saas-launch-kit
  Version: v2.1.0
  Generated: 2025-10-15

Customizations:
  Added Files: 12 custom files
  Modified Files: 8 files diverged from template
  Custom Features: Authentication, Payments, Analytics

Template Compliance:
  Generator Version: v2.1.0 (current: v2.3.0 - updates available)
  Divergence: 15% of template files modified
  Suggested Updates: 3 security patches, 2 feature updates
```

### 8. Update Config Files

Automatically update the following files with type-specific sections:

**`memory-bank/techContext.md`:**
```markdown
# Technology Stack

> **Last Updated:** YYYY-MM-DD HH:MM:SS  
> **Repository Type:** {{repoType}}  
> **Analysis Report:** [repo-analysis/YYYY-MM-DD-HHMMSS.md](repo-analysis/YYYY-MM-DD-HHMMSS.md)

{{#if repoType === 'generator'}}
## Generator Information

- **Template Version:** {{generator.version}}
- **Template Variables:** {{generator.placeholders.length}}
- **Customization Points:** {{generator.customizationPoints.length}}
- **Target Frameworks:** {{generator.targetFrameworks}}
{{/if}}

{{#if repoType === 'generated'}}
## Generated Application

- **Parent Generator:** {{generated.source}}
- **Generator Version:** {{generated.version}}
- **Generated Date:** {{generated.date}}
- **Customizations:** {{generated.customizations.length}} custom files
- **Divergence:** {{generated.divergenceScore}}%
{{/if}}

## Runtime

- **Node.js:** v{{node.version}}
- **Package Manager:** {{packageManager}} v{{packageManager.version}}

## Framework & Libraries

{{#each dependencies}}
- **{{name}}:** v{{version}}
{{/each}}

## Database

- **ORM:** {{schema.orm}} v{{schema.version}}
- **Database:** {{schema.database}} v{{schema.dbVersion}}
- **Models:** {{schema.modelCount}}

## Deployment

- **Method:** {{deployment.method}}
- **Platform:** {{deployment.platform}}
- **Configuration:** {{deployment.configFile}}

## CI/CD

- **Platform:** {{cicd.platform}}
- **Workflows:** {{cicd.workflows.length}} workflows
  {{#each cicd.workflows}}
  - {{name}} ({{file}})
  {{/each}}

## Testing

{{#each testFrameworks}}
- **{{name}}:** v{{version}}
{{/each}}

## Code Quality

{{#each linters}}
- **{{name}}:** v{{version}}
{{/each}}

## Development Tools

{{#each devDependencies}}
- **{{name}}:** v{{version}}
{{/each}}
```

**`config/schema/schema.prisma`** (if Prisma detected):
Copy from `prisma/schema.prisma` to `config/schema/schema.prisma`

**`config/schema/CHANGELOG.md`** (if schema changed):
Add entry documenting the schema change

### 9. Save Analysis Report

Create timestamped file in `docs/reports/` with type-specific sections, using naming pattern `repo-YYYY-MM-DD-HHMMSS.md`:

**Filename:** `YYYY-MM-DD-HHMMSS.md` (e.g., `2025-10-07-143000.md`)

**Content:**
```markdown
# Repository Analysis - YYYY-MM-DD HH:MM:SS

## Summary

- **Repository:** [Repo URL from config/repo-url.md]
- **Repository Type:** {{repoType}} ({{explicit/auto-detected}})
- **Repository Path:** {{repoPath}}
- **Analysis Duration:** X.Xs
- **Technologies Detected:** X
- **Confidence:** High/Medium/Low

{{#if repoType === 'generator'}}
## Generator Analysis

### Template Structure
- **Template Variables:** {{generator.placeholders.length}} placeholders
- **Config Files:** {{generator.configFiles.join(', ')}}
- **Generator Scripts:** {{generator.scripts.join(', ')}}

### Customization Points
- **Variable Files:** {{generator.variableFiles.length}} files with placeholders
- **Configurable Components:** {{generator.components.length}}
- **Example Content:** {{generator.exampleContent.length}} demo files

### Generator Metadata
- **Version:** {{generator.version}}
- **Target Frameworks:** {{generator.targetFrameworks.join(', ')}}
- **Compatible Node:** {{generator.nodeVersion}}
{{/if}}

{{#if repoType === 'generated'}}
## Generated Application Analysis

### Parent Generator
- **Source:** {{generated.source}}
- **Version:** {{generated.version}}
- **Generated Date:** {{generated.date}}

### Customizations
- **Added Files:** {{generated.addedFiles.length}}
  {{#each generated.addedFiles}}
  - {{this}}
  {{/each}}
- **Modified Files:** {{generated.modifiedFiles.length}}
  {{#each generated.modifiedFiles}}
  - {{this}}
  {{/each}}
- **Custom Features:** {{generated.customFeatures.join(', ')}}

### Template Compliance
- **Generator Status:** {{generated.latestVersion}} (current: {{generated.version}})
- **Divergence Score:** {{generated.divergenceScore}}%
- **Update Recommendation:** {{generated.updateRecommendation}}
- **Suggested Updates:** {{generated.suggestedUpdates.length}}
  {{#each generated.suggestedUpdates}}
  - {{this}}
  {{/each}}
{{/if}}

## Runtime Environment

### Node.js
- **Version:** v{{node.version}}
- **Source:** package.json engines.node or .nvmrc
- **Package Manager:** {{packageManager}} v{{version}}

## Dependencies ({{dependencies.length}})

### Production Dependencies
{{#each dependencies}}
- **{{name}}:** v{{version}}
  - Purpose: {{purpose}}
  - Last Updated: {{lastUpdated}}
{{/each}}

### Development Dependencies ({{devDependencies.length}})
{{#each devDependencies}}
- **{{name}}:** v{{version}}
{{/each}}

## Database & Schema

- **ORM:** {{schema.orm}} v{{schema.version}}
- **Database:** {{schema.database}} v{{schema.dbVersion}}
- **Connection:** {{schema.connectionString}}
- **Models:** {{schema.modelCount}} ({{schema.models.join(', ')}})
- **Schema File:** {{schema.file}}

## Deployment

- **Method:** {{deployment.method}}
- **Platform:** {{deployment.platform}}
- **Configuration:** {{deployment.configFile}}
- **Environment:** {{deployment.environment}}
- **Confidence:** {{deployment.confidence}}

## CI/CD

- **Platform:** {{cicd.platform}}
- **Workflows:** {{cicd.workflows.length}}
  {{#each cicd.workflows}}
  - **{{name}}** ({{file}})
    - Triggers: {{triggers.join(', ')}}
    - Steps: {{steps.length}}
    - Actions Used: {{actions.join(', ')}}
  {{/each}}

## Testing

{{#each testFrameworks}}
- **{{name}}:** v{{version}}
  - Config: {{configFile}}
  - Coverage: {{coverage}}%
{{/each}}

## Code Quality

{{#each linters}}
- **{{name}}:** v{{version}}
  - Config: {{configFile}}
  - Rules: {{rulesCount}}
{{/each}}

## Files Analyzed

- package.json
- package-lock.json / yarn.lock
- prisma/schema.prisma
- .github/workflows/*.yml
- docker-compose.yml
- Dockerfile
- [Other relevant files]

## Changes Applied

- ✅ Updated memory-bank/techContext.md
- ✅ Created this analysis report
- [Other changes]

## Recommendations

{{#if repoType === 'generator'}}
### Generator-Specific Recommendations
- [Template variable consistency]
- [Generator script improvements]
- [Documentation for template users]
- [Version compatibility updates]
{{/if}}

{{#if repoType === 'generated'}}
### Generated App-Specific Recommendations
- [Updates from parent generator: {{generated.suggestedUpdates.length}} available]
- [Security patches from template]
- [Feature updates from template]
- [Custom code that conflicts with template updates]
{{/if}}

### General Recommendations
- [Any version upgrades needed]
- [Security vulnerabilities found]
- [Performance improvements]

## Notes

- [Any relevant observations]
- [Warnings or errors during detection]
```

### 10. Confirm Completion

Display type-specific completion summary:

**For Generator Repositories:**
```
✅ Generator analysis complete!

📊 Report: docs/reports/repo-YYYY-MM-DD-HHMMSS.md
📝 Tech Stack: memory-bank/techContext.md
🎨 Template: {{generator.placeholders.length}} variables in {{generator.variableFiles.length}} files

Detected X technologies with Y versions

Generator Insights:
  ✅ Template Variables: {{generator.placeholders.length}}
  ✅ Customization Points: {{generator.components.length}}
  ✅ Target Frameworks: {{generator.targetFrameworks}}
```

**For Generated Applications:**
```
✅ Generated app analysis complete!

📊 Report: docs/reports/repo-YYYY-MM-DD-HHMMSS.md
📝 Tech Stack: memory-bank/techContext.md
🔗 Parent: {{generated.source}}@{{generated.version}}

Detected X technologies with Y versions

Customization Summary:
  📝 Custom Files: {{generated.addedFiles.length}}
  ✏️  Modified Files: {{generated.modifiedFiles.length}}
  📊 Divergence: {{generated.divergenceScore}}%
  🔄 Updates Available: {{generated.suggestedUpdates.length}}
```

**For Standard Repositories:**
```
✅ Analysis complete!

📊 Report: docs/reports/repo-YYYY-MM-DD-HHMMSS.md
📝 Tech Stack: memory-bank/techContext.md

Detected X technologies with Y versions
```

## Error Handling

- If detection utilities fail, show error and continue with partial results
- If config files don't exist, create them with detected values
- If version detection fails for a package, mark as "version unknown"
- If repository URL not configured, prompt to update config/repo-url.md
- If `--type` is invalid, show error and list valid types: `generator`, `generated`, `standard`
- If generator indicators conflict with generated indicators, prioritize explicit `--type` flag
- If type-specific analysis fails, fall back to standard analysis with warning

## Example Workflows

### Scenario 1: Analyzing Generator Repository (ai-saas-launch-kit)

```bash
# From your roadcrew instance

# 1. Analyze the generator/template repository
/analyze-repo --repo=../ai-saas-launch-kit --type=generator

# 2. Review generator-specific findings
open docs/reports/$(ls -t docs/reports/ | head -1)

# 3. Check template structure and customization points
open memory-bank/techContext.md
```

**Use Case:** Maintaining template/starter kit repositories

**Benefits:**
- Track template variables and customization points
- Monitor generator script changes
- Document target framework compatibility
- Identify template maintenance needs

**Output Highlights:**
- Template variables detected across codebase
- Customization points for generated apps
- Generator metadata and compatibility info

### Scenario 2: Analyzing Generated Application (patriot-heavy)

```bash
# From your roadcrew instance

# 1. Analyze an application generated from ai-saas-launch-kit
/analyze-repo --repo=../patriot-heavy --type=generated

# 2. Review customizations and divergence from template
open docs/reports/$(ls -t docs/reports/ | head -1)

# 3. Check for available template updates
open memory-bank/techContext.md
```

**Use Case:** Managing applications created from generators

**Benefits:**
- Track customizations vs template code
- Identify divergence from parent generator
- Get update recommendations from newer template versions
- Monitor custom features added to app

**Output Highlights:**
- Parent generator (ai-saas-launch-kit) and version
- List of custom files added
- List of template files modified
- Divergence percentage
- Available updates from generator

### Scenario 3: Standalone Roadcrew Analyzing External Repository

```bash
# From your standalone roadcrew instance (e.g., fxonai-roadcrew)

# 1. Analyze your main codebase (auto-detect type)
/analyze-repo --repo=../saas-starter-kit

# 2. Review generated report
open docs/reports/$(ls -t docs/reports/ | head -1)

# 3. Check updated tech stack
open memory-bank/techContext.md
```