Contents

Rhobots · 2026 45 min incl. Q&A

200 Days
From First AI Agent Steps
to an Autonomous Organism

What started as a chatbot with API keys became a system that observes, heals and optimizes itself — and runs a household, a portfolio and a small business along the way.

Feb 6 → Aug 2026 16 built systems 120+ failures turned into guardrails one 4 GB server
Agenda ~2 min

Four parts, one question

How does an AI agent stop being a tool you operate — and become a system that operates itself?

Part 1 · ~2 min

The goal

What we were actually building — stated up front, so everything that follows has a direction.

Part 2 · ~8 min

How the system grew

ARCHITECTURE.md and INVENTORY.md: four plateaus of the stack, and the inventory of everything that executes — from 1 script to 58 running components.

Part 3 · ~20 min

Seven principles, in depth

First the map of all seven, then one slide per principle — each one earned by a real failure.

Part 4 · ~7 min + Q&A

What runs today

The full architecture — every component — and sixteen built systems, live and clickable.

Part 1 · the goal, stated early ~1 min

The goal was never a chatbot

A reliable, self-healing, self-optimizing, proactive companion — for one person, one family, one business.

Reliable

Deterministic where it matters, tested, observable.

Self-healing

Detects failures and remediates them automatically.

Self-optimizing

Costs, models, performance — reviewed and tuned continuously.

Proactive

Anticipates instead of waiting to be asked.

Part 2 · ARCHITECTURE.md ~3 min

Four plateaus — each one a reaction

The stack never changed by plan. Each step up was the answer to a concrete failure or bill.

February

Agent + fallback

One cloud model, one fallback. The first “architecture” was a config file.

March – April

Scripts + services

Prompted routines became Python scripts under a process manager, apps behind one reverse proxy.

May – June

Model mesh + self-healing

Cost explosions forced a model strategy; outages forced a healing layer with runbooks.

July – August

One box, one registry

Everything consolidated: 16 systems, one server, self-hosted mail — governed by a single machine-readable registry.

ARCHITECTURE.md was rewritten once per plateau — today it describes behavior, not just topology.

Part 2 · everything that executes ~2 min

From one script to 58 running components

1
Feb
agent script
3
Apr
services
7
Jun
services
11
Jul
services
58
11 services
19 crons
28 scripts
Aug
everything running

Services under PM2, scheduled cron jobs, standalone scripts — everything that executes is inventoried. The rule: add or remove something significant, update the inventory in the same session.

Part 3 · the map for this part ~2 min

Seven principles, one meta-rule

Each of the next seven slides covers one principle — each earned by a real failure.

1

Determinism

Script what must be reliable. Reserve the LLM for judgment.

2

Observability

A failure nobody sees is a failure that persists.

3

Self-healing

Automate remediation the second time you do it by hand.

4

Model strategy

Treat models as infrastructure: costs, limits, providers.

5

Coverage

If it runs but isn’t registered, it doesn’t exist. One registry for everything.

6

Autonomy as a dial

Exactly the autonomy needed to close the loop — no more, approval gates where it matters.

7

Found = fixed

Every found issue is fixed in the same session, then made impossible to repeat.

Meta-principle across all seven: reliable, self-optimizing, proactive — a companion, not a tool.
Part 3 · principle 1 of 7 ~2.5 min

Determinism — when to script, when to ask the model

Deterministic scripts
Data pulls & routingTomTom distances, broker positions, weather & pollen APIs
Schedules & checksbriefings, heartbeat checks, health probes, disk monitors
Alerting & dedupfailure alerts, double-tap guards, log rotation
The mix
Briefing pipelinescripts gather & verify facts, model writes the prose
Trading agentscripts read broker & risk data, model decides, human approves
Model optimizerscripts measure cost & quality, model recommends the chain
Pure LLM
Writing & summarizingdrafts, digests, content
Review & judgmentcode review, planning, decisions under uncertainty
Conversationsanything that needs understanding intent
Rule of thumb: if you’d be annoyed the output was different yesterday, use a script. Every hallucination we caught — invented distances, drifted market figures, mis-stated trades — was fixed by moving that piece left.
Part 3 · principle 2 of 7 ~2 min

Observability — a failure nobody sees never gets fixed

Silent months

Trading agent dead since February — scheduler kept reporting OK every 30 min.

Empty success

Briefing’s health section ran empty behind a swallowed error.

Silent by design

