> ## Documentation Index
> Fetch the complete documentation index at: https://docs.myrmagent.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Scheduled Tasks

> Complete guide to cron scheduling, task chaining, and unattended automation.

# Scheduled Tasks

Create recurring tasks using natural language descriptions. Myrm's cron system supports three scheduling modes, task chaining, situation reports, and 10-layer anti-noise defense — far beyond basic cron scheduling.

## Creating a Task

### Via Chat (Natural Language)

Describe your schedule naturally in any conversation:

> "Every morning at 9 AM, scrape competitor prices and email me a comparison report"

The agent automatically detects scheduling intent and presents an approval card — once you confirm, the task is created instantly. A structured task card appears in the chat showing the task name, schedule, next run time, and bound model, with a button to jump to the management dashboard. The agent also auto-matches the best built-in blueprint template to improve task quality. Recurring schedules require explicit confirmation to prevent accidental creation.

### Cron Tool Mode (Agent Config)

By default, cron management is **discoverable** — it does not occupy your Turn1 tool schema (\~0 cron tokens). When you describe a schedule in chat, Myrm loads `cron_manage_tool` on demand.

| Setting                             | Turn1 tools             | Best for                                                        |
| ----------------------------------- | ----------------------- | --------------------------------------------------------------- |
| **Cron OFF** (default)              | Discover on intent      | Everyday chat — lean token footprint, prompt-cache friendly     |
| **Cron ON** in Agent built-in tools | Eager Turn1 (\~827 tok) | Power users who want cron callable every turn without discovery |

Enable or disable in **Agent config → Built-in tools → Scheduled tasks (Cron)**. On cloud/sandbox plans without cron entitlement, the toggle is disabled with an upgrade link — the same rule applies to GUI, REST API, and Agent paths.

Both discover (default) and eager modes are covered by automated tests and real-model WebUI end-to-end verification.

### Via GUI

Navigate to **Settings > Scheduled Tasks** and click **Create** to use the visual configuration dialog with schedule picker, model selector, and delivery options. Choose from **14 blueprint templates** (morning briefing, weekly review, wiki morning delta, read-it-later ingestion, etc.) for one-click setup — the same templates the Agent uses via API. The `GET /cron/blueprints` API returns localized **title**, **description**, and **prompt\_template** for **en, zh, ja, de, and ko**; the catalog loads exclusively from this API (retry on failure). Slot labels use frontend locale keys.

## Task Types

| Type                | Description                                                                 | LLM Cost    |
| ------------------- | --------------------------------------------------------------------------- | ----------- |
| **Agent**           | Full AI agent execution with prompt, model, and memory                      | Token-based |
| **Shell**           | Direct shell command (local/desktop only, hidden in cloud)                  | Free        |
| **Script (Python)** | Sandboxed Python script with 60s timeout (works everywhere including cloud) | Free        |

### Script Mode (Zero LLM Cost)

Select **Script (Python)** when creating a task to run Python code without any LLM invocation. The script executes in an isolated subprocess with a 60-second timeout.

* **stdout becomes the output** — non-empty output is delivered to configured channels, empty output is silently skipped
* **Skip signals**: Print `[SKIP]` or `{"action": "skip"}` to abort the task gracefully
* **Cloud-safe**: Unlike shell commands, Python scripts are available in all deployment modes (local, desktop, cloud sandbox)
* **Use cases**: API health checks, data monitoring, RSS filtering, database audits

## Three Scheduling Modes

| Mode         | Syntax                   | Example                  |
| ------------ | ------------------------ | ------------------------ |
| **CRON**     | Standard cron expression | `0 9 * * *` (daily 9 AM) |
| **INTERVAL** | Every N minutes (min 5)  | `every_minutes=30`       |
| **ONCE**     | ISO 8601 one-shot        | `2026-06-01T10:00:00`    |

## Session Modes

Control how the agent handles conversation context across repeated executions:

