routines · design

executable markdown on rails

A routine is a single markdown document — frontmatter for schedule, prose for judgment, fenced sh blocks for mechanics. routine runs the blocks deterministically; when one fails, the document itself becomes the prompt: claude receives the error in full context, repairs state, and the runner retries the block once. Every scheduler — launchd locally, a CI cron, a human at a shell — is a dumb tick that ends at the same routine run.

try   { blocks, in order }          # zero-LLM happy path — cheap, fast, CI-safe
catch { claude("handle $error") }   # the doc's prose is the handler's context
The whole control flow. Everything below is detail on these two lines.

Layout — a routines home, and the tool

The documents live in a routines home — $ROUTINE_HOME, default ~/.routines — and this repo is only the tool: personal routines never enter it.

~/.routines/<name>.md            # the routine: frontmatter + prose + ```sh blocks
~/.routines/.state/<name>/       # lock/, lock.reap/ while reaping, last-run.json, runs.jsonl, logs/<ts>-<pid>.log, ack, paused, resumed
~/.routines/.state/tick.log      # the sweep's journal — one line per tick

src/                             # the runner — one Rust binary, `routine`
routines/                        # this repo's own routines — the CI convention
.github/workflows/release.yaml   # a packslip release per merge to main
.github/workflows/routines.yaml  # the CI tick `routine sync-ci` writes
docs/                            # this page, its figure drawn in it
Install: routine setup — hotswap installs the latest release through packslip, pinned to its signer, into ~/.local/share/hotswap/routines/, links ~/.local/bin/routine through its current and loads its upgrade agent, which runs routine upgrade every 900 s and keeps its record at ~/.local/state/hotswap/routines.json (gigantic.dev/hotswap/); setup then loads the tick. No mise. Each merge to main releases YYYY.M.N for aarch64-apple-darwin and x86_64-unknown-linux-gnu, signed by packslip; routine --version names it.

The document — $ROUTINE_HOME/<name>.md

One file per routine. Frontmatter is flat key: value, no YAML library: # starts a comment, one pair of surrounding quotes is stripped, CRLF, trailing blanks and a leading BOM are tolerated. Only sh / bash fences execute, sequentially, each under bash -e; other fences are material for the prose. Fences follow CommonMark (``` or ~~~, 3+ long, indent 0–3 stripped, closed only by the same character at least as long); a fence inside an HTML comment is disabled. A block that needs an asset writes or references sibling paths.

---
schedule: 30 7 * * 1-5     # 5-field cron, evaluated in UTC; omit ⇒ on-demand only
timeout: 600               # seconds for the whole routine
requires: GITHUB_TOKEN     # env vars that must be non-empty in the environment
on_error: claude           # claude (default) | fail; else exit 64
---

# Morning brief

Prose is not decoration — it is the context the error-handler inherits:
intent, traps, judgment calls. Write it for the agent that arrives when
a block below has just failed.

```sh
gh api notifications --paginate > "$ROUTINE_STATE_DIR/inbox.json"
```

```sh
claude -p "summarize inbox.json …"   # a block may itself call claude — an agent step on rails
```
The schedule, the judgment and the mechanics in one artifact — script and prompt stop drifting apart.

try / catch — the failure contract

The happy path never calls a model. The document is the handler's context precisely because it was written before anything broke.

① try
  • blocks run in order; each block's output is appended to the run log under a block delimiter
  • each block's exit code is the truth — nothing interprets it
② catch — on_error: claude
  • the runner invokes claude --model opus --permission-mode=auto --no-session-persistence -p with the prompt on stdin (never argv — a large document passes ARG_MAX): the full document, the failing block, and its captured output, each section between markers carrying the run's random suffix so output cannot forge its end, cwd = the routines home, env carrying ROUTINE_NAME, ROUTINE_STATE_DIR and ROUTINE_HOME as the blocks see them
  • instruction: running unattended; diagnose and repair state; do not continue the routine yourself
③ retry
  • the runner re-executes the failing block once — pass ⇒ continue to the next block; fail ⇒ the routine exits with that block's code
  • one repair attempt per block, no loops
