# 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.*