| Mode                   | Behavior                                                                         | Best for                                                      |
| ---------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------- |
| **Isolated** (default) | Fresh context every run — no memory of previous executions                       | Independent one-off tasks                                     |
| **Main**               | Continues the agent's main chat thread (loads last 30 messages)                  | Tasks that need full conversation history                     |
| **Daily**              | Automatically injects same-day run outputs into prompt; resets at midnight (UTC) | Hourly monitoring, trend detection, recurring data collection |

### Daily Mode in Action

When a task runs in **Daily** mode:

1. The agent sees previous same-day outputs chronologically (up to 5 runs, truncated to 500 chars each)
2. The first run of a new day includes yesterday's final output as a brief summary
3. This enables the agent to detect trends — e.g., "CPU went from 45% → 72% → 90% over the last 3 hours"

Daily mode uses zero extra storage (reuses existing run records) and does not affect prompt cache efficiency.

## Task Chaining (context\_from)

Chain tasks together so one task's output feeds into another:

> "Task A collects daily sales data, Task B analyzes it and generates a report"

Set `context_from` to inject referenced jobs' latest successful output into the next task's prompt.

## Heartbeat Monitoring

Built-in periodic self-check (`__heartbeat__`) with **Situation Report** injection — the agent reviews memory changes, pending reminders, due commitments (follow-up tracking), and system health before each tick, transforming blind checks into intelligence-driven actions. Due commitments are automatically marked as delivered to prevent duplicate notifications.

### Agent Binding

Bind any Agent Profile to the heartbeat in **Settings → System → Heartbeat**. The heartbeat inherits the bound Agent's model, system prompt, skills, and tool configuration — no need to configure these separately.

* **One dropdown**: Select from built-in or custom Agents.
* **Model inheritance**: The UI shows which model will be used (e.g. "Using model: openai/gpt-4o-mini").
* **Unbind**: Switch back to "Default Agent" to clear the binding — heartbeat reverts to the global default model.
* **Agent Profile SSOT**: Update the Agent's model once and all bound heartbeats automatically use the new model at next execution.

## Scheduler Liveness Dashboard

A real-time visual indicator at the top of the Cron Dashboard shows scheduler health at a glance:

| Status     | Meaning                                                    | Visual             |
| ---------- | ---------------------------------------------------------- | ------------------ |
| **Green**  | Healthy — scheduler running and ticking normally           | Animated pulse dot |
| **Yellow** | Degraded — starting up, stale tick (>120s), or tick errors | Static amber dot   |
| **Red**    | Stopped — scheduler not running or missing timer           | Static red dot     |

The badge polls `GET /api/v1/cron/scheduler/health` every 30 seconds. It pauses automatically when the browser tab is hidden and refreshes immediately when you switch back — saving server resources in multi-tab workflows.

Hover over the badge to see the exact last tick timestamp and error count.

## Smart Delivery

| Feature                   | Description                                                                                                                                                                                                    |
| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Multi-channel**         | Results delivered via chat, webhook, Feishu, Slack, or any of 35+ channels                                                                                                                                     |
| **Feishu/Lark bot hooks** | Custom bot webhook URLs (`open.feishu.cn` / `open.larksuite.com`) receive **`msg_type=text`** payloads — works out of the box; no OAuth chat\_id wiring                                                        |
| **WeCom group bot hooks** | Paste a `qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...` URL — auto-detected, sends **`msgtype=markdown`** with bold headers and status emoji; retry with exponential backoff; validates `errcode` responses |
| **Inline IM routing**     | Script tasks show a channel selector at creation time — pick Telegram/Slack/Feishu/Discord directly, no extra steps                                                                                            |
| **\[SILENT] skip**        | When there's nothing actionable, the agent responds `[SILENT]` to skip notification                                                                                                                            |
| **Failure alerts**        | Separate `failure_webhook_url` for ops alerting                                                                                                                                                                |