One script carried ~124 bare excepts, writing to a log nobody read.

Wrong signal

Heartbeats said “OK” when the job ran — not whether it did anything.

Invisible costs

Spend unmetered for weeks — a broken fallback burned 73% of a week’s budget in 3 days.

Loud today: token metering · heartbeat state files · registry health checks · errors surfaced straight to chat — silence is treated as a failure mode, not as success.
Failing loudly is a feature. Silence is the bug.
Part 3 · principle 3 of 7 ~2 min

Self-healing — a loop, not a feature

Buildnew ships
Scanfinds it
Registerregistry
Healrunbooks
Optimizerepeat
Capacity

Disk & log growth → rotation and disk monitors.

Limits

Rate limits & quota exhaustion → provider fallbacks, health probes.

Runaway actions

Duplicate queued orders → dedup and pre-approval guards.

Coverage gaps

Unmonitored services → registry-driven checks for everything.

Security & certs

TLS expiries and unvalidated certificates → real certificate checks + renewal.

Process health

Crashloops and dead processes → automatic restarts, restart-storm alerts.

Part 3 · principle 4 of 7 ~2.5 min

Model strategy — organizing which model runs what

Capability match

Route each task to the cheapest model that does it well.

Rate limits

Fallback chains across three providers keep the system alive.

Peak hours

The router switches primaries automatically at peak pricing times.

Cost control

Every call is metered; a weekly report ranks models by real spend.

Provider balance

Subscription + pay-per-use + hyperscaler — no single point of failure.

New models

The optimizer re-evaluates the chain when a new model publishes — measured, not hype.

Current state — the cost pipeline
1
Optimize contextlossless DAG compaction · light-context subagents · prompts trimmed before the call
≈30%
2
Check model health & rate limitsquota monitors · fallback on first provider refusal — no cascade into expensive models
≈15%
3
Avoid peak hoursautomatic router: cheaper primary 06:00–10:00 UTC · flagship off-peak
≈25%
4
Optimize memorycompiled memory wiki · recall instead of re-reading · weekly distillation
≈10%
→
ChainGLM-5.1 → DeepSeek Flash → Gemini Flash · Anthropic only for critical tasks

≈% = saving on what remains after the previous stage — they compound: 1 − 0.7×0.85×0.75×0.9 ≈ 60% total

The punchline: best outcomes at ≈60% cost savings — the layered pipeline holds the monthly bill at ~40% of a single-flagship setup, with no loss of quality.
Part 3 · principle 5 of 7 ~2 min

Coverage — if it isn’t registered, it doesn’t exist

INVENTORY.md · for humans

What exists and why

Every app, script, doc and skill with its purpose. The reference for audits, onboarding, planning. Read by people — and by the agent when deciding what to touch.

“add it to both” human & agent update both records in the same session
ops/registry.json · for machines

How to check and heal it

Every service with its health check type, ports, heal runbook. Read by the self-healer — the machine-readable contract that makes services observable and fixable.

They complement each other: the inventory explains the system, the registry operates it. Adding a service means adding it to both.

The proof: a registry-driven audit sweep found four apps nobody was monitoring, a wrong health path, and TLS checks without actual certificate validation — all things hand-written monitoring had missed for months.
Part 3 · principle 6 of 7 ~2 min

Autonomy — the agent works, the human approves

AutoDo

Asynchronous task management

A Kanban-style task system built for agent work: tasks flow To Do → In Progress → Done, across boards for ops, content and ideas.

Human in the loop

Manual action = approval

Wherever a step needs money, emails or external effects, the task waits for the human — approval happens in chat, one tap.

Traceability

Everything leaves a trail

Comments and checklist items on every task record what was done, why, and with what result — full audit trail for every automated action.

It took seven attempts to get autonomy right. Complex dispatchers churned without completing anything. The working design is minimal: the agent itself picks a task, moves it to In Progress, does the work, closes it — with AutoDo as the single source of truth for what’s open.

Autonomy is a dial, not a switch: exactly the autonomy needed to close the loop — approval gates where it matters.
Part 3 · principle 7 of 7 ~2 min

Found = fixed. Same session.

Built on SRE principles — health checks, error budgets, runbooks, blameless postmortems — adapted for a one-person AI system. Plus continuous refactoring: the system shrinks where it can, not just grows.

01

Weekly deep scans — the code

