Back to skills
SkillHub ClubResearch & OpsFull StackBackendDevOps

synapse

Pattern detection and automatic skill recommendation system. Activates when analyzing Cortex memory files, detecting recurring work patterns, or determining if new skills are needed. Analyzes .cortex_log.md, PRD files, and task lists to identify patterns (API calls, testing, deployment, etc.) appearing 5+ times. Generates Synapse_RECOMMENDATIONS.md with prioritized skill suggestions. Use when optimizing workflows or identifying automation opportunities.

Packaged view

This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.

Stars
2
Hot score
79
Updated
March 20, 2026
Overall rating
C3.0
Composite score
3.0
Best-practice grade
B75.6

Install command

npx @skill-hub/cli install bacoco-evolveskill-synapse

Repository

bacoco/EvolveSkill

Skill path: .claude/skills/synapse

Pattern detection and automatic skill recommendation system. Activates when analyzing Cortex memory files, detecting recurring work patterns, or determining if new skills are needed. Analyzes .cortex_log.md, PRD files, and task lists to identify patterns (API calls, testing, deployment, etc.) appearing 5+ times. Generates Synapse_RECOMMENDATIONS.md with prioritized skill suggestions. Use when optimizing workflows or identifying automation opportunities.

Open repository

Best for

Primary workflow: Research & Ops.

Technical facets: Full Stack, Backend, DevOps, Testing.

Target audience: everyone.

License: Unknown.

Original source

Catalog source: SkillHub Club.

Repository owner: bacoco.

This is still a mirrored public skill entry. Review the repository before installing into production workflows.

What it helps with

  • Install synapse into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
  • Review https://github.com/bacoco/EvolveSkill before adding synapse to shared team environments
  • Use synapse for development workflows

Works across

Claude CodeCodex CLIGemini CLIOpenCode

Favorites: 0.

Sub-skills: 0.

Aggregator: No.

Original source / Raw SKILL.md

---
name: synapse
description: Pattern detection and automatic skill recommendation system. Activates when analyzing Cortex memory files, detecting recurring work patterns, or determining if new skills are needed. Analyzes .cortex_log.md, PRD files, and task lists to identify patterns (API calls, testing, deployment, etc.) appearing 5+ times. Generates Synapse_RECOMMENDATIONS.md with prioritized skill suggestions. Use when optimizing workflows or identifying automation opportunities.
allowed-tools: Read, Write, Bash, Grep, Glob
---

# Synapse - Automatic Skill Generator

**Analyzes your work patterns and automatically generates the skills you need.**

Synapse is the brain of the skill ecosystem. It watches Cortex memory, reads your PRD files, analyzes your tasks, and automatically creates new skills when patterns emerge.

## What Synapse Does

Synapse performs unified analysis from multiple sources:

### 1. Cortex Memory Analysis
- Reads `.cortex_log.md` and `.cortex_status.json`
- Detects recurring patterns (API calls, data processing, errors, etc.)
- Identifies patterns that appear ≥ threshold (default: 5 times)
- Calculates priority based on frequency

### 2. PRD Analysis
- Scans for PRD files (`*PRD*.md`, `*REQUIREMENTS*.md`, `*ROADMAP*.md`)
- Extracts tasks and requirements
- Classifies by domain (api, testing, deployment, etc.)
- Counts tasks per domain to identify skill needs

### 3. Task Analysis
- Reads TODO files and task lists
- Parses checkboxes, numbered lists, bullets
- Groups related tasks
- Identifies skill opportunities

## Automatic Skill Generation

**Synapse runs automatically and generates skills without user intervention:**

- **Periodically**: Every 30 minutes via cron (optional)
- **On git commit**: Via post-commit hook (optional)
- **When critical patterns detected**: Immediate generation

**Skills are auto-generated when:**
- Pattern appears ≥ threshold (default: 5 times)
- Priority is high or critical
- Skill doesn't already exist

## How It Works

```
You work normally
        ↓
Cortex traces everything
        ↓
Synapse monitors automatically:
  - Cortex memory (patterns)
  - PRD files (requirements)
  - Task lists (TODO)
        ↓
Detects patterns >= threshold
        ↓
Auto-generates skills if priority >= high:
  - Creates .claude/skills/[skill-name]/
  - Generates SKILL.md with progressive disclosure
  - Creates scripts with Cortex API integration
  - Records in Cortex memory
        ↓
New skill ready immediately!
        ↓
Claude uses it automatically
```

**No user intervention needed.**

## Priority Levels

Synapse assigns priorities based on frequency and task count:

- **🔴 CRITICAL**: Pattern appears 2+ times/day → Auto-generate immediately
- **🟠 HIGH**: Pattern appears 1+ times/day → Auto-generate
- **🟡 MEDIUM**: Pattern appears 3-7 times/week → Monitor
- **🟢 LOW**: Pattern appears <3 times/week → Monitor

Only HIGH and CRITICAL priorities trigger automatic generation.

## Output

Synapse generates `Synapse_RECOMMENDATIONS.md` with prioritized skill recommendations:

```markdown
# Synapse Skill Recommendations

## Summary
- Total recommendations: 3
- High priority: 2
- Medium priority: 1

## Recommended Skills

### 1. 🔴 api-optimizer (CRITICAL)
**Pattern:** api_call
**Frequency:** 3.5 times/day (24 total in 7 days)
**Reason:** Frequent API operations detected
...
```

See [OUTPUT_FORMAT.md](references/OUTPUT_FORMAT.md) for complete output specification.

## Quick Start

### Automatic Mode (Recommended)

Run auto-generator to analyze and generate skills automatically:

```bash
python .claude/skills/synapse/scripts/auto_skill_generator.py
```

Skills with HIGH or CRITICAL priority will be generated automatically.

### Analysis Only

Generate recommendations without auto-creating skills:

```bash
python .claude/skills/synapse/scripts/synapse_analyzer.py
```

This creates `Synapse_RECOMMENDATIONS.md` for manual review.

### Setup Monitoring

Add to crontab for automatic periodic checks:

```bash
# Every 30 minutes
*/30 * * * * /path/to/.claude/skills/synapse/scripts/synapse_auto_watch.sh
```

Or use as git hook (see [INSTALLATION.md](references/INSTALLATION.md)).

## Integration with Cortex

Synapse and Cortex work together seamlessly:

1. **Cortex traces** your work and records events
2. **Synapse analyzes** Cortex memory for patterns
3. **Synapse generates** skills when patterns reach threshold
4. **New skills use** Cortex API to record their own events
5. **Pattern detection improves** as more skills contribute data

This creates a self-improving system where skills emerge from actual usage patterns.

## Generated Skill Structure

Synapse creates skills following best practices:

```
generated-skill/
├── SKILL.md (with YAML frontmatter)
├── scripts/
│   └── main.py (with Cortex API integration)
└── references/ (if needed)
```

All generated skills:
- ✅ Follow progressive disclosure principles
- ✅ Include Cortex API integration
- ✅ Have concise SKILL.md (<200 lines)
- ✅ Record their own events for future pattern detection
- ✅ Work with Claude Code, GPT, and Gemini

## Multi-LLM Support

Synapse works with any CLI-based LLM:
- ✅ **Claude Code**: Native integration
- ✅ **GPT/Codex**: Reads `Synapse_RECOMMENDATIONS.md`
- ✅ **Gemini CLI**: Reads `Synapse_RECOMMENDATIONS.md`

See [MULTI_LLM.md](references/MULTI_LLM.md) for LLM-specific guides.

## Advanced Features

- **Pattern merging**: Combines Cortex + PRD patterns for higher priority
- **Duplicate detection**: Never generates skills that already exist
- **Context preservation**: Recommendations include example usage
- **Custom thresholds**: Configure sensitivity via command-line args

See [ADVANCED.md](references/ADVANCED.md) for detailed documentation.

## Configuration

Create `.synapse_config.json` for custom settings:

```json
{
  "analysis": {
    "threshold": 5,
    "window_days": 7
  },
  "sources": {
    "cortex_memory": true,
    "prd_files": true,
    "task_lists": true
  }
}
```

See [CONFIGURATION.md](references/CONFIGURATION.md) for all options.

## References

- **[INSTALLATION.md](references/INSTALLATION.md)** - Setup and git hooks
- **[MANUAL_USAGE.md](references/MANUAL_USAGE.md)** - Command-line options
- **[OUTPUT_FORMAT.md](references/OUTPUT_FORMAT.md)** - Recommendation file format
- **[EXAMPLES.md](references/EXAMPLES.md)** - Real-world skill generation examples
- **[ADVANCED.md](references/ADVANCED.md)** - Pattern merging, customization
- **[CONFIGURATION.md](references/CONFIGURATION.md)** - Complete config reference
- **[MULTI_LLM.md](references/MULTI_LLM.md)** - Using with GPT, Gemini, etc.

## Part of the Ecosystem

**Cortex** → Remembers everything
**Synapse** → Analyzes and generates
**Generated skills** → Solve specific problems
**Skills use Cortex** → Pattern detection improves

Synapse makes the system intelligent and self-improving.

---

*Synapse - The universal skill recommendation and generation engine*


---

## Referenced Files

> The following files are referenced in this skill and included for context.

### references/OUTPUT_FORMAT.md

```markdown
# Synapse Output Format

Complete specification for `Synapse_RECOMMENDATIONS.md`.

## File Structure

```markdown
# Synapse Skill Recommendations

> Generated on YYYY-MM-DD HH:MM:SS
> Analysis period: Last N days
> Pattern threshold: N occurrences

---

## Summary

- **Total recommendations**: N
- **High priority**: N
- **Medium priority**: N
- **Low priority**: N

---

## Recommended Skills

### 1. 🔴 skill-name

**Priority:** CRITICAL

**Pattern Type:** pattern_type

**Source:** Cortex patterns / PRD analysis / Task analysis

**Reason:** Brief explanation

**Frequency:** N.N times/day (N total)

**Example Contexts:**
- Context 1
- Context 2
- Context 3

---

### 2. 🟠 another-skill

**Priority:** HIGH

...

---

## Next Steps

1. **Review** these recommendations
2. **Run auto-generator** to create high-priority skills:
   ```bash
   python .claude/skills/synapse/scripts/auto_skill_generator.py
   ```
3. **Test** generated skills with your workflow
4. **Synapse will continue monitoring** and update recommendations

---

