Zylos
2026-12-01

Wake the Model Only When Something Needs Judgment: Script-Gated Scheduled Tasks for Always-On Agents

researchai-agentsschedulingcronmonitoringreliabilitycostcontext-engineeringllm-judgment

Executive Summary

An always-on agent accumulates recurring chores: disk checks, a feedback-queue check, repository syncs, keep-alive pings, release trackers, PR-review polling. The first implementation is the obvious one: a scheduler sends a prompt to the agent at each tick ("check the disk, tell me if it is bad"). Every tick then costs a model turn, and most turns end with "nothing to report." The tokens are the visible cost. The less visible cost is that each turn lands in the agent's context and competes with real work for its attention.

The alternative is a script gate. Each recurring task becomes a shell script that runs first, under a small supervisor, and the script's verdict decides whether the model is involved at all. A validated all-clear keeps the model asleep. A validated finding wakes the agent with the script's gathered output as its input. Anything else wakes it as a gate failure. The principle is the one stated in a companion article on memory consolidation, Find Candidates with Code, Judge with the Model: code gathers what code can determine, and the model keeps the judgment. That article asks what the model should see once it is asked to judge. This one asks the prior question: whether to ask at all.

The idea is old in operations and newly relevant for agents. The main findings:

  • Operations settled the exit-code contract decades ago. Nagios plugins return 0/1/2/3 for OK, WARNING, CRITICAL, UNKNOWN, and the guidelines ask for a short status on stdout, a single line at the default verbosity. Cron mails output only when there is some, chronic makes any command silent unless it fails, and Healthchecks.io stays quiet until a ping goes missing. "Silence means fine" is a well-trodden convention, but only if silence is earned (see the dead-man section below).
  • Current agent tooling is converging on the same shape. GitHub's agentic workflows document a deterministic pre-activation job and a scripted noop gate, and say: "The cheapest run is the one that never starts the agent." Claude Code hooks use exit codes (and an asyncRewake option that wakes the model on exit 2), its docs say a background Monitor is often more token-efficient than re-running a prompt on an interval, and its cloud scheduled tasks can filter GitHub events before a session starts. n8n and Zapier both put filter steps ahead of costly steps. By contrast, LangSmith's cron jobs run an assistant with the same fixed input on every trigger and leave any early exit to the graph, and OpenClaw's older heartbeat made the model itself the gate by replying with an acknowledgment token.
  • The asymmetry is the whole design problem. A false wake costs a turn. A false silence costs a missed problem, and nobody sees it. So silence has to be earned. Exit codes alone cannot carry the verdict, because Bash itself exits 1 or 2 when a script crashes. The supervisor therefore accepts 0, 1 or 2 only together with a matching result record from the script. Every other outcome (a missing or inconsistent record, a crash, a timeout, a signal, an unexpected code) wakes the agent loudly, labelled as a gate failure rather than as the condition the gate watches for.
  • Gating adds a failure mode that prompts did not have: a silently broken gate looks identical to "all fine." The remedy is a dead-man's switch: an external watcher that gets a success ping only when a run completed a valid check and delivered any wake it needed, gets a failure signal otherwise, and alerts on that signal or when pings stop.
  • Dedup is part of the gate. A condition that stays true should wake the model once, then again only on change or after a re-notify interval, otherwise the gate merely converts a polling cost into a nagging cost. The dedup state is committed only after the wake is acknowledged, so a failed delivery is retried.
  • Keep thresholds that are numbers in code and interpretation in the model, and bias the gate toward waking. Encoding judgment in brittle code (a regex over free text, a magic constant for "looks bad") moves errors from visible to invisible.
  • Migrate one task at a time, run old and new side by side for a few cycles, and read the first real wake-ups before trusting the quiet ones.

Where the sources give numbers, they are small and specific. GitHub documents a pre-activation job of about 10 to 30 seconds against an agent job of 1 to 15 minutes. OpenClaw's heartbeat documentation (v2026.6.9) sets a 30-minute default, or 1 hour under Anthropic OAuth/token auth, which is 48 full agent turns per agent per day if heartbeats run all day. Anthropic prices a 5-minute prompt-cache write at 1.25 times the base input price, with a five-minute default cache lifetime, so a poll slower than five minutes usually pays for its context again, unless other requests have renewed the same cached prefix in the meantime. No source gives a general "percent saved" figure, and this article does not claim one. A worked example near the end shows the arithmetic with stated, hypothetical inputs.

1. The Problem: What a Quiet Wake Costs

Consider a task that runs every 15 minutes: "Check disk usage; if any filesystem is above 85%, investigate and report." Run as a prompt, each tick does the following:

  1. The scheduler delivers a message to the agent.
  2. The agent loads its context, calls a tool to run df, reads the result, compares it to a number, and replies "all fine" (or does not reply).
  3. The turn, the tool call and the answer all stay in the conversation until the context is compacted or the session is rotated.

Three costs hide in that sequence.

Tokens. The turn pays for the agent's prefix (system prompt, instructions, memory, recent conversation) plus the tool output plus the reply. Anthropic's prompt-caching documentation states that the cache has a 5-minute lifetime by default and is refreshed at no extra cost each time the cached content is used, that 5-minute cache writes cost 1.25 times the base input price, and that cache reads cost 0.1 times (with lower multipliers for some newer models) [35]. Whether a 15-minute task finds a warm cache therefore depends on what else happens. If no other request has reused the same prefix within the previous five minutes, or if the prefix itself has changed (new memory, an edit early in the context), the run pays the write price again. A task that fires more often than every 5 minutes can keep an unchanged prefix warm and pay the read price, but it also fills the context faster. The optional 1-hour cache lifetime changes the arithmetic, at a higher write price [35]. Claude Code's own scheduler works around the edge case: its */5 jobs start 15 seconds early so that a run does not begin just after the five-minute cache has expired [21].

Attention. Anthropic's context-engineering guidance describes context as "a finite resource with diminishing marginal returns" and defines the goal as the smallest possible set of high-signal tokens [34]. Dozens of "all fine" exchanges per hour are the opposite of high-signal. We also suspect, without a measurement or a source to cite, that a long run of identical routine messages teaches the agent in-context that these messages never need action, which is the habit you do not want when one of them does.

Cadence pressure. If each check costs a turn, you check less often than you would like. If a check is a free shell script, you can run it every minute. The gate therefore improves detection latency as well as cost, which is the same argument GitHub's agentic-workflow docs make from the other side: "The primary cost lever for most workflows is how often they run." When an event-based trigger fires far more often than the agent needs to act, the same page says, a schedule is almost always cheaper [25].

The research question is not whether to filter (nearly every tool surveyed below does), but how to make the filter trustworthy enough that silence can be believed.

2. Prior Art from Operations

2.1 Nagios and Icinga: the exit-code contract

The Nagios Plugins development guidelines define the return codes: 0 OK (the plugin was "able to check the service and it appeared to be functioning properly"), 1 WARNING, 2 CRITICAL, and 3 UNKNOWN, which is reserved for invalid arguments or low-level failures inside the plugin that stop it from doing its job [1]. The guidelines also require that a plugin always print something to STDOUT saying whether the service is working or why it is failing, and keep it short (ideally under 80 characters, so the entire output fits in a pager message). The default output is a single line; the verbose levels allow more, up to multi-line debug output [1]. Plugins have a very limited runtime, typically 10 seconds, and should time out gracefully, but the page does not say which code a timeout should produce [1].