### Script Delivery (Inline Channel Selection)

When creating a **Script (Python)** task, the dialog shows an inline delivery target selector:

1. **Chat** (default) — output stays in the task history
2. **Connected IM channels** — auto-discovered from your configured integrations (only connected channels appear)
3. **Target field** — specify chat ID, channel name, or webhook URL depending on the selected channel

This eliminates the need to navigate to a separate delivery configuration page. The model selector is automatically hidden for script tasks since no LLM is involved.

## Delivery Assurance (Opt-In Post-Run Review)

For **Agent** scheduled tasks (not script-only jobs), you can enable an optional delivery review per Agent:

1. Open **Settings → Agents → \[your agent] → Capabilities**
2. Under **Delivery Assurance**, turn on **Scheduled Task Verification**
3. Save — the setting persists per Agent (default is off)

**What happens when enabled:**

| Step                                                         | User-visible effect                                                                       |
| ------------------------------------------------------------ | ----------------------------------------------------------------------------------------- |
| Cron run completes successfully                              | Run shows as successful (unchanged)                                                       |
| Run used side-effect tools (file write, bash, browser, etc.) | A built-in reviewer sub-agent runs afterward (≤ 120s, bounded by job timeout)             |
| Review passes                                                | Run history shows a **delivery review: pass** badge                                       |
| Review fails                                                 | Run **still shows success**, but history adds an amber warning — task is not auto-retried |

**Why this exists:** Unattended jobs can report “done” while side effects are wrong. This gives you a structured audit trail in the Cron run list — competitors typically only offer silent turn-end guards or goal rubrics, not **opt-in Cron run metadata + WebUI badges**.

**Cost control:** Default off; read-only runs skip review; interactive chat is unaffected (no extra Turn1 tools).

## Acceptance Criteria (Structured Output Verification)

Define measurable quality checks that automatically verify your task's output after every run. Unlike Delivery Assurance (LLM-based review), acceptance criteria are **deterministic** — shell commands or semantic checks that gate success/failure.

### Adding Criteria

When creating or editing a task in the GUI, expand the **Acceptance Criteria** section (agent-type tasks only):

1. Click **Add criterion**
2. Choose type:
   * **Shell** — a shell command that must succeed (exit code 0) or match expected output
   * **Semantic** — an LLM judge evaluates if the output meets a natural-language description
3. Describe the check (e.g., "Output JSON has at least 3 items" or "Report mentions all 5 competitors")

### How It Works

| Path                                  | Trigger                                | Mechanism                                                     |
| ------------------------------------- | -------------------------------------- | ------------------------------------------------------------- |
| **Goal queue** (active goal exists)   | `create_goal(acceptance_criteria=...)` | Harness `VerificationGatekeeper` runs after goal completion   |
| **Direct execution** (no active goal) | Post-run in `_run_once`                | `acceptance_verification.py` bridges `VerificationGatekeeper` |

Both paths use the same `VerificationGatekeeper` from the harness framework — criteria are evaluated identically regardless of execution mode.

### Failure Behavior

* If **any** criterion fails → run status is marked **FAIL**
* Failure delivery (configured alert channels) is triggered
* The task is **not** auto-retried (same as normal failures)

### Example

A daily price scraper with acceptance criteria:

| Type     | Description                                                  |
| -------- | ------------------------------------------------------------ |
| Shell    | `jq '.items \| length' /tmp/prices.json` must output `>=3`   |
| Semantic | "Report includes pricing data for all monitored competitors" |

If the scraper only fetches 2 of 3 competitors due to a site change, the shell check fails immediately — you get an alert instead of discovering missing data days later.

### API Support

The `POST /cron/jobs` and `PATCH /cron/jobs/:id` endpoints accept an `acceptance_criteria` array:

