# Automation and background agent

This chapter explains **what runs when you are not typing**, how **foreground idle** behavior differs from **launchd** background services, and where to look in **Settings** and **Diagnostics**. For every toggle label, the authoritative list is [10-settings-compendium.md](10-settings-compendium.md).

---

## View → Agent submenu (full checklist)

From [04-menus-and-shortcuts.md](04-menus-and-shortcuts.md), **View → Agent** contains:

| Item | What it does |
|------|----------------|
| **Background Agent: Running \| Stopped \| Unknown** | Read-only status (green checkmark when running, stop icon when stopped, question mark when the app cannot reach the background agent). |
| **Install Background Agent…** | Creates the LaunchAgent plist under `~/Library/LaunchAgents/` and related paths; required before start/stop works. |
| **Uninstall Background Agent…** | Removes the agent; clears the “desired running” marker so Mugi does not re-bootstrap it after quit. |
| **Start Background Agent** | Starts the launchd runner when it is installed. |
| **Stop Background Agent** | Unloads the LaunchAgent process. |
| **Restart Background Agent** | Bootout then bootstrap — use after changing **Advanced → Evolution mode** options that affect background consciousness (see in-app captions). |
| **Show Background Agent Log** | Opens a window that loads `~/.mugi/logs/background.log` via the backend (truncated to ~100 KB in the UI when large). **Refresh** reloads; **Close** dismisses. |

**Unknown** status usually means the backend HTTP server is not up yet, or the status request failed—check the main window connection state first.

---

## Three layers: chat, backend, background runner

| Layer | Role | Typical triggers |
|-------|------|------------------|
| **Foreground app** | Chat, tools, idle tick *eligibility*, UI | User messages, compact panel, idle timer |
| **Local backend** | Schedules heartbeats, cron, webhooks, diagnostics | Started by the Mac app with auth token |
| **Background runner (launchd)** | Separate process for proactive queue and work when the GUI is quit | Install/start from **View → Agent** |

The app’s **local backend** is *not* the same thing as the **Background Agent**. Many features (heartbeats, webhooks, diagnostics history) only need the backend while Mugi is open. The **Background Agent** keeps a **runner** alive under launchd for work that must continue when the app is quit.

```mermaid
flowchart TB
    subgraph foreground [Foreground app]
        Chat[Chat and tools]
        IdleMgr[IdleTickManager]
    end
    subgraph settings [Settings]
        HB[Heartbeats]
        Adv[Advanced: webhooks watcher hours]
    end
    subgraph background [Background services]
        BA[Background Agent launchd]
        Backend[Python backend HTTP]
    end
    Chat --> Backend
    IdleMgr --> Backend
    HB --> Backend
    Adv --> Backend
    BA --> Backend
    Backend --> Ledger[Task ledger / Diagnostics]
```

---

## Heartbeats (Settings → Heartbeats)

Heartbeats drive **periodic** background work: memory maintenance, growth checks, optional sounds, **RSS/Atom** and **watchlist** collectors, and the global **Standard interval** (minutes).

**Continuity (foreground behavior)**

- **Continuity prompts when idle** controls whether Mugi may send **internal prompts** after quiet chat on the **current thread**. This is the main switch if you want **no automatic foreground continuity** while still using heartbeats for other tasks.
- Disabling continuity does **not** by itself turn off the separate **Idle tick** pipeline (below).

**Collectors**

- **Watchlist** and **RSS / Atom** have their own **Check interval** ranges when enabled. Use **Save Heartbeat Settings** at the bottom of the pane when shown so JSON flushes to preferences.

---

## Active hours (Settings → Advanced → Active Hours)

**Active Hours** limits **some** background noise outside your schedule:

- Heartbeat-style work, **idle ticks**, and **curiosity** respect the window when configured.
- **Cron jobs** and **inbound webhooks** are **not** gated— they wake the backend when fired.

Use **Custom schedule** for start/end times and **Days** toggles; overnight ranges are supported. Empty weekday selection is treated as always active (see compendium).

---

## Idle ticks (foreground `IdleTickManager`)