“Is the code correct?” — bugs, dead code, missing error handling, silent excepts. Found → fixed in the same session, 3 iterations of scan → fix → re-test.

02

Weekly audits — the system

“Is reality what the records claim?” — parallel agents compare running processes against the registry & inventory: unregistered services, unmonitored apps, stale docs. Gaps → fixed or filed.

03

Innovation sprints

A clean scan proposes improvements instead of stopping at “no errors found”.

04

Refactoring passes

Dedupe scripts, drop dead code, expire stale data — subtraction as maintenance.

Scan
Fix
Retest
Log
Repeat
Part 4 · what runs now ~3.5 min

The organism, today

iOS app primary channel Telegram trade approvals Smart home solar · EV charging External APIs broker · TomTom · weather Family calendar · chat · approvals INTELLIGENCE Gateway sessions · routing · tools Model mesh 6 providers · fallback · peak router Skills + subagents 33 skills · parallel agents ClawCode coding agent · scans · fixes GOVERNING Scheduler + heartbeat 19 cron jobs · proactive checks Self-healer runbooks · auto-remediation Model optimizer chain tuning · cost report registry.json + INVENTORY.md machine · human record APPS 16 built systems · all usable AutoDo · RouteForge · Content Studio Token Dashboard · ImmoPulse · GovSpend FitSpark · DomainScanner · PollenRadar RadEvents · Health Explorer DocScanner · dein-projekt.ai + 28 scripts · 19 cron jobs Headless agents financial trader · health coach travel planner · morning briefing audit agents · deep scanner DATA databases · memory files & daily notes · registry state · health-check history · automated backups INFRASTRUCTURE one Hetzner VPS · PM2 · Caddy + TLS · Tailscale mesh · Stalwart mail · code-server
Intelligence Governing Infrastructure External world
Part 4 · built and running ~4 min

Apps with a face — live right now

And the headless ones — no UI, doing real work:

Financial Traderanti-cycle portfolio agent with trade approvals
Health Coachselfie analysis, flare tracking, med reminders
Travel Plannerlive trip monitor with proactive daily hints
Energy Automationsolar boost + smart EV charging
Morning Briefingweather, pollen, calendar, token costs — assembled daily
Self-Healerhealth probes + runbooks every 5 minutes
Model Optimizerweekly cost/quality review of the model chain
Deep Scanner & Audit Agentsparallel weekly code review and fixes
Pollen & News Monitorsexposure alerts, news digest pipeline
Backupsdaily OpenClaw + database backups, verified
Part 4 · built and running ~2.5 min

A day in my life — Sat, Jul 25 · transfer day, Portugal trip

06:45
☕
Briefing ready before I wakeweather · pollen · calendar · spend — auto-generated
08:10
🧭
Travel agent nudges firstcheck-out 11:00 · A28 clear · LH1179 confirmed
11:20
🔧
Cert expires → self-healedrenewed · verified · one push: “nothing to do”
13:05
🏠
House preps our returnhot water · EV · fridge — ordered before we pack
15:30
💡
Idea at the beach bar → AutoDo2 lines, picked up by the next sprint
17:20
🔁
Model quota dies → fallbackDeepSeek takes over mid-task — nobody notices
21:10
📸
Receipt photo → taxes/2026read · classified · filed — accountant-ready
The point: I didn’t operate anything. The system ran itself — I just lived the day.
Wrap-up ~10 min incl. Q&A ~8

What’s worth copying

The map

Seven principles — the checklist

Judge any agent system with it: determinism, observability, self-healing, model strategy, coverage, autonomy, found = fixed. Works on what you already run.

The pattern

The architecture — the blueprint

Build from it: channels → gateway → model mesh → scheduler → self-healer → registry, on one box. Ours is one instance of the shape — the full recipe is below.

Habit

Found = fixed

Fix issues the session you find them.

Signal

Fail loudly

What returns “OK” while doing nothing?

Economics

Models are infrastructure

Fallback chains, cost meters, peak routing.

Leverage

Automate the second time

Any fix done twice becomes a runbook.

Steal with pride — agent-build-prompt.md · scroll ↓ open raw →
# Build-Your-Own Autonomous AI Agent — Agent Prompt

> Copy everything below the line and give it to your AI agent (Claude Code, OpenClaw, Cursor, Devin, …).
> It contains the full philosophy, architecture, file formats, algorithms and step-by-step build order distilled from 200 days of running a production autonomous agent system — written so a competent AI agent can replicate the logic without access to the original setup.