Icinga's documentation fills that gap and adds a distinction that matters for gating. Invalid parameters and low-level resource errors (no fork resources, a busy IO device) are UNKNOWN, but higher-level errors such as DNS resolution failures and TCP connection timeouts "should be treated as Critical instead." And: "Whenever the plugin reaches its timeout (best practice) it should also terminate with Unknown." The timeout is best controlled inside the plugin, with a clear message [2].

Three lessons carry over:

  • The exit code is a coarse, machine-readable verdict, and the stdout text is the human-readable evidence. That is the same split we want between the gate and the model.
  • UNKNOWN is a first-class state, not a variant of OK. A monitoring system that folded UNKNOWN into OK would be useless, and a gate that folds "I could not tell" into "nothing to do" is worse.
  • In monitoring, whether and how urgently an UNKNOWN reaches a human is decided by the notification configuration. A gate has no such configuration unless you build one, so the safe default is that UNKNOWN wakes the model (section 4.1).

2.2 Cron, MAILTO and chronic: silence when fine

POSIX specifies that when a crontab command does not redirect its output, "any generated output or errors shall be mailed, via an implementation-defined method, to the user" [4]. Vixie-style cron adds MAILTO: if it is defined and non-empty, mail goes to that address; if it is defined but empty, no mail is sent; otherwise mail goes to the crontab's owner [3]. The system therefore turns "the job printed something" into "a human is notified" without any explicit alerting logic, which is why a well-behaved cron job is silent on success.

chronic from moreutils makes that discipline explicit: it "runs a command quietly unless it fails", displaying standard output and error only if the command exits non-zero or crashes, and with -e also when anything is written to stderr [5]. It is a gate with one threshold, and the evidence is the command's own output.

The weakness of this model is also instructive. If the job never runs, cron says nothing. Silence from cron is consistent with both "all fine" and "the daemon is down, the crontab was overwritten, or the machine was off." Cron has no concept of an expected run, which is why section 4.4 exists.

2.3 Kubernetes: probes and CronJobs

A Kubernetes exec probe is the gate pattern in miniature: the kubelet runs a command, and 0 means healthy while any non-zero value means failure [7]. The docs add two practical features. A built-in probe fails on timeout, so a hung probe is a failure and not a pass [7]. And a startup probe example sets failureThreshold to 30 with periodSeconds of 10, which allows five minutes for startup before the failure counts [7], an example of debouncing by requiring consecutive failures.

CronJobs contribute scheduling semantics that every scheduled-agent design has to answer. The docs state that scheduling is approximate: there are circumstances where two Jobs might be created or none, so "the Jobs that you define should be idempotent" [6]. concurrencyPolicy: Forbid skips a new run when the previous one is still running. startingDeadlineSeconds lets a run be skipped if it cannot start in time, with the example that a backup taken too late is no longer useful. If more than 100 schedules were missed, the controller records a TooManyMissedTimes Warning Event and still starts a Job for the most recent missed schedule; the earlier missed schedules do not run [6]. The relevant lessons are single-flight execution, no catch-up storm after downtime, and idempotent tasks.

2.4 GitHub Actions: conditional jobs, and the danger of "skipped means success"

A job-level if prevents a job from running unless a condition holds; otherwise it is marked skipped. The documentation adds a warning for gate design: a skipped job reports its status as Success, and "It will not prevent a pull request from merging, even if it is a required check" [8]. If the condition itself is broken (a wrong context name, an empty variable), the gate skips forever and the system reports green. A related operational fact is that scheduled workflows can be delayed under load, queued jobs may be dropped when load is high enough, and in public repositories scheduled workflows are automatically disabled after 60 days without repository activity [9]. The scheduler itself can go quiet.

2.5 Prometheus and the SRE book: alert on symptoms, page only for actionable things

The Prometheus alerting practices page summarizes its advice as "keep alerting simple, alert on symptoms, have good consoles to allow pinpointing causes", and recommends having as few alerts as possible [10]. For batch jobs, it says to page only when a job "has not succeeded recently enough" and this will cause user-visible problems. Google's SRE book is blunter: "Every page should be actionable"; "If a page merely merits a robotic response, it shouldn’t be a page"; and "Paging a human is a quite expensive use of an employee’s time" [11].

Replace "page a human" with "wake the model" and the argument transfers. Waking the model is an expensive use of its context. If the response to a wake is always the same robotic action, a script can take that action and the model is not needed. If the response requires judgment (is this growth normal? which of these three PRs matters?), the wake is justified. The same sources also explain why gates should look at symptoms ("the disk is at 91%") and not enumerate causes.

Prometheus also supplies the vocabulary for dedup. The for clause holds an alert "pending" until the condition has held for a duration, and keep_firing_for keeps an alert firing after the condition last held, to avoid flapping and false resolutions caused by missing data [12]. Alertmanager groups similar alerts into one notification, can inhibit notifications while other alerts are firing, and deduplicates [13].

2.6 Dead-man switches: how silence becomes trustworthy

Healthchecks.io inverts the polarity: the monitored job sends a ping on every run, the service stays quiet while pings arrive on time, and it alerts when one does not. It has explicit states (New, Up, Late, Down), a period and a grace time, and for cron-style schedules a check becomes late at the moment the wall clock matches the schedule and down after the grace time [15]. Appending /start and /fail or an exit code to the ping URL gives it run durations and explicit failures. With /start, the grace time also caps how long a run may take. Exit status 0 is success and every non-zero value is failure [15][16].

The same idea appears in two other places. The kube-prometheus Watchdog alert is deliberately always firing, and its runbook says: "If not firing then it should alert external systems that this alerting system is no longer working" [14]. Nagios Core's freshness checking exists "to ensure that host and service checks are being provided passively by external applications on a regular basis": if the age of the last result exceeds a threshold, the result is stale and Nagios forces an active check; the docs' example is a nightly backup with a 26-hour threshold that goes CRITICAL if no report arrives [17].

All three share one property: the absence of a signal is itself the signal, and the watcher lives outside the thing being watched. That is what we need for gates.

3. How Agent Tooling Handles Scheduled and Event-Triggered Runs

This section only states what the documentation says. Where a page was silent, that is noted. For each system: what starts a model run, and whether anything gates it before the model.

  • GitHub Agentic Workflows. Started by a schedule, events or dispatch. Gate: yes, skip-if-match / skip-if-no-match, custom pre-activation steps, and a scripted noop [25][26].
  • Claude Code hooks. Started by tool and session events. Gate: the hook's exit code and stdout decide, with event-specific rules; asyncRewake wakes the model on exit 2 [20].
  • Claude Code /loop and cron tools. Started by a timer inside a session. Gate: none, the prompt runs each time; the docs point to Monitor to avoid polling [21][22].
  • Claude Code Monitor. Started by each stdout line of a background script. Gate: the script is the filter, and only emitted lines reach the model [22].
  • Claude Code cloud scheduled tasks. Started by a schedule, an API call or a GitHub event. Gate: GitHub triggers have field filters (author, labels, branch, draft, merged) [24].
  • Claude Code channels. Started by a push from an MCP server. Gate: the server decides what to push [23].
  • LangSmith cron jobs (Agent Server). Started by a schedule; each run sends the same fixed input to the assistant, on the cron's existing thread or, for a stateless cron, on a new thread. Gate: none at the scheduler; whether a run calls the model is up to the graph [27].
  • OpenClaw heartbeat (older design). Started as a periodic agent turn. Gate: the model itself, which replies with an ack token that is suppressed [28][29].
  • n8n, Zapier. Started by a trigger. Gate: Filter / IF steps drop items before later steps [30][31][32].

