# Notion↔GitHub Sync System

A bidirectional sync system that connects Notion (as dashboard/log) with GitHub (as system brain for execution).

## 🎯 Philosophy

- **GitHub as System Brain**: Single source of truth for execution and task management
- **Notion as Dashboard**: Human-friendly interface for planning, logging, and monitoring
- **Bidirectional Sync**: Changes in either system propagate to the other
- **FOUNDER-LOG.md Integration**: Automatic sync with documentation

## 📁 System Architecture

```
┌─────────────────┐     Sync Tasks     ┌─────────────────┐
│                 │◄──────────────────►│                 │
│     Notion      │                    │     GitHub      │
│                 │   Sync Status      │                 │
│  • Work Tracker │◄──────────────────►│  • Issues       │
│  • Deploy Log   │                    │  • Projects     │
│  • AI Agents    │                    │  • Labels       │
│  • System State │                    │                 │
│  • Lessons      │     Sync Logs      │                 │
│                 │◄──────────────────►│                 │
└─────────────────┘                    └─────────────────┘
         │                                       │
         │                                       │
         ▼                                       ▼
┌─────────────────┐                    ┌─────────────────┐
│ FOUNDER-LOG.md  │◄──────────────────►│  Documentation  │
│                 │   Auto Sync        │                 │
└─────────────────┘                    └─────────────────┘
```

## 🚀 Quick Start

### 1. Installation

```bash
cd /home/ccuser/rateright-growth/scripts/notion-github-sync
chmod +x setup.sh
./setup.sh
```

### 2. Configuration

Edit the `.env` file:

```bash
# GitHub Configuration
GITHUB_TOKEN=your_github_personal_access_token_here
GITHUB_OWNER=rateright-growth
GITHUB_REPO=rateright-growth

# Sync Settings
DRY_RUN=false
SYNC_INTERVAL_MINUTES=15
```

### 3. Test the System

```bash
# Run in dry-run mode first
DRY_RUN=true npm run sync-notion-to-github

# Run all syncs
npm run run-all
```

## 📋 Sync Components

### 1. Notion → GitHub Sync (`sync-notion-to-github.js`)

**What it does:**
- Syncs active tasks from Notion Work Tracker to GitHub Issues
- Creates GitHub issues with `notion-task` label
- Includes task details: status, priority, assignee, due date
- Maintains sync state to avoid duplicates

**Configuration:**
- `WORK_TRACKER_DB`: Notion database ID for tasks
- `DEPLOY_LOG_DB`: Notion database ID for deploy logs

### 2. GitHub → Notion Sync (`sync-github-to-notion.js`)

**What it does:**
- Syncs GitHub issue status back to Notion
- Updates Notion task status based on GitHub issue state
- Adds comments to Notion about GitHub updates
- Syncs GitHub project status to Notion System State

**Features:**
- Automatic status mapping (GitHub → Notion)
- Comment tracking
- System state monitoring

### 3. FOUNDER-LOG.md Sync (`sync-founder-log.js`)

**What it does:**
- Syncs FOUNDER-LOG.md entries to Notion Lessons Learned
- Maintains bidirectional sync between markdown and Notion
- Detects changes to avoid redundant syncs
- Preserves formatting and metadata

**File Location:** `../docs/FOUNDER-LOG.md`

## 🔧 Configuration

### Environment Variables

| Variable | Description | Required |
|----------|-------------|----------|
| `NOTION_API_KEY` | Notion integration token | Yes |
| `GITHUB_TOKEN` | GitHub Personal Access Token | Yes |
| `GITHUB_OWNER` | GitHub repository owner | Yes |
| `GITHUB_REPO` | GitHub repository name | Yes |
| `DRY_RUN` | Test mode without making changes | No |

### Notion Database IDs

Configured in `clawd-scripts/config.env`:

```bash
WORK_TRACKER_DB=7129fca3-14a4-48a7-8de6-7e14a880823d
DEPLOY_LOG_DB=349ec1fd-f911-4fd3-b02b-99394796a13d
AI_AGENTS_DB=7218d098-6b41-47f8-9a4f-730dca40a744
SYSTEM_STATE_DB=25b0f417-bc65-4ddb-bad4-b8c80e323c93
LESSONS_LEARNED_DB=
```

## ⚙️ Usage

