---
name: heartbeat-refactor-execute
description: >-
  Self-validating autonomous execution of the heartbeat modularization refactor.
  Extracts 16 modules from the 1981-line monolith one at a time, validating
  output identity after each step. Runs end-to-end without user confirmation.
  Invoke to execute the full refactor pipeline.
allowed-tools: Read, Write, Edit, Bash, Grep, Glob, Agent
---

# Heartbeat Refactor: Autonomous Self-Validating Execution

ultrathink

## Execution Protocol

Run ALL steps below sequentially. After each extraction, self-validate by comparing
heartbeat output. Do NOT stop for user confirmation. If validation fails, revert
the step and try again with a different approach.

## Pre-Flight

1. Read the full refactor plan:
   - `.claude/skills/streaming-writer-exclusion-spike/references/heartbeat-refactor-plan.md`
   - `.claude/skills/streaming-writer-exclusion-spike/references/heartbeat-refactor-strategy.md`

2. Create the test harness on bigblack:

```bash
ssh bigblack 'cat > /tmp/test_heartbeat.py << '\''PYEOF'\''
import sys, json
sys.path.insert(0, "/home/tca/opendeviationbar-py/scripts")
from health_heartbeat import _run_checks, _format_message
results = _run_checks()
healthy = all(v is True for k, v in results.items() if isinstance(v, bool))
message = _format_message(results, healthy)
# Save snapshot
with open("/tmp/heartbeat_snapshot.json", "w") as f:
    json.dump({k: str(v) for k, v in results.items()}, f, indent=2, sort_keys=True)
with open("/tmp/heartbeat_snapshot.txt", "w") as f:
    f.write(message)
print(f"OK: {len(results)} keys, {len(message)} chars")
PYEOF'
```

1. Take baseline snapshot:

```bash
ssh bigblack '~/opendeviationbar-py/.venv/bin/python3 /tmp/test_heartbeat.py'
ssh bigblack 'cp /tmp/heartbeat_snapshot.json /tmp/heartbeat_baseline.json'
ssh bigblack 'cp /tmp/heartbeat_snapshot.txt /tmp/heartbeat_baseline.txt'
```

## Execution Order

### Phase 1: Zero-risk extractions

**Step 1: config.py** — Extract constants.
**Step 2: state.py** — Extract state persistence.
**Step 3: telegram.py** — Extract Telegram API.
**Step 4: alert_dedup.py** — Extract Redis dedup.

After Phase 1: validate snapshot matches baseline.

### Phase 2: Check modules

**Steps 5-12**: Extract each check module (services, clickhouse, freshness, kintsugi, resources, version, seeder, stathera).

After each step: validate snapshot.

### Phase 3: Orchestrator + Formatter

**Steps 13-16**: Extract orchestrator, formatter, main, create shim.

After Phase 3: validate + deploy to bigblack + verify one heartbeat cycle.

## Self-Validation Protocol

After EACH extraction:

```bash
# 1. Git sync to bigblack
ssh bigblack 'cd ~/opendeviationbar-py && git fetch origin main && git reset --hard origin/main'

# 2. Run heartbeat test
ssh bigblack '~/opendeviationbar-py/.venv/bin/python3 /tmp/test_heartbeat.py'

# 3. Compare with baseline
ssh bigblack 'diff /tmp/heartbeat_baseline.txt /tmp/heartbeat_snapshot.txt && echo "PASS: identical" || echo "FAIL: output changed"'
```

If FAIL: revert the commit (`git revert HEAD`), analyze the diff, fix, recommit.

## Bug Fix Phase (After Refactor)

Only after all 16 extractions pass validation:

1. Fix emergency alert HTML/Markdown mismatch
2. Add explicit HEALTH_GATE_KEYS set
3. Fix kintsugi_stuck inverted semantics
4. Add sidecar engine metrics check
5. Add dead letter count check

Each bug fix is a separate commit with its own validation pass.

## Completion Criteria

- All 16 modules extracted
- `scripts/health_heartbeat.py` is a thin shim (<10 lines)
- `scripts/heartbeat/` package contains all logic
- Telegram message output is byte-identical to baseline
- One full heartbeat cycle on bigblack produces identical message
- All 5 bug fixes committed and validated
- All changes pushed to origin/main