---

## THE PROMPT

You are going to help me build a **long-running autonomous AI agent system** — not a chatbot, not a demo. The goal is a system that is:

1. **Reliable** — deterministic where determinism matters, observable everywhere
2. **Self-healing** — detects its own failures and remediates them automatically
3. **Self-optimizing** — continuously reviews its costs, models and code quality
4. **Proactive** — acts on schedules and events instead of waiting to be asked

You will build this iteratively, on a single small server, with me as the only human approver. Before writing any code, read this entire brief. Then propose a phased plan (see phases below), confirm it with me, and execute phase by phase.

### Non-negotiable principles (in priority order)

1. **Determinism.** Anything that must be reliable 100% of the time is a script, not an LLM call. LLMs are for judgment (writing, reviewing, deciding under uncertainty), never for data retrieval, arithmetic, scheduling, or routing. If I would be annoyed the output was different yesterday, it must be code.
2. **Observability.** A failure nobody sees is a failure that persists. Every process must report failures loudly (non-zero exit + log + notification). "It ran" is not "it worked" — health checks must verify *output*, not just process liveness. All token usage is metered from day one.
3. **Self-healing.** Every manual fix performed twice becomes an automated runbook. Health checks feed a self-healer that can restart services, rotate logs, free disk, and switch providers — with an escalation path to me when remediation fails.
4. **Model strategy.** Models are infrastructure, not magic. Route each task to the cheapest model that does it well. Maintain a fallback chain across ≥2 providers. Meter every call. Never let a broken fallback cascade into the most expensive model. Re-evaluate the chain when new models publish — measured, not hype.
5. **Coverage.** If it runs but isn't registered, it doesn't exist. Maintain two synchronized records: a human-readable INVENTORY.md (what exists and why) and a machine-readable ops/registry.json (health-check type, ports, heal runbook per service). Adding a service means updating both in the same session.
6. **Autonomy as a dial.** Grant exactly the autonomy needed to close each loop — no more. Anything touching money, external communications, or irreversible actions requires explicit human approval (one-tap, in chat). Everything the agent does leaves an audit trail.
7. **Found = fixed.** Every bug found is fixed in the same session it's found. No "log and revisit." After fixing, add a guardrail so that class of bug cannot silently recur.

---

## Part I — The decision framework

### Script vs. LLM: the routing table

Before writing any component, classify every operation:

| Operation | Implementation | Why |
|---|---|---|
| Fetching weather / API data | Script | Deterministic, cacheable, free of hallucination |
| Arithmetic, comparisons, thresholds | Script | LLMs miscount; a bug in code is fixable, a "bug" in a model is a reroll |
| Scheduling, cron timing, retries | Script | Must fire exactly once, on time |
| Routing/branching logic | Script | Testable, auditable |
| Prose generation (briefings, summaries) | LLM | Judgment + writing |
| Code review, bug triage, drafting | LLM | Judgment |
| Choosing between ambiguous options under uncertainty | LLM (with constraints) | Judgment — but output must be validated by a script when it triggers an action |

Rule of thumb: **the LLM writes the words, the script moves the bytes.** A briefing is assembled by scripts (data) and only the connecting prose comes from a model. If a task can be expressed as a function, it must be a function.

### The autonomy dial (applied per action class)

| Action class | Autonomy level | Mechanism |
|---|---|---|
| Read files, run local checks, write memory | Full | No gate |
| Fix a bug in agent-owned code, restart a service the agent registered | Full, logged | Audit trail entry |
| Send me a message/notification | Full, logged | Rate-limited, quiet hours |
| Create/modify tasks on the internal board | Full, logged | — |
| Send email, post publicly, spend money, modify infrastructure config, change model chain, expand permissions | **Human approval required** | One-tap approval in chat, with idempotency (see Part IV) |
| Anything irreversible (delete data, revoke access) | **Human approval required** | Same, plus a typed confirmation for destructive ops |

Never "solve" an approval requirement by batching it into a broader pre-approval. If in doubt, ask.

---

## Part II — Workspace layout (replicate this shape)

One directory is the agent's home. Everything — code, memory, state — lives inside it, so backup = one directory (+ databases).

