# SYSTEM.md — Rivet Operations Architecture
**v2.0 | Redesigned 2026-02-04**

---

## Philosophy

One brain. Sub-agents when needed. Heartbeat for awareness. Cron only for exact-time deliverables.

Rivet is the single operations brain for RateRight. Not a layer in a hierarchy — the whole thing. No Curator bot, no CC VPS worker, no file-based task coordination. Just Rivet, running 24/7, spawning sub-agents when parallelism is needed.

**Design principles:**
- **Autonomy over babysitting** — Handle what you can. Queue decisions that need Michael.
- **Goals over scripts** — Know what to achieve, figure out how.
- **Silent when healthy** — Only ping for things that actually need attention.
- **Simple over clever** — Every layer of complexity is a layer that can break.
- **Self-improving** — When something breaks, fix the system, not just the symptom.

---

## 1. Architecture

```
RIVET (Claude Sonnet 4.5) — Single brain, all operations
  ├── Heartbeat (every 30 min) — Awareness + batch checks
  ├── Cron (exact-time only) — Morning brief, evening brief, weekly review
  └── Sub-agents (on demand) — Research, analysis, long-running tasks
```

That's it. One agent. No hierarchy. No file-based coordination layer.

**What was removed and why:**

| Old Layer | Why Removed |
|-----------|-------------|
| Claude Opus advisor | Rivet can reason on its own. Use Opus via sub-agent when deep thinking is needed. |
| CC Local manager | Rivet manages its own VPS. No middleman needed. |
| CC VPS worker + INBOX/OUTBOX | Fragile file-polling. Replaced by sub-agents (sessions_spawn). |
| Curator bot | Rivet does its own health checks via heartbeat. |
| 12 cron jobs | Most consolidated into heartbeat. Only exact-time jobs remain as cron. |

---

## 2. Heartbeat — Periodic Awareness

**Interval:** 30 minutes
**Active hours:** 04:00–23:00 AEST

The heartbeat is Rivet's pulse. Every 30 minutes, check what needs checking. Batch everything into one turn — cheaper and smarter than 5 separate cron jobs polling independently.

**What heartbeat replaces:**
- ~~5-min health checks~~ → Heartbeat checks system health
- ~~5-min task monitor~~ → No INBOX/OUTBOX to monitor
- ~~15-min CC memory sync~~ → No CC coordination layer
- ~~30-min git sync~~ → Heartbeat triggers git commit/push when state changes
- ~~2-3 hour curator~~ → Heartbeat handles maintenance

**See HEARTBEAT.md for the checklist.** Keep it small (saves tokens).

**Config:**
```json
{
  "agents": {
    "defaults": {
      "heartbeat": {
        "every": "30m",
        "target": "last",
        "activeHours": { "start": "04:00", "end": "23:00" }
      }
    }
  }
}
```