*Generated by Synapse Unified Analyzer*
*Combining Cortex patterns, PRD analysis, and task analysis*
```

## Priority Icons

- 🔴 **CRITICAL** - Immediate action recommended
- 🟠 **HIGH** - Should generate soon
- 🟡 **MEDIUM** - Generate when convenient
- 🟢 **LOW** - Monitor for increase

## Recommendation Fields

### Required Fields

- **Priority**: CRITICAL / HIGH / MEDIUM / LOW
- **Pattern Type**: Type of pattern detected (api_call, data_processing, etc.)
- **Source**: Where the recommendation came from
- **Reason**: Why this skill is recommended
- **Frequency**: How often the pattern occurs

### Optional Fields

- **Example Contexts**: Sample occurrences from Cortex
- **PRD Tasks**: Related tasks from PRD files
- **Suggested Capabilities**: What the skill should do
- **Related Skills**: Existing skills that complement this one

## Source Types

### Cortex Patterns

```markdown
**Source:** Cortex patterns
**Pattern Type:** api_call
**Frequency:** 3.5 times/day (24 total)
**Example Contexts:**
- Called GitHub API for repos
- Called Stripe API for customers
- Called SendGrid API for emails
```

### PRD Analysis

```markdown
**Source:** PRD analysis
**Pattern Type:** testing
**Task Count:** 15 test-related tasks
**PRD Files:**
- PROJECT_PRD.md (8 tasks)
- TEST_REQUIREMENTS.md (7 tasks)
```

### Task Analysis

```markdown
**Source:** Task analysis
**Pattern Type:** deployment
**Task Count:** 8 deployment TODOs
**Task Sources:**
- TODO.md (5 tasks)
- ROADMAP.md (3 tasks)
```

### Combined Sources

```markdown
**Source:** Cortex patterns + PRD analysis
**Pattern Type:** data_processing
**Cortex Frequency:** 2.1 times/day (15 total)
**PRD Tasks:** 7 ETL tasks
**Combined Priority:** CRITICAL (merged from HIGH + MEDIUM)
```

## Example Output Files

### Minimal Output (No Recommendations)

```markdown
# Synapse Skill Recommendations

> Generated on 2025-10-26 10:00:00
> Analysis period: Last 7 days
> Pattern threshold: 5 occurrences

---

## Summary

- **Total recommendations**: 0
- **High priority**: 0
- **Medium priority**: 0
- **Low priority**: 0

---

## Recommended Skills

✅ **No new skills needed** - existing skills cover current patterns.

## Next Steps

1. **Continue working** - Synapse will monitor for new patterns
2. **Synapse runs automatically** every 30 minutes (if configured)
3. **Check back later** for updated recommendations

---

*Generated by Synapse Unified Analyzer*
```

### Multiple Recommendations

```markdown
# Synapse Skill Recommendations

> Generated on 2025-10-26 10:00:00
> Analysis period: Last 7 days
> Pattern threshold: 5 occurrences

---

## Summary

- **Total recommendations**: 5
- **High priority**: 2
- **Medium priority**: 2
- **Low priority**: 1

---

## Recommended Skills

### 1. 🔴 api-optimizer

**Priority:** CRITICAL

**Pattern Type:** api_call

**Source:** Cortex patterns

**Reason:** Detected 24 API operations in 7 days

**Frequency:** 3.4 times/day (24 total)

**Example Contexts:**
- GET /api/users - Called 8 times
- POST /api/auth - Called 6 times
- GET /api/data - Called 10 times

**Suggested Capabilities:**
- Rate limiting and retry logic
- Response caching with TTL
- Error handling patterns
- Request/response logging

---

### 2. 🔴 data-transformer

**Priority:** CRITICAL

**Pattern Type:** data_processing

**Source:** Cortex patterns + PRD analysis

**Reason:** Frequent data transformation operations

**Cortex Frequency:** 2.1 times/day (15 total)

**PRD Tasks:** 7 ETL-related tasks in PROJECT_PRD.md

**Example Contexts:**
- Parsed CSV files (5 times)
- Transformed JSON responses (6 times)
- Validated data formats (4 times)

**Suggested Capabilities:**
- CSV/JSON/XML parsing
- Data validation and cleaning
- Format conversions
- Schema validation

---

### 3. 🟠 test-guardian

**Priority:** HIGH

**Pattern Type:** testing

**Source:** PRD analysis

**Reason:** Large number of testing requirements

**Task Count:** 15 test-related tasks

**PRD Files:**
- PROJECT_PRD.md (8 tasks)
- TEST_REQUIREMENTS.md (7 tasks)

**Suggested Capabilities:**
- Test case generation
- Coverage analysis
- Mock data creation
- Test runner integration

---

### 4. 🟡 deploy-sage

**Priority:** MEDIUM

**Pattern Type:** deployment

**Source:** Task analysis

**Reason:** Multiple deployment TODOs identified

**Task Count:** 8 deployment tasks

**Task Sources:**
- TODO.md (5 tasks)
- ROADMAP.md (3 tasks)

**Suggested Capabilities:**
- Docker container management
- CI/CD pipeline helpers
- Environment configuration
- Health check monitoring

---

### 5. 🟢 docs-writer

**Priority:** LOW

**Pattern Type:** documentation

**Source:** Cortex patterns

**Reason:** Occasional documentation updates

**Frequency:** 0.4 times/day (3 total)

**Example Contexts:**
- Updated README.md
- Created API documentation
- Added inline comments

**Suggested Capabilities:**
- Markdown generation
- API docs from code
- Comment generation
- Documentation templates

---

## Next Steps

1. **Review** these recommendations
2. **Run auto-generator** to create high-priority skills:
   ```bash
   python .claude/skills/synapse/scripts/auto_skill_generator.py
   ```
3. **Test** generated skills with your workflow
4. **Synapse will continue monitoring** and update recommendations

---

*Generated by Synapse Unified Analyzer*
*Combining Cortex patterns, PRD analysis, and task analysis*
```

## Machine-Readable Format

Synapse can also output JSON for programmatic consumption:

```bash
python .claude/skills/synapse/scripts/synapse_analyzer.py --format json
```

```json
{
  "generated_at": "2025-10-26T10:00:00",
  "analysis_period_days": 7,
  "threshold": 5,
  "summary": {
    "total_recommendations": 5,
    "by_priority": {
      "critical": 2,
      "high": 1,
      "medium": 1,
      "low": 1
    }
  },
  "recommendations": [
    {
      "skill_name": "api-optimizer",
      "priority": "critical",
      "pattern_type": "api_call",
"source": "cortex_patterns",
      "frequency": 3.4,
      "count": 24,
      "reason": "Detected 24 API operations in 7 days",
      "contexts": ["GET /api/users", "POST /api/auth", ...]
    },
    ...
  ]
}
```

## Reading the Output

### For Humans

Read `Synapse_RECOMMENDATIONS.md` to understand:
- Which skills are recommended
- Why they're recommended
- What priority they have
- Whether to generate them

### For Claude

Claude reads the markdown file and:
- Identifies high-priority recommendations
- Uses skill-creator to generate skills
- Records generation in Cortex memory

### For Other LLMs

GPT, Gemini, etc. can read the markdown file:
```
Read Synapse_RECOMMENDATIONS.md and tell me what skills I should create
```

### For Scripts

Parse the JSON format for automated workflows:
```python
import json

with open("Synapse_RECOMMENDATIONS.json") as f:
    recs = json.load(f)

for rec in recs["recommendations"]:
    if rec["priority"] in ["critical", "high"]:
        print(f"Generate: {rec['skill_name']}")
```

## See Also

- [EXAMPLES.md](EXAMPLES.md) - Real-world examples
- [MANUAL_USAGE.md](MANUAL_USAGE.md) - Command-line options
- Main SKILL.md - Synapse overview

```

### references/INSTALLATION.md

```markdown
# Synapse Installation Guide

Complete setup instructions for Synapse automatic skill generation.

## Prerequisites

- Python 3.7 or higher
- Cortex skill installed
- Git repository (for automatic monitoring)

## Quick Install

```bash
# 1. Synapse is already installed if you have .claude/skills/synapse/
cd /path/to/your/project

# 2. Verify Synapse is present
ls -la .claude/skills/synapse/

# 3. Test Synapse
python .claude/skills/synapse/scripts/synapse_analyzer.py --dry-run
```

That's it! Synapse is ready to use.

## Automatic Monitoring Setup

For automatic skill generation, set up monitoring via cron or git hooks.

### Option 1: Cron Job (Recommended)

Automatically run Synapse every 30 minutes:

```bash
# Edit crontab
crontab -e

# Add this line for every 30 minutes
*/30 * * * * /path/to/.claude/skills/synapse/scripts/synapse_auto_watch.sh >> /path/to/.synapse_cron.log 2>&1

# Or for hourly monitoring
0 * * * * /path/to/.claude/skills/synapse/scripts/synapse_auto_watch.sh >> /path/to/.synapse_cron.log 2>&1
```

**Adjust path:**

```bash
# Get absolute path
PROJECT_DIR=$(pwd)
echo "*/30 * * * * $PROJECT_DIR/.claude/skills/synapse/scripts/synapse_auto_watch.sh >> $PROJECT_DIR/.synapse_cron.log 2>&1" | crontab -
```

**Verify cron:**

```bash
# Check cron is scheduled
crontab -l

# Check logs after 30 minutes
tail -f .synapse_cron.log
```

### Option 2: Git Hook

Run Synapse automatically after every commit:

```bash
# Create post-commit hook
cat > .git/hooks/post-commit << 'EOF'
#!/bin/bash
# Run Synapse in background after commits

PROJECT_DIR=$(git rev-parse --show-toplevel)
"$PROJECT_DIR/.claude/skills/synapse/scripts/synapse_auto_watch.sh" >> "$PROJECT_DIR/.synapse_git_hook.log" 2>&1 &
EOF

# Make executable
chmod +x .git/hooks/post-commit
```

**Test git hook:**

```bash
# Make a test commit
echo "test" >> .gitignore
git add .gitignore
git commit -m "test: Synapse git hook"

# Check hook ran
tail .synapse_git_hook.log
```

### Option 3: Manual Runs

Run Synapse manually whenever needed:

```bash
# Analyze and auto-generate
python .claude/skills/synapse/scripts/auto_skill_generator.py

# Analyze only (no generation)
python .claude/skills/synapse/scripts/synapse_analyzer.py
```

## Configuration Setup

### Basic Configuration

Create `.synapse_config.json`:

```bash
cat > .synapse_config.json << 'EOF'
{
  "analysis": {
    "threshold": 5,
    "window_days": 7,
    "auto_threshold": "high"
  },
  "sources": {
    "cortex_memory": true,
    "prd_files": true,
    "task_lists": true
  },
  "auto_generation": {
    "enabled": true,
    "max_skills_per_run": 5,
    "log_to_cortex": true
  },
  "logging": {
    "enabled": true,
    "file": ".synapse_auto.log",
    "level": "INFO"
  }
}
EOF
```

### Project-Specific Paths

For non-standard project structures:

```json
{
  "paths": {
    "skills_dir": ".claude/skills",
    "prd_patterns": ["docs/*PRD*.md", "requirements/*.md"],
    "todo_patterns": ["tasks/*.md", "TODO.md"]
  }
}
```

## Verification

### Test Synapse Installation

```bash
# 1. Check Synapse files exist
ls -la .claude/skills/synapse/scripts/

