---
name: N8N Nervous System
description: |
  Genesis's nervous system for autonomous workflow orchestration.
  n8n provides the reactive layer that triggers actions based on events,
  manages workflows, and enables 24/7 autonomous operation.

  WHEN TO USE:
  - "Create an n8n workflow"
  - "Set up automation for [task]"
  - "Trigger when [event] happens"
  - "Schedule [task] to run automatically"
  - "Connect to external service"
  - Building autonomous revenue pipelines
  - Setting up webhook handlers
  - Creating scheduled tasks

  CAPABILITIES:
  - Workflow creation and management
  - Webhook and cron triggers
  - 541 pre-built node integrations
  - Execution monitoring
  - Credential management
  - Tag and project organization

allowed-tools:
  - Read
  - Write
  - Bash
  - mcp__n8n__*
---

# N8N Nervous System

## Purpose

n8n is Genesis's **nervous system** - the reactive layer that enables autonomous operation. While Claude is the brain (reasoning) and Modal runs agents (execution), n8n handles the triggers, routing, and integration that make 24/7 operation possible.

## Architecture Role

```
┌─────────────────────────────────────────────────────────────────┐
│                    GENESIS AUTONOMOUS LAYER                      │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  ┌─────────────┐                      ┌─────────────┐           │
│  │   CLAUDE    │◄────── Reasoning ───►│   MODAL     │           │
│  │   (Brain)   │                      │  (Agents)   │           │
│  └──────┬──────┘                      └──────┬──────┘           │
│         │                                    │                   │
│         └────────────────┬───────────────────┘                   │
│                          │                                       │
│                          ▼                                       │
│         ┌─────────────────────────────────┐                     │
│         │      N8N (NERVOUS SYSTEM)       │                     │
│         │                                 │                     │
│         │  • Webhooks (sensory input)     │                     │
│         │  • Cron (heartbeat)             │                     │
│         │  • Workflows (reflexes)         │                     │
│         │  • Integrations (motor output)  │                     │
│         └─────────────────────────────────┘                     │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘
```

## Genesis n8n Instance

- **URL**: Elestio managed service
- **Cost**: $16/month (cornerstone infrastructure)
- **Uptime**: 24/7 managed
- **Access**: Via API key

## MCP Integration

Two MCP servers provide n8n capabilities:

### 1. n8n-mcp (Documentation + Workflow Building)
```json
{
  "mcpServers": {
    "n8n-mcp": {
      "command": "npx",
      "args": ["n8n-mcp"],
      "env": {
        "MCP_MODE": "stdio",
        "N8N_API_URL": "YOUR_N8N_URL",
        "N8N_API_KEY": "YOUR_API_KEY"
      }
    }
  }
}
```

**Capabilities**:
- Smart node search (541 nodes)
- Property extraction
- 2,646 real-world examples
- Workflow validation

### 2. n8n-mcp-server (API Operations)
```json
{
  "mcpServers": {
    "n8n-api": {
      "command": "npx",
      "args": ["@illuminaresolutions/n8n-mcp-server"],
      "env": {
        "N8N_HOST": "YOUR_N8N_URL",
        "N8N_API_KEY": "YOUR_API_KEY"
      }
    }
  }
}
```

**Capabilities** (33 tools):
- Workflow CRUD operations
- Execute workflows
- Manage credentials
- Tag management
- Execution history
- Security audits

## Core Workflow Patterns

### Pattern 1: Webhook → Process → Action
```
[Webhook Trigger] → [Parse Data] → [Claude API] → [Action Node]
```
**Use for**: Inbound leads, form submissions, API callbacks

### Pattern 2: Cron → Query → Update
```
[Cron Trigger] → [Read State] → [Process] → [Update State]
```
**Use for**: Scheduled maintenance, daily reports, health checks

### Pattern 3: Event → Evaluate → Branch
```
[Trigger] → [IF Node] → [Branch A: High Priority]
                     → [Branch B: Normal]
                     → [Branch C: Low Priority]
```
**Use for**: Lead scoring, alert routing, conditional logic

### Pattern 4: Multi-Step Pipeline
```
[Trigger] → [Step 1] → [Step 2] → [Step 3] → [Notify]
                ↓
          [Error Handler] → [Alert]
```
**Use for**: Complex automations with error handling

## Genesis Nervous System Workflows

