Schedule crons

From sonichi/sutando · View interactive version

Schedule crons is an AI agent skill from the GitHub repository sonichi/sutando. Re-create all session cron jobs for Sutando. Run this on startup or after a session restart.

How to use this skill

Skill file

Schedule Crons

Re-create all session cron jobs for Sutando. Run this on startup or after a session restart.

Usage: /schedule-crons

Scope. This skill schedules Sutando's own startup, maintenance, heartbeat, backend and

proactive jobs, and they stay native, as do starter jobs the owner switches on in crons.json. A reminder or timed job an

owner asks for in an s.space room or DM goes to the platform scheduler instead

(CODE0); add one

here only in the last-resort case that skill describes. This does not disable cron, and starter jobs are not migrated automatically.

How It Works

Jobs are defined per host in <workspace>/hosts/<hostname>/crons.json — per-host, synced + backed up via the vault (carried as part of the hosts/*/ per-host subtree (#1717), which is hostname-qualified so it never collapses across hosts; see CODE2 and CODE3). <hostname> is bash scripts/sutando-config.sh host-label — the canonical per-host label ($SUTANDO_HOST_LABEL > scutil LocalHostName > short hostname), matching the sync layer's host slug. (Do NOT use a bare hostname | sed 's/\..*//': a DHCP lease can drift the hostname (e.g. Comcast → Chis-MBP) and split per-host paths from the stable label; #1745.) A template is in crons.example.json (in this skill dir, version-controlled). Step 1 seeds a missing per-host file with python3 skills/schedule-crons/scripts/seed_crons.py, which writes the template's starter set: every entry except those marked "opt_in": true. Do not cp the whole template: its opt-in entries start only on the owner's word. crons.example.history.json holds a digest of every entry the template has ever shipped, which the seeder uses to tell a shipped sample from an owner's job; a change to an entry of crons.example.json appends the new entry's digest there (tests/schedule-crons-seed-policy.test.py enforces it and computes it).

(Migrated from the old skills/schedule-crons/crons.json, which lived in the code checkout — misfiled per the workspace contract, and per-host-but-unsynced. That file is never seeded from: older installers filled it from the template, so its jobs prove no opt-in. The new path is proper per-user state: backed up + visible across hosts, each host keeping its own cron set.)

Each entry has:

On macOS, the Codex core launcher automatically reconciles ordinary fixed-interval entries to this owner because Codex has no session CronCreate surface. It preserves main-loop, dynamic loops, and entries already owned by execution: "codex-task", and initializes the runner boundary before changing ownership so activation never replays an old action backlog.

Durable Codex schedules

Install or reconcile the per-minute launchd runner after adding an execution: "codex-task" entry:

python3 skills/schedule-crons/scripts/codex-scheduler.py install
python3 skills/schedule-crons/scripts/codex-scheduler.py health

The runner calculates cron slots in each job's declared timezone, catches up the newest missed slot after sleep, atomically enqueues a deterministic task ID, and uses distinct attempt IDs when an inactive task needs retrying. A queued, claimed, or processed attempt is never duplicated; if it remains active past active_stale_minutes, the run fails with a proactive alert so the schedule cannot stall forever. Durable run state lives at <workspace>/state/schedules/codex-scheduler.json. Exhausted retries produce a proactive-schedule-alert-*.txt result. health exits non-zero for a stale scheduler heartbeat or a latest-run failure.

When core.runtime is codex, the canonical unmarked main-loop entry (prompt_skill: "proactive-loop") is also owned automatically by this runner. Codex has no session CronCreate surface, so each fire emits one silent, low-priority proactive-pass task. The host's crons.json is not rewritten; switching back to Claude restores the normal session-owned loop. The Codex launcher reconciles the launchd runner on every start or attach.

On Activation

  1. Read <workspace>/hosts/<hostname>/crons.json (resolve <workspace> via bash scripts/sutando-config.sh workspace; <hostname> = bash scripts/sutando-config.sh host-label). Self-heal: if that file is missing, the seeder creates it, then read it. It never enables a job the owner did not opt into: a host whose file existed before gets the template's starter set, an interim <workspace>/crons/<hostname>.json is migrated whole, and anything else gets the starter set. It never copies the in-checkout skills/schedule-crons/crons.json. It can print two owner notices. The seeder has already queued each one to the owner's DM, so do not send it again; follow it up when the owner answers, and once they have answered (re-added jobs, or said to leave them) run python3 skills/schedule-crons/scripts/seed_crons.py --notice-sent, which clears only the notices printed so far. Until then a notice stays recorded and is printed at most once a day. A not-enabled … only at <path> (an app update replaces it) line means no copy could be saved yet: say so to the owner; later runs keep retrying the copy. A not-enabled … lost: … line means an app update replaced that file before a copy was saved: the owner is told those jobs are lost. A notice-record-unreadable kept at <path> line means the notice record was damaged and set aside: read that file, tell the owner any notice it still holds, then run --notice-sent. restored <path>: this host's crons.json had been set up before and was missing, so the starter set was restored; the owner's own jobs are gone from it and need adding back. not-enabled <names> kept at <path>: the legacy file held jobs no shipped template matches, which may include jobs of the owner's own; say which jobs were not enabled and where the file is kept. Add a job to the per-host file only on the owner's word; never enable one without it. python3 skills/schedule-crons/scripts/seed_crons.py

1.5. Start the streaming task watcher NOW, before registering any cron jobs. This step used to run last (as step 5, after every CronCreate round-trip below) — moved here so an incoming task isn't queued unprocessed for the entire registration loop. Measured impact (startup-latency post-mortem, 2026-08-24, RC9 onboarding): with N session crons the old ordering left the watcher unarmed for ~76 seconds on a fresh boot (one CronCreate round-trip per entry, 9 entries measured), during which a brand-new user's first onboarding ping sat unprocessed — the single biggest contributor to "Sutando took a while to respond" reports on first boot.

If python3 src/watcher_rearm.py mod-ready --repo "$PWD" --workspace "$(bash scripts/sutando-config.sh workspace)" prints yes, the task-watch Mod (the default) runs the watcher: skip this step. On no, fall back to the Monitor below.

Start it via the Monitor tool — pass command: 'bash src/watch-tasks-stream.sh --role session --inbox "$(bash scripts/sutando-config.sh workspace)/tasks"' (an instance whose inbox isn't <workspace>/tasks/ substitutes $SUTANDO_TASKS_DIR for the resolved path instead: that variable, when set, is what the watcher and its supervisor both resolve to, so the tag must carry it, not the workspace default; every reader compares inboxes by their real path, so a trailing slash or a /private prefix does not split one inbox into two), timeout_ms: 1800000, description: 'Streaming task watcher'. Monitor has no persistent option (passing one does not keep the command alive; without timeout_ms the command is killed at the 5-minute default and the standby takes over until the next pass re-arms it). It kills the command at timeout_ms (30 min is the maximum) and sends one expiry notice; on that notice, run this step again — a start on a watched inbox exits 0. A notice that the command exited early is the same instruction (re-arm first, investigate second: the standby only covers after its 45 s grace); on macOS Claude Code reports a watcher killed by SIGTERM as exit code 144, which is not SIGURG and not the watcher's own crash. --role session --inbox <value> is what makes this an in-session watcher CODE can tell apart from an external one for the SAME inbox (#4477) — the watcher itself, on seeing --role session, proves readiness, stamps its sentinel, then waits up to 15 s for any external standby on this exact inbox to leave before its sweep (it kills nothing: #4585), and task-notifier-supervisor.sh (if one is running externally) polls the same inbox-scoped, sentinel-gated signal and stands the standby down; neither needs an instruction here to tear the other down, so there is no teardown step in this skill. The script emits one TASK_FILE: <basename> line per new task file (initial sweep + each subsequent event). Read the named file via the Read tool when notifications arrive. The watcher checks its own inbox at startup (watcher_identity.py inbox-holders): if a session watcher already covers it, the new one exits 0 naming the holder, so the Monitor call is safe to make whenever the per-inbox verdict says no session watcher is ready; never start it untagged, and use --force-restart only on the owner's word. The host-wide enumerator below stays for the STOP decision (which pids are ownerless), never for the start:

```bash

python3 -c "

import importlib.util, sys

s = importlib.util.spec_from_file_location('hc', 'src/health-check.py')

m = importlib.util.module_from_spec(s)

try: s.loader.exec_module(m)

except SystemExit: pass

ps = m._ps_snapshot()

sys.exit(2 if ps is None else (0 if m._watcher_trees(ps) else 1))"

case $? in

0) echo skip;;

1) echo start;;

*) echo 'UNKNOWN: ps did not run — do NOT start; a watcher may be live';;

esac

```

Three states, not two: an unavailable ps is UNKNOWN, not "no watcher".

_watcher_trees() catches every ps timeout/error and returns {}, which is

byte-identical to a clean empty scan — so the earlier `0 if m._watcher_trees()

else 1 form printed start` when enumeration merely failed. Starting there is

exactly the duplicate this step exists to prevent, and it is the same

can't-distinguish defect the paragraph below names for the sentinel, pointing

the other way. _ps_snapshot() separates them: None means ps did not run,

"" means it ran and found nothing. On UNKNOWN, do nothing — a missing

watcher costs delayed tasks, a duplicate one processes every task twice.

Do not gate on the sentinel alone. watch-tasks-stream.sh writes it once at startup, so an absent file means "no watcher" OR "a live watcher whose file was removed" — indistinguishable. Measured 2026-08-07 on a live core: _watcher_trees() returned {'12631': ['12631']} (functioning — it emitted TASK_FILE: for a probe) with the sentinel absent from disk. Gating on the sentinel there would have started a second watcher, and both then emit every task, so every task is processed twice. _watcher_trees() is also what makes the pgrep warning below unnecessary to re-solve: it drops its own pid and matches on argv shape. Don't use pgrep -f watch-tasks-stream: pgrep's -f argument matches the literal string watch-tasks-stream against full argv, which matches the bash wrapper invoking this very pgrep call (the wrapper's argv contains the search string), producing a transient self-match that returns a PID for a subshell that's already gone by the next ps. Same PID-stamp + kill -0 pattern as the catchup sentinel in step 0 — single anti-pattern, single fix. Documented as F5 in workspace/build_log.md 2026-06-03T00:02Z validation pass; replayed on the very next session bootstrap (07:25Z) — Sutando.app's checkWatcher Timer caught the gap and sent a watcher keystroke, but two owner DMs were silently held in tasks/ for ~5 min first. Don't kick off bash src/watch-tasks.sh (retired 2026-05-14).

1.6. Arm the registration watchdog, then handle tasks freely — registration is guarded by a mechanism, not by deferral. Because step 1.5 arms the watcher before the registration loop, a TASK_FILE notification (the startup sweep's, or a live arrival) can land while steps 2-4 are still running. Without a rule here the agent improvises under the general "process notifications when they arrive" instruction, pivots to the task, and may never finish registration — losing the /proactive-loop fallback, the one thing that guarantees the session has a recurring work driver (that silent loss is the incident class this step exists to close). The old cure was a deferral rule ("finish registration first"), which cost a waiting user the whole registration window before any answer. This step replaces discipline with a watchdog: immediately after step 1.5, before touching any task, arm ONE Monitor:

```

Monitor tool — description "schedule-crons watchdog", timeout_ms 3600000, command:

cd "$(git -C . rev-parse --show-toplevel 2>/dev/null || echo .)" 2>/dev/null || true

T0=$(date +%s); WS="$(bash scripts/sutando-config.sh workspace)"

STAMP="$WS/hosts/$(bash scripts/sutando-config.sh host-label)/schedule-crons-stamp.json"

[ -n "$WS" ] || { echo "CRONS-WATCHDOG-INERT: workspace did not resolve — guard not armed"; exit 1; }

sleep 90

while [ "$(stat -f %m "$STAMP" 2>/dev/null || echo 0)" -lt "$T0" ]; do

echo "CRONS-UNREGISTERED: schedule-crons has not stamped this boot — return and register now"

sleep 60

done

echo "CRONS-STAMPED: registration complete"

```

Then respond to task notifications as they land: send the fail-open progress ack first (python3 skills/task-progress/scripts/notify.py ... — one subprocess, no state mutation, cannot derail anything), and use judgment on handling — a short waiting owner task may simply be served before registration continues; anything substantial gets the ack and is handled when the agent is next free. Either way registration cannot be silently dropped: if it slips, the watchdog emits a nag every 60s until step 5.7's completion stamp lands, and the terminal CRONS-STAMPED line confirms the guard saw the stamp — which is also why that stamp write is not optional bookkeeping; it is what releases the watchdog. The 90s grace means a normal boot never hears from it, and the 1-hour cap bounds noise if a boot dies (an unregistered state dies with its session). Detection and re-prompt share one source of truth: the same stamp health-check.py's session-crons probe already reads. stat -f %m is the darwin form; swap for a python3 -c mtime read on linux. Resolve the workspace INSIDE the command — a Monitor is a fresh shell and the loop's WORKSPACE is a per-command local that is never exported, so an inherited $WORKSPACE is empty there and the stamp path silently becomes /hosts/<label>/..., which never exists: the guard would then nag on every healthy boot (~58 times before the cap) and never print CRONS-STAMPED. That failure looks like the watchdog working hard, which is why the empty-WS refusal above is loud instead: an unarmed guard must announce itself rather than pass as a busy one.

  1. Check existing cron jobs with CronList

python3 skills/proactive-loop/scripts/claude-quota-cadence.py --json when the selected core

is Claude. For the canonical main-loop entry, use its effective_cron instead of the raw

cron field. The helper returns the configured cron below 80% 7-day utilization and

*/30 * * * * at/above 80% or when quota telemetry is missing, stale, rejected, or not

authoritative for this routed core. This is a registration

override only; never rewrite crons.json, because that configured value is the restoration

target after quota resets. Codex keeps using its own quota telemetry and durable scheduler.

  1. Filter to entries the core owns before iterating. This step always runs as the core, never a worker (workers never call /schedule-crons; see skills/startup/SKILL.md's worker section). Skip any entry whose owner names a worker — it belongs to that worker's own registration, and registering it here too double-fires it (this closed a real incident: a room's event-mining-hourly posted from both the core and its pinned worker until the entry was marked owner-pinned). Absent owner is unaffected — that is still every entry today.

```bash

python3 src/cron_prompt_gate.py "$CF" # --owner core is the default

```

This prints entries_for_owner(cfg, CORE) (src/cron_ownership.py) with one extra field per

entry, registered_prompt: the exact text to pass to CronCreate (or as the /loop body),

with the owner-task gate preamble already in front of every entry that fires more than once a

day (or sets "gate": true) unless the entry is the main loop, opts out with "gate": false,

or already calls scripts/cron-gate.sh itself; a daily-or-rarer entry is registered verbatim

(src/cron_prompt_gate.py is the one rule; a worker's startup pass uses the same command with

--owner <its id>). Iterate the filtered list below, not the raw file.

entry already exists, RE-REGISTER it rather than skipping** — capture every existing job ID,

CronCreate the replacement from the current crons.json text, and confirm its new ID in

CronList before deleting any captured old ID. Then delete the old IDs and confirm exactly one

replacement remains. If creation or confirmation fails, retain the old job and stop loudly;

a brief duplicate preserves liveness, while delete-first can strand a session with no driver.

This bullet does not apply to the dynamic-loop branch below (loop: "dynamic"),

which is never CronCreated and keeps its own freshness-sentinel guard — re-launching one

mid-session would re-run the loop body immediately, the exact failure that guard prevents. A session cron is a **snapshot of the prompt taken at registration

time**; editing crons.json afterwards does not reach it. The former rule here was "skip if a

job with matching prompt/name already exists", which made that snapshot permanent for the life

of the session: a long-lived core kept firing a prompt its own config had already superseded,

and every cheap check agreed the config was right.

Observed on a long-lived core: it booted 2026-07-30, the pr-flag entry gained

--stand "<stand>" on 2026-08-03, and the registered job kept firing the pre-edit text for two

days. That flag is what makes the pr-triage skill's pr_flag.py populate is_mine (it is deliberately null

without one), so the cron's own instruction — "judge from `ci/mergeable/review/approvals/

is_mine`" — was reading a field that was structurally always null, with a correct script and

a correct config file. Re-registering fixed it: is_mine went from null on all 27 PRs to

20 true / 5 false.

**Do not "compare the prompt and only re-register on a mismatch": CronList truncates the

prompt**, so the differing tail is exactly what a comparison cannot see — the --stand drift

above sat past the truncation point. Unconditional re-registration is the only reliable form.

This does not risk the inline-fire failure described at the end of this step: CronCreate

schedules the next fire time and never runs the prompt on registration.

above for the Claude main-loop entry):

prompt_skill field. For an ungated entry that is the original prompt, or /skill-name

for a prompt_skill entry — the main loop's bare /proactive-loop (the leading slash

makes the scheduled cron fire the skill as a slash command). For a gated entry it is the

gate preamble followed by the original prompt, or by invoke the skill /skill-name for a

prompt_skill entry — the firing agent runs the check first and, when it prints clear,

invokes the skill through the Skill tool.

  1. Fallback — ensure /proactive-loop is scheduled. After step 3, check whether any job in crons.json references /proactive-loop (either "prompt_skill": "proactive-loop" or a "prompt" whose body invokes the loop). If none does, call CronCreate directly with the Claude quota helper's effective_cron (*/10 * * * * is its normal missing-config fallback) and prompt: "/proactive-loop" as a bootstrap-safety net. Rationale: post-#954 the CLI boots with -- "/schedule-crons" and exits once registration finishes, so if crons.json is missing/empty/forgot-to-include-the-loop-entry the session goes idle with no recurring work driver. The fallback guarantees the loop runs at least every 10 min when quota telemetry is healthy and below threshold, while preserving the same 30-minute protection near quota exhaustion. Idempotent: if the user has a custom */5 * * * * or */15 * * * * entry, that satisfies the check and the fallback is skipped (no duplicate cron).
  2. Streaming task watcher — already started in step 1.5, before this step's registration loop ran. (Moved 2026-08-24: previously ran here, after every CronCreate round-trip in steps 2-4, leaving the watcher unarmed for the whole registration window — see step 1.5 for the measured impact and the gate logic, which is unchanged, just earlier.) No action needed here on a normal pass; nothing in steps 2-4 above needs the watcher running to complete.

5.4. Arm monitor-type entries (durable Monitors). For each crons.json entry carrying a monitor object, arm its persistent driver via the Monitor tool — command: the entry's monitor.command, timeout_ms: 1800000 (the tool's maximum; there is no persistent option, so re-arm on the expiry notice exactly as step 1.5 does), description: the entry's monitor.description — UNLESS a process matching monitor.match is already running. Gate exactly like step 1.5's watcher: on a running PROCESS, never on a sentinel. At boot (a fresh session) nothing is running so it always arms; on a mid-session re-run it skips if the driver is live, so it never double-drives. Use a check whose own process tree can NEVER contain the match string (the same self-match trap step 1.5 warns about — do NOT use pgrep -f, and do NOT pass the match string as a literal anywhere on the command line: not as an argv to the checker, and not via a printf | python pipe either — the bash -c wrapper running the pipeline carries the WHOLE command text, match literal included, in its own argv, and it is alive during the scan, so excluding only the checker's pid still false-matches and reports skip while the monitor never arms). The checker must read the match from the crons.json FILE, keyed by entry NAME — the entry name is the only literal on the command line, and no driver's argv contains entry names. AND ITS FAILURES MUST NOT ARM: a two-way && skip || arm maps every checker failure (resolver error, missing/malformed crons.json, ps failure, exception) to arm, duplicating the monitor exactly when the host is least healthy. Three-way exit semantics — 0 = driver RUNNING (skip), 1 = VERIFIED absent (arm), 2 = CHECK FAILED (do NOT arm; post the failure like a loud-stop):

```bash

python3 -c "

import subprocess,sys,json,os

try:

r=subprocess.run(['bash','scripts/sutando-config.sh','workspace'],capture_output=True,text=True,timeout=15)

h=subprocess.run(['bash','scripts/sutando-config.sh','host-label'],capture_output=True,text=True,timeout=15)

if r.returncode or h.returncode: sys.exit(2)

entries=[e for e in json.load(open(os.path.join(r.stdout.strip(),'hosts',h.stdout.strip(),'crons.json'))) if e['name']==sys.argv[1]]

if not entries: sys.exit(2)

match=entries[0]['monitor']['match']

p=subprocess.run(['ps','-axo','pid=,command='],capture_output=True,text=True,timeout=15)

if p.returncode: sys.exit(2)

run=[l for l in p.stdout.splitlines() if match in l and 'ps -axo' not in l]

sys.exit(0 if run else 1)

except Exception:

sys.exit(2)" '<entry-name>'; rc=$?

case $rc in 0) echo skip;; 1) echo arm;; *) echo "CHECK-FAILED rc=$rc — do NOT arm";; esac

```

(No pid-exclusion is needed: the match literal exists only inside crons.json and the python process's HEAP, never in any argv in the checker's ancestry — so any ps hit is a genuine driver process. Requirement on monitor.match: pick a substring of the driver's command path that no entry NAME collides with, e.g. personal-content-loop/scripts/content-driver.sh.)

arm → call the Monitor tool with the entry's command/description and timeout_ms: 1800000. These entries are Monitors, not crons: do NOT CronCreate them and do NOT count them in step 5.7's registered. This is the durable-Monitor mechanism — a Monitor declared in crons.json and re-armed on every boot, the same shape the task watcher (step 1.5) uses, but data-driven.

5.5. Ensure the core heartbeat is running (sonichi/sutando#2198 prerequisite). src/core_heartbeat.py (the writer of state/cores/<hostname>.alive) is started by src/startup.sh — but the CLI boot path lands here without ever running startup.sh (observed 2026-07-20: desktop-supervised core running for 20+ min with state/cores/ empty, so the dashboard/health-check read the core as dead and the stop-path had no pid/socket target). Check freshness of "$WORKSPACE/state/cores/$(bash scripts/sutando-config.sh host-label).alive" — if the file is missing or its mtime is older than 90 seconds (the documented staleness threshold), start the heartbeat: nohup python3 src/core_heartbeat.py > /tmp/core-heartbeat.log 2>&1 &. Freshness-of-.alive is the running-check by design — do NOT use pgrep -f core_heartbeat (same wrapper-argv self-match anti-pattern as step 1.5's watcher note), and a fresh mtime is exactly the signal every other reader of the file trusts. Idempotent on mid-session re-runs: a live heartbeat keeps the mtime younger than 90s, so the start is skipped.

5.6. Auto session-recap on boot (owner directive 2026-07-13). When more than one session transcript exists (i.e. there is a previous session to recap), run the session-recap skill's boot recap over the previous session. Per the recap contract (skills/session-recap/SKILL.md "Automatic recap on restart"), this is two behaviors with different gates — do NOT gate the whole step on recap_room:

Idempotence lives in the recap skill's state/last-recap-session.txt stamp — a mid-session /schedule-crons re-run finds the previous session already stamped and skips both the write and the post, so this never double-writes or double-posts (same guard philosophy as the dynamic-loop freshness sentinel in step 3).

5.7. Stamp completion for the health-check divergence guard. After all registrations (and the fallback check in step 4), count the session-owned entries you actually registered this run (CronCreate successes + pre-existing matches from step 3, including the main-loop/fallback; EXCLUDE monitor-type, launchd, and codex-task entries — they are not session crons) and write the stamp — script-visible proof that THIS core boot completed registration:

```bash

WS="$(bash scripts/sutando-config.sh workspace)"

H="$(bash scripts/sutando-config.sh host-label)"

mkdir -p "$WS/hosts/$H"

DIGESTS="$(python3 src/cron_entry_digest.py "$WS/hosts/$H/crons.json")"

echo "{\"ts\": $(date +%s), \"registered\": <count>, \"config_total\": <total entries in crons.json>, \"config_digests\": $DIGESTS}" > "$WS/hosts/$H/schedule-crons-stamp.json"

```

health-check.py's session-crons probe compares this host-owned stamp against the same host's core heartbeat started_at: a stamp older than the boot means session crons died with a previous session and were never re-registered (the silent 2/18 failure observed on a peer instance 2026-07-23). Do not skip the stamp on re-runs, or when crons.json holds no entries: step 4 still registers the fallback /proactive-loop, so that run stamps "registered": 1. A fresh stamp is what stops the desktop re-sending /startup every 10 minutes. The gate still reports that case as incomplete (1 registered against 0 session-owned), so /startup complete is not printed for it.

config_digests is what makes an edit visible. Everything else in the stamp is a COUNT, and a

count cannot see an entry whose prompt changed after it was registered. Stamp the digest map of

the crons.json you just registered from; the probe recomputes it and names any session-owned

entry whose digest moved. Write it in the SAME command as the counts — a digest map stamped

separately can be skipped, and a stamp with fresh counts and a stale digest map is worse than one

with no digest map at all. Omitting the field is safe (the probe skips the check); a WRONG map

would report drift that is not there.

Then publish this host's schedule to the owner's Crons room database, so anyone can see what

every agent has scheduled: python3 skills/schedule-crons/scripts/crons_table.py sync. It is

fail-open (one line and a non-zero exit when the room is unreachable) and never blocks

registration; an unchanged crons.json writes nothing, so rows deleted in the room come back

only with sync --force. A cron may end its prompt with

python3 skills/schedule-crons/scripts/crons_table.py touch <name> "<one-line result>" to stamp

its row's Last ran (UTC) and Last result.

  1. Confirm what was scheduled — note whether the proactive-loop fallback was triggered (informs operator that crons.json may need a persistent entry).

Adding New Crons

Edit <workspace>/hosts/<hostname>/crons.json (this host's cron set) to add/remove jobs. No need to change this skill file. The proactive-loop fallback (step 4 above) auto-armed if your crons.json is missing the loop entry; add an explicit proactive-loop entry to suppress the fallback message and pick your own cadence.

Defer crons when owner tasks are queued

A session cron that fires more than once a day yields to the owner's queued work by mechanism,

not by discipline: step 3 registers such a prompt / prompt_skill entry behind a preamble that

runs bash scripts/cron-gate.sh --check <name> first and stops when it prints deferred (owner

task-*.txt files are pending in <workspace>/tasks/; peer-tier, cron-runner and classifier

emissions do not count, nor does a task a pool worker holds — a sentinel under

deliveries/<worker>/, read through src/pool_holder.py). A deferred fire is covered by the next

natural tick. The rule lives in src/cron_prompt_gate.py, so a host's crons.json needs no

hand-written wrapper:

minute and hour fields; more than one fire a day (*/30 * * * *, 0 * * * *, 0 9,17 * * *)

means gated. An entry with no cron (a dynamic loop) or one that does not parse as five fields

is gated too, since gating only delays.

at its one fire, the job is gone until its next day — one queued task at briefing time would

lose the briefing (PR #1437).

would rather skip a day than delay an owner reply); "gate": false registers a sub-daily

prompt verbatim.

core is stuck with owner tasks piled up, which is exactly when the gate would silence them.

never gated, whatever gate says — it is the owner-task handler, and gating it deadlocks

the queue.

bash scripts/cron-gate.sh <reason> <command...>, which execs the command or defers) is

registered as is; the helper never wraps twice.

Attaching cron output to an s.space room (if connected)

When the agent is connected to s.space, an output-producing cron can post its results into its own dedicated room instead of a shared channel — one room per cron, so the owner can monitor each stream separately. This is opt-in and connectivity-gated: a cron with no room field, or an agent with no gateway token, is unaffected.

Opt in by adding "room": "auto" to a cron entry in crons.json. On /schedule-crons activation (after step 3), run the helper once:

WS="$(bash scripts/sutando-config.sh workspace)"; H="$(bash scripts/sutando-config.sh host-label)"
OWNER="$(python3 scripts/connections.py list --json \
  | python3 -c 'import json,sys; print(next((r["owner_mxid"] or "" for r in json.load(sys.stdin) if r["primary"]), ""))')"
python3 skills/schedule-crons/ensure-cron-room.py \
  --crons-file "$WS/hosts/$H/crons.json" --owner "$OWNER" --repo .

OWNER is the primary connection row's owner_mxid: the owner's account on the homeserver the agent is on, whichever server that is. When the row has not learned it yet the value is empty; pass the owner's mxid yourself.

ensure-cron-room.py is idempotent: for each "room": "auto" entry it creates one room (Sutando · <cron>), invites the owner, posts a self-identifying first message, and rewrites room to the concrete !id:<server> (the homeserver it was created on). Entries that already hold a !id are skipped — re-running never makes duplicate rooms (the failure mode of ad-hoc creation). If no gateway token resolves, it exits 0 having done nothing. The cron's own prompt then posts output to its room id via the gateway op:message path ([[reference_gateway_op_message_room_post]]).

Which crons opt in: only output-producing crons (pr-shepherd, roadmap-driver, friction-room-sweep, disk-hygiene, ai-frontline-today, morning-briefing). Silent/internal crons (main-loop, sync-memory, briefing-fallback) stay room-less — a room each would be clutter.

Known gateway constraints (2026-07-11), baked into the helper's design:

When to gate (decision rule): applied by step 3's registered_prompt, not by hand.

| Entry | Gated? | Why |

| --- | --- | --- |

| main-loop (/proactive-loop) | NEVER | It is the owner-task handler; gating would deadlock. |

| Sub-daily (*/N, */30, hourly, 0 9,17 * * *) | YES, automatically | A skip is recovered by the next natural tick. |

| Daily / less frequent (X Y * * *, weekdays, weekly, monthly) | NO | A skip loses the function until its next day (PR #1437). |

| No cron (dynamic loop) or an unparseable one | YES | Gating only delays. |

| "gate": true / "gate": false | As set | Overrides the cadence default either way. |

| Health-check / watchdog prompts | NO — set "gate": false | They exist for the stuck-core case, when owner tasks are queued. |

Reliable OS-level crons (`"launchd": true`)

Session CronCreate jobs are best-effort: they only fire while the Claude REPL is idle at the fire minute, carry scheduler jitter (recurring fires up to 10% / max 15min late), and die with the session. On 2026-07-02 the 6:02 loop-engineering digest silently never delivered — the owner asked to "make the schedule reliably run".

For a cron that MUST fire regardless of session state, flag it "launchd": true and install the OS-level runner once:

bash src/install-cron-runner-launchd.sh          # install (idempotent)
bash src/install-cron-runner-launchd.sh --status # check
bash src/install-cron-runner-launchd.sh --uninstall

This installs com.sutando.cron-runner (launchd, every 60s → src/cron-runner.py), which reads the same crons.json, decides which "launchd": true entries are DUE since their last recorded fire, and emits a task file into tasks/ for each. The streaming watcher hands it to the session — same OS-level → emit-task → process pipeline as com.sutando.health-check-fallback. Missed fires (machine asleep/off) catch up exactly once on the next tick, never a backlog storm.

Mechanical shell jobs

A session cron runs its body inside the core's turn, so owner tasks queue

behind it until it finishes. Choose by what the body needs:

with "shell_command". It runs outside the core session entirely.

work to a background subagent instead of running it inline.

Launchd-owned entries may set "shell_command" for work that should not wake a

model session (for example, a polling or sync script):

{
  "name": "sync-workspace",
  "cron": "*/30 * * * *",
  "launchd": true,
  "shell_command": "bash scripts/sync-workspace.sh"
}

src/cron-runner.py starts the command in a detached child from the repository

root and returns without waiting, so a slow job never delays other launchd

crons. The child holds a per-job lock: a fire that lands while the previous run

is still going is skipped and logged. It enforces shell_timeout_s (default

300) by killing the process tree, and appends command, stdout, stderr and exit

code to <workspace>/logs/cron/<name>.log. A shell job runs even when the core

heartbeat is absent and never creates a tasks/ file. A job with something for

the owner writes results/proactive-*.txt itself, as src/morning-briefing.py

does (see "Digest cron delivery" below). If an entry contains

more than one execution form, precedence is shell_command > prompt_skill >

prompt; use only one form in new configuration.

When the selected core runtime is Codex on macOS, src/agent/codex/cli/start-cli.sh performs this installation/reconciliation automatically. Manual installation remains the opt-in path for Claude-core hosts.

Ownership partition (no double-fire): the launchd runner handles ONLY "launchd": true entries; this session skill (step 3) skips those same entries. Exactly one scheduler owns each cron. Leave main-loop / /proactive-loop session-owned (it drives the session itself — it is not a task and must never be launchd-owned).

Digest cron delivery — write one `results/proactive-*.txt`, nothing else

notify.py is for progress pings only (≤280 chars). Digest-style cron prompts that produce research summaries (1000–2000 chars) are silently dropped by notify.py's hard limit — the user sees nothing.

Correct delivery pattern for digest crons — the shared proactive primitive:

DELIVERY: Write the complete digest to results/proactive-<name>-$(date +%s).txt
(and nothing else). Do NOT use notify.py for the final result — it rejects
messages over 280 chars (it is a progress-ping tool, not a delivery channel).

results/proactive-*.txt is the one cross-surface delivery contract — every

configured bridge (Discord, Telegram, Slack) drains it, and proactive_routing.py

routes each file to the channel where the owner was most recently active, exactly

once (atomic .sending claim). That's why it's the primitive to use.

Do NOT write results/briefing-* and do NOT mint a synthetic

tasks/task-cron-* "for Tasks-tab visibility":

poll_dm_fallback) and Telegram (a briefing-as-proactive patch) drain it; **Slack

never delivers it**, so a briefing-* digest is silently archived on a Slack-only

install. proactive-* has no such gap.

results/task-cron-* keyed to that id, so the task never "completes" — the watcher

re-processes it (duplicate/noisy execution) and the task-id-keyed consumers

(Slack/Telegram/agent-api) deliver nothing. Delivery comes from the proactive-*

file alone; you don't need a task file for it.

See crons.example.json for the example-digest entry that shows this pattern. Scripts (like src/morning-briefing.py) already emit results/proactive-*.txt themselves and don't need this — only inline prompt crons that produce long output.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.