# Expected output:
# synapse_analyzer.py
# auto_skill_generator.py
# cortex_integration.py

# 2. Test analyzer
python .claude/skills/synapse/scripts/synapse_analyzer.py --dry-run

# Expected output:
# 📊 Synapse Unified Analyzer
# ✅ Analysis complete

# 3. Test auto-generator
python .claude/skills/synapse/scripts/auto_skill_generator.py --dry-run

# Expected output:
# 🤖 Synapse Auto Skill Generator (DRY RUN)
# 📊 Analysis Results: ...
```

### Test Cortex Integration

```bash
# 1. Check Cortex is available
python -c "from cortex_api import get_cortex_memory; print('✅ Cortex API available')"

# 2. Add test event
python -c "from cortex_api import add_cortex_event; add_cortex_event('test', 'Synapse test event')"

# 3. Run Synapse to detect
python .claude/skills/synapse/scripts/synapse_analyzer.py
```

### Test Automatic Monitoring

If using cron:

```bash
# Wait 30 minutes, then check logs
tail -f .synapse_cron.log
```

If using git hook:

```bash
# Make a test commit
git commit --allow-empty -m "test: Synapse monitoring"

# Check log
tail .synapse_git_hook.log
```

## Troubleshooting Installation

### Cortex Not Found

**Error:**
```
ModuleNotFoundError: No module named 'cortex_api'
```

**Solution:**

```bash
# Check Cortex is installed
ls -la .claude/skills/cortex/scripts/cortex_api.py

# Install Cortex if missing
cd .claude/skills/cortex/scripts
./install.sh
```

### Permission Denied

**Error:**
```
Permission denied: .synapse_auto.log
```

**Solution:**

```bash
# Create log file with correct permissions
touch .synapse_auto.log
chmod 644 .synapse_auto.log

# For cron, ensure directory is writable
chmod 755 $(pwd)
```

### Cron Not Running

**Error:**
Cron job not executing

**Solution:**

```bash
# Check cron service is running
systemctl status cron   # Linux
sudo launchctl list | grep cron  # macOS

# Check cron logs
grep Synapse /var/log/syslog  # Linux
grep Synapse /var/log/system.log  # macOS

# Use absolute paths in crontab
crontab -e
# Change: */30 * * * * ./script.sh
# To: */30 * * * * /full/path/to/script.sh
```

### Git Hook Not Triggering

**Error:**
Hook exists but doesn't run

**Solution:**

```bash
# Check hook is executable
ls -la .git/hooks/post-commit
# Should show: -rwxr-xr-x

# Make executable if needed
chmod +x .git/hooks/post-commit

# Test hook manually
.git/hooks/post-commit

# Check for errors
cat .synapse_git_hook.log
```

## Uninstallation

### Remove Cron Job

```bash
# Edit crontab
crontab -e

# Remove Synapse line, save and exit

# Verify removal
crontab -l | grep synapse
# Should show nothing
```

### Remove Git Hook

```bash
rm .git/hooks/post-commit
```

### Remove Configuration

```bash
rm .synapse_config.json
rm .synapse_auto.log
rm .synapse_cron.log
rm .synapse_git_hook.log
```

### Keep Synapse, Disable Auto-Generation

```json
{
  "auto_generation": {
    "enabled": false
  }
}
```

Or remove cron/hooks but keep Synapse for manual use.

## Upgrading Synapse

If Synapse is updated:

```bash
# Pull latest version
git pull

# No additional steps needed - Python scripts auto-reload

# Test new version
python .claude/skills/synapse/scripts/auto_skill_generator.py --version
```

## Multi-Project Setup

### Shared Synapse Installation

For multiple projects sharing skills:

```bash
# Project structure
~/workspace/
├── .shared_skills/
│   └── synapse/
└── project1/
    └── .claude/
        └── skills/ -> ../../.shared_skills/
```

### Per-Project Synapse

Each project has its own Synapse:

```bash
~/workspace/
├── project1/
│   └── .claude/skills/synapse/
└── project2/
    └── .claude/skills/synapse/
```

Setup cron for each:

```bash
# Edit crontab
crontab -e

# Add line for each project
*/30 * * * * /home/user/workspace/project1/.claude/skills/synapse/scripts/synapse_auto_watch.sh
*/30 * * * * /home/user/workspace/project2/.claude/skills/synapse/scripts/synapse_auto_watch.sh
```

## Platform-Specific Notes

### Linux

- Cron service usually pre-installed
- Use `systemctl` to manage services
- Logs typically in `/var/log/syslog`

### macOS

- Use `cron` or `launchd` for scheduling
- `launchd` is preferred for system services
- Logs in `/var/log/system.log`

### Windows (WSL)

- Install cron: `sudo apt-get install cron`
- Start cron: `sudo service cron start`
- Use Linux instructions

### Windows (Native)

Use Task Scheduler instead of cron:

```powershell
# Create scheduled task
$action = New-ScheduledTaskAction -Execute "python" -Argument "C:\path\to\auto_skill_generator.py"
$trigger = New-ScheduledTaskTrigger -Once -At 12:00 -RepetitionInterval (New-TimeSpan -Minutes 30) -RepetitionDuration (New-TimeSpan -Days 365)
Register-ScheduledTask -TaskName "Synapse Monitor" -Action $action -Trigger $trigger
```

## Docker Setup

For containerized environments:

```dockerfile
# Dockerfile
FROM python:3.9

WORKDIR /app
COPY .claude/skills/synapse /app/.claude/skills/synapse

# Install cron
RUN apt-get update && apt-get install -y cron

# Add cron job
RUN echo "*/30 * * * * python /app/.claude/skills/synapse/scripts/auto_skill_generator.py" | crontab -

# Run cron in foreground
CMD ["cron", "-f"]
```

## See Also

- [MANUAL_USAGE.md](MANUAL_USAGE.md) - Command-line options
- [CONFIGURATION.md](CONFIGURATION.md) - Config reference
- [EXAMPLES.md](EXAMPLES.md) - Real-world examples
- Main SKILL.md - Synapse overview

```

### references/MULTI_LLM.md

```markdown
# Synapse Multi-LLM Support

Using Synapse with different LLM platforms.

## Universal Output Format

Synapse uses LLM-agnostic formats:
- **Markdown** for human-readable recommendations
- **JSON** for machine-readable data
- **Python** for programmatic access

No LLM-specific syntax required.

## Supported LLMs

### Claude Code (Native)

**How It Works:**
- Synapse runs automatically via cron/git hooks
- Auto-generates skills when patterns detected
- Skills immediately available to Claude
- Full integration with Cortex memory

**Setup:**

```bash
# Run manually
python .claude/skills/synapse/scripts/auto_skill_generator.py

# Or setup automatic monitoring
*/30 * * * * /path/to/.claude/skills/synapse/scripts/synapse_auto_watch.sh
```

**Usage:**

```bash
# Claude automatically uses generated skills
claude

# Synapse has already created skills based on your patterns
# Claude loads them automatically
```

**Features:**
- ✅ Automatic skill generation
- ✅ Cortex integration
- ✅ Immediate skill loading
- ✅ Full progressive disclosure support

---

### OpenAI GPT (CLI)

**How It Works:**
- Synapse runs in background
- Generates `Synapse_RECOMMENDATIONS.md`
- GPT reads recommendations manually or via system prompt

**Setup:**

```bash
# 1. Setup Synapse monitoring (same as Claude)
*/30 * * * * /path/to/.claude/skills/synapse/scripts/synapse_auto_watch.sh

# 2. Configure GPT to read recommendations
cat > ~/.config/gpt/system_prompt.txt << 'EOF'
Check Synapse_RECOMMENDATIONS.md for skill recommendations.
If high-priority skills are recommended, notify the user.
EOF
```

**Usage:**

```bash
# Start GPT session
gpt

# Ask about recommendations
> Check Synapse recommendations

# GPT reads Synapse_RECOMMENDATIONS.md and reports:
"Synapse recommends 2 high-priority skills:
1. api-optimizer (CRITICAL)
2. test-guardian (HIGH)

Would you like me to create these skills?"
```

**Manual Workflow:**

```bash
# 1. Run Synapse analysis
python .claude/skills/synapse/scripts/synapse_analyzer.py

# 2. Read recommendations
cat Synapse_RECOMMENDATIONS.md

# 3. Ask GPT to create recommended skills
gpt
> Create the api-optimizer skill as recommended by Synapse
```

**Features:**
- ✅ Reads recommendations
- ⚠️ Manual skill creation
- ⚠️ No automatic monitoring
- ✅ Cortex integration (via Python API)

---

### Google Gemini (CLI)

**How It Works:**
- Synapse generates recommendations
- Gemini reads markdown recommendations
- Manual or semi-automatic skill creation

**Setup:**

```bash
# 1. Setup Synapse monitoring
*/30 * * * * /path/to/.claude/skills/synapse/scripts/synapse_auto_watch.sh

# 2. Configure Gemini startup script
cat > ~/.gemini/startup.sh << 'EOF'
#!/bin/bash
if [ -f "Synapse_RECOMMENDATIONS.md" ]; then
echo "📊 Synapse recommendations available. Type 'check synapse' to review."
fi
EOF
```

**Usage:**

```bash
# Start Gemini
gemini

# Check recommendations
> Read Synapse_RECOMMENDATIONS.md and summarize

# Create recommended skills
> Create the api-optimizer skill following Synapse recommendations
```

**Features:**
- ✅ Reads recommendations
- ⚠️ Manual skill creation
- ⚠️ No automatic monitoring
- ✅ Cortex integration (via Python API)

---

### Cursor

**How It Works:**
- Synapse runs in background
- Cursor reads recommendations via sidebar
- Skills created manually

**Setup:**

```bash
# 1. Setup Synapse monitoring
*/30 * * * * /path/to/.claude/skills/synapse/scripts/synapse_auto_watch.sh

# 2. Add to workspace settings (.vscode/settings.json)
{
  "cursor.ai.systemPrompt": "Check Synapse_RECOMMENDATIONS.md for skill recommendations. Notify user if high-priority skills are recommended."
}
```

**Usage:**

Open Cursor → AI will notify if Synapse has recommendations → Create skills manually

**Features:**
- ⚠️ Manual recommendation checking
- ⚠️ Manual skill creation
- ❌ No automatic skill generation
- ⚠️ Limited Cortex integration

---

### Aider

**How It Works:**
- Synapse generates recommendations
- Aider reads via file context
- Semi-automatic skill creation

**Setup:**

```bash
# 1. Setup Synapse monitoring
*/30 * * * * /path/to/.claude/skills/synapse/scripts/synapse_auto_watch.sh