```json theme={null}
{
  "acceptance_criteria": [
    { "type": "shell", "description": "jq '.count' output.json >= 5" },
    { "type": "semantic", "description": "Summary covers all key metrics" }
  ]
}
```

## 10-Layer Anti-Noise Defense

| Layer | Mechanism              | Effect                                                    |
| ----- | ---------------------- | --------------------------------------------------------- |
| 1     | Active Hours           | Only runs within configured time window                   |
| 2     | \[SILENT] instruction  | AI self-judges no-value content, skips push               |
| 3     | Output Hash dedup      | Identical results not re-pushed                           |
| 4     | Cooldown period        | Enforced minimum interval between pushes                  |
| 5     | Max Fires limit        | Auto-stops after N executions, push notification sent     |
| 6     | Skip If Active         | Won't spawn new instance while previous runs              |
| 7     | Expires At             | Auto-stops at expiration datetime, push notification sent |
| 8     | PreFlight Condition    | Sandboxed probe script must pass before execution         |
| 9     | No-content Skip        | Heartbeat skips LLM call when all sections empty          |
| 10    | Failure Alert Cooldown | Even failure alerts have cooldown periods                 |

## Incremental Monitoring

Enable intelligent delta detection so tasks only report genuinely new content:

| Setting                   | Purpose                             |
| ------------------------- | ----------------------------------- |
| `monitor_config.enabled`  | Activates incremental monitoring    |
| `monitor_config.ttl_days` | Baseline auto-resets after this TTL |

When enabled, the system computes a delta between current output and the stored baseline. If no new content is detected, delivery is silently skipped (exit\_code=0). Only genuinely new information triggers notifications (exit\_code=1), with just the delta delivered to channels.

Baseline auto-resets after TTL expiration, ensuring long-running monitors don't accumulate stale state.

**Agent dialogue control:** Monitoring can be fully configured through conversation — tell the Agent "only notify me when the price changes" to enable set-based monitoring, or "notify me every time" to disable it. The Agent supports `monitor_type` values `set`, `hash`, `timeseries`, and `off` (to disable).

## Integrity Verification (Merkle Chain)

Every execution is hash-chained to its predecessor using SHA-256, creating a tamper-evident audit trail:

* Verify chain integrity via `POST /api/v1/cron/{job_id}/verify-integrity`
* Detects gaps (missing runs), tampering (modified outputs), or reordering
* Enterprise compliance: cryptographic proof that scheduled tasks ran as expected

## Event-Driven Triggers

Beyond time-based scheduling, tasks can be triggered by external events:

| Trigger Type        | How It Works                                                                                                                                                                                                                                      |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Event Regex**     | Incoming IM channel messages matching a regex pattern trigger the task — configured in the GUI, no webhook URL required                                                                                                                           |
| **System Event**    | Structured events (source + event\_type + filters) trigger automatically                                                                                                                                                                          |
| **Webhook**         | External services send HTTP POST with HMAC-SHA256 signature verification                                                                                                                                                                          |
| **Stream (WS/SSE)** | Outbound WebSocket or Server-Sent Events connection — listens for real-time events from external services. Works behind NAT/firewall without exposing a public URL. Supports JSONPath + regex filtering, auto-reconnect with exponential backoff. |
| **Poll**            | Periodic HTTP GET with content-hash change detection — fires only when the response content changes. Supports JSONPath field extraction for targeted monitoring.                                                                                  |

Trigger context (the matched message, event payload, webhook body, stream data, or polled content) is injected into the Agent's prompt so it knows *why* it was triggered.

### IM Message → Event Trigger (Architecture)

Inbound messages from connected channels (Feishu, Telegram, Slack, etc.) can fire event-triggered cron jobs automatically:

1. **Connect a channel** in Settings — long-connection or webhook ingress
2. **Create a task** with trigger type **Event** — set channel filter and regex pattern
3. **Messages flow** through `AgentRouter` — commands (`/stop`, `/new`), reactions, and pending approvals are skipped; matching messages dispatch once