3.1 GitHub Agentic Workflows: the closest published analogue

GitHub's agentic-workflow documentation is the most explicit source on the pattern. Its cost-management page says: "If a task can be solved using deterministic tools, use deterministic tools." It also says: "The cheapest run is the one that never starts the agent." For simple GitHub-search conditions, skip-if-match and skip-if-no-match run in a low-cost pre-activation job. For arbitrary logic, a step writes a noop entry to $GH_AW_SAFE_OUTPUTS, and the page explains what follows: "The harness exits before starting the AI engine, so no AI Credits are charged". The page's own example counts open issues with gh issue list and emits a noop if there are none [25].

Details that matter: skip-if-match has a max threshold (default 1), and the docs describe the result as skipped-not-failed [26]. They recommend preferring the built-in skip options because they also avoid scheduling the agent job at all [25]. They give typical timings of 10 to 30 seconds for the pre-activation job and 1 to 15 minutes for the agent job, plus per-run and per-day credit caps as a backstop [25]. The docs do not say how a skipped agentic run interacts with required status checks, so the caution in section 2.4 still applies to anything that reads a skip as a pass.

3.2 Claude Code: exit codes, wake-up hooks and Monitor

Claude Code hooks build on the Unix contract, with rules that vary by event [20]. Exit 0 is success, and "Claude never sees stderr from a hook that exits 0". Exit 2 is a blocking error: on events that can block, Claude Code stops the action, and what happens to stderr depends on the event (on some it is shown to Claude as the reason; on SessionStart, for example, it only appears in the transcript and Claude does not see it). Any other exit code, a hook that fails to start, and invalid JSON are non-blocking errors. Exit 1 is non-blocking too, "even though 1 is the conventional Unix failure code". Stdout can override the code: on events such as PreToolUse, a hook that exits with some other code but prints JSON that passes validation is treated as success, and its fields decide. Timeouts and missing scripts are non-blocking errors on most events unless onFailure is set to block [20]. For our purposes the most relevant feature is asyncRewake: if set, a command hook "runs in the background and wakes Claude on exit code 2", with stderr (or stdout, if stderr is empty) shown to the model as a system reminder [20]. That is a script gate built into the product. Hook output injected as context is capped at 10,000 characters; longer output is saved to a file and the model receives the path plus a preview of up to 2,000 characters [20].

The scheduled-task docs for /loop describe a plain timer that re-runs a prompt: the scheduler checks every second, enqueues due prompts at low priority, and fires them between turns, not mid-response [21]. Recurring tasks expire after 30 days (7 days before v2.1.330), there is no catch-up for missed fires, and runs are jittered [21]. The same page notes that, where the Monitor tool is available, Claude may use it for a dynamic loop. Monitor "runs a background script and streams each output line back, which avoids polling altogether and is often more token-efficient and responsive than re-running a prompt on an interval" [21]. The tools reference describes Monitor the same way, and adds that every watch has a deadline (5 minutes by default, at most 30 minutes, and at most 10 minutes in a non-interactive -p run given a single prompt), after which Claude gets one notice [22]. Monitor is an event-stream cousin of the exit-code gate: the script decides what to print, and printing is the wake-up.

Cloud scheduled tasks (formerly routines) add a different kind of gate. GitHub triggers can be filtered by author, title, body, branches, labels, draft and merged state so that only matching pull requests start a session, and the docs warn that the run outcomes say "how the session ended, not whether Claude completed the work your prompt describes" [24]. The same page documents hourly caps, with events beyond a cap dropped until the window resets [24], which is a reminder that a gate in front of a rate-limited resource also protects the cap.

3.3 LangSmith cron jobs: scheduling without a built-in gate

LangSmith Agent Server cron jobs take a schedule, an assistant and an input, and on each trigger run the assistant with that input; the docs note that "this sends the same input to the thread every time" [27]. A cron job can be created for an existing thread, which it then reuses; a stateless cron job creates a new thread for each execution [27]. After advising that cron jobs no longer needed be deleted, the page warns: "Otherwise you could rack up unwanted API charges to the LLM!" [27]. The page documents no conditional skip at the scheduler level. Whether a run calls a model at all is up to the graph the assistant runs, and a graph can begin with a deterministic node that returns early. Scheduling primitives and gating are separate concerns, and here the gate is the application's job.

3.4 OpenClaw heartbeats: the model as gate

OpenClaw's heartbeat is a useful contrast. Its documentation as of v2026.6.9 describes periodic agent turns in the main session. If nothing needs attention, the model replies HEARTBEAT_OK. When that token is at the start or end of the reply, it is stripped, and the reply is dropped if what remains is at most ackMaxChars characters (300 by default) [29]. The default interval is 30 minutes, or 1 hour when Anthropic OAuth/token auth is the detected auth mode, and the page's cost section says it plainly: "Heartbeats run full agent turns" [29]. At 30 minutes that is 48 turns per agent per day if heartbeats run all day (active hours can restrict them). The same page estimates that an isolated session cuts the prompt from about 100K tokens to about 2 to 5K per run [29]. The suppression hides the answer, not the cost. The current documentation has retired that design in favor of ordinary automation jobs: a check returns NO_REPLY when there is no visible update, and a job can skip a run whose scratch checklist is explicitly empty [28]. The direction of travel is toward doing less model work on a quiet tick.

3.5 Workflow tools: filter before the model

n8n's Filter node "omits the item from its output" if it does not meet the condition [30]. Its production-AI playbook says to add an IF node right after normalization that checks for the minimum viable input, and states two rules: "Start deterministic, add AI last" and "The AI suggests; the workflow decides" [31]. Zapier's Filter lets a Zap "only continue if the data from your app meets that condition" [32]; the page states that filters are available on paid plans and says nothing about whether filtered runs count toward task usage, so we make no billing claim. Anthropic's Building effective agents frames the general principle. Workflows are systems where LLMs and tools are "orchestrated through predefined code paths", agents let the model direct its own process, and "Agentic systems often trade latency and cost for better task performance", so the authors recommend "finding the simplest solution possible, and only increasing complexity when needed" [33].

None of these sources ran a controlled study of gating, and this article cites none. What they provide is convergent design practice, and in GitHub's case, explicit timing and credit numbers.

4. Design Questions

4.1 The exit-code contract