```
agent/
├── AGENTS.md            # operating rules, loaded every session
├── SOUL.md              # persona/tone directives
├── USER.md              # facts about the human (timezone, preferences)
├── TOOLS.md             # local config notes, gotchas (which tools exist, quirks)
├── memory/              # agent memory — see Part V
│   ├── YYYY-MM-DD.md    # daily notes (raw log)
│   ├── MEMORY.md        # curated long-term memory (compact, < 8 KB)
│   ├── ref-*.md         # detailed reference docs distilled out of MEMORY.md
│   ├── heartbeat-state.json   # last-run timestamps for every periodic task
│   └── *.json           # state files (dedupe caches, escalation counters)
├── docs/
│   ├── INVENTORY.md     # what exists and why (human-readable registry)
│   └── guides, architecture notes
├── ops/
│   └── registry.json    # machine-readable service registry (schema below)
├── scripts/             # standalone deterministic scripts (one job each)
├── tools/               # small web apps / services, one dir each
├── skills/              # reusable procedure packages (SKILL.md + assets)
├── projects/            # larger multi-component projects
└── archive/             # anything deprecated — deleted after a grace period
```

**Rules:**
- Scripts stay flat in `scripts/` (no deep nesting) — a flat dir is greppable, audit-able, and hard to orphan.
- Every new component updates `docs/INVENTORY.md` **and** `ops/registry.json` in the same session it's created (Principle 5).
- `archive/` is not a junk drawer: items get a deletion date in a header comment, and a subtraction pass actually deletes them.

---

## Part III — The registry and the self-healer

### ops/registry.json schema

```json
{
  "services": [
    {
      "name": "example-app",
      "kind": "webapp",
      "location": "tools/example-app",
      "port": 3000,
      "process": "pm2:example-app",
      "purpose": "one sentence: what it does and who it's for",
      "healthcheck": {
        "type": "http",
        "target": "http://127.0.0.1:3000/health",
        "expect": 200,
        "validate_body": "\"status\":\"ok\""
      },
      "heal": ["pm2_restart:example-app"],
      "criticality": "high|medium|low",
      "backup": {"included": true, "paths": ["tools/example-app/data"]},
      "owner": "agent",
      "notes": "quirks, restart caveats"
    }
  ],
  "scripts": [
    {
      "name": "disk-monitor",
      "location": "scripts/disk_monitor.py",
      "schedule": "cron:*/10 * * * *",
      "healthcheck": {"type": "last_success", "max_age_minutes": 15,
                      "state_file": "memory/state/disk-monitor.json"},
      "heal": ["rerun"],
      "criticality": "medium"
    }
  ]
}
```

Health-check types to support: `http` (status + body substring), `process` (PM2/systemd status), `port` (TCP connect), `last_success` (timestamp in a state file — this is what catches "cron reports OK but does nothing"), `certificate` (actual expiry validation, not just a TCP handshake).

**Validate the check itself:** every health check must be tested against both a healthy and a deliberately broken target before you trust it. A check that never fails is worse than no check.

### Self-healer design

Run every 5 minutes from cron. Algorithm:

```
for each entry in registry:
    result = run_healthcheck(entry)
    if result.ok:
        reset escalation counter for entry
        continue
    # failure:
    counter = increment_failure_counter(entry)      # persisted in memory/state/
    if counter == 1:  log + silent                 # transient noise: watch only
    elif counter in 2..3:
        for step in entry.heal:  execute(step)      # runbook: restart, clean, rerun
        recheck; if ok: log "healed" + notify (one short message)
        else: fall through
    elif counter >= 4: ALERT (human)                # escalation: loud, with context
                                                      # include: what failed, what was
                                                      # tried, last known-good time, logs tail
write summary state file (JSON) for the heartbeat to read
exit non-zero if any alert fired                     # cron must see failures too
```

Heal runbooks are ordered, idempotent steps like `pm2_restart:<name>`, `clean_logs:<dir>`, `rerun`, `switch_provider:<name>`. Never put anything destructive in a runbook — destructive actions escalate to the human, always.

Two design constraints that matter in practice:
1. **Notify once per incident, not once per 5-minute poll.** The escalation counter gates alerts; a healing event gets exactly one summary message ("service X failed, restarted, healthy again — no action needed").
2. **Every heal action is logged** (timestamp, entry, steps, outcome) to a run-history file. Patterns in that history (same service failing weekly) are themselves a finding — surface them in the weekly audit.

---

## Part IV — The heartbeat, scheduler, and approvals

### Scheduler cadences