:::tip Cloud & Local Parity
In cloud deployments, the Control Plane ingress endpoint only enqueues messages. Event dispatch happens in the sandbox router — preventing duplicate triggers that would occur if both layers dispatched.
:::

**Tested scenarios:** normal dispatch, command skip, approval skip, reaction skip, duplicate message dedup — 16 automated tests verify the full path.

### Remote Node Events (Mobile / IoT Automation)

External systems can report structured events to your Agent via HTTP — no always-on connection, no SDK required:

```bash theme={null}
curl -X POST https://your-myrm.example/api/v1/remote-access/node/events \
  -H "Authorization: Bearer <pair_token>" \
  -H "Content-Type: application/json" \
  -d '{"source": "ios_shortcuts", "event_type": "location_arrived", "payload": {"location": "home"}}'
```

| Field        | Description                                                                                    |
| ------------ | ---------------------------------------------------------------------------------------------- |
| `source`     | Identifier of the reporting system (e.g., `ios_shortcuts`, `android_tasker`, `home_assistant`) |
| `event_type` | The event name (e.g., `location_arrived`, `wifi_connected`, `battery_low`)                     |
| `payload`    | Arbitrary JSON context passed to the triggered Agent task                                      |

**Authentication:** Requires a valid `pair_token` (hub\_list scope) issued via QR code pairing, or an active WebUI session.

**How to set up:**

1. Pair your mobile device via Settings → Remote Access → QR Code
2. Create a scheduled task with trigger type **System Event** — set source and event\_type filters
3. Configure iOS Shortcuts / Android Tasker / Home Assistant to POST events to the endpoint

The event is automatically matched against your configured SystemEventTrigger rules and fires the bound Agent task with the payload injected as context. Rate-limited to 60 requests/minute.

:::tip Zero Battery Drain
Unlike competitors that require persistent WebSocket connections (draining battery and requiring background keep-alive hacks), our HTTP-based approach fires only when an event occurs — zero idle power consumption.
:::

## Crash Recovery

Myrm's scheduler auto-recovers after unexpected restarts with a 3-phase startup recovery:

1. **Stale-Run Recovery** — detects tasks marked "running" that never completed (process crash) and reschedules
2. **Missed-Slot Replay** — identifies cron slots that were missed during downtime and replays them
3. **Grace Window** — tasks within the misfire grace window execute immediately; expired ones skip to next cycle

## Security

* **Fail-closed by default**: tasks without declared `required_capabilities` are denied shell/code/MCP execution with clear guidance
* **Per-job capability fence**: each task independently declares required permissions (`shell_exec`, `file_write`, `mcp_invoke`, etc.) — declared capabilities are pre-approved, undeclared ones are denied
* **BLOCK-level absolute denial**: destructive commands (`rm -rf /`, `sudo`, `DROP DATABASE`, etc.) are always rejected even within approved capabilities
* **Prompt injection scanning** (12 patterns) before every execution
* **ContextVar self-scheduling guard** prevents infinite task chains (cron job cannot create new cron jobs)
* **Budget enforcement** blocks execution when daily budget is exceeded
* **ReDoS protection** on event trigger regex patterns
* **SSRF protection** on webhook delivery URLs

## Desktop Power Management

On Tauri desktop, scheduled tasks automatically acquire a **PowerLock** to prevent system sleep during execution:

* **macOS**: `caffeinate` subprocess
* **Linux**: `systemd-inhibit`
* **Windows**: `SetThreadExecutionState`

The lock is RAII-guarded and auto-released when the task completes, even on failure.

## Blueprint Templates (One-Click Setup)

Create common automation tasks in 3 clicks with pre-built templates. Navigate to **Scheduled Tasks > Create > From Template** to browse available blueprints.

