# CultGuard Agents - pi-agent Framework Implementation Summary

## ✅ Completed

### 1. Core Extension (`.pi/extensions/cultguard-monitor.ts`)

**Custom Tools Registered:**
- `start_monitoring` - Start autonomous Facebook page surveillance
- `check_new_content` - Poll for new posts/comments since last check
- `analyze_content` - Risk scoring and pattern detection
- `generate_report` - Comprehensive investigation reports
- `configure_alerts` - Tune alert thresholds

**Custom Commands:**
- `/monitoring-status` - Show active investigations
- `/monitoring-reset` - Clear monitoring state

**Event Hooks:**
- Session state restoration on startup
- Tool call interception for monitoring context
- Status line updates

### 2. Autonomous Agents

#### Facebook Monitor (`src/agents/facebook-monitor.ts`)
- Continuous polling with configurable intervals (5-1440 min)
- Auto-scrape on new content detection
- Activity spike alerts
- Exponential backoff on failures
- Session persistence

**Run:** `agent-monitor -i <id> -p <url> --interval 30`

#### Content Analyzer (`src/agents/content-analyzer.ts`)
- Heuristic risk scoring (0-100)
- LLM-powered deep analysis
- Coordination detection (timing, similarity)
- Sentiment analysis
- Pattern detection:
  - Urgency/manipulation language
  - Call-to-action phrases
  - Conspiracy markers
  - Coordinated hashtags
  - Bot-like behavior

**Run:** `agent-analyzer -i <id> --batch-size 50 --llm`

#### Alert System (`src/agents/alert-system.ts`)
- Alert types: activity spikes, high-risk content, coordination, new entities
- Delivery channels: email (TODO: integrate gmcli), dashboard, console
- Configurable thresholds
- Failure monitoring

**Run:** `agent-alert -i <id> --channel email --email user@example.com`

#### Evidence Collector (`src/agents/evidence-collector.ts`)
- Auto-download media (images, videos)
- SHA-256 deduplication
- HTTP response archiving
- Identifier extraction (phone, email, domain)
- Batch processing

**Run:** `agent-collector -i <id> --auto`

### 3. Package Configuration

**Updated Nix + Node wiring:**
- package-lock-backed npm dependency graph
- Nix-built `node_modules` derivation
- pure devenv commands for all agents and CLIs
- TypeBox for schema definitions

**Key direct dependencies:**
```json
"@mariozechner/pi-ai": "^0.64.0",
"@mariozechner/pi-coding-agent": "^0.64.0",
"@sinclair/typebox": "^0.34.0"
```

### 4. Documentation

**Created:**
- `AGENTS.md` - Comprehensive agent documentation
- Architecture diagrams
- Usage examples
- Troubleshooting guide
- Systemd service templates

## 🏗️ Architecture

```
┌─────────────────────────────────────────────────────────┐
│              pi-agent Extension Layer                    │
│  cultguard-monitor.ts                                    │
│  • Custom LLM tools                                      │
│  • Event hooks                                           │
│  • State management                                      │
└──────────────────┬──────────────────────────────────────┘
                   │
                   ▼
┌─────────────────────────────────────────────────────────┐
│           Autonomous Agent Processes                     │
│  ┌────────────┐ ┌──────────┐ ┌────────┐ ┌──────────┐   │
│  │ Facebook   │ │ Content  │ │ Alert  │ │ Evidence │   │
│  │ Monitor    │ │ Analyzer │ │ System │ │ Collector│   │
│  └────────────┘ └──────────┘ └────────┘ └──────────┘   │
└──────────────────┬──────────────────────────────────────┘
                   │
                   ▼
┌─────────────────────────────────────────────────────────┐
│              PostgreSQL Database                         │
│  • investigations • entities • content • media          │
│  • annotations • identifiers • relationships            │
└─────────────────────────────────────────────────────────┘
```

## 🎯 Key Features