Don't invent cadences per task — use a small fixed ladder so the system is predictable:

| Cadence | Jobs |
|---|---|
| every 5 min | self-healer sweep, rate-limit monitor |
| every 30 min | task dispatcher (picks next board task), domain-specific monitors |
| every 2 h | token/cost dashboard cache |
| hourly | time-sensitive monitors (travel, alerts) |
| daily | morning briefing, data hygiene |
| weekly (staggered: Mon deep scan, Wed model report, Sun audit/housekeeping) | maintenance |
| heartbeat (every 30–60 min) | agent session for periodic tasks too irregular for cron |

### Heartbeat protocol

The heartbeat is a recurring *agent* session (not a script) that handles irregular/periodic work. It must be **idempotent and quiet by default**:

1. Read `memory/heartbeat-state.json` — a map of task → last-run timestamp.
2. For each periodic task, run it only if enough time has passed (e.g. weekly task: > 6 days).
3. Update the state file after each task (atomic write: temp file + rename — never write JSON in place).
4. **Notification policy:** if nothing happened, reply with a fixed silent token (`HEARTBEAT_OK`) that the channel layer suppresses. No "all clear" messages, no summaries. Only message the human when a task completed, something was fixed, or a decision is needed.
5. Respect quiet hours (e.g. 23:00–08:00 local) for anything non-urgent; queue it for the morning heartbeat.

Frequent checks that cron can do deterministically (service health, rate limits) get **dedicated cron jobs**, not heartbeat logic — never duplicate a check in both places. The heartbeat is only for work that needs judgment.

### Approval gates with idempotency

Approvals arrive as chat buttons (`approve_x` / `reject_x`). Humans double-tap. Therefore:

1. On every approve/reject callback, check a dedupe cache (`memory/action-log.json`): if the same target+action was processed in the last 5 minutes → reply "already handled" and stop.
2. Otherwise execute once, then log `{target, action, timestamp}` to the cache.
3. Every external action (email sent, trade placed, post published) appends to an append-only audit log with the triggering approval id.

AutoDo-style pre-approvals: specific recurring actions can be pre-approved by name ("daily briefing may send email to address X"). The pre-approval list lives in a config file the agent may read but never write.

---

## Part V — Memory architecture

The agent restarts with amnesia; the files *are* the memory. Three layers:

1. **Daily notes** (`memory/YYYY-MM-DD.md`) — raw append-only log of what happened: fixes, decisions, findings, failures. Cheap to write, never edited (append-only; corrections are new entries).
2. **Curated long-term memory** (`memory/MEMORY.md`, kept < ~8 KB) — preferences, accounts, infrastructure facts, standing directives, lessons. Distilled from daily notes periodically. Keep it compact; detailed material moves to `memory/ref-*.md` files referenced by short pointers.
3. **Session bootstrap** — every session starts by reading: SOUL.md, USER.md, today's + yesterday's daily note, MEMORY.md. This is the minimum viable continuity; wire it into the agent's system prompt loading.

**Recall protocol:** before answering anything about prior work, decisions, dates or preferences, the agent must *search* the memory files (semantic or grep), then pull only the needed lines. Never answer "from memory" about the past — the files outrank the model's context.

**Write-to-file rule:** anything worth remembering is written to a file in the same session it's learned. Mental notes don't survive restarts. This is enforced by convention, checked in the weekly audit.

**Distillation:** weekly, merge the week's daily notes into MEMORY.md (and prune what's stale). Subtraction applies to memory too: expired facts get deleted, not commented out.

---

## Part VI — Model mesh and cost control

### Fallback chain (per call)

```
chain = ["provider-a/model-primary", "provider-b/model-fallback", "provider-c/model-fallback2"]
for model in chain:
    try:    return call(model, prompt)
    except RateLimitOrQuota: continue    # only these errors trigger fallback
    except Error: raise                  # a real error must NOT cascade to a pricier model
alert("chain exhausted")                 # loud, never silent
```

Critical rules:
- Only **rate-limit/quota errors** advance the chain. Application errors raise — otherwise one broken provider silently triples your bill on the most expensive fallback.
- Reserve a premium/critical tier (if you have one) behind an *explicit* model override for high-stakes tasks only. It must never appear in the automatic chain.
- Per-call metering: every call appends `{timestamp, model, prompt_tokens, completion_tokens, cost}` to a JSONL log. From day one — retrofitting metering is much harder than having it.