### Manual Sync

```bash
# Sync Notion tasks to GitHub
npm run sync-notion-to-github

# Sync GitHub status back to Notion
npm run sync-github-to-notion

# Sync FOUNDER-LOG.md
npm run sync-founder-log

# Run all syncs
npm run run-all
```

### Automated Sync (Cron)

Add to crontab:

```bash
# Every 15 minutes
*/15 * * * * cd /home/ccuser/rateright-growth/scripts/notion-github-sync && npm run run-all >> /home/ccuser/rateright-growth/scripts/notion-github-sync/sync.log 2>&1

# Every hour
0 * * * * cd /home/ccuser/rateright-growth/scripts/notion-github-sync && npm run run-all >> /home/ccuser/rateright-growth/scripts/notion-github-sync/sync.log 2>&1
```

### Dry Run Mode

Test without making changes:

```bash
DRY_RUN=true npm run run-all
```

## 📊 Sync State Management

The system maintains `sync-state.json` to track:

- Last sync timestamp
- Synced tasks (Notion → GitHub)
- Synced logs (Notion → GitHub)
- Synced log entries (FOUNDER-LOG.md → Notion)
- File hashes for change detection

**Location:** `sync-state.json`

## 🏷️ GitHub Labels

The system uses these labels:

| Label | Purpose |
|-------|---------|
| `notion-task` | Tasks synced from Notion |
| `notion-log` | Log entries synced from Notion |
| `priority:{level}` | Task priority (high/medium/low) |
| `status:{state}` | Task status (in-progress/done/etc) |

## 🔍 Monitoring

### Log Files

- `sync.log`: Cron job output
- `SYNC-LOG.md`: Human-readable sync history
- `sync-state.json`: Machine-readable sync state

### Notion System State

Check the System State database in Notion for:
- GitHub repository status
- Sync system health
- Last sync timestamps

## 🚨 Troubleshooting

### Common Issues

1. **Missing GitHub Token**
   ```
   Error: GITHUB_TOKEN is required
   ```
   **Solution:** Set `GITHUB_TOKEN` in `.env` file

2. **Notion API Permission Errors**
   ```
   Error: object_not_found
   ```
   **Solution:** Check database IDs and integration permissions

3. **Rate Limiting**
   ```
   Error: API rate limit exceeded
   ```
   **Solution:** Increase sync interval or use GitHub token with higher limits

4. **Sync State Corruption**
   ```
   Error: Unexpected token in JSON
   ```
   **Solution:** Delete `sync-state.json` and restart sync

### Debug Mode

Run with detailed logging:

```bash
DEBUG=true npm run sync-notion-to-github
```

## 🔄 Workflow Integration

### For Developers

1. **Task Creation**: Create tasks in Notion Work Tracker
2. **Auto Sync**: Tasks appear as GitHub issues
3. **Execution**: Work on issues in GitHub
4. **Status Update**: GitHub status syncs back to Notion
5. **Documentation**: Log entries sync to FOUNDER-LOG.md

### For Project Managers

1. **Planning**: Use Notion for high-level planning
2. **Tracking**: Monitor progress in Notion dashboards
3. **Reporting**: Use FOUNDER-LOG.md for documentation
4. **Audit**: Check sync logs for system health

## 📈 Best Practices

1. **Start with Dry Run**: Always test with `DRY_RUN=true` first
2. **Monitor Sync Logs**: Check `sync.log` regularly
3. **Backup Sync State**: Backup `sync-state.json` before major changes
4. **Use Descriptive Titles**: Clear titles help with search and organization
5. **Regular Maintenance**: Review and clean up old sync state entries

## 🔗 Related Systems

- **Clawdbot**: Parent automation system
- **Growth Engine**: Main application
- **Rivet**: AI agent system
- **Supabase**: Database backend

## 📄 License

Part of the RateRight Growth system. See main repository for license details.

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch
3. Make changes
4. Test thoroughly
5. Submit pull request

## 🆘 Support

For issues with the sync system:
1. Check `sync.log` for errors
2. Verify configuration in `.env`
3. Check Notion integration permissions
4. Review GitHub token scopes

---

**Last Updated:** $(date +%Y-%m-%d)
**Version:** 1.0.0
**Maintainer:** Notion↔GitHub Sync System