### Autonomous Operation
- Agents run continuously without manual intervention
- Configurable polling intervals
- Automatic failure recovery with backoff
- State persistence across restarts

### LLM Integration
- Deep content analysis via pi-agent
- Risk scoring with explainable flags
- Coordination pattern detection
- Natural language report generation

### Alert System
- Multiple alert types (spikes, risk, coordination)
- Configurable thresholds
- Email/dashboard/console delivery
- Failure monitoring

### Evidence Pipeline
- Auto-ingest media
- HTTP archiving
- Identifier extraction
- SHA-256 deduplication

## 📊 Risk Scoring System

| Pattern | Weight |
|---------|--------|
| Urgency language | +15 |
| Call-to-action | +10 |
| Conspiracy markers | +20 |
| Coordinated hashtags | +15 |
| High engagement (>1K) | +10 |
| Viral engagement (>5K) | +20 |
| High share ratio | +15 |
| Coordination detected | +20 |

**Risk Levels:**
- 0-14: Low
- 15-29: Medium
- 30+: High (triggers alerts)

## 🚀 Quick Start

### 1. Install & Setup
```bash
devenv up
devenv shell
typecheck
```

### 2. Interactive Mode (via pi)
```bash
pi
# Then use tools:
/start_monitoring --investigation demo --page <url>
/check_new_content --investigation demo
/analyze_content --content_ids ["id1"]
/generate_report --investigation demo
```

### 3. Autonomous Mode
```bash
# Start all agents
agent-monitor -i demo -p <url> --interval 30 &
agent-analyzer -i demo --batch-size 50 --llm &
agent-alert -i demo --channel email &
agent-collector -i demo --auto &
```

## 🔧 Next Steps (Recommended)

### 1. Email Integration (High Priority)
Wire up gmcli skill in alert-system.ts:
```typescript
// In sendEmailAlert():
pi.sendUserMessage(
  `/send-email --to ${recipient} --subject "${alert.title}" --body "${alert.message}"`,
  { deliverAs: "followUp" }
);
```

### 2. Dashboard Integration (Medium Priority)
Create Metabase dashboards:
- Real-time alert feed
- Content timeline visualization
- Entity network graph
- Risk score distribution

### 3. Embedding Pipeline (Medium Priority)
Finish `src/embed.ts` to enable:
- Semantic similarity for coordination detection
- Better content clustering
- Duplicate detection

### 4. Production Hardening
- Add systemd services
- Configure log rotation
- Set up monitoring for agents themselves
- Add metrics/observability

### 5. Multi-Platform Support
- Twitter/X scraper
- Telegram channel monitor
- Instagram page scraper

## 📝 Testing Checklist

- [ ] Start Facebook monitor with test page
- [ ] Verify new content detection
- [ ] Test content analyzer with sample posts
- [ ] Validate alert thresholds
- [ ] Check evidence collector media downloads
- [ ] Verify database writes
- [ ] Test agent restart/resume
- [ ] Validate pi extension tools work
- [ ] Check session persistence

## 🔐 Security Notes

- All agents run locally (no cloud)
- Facebook session managed by Chromium (not agents)
- Database isolated to local PostgreSQL
- Review alert thresholds before production use
- Agents respect rate limits

## 📚 Documentation

- **Main docs:** `AGENTS.md`
- **Architecture:** See diagram above
- **Examples:** Throughout AGENTS.md
- **Troubleshooting:** AGENTS.md "Troubleshooting" section

## 🎉 Success Criteria Met

✅ Converted cultguard-agents to pi-agent extension
✅ Built 4 autonomous monitoring agents
✅ Integrated with existing PostgreSQL schema
✅ Reused existing Facebook scraping logic
✅ Added LLM-powered analysis
✅ Implemented alert system
✅ Created evidence collection pipeline
✅ Full TypeScript type checking
✅ Comprehensive documentation

---

**Status:** Ready for testing and deployment