### Peak router

Some providers charge 2–3× during peak hours. A tiny cron-driven config switch handles this: at peak start, rewrite the primary to a cheaper capable model; at peak end, restore. The switch edits a config file and restarts nothing else. Log every switch.

### Cost monitor + weekly report

- A dashboard job aggregates the JSONL logs: spend by model/day/task-type.
- **Anomaly alert:** if daily spend exceeds e.g. 2× the trailing 7-day average → immediate notification. This is the seatbelt: one broken fallback once burned 73% of a weekly budget in 3 days before cost metering existed.
- Weekly model-optimizer report: spend per model, health-check each provider, recommend a cheaper chain. **Report only — never auto-apply chain changes.** Chain changes are human-approved, always.

---

## Part VII — Task board and sub-agents

### The task board (single source of truth)

A Kanban (To Do → In Progress → Done) with tags and priorities. Two hard rules:

1. **Anything not fixable inline (< ~5 min, low risk) becomes a board task**, not a log line. Findings that aren't tracked don't get done.
2. Duplicate detection by title on task creation — the agent checks before creating, so audits don't spawn five copies of the same finding.

Task lifecycle: created (with context: what was tried, where the evidence is) → picked by the dispatcher or the heartbeat → worked → if it needs approval, the approval request references the task id → done with an outcome note. Tasks age: anything untouched for weeks gets surfaced in the weekly audit (do it, delegate it, or delete it).

### Sub-agents and model tiering

Spawn isolated child sessions for parallelizable work (scans, audits, data collection). They get: a scoped brief (objective, output file, write-scope, verification step), a fresh context (no parent transcript unless truly needed), and a model chosen by complexity:

| Tier | Use for |
|---|---|
| fast/cheap | boilerplate, format conversion, scan-and-report, grep sweeps |
| mid | debugging, code review, multi-file refactors, drafting |
| flagship | security review, critical algorithms, high-stakes decisions |
| premium (if any) | reserved — money, health, irreversible |

Spawn hygiene: verify providers are healthy before spawning a fleet (a silently broken provider produces empty 0-token agent deaths — preflight-check it). Each audit sub-agent writes findings to its own scratch file *as it goes*, so progress survives a context overflow. Anti-overflow protocol for agents: syntax-check everything first (`py_compile`/`bash -n`), grep for hotspots, read ≤ 200-line chunks around findings — don't read whole files reflexively.

### Skills

Reusable procedures (how to send email, how to build slides, how to triage) become skill packages: a `SKILL.md` with the procedure + supporting scripts/templates. Rules: one skill = one procedure, versioned; the agent reads the SKILL.md when the task matches, never guesses the steps; vet third-party skills before use (read the code, check what it exfiltrates); dead/duplicate skills get deleted, not archived forever.

---

## Part VIII — Build phases (do not skip the order)

Each phase has acceptance criteria. Do not start phase N+1 until N passes.

**Phase 0 — Foundation (week 1)**
VPS, process manager (PM2 or systemd), reverse proxy with automatic TLS, mesh VPN for private admin access, automated backups, one chat channel wired to one model **with one fallback**. Create AGENTS.md / SOUL.md / USER.md / TOOLS.md, `memory/` with today's daily note, `docs/INVENTORY.md`, `ops/registry.json` (can be empty arrays).
*Accept:* message round-trip works from my phone; fallback triggers when you revoke the primary key on purpose; a backup restores to a fresh directory; the agent reads its memory files at session start.

**Phase 1 — First deterministic tools (weeks 2–3)**
Scripts: morning briefing (data assembled 100% by scripts — weather, calendar, whatever feeds I choose — with the model writing only the connecting prose), disk monitor, log rotation, basic service probe. Every failure exits non-zero AND notifies.
*Accept:* I can read the briefing on my phone with zero interaction; kill a service and I get told within 10 minutes; a full disk gets cleaned before it's full.

**Phase 2 — Registry + self-healer (weeks 4–6)**
INVENTORY.md + registry.json with every existing service (do a manual census first — you will find things you forgot). Self-healer per Part III. Heartbeat per Part IV.
*Accept:* kill a registered service twice in a row → it restarts itself and I get exactly one message; kill it 4 times → I get an escalation with logs; the heartbeat is silent for 24h of healthy operation.