**Idle ticks** are **not** cron. They are a **foreground** timer: when the main chat thread has been idle long enough, the app `POST`s `/idle_tick` with the **current thread id**.

**Eligibility (all must pass)**

- Idle ticks **enabled** and **agent plane** enabled (shown in **Settings → Advanced** / idle status when available).
- macOS app is **active** (not background-only).
- Backend state is **ready**.
- Not in cooldown after a recent failed tick (60s).
- **No** agent run in progress, **no** voice capture, **no** non-empty draft, **no** pending attachments, **no** modal sheet, **no** onboarding, and the **current thread has at least one message**.
- User idle longer than **idle_minutes** from config (default 5).

User activity (typing, send, tab switch, focus) resets the idle clock via `noteUserActivity()`.

Skipped idle ticks often appear as **Idle** / **skipped** in the **Recent background runs** strip—this is expected when rate limits or mesh cooldowns apply server-side.

---

## Webhooks

**Inbound (Settings → Advanced → Inbound Webhooks)**

- Master toggle **Accept inbound webhooks**; secrets live in **Keychain** only.
- Per-source modes include **Notify only** vs **Full turn**; HMAC setup is per source.
- **Copy webhook URL** and token rotation buttons are documented in [10-settings-compendium.md](10-settings-compendium.md#advanced).

**Outbound (Advanced → Outbound Webhooks)**

- HTTPS targets identified by **slug**; cron **Deliver-to** references those slugs. Signatures use Keychain-backed secrets.

Tunneling (ngrok, cloudflared), tokens, and verification steps are in [Inbound webhooks](inbound-webhooks.md).

---

## File watcher (Advanced → File Watcher)

- Rules are stored under `[file_watcher]` in **`mugi_config.toml`** (path under `~/.mugi` or repo per your install).
- Each rule can be **Notify only** or **Full turn**, with glob, recursion, and debounce—see compendium for control names.

---

## Cron and “consciousness” style features

- **Cron** jobs are scheduled server-side; results can trigger **outbound webhook** delivery by slug.
- **Weekly self-review** (Advanced) can write to memory files using the utility model when enabled; **Run now** is available.
- **Evolution mode (advanced)** includes **background consciousness** and **workflow learning**. Captions require **restarting the background agent** after certain changes so the LaunchAgent-side runner reloads policy.

---

## Task ledger (Settings → Diagnostics → Recent background runs)

The ledger append-only log records **kinds** such as `heartbeat`, `idle_tick`, `cron`, `webhook`, `browser`, `file_event`, `delivery`, and others. On disk this is typically `~/.mugi/task_ledger.jsonl`.

**In the UI**

- **Run Diagnostics** refreshes **both** the doctor report **and** the ledger.
- **Refresh** under the ledger section reloads **history only** (doctor unchanged). The **skip reason catalog** from the last successful doctor is kept so hints survive a ledger-only refresh.
- **Filter by run kind:** All, Cron, Webhooks, Heartbeats, Idle, Browser (maps to backend `kind` query).
- **Filter by run status:** All; **Skipped**; **Problems** (backend merges **error** and **timeout** rows).

**How to read rows**

- **Skipped** is normal when conditions are not met (cooldowns, active hours, empty queue, etc.). Hover for tooltip text; skipped rows may show a **catalog title** on the right when the doctor shipped a `skip_reason_catalog` entry.
- **Problems** needs investigation—cross-check `~/.mugi/logs` and the doctor report.

First-line interpretation: [06-diagnostics-and-basic-troubleshooting.md](06-diagnostics-and-basic-troubleshooting.md).

---

## Compact panel

The quick panel shares backend state with the main app; returning from compact flows may reload conversation content—see [09-compact-panel-llms-and-audio.md](09-compact-panel-llms-and-audio.md).

---

## Cross-references

- Settings control list: [10-settings-compendium.md](10-settings-compendium.md)  
- Diagnostics basics: [06-diagnostics-and-basic-troubleshooting.md](06-diagnostics-and-basic-troubleshooting.md)  
- Deeper FAQ: [13-troubleshooting.md](13-troubleshooting.md)