Exit codes alone cannot carry the verdict. Bash itself exits 1 when a command fails under set -e or when set -u meets an unset variable, and 2 on a syntax error. In a local test with Bash 5.2, three small scripts produced exactly those codes, and the set -e case printed nothing at all. If 1 and 2 meant "finding," a crashed script would arrive as a finding, perhaps an urgent one, and no amount of reading its output would help when there is none. So the contract has two parts: the exit code, and a result record that the script prints as the last line of stdout only after its checks have passed. The supervisor that runs the script decides the outcome:

  • Exit 0 with the record gate-result: ok. Checked, nothing needs judgment. The model is not woken and is told nothing. This is the only silent outcome.
  • Exit 1 with gate-result: finding fp=<fingerprint>. Something needs judgment. The model is woken with the stdout evidence.
  • Exit 2 with gate-result: urgent fp=<fingerprint>. The same, at a higher level the supervisor can use to choose how loudly to notify.
  • Anything else is a gate failure. A missing, malformed or inconsistent record (ok with exit 1, a finding with exit 0), a launch failure, a signal, a timeout, or any other exit code. The model is woken and told "gate failure," with the exit code and the tail of stderr, never as a finding.

Why this shape:

  • Fail loud, not silent. Nagios gives the check author UNKNOWN for a check that could not decide, and Icinga says a timeout should end as UNKNOWN [1][2]. Kubernetes treats a probe timeout as a failure [7]. In a gate that decides whether a model is woken, "I could not tell" must not collapse into "nothing to do." The Claude Code hooks documentation shows the opposite default is easy to fall into: on most hook events, an exit code other than 0 or 2 is non-blocking and the action goes ahead, unless valid JSON on stdout decides otherwise [20]. That is the right trade-off for a pre-tool-use policy check, where failing closed would freeze the agent, and the wrong one for a gate whose silence is read as health.
  • Label gate failures differently from findings. When the gate crashes, the model should not be told that the disk is full. It should be told the gate failed, with the exit code and the tail of stderr. Otherwise the agent investigates a condition that does not exist, or worse, reasons from an error message as if it were evidence. Nagios's UNKNOWN is separate from CRITICAL for the same reason, and the result record is what lets the supervisor tell the two apart.
  • Exit 0 must be earned. Most failures happen on the quiet path. Bash's pipeline status is the last command's status unless pipefail is enabled [19], so check | sort | head can swallow the failure of check. A trailing || true converts any error into silence. Use set -euo pipefail, validate that the gathered data is non-empty and well-formed before comparing it to a threshold (an empty df output is not "no disk problems"), and print the ok record and exit 0 only at the bottom of the script after those checks.
  • The supervisor owns the timeout, with a forced kill behind it. A gate that hangs holds a scheduler slot and, if the scheduler waits for it, blocks every later run; K8s's concurrencyPolicy exists for this case [6]. Nagios expects plugins to enforce their own limit [1], and a script may keep one, but the verdict "timed out" has to come from outside, because a hung script cannot report it. GNU timeout sends TERM at the limit, and a script that blocks or ignores TERM keeps running unless -k adds a KILL after a grace period [18]. In a local test with coreutils 9.4, a script that ignored TERM ran its full second under timeout 0.1s and was killed after 0.2 seconds under timeout -k 0.1s 0.1s. Do not add --preserve-status: it returns the command's own status instead of 124 [18], so a script that catches TERM and exits 0 turns a timeout into apparent success, and in the same test it did return 0.
  • Timeout codes need no special handling. GNU timeout exits 124 when the command times out, 125 if timeout itself fails, 126 if the command "cannot be invoked", 127 if it "cannot be found", and 137 for a KILL signal [18]. With the record rule, all of them are gate failures without per-code logic, and so is a 0, 1 or 2 that arrives without its record.
  • Why two non-zero codes? In Nagios the difference between 1 and 2 is severity. For a gate, the minimal useful version is that both wake the model. A second code is justified only if the system uses it, for example to choose how loud the notification is or whether the wake interrupts or queues. Without that, it is complexity with no consumer.

How one deployed scheduler compares. This article grew out of the script tasks in Zylos Core's scheduler. Its documented behavior in the installed version, 1.0.0-beta.21, matches the public documentation at a pinned commit [36], and it is simpler than the contract above. The scheduler runs the command with /bin/sh -c. Exit 0 records success silently. On failure or timeout it sends the agent one message with the command, the result and the last 4 KiB of combined output. It reads no result record and defines no separate severity for 1 and 2, so a crash and a finding arrive in the same kind of message and can only be told apart by reading the output. At timeout or shutdown it sends SIGTERM to the script's process group and SIGKILL one second later, which matches the supervisor-owned timeout with a kill fallback described above. One path is silent by design: on shutdown, or when startup finds an interrupted script run, it records the run as failed with INTERRUPTED, does not repeat it, and does not wake the agent [36]. The proposal in this section is therefore not that system's current behavior. On that scheduler, the wrapper in section 4.5 would supply the record check, labelling and dedup, and the scheduler's own wake on a non-zero exit would remain the path for the wrapper's failures. Some scheduler failures need monitoring outside the scheduler: interrupted runs, which are recorded but wake no one; a scheduler that is not running at all; and a wake that never reaches the agent's queue. For the last one the documentation is explicit: the scheduler keeps the script outcome, makes a single wake-up attempt, and appends any delivery error to the run's history [37], so a failed send is recorded, not retried. The external dead-man heartbeat of section 4.4, run off the host, covers a scheduler that stops, interrupted runs (no completed check, so no ping) and wakes that fail to enqueue, provided the ping is tied to delivery as in section 4.5. It cannot see a wake that was enqueued and never consumed; that needs monitoring of the queue or of the agent that reads it.

4.2 What the script passes to the model

On a wake, the script's stdout is the model's input. Treat it as an evidence packet:

  • Say why the model was woken, in the first line. "disk-gate: 2 filesystems at or above 85%" is better than raw df output. This is the Nagios rule that a plugin should say whether a service is working or why not [1], but at a few hundred characters rather than 80.
  • Include the facts the model needs to avoid re-gathering them, and identifiers for the rest. This is the context-engineering trade-off Anthropic describes: data retrieved up front is faster, lightweight identifiers let the agent load more just in time, and the most effective agents might use a hybrid of the two [34]. For a PR poll, pass the PR number, title, author, what changed since last run and the review state, not the diff; the agent can fetch the diff if it decides to look.
  • Bound the size, and say when you truncated. Claude Code caps hook-injected context at 10,000 characters and substitutes a file path and a 2,000-character preview beyond that [20], a reasonable shape to copy. Cap the number of items and print "and 37 more" so the model knows the list is partial. Cut only after reading and validating the whole input. Under pipefail, a pipeline takes the status of its last failing command [19], so producer | head -n 20 can fail when head exits early and the producer is killed by SIGPIPE: in a local test, seq 1 1000000 | head -n 20 returned 141 while a short input returned 0. The example in section 4.5 captures the full df output, validates it, and only then keeps the first 20 items; its supervisor also caps every packet at 8,000 bytes and appends a note giving the original size. Unbounded output turns a cheap gate into the context flood it was meant to prevent.
  • Plain text with stable labels is enough. The reader is a model. Key-value lines and one item per line are easy for both the model and a human skimming the log. JSON adds quoting failures for little benefit unless another program also consumes the output. The one machine-read line is the result record.
  • Separate evidence from instruction. The script reports what it found. Whether the finding matters, and what to do, is the model's job. A script that prints "please restart the service" has smuggled judgment into code, and has also made the packet an instruction source, which raises the injection stakes if the gathered data includes text written by others (a feedback queue, PR titles). Treat gathered text from third parties as data, as the companion article on push-triggered sync argues for push payloads.

