## Script Maintenance and Debugging Patterns

### 1. Atomic Config Update Script

Uses tempfile.mkstemp + os.replace() for safe atomic writes. Always clean up temp files in a finally block. Use os.fsync() to ensure data is on disk before replace.

### 2. Common Code Fixes

1. Import Cleanup: remove duplicate `import time`, add missing `import os`, fix `_time.sleep()` to `time.sleep()`

2. Error Handling: handle missing config files, stable YAML parsing, descriptive logging

3. String Syntax: Python docstrings with triple quotes must be properly terminated. Bad patches can leave unterminated strings that crash the entire script.

### 3. Preserved Background Services

CPU-only models (ngl 0) must never be stopped during GPU model switches:

- Add `"preserve": True` to the model dict in models.py
- In model-switcher swap(): check `active.get("preserve")` before stopping
- get_active_service() iterates ALL MODELS, so a CPU-only service will appear as "active" and will be stopped if not guarded
- SmolLM3-3B-CPU is the primary preserved model (Hindsight memory, always running)

### 4. Python Gotcha

Booleans in models.py must be capitalized: `True` not `true`. JSON-style lowercase causes `NameError: name 'true' is not defined`.

### 5. Verification

```bash
# Test model definitions load
python3 -c '
import sys
sys.path.insert(0, "/home/rurouni/.hermes/scripts")
from models import MODELS
print(f"Loaded {len(MODELS)} models")
for m in MODELS:
    print(f"  {m[\"short\"]:8s} port {m[\"port\"]}  {m[\"name\"]}")
'

# Check for duplicate imports
grep -c "^import time$" /home/rurouni/.hermes/scripts/model-switcher

# Validate all referenced services have systemd units
python3 -c '
import sys, subprocess, os
sys.path.insert(0, "/home/rurouni/.hermes/scripts")
from models import MODELS
for m in MODELS:
    svc = m["service"]
    unit_path = f"/etc/systemd/system/{svc}.service"
    exists = os.path.exists(unit_path)
    active = subprocess.run(["systemctl", "is-active", svc], capture_output=True, text=True).stdout.strip()
    print(f"  {m['short']:8s} service={svc:30s} unit={'OK' if exists else 'MISSING'}  status={active}")
'
```