④ degrade
  • no claude binary, or no credentials (claude auth status exits 1 — bare CI) ⇒ behaves as on_error: fail, with the reason logged; credentials are never verified, so a bad or expired one still runs the catch, and its failed agent stamps the degraded marker that a repair which ran clears

Due-ness — derived, never matched

A routine is due when next-fire-after(last started run, schedule) ≤ now; a missing last-run.json, or one stamped ahead of the clock (a stepped clock), means due. Cron evaluates in UTC — one clock for launchd, CI, and the shell.

one evaluator buyswhy
CI correctness under delayed or skipped tickscompare against the last run, not "does now match the expr"
launchd catch-up after sleepfree — the same comparison, no wake hook
routine run --due as the universal entryevery scheduler is a dumb tick

next-fire-after walks days forward from the last run, dates by arithmetic, never a fork (horizon eight years, so Feb 29 recurs; dead months skip to their 28th) — dumb, correct, sub-second. Day-of-month and day-of-week follow cronie: OR when both are restricted, AND when either opens with * (*/2 included).

Schedulers are dumb ticks

Neither scheduler knows a routine's schedule. Both wake up, ask the one evaluator what is due, and exit.

launchd — dev.gigantic.routines.due
  • routine setup writes it, first booting out the retired com.routines.due; --remove boots it out; the upgrade agent is hotswap's alone
  • StartInterval 60 + RunAtLoad true, running ~/.local/bin/routine run --due, the link through hotswap's current — a swap needs no rewrite, and a loaded tick whose plist changed is booted out and bootstrapped again — with PATH and the ROUTINE_HOME/ROUTINE_DIR/ROUTINE_STATE anchors stamped (XML-escaped) — no cd, the runner enters the routines home itself
  • RunAtLoad fires once at load — bootstrap and login; after a sleep the first StartInterval fire (those due while asleep are missed, launchd.plist(5)) runs --due, and derived due-ness catches up whatever fell due
CI — one static workflow
  • routine sync-ci emits .github/workflows/routines.yaml into the repo it is invoked in
  • cron every 15 min + workflow_dispatch, one tick at a time (a concurrency group: runners share no lock); ROUTINE_HOME = that repo's routines/; restore routines/.state from actions/cache; mise-action with no tools, then mise x packslip:jgeschwendt/routines@latest -- env -u GITHUB_TOKEN routine run --due — mise verifies the release against its signed packslip, MISE_MINIMUM_RELEASE_AGE_EXCLUDES=packslip:jgeschwendt/routines lets it see one under 24 h old, and env -u drops the token mise-action exports; save the cache
  • the save runs under if: always() — actions/cache saves only on success, so one red routine would roll back every other routine's state
  • each tick saves a new key, keyed by run and attempt so a re-run never collides with a taken one; once this run's key is listed (a failed save still exits 0) every older routines-state- entry on the same ref is deleted (gh cache delete, actions: write)
  • every action is pinned by commit and checkout persists no token (persist-credentials: false): a moved tag cannot run under the job's token, and no block reads it from .git/config — a block that needs git auth brings its own
  • cache eviction makes everything due once — idempotency absorbs it
  • the private ~/.routines repo carries no workflow: its only tick is launchd's