4.3 Idempotency and dedup: do not wake on the same fact twice

A condition that remains true on every run (the disk stays at 91% for a week) wakes the model every 15 minutes unless the gate remembers. Options, from simple to elaborate:

  1. Wake on transition. Keep a small state file; wake only when the set of offending items changes. The example in section 4.5 stores a fingerprint of the offending mount points and the time of the last delivered wake. The stored key also carries the severity, so a finding that turns urgent wakes the model again. While the same key stays deduplicated and silent, both values are kept unchanged.
  2. Re-notify on a schedule. Same fingerprint, but wake again after an interval (6 hours in the example), measured from the last delivered wake, so that "handled but not resolved" does not stay invisible forever. Prometheus separates the two concerns explicitly: for delays firing until the condition has held, and Alertmanager handles deduplication, grouping and inhibition downstream [12][13].
  3. Clear on recovery, and only on recovery. When a valid check reports that the condition has returned to normal, delete the state, so a recurrence wakes the model again. A check that failed is not a recovery: it must leave the state alone, or the next real finding after a flaky df would look new while the old one was never resolved. Prometheus's keep_firing_for addresses a related problem (flapping and false resolutions from missing data) by holding the alert open for a while after the condition clears [12]. A gate that flaps around its threshold needs hysteresis in the same spirit: wake at 85%, clear at 80%. The example omits hysteresis to stay short.
  4. Debounce transient failures where the cost of delay is low. Kubernetes uses consecutive-failure thresholds [7]. For a network keep-alive, require two consecutive failures. For a disk, do not wait.