**Phase 3 — Cost control + model mesh (weeks 7–9)**
JSONL call metering, cost dashboard, weekly model report (report-only), peak router, rate-limit monitor.
*Accept:* I can answer "what did we spend yesterday, on which model, for what" in under a minute; forcing a provider failure costs exactly zero extra (fallback, not cascade); the anomaly alert fires on a simulated 3× day.

**Phase 4 — Autonomy with approval gates (weeks 10–13)**
Task board + dispatcher; approval buttons with idempotency; sub-agents with model tiering.
*Accept:* I can create a task by chat and find it done later with an audit trail; double-tapping an approve button does nothing bad; an audit split across 3 sub-agents completes without any of them losing findings.

**Phase 5 — Continuous improvement loop (ongoing)**
Weekly deep code scan (find → fix same session → 3 fix/retest iterations → log), weekly inventory audit (parallel agents, split scopes, findings to files, AutoDo tasks for what can't be fixed inline), weekly memory distillation, monthly subtraction pass (delete dead code, dedupe scripts, expire stale data, archive with deletion dates).
*Accept:* the weekly scan's clean result is "0 errors + N improvement proposals", never just "OK"; INVENTORY.md count matches what's actually running (verify with the process list, not the file).

---

## Part IX — Hard rules during the build

- Never send emails, messages, or external requests without my explicit approval (unless pre-approved by name for a recurring action)
- Never auto-apply model chain changes, infrastructure changes, or permission expansions — propose them
- Never swallow an exception silently; every failure path is loud and logged. Ban bare `except:` at lint level, not by good intentions
- No hardcoded secrets in code — environment/config files only, and secrets never enter logs, memory files, or git
- Private/personal data stays on the box; anything private is processed by local or private-connection models only, never sent to third-party APIs
- Every new service: registered (inventory + registry) + health check + backup coverage, in the same session it's created
- When context runs low: write state to a scratch file and continue — never lose progress silently
- Fix bugs in the same session they're found; after fixing, add a guardrail (test, lint rule, or check) so that class of bug can't silently recur

---

## Part X — Known failure modes to design against (all learned in production)

| Failure mode | Countermeasure |
|---|---|
| Cron reports "OK" while the job silently does nothing | `last_success` state-file checks — verify outputs, not liveness |
| Broken fallback cascading into the most expensive model (73% of a weekly budget in 3 days) | Only rate-limit errors advance the chain; meter everything; cost-anomaly alert |
| Hundreds of bare `except:` handlers writing to logs nobody reads | Lint-ban silent excepts; failures notify; weekly scans grep for them |
| Complex autonomous task dispatchers that churn forever without completing | Keep the autonomy loop minimal: pick task → work → done/approval. No nested self-scheduling |
| Services accumulating with zero monitoring (first audit found 4 unwatched apps) | Registry-driven coverage: no registration = doesn't exist; weekly census vs process list |
| TLS checks that pass while certificates are invalid | Validate the certificate itself, and test the check against a broken target |
| Sub-agents dying at spawn with empty 0-token responses | Provider preflight before spawning fleets |
| Context overflow losing audit progress | Per-agent scratch files written after each finding; syntax-check-first protocol |
| Double-tapped approval buttons executing twice | 5-minute idempotency cache on approve/reject callbacks |
| Memory files growing until they break context | Size cap on curated memory + weekly distillation + ref-file split |
| Heartbeat spamming "all clear" messages | Silent token on routine results; notify only on events |
| Self-healer restart-looping a broken service | Escalation ladder with counters; alert after N failures, not forever |

---

## Part XI — What to do first

1. Ask me about my environment: server, OS, chat channel(s), API keys available, budget
2. Propose the Phase 0 setup as a concrete checklist
3. Execute Phase 0, then stop and show me the result before continuing

Build this as if you'll be the one operating it at 3 AM. Because you will be.

---

*Derived from a system that grew from 1 script to 58 running components (11 services, 19 cron jobs, 28 scripts, 33 skills, 16 built apps) on one 4 GB VPS in 200 days — generalized here so none of the specifics of that setup are needed to replicate the logic.*
Closing

From a tool you operate
to a companion that runs itself

Reliable. Self-healing. Self-optimizing. Proactive.
The next 200 days: making it useful for more people.

Thank you — questions welcome.

2.0M tokens processed 52 model calls 10 feedback rounds $0 extra — flat-rate subscription — the cost of building this very presentation, me iterating with Steffen
1200 Days · Steffen Meyer · 2026