| Blueprint                   | Category     | Slots                                                 | Description                                                                            |
| --------------------------- | ------------ | ----------------------------------------------------- | -------------------------------------------------------------------------------------- |
| Morning Briefing            | Productivity | time, weekdays                                        | Daily briefing on news, weather, and reminders                                         |
| Weekly Review               | Productivity | time, day                                             | Summarize weekly progress and plan ahead                                               |
| Custom Reminder             | Personal     | time, message                                         | Recurring reminder with your own message                                               |
| News Digest                 | Information  | time, weekdays, topic                                 | Curated news digest on chosen topics                                                   |
| Evening Winddown            | Personal     | time, weekdays                                        | Calming daily summary and tomorrow's preview                                           |
| Local Health Check          | DevOps       | time, weekdays                                        | Monitor system CPU, memory, and disk                                                   |
| Competitor Watch            | Business     | time, day, competitors                                | Track competitor news and product updates                                              |
| Habit Check-in              | Personal     | time, habits                                          | Daily habit tracking with streak awareness                                             |
| Daily Learning              | Education    | time, weekdays, subject                               | Get a curated learning topic each day                                                  |
| **Social Media Watch**      | Business     | time, weekdays, brand, platforms, keywords (optional) | Monitor brand mentions and sentiment across social platforms                           |
| **Read-it-Later Ingestion** | Productivity | time, weekdays                                        | Auto-ingest saved articles into your knowledge base daily                              |
| **Wiki Morning Delta**      | Productivity | time, weekdays                                        | Daily vault change digest (≤3 lines); skips delivery when nothing changed (`[SILENT]`) |

**Second Brain quick start (Settings → Wiki):** One click applies the preset agent plus **both** Read-it-Later (06:00) and Wiki Morning Delta (07:00) cron jobs — no manual blueprint wiring. Re-apply is idempotent if you applied an earlier preset version that only had one cron.

Automated brand monitoring using browser automation — works on platforms without public APIs (Xiaohongshu, Weibo, Twitter/X, LinkedIn, Douyin).

**Setup:** Select the Social Media Watch template → fill in your brand name and target platforms → keywords are optional (brand-only monitoring works) → choose delivery channel → done.

**What it does each run:**

1. Navigates target platforms via browser automation
2. Searches for brand mentions using configured keywords
3. Classifies sentiment (positive/neutral/negative)
4. Produces a structured intelligence report
5. Flags strongly negative posts for immediate attention
6. Delivers via configured IM channel (or stays silent if nothing notable)

**Key advantage:** Unlike API-dependent tools, browser automation works on any platform with a login session — no API keys, no rate limits, no breaking changes when platforms update their APIs.

## Examples

| Description             | Schedule              | Features Used                              |
| ----------------------- | --------------------- | ------------------------------------------ |
| Daily report            | `0 9 * * *`           | Cron + channel delivery                    |
| Weekly backup           | `0 2 * * 1`           | Cron + shell command                       |
| Hourly monitoring       | `0 * * * *`           | Interval + \[SILENT] skip                  |
| One-time reminder       | `2026-06-01T10:00:00` | Once + chat delivery                       |
| Data pipeline           | `0 8 * * *`           | Cron + context\_from chaining              |
| Heartbeat self-check    | Configurable          | Heartbeat + Situation Report               |
| API uptime monitor      | `*/5 * * * *`         | Script mode + \[SKIP] on success           |
| Database audit          | `0 6 * * *`           | Script mode + multi-line output            |
| Social media monitoring | `0 9 * * 1-5`         | Blueprint + browser automation + \[SILENT] |

## Related Features

* **[Growth Dashboard](/core-concepts/memory-system#growth-dashboard)** — AI Daily Wrap auto-generates a summary of your day's activity, keywords, and suggestions. The Growth Dashboard visualizes activity heatmaps, memory health radar, skill evolution events, and cost savings.
* **[Statistics API](/api-reference/statistics)** — Programmatic access to daily wrap data, growth metrics, and usage analytics.