# 2. Add to .aider.conf.yml
read:
  - Synapse_RECOMMENDATIONS.md

message: |
  Check Synapse_RECOMMENDATIONS.md for skill recommendations.
  Create high-priority skills automatically.
```

**Usage:**

```bash
# Start Aider
aider

# Aider automatically reads Synapse_RECOMMENDATIONS.md
# Ask to create skills:
> Create the skills recommended by Synapse
```

**Features:**
- ✅ Automatic recommendation reading
- ⚠️ Semi-automatic skill creation
- ✅ Cortex integration
- ✅ Good file context management

---

## Cross-LLM Workflows

### Scenario 1: Claude Generates, GPT Uses

```bash
# Developer A uses Claude Code
# Synapse auto-generates api-optimizer skill

# Developer B uses GPT
# Checks out same repository
# GPT can't load skills automatically but can read:
gpt
> Read .claude/skills/api-optimizer/SKILL.md and apply its patterns
```

### Scenario 2: Shared Recommendations

```bash
# Project team uses different LLMs
# Synapse generates universal recommendations

# All team members can:
cat Synapse_RECOMMENDATIONS.md

# Each LLM handles skill creation differently:
# - Claude: Automatic
# - GPT: Manual via skill-creator
# - Gemini: Manual via skill-creator
```

---

## LLM Comparison Table

| Feature | Claude Code | GPT CLI | Gemini CLI | Cursor | Aider |
|---------|-------------|---------|------------|--------|-------|
| Auto skill generation | ✅ Full | ❌ No | ❌ No | ❌ No | ⚠️ Semi |
| Read recommendations | ✅ Auto | ⚠️ Manual | ⚠️ Manual | ⚠️ Manual | ✅ Auto |
| Cortex integration | ✅ Full | ⚠️ API only | ⚠️ API only | ❌ No | ⚠️ API only |
| Skill loading | ✅ Auto | ❌ No | ❌ No | ❌ No | ❌ No |
| Progressive disclosure | ✅ Full | ⚠️ Manual | ⚠️ Manual | ⚠️ Manual | ⚠️ Manual |
| Monitoring setup | ✅ Easy | ✅ Easy | ✅ Easy | ✅ Easy | ✅ Easy |

**Legend:**
- ✅ Full support
- ⚠️ Partial / Manual
- ❌ Not supported

---

## Recommendation Consumption

### For Humans

Read the markdown file directly:

```bash
cat Synapse_RECOMMENDATIONS.md
```

### For Claude Code

Claude automatically:
1. Runs Synapse in background
2. Generates skills when patterns detected
3. Loads skills automatically

### For Other LLMs

**Option 1: Manual Creation**

```bash
# 1. Read recommendations
cat Synapse_RECOMMENDATIONS.md

# 2. Ask LLM to create skill
your-llm
> Create a skill called api-optimizer based on Synapse recommendations
```

**Option 2: Use skill-creator**

```bash
# 1. Read recommendations
python .claude/skills/synapse/scripts/synapse_analyzer.py

# 2. Use skill-creator meta-skill
your-llm
> Use skill-creator to generate the api-optimizer skill
```

**Option 3: Python Script**

```python
#!/usr/bin/env python3
"""Auto-create skills from Synapse for non-Claude LLMs"""
import subprocess
import json

# Read recommendations
with open("Synapse_RECOMMENDATIONS.md") as f:
    content = f.read()

# Parse recommendations (simplified)
if "🔴 CRITICAL" in content or "🟠 HIGH" in content:
    # Trigger skill-creator
    subprocess.run([
        "your-llm-cli",
        "--prompt",
        "Create skills based on Synapse_RECOMMENDATIONS.md"
    ])
```

---

## JSON Format for Programmatic Access

Generate machine-readable format:

```bash
python .claude/skills/synapse/scripts/synapse_analyzer.py --format json
```

```json
{
  "recommendations": [
    {
      "skill_name": "api-optimizer",
      "priority": "critical",
      "pattern_type": "api_call",
      "frequency": 3.4,
      "contexts": [...]
    }
  ]
}
```

Parse with any language:

```python
# Python
import json
with open("Synapse_RECOMMENDATIONS.json") as f:
    recs = json.load(f)

# JavaScript
const recs = require('./Synapse_RECOMMENDATIONS.json');

# Ruby
require 'json'
recs = JSON.parse(File.read('Synapse_RECOMMENDATIONS.json'))
```

---

## Best Practices by LLM

### For Claude Code Users

**Do:**
- ✅ Setup automatic monitoring (cron/git hooks)
- ✅ Let Synapse auto-generate skills
- ✅ Trust the automation

**Don't:**
- ❌ Manually create skills that Synapse recommends
- ❌ Disable auto-generation without reason

### For GPT Users

**Do:**
- ✅ Check `Synapse_RECOMMENDATIONS.md` regularly
- ✅ Use skill-creator to generate recommended skills
- ✅ Integrate Cortex API in custom scripts

**Don't:**
- ❌ Ignore high-priority recommendations
- ❌ Recreate skills that Synapse would auto-generate

### For Gemini Users

**Do:**
- ✅ Setup monitoring (Synapse runs same way)
- ✅ Read recommendations at session start
- ✅ Create skills for critical/high priorities

**Don't:**
- ❌ Skip checking recommendations
- ❌ Create skills for low-priority patterns

### For Cursor Users

**Do:**
- ✅ Add Synapse to workspace awareness
- ✅ Review recommendations weekly
- ✅ Create high-priority skills manually

**Don't:**
- ❌ Ignore Synapse entirely (limited value)

### For Aider Users

**Do:**
- ✅ Add Synapse_RECOMMENDATIONS.md to read list
- ✅ Configure auto-reading in .aider.conf.yml
- ✅ Batch-create recommended skills

**Don't:**
- ❌ Skip configuration step
- ❌ Ignore semi-automation opportunities

---

## Troubleshooting by LLM

### GPT: Can't Read Recommendations

**Problem:**
GPT doesn't automatically check Synapse_RECOMMENDATIONS.md

**Solution:**
```bash
# Explicitly ask GPT:
> Read Synapse_RECOMMENDATIONS.md and tell me what skills are recommended
```

### Gemini: Skill Creation Failed

**Problem:**
Gemini doesn't understand skill structure

**Solution:**
```bash
# Provide skill-creator guidance:
> Use the skill-creator skill to generate the api-optimizer skill following the template in .claude/skills/skill-creator/
```

### Cursor: No Skill Awareness

**Problem:**
Cursor doesn't load Claude skills

**Solution:**
```bash
# Manual skill application:
> Read .claude/skills/api-optimizer/SKILL.md and apply those patterns to this API call
```

---

## See Also

- [INSTALLATION.md](INSTALLATION.md) - Setup guide
- [MANUAL_USAGE.md](MANUAL_USAGE.md) - Command-line options
- [EXAMPLES.md](EXAMPLES.md) - Real-world examples
- Cortex [MULTI_LLM.md](../../cortex/references/MULTI_LLM.md) - Cortex multi-LLM guide
- Main SKILL.md - Synapse overview

```

### references/ADVANCED.md

```markdown
# Synapse Advanced Features

Advanced functionality and customization options.

## Pattern Merging

Synapse intelligently merges patterns from multiple sources to calculate combined priority.

### How It Works

When the same pattern type appears in multiple sources:

```
Cortex pattern: api_call
  Count: 12
  Frequency: 1.7/day
  Priority: HIGH

PRD pattern: api_call
  Task count: 8
  Priority: MEDIUM

MERGED:
  Source: Cortex + PRD
  Combined priority: CRITICAL
  Reason: Pattern in both usage and requirements
```

### Merging Rules

**Priority Escalation:**

| Cortex Priority | PRD Priority | Merged Priority |
|---------------|--------------|-----------------|
| HIGH | HIGH | CRITICAL |
| HIGH | MEDIUM | CRITICAL |
| HIGH | LOW | HIGH |
| MEDIUM | MEDIUM | HIGH |
| MEDIUM | LOW | MEDIUM |
| LOW | LOW | MEDIUM |

**Additional Factors:**

- **Trend analysis**: Increasing frequency → priority boost
- **Error correlation**: Errors in same domain → priority boost
- **Task complexity**: PRD task complexity → priority adjustment

### Example

```python
# Pattern appears in Cortex
cortex_pattern = {
    "type": "data_processing",
    "count": 10,
    "frequency": 1.4,  # per day
    "priority": "medium"
}

# Same pattern in PRD
prd_pattern = {
    "type": "data_processing",
    "task_count": 6,
    "priority": "medium"
}

# Synapse merges:
merged = {
    "type": "data_processing",
    "source": "Cortex + PRD",
    "priority": "high",  # Escalated from medium
    "cortex_frequency": 1.4,
    "prd_tasks": 6,
    "reason": "Pattern confirmed in both usage and requirements"
}
```

---

## Duplicate Detection

Synapse prevents generating duplicate skills.

### Detection Methods

1. **Exact name match**: Skill directory already exists
2. **Pattern match**: Existing skill covers the pattern type
3. **Capability match**: Existing skill provides same capabilities

### Example

```bash
# Existing skills
.claude/skills/
├── api-optimizer/     # Handles api_call patterns
├── test-guardian/     # Handles testing patterns
└── data-master/       # Handles data_processing patterns

# Synapse detects api_call pattern
# Checks: does api-optimizer exist? YES
# Result: Skip recommendation
```

### Override

Force recommendation even if skill exists:

```bash
python auto_skill_generator.py --force-recommendations
```

---

## Context Preservation

Synapse preserves example contexts from Cortex for better skill generation.

### How Contexts Are Collected

```python
# Cortex events with metadata
events = [
    {
        "type": "api_call",
        "description": "Called GitHub API for repos",
        "metadata": {"endpoint": "/user/repos", "status": 200}
    },
    {
        "type": "api_call",
        "description": "Called Stripe API for customers",
        "metadata": {"endpoint": "/customers", "status": 200}
    },
    # ... more events
]

# Synapse extracts contexts
contexts = [
    "Called GitHub API for repos",
    "Called Stripe API for customers",
    # ... up to include_contexts limit (default: 5)
]
```

### Usage in Skill Generation

Generated skills include these contexts as examples:

```markdown
# api-optimizer

## Common Use Cases

Based on analyzed patterns:

- Calling GitHub API for repository data
- Calling Stripe API for customer information
- Calling SendGrid API for email delivery

## Example Code

```python
# Pattern: GitHub API calls
response = call_api("github.com", "/user/repos", retry=True)
\`\`\`
```

---

## Trend Analysis

