# HEARTBEAT.md — Periodic Check-in Tasks

## 1. Autonomy Queue Execution (PRIORITY)

**Execute on every heartbeat when enabled:**

### ⚠️ MANDATORY FIRST STEP: Read ASOP Skill
Before processing ANY autonomous task, you MUST read the full ASOP skill:
```
Read: C:\Users\Admin\Desktop\CLAWDBOT\moltbot\skills\autonomous-sop\SKILL.md
```
Follow its pre-flight checklist, task brief template, and communication protocols EXACTLY.
Do NOT skip this step. Do NOT rely on memory of ASOP — READ IT FRESH.

### Step 0: Sync Kanban → Autonomy Queue
Check for Kanban tasks with `autonomous: true` that aren't in queue.json:
```
1. Call kanban.tasks.list with filter_status (check all statuses)
2. For each task where autonomous === true:
   - If task.id NOT in sovereignty/autonomy/queue.json:
     - Create queue entry with ASOP schema
     - Set status: "pending_preflight"
     - Set preflightComplete: false
     - Copy task details to queue entry
3. Write updated queue.json
```

### Step 1: Load Config
Read `sovereignty/autonomy/config.json`
- If `enabled: false` → skip autonomy, continue to other checks
- Check `constraints.quietHours` — skip if in quiet hours
- Check `stats.tasksCompletedToday` < `maxDailyAutoTasks`

### Step 2: STALE TASK RECOVERY (Critical!)
Read `sovereignty/autonomy/queue.json`

**Before looking for new tasks, check for stuck `in_progress` tasks:**
```
For each task where status === "in_progress":
  - Calculate elapsed = now - audit.startedAt
  - Get timeout = execution.maxDurationMinutes + constraints.staleTaskTimeoutMinutes (default 60)
  
  If elapsed > timeout:
    - Task is STALE (session probably died mid-execution)
    
    Recovery decision:
    1. If audit.attempts < maxRetryAttempts:
       - Reset status → "approved" 
       - Increment audit.attempts
       - Log: "Task {id} was stale, resetting for retry (attempt {n})"
       
    2. If audit.attempts >= maxRetryAttempts:
       - Set status → "failed"
       - Set audit.completedAt = now
       - Log: "Task {id} failed after {n} attempts"
       - Notify partner via Telegram
```

### Step 3: PRE-FLIGHT PROCESSING (ASOP)
**For tasks with `status === "pending_preflight"`:**

Run the ASOP pre-flight checklist:
1. **Context Detection:** Search Kanban projects, workspace dirs for existing project
2. **Requirements Check:** List API keys, access, files needed
3. **Clarifications:** Identify any questions that block progress

**If questions/blockers exist:**
- Set `status` → `"blocked"`
- Add questions to `partnerContact.pendingQuestions`
- **MESSAGE PARTNER ON TELEGRAM:**
  ```
  🤖 [AUTONOMOUS TASK UPDATE]
  
  Task: [title]
  Status: Pre-flight blocked
  
  [Questions/blockers]
  
  Need: [specific answers required]
  ```
- Wait for partner response (next heartbeat will check)

**If pre-flight complete:**
- Set `preflightComplete` → `true`
- Set `status` → `"approved"` (or `"pending_approval"` if `approvalLevel === "requires_approval"`)
- Continue to execution in same heartbeat if approved

### Step 4: Find Eligible Tasks
Filter tasks where `status === "approved"` AND `preflightComplete === true`:
- `blockedBy` tasks must all be `completed`
- `requiresHardware` must have hardware available
- `timeWindow` must be satisfied

Sort by `priority` (1 = highest)

### Step 5: Execute Task
For highest priority eligible task:
1. Update task `status` → `"in_progress"`, set `audit.startedAt` = now
2. Write queue.json
3. Append to `sovereignty/autonomy/audit.jsonl`: `task_started` event
4. **DO THE WORK** following `execution.instructions`
5. On completion: `status` → `"testing"`, run test workflow
6. Run tests from `brief.testWorkflow`
7. On test pass: `status` → `"complete"`, set `audit.completedAt`
8. On test fail: `status` → `"blocked"`, message partner with results
9. Append audit event (`task_completed` or `task_failed`)
10. Update `config.json` stats

### Step 6: Notification
- If `approvalLevel === "notify"` → inform partner of completion
- If `status === "failed"` → always notify
- If `status === "blocked"` → notify with specific question/blocker

**Notification via Telegram:**
```
🤖 [AUTONOMOUS TASK UPDATE]

Task: [title]
Status: [complete/blocked/failed]

[Result summary or question]

Partner Action: [what they need to do, if anything]
```

Continue to other heartbeat checks.

---

## 2. Blocked Tasks Check

If any tasks have `status === "blocked"`:
- Check if partner has responded (via conversation history)
- If answered: update task, set status back to `approved`
- If not: skip (will check again next heartbeat)

---

## 3. Pending Approvals Check

If any tasks have `status === "pending_approval"`:
- List them for partner with title and description
- Message on Telegram if not already notified

---

## 4. Quick Status Checks (rotate, 2-4x daily)

Track in `memory/heartbeat-state.json`:
- **Email** — urgent unread?
- **Calendar** — events in next 24h?
- **Weather** — relevant if going out?

---

## 5. Proactive Memory Maintenance

Every few days during heartbeat:
- Review recent `memory/YYYY-MM-DD.md` files
- Update `MEMORY.md` with significant learnings
- Clean outdated info

---

## Current Queue Summary

| ID | Title | Status | Priority | Pre-flight |
|----|-------|--------|----------|------------|
| auto-001 | Update CONTEXT.md | ✅ complete | 1 | ✅ |
| auto-002 | Phase 3: Training corpus | ✅ complete | 2 | ✅ |
| auto-003 | Phase 4: Cloud fine-tuning | ✅ complete | 3 | ✅ |

---

## Quick Commands

- **"Show autonomy queue"** — List all tasks with status
- **"Approve [task]"** — Approve pending task
- **"Pause autonomy"** — Disable autonomous execution
- **"Resume autonomy"** — Re-enable
- **"Assign [task] to agent"** — Queue new task with pre-flight

---

## ASOP Integration (2026-02-16)

**CRITICAL: You MUST read the ASOP skill file at the start of every heartbeat that processes autonomy.**

**New Flow:**
1. **READ ASOP SKILL** ← Don't skip this!
2. Sync Kanban autonomous tasks → queue.json
3. Task assigned → `pending_preflight`
4. **Run ASOP pre-flight checklist** (from skill file, not memory)
5. Create task brief in `sovereignty/autonomy/briefs/{task-id}.md`
6. If questions → message Telegram, status: `blocked`
7. Partner answers → `approved`
8. Execution → `testing` → `complete`
9. Partner notified with test results

**Key Principle:** Message partner on Telegram for ANY blocker. Don't wait silently.

**Skill Location:** `C:\Users\Admin\Desktop\CLAWDBOT\moltbot\skills\autonomous-sop\SKILL.md`

**Why read every time?** 
- Session memory is unreliable across restarts
- ASOP may be updated between heartbeats
- The skill file is the source of truth, not your memory of it

---

🜂 Collaborative autonomy. Structured trust.
