Lesson 8: Schedule Agent Runs and Configure Alerts
What you'll learn: schedule Lesson 7's runner, classify its results, delay nonurgent requests, and alert when scheduled runs stop starting. What you need: the runner, workflow, and deny rules from Lesson 7, working by hand; a phone with the ntfy app; a machine that stays on and has cron. Time: about thirty minutes to configure, then a day observing scheduled runs. Cost: existing machine and agent access, CI usage, and notification-service usage; check your service allowances.
The idea#
Schedule the task runner only after it completes correctly when started by hand. A wrapper script can then classify each result: blocked for an urgent failure, review for a decision that can wait, and info for routine logging. These notification categories are separate from Lesson 6's model-selection tiers.
The classification needs an observable input. Here it uses the exit code and known output strings from the runner. A separate watch compares the last start time with the schedule. Without that check, a stopped runner produces no result to classify.
Why start here#
Unattended work needs both failure reporting and evidence that runs are starting. Establish those before increasing the schedule's frequency. A notification written to a log does not prove delivery to your phone.
The template#
Save three scripts in gate/, update one runner prompt, and add two cron entries. Start with the notification script:
#!/bin/sh
# gate/notify.sh <tier> <message>: route one event by what your action changes.
# blocked the system is not in a state you chose. Push now, at any hour.
# review one item waits for your decision. Push, except in quiet hours; hold it then.
# info nothing waits for you. The log only; a pass also clears the repeat check.
# The same message twice in a row is pushed once. A push that fails is only logged:
# the runner repeats an ending until you act, so the next tick raises it again.
set -eu
tier=$1; shift; msg=$*
quiet_from=22; quiet_to=7 # local hours; the blocked tier ignores them
topic=$(cat gate/topic) # a random string; whoever knows it can read and post
quiet() { h=$(date +%H); h=${h#0}; [ "$h" -ge "$quiet_from" ] || [ "$h" -lt "$quiet_to" ]; }
push() { # $1 priority, $2 title, $3 body
[ "$3" != "$(cat gate/last-push 2>/dev/null)" ] || return 0
if curl -fsS -o /dev/null --max-time 20 -H "Title: $2" -H "Priority: $1" -d "$3" "https://ntfy.sh/$topic"
then printf '%s' "$3" > gate/last-push
else echo "notify: push failed; the next tick raises it again" >&2; fi
}
case $tier in
flush) # at the start of every tick: send what quiet hours held, as one message
[ -s gate/held ] && ! quiet || exit 0
body=$(cat gate/held); rm gate/held; push default review "$body"
printf '%s\n' "$body" | tail -n 1 > gate/last-push; exit 0 ;;
blocked) push urgent blocked "$msg" ;;
review) if ! quiet; then push default review "$msg"
elif [ "$msg" != "$(cat gate/last-push 2>/dev/null)" ]; then
grep -qxF -- "$msg" gate/held 2>/dev/null || echo "$msg" >> gate/held; fi ;;
info) rm -f gate/last-push ;;
*) echo "notify: unknown tier $tier" >&2; exit 2 ;;
esac
printf '%s %s %s\n' "$(date -u +%FT%TZ)" "$tier" "$msg" >> gate/events.log
Cron calls the tick script. It takes a lock, records a start timestamp called a heartbeat, runs one task, and assigns a notification category:
#!/bin/sh
# gate/tick.sh: what the timer runs. Take the lock, record the start time (the heartbeat
# the watch reads), run Lesson 7's runner once, and send one event, its tier read from
# how the run ended.
cd "$(dirname "$0")/.."
mkdir gate/running 2>/dev/null || { echo "tick: a run is still going; skipping"; exit 0; }
trap 'rmdir gate/running' EXIT
printf '%s %s\n' "$(date +%s)" "$(date -u +%FT%TZ)" > gate/last-tick.new && mv gate/last-tick.new gate/last-tick
sh gate/notify.sh flush
out=$(sh gate/run-next.sh 2>&1); code=$?
last=$(printf '%s\n' "$out" | tail -n 1)
case $code:$last in
0:*) tier=info ;; # live, a STOP file, or nothing to do
1:*"STOPPED empty"*) tier=info ;; # no ready item
1:*"not live"*) tier=blocked ;; # merged, and the site does not show it
1:*"Session stopped"*|1:*"no live: line"*)
tier=review ;; # the agent asked, or the spec has no live: line
*) tier=blocked; last="run-next.sh exited $code: $last" ;; # the runner itself failed
esac
case $code:$out in # endings the runner prints a log after
1:*"stays unmerged"*) tier=review; last=$(printf '%s\n' "$out" | grep "stays unmerged") ;;
0:*"by hand"*) tier=review; last=$(printf '%s\n' "$out" | grep "by hand") ;;
esac
sh gate/notify.sh "$tier" "$last"
Schedule the watch separately so it can detect when ticks stop starting:
#!/bin/sh
# gate/watch.sh <seconds between ticks>: the missed-run rule, on its own timer line.
# A run that should have happened and did not is blocked, at any hour.
cd "$(dirname "$0")/.."
interval=${1:-3600}
read -r last at < gate/last-tick 2>/dev/null || { last=0; at=never; }
age=$(( $(date +%s) - last ))
[ "$age" -le $(( 2 * interval )) ] \
|| sh gate/notify.sh blocked "missed $(( age / interval )) runs; last tick started $at"
Add these entries through crontab -e, replacing the project path. Include the directories containing claude and gh in cron's PATH:
PATH=/usr/local/bin:/usr/bin:/bin:/home/you/.local/bin
5 * * * * cd /home/you/project && sh gate/tick.sh >> gate/timer.log 2>&1
*/15 * * * * cd /home/you/project && sh gate/watch.sh 3600 >> gate/timer.log 2>&1
The runner's first prompt ends with or STOPPED <reason>."; replace that suffix with the stop categories the tick expects:
STOPPED empty if no item qualifies; STOPPED investigation; or STOPPED ask <your question>."
Create the topic with head -c 12 /dev/urandom | base64 | tr -dc A-Za-z0-9 > gate/topic, then subscribe to that string in the ntfy app. Anyone who learns this public-service topic can read or post messages. Keep message content appropriate for that access model.
Each part, and the mistake it prevents#
The tick classifies successful runs and an empty queue as info. A missing live: command, a stopped session, or a rejected review becomes review. A merged change that fails its deployment check becomes blocked, as do unrecognized failures. If the runner asks for a manual queue update, that also requires review. Changing the runner's output can break this classification; inspect both scripts together.
Quiet hours delay only review. The next tick outside those hours combines held messages into one push. This example deletes the held file before delivery and does not reliably retry a failed flush. Inspect errors and test receipt; do not use the log as proof of delivery.
Duplicate suppression compares message text with the last pushed message. A repeated investigation request can therefore stay in the log without sending hourly pushes. An info event clears that memory. Changing message text, such as an increasing missed-run count, can still generate repeated notifications.
The directory lock prevents overlapping ticks from selecting the same task. An abrupt termination can leave gate/running behind. Before removing it, confirm that no runner or drill still uses it.
The heartbeat records a start, not completion. A hung run can eventually trigger the stale-start alert because subsequent ticks cannot acquire the lock. A watch on the same machine cannot detect that machine's complete failure, and both cron entries stop if the scheduler stops. Independent host monitoring requires a watcher elsewhere.
A worked example#
I used Lesson 7's scratch project and started ticks by hand; cron was untested. Ready item B-005 added a heading to the status page. I removed its live: line from the spec in my checkout. Two minutes into the first tick, the topic received:
review specs/web/005-status-heading.md has no live: line; not merging.
The second tick logged the same review result without another push. I restored the line. The third tick merged B-005, passed the deployment check, and added this log entry:
2026-10-11T20:33:56Z info B-005 is live: curl -fsS --max-time 20 https://.../status.html | grep -q '<h1>Status</h1>'
The fourth tick found no ready item and logged info. I then set the heartbeat back twenty-five minutes and ran sh gate/watch.sh 600:
blocked missed 2 runs; last tick started 2026-10-11T20:09:53Z
Those five runs produced two topic messages. They demonstrated manual classification and the stale-start check, not scheduled execution or complete-host failure detection.
How it scales#
Choose an interval that leaves time for the task to finish. Update classifications when runner outcomes change, and use an external watcher when host availability matters. You set the response policy and handle decisions; the wrapper routes the messages.
From the field#
On July 2, a price alarm in my financial application appeared in the engine log, a digest file, and an outbox. The outbox's channel field read none-configured. None of the three records delivered an alert. I discovered it that afternoon while reviewing code. I configured an ntfy topic and sent a live test message. The existing alarm already suppressed duplicates; the script above adapts that rule.
Exercise#
- In the test project, save the scripts, update the runner prompt, create a topic, and subscribe on your phone.
- Run
sh gate/tick.shmanually. Then configure both cron entries with your paths and interval. - Outside quiet hours, remove the next ready task's
live:line. Wait for a scheduled tick and confirm the review message arrives. - Restore the line. Confirm a successful run logs
infowithout a push. - Disable the tick's cron entry while leaving the watch enabled. After two intervals and the next watch run, confirm a blocked message arrives.
- Restore the entry. Check delayed review delivery during quiet hours and inspect a week of alerts for incorrect classifications.
You're done when#
The missing-line test arrived on your phone, the successful scheduled run produced an info log without a push, and disabled ticks produced a blocked alert. Verify the timestamps and restore the schedule. These results cover those cases; they do not prove reliable delivery during network failures or detection of a powered-off host.
Common mistakes#
- Letting an agent choose the notification category without checking its result.
- Running the watch only inside the tick it needs to monitor.
- Omitting CLI directories from cron's PATH.
- Deleting a lock without confirming the process has stopped.
- Assuming a recorded event was delivered to the subscribed device.
Further reading#
The ntfy publishing docs cover priorities and titles. Rob Ewaschuk's My Philosophy on Alerting informed the rule that an alert should require human action. The Google SRE book's monitoring chapter distinguishes pages, tickets, and logs.
Next lesson#
Test Your Git Hooks, CI Checks, and Merge Rules: submit a deliberate violation, inspect rejection and cleanup, and receive the result through these alerts.
Questions this post answers
- When should an unattended AI agent notify me?
- Send an immediate blocked alert for a failed runner or a merged change that fails its deployment check. Send review when a task needs a decision, delaying it during configured quiet hours. Log routine success and an empty queue as info. The wrapper script chooses the category from the runner's exit code and output.
- How does the watch detect missed runs?
- Each tick records its start time before launching the runner. A separate scheduled script raises blocked when that time is more than two intervals old. This observes starts, not successful completion. A watch on the same machine cannot report a complete machine or scheduler failure.
- What do quiet hours hold?
- They delay review messages until the first tick outside the configured hours. Blocked messages bypass the delay; info events stay in the log. The held-file example is not a reliable delivery queue, so test receipt on the subscribed device and inspect delivery failures.
- How does duplicate suppression work?
- The script remembers the last pushed message and suppresses an identical consecutive message. An info event clears that memory. Messages whose text changes, including missed-run counts, can produce additional alerts.