Synapse tracks pattern trends over time.

### How It Works

```python
# Analyze pattern frequency over time windows
week_1_frequency = 1.2  # calls/day
week_2_frequency = 1.8  # calls/day
week_3_frequency = 2.4  # calls/day
week_4_frequency = 3.1  # calls/day

# Calculate trend
trend = "increasing"  # 30%+ increase
priority_boost = True  # Apply boost for increasing trends
```

### Priority Adjustments

| Trend | Priority Adjustment |
|-------|-------------------|
| Rapidly increasing (>50%/week) | +2 levels (medium → critical) |
| Increasing (>30%/week) | +1 level (medium → high) |
| Stable (±30%) | No change |
| Decreasing (>30%/week) | -1 level (high → medium) |

### Example

```markdown
### 🔴 database-optimizer (CRITICAL)

**Trend:** Rapidly increasing ⬆️
- Week 1: 1.5 queries/day
- Week 2: 2.3 queries/day
- Week 3: 3.8 queries/day
- Week 4: 6.2 queries/day

**Reason:** Pattern frequency increasing 40% per week
**Priority:** Escalated to CRITICAL due to rapid growth
```

---

## Custom Pattern Definitions

Define custom patterns in configuration.

### Example Configuration

```json
{
  "patterns": {
    "custom_patterns": {
      "pdf_processing": {
        "keywords": ["pdf", "extract", "parse pdf", "pdfplumber"],
        "suggested_skill": "pdf-master",
        "priority_multiplier": 1.5,
        "required_metadata": ["file_size", "pages"]
      },
      "image_manipulation": {
        "keywords": ["image", "resize", "crop", "convert", "pillow"],
        "suggested_skill": "image-wizard",
        "priority_multiplier": 2.0,
        "capabilities": [
          "Image resizing and cropping",
          "Format conversion",
          "Batch processing",
          "Optimization"
        ]
      }
    }
  }
}
```

### How Custom Patterns Work

1. Synapse scans Cortex events for keywords
2. Matches events to custom pattern definitions
3. Applies priority multiplier
4. Uses suggested skill name
5. Includes predefined capabilities in recommendations

---

## Skill Template Customization

Customize generated skill structure.

### Template Variables

```markdown
# {skill_name}

**Pattern Type:** {pattern_type}
**Generated:** {timestamp}

## Detected Use Cases

{context_examples}

## Capabilities

{suggested_capabilities}

## Integration with Cortex

{cortex_api_code}
```

### Create Custom Template

```bash
# Create template directory
mkdir -p .synapse_templates/

# Create custom template
cat > .synapse_templates/my_template.md << 'EOF'
---
name: {skill_name}
description: {description}
---

# {skill_name}

Auto-generated skill for {pattern_type} patterns.

## Quick Start

{quick_start_code}

## Examples

{context_examples}
EOF

# Use custom template
python auto_skill_generator.py --template my_template
```

---

## Integration with External Tools

### GitHub Actions

```yaml
# .github/workflows/synapse.yml
name: Synapse Monitoring

on:
  push:
    branches: [main]
  schedule:
    - cron: '0 */6 * * *'

jobs:
  analyze:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - name: Run Synapse Analysis
        run: |
          python .claude/skills/synapse/scripts/auto_skill_generator.py \
            --dry-run \
--output synapse-report.md

      - name: Create Issue if High Priority Found
        run: |
if grep -q "🔴 CRITICAL" synapse-report.md; then
            gh issue create \
              --title "Synapse: Critical skill recommendation" \
--body-file synapse-report.md \
--label "synapse,auto-generated"
          fi
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
```

### Slack Notifications

```python
#!/usr/bin/env python3
"""Send Synapse recommendations to Slack"""
import requests
import json

# Run analysis
from auto_skill_generator import AutoSkillGenerator

generator = AutoSkillGenerator()
results = generator.run_auto_generation()

# Send to Slack if high-priority recommendations
if results["high_priority_count"] > 0:
    webhook_url = "https://hooks.slack.com/services/YOUR/WEBHOOK/URL"

    message = {
        "text": f"🤖 Synapse found {results['high_priority_count']} high-priority skill recommendations",
        "attachments": [
            {
                "color": "danger",
                "fields": [
                    {
                        "title": "Recommendations",
                        "value": "\n".join(results["skill_names"]),
                        "short": False
                    }
                ]
            }
        ]
    }

    requests.post(webhook_url, json=message)
```

### Jira Integration

```python
#!/usr/bin/env python3
"""Create Jira tickets for Synapse recommendations"""
from jira import JIRA
from auto_skill_generator import AutoSkillGenerator

# Connect to Jira
jira = JIRA(server="https://your-domain.atlassian.net", auth=("email", "token"))

# Run Synapse
generator = AutoSkillGenerator()
recommendations = generator.get_recommendations()

# Create tickets for high-priority recommendations
for rec in recommendations:
    if rec["priority"] in ["critical", "high"]:
        issue = jira.create_issue(
            project="SKILLS",
            summary=f"Implement {rec['skill_name']} skill",
            description=rec["reason"],
            issuetype={"name": "Task"},
labels=["synapse", "auto-generated", rec["priority"]]
        )
        print(f"Created: {issue.key}")
```

---

## Performance Optimization

### Caching Analysis Results

```python
#!/usr/bin/env python3
"""Cache Synapse analysis for faster runs"""
import pickle
from pathlib import Path
from datetime import datetime, timedelta

CACHE_FILE = ".synapse_cache.pkl"
CACHE_TTL_HOURS = 1

def get_cached_analysis():
    if not Path(CACHE_FILE).exists():
        return None

    with open(CACHE_FILE, 'rb') as f:
        cache = pickle.load(f)

    if datetime.now() - cache["timestamp"] < timedelta(hours=CACHE_TTL_HOURS):
        return cache["data"]

    return None

def save_analysis_cache(data):
    with open(CACHE_FILE, 'wb') as f:
        pickle.dump({"timestamp": datetime.now(), "data": data}, f)
```

### Incremental Analysis

```python
# Only analyze new events since last run
last_run_time = load_last_run_timestamp()
new_events = get_cortex_memory(since=last_run_time)

# Only analyze if significant new data
if len(new_events) >= 10:
    run_full_analysis()
else:
    print("Not enough new data, skipping analysis")
```

---

## Multi-Project Analysis

Analyze patterns across multiple projects.

```bash
#!/bin/bash
# Analyze all projects in workspace

for project in ~/workspace/*/; do
    echo "Analyzing: $project"
    cd "$project"

    if [ -d ".claude/skills/cortex" ]; then
python .claude/skills/synapse/scripts/synapse_analyzer.py \
            --output "synapse_$(basename $project).md"
    fi
done

# Merge recommendations
python merge_synapse_reports.py ~/workspace/*/synapse_*.md
```

---

## Debugging and Troubleshooting

### Verbose Mode

```bash
python auto_skill_generator.py --verbose
```

Shows:
- All detected events
- Pattern matching details
- Priority calculations
- Merging logic
- Skill generation steps

### Debug Mode

```bash
Synapse_DEBUG=1 python auto_skill_generator.py
```

Creates debug files:
- `.synapse_debug_events.json` - All Cortex events
- `.synapse_debug_patterns.json` - Detected patterns
- `.synapse_debug_merge.json` - Merging decisions

### Testing Pattern Detection

```python
#!/usr/bin/env python3
"""Test custom pattern matching"""
from synapse_analyzer import SynapseUnifiedAnalyzer

analyzer = SynapseUnifiedAnalyzer(threshold=1)  # Lower threshold for testing

# Add test events to Cortex
from cortex_api import add_cortex_event

add_cortex_event("pdf_processing", "Test PDF extraction")
add_cortex_event("pdf_processing", "Test PDF parsing")

# Run analysis
recs = analyzer.get_all_recommendations()

# Check if pattern detected
pdf_recs = [r for r in recs if r["pattern_type"] == "pdf_processing"]
print(f"PDF recommendations: {len(pdf_recs)}")
```

---

## See Also

- [CONFIGURATION.md](CONFIGURATION.md) - Complete config reference
- [EXAMPLES.md](EXAMPLES.md) - Real-world examples
- [MANUAL_USAGE.md](MANUAL_USAGE.md) - Command-line options
- Main SKILL.md - Synapse overview

```

### references/CONFIGURATION.md

```markdown
# Synapse Configuration Reference

Complete configuration options for Synapse.

## Configuration File

Create `.synapse_config.json` in your project root:

```json
{
  "analysis": {
    "threshold": 5,
    "window_days": 7,
    "auto_threshold": "high"
  },
  "sources": {
    "cortex_memory": true,
    "prd_files": true,
    "task_lists": true,
    "code_analysis": false
  },
  "patterns": {
    "custom_patterns": {},
    "ignore_patterns": [],
    "priority_overrides": {}
  },
  "output": {
    "file": "Synapse_RECOMMENDATIONS.md",
    "format": "markdown",
    "include_examples": true,
    "include_contexts": 5
  },
  "auto_generation": {
    "enabled": true,
    "max_skills_per_run": 5,
    "log_to_cortex": true,
    "dry_run": false
  },
  "skill_generation": {
    "template": "default",
    "include_cortex_api": true,
    "progressive_disclosure": true
  },
  "paths": {
    "skills_dir": ".claude/skills",
    "prd_patterns": ["*PRD*.md", "*REQUIREMENTS*.md", "*ROADMAP*.md"],
    "todo_patterns": ["TODO.md", "TASKS.md", "*TODO*.md"]
  },
  "logging": {
    "enabled": true,
    "file": ".synapse_auto.log",
    "level": "INFO"
  }
}
```

## Configuration Sections

### Analysis Settings

Controls how Synapse analyzes patterns.

```json
"analysis": {
  "threshold": 5,
  "window_days": 7,
  "auto_threshold": "high"
}
```

**Options:**

- **`threshold`** (int, default: 5)
  - Minimum pattern occurrences to generate recommendation
  - Lower = more sensitive (more skills recommended)
  - Higher = less sensitive (only frequent patterns)
  - Recommended range: 2-10

- **`window_days`** (int, default: 7)
  - Number of days to analyze in Cortex memory
  - Shorter window = recent patterns only
  - Longer window = strategic patterns
  - Recommended range: 3-30

- **`auto_threshold`** (string, default: "high")
  - Minimum priority to auto-generate skills
  - Options: "low" | "medium" | "high" | "critical"
  - "high" = conservative (only high/critical)
  - "medium" = moderate (medium and above)
  - "critical" = very conservative (only critical)

### Source Settings

Controls which sources Synapse analyzes.

```json
"sources": {
  "cortex_memory": true,    // Analyze Cortex patterns
  "prd_files": true,        // Analyze PRD requirements
  "task_lists": true,       // Analyze TODO files
  "code_analysis": false    // Analyze codebase (future)
}
```