Two subtleties. First, when to record the state. If you write the fingerprint before the wake is safely delivered and the delivery fails, the wake is lost and the dedup will suppress it until the re-notify interval. So a wake counts as delivered only when the delivery command acknowledges that the message is durably enqueued (written to the agent's persistent queue, not merely handed to a socket), and the state is written after that acknowledgement. If delivery fails, the state stays as it was and the next run detects the same condition and tries again. A crash between delivery and write produces a duplicate wake; prefer that at-least-once behavior and make the agent's handling idempotent, which is the advice Kubernetes gives for CronJobs [6], and the same posture as the dedup-by-id and single-flight advice in the companion push-sync article. Second, overlapping runs. If the gate takes longer than its interval, two copies may run and race on the state file. One lock should cover reading the state, delivering the wake and committing the state; CronJob's Forbid is the reference behavior for the overlap (skip, do not queue) [6]. Claude Code's scheduler does something similar by coalescing missed fires into one when the session becomes idle [21].

4.4 Staleness: a broken gate must not look like "all fine"

Prompt-based tasks failed visibly: the agent said something odd or nothing arrived. Gated tasks fail silently by construction, because quiet is the success case. The prior art is unambiguous about the remedy [14][15][17]:

  • Make the success ping mean something. A ping that only proves the process ran keeps the watcher green while the gate is crashing or its wakes are being lost. Send the success ping only when the run completed a valid check and any wake it needed was delivered (or was deliberately deduplicated). Send an explicit failure signal, such as Healthchecks' /fail [16], on a gate failure or a failed delivery. A run that dies before either ping, or a scheduler that stops starting runs, shows up as an overdue ping past period plus grace [15]. The example in section 4.5 follows these rules.
  • Put the watcher outside the thing watched. Watchdog alerts only help if something external notices their absence [14]. A heartbeat consumed by the same agent or scheduler that may have died proves nothing.
  • Alert on the absence, route it to a place that can reach a human or a model that is awake. The dead-man alert is itself a wake-up. It is rare by design, and it is the one case where waking the model for "nothing happened" is correct.
  • Record last-run time and last exit code per task. Nagios freshness checking is this idea: compare the age of the last result to a threshold [17]. A "gate inventory" that lists each task, its expected interval, last run and last code lets one cheap script (or one cheap model glance per day) spot tasks that stopped.
  • Expect the scheduler itself to go quiet. GitHub documents scheduled workflows being disabled after 60 days of repository inactivity and queued jobs being dropped under load [9]. Claude Code's recurring tasks expire after 30 days and are not restored for missed runs [21]. The Zylos scheduler records interrupted runs without waking the agent [36]. Whatever scheduler you use has such limits, and the dead-man switch is what makes them visible.
  • Test it by breaking it. Kill the gate once, and confirm the dead-man alert arrives. The same applies to a Watchdog: break the thing it watches and confirm the alert fires [14].

4.5 A worked example: a disk gate and its supervisor

The example has two parts. disk-gate.sh only checks: it prints evidence and, as its last line, a result record. gate-run.sh is the supervisor, shared by all gated tasks: it owns the lock, the timeouts, the record check, the size cap, the dedup state, the wake and the heartbeat. WAKE_CMD stands for whatever delivers a message to the agent; it must exit 0 only after the message is durably enqueued, and the supervisor gives it 30 seconds. HC_URL is the task's Healthchecks-style ping URL. The supervisor treats its own failures (a lock error other than contention, an unreadable clock, a state file it cannot read, replace or remove) as failures too: it tries a bounded wake, sends /fail and exits non-zero, rather than reporting success.

#!/bin/bash
# disk-gate.sh: check only. Evidence on stdout, then one result record as the last line.
set -euo pipefail
export LC_ALL=C                 # fixed df headers and number format
WARN=85 URGENT=95 MAX_ITEMS=20
# Read the whole input first; if df fails, the script ends here with no result record.
raw=$(df -P -x tmpfs -x devtmpfs -x squashfs)
# Validate before comparing: the POSIX header, then on every row three integer columns,
# an integer use% and a non-empty mount point. One bad row fails the whole check.
rows=$(printf '%s\n' "$raw" | awk '
  NR == 1 { if ($1 != "Filesystem" || $NF != "on") exit 3; next }
  { if (NF < 6 || $2 !~ /^[0-9]+$/ || $3 !~ /^[0-9]+$/ || $4 !~ /^[0-9]+$/ ||
        $5 !~ /^[0-9]+%$/) exit 3
    u = $5; sub(/%$/, "", u)
    m = $0; for (i = 0; i < 5; i++) sub(/^[^ ]+ +/, "", m)
    if (m == "") exit 3
    print u, m; n++ }
  END { if (n == 0) exit 3 }') || { echo "disk-gate: unparseable df output" >&2; exit 3; }
hits=$(printf '%s\n' "$rows" | awk -v w="$WARN" '$1 >= w' | sort -k1,1nr)
if [ -z "$hits" ]; then echo "gate-result: ok"; exit 0; fi
n=$(printf '%s\n' "$hits" | wc -l)
echo "disk-gate: $n filesystem(s) at or above $WARN%"
printf '%s\n' "$hits" |
  awk -v max="$MAX_ITEMS" 'NR <= max { print "use=" $1 "% mount=" substr($0, index($0, " ") + 1) }'
if [ "$n" -gt "$MAX_ITEMS" ]; then echo "... and $((n - MAX_ITEMS)) more"; fi
fp=$(printf '%s\n' "$hits" | cut -d' ' -f2- | sort | sha256sum | cut -c1-16)
top=$(printf '%s\n' "$hits" | awk 'NR == 1 { print $1 }')
if [ "$top" -ge "$URGENT" ]; then echo "gate-result: urgent fp=$fp"; exit 2; fi
echo "gate-result: finding fp=$fp"; exit 1
#!/bin/bash
# gate-run.sh TASK SCRIPT: the supervisor. Owns the lock, timeouts, result check, dedup
# state, wake and heartbeat. WAKE_CMD must exit 0 only after the wake is durably enqueued.
# HC_URL is the task's Healthchecks-style ping URL. A non-zero exit means a wake was not
# delivered or the supervisor itself failed; whatever runs this script should alert on it.
set -uo pipefail
export LC_ALL=C                 # byte-based truncation below
task=$1 script=$2 dir=${GATE_STATE_DIR:-$HOME/.gate}/$1
RENOTIFY=$((6 * 3600)) MAX_BYTES=8000
wake() { timeout -k 5s 30s "$WAKE_CMD" "$task" "$1" "$2"; }   # bounded delivery
ping() { curl -fsS -m 10 -o /dev/null "$HC_URL$1" || :; }      # a lost ping shows as Late
die() {   # the supervisor itself failed: try to wake (bounded), then report, then stop
  wake "supervisor-failure" "$1" || :; ping /fail; exit 1
}
mkdir -p "$dir" && exec 9>"$dir/lock" || die "cannot open lock in $dir"
flock -n -E 75 9; lrc=$?
if (( lrc == 75 )); then exit 0; fi          # another run holds the lock: normal overlap
(( lrc == 0 )) || die "flock failed with $lrc"
# The lock is held from here on: state read, wake and state commit.
now=$(date +%s) && [[ $now =~ ^[0-9]+$ ]] || die "clock unreadable"
old_key= old_at=0
if [[ -e $dir/state || -L $dir/state ]]; then
  [[ -f $dir/state ]] && read -r old_key old_at < "$dir/state" && [[ $old_at =~ ^[0-9]+$ ]] ||
    die "state file $dir/state unreadable or malformed"
fi
out=$(timeout -k 5s 60s "$script" 2>"$dir/stderr"); rc=$?
rec=${out##*$'\n'}        # last line of stdout
if   [[ $rc == 0 && $rec == "gate-result: ok" ]]; then kind=ok
elif [[ $rc == 1 && $rec =~ ^gate-result:\ finding\ fp=([0-9a-f]{16})$ ]]; then kind=finding
elif [[ $rc == 2 && $rec =~ ^gate-result:\ urgent\ fp=([0-9a-f]{16})$ ]]; then kind=urgent
else kind=gate-failure; fi
key=$kind:${BASH_REMATCH[1]:-}   # severity is part of the key: finding -> urgent wakes again
if (( ${#out} > MAX_BYTES )); then   # bound the packet; say that it was cut
  out="${out:0:MAX_BYTES}"$'\n'"[evidence truncated at $MAX_BYTES of ${#out} bytes]"
fi
case $kind in
  ok)  # only a valid all-clear clears the state
    rm -f -- "$dir/state" || die "cannot clear $dir/state"; ping "" ;;
  gate-failure)  # state untouched: a failed check is not a recovery; wake first, then report
    wake "gate-failure exit=$rc" "$(tail -c 2000 "$dir/stderr")"; w=$?; ping /fail; exit $w ;;
  *) if [[ $key == "$old_key" ]] && (( now - old_at < RENOTIFY )); then
       ping ""                                   # same fact, already delivered: quiet
     elif wake "$kind" "$out"; then
       # The wake is enqueued. If the state cannot be committed, the next run delivers it
       # again (a duplicate, never a loss) and the supervisor reports itself as failed.
       printf '%s %s\n' "$key" "$now" > "$dir/state.tmp" &&
         mv -fT -- "$dir/state.tmp" "$dir/state" || { ping /fail; exit 1; }
       ping ""
     else
       ping /fail; exit 1                        # not delivered: state unchanged, retry next run
     fi ;;
esac

We ran both scripts against faked df output, a fake delivery command and a fake ping endpoint. The behavior matched the design. A new finding was delivered and only then recorded. The same finding 15 minutes later stayed silent with its fingerprint and timestamp unchanged. A df failure and a malformed df line (a missing column, a non-numeric size) each woke the agent as a gate failure, sent /fail, and left the state alone. After 6 hours the same finding was re-sent, and a finding on the same mount that turned urgent within those 6 hours woke the agent again. A failed delivery sent /fail, left the state unchanged, and was retried successfully on the next run; a delivery command that hung was cut off after 30 seconds and treated the same way. A valid all-clear deleted the state. A check that ignored TERM was killed at limit plus grace (exit 137), and one that caught TERM and exited 0 was still reported as a timeout (exit 124). A record that did not match its exit code (ok with exit 1, exit 0 with no record, set -e dying before the record) was a gate failure every time. A lock command that failed for a reason other than contention, a state file replaced by a directory, and a state commit that failed after delivery each ended with /fail and a non-zero exit instead of a success ping; in the last case the next run delivers the wake again, a duplicate rather than a loss. A 30 KB packet with a valid record reached the delivery command cut to 8,000 bytes plus the truncation note. Two limits of the sketch: a persistent gate failure wakes the agent on every run until fixed (it could be deduplicated the same way, keyed on the exit code), and the limits (60 seconds for the check, 30 for delivery, 6 hours between repeats, 8,000 bytes) would be per-task settings in practice.

4.6 Where the threshold logic belongs

The principle says the script gathers what code can determine and the model judges. The hard part is drawing the line.

Belongs in the script: facts with a definition. Disk usage percentage, queue length, age of the oldest item, whether a commit exists that the local branch lacks, whether a process answers a ping, whether a new release tag appeared. These are deterministic, testable with fixtures, and cost nothing to run.

Belongs in the model: interpretation. Is this growth expected given what the agent knows is running? Is this feedback item a duplicate of one it handled yesterday? Does this PR need review now or can it wait? These depend on context, wording and history that the script lacks.

The gray zone is where the risk concentrates. A numeric threshold is judgment in disguise: "85% is bad" encodes knowledge about the machine. A regex over a feedback queue that wakes the model only for items containing "error" encodes a belief about what matters. When code decides, mistakes are invisible: the model never sees what the gate suppressed. Some guidance, offered as engineering judgment and not as a published result:

  • Bias toward waking. Set thresholds so the gate over-wakes slightly. A false wake costs one turn; a false silence costs the problem. Prometheus's guidance to allow slack for small blips [10] is a counterweight: do not over-tune in either direction, but on the first migration, err loud.
  • Gate on simple, objective predicates (changed, new, over a number, older than). Avoid semantic predicates (looks suspicious, seems important) in code. If the question really is semantic, the right gate is "is there anything new?", then let the model decide.
  • Keep thresholds in one visible place per script and name them. The model can then read the script when it wonders why it was or was not woken.
  • Let the model tune the gate. The agent can propose a new threshold from what it sees after a wake ("this fires every day and I always dismiss it"), through whatever review path changes the script. The loop closes only if wakes carry enough information for that, which is a further argument for evidence packets (section 4.2).
  • Sample the quiet runs. Occasionally (weekly, say) run the evidence-gathering part of a gate in "verbose" mode and let the model skim what it would have suppressed. This is the same recall check the companion article proposes for blockers: measure what the cheap step misses, since the cheap step cannot report its own false negatives.

4.7 Migration: one task at a time

Converting a dozen prompt-based tasks at once makes any regression hard to attribute. A practical order:

  1. Start with the task whose answer is almost always "nothing" and whose check is a plain command (a disk check, a keep-alive, a repository sync that either fast-forwards or does not). These have the best savings and the least judgment to mis-encode.
  2. Write the script from the old prompt's own instructions. The prompt already states the condition ("if any filesystem is above 85%..."); the script is that sentence in code. Keep the model's follow-up prompt for the wake path.
  3. Run old and new side by side for a few cycles. The prompt-based task is the reference; the script should wake whenever the model would have found something. Disagreements are the useful output: each one is a gate bug or a prompt that was over-reporting.
  4. Read the first real wake-ups closely. Check that the packet is sufficient (the agent did not need to re-gather), bounded, and correctly labelled.
  5. Verify the quiet path positively. Confirm the heartbeat arrives, last-run time advances, and a deliberately induced condition (fill a scratch filesystem, add a test item to a queue) does wake the model. Verification of "nothing happened" needs an induced event, or it verifies nothing.
  6. Convert the next task. Leave judgment-heavy tasks as prompts for now (see section 6).
  7. Keep the old prompt around for rollback until the dead-man switch has been exercised once.

The recurring tasks of the Zylos Core agent behind this article sort naturally. Disk checks, keep-alive pings and repository syncs are pure facts. A feedback-queue check and PR-review polling reduce to "is there anything new since last run?", with the judgment about what to do remaining with the agent. A release tracker is "did a new version appear?" against a stored last-seen value. All of them have a dedup story (last-seen id or fingerprint).

4.8 Cost and attention: what the sources support

No source we found measures savings from gating agent schedules in general. What can be said, with sources:

  • A quiet gate run is a shell script. GitHub reports pre-activation at about 10 to 30 seconds and agent jobs at 1 to 15 minutes, plus a default per-workflow-run cap of 1000 AI Credits and 5000 per workflow per day, where 1 AIC is $0.01 [25].
  • Frequency is the lever. GitHub: "The primary cost lever for most workflows is how often they run" [25]. OpenClaw's v2026.6.9 documentation: a 30-minute default heartbeat, each a full agent turn, which is 48 turns per agent per day if it runs all day [29].
  • Cold caches matter for slow polls: 1.25 times base input for a 5-minute cache write, 0.1 times for a read (lower for some newer models), and a 5-minute default lifetime that each use of the same prefix refreshes [35].

An illustrative calculation (hypothetical inputs, not a measurement): suppose 10 recurring tasks each run every 30 minutes (480 runs per day), each model turn carries a 10,000-token prefix, and the cache is cold on every run (no other request renews the prefix in between). Take Claude Opus 5 as the example model: its base input price is $5 per million tokens, so a 5-minute cache write is $6.25 per million [35]. Then input alone is 480 × 10,000 = 4.8 million tokens, about $30 per day, before output, tool results and the extra context they leave behind. If 2% of runs need judgment, a gated version wakes the model about 10 times a day, about $0.60. The scripts themselves cost a few seconds of CPU. Change any assumption (shorter prefix, warm cache, cheaper model) and the dollar figure moves a lot, but the ratio is set by the fraction of quiet runs, which is why the best candidates are tasks that are quiet 95% of the time or more. The attention saving does not fit in a formula: 470 fewer "all fine" turns per day is 470 fewer entries competing for the agent's context.

5. Failure Modes and Trade-offs

  • Silent gate death. How it happens: the script stops running (scheduler disabled, crontab lost, host off), and quiet looks like fine. Mitigation: an external dead-man heartbeat on every valid completed run; a last-run inventory [14][15][17].
  • False "OK" from masked errors. How it happens: a pipeline swallows a failure, a trailing || true hides an error, or empty input is compared to a threshold. Mitigation: set -euo pipefail [19]; validate data before comparing; print the ok record and exit 0 only at the end.
  • Skipped treated as success. How it happens: a broken condition skips every run and the system reports green [8]. Mitigation: distinguish "skipped" from "ran and found nothing"; send the success ping only for a valid completed check.
  • Crash looks like a finding. How it happens: Bash exits 1 or 2 on its own errors, sometimes with no output, and the model reads it as "condition detected." Mitigation: the supervisor accepts 0, 1 or 2 only with a matching result record; everything else is labelled a gate failure, with the exit code and stderr tail.
  • Gate hangs. How it happens: a network call without a timeout blocks the slot and every later run [1][6]. Mitigation: a supervisor-owned timeout with a forced kill after a grace period, without --preserve-status [18]; single-flight; expiry wakes as a gate failure.
  • Alert storms. How it happens: the condition stays true and wakes the model every run. Mitigation: fingerprint dedup with a re-notify interval; hysteresis [12].
  • Lost wake. How it happens: state is recorded before delivery, delivery fails, and dedup suppresses the retries. Mitigation: commit state only after a durable-enqueue acknowledgement, under the same lock as the state read; a failed delivery leaves the state unchanged so the next run retries; idempotent handling [6].
  • Recovery recorded from a failed check. How it happens: a crashed or unparseable check is treated as "condition gone," the state is cleared, and the alert history is lost. Mitigation: clear state only on a validated all-clear; a gate failure never touches it.
  • Brittle judgment in code. How it happens: a regex or magic number encodes a belief that stops being true. Mitigation: gate on objective predicates; bias toward waking; name thresholds and keep them visible; sample quiet runs.
  • Evidence flood. How it happens: unbounded output on wake fills the context the gate was meant to protect. Mitigation: cap items and bytes after validating the full input; say when truncated [20].
  • Untrusted text in the packet. How it happens: gathered feedback or PR text contains instructions. Mitigation: treat it as data; label its source; the script reports, the model decides.
  • Evidence not enough. How it happens: the model must re-gather everything, costing the turns the gate saved. Mitigation: review the first real wake packets; include facts plus identifiers [34].
  • Scheduler limits. How it happens: expiry, drops, disabling [9][21], or interrupted runs recorded without waking anyone [36]. Mitigation: the external dead-man switch covers scheduler and script alike.
  • Maintenance burden. How it happens: N scripts, each with thresholds, state files and tests. Mitigation: one shared supervisor for timeout, record check, heartbeat, state and labelling; keep check scripts short.
  • Over-gating. How it happens: judgment-heavy work is forced into a brittle predicate. Mitigation: leave it as a prompt (section 6).

The trade-off underneath all of these: a prompt-based task spends tokens for robustness, because the model notices odd situations the author did not anticipate. A script gate spends engineering effort for efficiency and accepts that the script sees only what its author thought to look at. The mitigations above are ways of buying robustness back cheaply.

6. When Not to Gate

  • Inputs are unstructured and meaning is the question. An inbox, a free-text feedback queue where "is there anything that matters?" has no objective predicate. The right gate may be only "anything new since last run?", and that is already most of the saving.
  • The task is the model's job. A daily digest or a periodic reflection is not a check; it is the work.
  • The check is cheap and rare. A weekly task costing one turn does not need a script. The migration has a cost too, and the saving scales with frequency times quiet fraction.
  • An event is available. If the source can push, a hint-triggered sync with a backstop poll is better than a tight poll with a gate; see the companion article Push as a Hint, Not a Message. Gates are for sources you have to poll. Claude Code's Monitor and Channels are the product versions of the same preference for events over timers [21][22][23].
  • The gate would need the model to decide. If writing the script means calling the LLM to decide whether to call the LLM, the first call is the gate and it should be the cheap one: a small, fast model call with a narrow prompt is a legitimate pre-filter, but it is a different design with its own recall problem, and this article does not evaluate it.

7. A Practical Checklist

Contract

  • The supervisor accepts exit 0, 1 or 2 only with a matching result record printed as the script's last line; exit 0 with ok is the only silent outcome.
  • Everything else (missing, malformed or inconsistent record, launch failure, crash, timeout, signal, unknown code) wakes the agent as "gate failure" with the exit code and stderr tail.
  • set -euo pipefail; no || true on the checking path; input validated before comparison; the ok record and exit 0 only at the end.
  • Timeout enforced by the supervisor, with a forced kill after a grace period (for example timeout -k) and no --preserve-status; single-flight lock.

Evidence

  • First line says why the model was woken.
  • Facts needed to decide, plus identifiers for anything larger; capped by items and bytes after the full input is validated; truncation stated.
  • Third-party text labelled as data; the script reports, it does not instruct.

Dedup

  • State keyed on a fingerprint of the condition; kept unchanged while a repeat is suppressed; wake on change; re-notify after a stated interval; hysteresis for flapping values.
  • State cleared only by a validated all-clear, never by a failed check.
  • One lock covers state read, wake delivery and state commit; delivery has its own time limit; state written only after a durable-enqueue acknowledgement; a failed delivery is retried on the next run; handling idempotent.
  • The supervisor's own failures (lock error other than contention, unreadable clock, state it cannot read or replace) end in a failure signal and a non-zero exit, never a success ping.

Staleness

  • External dead-man heartbeat with period and grace set per task: success ping only for a valid check whose wake (if any) was delivered, an explicit failure signal for gate failures and failed deliveries.
  • Last-run time and last exit code recorded per task; scheduler expiry, disabling and silently recorded interruptions covered by the same heartbeat.
  • Dead-man alert tested by breaking the gate once.

Thresholds

  • Numeric and objective predicates in the script, named and visible; interpretation in the model.
  • Biased toward waking on first rollout; quiet runs sampled periodically for missed cases.

Migration

  • One task at a time, starting with high-frequency, low-judgment tasks.
  • Old prompt and new gate run side by side for a few cycles; disagreements reviewed.
  • First real wakes read in full; quiet path verified with an induced condition.
  • Old prompt retained for rollback until the dead-man switch has fired once in a test.

Conclusion

Operations engineering has long separated detection from response: a cheap, deterministic check runs often and speaks only when something is wrong, and a more expensive responder acts on what it says. Agent frameworks are rediscovering that split in their own vocabulary (pre-activation jobs, noop outputs, hook exit codes, monitors, filters), and the strongest documented statement is also the simplest: the cheapest run is the one that never starts the agent. For an always-on agent with many recurring chores, script gates give back tokens, context and cadence. What they take is the safety net a prompt provides, which is that a model reading "all fine" at least looks. The design therefore has to earn its silence: one silent outcome backed by a result record, loud failure for everything else, bounded evidence on wake, dedup that remembers and only forgets on a real recovery, and an external dead-man switch that notices when the gate itself has gone quiet. Judgment stays where it belongs, with the model, and the script's job is to decide when to ask for it.

References

  1. Nagios Plugins. Plugin Development Guidelines (return codes, output and verbosity levels, timeouts).
  2. Icinga. Icinga 2 Service Monitoring: Plugin API (exit codes, UNKNOWN, timeouts).
  3. crontab(5), Linux manual page (MAILTO).
  4. The Open Group. crontab, POSIX.1-2017 (unredirected output is mailed to the user).
  5. chronic(1), moreutils.
  6. Kubernetes. CronJob (concurrencyPolicy, startingDeadlineSeconds, missed schedules and the TooManyMissedTimes event, idempotency).
  7. Kubernetes. Configure Liveness, Readiness and Startup Probes.
  8. GitHub Docs. Control jobs with conditions.
  9. GitHub Docs. Events that trigger workflows: schedule.
  10. Prometheus. Alerting practices.
  11. Google. Site Reliability Engineering, Monitoring Distributed Systems.
  12. Prometheus. Alerting rules (for, keep_firing_for).
  13. Prometheus. Alertmanager overview.
  14. Prometheus Operator runbooks. Watchdog.
  15. Healthchecks.io. Documentation: how the dead man's switch works.
  16. Healthchecks.io. Signaling failures.
  17. Nagios Core. Service and host freshness checks.
  18. GNU Coreutils. timeout invocation (--kill-after, --preserve-status, exit statuses 124, 125, 126, 127, 137).
  19. GNU Bash Reference Manual. Pipelines (pipeline status, pipefail).
  20. Anthropic. Claude Code hooks reference (exit codes and per-event behavior, JSON output, onFailure, asyncRewake, context caps).
  21. Anthropic. Claude Code: Run prompts on a schedule (/loop, cron tools, jitter, expiry, limitations).
  22. Anthropic. Claude Code tools reference: Monitor tool (watch deadlines, including non-interactive runs).
  23. Anthropic. Claude Code: Push events into a running session with channels.
  24. Anthropic. Claude Code: Automate work with scheduled tasks (cloud) (GitHub triggers and filters, hourly limits, run status).
  25. GitHub. GitHub Agentic Workflows: Cost Management.
  26. GitHub. GitHub Agentic Workflows: Triggers (skip-if-match, pre-activation, skipped-not-failed).
  27. LangChain. Use cron jobs (LangSmith Agent Server) (fixed input, thread and stateless crons).
  28. OpenClaw. Heartbeat migration (current docs: automation jobs, NO_REPLY, empty-scratch skip).
  29. OpenClaw. Heartbeat documentation at v2026.6.9 (version-pinned description of the older design: HEARTBEAT_OK ack, ackMaxChars default 300, default interval, cost estimates).
  30. n8n. Filter node.
  31. n8n. Production AI Playbook: Deterministic Steps and AI Steps.
  32. Zapier. Add conditions to Zaps with Filter.
  33. Anthropic. Building effective agents (Dec 2024).
  34. Anthropic. Effective context engineering for AI agents.
  35. Anthropic. Prompt caching (5-minute lifetime and refresh, write and read multipliers, per-model prices).
  36. Zylos Core. Scheduler skill: Script tasks (pinned commit; matches the documentation shipped with version 1.0.0-beta.21: silent exit 0, one wake message on failure or timeout with the last 4 KiB of output, SIGTERM then SIGKILL after one second, INTERRUPTED runs recorded without a wake).
  37. Zylos Core. Scheduler skill: history (same pinned commit: script result codes, wake-up errors appended to history, a single wake-up attempt).

Companion articles in this section: Find Candidates with Code, Judge with the Model (2026-11-28) and Push as a Hint, Not a Message (2026-11-29).