### 1. Memory Maintenance (Weekly)
```yaml
trigger: Cron (Sunday 3 AM)
steps:
  1. Read memory stats
  2. Identify stale memories
  3. Call pruning script (Modal)
  4. Update HANDOFF.md
  5. Notify on completion
```

### 2. YouTube Monitor (Daily)
```yaml
trigger: Cron (9 AM)
steps:
  1. Check IndyDevDan RSS
  2. If new video:
     a. Fetch transcript
     b. Send to Claude API
     c. Generate skill
     d. Commit to repo
  3. Update knowledge graph
```

### 3. Lead Handler (On Webhook)
```yaml
trigger: Webhook (form submission)
steps:
  1. Parse lead data
  2. Score lead (Claude API)
  3. If score > 70:
     a. Add to CRM
     b. Schedule follow-up
     c. Send welcome email
  4. Store in outcome memory
```

### 4. Revenue Tracker (Hourly)
```yaml
trigger: Cron (hourly)
steps:
  1. Query payment provider
  2. Calculate daily revenue
  3. If below threshold:
     a. Trigger marketing workflow
  4. Update revenue memory
  5. Generate daily summary
```

## Trigger Memory Implementation

n8n IS the trigger memory execution layer:

```
┌─────────────────────────────────────────────────────────────┐
│                    TRIGGER MEMORY                            │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  Condition              n8n Workflow          Action         │
│  ─────────────────────────────────────────────────────────  │
│  revenue < $100/day  →  revenue_alert.json  → notify+adjust │
│  new_video_detected  →  youtube_skill.json  → extract+store │
│  lead_score > 70     →  high_value_lead.json→ nurture       │
│  error_rate > 5%     →  health_alert.json   → investigate   │
│  time = Sunday 3AM   →  maintenance.json    → prune_memory  │
│                                                              │
└─────────────────────────────────────────────────────────────┘
```

Each workflow IS a stored trigger-action pair. Creating a workflow = creating a memory.

## Outcome Memory Integration

Every workflow should log outcomes:

```javascript
// At end of each workflow, add this node:
{
  "name": "Log Outcome",
  "type": "n8n-nodes-base.httpRequest",
  "parameters": {
    "url": "GENESIS_MEMORY_ENDPOINT",
    "method": "POST",
    "body": {
      "workflow_id": "{{$workflow.id}}",
      "execution_id": "{{$execution.id}}",
      "trigger": "{{$node.trigger.json}}",
      "result": "{{$json}}",
      "timestamp": "{{$now}}",
      "success": "{{$execution.successful}}"
    }
  }
}
```

This enables:
- Attribution tracking
- Success pattern detection
- Self-optimization

## Best Practices

### 1. Error Handling
Always add error workflows:
```
Main Flow → [On Error] → Log Error → Notify → Retry Logic
```

### 2. Idempotency
Design workflows to be safely re-runnable:
- Check if action already completed
- Use unique identifiers
- Avoid duplicate side effects

### 3. State Management
Use n8n's built-in storage or external state:
- Workflow static data for simple state
- External database for complex state
- HANDOFF.md for Genesis state bridge

### 4. Credential Security
- Store credentials in n8n credential manager
- Never hardcode secrets in workflows
- Use environment variables for configuration

## Quick Start Commands

```bash
# List all workflows
n8n-mcp list_workflows

# Execute a workflow
n8n-mcp execute_workflow --id "workflow-id"

# Get workflow status
n8n-mcp get_execution --id "execution-id"

# Create new workflow
n8n-mcp create_workflow --name "New Workflow" --nodes "[...]"
```

## Integration with Other Skills

| Skill | Integration Point |
|-------|-------------------|
| `model-stack-strategy` | Route to appropriate model in workflow |
| `piter-framework` | Implement PITER as n8n workflow |
| `closed-loop-verification` | Add verification nodes to workflows |
| `self-correcting-agents` | Error handlers trigger self-correction |

## References

See `references/` for:
- Complete node documentation
- Workflow templates
- API reference
- Best practices guide

## Sources

- [n8n-mcp by czlonkowski](https://github.com/czlonkowski/n8n-mcp)
- [n8n MCP Server by illuminaresolutions](https://glama.ai/mcp/servers/@illuminaresolutions/n8n-mcp-server)
- [n8n Official Documentation](https://docs.n8n.io/)