**Options:**

- **`cortex_memory`** (bool, default: true)
  - Enable Cortex memory pattern detection
  - Recommended: true (core feature)

- **`prd_files`** (bool, default: true)
  - Enable PRD file analysis
  - Set false if no PRD files in project

- **`task_lists`** (bool, default: true)
  - Enable TODO/task file analysis
  - Set false if using external task tracking

- **`code_analysis`** (bool, default: false)
  - Enable codebase analysis (future feature)
  - Currently not implemented

### Pattern Settings

Advanced pattern customization.

```json
"patterns": {
  "custom_patterns": {
    "pdf_processing": {
      "keywords": ["pdf", "extract", "parse pdf"],
      "suggested_skill": "pdf-master",
      "priority_multiplier": 1.5
    }
  },
  "ignore_patterns": ["debug", "test_event"],
  "priority_overrides": {
    "security": "critical"
  }
}
```

**Options:**

- **`custom_patterns`** (object, default: {})
  - Define custom pattern detection rules
  - Keys: pattern type names
  - Values: pattern configuration objects

- **`ignore_patterns`** (array, default: [])
  - Event types to ignore during analysis
  - Useful for excluding debug/test events

- **`priority_overrides`** (object, default: {})
  - Force specific priorities for pattern types
  - Keys: pattern types
  - Values: "low" | "medium" | "high" | "critical"

### Output Settings

Controls recommendation output format.

```json
"output": {
  "file": "Synapse_RECOMMENDATIONS.md",
  "format": "markdown",
  "include_examples": true,
  "include_contexts": 5
}
```

**Options:**

- **`file`** (string, default: "Synapse_RECOMMENDATIONS.md")
  - Output file path
  - Can be relative or absolute

- **`format`** (string, default: "markdown")
  - Output format
  - Options: "markdown" | "json"

- **`include_examples`** (bool, default: true)
  - Include example contexts in recommendations
  - Set false for more concise output

- **`include_contexts`** (int, default: 5)
  - Number of example contexts to include
  - 0 = no examples
  - Recommended range: 3-10

### Auto-Generation Settings

Controls automatic skill generation behavior.

```json
  "auto_generation": {
    "enabled": true,
    "max_skills_per_run": 5,
    "log_to_cortex": true,
    "dry_run": false
}
```

**Options:**

- **`enabled`** (bool, default: true)
  - Enable automatic skill generation
  - Set false to only generate recommendations

- **`max_skills_per_run`** (int, default: 5)
  - Maximum skills to generate in one run
  - Prevents generating too many skills at once
  - 0 = unlimited

- **`log_to_cortex`** (bool, default: true)
  - Record skill generation events in Cortex
  - Recommended: true (enables tracking)

- **`dry_run`** (bool, default: false)
  - Analyze only, don't create skills
  - Set true for testing configuration

### Skill Generation Settings

Controls how generated skills are structured.

```json
  "skill_generation": {
    "template": "default",
    "include_cortex_api": true,
    "progressive_disclosure": true
}
```

**Options:**

- **`template`** (string, default: "default")
  - Skill template to use
  - Options: "default" | "minimal" | "advanced"

- **`include_cortex_api`** (bool, default: true)
  - Auto-integrate Cortex API in generated skills
  - Recommended: true (enables pattern tracking)

- **`progressive_disclosure`** (bool, default: true)
  - Apply progressive disclosure principles
  - Creates references/ directory for details

### Path Settings

Controls file and directory locations.

```json
"paths": {
  "skills_dir": ".claude/skills",
  "prd_patterns": ["*PRD*.md", "*REQUIREMENTS*.md"],
  "todo_patterns": ["TODO.md", "*TODO*.md"]
}
```

**Options:**

- **`skills_dir`** (string, default: ".claude/skills")
  - Directory where skills are stored

- **`prd_patterns`** (array, default: ["*PRD*.md", "*REQUIREMENTS*.md", "*ROADMAP*.md"])
  - Glob patterns for PRD files

- **`todo_patterns`** (array, default: ["TODO.md", "TASKS.md", "*TODO*.md"])
  - Glob patterns for TODO files

### Logging Settings

Controls log output.

```json
"logging": {
  "enabled": true,
  "file": ".synapse_auto.log",
  "level": "INFO"
}
```

**Options:**

- **`enabled`** (bool, default: true)
  - Enable logging

- **`file`** (string, default: ".synapse_auto.log")
  - Log file path

- **`level`** (string, default: "INFO")
  - Log level
  - Options: "DEBUG" | "INFO" | "WARNING" | "ERROR"

## Example Configurations

### Conservative (Fewer Skills)

```json
{
  "analysis": {
    "threshold": 10,
    "window_days": 14,
    "auto_threshold": "critical"
  },
  "auto_generation": {
    "max_skills_per_run": 2
  }
}
```

Only generates skills for very frequent patterns.

### Aggressive (More Skills)

```json
{
  "analysis": {
    "threshold": 2,
    "window_days": 3,
    "auto_threshold": "medium"
  },
  "auto_generation": {
    "max_skills_per_run": 10
  }
}
```

Generates skills for even infrequent patterns.

### Cortex-Only Analysis

```json
{
  "sources": {
    "cortex_memory": true,
    "prd_files": false,
    "task_lists": false
  }
}
```

Only analyzes actual usage patterns from Cortex.

### Manual Mode (No Auto-Generation)

```json
{
  "auto_generation": {
    "enabled": false,
    "dry_run": true
  }
}
```

Only creates recommendations, never auto-generates.

### Custom Patterns

```json
{
  "patterns": {
    "custom_patterns": {
      "database_query": {
        "keywords": ["sql", "query", "database", "SELECT", "INSERT"],
        "suggested_skill": "db-optimizer",
        "priority_multiplier": 2.0
      },
      "image_processing": {
        "keywords": ["image", "resize", "convert", "png", "jpg"],
        "suggested_skill": "image-master",
        "priority_multiplier": 1.5
      }
    },
    "ignore_patterns": ["debug_log", "test_", "temp_"]
  }
}
```

### Security-Focused

```json
{
  "patterns": {
    "priority_overrides": {
      "security": "critical",
      "authentication": "critical",
      "authorization": "critical",
      "encryption": "high"
    }
  }
}
```

Forces security-related patterns to high/critical priority.

## Command-Line Override

Command-line arguments override config file:

```bash
# Config says threshold=5, this uses threshold=3
python auto_skill_generator.py --threshold 3

# Config says auto_threshold=high, this uses medium
python auto_skill_generator.py --auto-threshold medium
```

## Environment Variables

```bash
# Override config file location
export SYNAPSE_CONFIG="/path/to/custom_config.json"

# Override output file
export SYNAPSE_OUTPUT="/path/to/custom_output.md"

python auto_skill_generator.py
```

## Validation

Validate your configuration:

```bash
python .claude/skills/synapse/scripts/validate_config.py
```

Output:
```
✅ Configuration valid
   - threshold: 5 (valid range: 1-100)
   - window_days: 7 (valid range: 1-365)
   - auto_threshold: high (valid)
   - All paths exist
   - All patterns valid
```

## See Also

- [MANUAL_USAGE.md](MANUAL_USAGE.md) - Command-line options
- [ADVANCED.md](ADVANCED.md) - Advanced features
- [EXAMPLES.md](EXAMPLES.md) - Real-world examples
- Main SKILL.md - Synapse overview

```

### references/MANUAL_USAGE.md

```markdown
# Synapse Manual Usage

Complete command-line reference for Synapse tools.

## Auto-Generator (Recommended)

Analyzes patterns and automatically generates skills.

### Basic Usage

```bash
# Run with defaults (threshold=5, days=7, auto-threshold=high)
python .claude/skills/synapse/scripts/auto_skill_generator.py
```

This will:
1. Analyze Cortex memory for patterns
2. Analyze PRD files for requirements
3. Analyze task lists for TODOs
4. Generate skills for HIGH and CRITICAL priorities
5. Log generated skills in Cortex memory

### Command-Line Options

```bash
python .claude/skills/synapse/scripts/auto_skill_generator.py \
  --threshold 3 \           # Pattern occurrence threshold (default: 5)
  --days 14 \               # Analysis window in days (default: 7)
  --auto-threshold medium \ # Auto-generate if priority >= this (default: high)
  --dry-run \               # Analyze only, don't generate skills
  --output custom.md        # Custom output file (default: Synapse_RECOMMENDATIONS.md)
```

### Options Reference

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--threshold` | int | 5 | Minimum pattern occurrences to recommend |
| `--days` | int | 7 | Number of days to analyze |
| `--auto-threshold` | str | high | Auto-generate if priority >= this (low/medium/high/critical) |
| `--dry-run` | flag | false | Analyze only, don't create skills |
| `--output` | str | Synapse_RECOMMENDATIONS.md | Output file path |
| `--config` | str | .synapse_config.json | Config file path |
| `--verbose` | flag | false | Detailed output |
| `--quiet` | flag | false | Minimal output |

### Examples

#### Dry Run (Analysis Only)

```bash
# See what would be generated without creating skills
python .claude/skills/synapse/scripts/auto_skill_generator.py --dry-run
```

Output:
```
🤖 Synapse Auto Skill Generator (DRY RUN MODE)

📊 Analysis Results:
   Total recommendations: 3
   High priority: 2
   Medium priority: 1

🔧 Would generate (not actually creating):
   ✓ api-optimizer (priority: critical)
   ✓ data-transformer (priority: high)
   ⊗ deploy-helper (priority: medium - below threshold)

💾 Recommendations saved to: Synapse_RECOMMENDATIONS.md
```

#### Lower Threshold

```bash
# More sensitive - generate skills for patterns >= 3 occurrences
python .claude/skills/synapse/scripts/auto_skill_generator.py --threshold 3
```

#### Longer Analysis Window

```bash
# Analyze last 30 days instead of 7
python .claude/skills/synapse/scripts/auto_skill_generator.py --days 30
```

#### Generate MEDIUM Priority Skills

```bash
# Auto-generate for medium and higher (more aggressive)
python .claude/skills/synapse/scripts/auto_skill_generator.py --auto-threshold medium
```

#### Conservative Mode

```bash
# Only generate CRITICAL skills
python .claude/skills/synapse/scripts/auto_skill_generator.py --auto-threshold critical
```

#### Verbose Output

```bash
# Show detailed analysis
python .claude/skills/synapse/scripts/auto_skill_generator.py --verbose
```

Output:
```
🤖 Synapse Auto Skill Generator

🔍 Analyzing Cortex memory...
   Found 47 events in last 7 days
   Detected patterns:
     - api_call: 24 occurrences (3.4/day)
     - data_processing: 15 occurrences (2.1/day)
     - error: 8 occurrences (1.1/day)