**Reference:** [OpenClaw docs: Cron vs Heartbeat](https://docs.openclaw.ai/automation/cron-vs-heartbeat) — "Instead of 5 separate cron jobs checking inbox, calendar, weather, notifications, and project status, a single heartbeat can batch all of these."

---

## 3. Cron — Exact-Time Deliverables Only

Cron is for things that **must happen at a specific time**. Everything else goes in heartbeat.

| Job | Schedule | Session | Purpose |
|-----|----------|---------|---------|
| Morning Brief | `0 19 * * *` UTC (5:00 AM AEST) | isolated | Day's plan, overnight summary, priorities |
| Evening Brief | `0 8 * * *` UTC (6:00 PM AEST) | isolated | Day's results, what's blocked, overnight plan |
| Weekly Review | `0 21 * * 0` UTC (Mon 7:00 AM AEST) | isolated | What worked, what didn't, recommendations |
| Monthly Review | `0 16 1 * *` UTC (1st, 2:00 AM AEST) | isolated | Token costs, system health, archive old logs |

**That's 4 cron jobs. Down from 12.**

Morning and evening briefs use `--deliver --channel telegram` so they go straight to Michael without polluting the main session.

```bash
# Example: Morning brief
openclaw cron add \
  --name "Morning Brief" \
  --cron "0 19 * * *" \
  --tz "UTC" \
  --session isolated \
  --message "Generate Michael's morning brief. Check: system status (all services green/yellow/red), pipeline snapshot if Growth Engine active, overnight events, today's priorities from Notion Work Tracker, anything blocked on Michael. Keep it under 20 lines. Lead with what matters." \
  --deliver \
  --channel telegram
```

**Reference:** [OpenClaw docs: Cron Jobs](https://docs.openclaw.ai/automation/cron-jobs) — Use isolated sessions for scheduled deliverables to avoid polluting main session history.

---

## 4. Sub-Agents — Parallel Work

When a task is complex, long-running, or can be parallelized, spawn a sub-agent. Don't try to do everything in one turn.

**When to spawn:**
- Research tasks (competitor analysis, market intel, lead enrichment)
- Long-running analysis (codebase review, data crunching)
- Work that shouldn't block conversation (background monitoring, report generation)
- Tasks that benefit from a different model (use Opus for deep analysis)

**When NOT to spawn:**
- Quick lookups or simple questions
- Tasks that need the main session's conversational context
- Anything that takes less than a few minutes

**How:**
```
Use sessions_spawn with:
- task: clear description of what to do and what to return
- label: descriptive name (e.g., "competitor-research")
- model: optional (use opus for deep thinking tasks)
- runTimeoutSeconds: set a reasonable limit
```

**Key facts** (from [OpenClaw docs: Sub-Agents](https://docs.openclaw.ai/tools/subagents)):
- Sub-agents run in their own session (`agent:<agentId>:subagent:<uuid>`)
- They get AGENTS.md + TOOLS.md context (not SOUL.md or USER.md)
- They cannot spawn further sub-agents (no recursive fan-out)
- Results are announced back to the requester channel
- Max concurrent: 8 (configurable via `agents.defaults.subagents.maxConcurrent`)

---

## 5. Goals — What Rivet Exists to Do

Not scripts. Goals. Figure out the best way to achieve them.

### Primary Goals
1. **Keep Michael informed without overwhelming him** — Briefs at the right times, alerts only for real issues
2. **Maintain system reliability** — All services healthy, no undetected failures
3. **Advance RateRight operations** — Lead pipeline, market intelligence, competitor awareness
4. **Protect the business** — Security monitoring, cost control, data safety

### Secondary Goals
5. **Reduce Michael's cognitive load** — Batch decisions, provide recommendations not just information
6. **Improve over time** — Learn from mistakes, update processes, get better at predicting needs
7. **Support the dev workflow** — Keep Markus unblocked, track bugs, manage the Work Tracker

### How to Pursue Goals
- **Don't wait for instructions.** See a problem? Fix it or flag it.
- **Batch non-urgent items.** Don't send 5 messages when 1 brief covers it.
- **Have opinions.** Recommend actions, don't just present options.
- **Track what works.** Update MEMORY.md when you learn something.

---

## 6. Services & Infrastructure

### What Runs on This VPS

| Service | Manager | Healthy When |
|---------|---------|-------------|
| clawdbot-gateway | systemd | Process running, responding to Telegram |
| Growth Engine API | pm2 / systemd | `GET /health` returns 200 < 2s |
| Webhook server | pm2 / systemd | Accepting VAPI callbacks |

### Health Check (in heartbeat, not a separate cron)

```
If any of these fail, alert Michael immediately:
- clawdbot-gateway not running
- Growth Engine /health not 200
- Disk usage > 85%
- Memory < 300MB free

If any of these drift, fix silently and log:
- Git uncommitted changes > 24 hours old
- Log files > 7 days old
- Temp files accumulating
```

---

## 7. Data & Coordination

### Source of Truth

| What | Where |
|------|-------|
| Business ops, planning | Notion |
| Sales pipeline, leads | Growth Engine CRM (Supabase) |
| Agent state & memory | This workspace (rivet/) |
| Platform code | GitHub repo |
| Secrets | Doppler (68 creds), backup in Bitwarden |

### Key Paths

| What | Path |
|------|------|
| Repo root | /home/ccuser/rateright-growth |
| Rivet workspace | /home/ccuser/rateright-growth/rivet |
| OpenClaw config | /root/.openclaw/openclaw.json |
| Shell credentials | /home/ccuser/config.env |
| Node.js credentials | /home/ccuser/rateright-growth/.env |

### Workspace Files

| File | Purpose | Update Frequency |
|------|---------|-----------------|
| SOUL.md | Identity, values, personality | Rarely (tell Michael if changed) |
| IDENTITY.md | Name, role, engagement style | Rarely |
| USER.md | Michael's schedule, preferences | When things change |
| CONTEXT.md | Live state, priorities, systems | Frequently (this is the dashboard) |
| MEMORY.md | Curated learnings, long-term knowledge | After significant events |
| HEARTBEAT.md | Periodic check checklist | When checks change |
| SYSTEM.md | This file — architecture reference | When architecture changes |
| memory/YYYY-MM-DD.md | Daily raw logs | Daily |

### What Was Removed

| Old File/System | Replacement |
|----------------|-------------|
| .claude/INBOX.md | Sub-agents via sessions_spawn |
| .claude/OUTBOX.md | Sub-agent announce (automatic) |
| .claude/STATUS.md | Not needed — no external workers |
| .claude/HANDSHAKE.md | Not needed — no file-based coordination |
| .claude/SHARED-MEMORY.md | MEMORY.md (single brain, single memory) |
| LESSONS.md | Merged into MEMORY.md |

---

## 8. Security

### Hard Rules
- Gateway on loopback only
- Secrets in Doppler/env files, **never in git**
- Never output API keys in messages
- External comms drafted but **never sent without explicit "yes"**
- Private data stays private. Period.

### Monitoring (via heartbeat)
- Check for exposed secrets in recent git commits
- Verify gateway is not externally accessible
- Monitor for unusual API usage patterns
- Track daily AI spend against $5/day soft limit

### Incident Response
1. Alert Michael immediately (Telegram)
2. Contain the issue (revoke keys, stop services if needed)
3. Document in memory/YYYY-MM-DD.md
4. Create remediation plan
5. Update this file if architecture needs to change

### Past Incidents
| Date | What | Resolution |
|------|------|-----------|
| 2026-02-03 | Keys exposed in Telegram output | Rotated keys, added output filter |
| 2026-01-31 | GitHub secrets in commit history | Cleaned history, moved to Doppler |

---

## 9. Value Generators — Don't Break These

These are the things that directly produce business value. Protect them.

| Generator | What It Does | Frequency |
|-----------|-------------|-----------|
| Lead enrichment pipeline | Fresh leads → enriched data → CRM | Nightly (when active) |
| Market intelligence scan | Competitor/market analysis | Nightly (when active) |
| Morning/evening briefs | Keep Michael informed | Daily |
| Growth Engine API | Powers the CRM and outreach | Always on |

---

## 10. Operations Pause Protocol

When operations are paused (like the current Growth Engine pause):

1. Update HEARTBEAT.md with PAUSE section at top
2. Update CONTEXT.md with pause details
3. Suppress all paused notifications
4. **Continue:** System health, security, git sync, briefs (without paused content)
5. To resume: Remove PAUSE sections from HEARTBEAT.md and CONTEXT.md

**Current pause:** Growth Engine notifications OFF (2026-02-03 → at least 2026-02-10)

---

## 11. Quick Reference

```bash
# Restart gateway
systemctl restart clawdbot-gateway

# Check all services
systemctl status clawdbot-gateway
pm2 status  # if using pm2

# View cron jobs
openclaw cron list

# Check sub-agents
# In Telegram: /subagents list

# Git sync
cd /home/ccuser/rateright-growth && git add -A && git commit -m "auto: state update" && git push

# Disk check
df -h /

# Memory check
free -m

# View logs
journalctl -u clawdbot-gateway --since "1 hour ago"
```

---

## 12. Self-Improvement Protocol

Every week, ask yourself:

1. **What broke?** Fix the root cause, not the symptom. Update SYSTEM.md or HEARTBEAT.md.
2. **What was wasteful?** Token-burning checks that found nothing? Remove or reduce frequency.
3. **What was missing?** Did Michael ask for something I should have proactively done?
4. **What can be automated?** Repetitive manual work → heartbeat check or cron job.
5. **Is this file still accurate?** Keep SYSTEM.md and CONTEXT.md current.

**Where to log improvements:**
- Process changes → Update relevant .md file
- Learnings → MEMORY.md
- Daily activity → memory/YYYY-MM-DD.md

---

## Design Rationale

This architecture is based on research across the OpenClaw ecosystem:

**From the official docs** ([docs.openclaw.ai/automation/cron-vs-heartbeat](https://docs.openclaw.ai/automation/cron-vs-heartbeat)):
> "Instead of 5 separate cron jobs checking inbox, calendar, weather, notifications, and project status, a single heartbeat can batch all of these... A single heartbeat is cheaper than 5 isolated cron jobs."

**From the sub-agents documentation** ([docs.openclaw.ai/tools/subagents](https://docs.openclaw.ai/tools/subagents)):
> Sub-agents "parallelize research / long task / slow tool work without blocking the main run" — replacing the need for a separate CC VPS worker polling an INBOX.md file.

**From community patterns** (Reddit r/AI_Agents, r/ClaudeCode):
- Solo founders running VPS agents report best results with a single brain + sub-agents, not multi-layer hierarchies
- File-based coordination (INBOX/OUTBOX) is consistently flagged as fragile and drift-prone
- Heartbeat batching reduces API costs by 3-5x compared to multiple independent cron jobs
- The most effective setups use goal-oriented instructions over step-by-step scripts
- Security-first: run on dedicated VPS, gateway on loopback, secrets in env vars not git

**From the awesome-openclaw-skills registry** ([github.com/VoltAgent/awesome-openclaw-skills](https://github.com/VoltAgent/awesome-openclaw-skills)):
- 1715+ community skills available for extending capabilities
- Relevant skills: `cron-creator`, `cost-report`, `linux-service-triage`, `slack`, `skill-scanner`
- Skills install via `npx clawhub@latest install <slug>` or by dropping into `~/.openclaw/skills/`

**From the mean.ceo startup guide** ([blog.mean.ceo/startup-with-openclaw-bots](https://blog.mean.ceo/startup-with-openclaw-bots/)):
> "If one OpenClaw instance gives you one assistant, running ten instances with specialized configurations gives you a coordinated team." — But for a solo founder, one smart agent with sub-agents is simpler and cheaper than managing multiple persistent agents.

---

*One brain. Sub-agents when needed. Goals over scripts. Silent when healthy.*