routine run  frontmatter → lock (mkdir .state/<name>/lock, pid and its start time inside; live pid ⇒ 75, dead ⇒ reap, reused (its UTC start time differs, where ps can read it) ⇒ reap, no pid ⇒ held for a minute; no lock age frees a live pid — a sleep or a lowered timeout ages a live holder's too; a reap runs under a mkdir lock.reap guard and re-judges inside it, so two reapers never both win — a fresh guard ⇒ 75, one a minute old is a crashed reaper's)
             → requires gate (exit 78, loud list of missing vars — recorded only by the holder; a run that loses the lock records nothing, even signalled)
             → cd $ROUTINE_HOME (blocks and the catch run there; a missing home ⇒ 64)
             → watchdog (a thread on the monotonic clock; SIGTERM to the block's group, SIGKILL after grace; a block's leftover children (cmd &) get TERM when it exits; a block or agent started past the deadline is TERMed within a second, once exec'd, and KILLed with the rest; a sequence still not done a second after the KILL is KILLed too, with any child it forked meanwhile, so the watch is bounded; exit 124, and a catch that outlives the deadline skips its retry)
             → HUP/INT/TERM (129/130/143) TERM the block's group, KILL it after two seconds, before the record and the lock release; run --due forwards its own as TERM to every routine it runs
             → blocks under the try/catch contract
             → last-run.json {started, started_epoch, finished, exit, duration, degraded}, written on every path, renamed into place, and appended to runs.jsonl
             → the failing block's exit passes through
The shared wrapper — every verb that runs a routine runs it through this.

The figure

One execution path, end to end: the tick, the gate, the lock, the blocks, and the single catch that repairs and retries.

  • launchd tick · CI cron · shell
  • run · the shared wrapper
  • catch · claude repairs, retry once
  • bypass · exit with the block's code

exit · 64 usage · 75 lock held · 78 requires missing · 124 timeout · else the failing block's code

One execution path, end to end: every scheduler ticks into the same wrapper, and a failing block gets one repair and one retry before its own code exits.

Verbs

The whole surface, plus help and --version.

verbduty
run <name>run one document through the wrapper — gate, lock, timeout, try/catch
run --duethe universal entry — each due routine a routine run <name> child ignoring INT and QUIT, all started at once and waited for; silent when none are; exits 1 when any failed
statusfrontmatter × last-run join: schedule, due? (bad for a schedule the parser rejects, which never fires; paused while a pause holds it), last exit, duration
health [--json]one verdict over the home, from the runner's own parsers and state, never a second reading of them. Per routine the first match wins: lint — every reason the runner would refuse or mis-read the doc (no sh/bash block, an on_error neither claude nor fail, a timeout that is no positive number, a schedule that never fires); wedged — a live lock held past the doc's timeout and the watchdog's minute; paused — a pause holds it, so it is never due, stale or red, whatever its last exit; a non-zero last exit — acknowledged while an ack holds that exit, else finding for exit 1 (it ran and found something: informational, never red) and failed for 2 and above; stale — due, idle, and passed over by a sweep that could dispatch (a tick docs= line in tick.log no defer dark-wake follows) half an hour after it fell due or was resumed, so a slept machine or a dark wake never reads as stale. The tick is not-loaded, stale when tick.log has been quiet ten minutes since its last line or the machine's last wake (sysctl -n kern.waketime), whichever is later, and no routine runs (a long run holds the tick), or unmanaged with no launchctl; a slug-less doc opening with frontmatter and state with no doc are red too (archive the state, never delete it). Plain prints each red finding with its fix, then each routine's finding, acknowledgement and pause, and a closing line — healthy — N routines or unhealthy — N red, with · M finding(s) when there are any; --json prints one line for an app to render, every finding — a routine's, the tick's, a skipped doc's, an orphan's — carrying the fix the plain report prints, so a renderer never invents one. The watcher belongs outside the tick: an app that calls routine health sees a dead tick, a routine riding the tick cannot
ack <name> [reason…] | --clearhold the last run's non-zero exit — a finding's too — as known in .state/<name>/ack, so health reports it acknowledged and stays green; the runner drops the ack when a run exits otherwise — green, or a different failure — so an ack never hides a new kind of failure; --clear drops it by hand
pause <name> [reason…]hold the routine off the tick in .state/<name>/paused: run --due passes it over, journalled <name>@paused in tick.log, and health reports it paused, never red; run <name> still runs it. Pausing again restamps the time and reason; the marker's presence is the pause, whatever it holds
resume <name>lift the pause and stamp .state/<name>/resumed; due-ness is derived, so a fire the pause covered runs once on the next tick, and health counts stale from the resume; a routine that is not paused is left as it is
setup [--remove]aliases install · uninstall; hotswap::ensure first — the latest release installed when none is, ~/.local/bin/routine linked through current, the upgrade agent dev.gigantic.routines.upgrade written, loaded or reloaded by hotswap alone — then write and load the tick on that link, reloading it when its plist changed. The tick never runs the binary that ran setup, so a checkout's cargo run -- setup wires the installed release, its own plist rendered until the next swap reruns the release's setup. --remove boots the tick out, deletes it and the link, and hotswap::forget drops the upgrade agent, the layout and the record
upgrade [--check | --back | --retry]hotswap::upgrade: packslip installs the release, hotswap repoints current; the drain refuses while any routine holds its lock/ (setup's reload and the tick's restart would kill it), then routine setup, the tick's restart, and routine status as the smoke probe, 120 s a step — green settles, red rolls back. The restart is decided when the step runs: a tick launchd loaded at login carries a managed launch constraint that a swapped binary violates, and only a bootout, a wait until launchctl print fails, then a bootstrap from the plist path print names (five tries, 2 s apart) drops it, so a tick whose print shows managed LWCR and is not disabled is reloaded that way, and any other is kickstarted. The upgrade agent's own reload waiter does the same whenever its print shows the constraint. Exits 0 green or settled, 1 red or refused, 2 unable to try. Off mise: the release before this one bumps mise, then drains; a refused drain strands the host on the new binary through mise's shim, and the next tick's upgrade, run through that shim, lays out every version mise holds, makes the running one current and moves the upgrade agent onto the link before its own drain; its setup moves the tick at the swap. A red first swap rolls back onto mise's copy of the old release with mise use -g packslip:jgeschwendt/routines@<V> first, so its setup's shim runs it; the next release moves the host again. mise's dirs are left alone; once no version on disk predates hotswap, an upgrade says to run mise unuse -g packslip:jgeschwendt/routines
sync-ci(re)write ./.github/workflows/routines.yaml in the invoking repo

Exit codes and contracts

codemeaning
64unknown routine, or usage; ack of a last run that is no failure; pause or resume of an unknown routine; recorded when the document has no sh/bash block or an on_error neither claude nor fail, or the routines home is missing
73recorded when mktemp cannot create the run's temp dir (a missing TMPDIR); unrecorded when the routine's state dir is not writable, its refusal in tick.log; ack when the ack cannot land; pause or resume when the marker cannot land or lift
75lock held by a live run
78requires missing
124timeout — the watchdog fired
129/130/143HUP/INT/TERM — the block's group stopped, the exit recorded; run --due forwards its own as TERM and exits with it
1run --due: a dispatched routine failed · health: anything is red · install/setup: the release cannot install or link, a plist cannot land, or launchctl bootstrap failed · upgrade: red, or refused by the drain or the red hold
elsethe failing block's own code, passed through

Scale: the runner is ~1,900 lines of Rust outside its tests (measured 2026-11-22 · non-blank lines of src/*.rs above each #[cfg(test)]).

Next

  1. One long run holds every tick — run --due waits for its slowest child, and launchd fires no tick meanwhile; proposal tick-no-wait (docket 5c18bc51) is back for revision (owner, 2026-10-27).
  2. An old reap guard is passed, not claimed — two runs meeting a crashed reaper's lock.reap can both reap — reproduced by injection (s-20261027T0645Z); claiming it by rename is still ABA-prone, so it needs guard identity (pid + start).
  3. hk 2.5.0 → 2.8.1 (mise.toml, hk.pkl): no breaking change listed; the shift sandbox cannot install it.

Gate spans

Every run of mise run check is one OpenTelemetry trace through floodgate span: a check span with each step nested under it (fmt, clippy, cover, stele.check and stele.emit), so floodgate's page shows which steps cost the time and CPU.

check only wraps check:steps in its root span; the steps live there. A step is wrapped in mise run span -- <name> [--attr k=v]… -- <cmd…> (.mise/tasks/span): it execs floodgate span when floodgate is on PATH, else the command after the second --, so a machine without floodgate, CI included, gates as before. To add a step, put it in the check:steps task's run list wrapped the same way; a step left bare is time no span explains.

Rejected alternatives

since 2026-08-12 · initial design — user sketch + executable-markdown/try-catch directive · since 2026-08-16 · ROUTINE_HOME — documents and state live outside the tool repo