🔍 Analyzing PRD files...
   Found 2 PRD files:
     - PROJECT_PRD.md (18 tasks)
     - TEST_REQUIREMENTS.md (7 tasks)

   Task breakdown:
     - testing: 15 tasks
     - api: 7 tasks
     - deployment: 3 tasks

🔍 Analyzing task lists...
   Found 1 TODO file:
     - TODO.md (12 tasks)

   Task types:
     - deployment: 5 tasks
     - testing: 4 tasks
     - docs: 3 tasks

🧮 Merging and prioritizing...
   Merged 'api' patterns (Cortex + PRD) → CRITICAL
   Merged 'testing' patterns (PRD + TODO) → HIGH

📊 Final recommendations: 3
   🔴 api-optimizer (critical)
   🟠 test-guardian (high)
   🟡 deploy-helper (medium)

🔧 Generating skills (auto-threshold: high)...
   ✅ api-optimizer created successfully
   ✅ test-guardian created successfully
   ⊗ deploy-helper skipped (below threshold)

✅ Auto-generation complete!
   Skills created: 2
   Skills skipped: 1
```

---

## Analyzer (Analysis Only)

Generates recommendations without auto-creating skills.

### Basic Usage

```bash
# Analyze and create Synapse_RECOMMENDATIONS.md
python .claude/skills/synapse/scripts/synapse_analyzer.py
```

### Command-Line Options

```bash
python .claude/skills/synapse/scripts/synapse_analyzer.py \
  --threshold 3 \
  --days 14 \
  --output MY_RECOMMENDATIONS.md \
  --format markdown \
--config .synapse_config.json
```

### Options Reference

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--threshold` | int | 5 | Minimum pattern occurrences |
| `--days` | int | 7 | Analysis window in days |
| `--output` | str | Synapse_RECOMMENDATIONS.md | Output file path |
| `--format` | str | markdown | Output format (markdown/json) |
| `--config` | str | .synapse_config.json | Config file path |
| `--cortex-only` | flag | false | Only analyze Cortex patterns |
| `--prd-only` | flag | false | Only analyze PRD files |
| `--tasks-only` | flag | false | Only analyze task lists |

### Examples

#### JSON Output

```bash
# Generate machine-readable JSON
python .claude/skills/synapse/scripts/synapse_analyzer.py --format json --output recs.json
```

#### Cortex Analysis Only

```bash
# Only analyze Cortex memory patterns
python .claude/skills/synapse/scripts/synapse_analyzer.py --cortex-only
```

#### PRD Analysis Only

```bash
# Only analyze PRD files
python .claude/skills/synapse/scripts/synapse_analyzer.py --prd-only
```

#### Multiple Analysis Runs

```bash
# Short-term patterns (last 3 days, lower threshold)
python .claude/skills/synapse/scripts/synapse_analyzer.py \
  --days 3 \
  --threshold 2 \
  --output Synapse_SHORT_TERM.md

# Long-term patterns (last 30 days, higher threshold)
python .claude/skills/synapse/scripts/synapse_analyzer.py \
  --days 30 \
  --threshold 10 \
  --output Synapse_LONG_TERM.md
```

---

## Monitoring Script

Wrapper for automatic periodic execution.

### Usage

```bash
# Run monitoring (calls auto_skill_generator.py)
/path/to/.claude/skills/synapse/scripts/synapse_auto_watch.sh
```

### Cron Setup

```bash
# Edit crontab
crontab -e

# Add one of these lines:

# Every 30 minutes
*/30 * * * * /path/to/.claude/skills/synapse/scripts/synapse_auto_watch.sh

# Every hour
0 * * * * /path/to/.claude/skills/synapse/scripts/synapse_auto_watch.sh

# Twice daily (9am and 5pm)
0 9,17 * * * /path/to/.claude/skills/synapse/scripts/synapse_auto_watch.sh

# Daily at midnight
0 0 * * * /path/to/.claude/skills/synapse/scripts/synapse_auto_watch.sh
```

### Git Hook Setup

```bash
# Add to .git/hooks/post-commit
cat >> .git/hooks/post-commit << 'EOF'
#!/bin/bash
# Run Synapse in background after commits
/path/to/.claude/skills/synapse/scripts/synapse_auto_watch.sh &
EOF

chmod +x .git/hooks/post-commit
```

---

## Configuration File

Create `.synapse_config.json` for persistent settings:

```json
{
  "analysis": {
    "threshold": 5,
    "window_days": 7,
    "auto_threshold": "high"
  },
  "sources": {
    "cortex_memory": true,
    "prd_files": true,
    "task_lists": true,
    "code_analysis": false
  },
  "output": {
    "file": "Synapse_RECOMMENDATIONS.md",
    "format": "markdown",
    "include_examples": true
  },
  "auto_generation": {
    "enabled": true,
    "max_skills_per_run": 5,
    "log_to_cortex": true
  }
}
```

Then run without arguments:
```bash
# Uses config file settings
python .claude/skills/synapse/scripts/auto_skill_generator.py
```

Command-line args override config file.

---

## Return Codes

Synapse scripts use standard exit codes:

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | General error |
| 2 | Invalid arguments |
| 3 | Cortex not available |
| 4 | No patterns detected |
| 5 | Skill generation failed |

### Example Usage in Scripts

```bash
#!/bin/bash

python .claude/skills/synapse/scripts/auto_skill_generator.py
exit_code=$?

if [ $exit_code -eq 0 ]; then
    echo "✅ Synapse ran successfully"
elif [ $exit_code -eq 4 ]; then
    echo "ℹ️  No patterns detected - nothing to do"
else
    echo "❌ Synapse failed with code $exit_code"
fi
```

---

## Logs

Synapse logs to `.synapse_auto.log`:

```bash
# View recent logs
tail -n 50 .synapse_auto.log

# Watch logs in real-time
tail -f .synapse_auto.log

# Search for errors
grep ERROR .synapse_auto.log

# Find generated skills
grep "created successfully" .synapse_auto.log
```

---

## Troubleshooting

### No Patterns Detected

```bash
# Lower threshold to detect more patterns
python .claude/skills/synapse/scripts/auto_skill_generator.py --threshold 2
```

### Cortex Not Available

```bash
# Check Cortex installation
python .claude/skills/cortex/scripts/cortex_api.py

# Reinstall if needed
cd .claude/skills/cortex/scripts && ./install.sh
```

### Skills Not Generating

```bash
# Check with dry-run to see what would happen
python .claude/skills/synapse/scripts/auto_skill_generator.py --dry-run --verbose

# Try lower auto-threshold
python .claude/skills/synapse/scripts/auto_skill_generator.py --auto-threshold medium
```

### Permission Denied

```bash
# Make scripts executable
chmod +x .claude/skills/synapse/scripts/*.py
chmod +x .claude/skills/scripts/*.sh
```

---

## Advanced Usage

### Custom Analysis Pipeline

```python
#!/usr/bin/env python3
"""Custom Synapse pipeline"""
import sys
from pathlib import Path

# Add Synapse to path
synapse_scripts = Path(".claude/skills/synapse/scripts")
sys.path.insert(0, str(synapse_scripts))

from synapse_analyzer import SynapseUnifiedAnalyzer
from auto_skill_generator import AutoSkillGenerator

# Custom analyzer
analyzer = SynapseUnifiedAnalyzer(threshold=3, window_days=14)
recommendations = analyzer.get_all_recommendations()

# Filter for specific pattern types
api_recs = [r for r in recommendations if r['pattern_type'] == 'api_call']

# Custom generation logic
if len(api_recs) > 0:
    generator = AutoSkillGenerator(auto_threshold="medium")
    for rec in api_recs:
        generator.generate_skill_with_creator(rec)
```

### Integration with CI/CD

```yaml
# .github/workflows/synapse.yml
name: Synapse Analysis

on:
  push:
    branches: [main]
  schedule:
    - cron: '0 */6 * * *'  # Every 6 hours

jobs:
  analyze:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Run Synapse
        run: |
          python .claude/skills/synapse/scripts/auto_skill_generator.py --dry-run
      - name: Upload recommendations
        uses: actions/upload-artifact@v2
        with:
name: synapse-recommendations
          path: Synapse_RECOMMENDATIONS.md
```

---

## See Also

- [CONFIGURATION.md](CONFIGURATION.md) - Complete config reference
- [INSTALLATION.md](INSTALLATION.md) - Setup guide
- [EXAMPLES.md](EXAMPLES.md) - Real-world examples
- Main SKILL.md - Synapse overview

```

### references/EXAMPLES.md

```markdown
# Synapse Real-World Examples

Real scenarios showing how Synapse detects patterns and generates skills.

## Example 1: API Integration Skill

### Scenario

Developer working on a project that integrates with multiple external APIs.

### Cortex Events (Over 7 Days)

```
Day 1:
- api_call: Called GitHub API to fetch repos
- api_call: Called Stripe API for customer data
- error: GitHub API rate limit exceeded

Day 2:
- api_call: Called Stripe API for invoices
- api_call: Called SendGrid API for email
- error: Stripe API timeout

Day 3:
- api_call: Called GitHub API for issues
- api_call: Called Slack API for notifications
- api_call: Called Stripe API for subscriptions

... (continuing through Day 7)

Total: 24 API calls, 5 API errors
```

### Synapse Analysis

```bash
python .claude/skills/synapse/scripts/auto_skill_generator.py
```

**Detected Pattern:**
- Pattern type: `api_call`
- Count: 24 occurrences
- Frequency: 3.4 times/day
- Priority: **CRITICAL** (frequency >= 2/day)

**Recommendation:**

```markdown
### 🔴 api-optimizer (CRITICAL)

**Pattern Type:** api_call
**Frequency:** 3.4 times/day (24 total)
**Reason:** Frequent API operations with error patterns detected

**Example Contexts:**
- Called GitHub API (8 times)
- Called Stripe API (10 times)
- Called SendGrid API (4 times)
- Called Slack API (2 times)

**Suggested Capabilities:**
- Rate limiting and backoff
- Retry logic for failed requests
- Response caching with TTL
- Error handling patterns
- Request logging and monitoring
```

**Auto-Generated Skill:**

Synapse automatically creates `.claude/skills/api-optimizer/` with:
- SKILL.md with API best practices
- scripts/api_helper.py with retry/caching logic
- Cortex API integration to log API calls

### Result

Next time developer mentions "call API", Claude uses the `api-optimizer` skill automatically, applying rate limiting and retry logic.

---

## Example 2: Testing Skill from PRD

### Scenario

Project has extensive testing requirements in PRD.

### PRD File (PROJECT_PRD.md)

