# CLI Auto Context Detection

The MORPH-SPEC CLI now includes intelligent auto-detection that analyzes your project and automatically generates accurate configuration files.

## Features

- **🤖 LLM-Powered Analysis**: Uses Claude Code's embedded LLM to analyze your project
- **📊 Multi-Stack Support**: Detects Next.js, Blazor, .NET APIs, monorepos, and more
- **🔒 Privacy-First**: All data stays local (no external API calls)
- **🎯 90%+ Accuracy**: Few-shot learning with real project examples
- **🛡️ Secret Sanitization**: Automatically redacts API keys, passwords, and sensitive data
- **🧙 Fallback Wizard**: Manual 7-question wizard if auto-detection fails

## Usage

### New Projects

```bash
# Initialize MORPH with auto-detection
morph-spec init

# Skip auto-detection (manual config later)
morph-spec init --skip-detection

# Force wizard mode (skip LLM)
morph-spec init --wizard
```

### Existing Projects

```bash
# Re-analyze and update configs
morph-spec update

# Skip auto-detection during update
morph-spec update --skip-detection

# Force wizard mode
morph-spec update --wizard
```

## How It Works

### 1. Project Scanning

Scans your project for:
- `package.json` (dependencies, scripts)
- `.csproj` and `.sln` files
- `README.md` and `CLAUDE.md`
- Directory structure (src/, frontend/, backend/, etc.)
- Infrastructure files (Dockerfile, *.bicep, CI/CD pipelines)
- Git remote URL

### 2. Context Sanitization

Removes sensitive data before LLM analysis:
- **Whitelisted files**: Only reads safe files (package.json, README, etc.)
- **Blacklisted directories**: Never scans node_modules/, .git/, bin/, obj/
- **Secret redaction**: Removes API keys, passwords, connection strings
- **File truncation**: Limits README/CLAUDE.md to first 500 chars

### 3. LLM Analysis

Uses Claude Code's LLM with few-shot learning:
- 3 example projects (Next.js, Blazor, Monorepo)
- Structured JSON output
- Schema validation with Ajv
- Confidence scoring (0-100%)

### 4. User Review

Interactive preview with options:
- ✅ **Approve** - Save configs as-is
- ✏️ **Edit** - Open in $EDITOR before saving
- ❌ **Cancel** - Abort without changes

Shows diff if updating existing configs.

### 5. Fallback to Wizard

If LLM fails (no Claude Code, timeout, invalid response):
- Automatically launches 7-question interactive wizard
- Asks: name, description, type, frontend, backend, database, infrastructure
- Generates valid config from manual input

## Requirements

- **Claude Code CLI**: Auto-detection requires Claude Code environment
- **Node.js 18+**: For running the CLI
- **Git (optional)**: For remote URL detection

## Configuration Files Generated

### `.morph/project.md`

Human-readable project overview:
- Stack summary table
- Architecture pattern
- Code conventions
- Infrastructure (Azure, Docker, CI/CD)
- LLM confidence score
- Warnings (if any)

### `.morph/config/config.json`

Machine-readable config for agents:
- Project name, type, description
- Stack (frontend, backend, database, hosting)
- Architecture pattern
- Infrastructure flags
- Generated metadata (timestamp, confidence)

## Supported Project Types

| Type | Detection Criteria | Example |
|------|-------------------|---------|
| `nextjs` | package.json has `next` dependency | Next.js app |
| `blazor-server` | .csproj with Blazor.Server | Blazor Server app |
| `dotnet-api` | .csproj without Blazor | .NET Web API |
| `cli-tool` | package.json with `bin` field | CLI tool |
| `monorepo` | frontend/ and backend/ directories | Full-stack monorepo |
| `other` | Fallback for unknown projects | Custom setups |

## Troubleshooting

### "Claude Code environment not detected"

Auto-detection requires Claude Code CLI. Options:
1. Run `morph-spec init --wizard` for manual configuration
2. Install Claude Code and retry
3. Use `--skip-detection` to configure later

### "LLM analysis timeout"

Default timeout is 60 seconds for interactive use. If analysis takes too long:
1. Reduce project size (clean node_modules, dist)
2. Use `--wizard` for manual configuration
3. Check Claude Code performance

### "Schema validation failed"

LLM returned invalid JSON. Possible causes:
- Project structure too complex
- Missing critical files (no package.json or .csproj)
- Solution: Use `--wizard` mode

### Configs overwriting customizations

Auto-detection creates backups:
- `.morph/project.md.YYYY-MM-DDTHH-MM-SS.backup`
- `.morph/config/config.json.YYYY-MM-DDTHH-MM-SS.backup`

Review diffs before approving updates.

## Edge Cases

| Edge Case | Behavior |
|-----------|----------|
| Empty project (no files) | Falls back to wizard |
| Large project (1000+ files) | Only whitelisted files read |
| Monorepo with multiple stacks | Detects all stacks, shows in config |
| No database detected | `stack.database` set to `null` |
| No frontend detected | `stack.frontend` set to `null` |
| Git repo without remote | `gitRemote` set to `null` |
| User cancels (Ctrl+C) | Clean exit, no files modified |

## Privacy & Security

✅ **Local-only processing**: LLM runs in Claude Code (no external API calls)
✅ **Secret redaction**: 10+ secret patterns detected and removed
✅ **Whitelist-only reads**: Only safe files are analyzed
✅ **No telemetry**: No data sent to Anthropic or third parties

## Examples

### Example 1: Next.js + Supabase

**Detected:**
```json
{
  "name": "my-nextjs-app",
  "type": "nextjs",
  "stack": {
    "frontend": { "tech": "Next.js", "version": "15" },
    "backend": { "tech": "Supabase", "version": "latest" },
    "database": { "tech": "PostgreSQL", "version": "16" }
  },
  "confidence": 95
}
```

### Example 2: Blazor + Azure SQL

**Detected:**
```json
{
  "name": "MyApp",
  "type": "blazor-server",
  "stack": {
    "frontend": { "tech": "Blazor", "version": "10" },
    "backend": { "tech": ".NET", "version": "10" },
    "database": { "tech": "Azure SQL", "version": "latest" }
  },
  "hasAzure": true,
  "confidence": 98
}
```

## Command Flags

| Flag | Description |
|------|-------------|
| `--skip-detection` | Skip auto-detection (manual config) |
| `--wizard` | Force interactive wizard mode |
| `--force` | Overwrite existing configs without prompt |

---

For more help, see the [Troubleshooting Guide](./troubleshooting.md).