```markdown
## Testing Requirements

- [ ] Unit tests for auth module
- [ ] Integration tests for API endpoints
- [ ] End-to-end tests for checkout flow
- [ ] Performance tests for database queries
- [ ] Security tests for authentication
- [ ] Regression tests for bug fixes
- [ ] Test data generators
- [ ] Mock external services
- [ ] Code coverage > 80%
- [ ] Automated test runs in CI/CD
- [ ] Test documentation
- [ ] Visual regression tests
- [ ] Load testing for API
- [ ] Accessibility tests
- [ ] Cross-browser compatibility tests

Total: 15 testing tasks
```

### Synapse Analysis

```bash
python .claude/skills/synapse/scripts/synapse_analyzer.py --prd-only
```

**Detected Pattern:**
- Pattern type: `testing`
- Task count: 15 tasks
- Source: PRD analysis
- Priority: **HIGH** (10-20 tasks)

**Recommendation:**

```markdown
### 🟠 test-guardian (HIGH)

**Pattern Type:** testing
**Source:** PRD analysis
**Task Count:** 15 test-related tasks

**PRD Files:**
- PROJECT_PRD.md (15 tasks)

**Suggested Capabilities:**
- Test case generation
- Mock data creation
- Coverage analysis
- Test runner integration
- CI/CD test automation
```

**Auto-Generated Skill:**

```bash
python .claude/skills/synapse/scripts/auto_skill_generator.py
```

Creates `.claude/skills/test-guardian/` with:
- SKILL.md with testing best practices
- scripts/test_generator.py for test scaffolding
- Coverage analysis tools
- Mock data generators

---

## Example 3: Combined Pattern (Cortex + PRD)

### Scenario

Data processing appears in both Cortex memory AND PRD requirements.

### Cortex Events

```
- data_processing: Parsed CSV file with user data (5 times)
- data_processing: Transformed JSON API response (6 times)
- data_processing: Validated data against schema (4 times)

Total: 15 data processing events over 7 days
Frequency: 2.1 times/day
```

### PRD Tasks

```markdown
## Data Pipeline Requirements

- [ ] ETL pipeline for user data
- [ ] CSV import functionality
- [ ] JSON transformation layer
- [ ] Data validation rules
- [ ] Schema evolution support
- [ ] Error handling for malformed data
- [ ] Bulk data operations

Total: 7 data processing tasks
```

### Synapse Analysis

```bash
python .claude/skills/synapse/scripts/auto_skill_generator.py
```

**Pattern Merging:**

```
Cortex pattern: data_processing
  Count: 15
  Frequency: 2.1/day
  Individual priority: HIGH

PRD pattern: data_processing
  Task count: 7
  Individual priority: MEDIUM

MERGED priority: CRITICAL
  (Cortex HIGH + PRD MEDIUM = CRITICAL when combined)
```

**Recommendation:**

```markdown
### 🔴 data-transformer (CRITICAL)

**Pattern Type:** data_processing
**Source:** Cortex patterns + PRD analysis
**Cortex Frequency:** 2.1 times/day (15 total)
**PRD Tasks:** 7 ETL-related tasks

**Combined Reason:**
Pattern detected in both actual usage (Cortex) and planned requirements (PRD),
indicating critical need for dedicated data processing skill.

**Example Contexts (Cortex):**
- Parsed CSV files (5 times)
- Transformed JSON responses (6 times)
- Validated data schemas (4 times)

**Requirements (PRD):**
- ETL pipeline
- CSV/JSON handling
- Data validation
- Schema support

**Suggested Capabilities:**
- CSV/JSON/XML parsing
- Data validation and cleaning
- Format conversions
- Schema validation
- Bulk operations
- Error handling
```

**Result:**

Higher priority due to merging → Immediate auto-generation of `data-transformer` skill.

---

## Example 4: Error Pattern Detection

### Scenario

Recurring error pattern suggests need for error-handling skill.

### Cortex Events

```
Day 1:
- error: Database connection timeout
- error_resolved: Implemented retry logic

Day 2:
- error: External API unavailable
- error_resolved: Added fallback mechanism

Day 3:
- error: Database connection timeout (again)
- error: JSON parsing failed on malformed input

Day 4:
- error_resolved: Added connection pooling

... continuing

Total: 12 errors in 7 days
Frequency: 1.7 times/day
```

### Synapse Analysis

```bash
python .claude/skills/synapse/scripts/auto_skill_generator.py --verbose
```

**Detected Pattern:**
- Pattern type: `error`
- Count: 12 occurrences
- Frequency: 1.7 times/day
- Priority: **HIGH** (frequency >= 1/day)

**Recommendation:**

```markdown
### 🟠 error-guardian (HIGH)

**Pattern Type:** error
**Frequency:** 1.7 times/day (12 total)
**Reason:** Recurring error patterns requiring systematic handling

**Example Error Types:**
- Database timeouts (4 times)
- API unavailability (3 times)
- JSON parsing errors (2 times)
- Network issues (3 times)

**Resolution Patterns Detected:**
- Retry logic
- Fallback mechanisms
- Connection pooling
- Input validation

**Suggested Capabilities:**
- Centralized error handling
- Retry strategies (exponential backoff)
- Circuit breaker pattern
- Fallback mechanisms
- Error logging and monitoring
- Input validation helpers
```

**Auto-Generated Skill:**

Creates error handling skill with patterns learned from previous resolutions.

---

## Example 5: No Generation (Pattern Below Threshold)

### Scenario

Pattern detected but below threshold.

### Cortex Events

```
- deployment: Deployed to staging (2 times)
- deployment: Updated production config (1 time)

Total: 3 deployment events in 7 days
Frequency: 0.4 times/day
```

### Synapse Analysis

```bash
python .claude/skills/synapse/scripts/auto_skill_generator.py --dry-run
```

**Output:**

```
📊 Analysis Results:
   Total recommendations: 0

⚠️  Patterns below threshold (monitoring):
   - deployment: 3 occurrences (threshold: 5)

💡 These patterns are being monitored. If frequency increases,
   they will be recommended in future analyses.
```

**Result:**

No skill generated. Pattern monitored for future increase.

If deployment frequency increases to 5+ occurrences, Synapse will automatically recommend `deploy-sage` skill.

---

## Example 6: Preventing Duplicates

### Scenario

Pattern detected but skill already exists.

### Existing Skills

```
.claude/skills/
├── api-optimizer/
├── test-guardian/
└── cortex/
```

### Cortex Events

```
- api_call: Called GitHub API (occurred 20 times in 7 days)
Frequency: 2.9 times/day
Priority: CRITICAL
```

### Synapse Analysis

```bash
python .claude/skills/synapse/scripts/auto_skill_generator.py
```

**Output:**

```
🔍 Analyzing patterns...
   Detected pattern: api_call (20 occurrences, CRITICAL)

🔍 Checking existing skills...
   ✓ api-optimizer already exists

⊗ Skipping api-optimizer (already exists)

✅ Analysis complete: 0 new skills generated
```

**Result:**

No duplicate created. Existing `api-optimizer` skill is sufficient.

---

## Example 7: Custom Threshold

### Scenario

Developer wants earlier skill generation (more aggressive).

### Command

```bash
# Lower threshold to 3 occurrences instead of 5
python .claude/skills/synapse/scripts/auto_skill_generator.py \
  --threshold 3 \
  --auto-threshold medium
```

### Cortex Events

```
- pdf_processing: Extracted text from PDF (4 times in 7 days)
Frequency: 0.6 times/day
```

**With Default Settings (threshold=5):**
- Pattern count: 4
- Threshold: 5
- Result: ❌ Not recommended (below threshold)

**With Custom Settings (threshold=3):**
- Pattern count: 4
- Threshold: 3
- Priority: MEDIUM (frequency 0.6/day)
- Auto-threshold: medium
- Result: ✅ `pdf-processor` skill auto-generated

---

## Example 8: Long-Term Analysis

### Scenario

Analyze patterns over longer period for strategic planning.

### Command

```bash
# Analyze last 30 days with higher threshold
python .claude/skills/synapse/scripts/synapse_analyzer.py \
  --days 30 \
  --threshold 15 \
  --output Synapse_LONG_TERM.md
```

### Results

```markdown
# Synapse Skill Recommendations (30-Day Analysis)

## Recommended Skills

### 1. 🔴 database-optimizer (CRITICAL)
**Count:** 67 database operations in 30 days
**Average:** 2.2 times/day
**Trend:** Increasing (week 1: 1.5/day → week 4: 3.0/day)

### 2. 🟠 security-auditor (HIGH)
**Count:** 42 security-related events in 30 days
**Average:** 1.4 times/day
**Trend:** Stable
```

Longer window reveals strategic needs not visible in 7-day window.

---

## Example 9: Multi-Source Workflow

### Scenario

Complete workflow showing all analysis sources.

### 1. Developer Works

```bash
# Developer uses Claude to build features
# Cortex automatically tracks:
- api_call: GitHub API (multiple times)
- data_processing: CSV imports (multiple times)
- error: Connection timeouts (few times)
```

### 2. PRD Exists

```markdown
## PROJECT_PRD.md

### Testing Requirements
- [ ] Unit tests
- [ ] Integration tests
... (12 total test tasks)

### API Integration
- [ ] GitHub OAuth
- [ ] Stripe payments
... (8 total API tasks)
```

### 3. TODOs Tracked

```markdown
## TODO.md

- [ ] Deploy to staging
- [ ] Set up production monitoring
- [ ] Configure CI/CD
... (6 deployment tasks)
```

### 4. Synapse Analyzes (Automatic)

```bash
# Runs every 30 minutes via cron
*/30 * * * * /path/to/.claude/skills/synapse/scripts/synapse_auto_watch.sh
```

### 5. Results

```
🔴 api-optimizer (CRITICAL)
   - Cortex: 24 api_calls
   - PRD: 8 API tasks
   - Combined priority: CRITICAL
   → AUTO-GENERATED ✅

🟠 test-guardian (HIGH)
   - PRD: 12 test tasks
   - Priority: HIGH
   → AUTO-GENERATED ✅

🟡 deploy-helper (MEDIUM)
   - TODO: 6 deployment tasks
   - Priority: MEDIUM
   → RECOMMENDED (not auto-generated)
```

### 6. Developer Benefits

Next session, developer has:
- `api-optimizer` skill ready for GitHub/Stripe integration
- `test-guardian` skill for automated testing
- Recommendation for `deploy-helper` to consider

All generated automatically based on actual work patterns!

---

## See Also

- [MANUAL_USAGE.md](MANUAL_USAGE.md) - Command-line options
- [OUTPUT_FORMAT.md](OUTPUT_FORMAT.md) - Output specification
- [ADVANCED.md](ADVANCED.md) - Advanced features
- Main SKILL.md - Synapse overview

```

synapse | SkillHub