42. Autonomy

Why this layer exists

Chapter 41’s gateways make the daemon answer: a post arrives, a turn runs, a reply goes out. Nothing in those chapters makes it act when nobody has typed. Time enters the runtime three ways. A schedule runs a task at its fire times, at 09:00 or every fifteen minutes. A pulse shows that the loop is alive and lets the process say what has changed. And the daemon’s own housekeeping needs a cadence: chapter 35’s Derive, which turns queued messages into facts, and chapter 34’s rotation and snapshot, which chapter 40 ran only at Close. This chapter runs all three through one mechanism, because a mechanism written three times has three sets of failure cases.

Every such run is unattended, and three obligations that earlier chapters opened meet there.

Durability. Chapter 40’s ledger says what a tool call in flight at a crash means, and closes the interrupted turn at the session’s next open. It says nothing about a slot, the scheduled time a run stood for. A daemon that dies mid-run has to come back knowing that the slot was started and not finished, and decide by a policy whether to run it again. The two halves compose without reaching into each other: a run killed mid-turn leaves a session that chapter 40 resolves and a slot that this chapter’s policy decides.

Approval as protocol. Chapter 27’s approver asks a person, and silence is a timeout. A run at 03:00 has no person to ask, so its honest approver answers the timeout at once instead of after the approval timeout, and the loop’s Abort ends the run with every call answered. It aborts and does not allow because oversight degrades with the use of the thing overseen: Mitchell, Ghosh and Passi argue that current agent designs impede effective human oversight and that the cognitive capacities oversight needs are themselves degraded by extended use of AI systems (the abstract of arXiv 2608.23642; this chapter cites the paper for that thesis and for nothing else in it). A daemon that approved its own marked calls at 03:00 would be training its reader to find them approved by morning. A marked call in an unattended run stops the run instead, and the stop becomes a line the reader reads, through the same gate as any other line.

The user model. Chapter 35 holds how the reader wants to be interrupted, in four sentence forms with no model on the path. This chapter enforces it. A deterministic rule decides everything it can: the reader’s quiet window, the daemon’s own notices (a failure, a suspension, a recovery) and one override that belongs to the reader alone, a job marked critical in aecd.json. Chapter 21’s urgency head, through chapter 28’s decide, answers the one question that rule cannot, for a job’s result, whose text a model wrote. Nothing a model writes, no task text and no peer can set the critical marking.

Hermes has the same layers, and again the differences are choices (everything below is at commit cca83848ec79a4a6a2ecc10285725559bf72c97c). A ticker runs every 60 seconds (cron/scheduler_provider.py:439), each due job gets a fresh session named for the job and the second (cron/scheduler.py:2553), and a recurring job’s next_run_at is advanced before dispatch (cron/scheduler_tick.py:140–141, “at-most-once”) so that a crash mid-run “must not re-fire on every restart” (cron/occurrences.py:60–61). That leaves a window in which the occurrence is lost, and a durable pending slot repairs it (cron/occurrences.py:60–69). A job later than its grace, “half the period, clamped to [120s, 2h]” (cron/jobs.py:937–947), either runs once now or, with catch_up_missed set false, is skipped; the default is true (hermes_cli/config_defaults.py:1801; the branch is cron/jobs.py:3126–3136). This book’s scheduler does not tick: it computes the next fire time and waits for it, for at most an hour. A job’s runs share one session. It keeps a state file per job. And it is at-least-once with a bound, where Hermes is at-most-once with a repair. The worry in Hermes’s comment is the same, and the answer here is a limit instead of an avoidance: at most two runs of one scheduled time may die with the process before the slot is recorded as failed, and a job whose last two runs never ended is suspended (below). An orderly stop is another matter: it leaves the slot to the policy and nothing bounds it. The book’s skip is Hermes’s catch_up_missed: false with the same grace, judged one step later (when the run would start, not when it is found due).

A survey of autonomy topics, AI Engineering from Scratch, lists in its Phase 15 “Durable Execution for Long-Running Agents”, “Action Budgets, Iteration Caps, Cost Governors”, “Kill Switches, Circuit Breakers, Canary Tokens”, “HITL: Propose-Then-Commit” and “Checkpoints and Rollback” (lessons 12 to 16 of the README at the commit in Further reading). Four of the five are answered somewhere in the book. Durable execution is chapter 40’s ledger and resume rule plus this chapter’s in_flight: a slot is never lost without a count. Propose-then-commit is chapter 27’s approval protocol as the daemon runs it: a marked call is a proposal, allow commits it, and the unattended approver never commits; chapter 47 decides which calls propose. Checkpoints are the session file’s per-turn appends and compact.json (chapter 40). The cost governors are chapter 26’s MaxTurns and MaxToolCalls, chapter 53’s MaxTokens (a completion cap per request), this chapter’s Job.Timeout, and chapter 49’s accounting. The kill switches are Session.Cancel, daemon/shutdown and chapter 47’s deny, and the circuit breaker is chapter 28’s router, which routes around a provider that fails. Two are left out. Rollback as a general mechanism is absent because a tool’s side effect is not undone by this runtime (chapter 54’s worktree isolation and landing gates are where an agent’s change is kept from landing), and canary tokens because nothing here plants a credential to watch.

Mechanism

A cron line is a set of instants

A job’s schedule is a crontab(5) line, and the scheduler needs one function of it: the first fire time strictly after a given instant. Spec holds the line as five bitsets, one bit per allowed value, and the flags the day rule and the daylight-saving rules need.

// Spec is one crontab(5) line as bitsets: bit m of Minute is minute m, bit
// h of Hour hour h, bit d of Dom day d (1..31), bit m of Month month m
// (1..12), bit w of Dow weekday w (0..6, Sunday 0; 7 is folded onto 0).
// DomStar and DowStar record whether the day fields were "*", which the
// day rule needs: when both are restricted a day matches when EITHER does.
// MinStar and HourStar record whether the minute and hour fields BEGIN with
// "*" ("*", "*/5"; Vixie's MIN_STAR and HR_STAR, entry.c:197-198 and
// :209-210 at 9cc8ab1): a line with either set is a wildcard line, which
// cron does not hold back or hold off when the clock moves (see Next).
// Source is the line as given, after alias expansion.
type Spec struct {
    Minute, Hour, Dom, Month, Dow uint64 // bitsets
    DomStar, DowStar              bool
    MinStar, HourStar             bool
    Source                        string
}

// Wildcard reports a line cron treats as a wildcard line: a "*" at the
// start of the minute or the hour field (@hourly is one; @daily is not).
func (s Spec) Wildcard() bool { return s.MinStar || s.HourStar }

// Aliases are crontab(5)'s @-forms. @reboot is refused: a daemon restart is
// not a boot, and the missed-run rule says what a restart means.
var aliases = map[string]string{
    "@yearly":   "0 0 1 1 *",
    "@annually": "0 0 1 1 *",
    "@monthly":  "0 0 1 * *",
    "@weekly":   "0 0 * * 0",
    "@daily":    "0 0 * * *",
    "@midnight": "0 0 * * *",
    "@hourly":   "0 * * * *",
}

var ErrReboot = errors.New("sched: @reboot is not a schedule; a daemon restart is not a boot (the missed-run rule covers it)")

// MaxLine bounds a line; longer is refused before parsing, so a hostile
// configuration cannot make Parse work on more than this.
const MaxLine = 1024

The grammar is the manual page’s. Ranges are inclusive, a step follows a range or an asterisk, a list mixes numbers and ranges, a name stands alone (crontab(5): “Ranges or lists of names are not allowed”), and 7 is Sunday. Parse refuses what the page allows or ignores and a job cannot use. @reboot is refused because a daemon restart is not a boot, and the missed-run rule below says what a restart means. A sixth field is refused because the page’s sixth field is the command and a job here is a task. The page’s table lists day 0 and month 0, which match no date, so the parser’s ranges start at 1 and Check refuses a line that cannot fire within four years (0 0 31 2 *). A line over 1,024 bytes is refused before it is read, so Parse is one linear pass over bounded input (the package’s test refuses a 12,000-character line within 100 ms).

// Parse reads a five-field crontab(5) line or an @-alias. Each field is a
// comma list of "*", "*/step", "n", "a-b" or "a-b/step"; a month or weekday
// may be a three-letter name standing alone (crontab(5): "Ranges or lists
// of names are not allowed"); ranges are inclusive; day of week 7 is Sunday.
// A sixth field is refused (there is no command: the job is the command).
func Parse(line string) (Spec, error) {
    if len(line) > MaxLine {
        return Spec{}, fmt.Errorf("sched: a cron line is at most %d bytes", MaxLine)
    }
    src := strings.TrimSpace(line)
    if strings.HasPrefix(src, "@") {
        if strings.EqualFold(src, "@reboot") {
            return Spec{}, ErrReboot
        }
        exp, ok := aliases[strings.ToLower(src)]
        if !ok {
            return Spec{}, fmt.Errorf("sched: unknown alias %q", src)
        }
        src = exp
    }
    fields := strings.Fields(src)
    if len(fields) != 5 {
        return Spec{}, fmt.Errorf("sched: a cron line has five fields, this one has %d", len(fields))
    }
    s := Spec{Source: src, MinStar: strings.HasPrefix(fields[0], "*"), HourStar: strings.HasPrefix(fields[1], "*")}
    var err error
    if s.Minute, _, err = parseField(fields[0], 0, 59, nil); err != nil {
        return Spec{}, fmt.Errorf("sched: minute: %w", err)
    }
    if s.Hour, _, err = parseField(fields[1], 0, 23, nil); err != nil {
        return Spec{}, fmt.Errorf("sched: hour: %w", err)
    }
    if s.Dom, s.DomStar, err = parseField(fields[2], 1, 31, nil); err != nil {
        return Spec{}, fmt.Errorf("sched: day of month: %w", err)
    }
    if s.Month, _, err = parseField(fields[3], 1, 12, monthNames); err != nil {
        return Spec{}, fmt.Errorf("sched: month: %w", err)
    }
    if s.Dow, s.DowStar, err = parseField(fields[4], 0, 7, dayNames); err != nil {
        return Spec{}, fmt.Errorf("sched: day of week: %w", err)
    }
    if s.Dow&(1<<7) != 0 { // 7 is Sunday
        s.Dow = (s.Dow &^ (1 << 7)) | 1
    }
    return s, nil
}

The day rule is the page’s, with its own example. “If both fields are restricted (ie, aren’t *), the command will be run when either field matches the current time. For example, 30 4 1,15 * 5 would cause a command to be run at 4:30 am on the 1st and 15th of each month, plus every Friday.” The rule is a function of whether a field is *, not of its bits, since 1-31 is restricted though every bit is set, which is why Spec carries DomStar and DowStar. Vixie’s source says as much: “yes, it’s bizarre. like many bizarre things, it’s the standard” (cron.c:299–304 at commit 9cc8ab1087bb9ab861dd5595c41200683c9f6712). One difference from that source is deliberate. This parser sets a day flag only for a field that is exactly *, reading the page’s “aren’t *” literally, so */2 in the day-of-month field is restricted and 0 0 */2 * 1 means every second day or every Monday. Vixie’s entry.c sets DOM_STAR for any field that begins with * (entry.c:230–231), and cron.c:317–319 then requires both day fields to match, which makes the same line every second day that is a Monday. The minute and hour flags use Vixie’s reading, and the next section says why.

// Matches reports whether t's wall-clock fields, in t's own Location, are
// a fire time of s: minute, hour and month must match, and the day matches
// by crontab(5)'s rule: both day fields "*" is every day; one restricted is
// that one; both restricted is either.
func (s Spec) Matches(t time.Time) bool {
    if s.Minute&(1<<uint(t.Minute())) == 0 || s.Hour&(1<<uint(t.Hour())) == 0 || s.Month&(1<<uint(t.Month())) == 0 {
        return false
    }
    return s.dayMatches(t)
}

func (s Spec) dayMatches(t time.Time) bool {
    dom := s.Dom&(1<<uint(t.Day())) != 0
    dow := s.Dow&(1<<uint(t.Weekday())) != 0
    switch {
    case s.DomStar && s.DowStar:
        return true
    case s.DomStar:
        return dow
    case s.DowStar:
        return dom
    }
    return dom || dow
}

Matches(t) reads t’s wall clock in t’s own Location. Config.Zone is "" for UTC (chapter 40), so a daemon with no zone configured has no daylight-saving time at all and a job at 0 9 * * * fires at 09:00 UTC; the one thing the daemon says about an unset zone is the quiet-window line below.

Next, and the two rules for a clock that moves

Next(t) searches forward from t. A candidate is an instant, the search jumps over instants that cannot match (to the next month, midnight or hour) and steps a minute when it cannot be sure a jump is safe, and each candidate is read back from the wall clock.

// SearchBound is how far Next looks: four years and a day covers every
// five-field spec that fires at all (a February 29 fires within four years).
const SearchBound = 4*365*24*time.Hour + 24*time.Hour

// Next is the first fire time strictly after t, in t's Location, or false
// if none lies within SearchBound. A fire time is an instant whose wall-
// clock fields match the spec, with cron's rules for a zone whose clock
// moves, which apply to fixed-time lines only. cron(8): "Special
// considerations exist when the clock is changed by less than 3 hours, for
// example at the beginning and end of daylight savings time. If the time
// has moved forwards, those jobs which would have run in the time that
// was skipped will be run soon after the change. Conversely, if the time
// has moved backwards by less than 3 hours, those jobs that fall into the
// repeated time will not be re-run. Only jobs that run at a particular
// time (not specified as @hourly, nor with '*' in the hour or minute
// specifier) are affected. Jobs which are specified with wildcards are run
// based on the new time immediately." Vixie's cron.c at 9cc8ab1 does the
// same: the "medium" case runs wildcard jobs for the current minute and
// fixed-time jobs for each minute missed (:195-218), the "negative" case
// "Just run the wildcard jobs. The fixed-time jobs probably have already
// run, and should not be repeated" (:224-236), and a job is a wildcard job
// when MIN_STAR or HR_STAR is set (:322-324).
//
// So for a fixed-time line (neither MinStar nor HourStar): a wall time
// inside a spring-forward gap runs once, at the first instant after the
// gap (03:00 PDT for a 02:30 job on 2026-03-08 in Los Angeles), and a wall
// time that occurs twice fires at its first occurrence only. For a
// wildcard line the wall clock is simply read: `* * * * *` has no gap of
// silence and `5 * * * *` no extra run at the end of a gap, and the
// repeated hour fires on both passes. Not modelled: cron's three-hour
// bound (a shift of three hours or more is a correction there).
//
// The search jumps by real time (to the next month, midnight or hour) and
// accepts a jump only if it stays inside the current zone period and reads
// the wall clock it asked for; otherwise it steps one minute, so a gap is
// always crossed minute by minute and seen, and a time.Date call is never
// asked for an ambiguous wall time (it answers the first occurrence west of
// Greenwich and the second east of it).
func (s Spec) Next(t time.Time) (time.Time, bool) {
    fixed := !s.Wildcard()
    prev := t.Truncate(time.Minute)
    c := prev.Add(time.Minute)
    limit := t.Add(SearchBound)
    for c.Before(limit) {
        if fixed {
            // The wall clock moved by more than the minutes of real time
            // between prev and c: the minutes between did not exist on this
            // day. cron's rule: a job at a skipped wall time runs once, at c.
            if n := skippedMinutes(prev, c); n > 0 {
                for k := 1; k <= n; k++ {
                    if s.Matches(wallPlus(prev, k)) {
                        return c, true
                    }
                }
            }
        }
        if s.Matches(c) && !(fixed && repeated(c)) {
            return c, true
        }
        prev, c = c, s.jump(c)
    }
    return time.Time{}, false
}

// Never reports a line that cannot fire within SearchBound (31 February):
// Check refuses it.
func (s Spec) Never() bool {
    _, ok := s.Next(time.Date(2001, 1, 1, 0, 0, 0, 0, time.UTC))
    return !ok
}

// jump is the next candidate after c: the first of the next month when the
// month does not match, the next midnight when the day does not, the next
// hour when the hour does not, else the next minute. A jump is a real-time
// step to a wall time computed in UTC arithmetic (no ambiguity), and is
// refused (the next smaller jump, at last one minute) if it would leave c's
// zone period or not read the wall clock it asked for.
func (s Spec) jump(c time.Time) time.Time {
    y, m, d := c.Date()
    h := c.Hour()
    var targets []time.Time
    switch {
    case s.Month&(1<<uint(m)) == 0:
        targets = []time.Time{time.Date(y, m+1, 1, 0, 0, 0, 0, time.UTC), time.Date(y, m, d+1, 0, 0, 0, 0, time.UTC), time.Date(y, m, d, h+1, 0, 0, 0, time.UTC)}
    case !s.dayMatches(c):
        targets = []time.Time{time.Date(y, m, d+1, 0, 0, 0, 0, time.UTC), time.Date(y, m, d, h+1, 0, 0, 0, time.UTC)}
    case s.Hour&(1<<uint(h)) == 0:
        targets = []time.Time{time.Date(y, m, d, h+1, 0, 0, 0, time.UTC)}
    }
    for _, w := range targets {
        delta := time.Duration(w.Unix()/60-wallMinute(c)) * time.Minute
        if delta <= 0 {
            continue
        }
        j := c.Add(delta)
        if _, end := c.ZoneBounds(); !end.IsZero() && !j.Before(end) {
            continue // a transition lies in the way
        }
        if wallMinute(j) != w.Unix()/60 {
            continue
        }
        return j
    }
    return c.Add(time.Minute)
}

// wallMinute is a time's wall-clock reading as a count of minutes, zone
// ignored: two readings differ by the minutes a clock shows between them.
func wallMinute(t time.Time) int64 {
    return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), 0, 0, time.UTC).Unix() / 60
}

// skippedMinutes is how many wall-clock minutes lie strictly between prev
// and c that the clock never showed: the wall clock advanced by more than
// the minutes of real time between them (60 across a one-hour spring-
// forward gap), else 0 (a fall back is negative, clamped).
func skippedMinutes(prev, c time.Time) int {
    n := wallMinute(c) - wallMinute(prev) - int64(c.Sub(prev)/time.Minute)
    if n < 0 {
        return 0
    }
    return int(n)
}

// wallPlus is the wall-clock reading k minutes after t, as a UTC time
// whose fields are that reading (a skipped minute has no instant in t's
// zone, so Matches reads it this way).
func wallPlus(t time.Time, k int) time.Time {
    return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute()+k, 0, 0, time.UTC)
}

// repeated reports whether c is the second occurrence of its wall-clock
// time. If the zone period c is in began at start with the offset dropping
// from prev to cur (a fall back of prev-cur seconds), the instants of
// [start, start+(prev-cur)) show wall clocks the previous period already
// showed. Exact for any shift (30 minutes at Lord Howe, two hours at
// Troll).
func repeated(c time.Time) bool {
    start, _ := c.ZoneBounds()
    if start.IsZero() {
        return false
    }
    _, cur := c.Zone()
    _, prev := start.Add(-time.Second).Zone()
    return prev > cur && c.Sub(start) < time.Duration(prev-cur)*time.Second
}

A jump is a real-time step computed in UTC arithmetic, so no wall time in it is ambiguous. jump accepts one only if it stays inside the current zone period (ZoneBounds) and lands on the wall minute it asked for; a transition in the way, or a landing on another wall time, replaces the jump by a single minute. A gap or a fold is therefore always crossed one minute at a time, and seen.

What a firing rule must say about those minutes is cron’s, and cron’s is written down twice. The manual page, cron(8) (the comment on Next above carries the same paragraph):

Special considerations exist when the clock is changed by less than 3 hours, for example at the beginning and end of daylight savings time. If the time has moved forwards, those jobs which would have run in the time that was skipped will be run soon after the change. Conversely, if the time has moved backwards by less than 3 hours, those jobs that fall into the repeated time will not be re-run.

Only jobs that run at a particular time (not specified as @hourly, nor with ‘*’ in the hour or minute specifier) are affected. Jobs which are specified with wildcards are run based on the new time immediately.

And Vixie’s cron.c at the same commit, in the case for a small forward step (:195–222): “run wildcard jobs once, then run any fixed-time jobs that would otherwise be skipped”, a loop that visits each skipped minute and runs the fixed-time jobs for it; in the case for a small backward step (:224–236): “Just run the wildcard jobs. The fixed-time jobs probably have already run, and should not be repeated”; and the test that tells the two kinds of job apart (:321–324) is whether MIN_STAR or HR_STAR is set, which entry.c sets when the minute field, or the hour field, begins with * (:197–198 and :209–210). That is why MinStar and HourStar are begins with flags and the day flags are not.

Next implements both rules for fixed-time lines. Forward. If c follows prev by one minute of real time and by more on the wall clock, the minutes between never showed on this clock (skippedMinutes); each is read as a wall time (wallPlus) and tested against the spec, and a match fires once, at c, the first instant after the gap. 30 2 * * * on 2026-03-08 in Los Angeles fires at 03:00 PDT. The trace, replayed from Next’s loop in a scratch copy of the package on wntrmute: from 00:00 PST the candidate 00:01 fails the hour, and a jump to the hour is accepted and lands on 01:00; the jump from 01:00 to a wall 02:00 would land on the transition itself, so it is refused and the search steps a minute at a time through 01:59 PST, 60 candidates in all; the next candidate is 03:00 PDT, skippedMinutes is 60, the wall minute 02:30 is one of them and matches, and the answer is 03:00 PDT. Where Vixie’s loop visits the skipped minutes and queues the job once for each that matches, so that as this chapter reads it a line matching two of them is run twice (the queue is run between minutes, :214–215), a set of instants has one 03:00, and 0,30 2 * * * fires once. Backward. A wall time that occurs twice fires at its first occurrence only (repeated: the instant is inside the first prev − cur seconds of a zone period whose offset dropped by that much, so the check is exact for a 30-minute shift at Lord Howe or a two-hour one at Troll). 30 1 * * * on 2026-11-01 fires at 01:30 PDT and not again at 01:30 PST an hour later; its next fire is Nov 2 01:30 PST. A change of more than 3 hours is, for cron(8), one of the “corrections to the clock”, and the new time is used immediately; Next computes instants, not ticks, so it has no such case, and what a daemon that was down does is the missed-run rule’s.

Wildcard lines are exempt, as the page says, and the wall clock is simply read: * * * * * has no gap of silence, 5 * * * * has no extra run at the end of a gap, and the repeated hour fires on both passes. The first draft of this scheduler applied both rules to every line, and the review that read it found the cost: the heartbeat, a wildcard line, went silent for an hour once a year, and 5 * * * * got an extra run at the end of the gap. The output below pins the rule.

The next fire times across the 2026 transitions are printed by TestPrintMissedTable (wntrmute, 2026-10-12; straylight’s run printed the same lines, which says the program and the tzdata agree and is not a measurement):

spec           from               next fire times
30 2 * * *     2026-03-08 00:00 PST Mar 8 03:00 PDT, Mar 9 02:30 PDT, Mar 10 02:30 PDT
*/30 * * * *   2026-03-08 01:00 PST Mar 8 01:30 PST, Mar 8 03:00 PDT, Mar 8 03:30 PDT
30 1 * * *     2026-11-01 00:00 PDT Nov 1 01:30 PDT, Nov 2 01:30 PST, Nov 3 01:30 PST
*/30 * * * *   2026-11-01 00:30 PDT Nov 1 01:00 PDT, Nov 1 01:30 PDT, Nov 1 01:00 PST
0 * * * *      2026-11-01 00:30 PDT Nov 1 01:00 PDT, Nov 1 01:00 PST, Nov 1 02:00 PST

Rows 2, 4 and 5 are wildcard lines: */30 goes 01:30 PST, 03:00 PDT (the wall clock has no 02:00 or 02:30 to read) and reads 01:00 twice on the fall-back morning; 0 * * * * fires at both 01:00s. Rows 1 and 3 are fixed-time lines, and the first-occurrence and gap rules show in them.

The rule has a consequence a reader can trip on, because “begins with *” is a property of the text. The five lines below were run through Next over the whole local day of a transition, on wntrmute, by a throwaway test (the lab’s TestNextDST pins the first fire times of each):

Line Day (Los Angeles) Fires Times
*/30 1 * * * 2026-11-01 4 01:00 PDT, 01:30 PDT, 01:00 PST, 01:30 PST
0-59/30 1 * * * 2026-11-01 2 01:00 PDT, 01:30 PDT
*/30 2 * * * 2026-03-08 0 none: 02:00 and 02:30 do not exist and a wildcard line is not held over
0,30 2 * * * 2026-03-08 1 03:00 PDT
30 2 * * * 2026-03-08 1 03:00 PDT

*/30 and 0-59/30 name the same minutes. One is a wildcard line and the other is not, because the minute field of one begins with *; the first runs four times on the fall-back day and the second twice, and one skips the spring-forward day while the other does not. That is cron’s rule, kept, and a reader who has a job that must run once a day writes a fixed time.

A rule that depends on the zone, and the way it hid

The first version of this code computed fire times in the zone of the persisted last-check time. A state file read back does not carry the configured zone: Go’s time parser keeps the host’s Local when the offset matches the host’s zone at that instant and invents a fixed-offset zone otherwise. After one round trip through the state file the fire times were therefore read in whichever zone the host was in, and not in the zone aecd.json names. A daemon configured for Los Angeles on a host set to UTC would have fired an hour late for half the year and never applied a daylight-saving rule at all. Every gate passed. Both machines that ran them, wntrmute and straylight, are in Pacific time (date +%Z prints PDT on both), so the configured zone and the host’s zone were the same zone, and the bug could not show. The independent review found it by running the tests under TZ=UTC.

Two things catch it now, and both are about the test’s design more than the fix. Due computes fire times in now’s Location, never the persisted time’s, and says so in its comment. And the tests that touch a zone set the machine’s own zone, time.Local, to a zone that is not the clock’s: the lab’s eachHostZone runs TestMissedAcrossDST with the host in UTC, Tokyo, Los Angeles and Berlin, and the package tests pass under TZ=UTC, TZ=Asia/Tokyo and TZ=Europe/London. The oracle, TestOracle, never asks time.Date for a wall time in a zone that has transitions (it calls it in UTC only). A generator builds each of the 150 random lines as five sets and renders the text, so Parse is checked against those sets; the 18 chosen lines are parsed by Parse itself and test Next alone. A table of the wall-clock reading of every minute of 2026 to 2031 in a zone gives the fire rule directly (a fixed-time line fires at the first instant of a matching wall minute not shown before, and at the first instant after a gap that skipped one; a wildcard line at every matching minute). It shares one helper with the code under test, wallMinute. It compares Next from random start times in 2026 and from times around that year’s transitions; the table holds twelve transitions per zone, which a long search can reach. The reviewer who found the bug wrote it, and it was ported into the package as a test. On wntrmute it ran 168 specs (150 random, 18 chosen) and 5,327 comparisons in seven zones (UTC, Los Angeles, Lord Howe, Havana, Santiago, London and Troll; twelve transitions in each but UTC) in 8.63 s, with no disagreement; on straylight the same counts in 5.39 s. What it shows is that Next implements the rule the oracle encodes, which is the rule as this chapter reads cron(8) and Vixie. No cron binary was run against it.

The missed set and the recurrence

The missed set and what each policy runs A time line runs left to right with the fire times of a */15 job as ticks every 15 minutes from 10:00 to 12:00. L, the newest accounted slot, is marked at 10:00 and N, now, at 11:52; the ticks strictly after L and up to N are the missed set M, bracketed above the line, seven of them. A second bracket below the line shows that N is 7 minutes after the newest slot, inside the grace of 7.5 minutes. Below, three rows show what each policy runs at N. skip runs once for the newest slot because it is on time, and the six older slots are dropped and counted. catch_up_one runs once for the newest and folds the six older slots into that run. catch_up_all runs once per slot, oldest first. A footer says L moves to a slot only after its run ends, and that a slot whose run died is offered to the policy once more, and a second death records it as failed. 10:00 11:00 12:00 L newest accounted slot N now M = fire times in (L, N], seven of them N is 7 minutes after the newest slot; the grace of a */15 job is 7.5 skip one run, six dropped and counted; had the newest been late, none would run catch_up_one one run for the newest, however late; the six older slots are named to the task catch_up_all seven runs, oldest first; past MaxCatchUp the oldest are dropped and counted L moves to a slot only after its run ends, and past dropped slots in the write that counts them a slot whose run died is offered to the policy once more; a second death records it as failed

Write FF for a spec’s fire times, LL for the job’s newest accounted time (State.Last: the slot a run for which ended, or the newest slot dropped and counted; a job seen for the first time gets L=NL = N, so it has nothing due) and NN for now. The missed set is

M={t∈F:L<t≤N}. M = \{\, t \in F : L < t \le N \,\}.

A timer that wakes at a fire time finds MM holding that one slot. A daemon that was down, a host that was suspended and a job that was still running at the last fire time find more, and what a job does about them is its policy. Each policy runs at most once per element of MM.

  • skip runs nothing for a missed slot, which is cron’s own behaviour. The newest element of MM runs only if it is on time: no later than the job’s grace after its fire time. A late newest element and every older element are dropped and counted in State.Dropped. Lateness is judged when the check finds the slot and again when the run would start, because a run that waited for a run slot behind a long one is late by what it waited.
  • catch_up_one runs once, standing for the newest element however late it is, and the older elements are folded into that run: the task text gains “This run also stands for the N scheduled runs that were missed” and the first and last three times (Due.Describe, bounded however long the outage was). This is systemd.timer(5)’s Persistent=true: “the service unit is triggered immediately if it would have been triggered at least once during the time when the timer was inactive” (the page on wntrmute, systemd 261).
  • catch_up_all runs once per element, oldest first, for a task that carries its scheduled time (a report for each hour that passed). The newest MaxCatchUp elements run (24 when the job does not say) and the rest are dropped and counted.
// plan turns M into Dues under the job's policy, with how many slots it
// dropped (a prefix of M) and the newest of them (zero: none).
func (s *Scheduler) plan(j Job, now time.Time, m []time.Time) (dues []Due, dropped int, lastDropped time.Time) {
    newest := m[len(m)-1]
    older := m[:len(m)-1]
    switch j.Policy {
    case CatchUpOne:
        d := Due{Job: j, At: now, Scheduled: newest}
        if len(older) > 0 {
            d.Folded = append([]time.Time(nil), older...)
        }
        s.logf("job %s: due for %s, folding %d missed", j.Name, newest.Format(time.RFC3339), len(older))
        return []Due{d}, 0, time.Time{}
    case CatchUpAll:
        max := j.MaxCatchUp
        if max <= 0 {
            max = DefaultMaxCatchUp
        }
        if len(m) > max {
            dropped = len(m) - max
            lastDropped = m[dropped-1]
            m = m[dropped:]
        }
        for _, t := range m {
            dues = append(dues, Due{Job: j, At: now, Scheduled: t})
        }
        dues[len(dues)-1].Dropped = dropped
        s.logf("job %s: %d due, oldest %s, %d dropped", j.Name, len(m), m[0].Format(time.RFC3339), dropped)
        return dues, dropped, lastDropped
    default: // Skip: the newest slot runs only when it is on time.
        late := now.Sub(newest)
        if g := s.grace(s.specs[j.Name], newest); late > g {
            s.logf("job %s: %d missed dropped; the newest, %s, is %s late (grace %s)", j.Name, len(m), newest.Format(time.RFC3339), late, g)
            return nil, len(m), newest
        }
        s.logf("job %s: due for %s, %d missed dropped", j.Name, newest.Format(time.RFC3339), len(older))
        if len(older) > 0 {
            lastDropped = older[len(older)-1]
        }
        return []Due{{Job: j, At: now, Scheduled: newest, Dropped: len(older)}}, len(older), lastDropped
    }
}

The grace is half the job’s period, measured from the slot to the next fire time and clamped to two minutes at the bottom and two hours at the top: Hermes’s numbers, since the question is the same one. A scheduler that wakes on a timer finds its slot microseconds late, and a loaded host or a previous run of the same job can make that minutes, so “missed” has to be a bound a reader can state. The floor keeps a minutely job from dropping a slot a busy host merely delayed. The ceiling keeps a weekly job that comes up three days late from counting as on time. Scheduler.Grace replaces the function, and the lab tests that the scheduler’s own is the one consulted.

// DefaultGrace is how late a slot may be and still count as on time
// under Skip: half the job's period, clamped to [MinGrace, MaxGrace] (the
// numbers Hermes's scheduler uses for the same purpose, Facts), so a daily
// job that comes up two hours late still runs and a minutely one does not
// run a slot from ten minutes ago.
func DefaultGrace(period time.Duration) time.Duration {
    g := period / 2
    if g < MinGrace {
        g = MinGrace
    }
    if g > MaxGrace {
        g = MaxGrace
    }
    return g
}

const (
    MinGrace = 2 * time.Minute
    MaxGrace = 2 * time.Hour
)

How many elements MM has, for */15. Write L=t0+φL = t_0 + \varphi with t0∈Ft_0 \in F and 0≤φ<150 \le \varphi < 15 minutes, and N=L+gN = L + g. The fire times after t0t_0 are t0+15jt_0 + 15j for j≥1j \ge 1. Then t0+15j∈Mt_0 + 15j \in M exactly when φ<15j≤φ+g\varphi < 15j \le \varphi + g. The left inequality holds for every j≥1j \ge 1 because φ<15\varphi < 15, and fails for j=0j = 0. The right one is j≤(φ+g)/15j \le (\varphi + g)/15. So

∣M∣=⌊g+φ15⌋, |M| = \left\lfloor \frac{g + \varphi}{15} \right\rfloor,

which is ⌊g/15⌋\lfloor g/15 \rfloor or ⌊g/15⌋+1\lfloor g/15 \rfloor + 1 depending on whether the phase φ\varphi carries the remainder of gg over the next fire time. missed computes MM by calling Next from LL until a fire time passes NN (keeping the newest MaxMissed = 100,000 and counting the rest as dropped, so a * * * * * job after a long outage costs a bounded amount):

// missed is M for one job: the fire times in (last, now], oldest first. If
// there are more than MaxMissed, the newest MaxMissed are returned, lost is
// how many older ones were left out (counted while walking, at most
// MaxWalk fire times in all) and lastLost is the newest of those.
func missed(sp Spec, last, now time.Time) (m []time.Time, lost int, lastLost time.Time) {
    t := last
    for walked := 0; walked < MaxWalk; walked++ {
        n, ok := sp.Next(t)
        if !ok || n.After(now) {
            break
        }
        m = append(m, n)
        t = n
        if len(m) == 2*MaxMissed {
            lost += MaxMissed
            lastLost = m[MaxMissed-1]
            m = append(m[:0], m[MaxMissed:]...)
        }
    }
    if len(m) > MaxMissed {
        k := len(m) - MaxMissed
        lost += k
        lastLost = m[k-1]
        m = m[k:]
    }
    return m, lost, lastLost
}

TestPrintMissedTable prints ∣M∣|M| and what each policy does for a gap gg after LL = 10:00 (φ=0\varphi = 0) and after LL = 10:07 (φ=7\varphi = 7), wntrmute, 2026-10-12 (straylight’s run printed the same rows):

L      gap   |M|  skip                   catch_up_one           catch_up_all
10:00  0     0    -                      -                      -
10:00  1     0    -                      -                      -
10:00  14    0    -                      -                      -
10:00  15    1    run 10:15, drop 0      run 10:15, fold 0      run 10:15 .. 10:15 (1)
10:00  16    1    run 10:15, drop 0      run 10:15, fold 0      run 10:15 .. 10:15 (1)
10:00  23    1    late: drop 1           run 10:15, fold 0      run 10:15 .. 10:15 (1)
10:00  180   12   run 13:00, drop 11     run 13:00, fold 11     run 10:15 .. 13:00 (12)
10:07  0     0    -                      -                      -
10:07  1     0    -                      -                      -
10:07  14    1    run 10:15, drop 0      run 10:15, fold 0      run 10:15 .. 10:15 (1)
10:07  15    1    run 10:15, drop 0      run 10:15, fold 0      run 10:15 .. 10:15 (1)
10:07  16    1    late: drop 1           run 10:15, fold 0      run 10:15 .. 10:15 (1)
10:07  23    2    run 10:30, drop 1      run 10:30, fold 1      run 10:15 .. 10:30 (2)
10:07  180   12   run 13:00, drop 11     run 13:00, fold 11     run 10:15 .. 13:00 (12)

The formula’s rows: at φ=0\varphi = 0, g=14g = 14 gives 0 and g=180g = 180 gives 12; at φ=7\varphi = 7, g=14g = 14 gives ⌊21/15⌋=1\lfloor 21/15 \rfloor = 1 and g=23g = 23 gives ⌊30/15⌋=2\lfloor 30/15 \rfloor = 2, where the same gap from 10:00 gives one. The two late rows are the same case twice. At 10:23 the newest slot, 10:15, is 8 minutes late against a grace of 7.5, so skip runs nothing and counts it, while the other two policies run it. The row for a gap of 23 from 10:07 reaches 10:30, which is on time, and skip runs it and drops 10:15. The 180-minute rows ask for 12 runs of catch_up_all, under the default cap of 24; with max_catch_up: 5 the newest five, 12:00 to 13:00, would run and seven would be dropped and counted.

The recurrence, and what it guarantees. A check at time NiN_i computes Mi=F∩(Li,Ni]M_i = F \cap (L_i, N_i] and deals with every element of it: runs it, folds it or drops it. Then

Li+1={maxMiMi≠∅LiMi=∅ L_{i+1} = \begin{cases} \max M_i & M_i \ne \varnothing \\ L_i & M_i = \varnothing \end{cases}

with the clock never going backwards, Ni≤Ni+1N_i \le N_{i+1} (a clock that steps back makes the job wait, as the end of this section says). The claim: every fire time in (L0,Nn](L_0, N_n] lies in exactly one MiM_i. First, F∩(Li+1,Ni]=∅F \cap (L_{i+1}, N_i] = \varnothing: if MiM_i is not empty, a fire time above maxMi\max M_i and at most NiN_i would be an element of MiM_i; if it is empty, there is no fire time in (Li,Ni](L_i, N_i] at all. Both cases give Li+1≤NiL_{i+1} \le N_i (since maxMi≤Ni\max M_i \le N_i, and L0≤N0L_0 \le N_0 by first sight), which is what splits (Li+1,Ni+1](L_{i+1}, N_{i+1}] at NiN_i. Therefore

Mi+1=F∩(Li+1,Ni+1]=F∩(Ni,Ni+1], M_{i+1} = F \cap (L_{i+1}, N_{i+1}] = F \cap (N_i, N_{i+1}],

and the windows (Ni−1,Ni](N_{i-1}, N_i] partition (L0,Nn](L_0, N_n], with M0=F∩(L0,N0]M_0 = F \cap (L_0, N_0] the first of them. Hence under catch_up_all with no cap every fire time gets exactly one run, and under every policy it is accounted for exactly once, as run for, folded or dropped: no policy counts a slot twice or loses one without a count. State.Dropped is the exact count (apart from the bounded walk, whose count is “at least”), so a lost slot is always a reported one, and aecd jobs prints it. A run on request stands for no slot and moves LL nowhere. The proof assumes each write lands. What a kill does to it is the next section.

Two things the recurrence does not say. LL is not the time of the last check: a check that finds nothing writes nothing, which is why a job’s first sight writes L=NL = N and why the phase φ\varphi above exists. And a clock that steps back changes nothing silently. A state whose LL is ahead of the clock by under an hour (MaxClockSkew) makes the job wait and logs it once; by more than an hour the job restarts from now, keeping its counts, because a clock that was a year ahead must not silence a job for a year.

A slot in flight

The recurrence moves LL to a slot after its run ended. A daemon can die between any two instructions, so the state file has to say, before the run starts, that a slot is in flight. State is the per-job file Dir/jobs/<name>.json:

// Due is one run the rule asks for: At is the check time N; Scheduled the
// fire time the run stands for (N itself for a Manual run, one the reader
// triggered); Folded the older missed times this run also stands for
// (CatchUpOne); Dropped how many missed times no run will stand for (Skip,
// or CatchUpAll past MaxCatchUp; on the last Due of a job's batch).
type Due struct {
    Job       Job
    At        time.Time
    Scheduled time.Time
    Folded    []time.Time
    Dropped   int
    Manual    bool
}

// State is the per-job file, Dir/<name>.json. Last is L: the newest slot
// accounted for (a run for it ended, or it was dropped and counted); LastRun
// the start of the last run and LastStop how it ended. InFlight is the slot
// a run started for and has not been recorded as ended, written before the
// run starts and cleared after, with Attempts counting how many times a
// run was started for it: a daemon that comes up with InFlight set knows a
// run died with the process and offers the slot once more; when that
// run also dies (Attempts is 2) the slot is recorded as failed (Failed,
// LastStop "abandoned") and never offered again: the bound is per scheduled
// time. A run stopped by an orderly shutdown leaves its slot in flight and
// takes its attempt back, so the policy decides whether it runs again and
// the stop counts toward neither bound; Stops counts those stops for the
// slot in flight (cleared by a run that ends, and when the slot is dropped,
// abandoned or replaced by a newer one), and each re-run after a stop is
// warned of with the count, nothing more. Manual is the instant of a run
// on request (Trigger) that has not ended: a record of its own, so a run
// on request never overwrites a slot's InFlight and Attempts, and one that
// died stands for no slot. Crashes counts the runs of the job, scheduled or
// on request, that were started and never ended (the process died with
// them), consecutively: a run that ends, with any stop reason, sets it to
// 0; at MaxCrashes the job is Suspended, which only a run on request that
// ends, or any change to the job's entry in aecd.json (Entry is a digest of
// the decoded job; a changed cron line also starts the job from now), clears.
// A clock step does not. Dropped counts the slots no run ever stood for, once
// each; Cron is the line the state was written under (a changed line starts
// the job from now, keeping Dropped and Failed). Untold holds the
// suspension and abandonment notices raised and not yet handed to the
// notifier: a start that finds one raises it again, so a notice is told at
// least once, not exactly once. ToldKinds, Suppressed and Streak belong to
// the daemon's failure notices: ToldKinds holds, for each kind of failure
// told, the scheduled time of the run at which it was last told (a run on
// request uses its start time); Suppressed how many failures since were not
// repeated; Streak how many runs have failed since the last one that ended
// final, told or not, of any kind. A restart from now keeps all three; a
// changed entry in aecd.json (a changed cron line included) and a run on
// request clear ToldKinds and Suppressed (not Streak), so the reader's own
// next attempt is told. Told and ToldAt are the keys of an earlier version
// (one kind and when it was told): they are read as one entry of ToldKinds
// and never written.
type State struct {
    Last       time.Time            `json:"last"`
    LastRun    *time.Time           `json:"last_run,omitempty"`
    LastStop   string               `json:"last_stop,omitempty"`
    InFlight   *time.Time           `json:"in_flight,omitempty"`
    Attempts   int                  `json:"attempts,omitempty"`
    Stops      int                  `json:"stops,omitempty"`
    Manual     *time.Time           `json:"manual,omitempty"`
    Crashes    int                  `json:"crashes,omitempty"`
    Suspended  bool                 `json:"suspended,omitempty"`
    Dropped    int                  `json:"dropped,omitempty"`
    Failed     int                  `json:"failed,omitempty"`
    Cron       string               `json:"cron,omitempty"`
    Entry      string               `json:"entry,omitempty"`
    Untold     []Untold             `json:"untold,omitempty"`
    ToldKinds  map[string]time.Time `json:"told_kinds,omitempty"`
    Told       string               `json:"told,omitempty"`   // read only: an earlier version's kind last told
    ToldAt     time.Time            `json:"told_at,omitzero"` // read only: when it was told
    Suppressed int                  `json:"suppressed,omitempty"`
    Streak     int                  `json:"streak,omitempty"`
}

// Untold is a notice raised and not yet told: Kind "suspended" (Attempts is
// the crash count) or "abandoned" (Slot is the slot recorded as failed).
type Untold struct {
    Kind     string    `json:"kind"`
    Slot     time.Time `json:"slot,omitzero"`
    Attempts int       `json:"attempts"`
}

// MaxAttempts is how many runs started for one scheduled time may die with
// the process before the slot is recorded as failed: the run and one re-run
// after a crash. A start that an orderly stop took back is not counted, so
// orderly stops restart a slot without bound.
const MaxAttempts = 2

// MaxCrashes is how many consecutive runs of one job may be started and
// never end before the job is suspended.
const MaxCrashes = 2

// RetryAfterWriteFailure is how long a job whose pre-run state write failed
// is left alone before its slot is offered again.
const RetryAfterWriteFailure = time.Minute

The procedure is four steps, and a kill can fall in each gap.

  1. The check. Due is the scheduler’s own step and not a query (LoadState, NextFor and Quarantined are the queries). Per job it reads the state (a file that cannot be read, holds a negative counter or an untold record of a kind this code does not write, quarantines that job alone: the file is left for the reader and the other jobs go on); clears a run on request that died; starts the job from now on first sight, on a changed cron line and when the clock is more than an hour behind LL; clears a suspension when the job’s entry has changed; suspends a job whose Crashes has reached 2; abandons a slot whose attempts has reached 2; raises every notice recorded in Untold; and only then serves a pending trigger or plans MM. A slot it drops it counts, and moves LL past it, in one write. LL never passes a slot the check hands out.
func (s *Scheduler) dueJob(j Job, st State, now time.Time, loc *time.Location) (dues []Due, triggered bool, err error) {
    dirty := false
    entry := s.entries[j.Name]
    if st.Manual != nil {
        s.logf("job %s: a run on request (%s) died with the process; it stood for no slot", j.Name, st.Manual.Format(time.RFC3339))
        st.Manual, dirty = nil, true
    }
    // restart starts the job from now, keeping Dropped, Failed, the daemon's
    // failure-notice bookkeeping (ToldKinds, Suppressed, Streak) and the
    // notices not yet told. A changed cron line is a changed entry: it clears
    // the suspension and what was told (keep false), so the reader's next
    // attempt is told; a clock step does neither (keep true).
    restart := func(keep bool) {
        n := State{Last: now, Cron: j.Cron, Entry: entry, Dropped: st.Dropped, Failed: st.Failed, Streak: st.Streak}
        if keep {
            n.ToldKinds, n.Suppressed = st.ToldKinds, st.Suppressed
        }
        for _, u := range st.Untold {
            if u.Kind != "suspended" || keep {
                n.Untold = append(n.Untold, u)
            }
        }
        if keep {
            n.Crashes, n.Suspended = st.Crashes, st.Suspended
        }
        st = n
        dirty = true
    }
    waiting := false
    switch {
    case st.Last.IsZero():
        s.logf("job %s: first seen; nothing missed", j.Name)
        st.Last, st.Cron, st.Entry, dirty = now, j.Cron, entry, true
    case s.lineChanged(j, st):
        s.logf("job %s: the cron line changed (%q to %q); it starts from now", j.Name, st.Cron, j.Cron)
        restart(false)
    case st.Last.After(now):
        if st.Last.Sub(now) > MaxClockSkew {
            s.logf("job %s: Last (%s) is more than %s ahead of the clock (%s); it starts from now", j.Name, st.Last.Format(time.RFC3339), MaxClockSkew, now.Format(time.RFC3339))
            restart(true)
        } else {
            if !s.behind[j.Name] {
                s.behind[j.Name] = true
                s.logf("job %s: the clock (%s) is behind Last (%s); nothing is due until it passes", j.Name, now.Format(time.RFC3339), st.Last.Format(time.RFC3339))
            }
            waiting = true
        }
    }
    if !waiting {
        delete(s.behind, j.Name)
    }
    if st.Entry != entry {
        // Any change to the job's entry in aecd.json (not only the cron line)
        // clears a suspension, the crash count and what was told of a failure
        // (so the reader's next attempt is told). A state with no digest was
        // written before the digest existed: it adopts the entry as it is and
        // clears nothing.
        if st.Entry != "" {
            if st.Suspended || st.Crashes > 0 {
                s.logf("job %s: its entry in aecd.json changed; the crash count and any suspension are cleared", j.Name)
                if st.Suspended {
                    s.warnf("job %s: its entry in aecd.json changed; the suspension is cleared and the job runs again", j.Name)
                }
                st.Suspended, st.Crashes = false, 0
                st.Untold = withoutKind(st.Untold, "suspended")
            }
            st.ToldKinds, st.Suppressed = nil, 0
        }
        st.Entry, dirty = entry, true
    }
    suspended, suspendedNow := false, false
    if !waiting {
        switch {
        case st.Suspended || st.Crashes >= MaxCrashes:
            suspended = true
            if !st.Suspended {
                st.Suspended, dirty = true, true
                st.Untold = append(st.Untold, Untold{Kind: "suspended", Attempts: st.Crashes})
                suspendedNow = true
            }
        case st.InFlight != nil && !st.InFlight.After(now) && st.Attempts >= MaxAttempts:
            s.abandon(j, &st, st.InFlight.In(loc), st.Last.In(loc))
            dirty = true
        }
    }
    if dirty {
        if err := s.SaveState(j.Name, st); err != nil {
            return nil, false, err
        }
    }
    if suspendedNow {
        // After the save, never before: a reader that waits for this line and
        // then asks for the state (aecd jobs) must find the job suspended, and
        // a save that fails must not leave a line saying it is.
        s.warnf("job %s: its last %d runs were started and never ended (the process died in each); the job is suspended: no slot of it starts until a run on request ends (aecd jobs -run %s) or its entry in aecd.json changes", j.Name, st.Crashes, j.Name)
    }
    // A notice raised and not yet handed to the notifier is raised again at
    // every start that finds it (tellReports clears it once told).
    // A check that fails later (another job's state could not be written)
    // leaves these in s.reports; the next check finds the same records, so a
    // report already waiting is not added twice.
    for _, u := range st.Untold {
        s.addReport(report{job: j, slot: u.Slot, attempts: u.Attempts, suspend: u.Kind == "suspended"})
    }
    if s.manual[j.Name] {
        s.logf("job %s: triggered; one run for %s", j.Name, now.Format(time.RFC3339))
        return []Due{{Job: j, At: now, Scheduled: now, Manual: true}}, true, nil
    }
    if waiting || suspended {
        return nil, false, nil
    }
    last := st.Last.In(loc)
    var inflight *time.Time
    if st.InFlight != nil && !st.InFlight.After(now) {
        // A run that died with the process (or was stopped by an orderly
        // shutdown) stands for its slot still.
        f := st.InFlight.In(loc)
        inflight = &f
        s.logf("job %s: a run for %s was in flight at the last stop (attempt %d); counted as missed", j.Name, f.Format(time.RFC3339), st.Attempts)
    }
    m, lost, lastLost := missed(s.specs[j.Name], last, now)
    if lost > 0 {
        s.logf("job %s: at least %d fire times since %s; the newest %d are kept", j.Name, lost+len(m), last.Format(time.RFC3339), len(m))
    }
    if inflight != nil {
        m = insertTime(m, *inflight)
    }
    if len(m) == 0 {
        return nil, false, nil
    }
    dues, dropped, lastDropped := s.plan(j, now, m)
    dropped += lost
    if lastLost.After(lastDropped) {
        lastDropped = lastLost
    }
    if dropped > 0 || !lastDropped.IsZero() {
        // One write counts the dropped slots and moves L past them, so a
        // crash counts none of them twice and loses none of the rest.
        st.Dropped += dropped
        if lastDropped.After(st.Last) {
            st.Last = lastDropped
        }
        if st.InFlight != nil && !st.InFlight.After(st.Last) {
            st.InFlight, st.Attempts, st.Stops = nil, 0, 0 // its slot was dropped
        }
        st.Cron = j.Cron
        if err := s.SaveState(j.Name, st); err != nil {
            return nil, false, err
        }
    }
    return dues, false, nil
}
  1. The start. runOne writes in_flight (the slot), attempts + 1 and crashes + 1 in one fsynced write, and starts the run only if that write succeeded. A failed write leaves the slot offered again after a minute (RetryAfterWriteFailure) and stops the job’s batch there: going on to a newer slot of a catch_up_all batch would move LL past the slot that never ran. Under skip the lateness is re-judged just before this write.
  2. The turn. Chapter 40’s Send: the ledger, the session, the memory record, and any notice.
  3. The final write. If the run ended, L←max(L,slot)L \leftarrow \max(L, \text{slot}), in_flight is cleared, attempts, crashes and stops return to 0, suspended clears, and last_stop and last_run are set. If instead the scheduler’s context ended, or the daemon is closing, and the run returned cancelled (an orderly stop), in_flight stays, the attempt and the crash are taken back and stops goes up by one.
// runOne writes InFlight (and counts the attempt) or, for a run on request,
// Manual, and counts the run in Crashes; runs; writes the outcome. Under
// Skip the slot's lateness is judged here, when the run would start: a slot
// that waited for a run slot past its grace is dropped and counted instead
// of run. If the state before the run cannot be written the run is NOT
// started (nothing on disk would say it ran, and a restart would count it
// as a first start): the job is left alone for RetryAfterWriteFailure and
// its slot is offered again, and runOne returns false so that the batch it
// belongs to goes no further (a newer slot's final write would move L past
// this one). It returns true when the slot was dealt with: run, or dropped
// as late. A state write after the run that fails is warned of and the run
// goes on; the process keeps the state it meant to write (LoadState), so the
// slot is not handed out again until the process ends.
//
// A run that returns "cancelled" because ctx ended (an orderly stop) is not
// recorded as ended: its slot stays in flight, with the attempt taken back
// and the crash not counted, so the next start applies the missed-run
// policy to it as it does to a run that died, and the stop does not count
// toward either bound. Stops counts such stops of the one slot in flight, and
// each re-run of that slot after one is warned of; nothing bounds them (the
// policy decides). A run for a newer slot starts the count again, with one
// warning that the stopped slot is not the one running. A kill between two
// stops does not reset the count. The stop
// counts as a crash all the same if the process is killed before the final
// write below lands (a service manager's stop timeout) or that write fails:
// the disk then still holds the crash counted at the start, and two such
// stops in a row suspend the job.
func (s *Scheduler) runOne(ctx context.Context, d Due) bool {
    sched := d.Scheduled
    s.mu.Lock()
    st, err := s.LoadState(d.Job.Name)
    if err != nil {
        s.mu.Unlock()
        s.warnf("job %s: state: %v", d.Job.Name, err)
        return false
    }
    if d.Job.Policy == Skip && !d.Manual {
        start := s.Clock()
        if g := s.grace(s.specs[d.Job.Name], sched); start.Sub(sched) > g {
            s.logf("job %s: the run for %s would start %s late (grace %s); dropped", d.Job.Name, sched.Format(time.RFC3339), start.Sub(sched), g)
            st.Dropped++
            if sched.After(st.Last) {
                st.Last = sched
            }
            if st.InFlight != nil && !st.InFlight.After(st.Last) {
                st.InFlight, st.Attempts, st.Stops = nil, 0, 0
            }
            st.Cron = d.Job.Cron
            if err := s.SaveState(d.Job.Name, st); err != nil {
                s.warnf("job %s: state: %v", d.Job.Name, err)
            }
            s.mu.Unlock()
            return true
        }
    }
    rerun := 0 // orderly stops of this slot before this start
    switch {
    case d.Manual:
        st.Manual = &sched
        // A run on request is the reader's own attempt: what was told of a
        // failure is forgotten, so this attempt's failure is told too.
        st.ToldKinds, st.Suppressed = nil, 0
    case st.InFlight != nil && st.InFlight.Equal(sched):
        st.Attempts++
        rerun = st.Stops
    default:
        if st.InFlight != nil && st.Stops > 0 {
            // Stops is of one slot; this run is for another, so the count starts
            // again. This case is reached only when the stopped slot was still
            // in flight at this start (catch_up_one, where the newer run folds
            // the stopped slot in and stands for it), and the reader is told
            // once. Under skip, and under catch_up_all past max_catch_up, the
            // check has already dropped the stopped slot (counted in Dropped,
            // with a -v line) and cleared Stops, so nothing is warned.
            s.warnf("job %s: the run for %s was stopped %d time(s); this run is for %s and stands for it", d.Job.Name, st.InFlight.Format(time.RFC3339), st.Stops, sched.Format(time.RFC3339))
        }
        st.InFlight, st.Attempts, st.Stops = &sched, 1, 0 // another slot: its stops are not this one's
    }
    st.Crashes++
    st.Cron = d.Job.Cron
    if err := s.trySave(d.Job.Name, st); err != nil {
        s.held[d.Job.Name] = s.Clock().Add(RetryAfterWriteFailure)
        s.warnf("job %s: the state for the run of %s could not be written (%v); the run is not started and the slot is offered again in %s", d.Job.Name, sched.Format(time.RFC3339), err, RetryAfterWriteFailure)
        s.mu.Unlock()
        return false
    }
    if rerun > 0 {
        s.warnf("job %s: the run for %s is started again after %d orderly stop(s) (the policy decides; nothing bounds this)", d.Job.Name, sched.Format(time.RFC3339), rerun)
    }
    s.mu.Unlock()
    timeout := d.Job.Timeout
    if timeout <= 0 {
        timeout = DefaultTimeout
    }
    rctx, cancel := context.WithTimeout(ctx, timeout)
    stop, rerr := s.Run(rctx, d)
    cancel()
    // The daemon's own stop: the context has ended, or the caller is closing and
    // cancelled its sessions first (Closing); either way a cancelled run is
    // not a run that ended.
    shutdown := (ctx.Err() != nil || s.closing()) && (stop == "cancelled" || errors.Is(rerr, context.Canceled))
    if rerr != nil {
        if stop == "" {
            stop = "error"
        }
        s.logf("job %s: run for %s: %s: %v", d.Job.Name, sched.Format(time.RFC3339), stop, rerr)
    } else {
        s.logf("job %s: run for %s: %s", d.Job.Name, sched.Format(time.RFC3339), stop)
    }
    if s.afterRun != nil {
        defer s.afterRun(d) // after the lock is released
    }
    s.mu.Lock()
    defer s.mu.Unlock()
    st, err = s.LoadState(d.Job.Name)
    if err != nil {
        s.warnf("job %s: state: %v", d.Job.Name, err)
        return true
    }
    started := d.At
    st.LastRun = &started
    switch {
    case shutdown:
        st.LastStop = "cancelled"
        if st.Crashes > 0 {
            st.Crashes--
        }
        if d.Manual {
            st.Manual = nil
        } else {
            if st.Attempts > 0 {
                st.Attempts-- // InFlight stays: the policy decides at the next start
            }
            st.Stops++
        }
    default:
        if d.Manual {
            st.Manual = nil // a run on request stands for no slot: L stays
        } else {
            if sched.After(st.Last) {
                st.Last = sched
            }
            st.InFlight, st.Attempts, st.Stops = nil, 0, 0
        }
        st.LastStop = stop
        st.Crashes, st.Suspended = 0, false
        st.Untold = withoutKind(st.Untold, "suspended")
    }
    st.Cron = d.Job.Cron
    if err := s.SaveState(d.Job.Name, st); err != nil {
        s.warnf("job %s: state: %v (the process keeps it)", d.Job.Name, err)
    }
    return true
}

What each kill leaves, and what the next daemon does:

Kill at Left The next daemon
inside the check as before; an untold record if its write landed the same slots are found; the record is raised again
after the drop write dropped slots counted once, LL past them the run’s slot is offered again
before the in_flight write completes nothing new the slot is offered as new; the batch had stopped there
after the in_flight write attempts nn, crashes cc n<2n < 2 and c<2c < 2: offered once more. c=2c = 2: suspended, nothing starts. n=2n = 2 and c<2c < 2 (a clear in between): recorded as failed and the reader told
mid-turn the same, and a ledger begin with no end chapter 40 closes the turn at the session’s next open and never re-runs it; catch_up_* re-runs the slot, skip only inside the grace
after the notice, before the final write the same as above; the notice may be told again
after the final write LL at the slot, in_flight clear, counts zero nothing
an orderly stop mid-turn last_stop is cancelled, in_flight kept, the attempt and the crash taken back, stops + 1 as a kill, but the stop counts toward neither bound; a re-run of the same slot warns with the count. A stop killed before that write lands, or whose write fails, is a crash
a run on request, killed manual set, a crash counted the record is cleared; nothing is re-run or dropped and LL is unmoved; the crash counts toward the suspension
between a suspension’s (or an abandonment’s) write and its report suspended and an untold record the report is raised again; once sent or queued, never again

Two bounds. At most two runs of one scheduled time may die with the process (MaxAttempts); an orderly stop takes its attempt back and is not counted. A check that finds a slot in flight whose attempts has reached 2 records it as failed (failed + 1, last_stop abandoned), moves LL to it, counts the older slots it also stood for as dropped, and raises a notice that the run “was started 2 times and the daemon stopped each time before it ended; it will not be run again”. And a job whose last two runs, of any slots, were started and never ended is suspended (MaxCrashes). The second is not the first over again. A */15 job that kills the daemon at every run starts a different slot each time, so no slot reaches two attempts, and the job would run for ever; crashes counts consecutive runs of the job, and any run that ends, with any stop reason, sets it to 0. A suspended job starts nothing, shows no next fire time in aecd jobs, and is released by a run on request that ends (aecd jobs -run NAME) or by any change to its entry in aecd.json (Entry is a digest of the decoded job; a changed cron line also starts the job from now). A clock step does not release it. The suspension is told, at least once, as critically as the job is marked. After a long suspension the first check hands out whatever the policy says about everything since LL: up to MaxCatchUp runs at once for catch_up_all, one for catch_up_one, and for skip the newest slot only if it is on time.

Neither bound is exactly-once, and nothing here claims it. The final write can be lost after a run that ended; the notice can be told, and the daemon killed before the state records it, so a re-run may repeat a notice. What the bounds buy is that the number of runs of one scheduled time that die with the process, while the disk takes the writes, is at most two, and that a job which cannot stay alive is stopped and the reader told. Orderly stops are outside both bounds.

An orderly stop is left to the policy. A shutdown cancels the scheduler’s context, the turn returns cancelled, and runOne keeps the slot in flight with the attempt and the crash taken back. The next daemon applies the policy to it as it would after a kill: catch_up_one and catch_up_all run it again, skip only if it is still within the grace. What that gives is a slot that survives a restart by a service manager. What it does not give is a bound. A job whose own run stops the daemon in an orderly way re-runs under catch_up_* at every restart, and nothing stops it; stops counts the orderly stops of the slot in flight, aecd jobs shows stops=N, and a re-run of the same slot writes a warning naming it and the count, to stderr whatever -v says; under catch_up_one, where the next start is for a newer slot that folds the stopped one in, one warning says the older slot was stopped that many times and that the newer run stands for it, and the count starts again; under skip, and under catch_up_all past its cap, the stopped slot is dropped and counted like any missed slot, with no warning. The stop is never told as a notice and never suspends the job.

What the pair gives. A scheduled run killed mid-turn is a session turn with a pending ledger record. At the session’s next open chapter 40’s rule completes or erases that turn from the record’s arithmetic (the outcome of a write tool unknown: abort and the model told so; an idempotent tool: replay of the batch) and never re-runs a turn by itself. Whether the slot runs again is this chapter’s policy and nothing else, and when it does, the second run starts on a session whose first turn was closed by the ledger before it began: that is why a re-run is safe where the first run may have been half done, and why the rule is at-least-once and not at-most. Chapter 53’s lab, which kills the driver or the daemon mid-step and resumes from the round ledger, builds on this: the daemon resolves the half-done turn at the session’s next open, and chapter 53’s driver re-sends the step from its own round ledger.

Serve. The loop wakes at the earlier of the next fire time of any job (a job that is running included) and MaxWait, an hour, and also when a run ends or a trigger arrives; it never ticks. It never waits for a run: each job’s batch runs in a goroutine of its own, in Jobs order through a first-in-first-out semaphore of Parallel places (1 in the daemon), and one job never overlaps itself. The slots a running job misses are the next check’s MM. A Serve that returns an error has stopped scheduling; the daemon says so (daemon/status reads restarting after: …), warns on stderr, and starts it again after a full-jitter wait (chapter 41’s Backoff). The job’s turn runs under the scheduler’s context, bounded by the job’s Timeout (10 minutes unless it says), so a caller whose context ends cancels its turn, as chapter 40 requires.

// Serve checks at start and then at every fire time (or MaxWait, whichever
// is sooner) until ctx ends, running each Due through Run with the state
// written before (InFlight, Attempts, Crashes) and after (Last, LastRun,
// LastStop). The loop never waits for a run: each job's batch runs in a
// goroutine of its own that takes a slot (at most Parallel at once) and
// re-wakes the loop when it ends, so a trigger or an on-time slot is seen
// while another job runs. A job's own Dues run in order. A Serve that
// returns an error has stopped scheduling and returns at once (runs in
// flight go on under ctx and are waited for by the next Serve or by Wait);
// its caller says so and starts it again. Serve refuses to run twice at
// once on one Scheduler. When ctx ends Serve waits for the runs.
func (s *Scheduler) Serve(ctx context.Context) error {
    if err := s.Check(); err != nil {
        return err
    }
    s.mu.Lock()
    if s.serving {
        s.mu.Unlock()
        return ErrServing
    }
    s.serving = true
    s.mu.Unlock()
    defer func() {
        s.mu.Lock()
        s.serving = false
        s.mu.Unlock()
    }()
    if s.Clock == nil {
        s.Clock = time.Now
    }
    s.mu.Lock()
    if s.slots == nil {
        par := s.Parallel
        if par <= 0 {
            par = 1
        }
        s.slots = &fifoSem{free: par}
    }
    slots := s.slots
    s.mu.Unlock()
    s.sweeper.Do(s.sweep) // once per Scheduler: a restarted Serve must not sweep a live temp file
    for {
        if err := ctx.Err(); err != nil {
            s.wg.Wait()
            return err
        }
        now := s.Clock()
        due, err := s.Due(now)
        if err != nil {
            return err
        }
        s.tellReports()
        if s.Checked != nil {
            s.Checked(now)
        }
        byJob := map[string][]Due{}
        var order []string
        for _, d := range due {
            if _, seen := byJob[d.Job.Name]; !seen {
                order = append(order, d.Job.Name)
            }
            byJob[d.Job.Name] = append(byJob[d.Job.Name], d)
        }
        for _, name := range order {
            batch := byJob[name]
            s.mu.Lock()
            s.running[name] = true
            s.mu.Unlock()
            place := slots.enter() // in Jobs order, here, not in the goroutine
            s.wg.Add(1)
            go func(name string, batch []Due) {
                defer s.wg.Done()
                defer s.poke()
                defer func() {
                    s.mu.Lock()
                    delete(s.running, name)
                    s.mu.Unlock()
                }()
                if !slots.wait(ctx, place) {
                    return
                }
                defer slots.leave()
                s.runBatch(ctx, batch)
            }(name, batch)
        }
        // The wait runs from the slot after the check time (so none between
        // the check and now is missed) to a fresh reading of the clock.
        wait := MaxWait
        if next, ok := s.nextFire(now); ok {
            if w := next.Sub(s.Clock()); w < wait {
                wait = w
            }
        }
        if h, ok := s.nextHeld(); ok {
            if w := h.Sub(s.Clock()); w < wait {
                wait = w
            }
        }
        if wait <= 0 {
            continue
        }
        var tc <-chan time.Time
        var stopTimer func() bool
        if s.Timer != nil {
            tc = s.Timer(ctx, wait)
        } else {
            tm := time.NewTimer(wait)
            tc, stopTimer = tm.C, tm.Stop
        }
        s.mu.Lock()
        wake := s.wake
        s.mu.Unlock()
        select {
        case <-tc:
        case <-wake:
        case <-ctx.Done():
        }
        if stopTimer != nil {
            stopTimer()
        }
    }
}

// closing reports that the caller has begun to shut down (Closing).
func (s *Scheduler) closing() bool { return s.Closing != nil && s.Closing() }

// runBatch runs one job's Dues in order. It stops at a done context, at a
// caller that is closing, and at the first Due that did not start (a failed
// pre-run write, an unreadable state): going on would run a newer slot, whose
// final write moves L past the one that never ran, so the slot would be lost
// without a count; the job is held and the check offers every slot again.
func (s *Scheduler) runBatch(ctx context.Context, batch []Due) {
    for _, d := range batch {
        if ctx.Err() != nil || s.closing() {
            return
        }
        if !s.runOne(ctx, d) {
            return
        }
    }
}

This chapter writes the slot down before the run and clears it after, which can run a slot again and cannot lose one without a count; the two bounds above limit what a crash loop can do with that.

Unattended: what a run is given and what the reader is told

A job is configuration the principal wrote. Job is its record, and its JSON is read strictly: an unknown key, a key in the wrong case, a repeated key, a null, a wrong type and a negative max_catch_up are errors that name the job. The strictness is not tidiness. A misspelt key is dropped because encoding/json ignores unknown keys, and DisallowUnknownFields does not reach into a type that decodes itself, so a misspelt "critcal": true would have run a job the reader meant to mark as an ordinary one. And encoding/json matches keys without regard to case and keeps the last of a repeated key, so "critical": true, …, "critical": false would have passed as unmarked.

// Job is one scheduled task. Name is [A-Za-z0-9_-]{1,60}, not beginning
// with "-" (a file name under the scheduler's Dir and, as job-<Name>, a
// session id of at most 64 bytes; two names that differ only in case are
// refused together); Cron a crontab(5) line;
// Task the user text of the turn; Tools the names of the daemon's tools the
// run is given: nil (no "tools" key) is the daemon's fixed safe list
// (daemon.DefaultJobTools), an empty non-nil list is no tool at all, and a
// named list is exactly that list; terminal reaches a job only by being named
// here, and is then still refused at once if it is marked (Unattended);
// Session a plain session id
// the runs use instead of job-<Name> (never another job's job-... id; the
// runs then queue behind that session's other turns, a reader's included);
// Timeout the wall-clock limit of one run. Critical is the
// reader's own marking in aecd.json, and the only thing that lets a
// notice interrupt inside the quiet window (it also lets a result notice
// past the urgency threshold, and still goes only to the allowed
// channels); nothing a task says or a model writes can set it.
type Job struct {
    Name       string        `json:"name"`
    Cron       string        `json:"cron"`
    Task       string        `json:"task"`
    Tools      []string      `json:"tools,omitempty"` // nil: the default list; empty: none
    Policy     MissedPolicy  `json:"missed"`
    MaxCatchUp int           `json:"max_catch_up,omitempty"` // default 24
    Timeout    time.Duration `json:"timeout"`
    Notify     bool          `json:"notify"` // the run's final text goes through the Notifier
    Session    string        `json:"session,omitempty"`
    Critical   bool          `json:"critical,omitempty"`
}

The approver of such a run is Unattended (a daemon with a policy block, chapter 47, gives it that block’s unattended approver instead). Chapter 27’s protocol is unchanged: silence is a timeout, and the nonce binds a reply to one dispatch. The difference is that nobody is there to break the silence, so Approve answers Timeout at once, with the request’s nonce and call hash and By: "unattended", and the loop records decision=timeout by=unattended on the approval span. OnTimeout is Abort, so the run ends approval_timeout with every call of the batch answered (the gate settles the whole batch before any call of it is dispatched, so the batch that held the marked call did not run; batches earlier in the turn did). It agrees with chapter 41’s approval path, the same Approver contract with a different answer to silence: a turn from a channel under approve: channel asks in the thread and waits, and a scheduled turn asks no one.

// Unattended is the Approver of a run nobody is watching. It answers every
// marked call "timeout" at once: chapter 27's protocol says silence is a
// timeout, and a scheduled run has no one to break it, so waiting the
// approval timeout would only delay the same answer. Under Loop.OnTimeout
// Abort (the default) the run then ends with Stop.Reason approval_timeout
// with every call of the batch answered, and the Notifier tells the
// principal what was refused. Log sees each request (the daemon logs the
// call's name and hash, never its arguments).
type Unattended struct {
    Log func(agent.ApprovalRequest)
}

var _ agent.Approver = Unattended{}

func (u Unattended) Approve(ctx context.Context, req agent.ApprovalRequest) (agent.Approval, error) {
    if u.Log != nil {
        u.Log(req)
    }
    return agent.Approval{Request: req.ID, CallHash: req.Call.Hash, Decision: agent.Timeout, By: "unattended"}, nil
}

What tools a run has. A job with no tools key is given a fixed list, DefaultJobTools: read_file and search_files (the workspace, read-only), scratch_read and scratch_write (the scratchpad is the one place it may write), memory_recall and skill_view (reads of memory and skills). Of these, only the ones the daemon has mounted: without memory or skills those names are simply absent (TestJobToolsMissingMountsAreAbsent). The filter is by name: a tool a hook mounts under one of those six names is given to the job. Anything that writes outside the scratchpad, writes a skill, or is mounted from an MCP server (chapter 44) must be named in the job’s tools, and "tools": [] means none at all. The decoder tells an absent key from an empty list. A name the daemon does not have is refused at Open, with the job and the tool named, because a misspelt name would otherwise narrow a run to less than the reader meant without a word. There are two exceptions, for a name spelt <prefix>__<rest> under a configured MCP mount, since the daemon cannot tell a misspelt name from a server that changed (chapter 44): under a mount that did not start the name is accepted, since the mount’s tools were never listed and the mount has its own warning, and under a mount that is up and did not mount it the name is accepted with one warning through the daemon’s warning sink, naming the job, the tool and the server. In both, the job’s turns simply lack the tool. A name that begins with no mount’s prefix and is none of the daemon’s tools is refused whichever mounts are up.

// DefaultJobTools is the tool set of a job with no "tools" key (Kyle,
// 2026-10-12, "Fixed safe list"): read-only on the workspace (read_file,
// search_files), writes only to the scratchpad (scratch_write; scratch_read),
// and reads of memory and skills (memory_recall, skill_view). Of these the
// daemon has mounted, no more: without memory or skills the corresponding
// names are simply absent. Nothing else is in it: not write_file, skill_write,
// memory_chat or terminal, and no name a ToolHook adds (a tool that chapters
// 43 and 44 mount under a name of its own reaches a job only by being named in
// its list). "tools": [] is no tool at all.
//
// The filter is by name, not by origin: a tool a ToolHook mounts under one of
// these six names is given to a job with no "tools" key, and a hook that
// wants its tool kept from jobs gives it a name of its own. Chapter 43's
// execute_code and skill_run are names of their own, outside this list, so a
// job must name them.
var DefaultJobTools = []string{"read_file", "search_files", "scratch_read", "scratch_write", "memory_recall", "skill_view"}

// checkJobTools refuses a job whose Tools names something the daemon does
// not have (the daemon's tools, the ToolHook's included), naming the job and
// the tool: a misspelt name would otherwise narrow a run to nothing, or to
// less than the reader meant, without a word. Two kinds of name are not
// refused, because the daemon cannot tell a misspelt name from a server that
// changed (rulings 7e-E1b and FU-6): a name spelt <prefix>__<rest> under a
// mount that did not start is accepted (the mount has its own warning), and
// one under a mount that is up but is not among its mounted tools is accepted
// with one warning per job and name through Config.Warn naming the job, the
// tool and the server. Either way the job's turns have
// no such tool (jobToolFilter drops absent names). A name that matches no
// mount's prefix and none of the daemon's tools still refuses. Every part of
// the warning is the reader's (the job and tool names come from aecd.json,
// the server's name is its configured one), so none passes mcp.Clean. It asks
// Tools for the names with a workspace path that does not exist (no turn is
// running), so a ToolHook must only build tools from that path, not touch it.
func (d *Daemon) checkJobTools(jobs []sched.Job) error {
    known := map[string]bool{}
    var names []string
    for _, t := range d.tools(filepath.Join(d.cfg.Dir, "jobs-tools-check")) {
        n := t.Spec().Name
        if !known[n] {
            known[n] = true
            names = append(names, n)
        }
    }
    for _, n := range d.extraToolNames() { // chapter 45: delegate, appended per turn when the pool exists
        known[n] = true
        names = append(names, n)
    }
    sort.Strings(names)
    for _, j := range jobs {
        warned := map[string]bool{} // a name a job repeats is warned of once
        for _, n := range j.Tools {
            if known[n] {
                continue
            }
            // A tool of a mount that did not start (ruling 7e-E1b) cannot be
            // checked, since its tools were never listed: the job is accepted,
            // and its turn simply has no such tool.
            if d.namesDownMount(n) {
                continue
            }
            // A tool an up server did not mount (ruling FU-6; unlisted, or
            // excluded by mcp.Mount, whose reason goes to the -v log): warn
            // and run.
            if srv, ok := d.upMountOf(n); ok {
                if !warned[n] {
                    warned[n] = true
                    d.warnf("aecd: job %q: tool %q is not among the tools mounted from MCP server %q; the job runs without it", j.Name, n, srv)
                }
                continue
            }
            return fmt.Errorf("aecd: job %q: tool %q is not one of the daemon's tools (%s)", j.Name, n, strings.Join(names, ", "))
        }
    }
    return nil
}

// jobToolFilter is the tool set of a job's turn: nil names (no "tools" key)
// is DefaultJobTools, an empty list is no tool, and a named list is exactly
// that list (terminal reaches a job only by being named, and is then still
// refused at once if it is marked).
func jobToolFilter(names []string) func([]agent.Tool) []agent.Tool {
    if names == nil {
        names = DefaultJobTools
    }
    allow := map[string]bool{}
    for _, n := range names {
        allow[n] = true
    }
    return func(base []agent.Tool) []agent.Tool {
        var out []agent.Tool
        for _, t := range base {
            if allow[t.Spec().Name] {
                out = append(out, t)
            }
        }
        return out
    }
}

The reason for a list with so few names in it is skill_write. A skill is text that every later session loads (chapter 36), so an unattended run that can write one can change what the reader’s next conversation starts from, with nobody present when it did. terminal and write_file reach the workspace and a shell. A job that needs them says so in aecd.json, where the reader can read it, and a call that is marked is still refused at once by Unattended when the model makes it. The filter belongs to the turn (Turn.ToolFilter, applied before the loop gets its tools); the reader’s own turn on the same session, if a job shares one, has the full set (TestJobToolsThreeCases runs both).

Who a job speaks as. The task is configuration the principal wrote, so the model reads it unfenced at User level as his (Turn.Peer is the principal). It is not his speech, so the daemon records the turn in memsvc under the peer sched (Turn.RecordAs). Two consequences are pinned by TestTaskLineIsNotPolicy. A task that is, word for word, one of chapter 35’s four forms does not bind the user model, and a job that runs every fifteen minutes does not fill the principal’s memory with its own prompt: the session job-<name> has the peers sched and the agent. And the one that must be said plainly: memsvc.Context renders a message by its recorded peer, so it replays a job’s task inside the fence as peer_sched (Context’s render), while session.jsonl holds the same text as the principal’s. A resumed session and a memory replay of it differ in exactly that fence, by design. A job’s session persists across its runs, so a run sees what the earlier ones left, which is what the heartbeat’s “what has changed since your last run” depends on; the session grows by a turn per run and chapter 40’s compaction is what bounds what the model sees of it.

What the reader is told. The rule is one sentence: every way a job’s turn can end except the daemon’s own shutdown raises a notice. A run that ends final is told only when the job says notify, as a result notice. Every other end raises the daemon’s own notice (Notice.Own, which notifyNotice sets from the kind and nothing else sets), notify or not, and one warning line. A notice the daemon wrote itself is never scored: it is sent outside the quiet window and queued inside it, and a job marked critical is sent inside the window as well. A constant string’s score would be one unmeasured number for each job name and kind, a coin the reader never saw tossed, whereas a failure is the daemon’s own knowledge and the quiet window is the reader’s own marking. The cost is that every failure outside the window interrupts, bounded by the per-kind suppression and the 24-hour retelling below, and that the user model’s minimum urgency level does not hold these back. Marking a job critical is for one purpose, to interrupt inside quiet hours.

// runJob is Scheduler.Run: the maintenance jobs each do their one step; every
// other job is one turn on the job's session under Unattended, with the
// tools its Tools list names (no list: DefaultJobTools; an empty list: none),
// the task text carrying the scheduled time and, under CatchUpOne, the slots
// the run stands for. The heartbeat job is an ordinary job (its file is
// touched by the scheduler's loop, checked). The task is configuration the
// principal wrote, so the model reads it unfenced at User level (Peer); it is
// not his speech, so memsvc records the turn under SchedPeer (RecordAs).
//
// What the reader is told: the run's final text, as a "result" notice, only
// for a run that ended final and only when the job says notify; every other
// way a job's turn can end but the daemon's own shutdown raises the daemon's
// own notice (Notice.Own: never scored, sent outside quiet hours and queued
// inside them unless the job is critical), notify or not, and one warning
// line: "stopped: <stop reason>" for a turn that ended any other way
// (a provider that cannot be reached ends the turn "error" with a nil error,
// as do max_turns, max_tool_calls and refused; a turn cancelled through its
// session by a control client is cancelled), "stopped" for a timeout, and
// "failed: error" for a Send that returned an error or a session that could
// not be opened. No notice carries model text or error text. The two
// maintenance jobs tell nobody: a failure is one warning line per episode. A
// job's failures of the same kind are told once (State.ToldKinds) and again
// when FailureRetell has passed between the scheduled times; a changed entry
// in aecd.json and a run on request forget what was told. State.Streak
// counts every failed run since the last that ended final, told or not; the
// next run that ends final says that number when it is two or more, and
// clears the streak. The turn
// runs under the job's context alone: a job whose context ends cancels its
// own turn and nobody else's (a session it shares with a reader is the
// reader's).
func (d *Daemon) runJob(ctx context.Context, due sched.Due) (string, error) {
    switch due.Job.Name {
    case DeriveJob:
        n, err := d.derive(ctx)
        if err != nil {
            d.maintenanceFailed(ctx, due.Job.Name, err)
            return "error", err
        }
        d.maintenanceOK(due.Job.Name)
        d.logf("derive: facts=%d", n)
        return "ok", nil
    case RotateJob:
        if d.mem == nil {
            err := errors.New("aecd: no memory service (no embedder configured)")
            d.maintenanceFailed(ctx, due.Job.Name, err)
            return "error", err
        }
        rr, err := d.mem.Maintain(ctx)
        if err != nil {
            d.maintenanceFailed(ctx, due.Job.Name, err)
            return "error", err
        }
        d.maintenanceOK(due.Job.Name)
        d.logf("rotate: records=%d tombstones=%d bytes=%d", rr.Records, rr.Tombstones, rr.Bytes)
        return "ok", nil
    }
    sess, err := d.Session(ctx, due.Job.SessionID())
    if err != nil {
        if d.shuttingDown() {
            // Close began between the scheduler's check and this open: the
            // daemon's own stop, so the slot is left to the policy.
            return agent.StopCancelled, nil
        }
        if ctx.Err() == nil {
            d.notifyErr(ctx, due.Job, due.Scheduled, "failed: error", err)
        }
        return "error", err
    }
    text := fmt.Sprintf("%s\n\n(Scheduled run for %s.)", due.Job.Task, due.Scheduled.Format(time.RFC3339))
    if due.Manual {
        text = fmt.Sprintf("%s\n\n(Run on request at %s.)", due.Job.Task, due.Scheduled.Format(time.RFC3339))
    }
    if s := due.Describe(); s != "" {
        text += " " + s
    }
    unattendedLog := func(r agent.ApprovalRequest) {
        // The reason names a worker's call's worker ("worker s/1/w1: ..."); it
        // can hold text the model wrote (a path), so it is quoted.
        d.logf("job %s: marked call %q (%s) refused unattended: %q", due.Job.Name, r.Call.Name, r.Call.Hash, r.Reason)
    }
    var approver agent.Approver = sched.Unattended{Log: unattendedLog}
    if d.gate != nil {
        // Chapter 47: the gate's unattended approver allows what
        // allow_unattended names and the gate did not escalate; everything
        // else is "timeout" at once, as Unattended answers, or a denial from
        // the strict tier (ruling X8-3). runTurn fills in the turn's taints.
        approver = policy.Approver{Gate: d.gate, Principal: nil, Allowed: d.allowUnattended,
            Log: func(req agent.ApprovalRequest, ap agent.Approval, dec policy.Decision) {
                if ap.Decision == agent.Allow {
                    d.logf("job %s: allowed call %q (%s) ran unattended under allow_unattended (tier %s)", due.Job.Name, req.Call.Name, req.Call.Hash, dec.Tier)
                    return
                }
                unattendedLog(req)
                d.logf("job %s: the gate's answer for %q was tier %s%s", due.Job.Name, req.Call.Name, dec.Tier, strictNote(dec))
            }}
    }
    res, err := sess.Send(ctx, Turn{
        Input:      text,
        Peer:       d.cfg.Principal,
        RecordAs:   SchedPeer,
        Channel:    "sched",
        Approver:   approver,
        ToolFilter: jobToolFilter(due.Job.Tools),
    })
    if cerr := ctx.Err(); cerr != nil && (err != nil || res.Stop.Reason == agent.StopCancelled) {
        if errors.Is(cerr, context.DeadlineExceeded) {
            // The job's own Timeout (the job context's, not a provider's).
            d.warnf("job %s: stopped: timeout", due.Job.Name)
            d.tellFailure(context.WithoutCancel(ctx), due.Job, due.Scheduled, "timeout", "stopped: the run passed the job's timeout and was cancelled", "")
            return "timeout", nil
        }
        // A shutdown: the turn was cancelled by the scheduler's context; the
        // session's ledger holds the rest (chapter 40).
        return agent.StopCancelled, nil
    }
    if err != nil {
        d.notifyErr(ctx, due.Job, due.Scheduled, "failed: error", err)
        return "error", err
    }
    reason := res.Stop.Reason
    switch {
    case reason == agent.StopFinal:
        d.recovered(ctx, due.Job)
        if due.Job.Notify {
            if sess.Info().Private {
                // A private session's text goes to no other channel and to no
                // embedder: the notice is the daemon's own frame and a pointer
                // to the session (ruling 7f-E11).
                d.notifyPrivateResult(ctx, due.Job, sess.ID)
            } else {
                d.notify(ctx, due.Job, "result", res.Stop.Final)
            }
        }
    case reason == agent.StopCancelled && d.shuttingDown():
        // The daemon's own shutdown cancelled the session before the job's
        // context ended: the ledger holds the rest.
    case reason == agent.StopApprovalTimeout:
        d.warnf("job %s: stopped: %s", due.Job.Name, reason)
        d.tellFailure(ctx, due.Job, due.Scheduled, reason, "stopped: a tool call needed your approval and nobody was there to give it; the batch of calls that held it did not run (calls earlier in the turn may have)", "")
    default:
        d.warnf("job %s: stopped: %s", due.Job.Name, reason)
        d.tellFailure(ctx, due.Job, due.Scheduled, reason, "stopped: "+reason, "")
    }
    return reason, nil
}

The kinds are stopped: <reason> for a turn that ended with any stop reason but final (a provider that cannot be reached ends the turn error with a nil error, as do max_turns, max_tool_calls and refused; a turn cancelled through its session by a control client is cancelled), a timeout-specific sentence for the job’s own Timeout, the approval sentence (stopped: a tool call needed your approval and nobody was there to give it; the batch of calls that held it did not run (calls earlier in the turn may have)), and failed: error for a Send that returned an error or a session that could not be opened. No notice carries model text or error text. The error goes to the warning sink, and to the queue’s reason, which stays on the reader’s disk. A failed run’s notice to a channel is the daemon’s frame and a kind, which is why a provider’s error, which can name hosts and paths, never reaches a chat.

The failure streak. The first failure of a streak is told. Each kind of failure keeps the scheduled time of the run at which it was last told. A failure of that kind is not repeated while its run’s scheduled time is less than 24 hours (FailureRetell) after that entry; it is counted, and aecd jobs shows suppressed=N. At the first failure of the kind 24 hours or more after the entry it is told again with the length of the streak so far, so a nightly job that keeps failing is told every night and two kinds that alternate every minute are each told once a day. A first telling that the quiet window only queued is still a telling, so the reader is not interrupted about that failure again until the next telling, 24 hours or more later, unless the job is critical. A change to the job’s entry in aecd.json (a changed cron line included) or a run on request forgets what was told, so the reader’s own next attempt speaks; a restart does not. The next run that ends final raises one recovered notice giving the number of runs that failed since the last one that did, of any kind, told or not, whenever that is two or more; one failed run is not announced. Without the suppression a provider that stays down for a night would put a notice into the queue, or a post in a chat, at every fire time.

// FailureRetell is how long a failure that is told once stays silent: a
// kind of failure is told again at the first failure of that kind whose
// scheduled time is this much or more after the scheduled time of the run at
// which it was last told, with the number of runs in the streak so far. Each
// kind has its own entry, so two kinds alternating are each told once a day.
// A changed entry in aecd.json and a run on request end the silence at once.
const FailureRetell = 24 * time.Hour

// tellFailure raises a failure notice (kind is its text, key what makes two
// failures the same) for the run scheduled at at (a run on request: its start
// time) and counts the run in State.Streak. The notice is not repeated while
// the job's entry for this key (State.ToldKinds: the scheduled time of the
// run at which the key was last told) is less than FailureRetell before at
// and nothing has cleared it (a run that ended final, a changed entry, a run
// on request): the failure is counted in State.Suppressed instead, so a
// provider that stays down cannot fill the queue. An entry later than at (the
// clock stepped back, or the file was edited) counts as lapsed: told, and the
// entry reset. The notice is told before the state records it, and recorded
// only if it was sent or queued, so a kill between them repeats a notice
// rather than loses one, and a notice that went nowhere is told again at the
// next failure. A first telling that the quiet window only queued is still a
// telling: the queue is the reader's to read.
func (d *Daemon) tellFailure(ctx context.Context, job sched.Job, at time.Time, key, kind, detail string) {
    st, err := d.sched.LoadState(job.Name)
    if err != nil {
        d.notifyNotice(ctx, job, kind, "", detail)
        return
    }
    st.Streak++
    told, had := st.ToldKinds[key]
    record := func() {
        kinds := make(map[string]time.Time, len(st.ToldKinds)+1)
        for k, v := range st.ToldKinds {
            kinds[k] = v
        }
        kinds[key] = at
        st.ToldKinds = kinds
    }
    switch {
    case had && told.IsZero(): // an earlier version's file with no time: not retold, the time starts now
        st.Suppressed++
        d.met.notices.Inc(firstWord(kind), "suppressed") // chapter 49
        record()
    case had && !told.After(at) && at.Sub(told) < FailureRetell:
        st.Suppressed++
        d.met.notices.Inc(firstWord(kind), "suppressed") // chapter 49
    default:
        if had {
            kind = fmt.Sprintf("%s (%d runs in a row have stopped without a result)", kind, st.Streak)
        }
        if d.notifyNotice(ctx, job, kind, "", detail) {
            record()
            st.Suppressed = 0
        }
    }
    if err := d.sched.SaveState(job.Name, st); err != nil {
        d.warnf("job %s: state: %v", job.Name, err)
    }
}

// recovered ends a streak of failures: a run ended final. If two or more runs
// failed since the last one that ended final (told or not, of any kind) it
// says how many; one failed run is not announced. The notice is told, then the
// state forgets the streak, so a kill between them repeats the notice rather
// than loses it.
func (d *Daemon) recovered(ctx context.Context, job sched.Job) {
    st, err := d.sched.LoadState(job.Name)
    if err != nil || (st.Streak == 0 && len(st.ToldKinds) == 0) {
        return
    }
    if st.Streak >= 2 {
        d.notify(ctx, job, fmt.Sprintf("recovered: this run ended normally after %d runs in a row that stopped without a result", st.Streak), "")
    }
    st.ToldKinds, st.Suppressed, st.Streak = nil, 0, 0
    if err := d.sched.SaveState(job.Name, st); err != nil {
        d.warnf("job %s: state: %v", job.Name, err)
    }
}

One exception: a run that stops because the daemon is shutting down raises nothing (the next start decides what to do with the slot).

What a notice is. A constant frame, aecd job NAME: KIND, and the model’s text inside a code block whose fence is longer than any run of backticks in it, cut at 4,000 runes before it is fenced. This is chapter 41’s rule for anything model-written that the daemon posts on its own behalf, and it is conservative: the frame carries nothing a model wrote, so a mention or a markdown trick in the text stays text. The cost is that the reader sees a block and not a sentence. Cutting before fencing means the fence is never cut in two, and a notice never reaches chapter 41’s 16,383-rune split; one that would is queued with that reason instead (MaxPostRunes). The one exception is a result from a private session (chapter 45): the notice is the frame and a line that names the session, none of the model’s text, so it is the daemon’s own and is never scored. That closes the urgency head to private text: the notices a private session can raise are that one and the failure and recovery notices, which are frames the daemon wrote whole (an error’s text goes to the queue’s reason and the warning sink, never to the head), so the head’s embedder is sent nothing a private turn wrote, and embedder_local (chapter 45) has nothing to gate there.

// MaxNoticeRunes bounds the model text a notice carries: a chat post is
// one message (chapter 41 splits at 16,383 runes, which would break the
// fence), and a notice is a line, not a transcript.
const MaxNoticeRunes = 4000

// noticeText is what a notification says: a constant frame naming the
// job and the kind of notice, then the model's text inside a code block
// whose fence is longer than any run of backticks in it (chapter 41's
// rule for anything model-written the daemon posts on its own behalf: a
// mention or a markdown trick in the text stays text). The frame is the
// daemon's words and carries nothing model-written.
func noticeText(job, kind, modelText string) string {
    head := fmt.Sprintf("aecd job %s: %s", job, kind)
    if modelText == "" {
        return head
    }
    if utf8.RuneCountInString(modelText) > MaxNoticeRunes {
        r := []rune(modelText)
        modelText = string(r[:MaxNoticeRunes]) + "\n[cut: the run's text is longer than a notice carries; the session has it]"
    }
    return head + "\n" + fence(modelText)
}

// fence wraps text in a Markdown code block that no backtick run inside
// can close.
func fence(text string) string {
    longest, run := 0, 0
    for _, r := range text {
        if r == '`' {
            run++
            if run > longest {
                longest = run
            }
        } else {
            run = 0
        }
    }
    f := strings.Repeat("`", max(3, longest+1))
    return f + "\n" + strings.TrimRight(text, "\n") + "\n" + f
}

Where it goes is sendNotification: to the gateway channel the user model names, to the conversation notify_to gives for it. A user model that names no channel gives the empty channel, which the daemon reads as every channel notify_to lists, and a notice is queued only if none took it. An unregistered channel, a channel with no notify_to entry, a failed send and a notice too long for one post all queue, with the reason.

// MaxPostRunes is the longest chat post the gateways take (Mattermost's
// 16,383 runes; chapter 41 splits a longer text and refuses a longer
// post). A notice is a frame and a fenced, cut text, far below it; a text
// that would not fit one post is queued with the reason, never split, so a
// fence is never cut in two.
const MaxPostRunes = 16383

// sendNotification delivers to the registered gateway channel named
// channel, addressed to the principal in the conversation Config.NotifyTo
// names for it. "" (a readable user model that names no channel) means every
// channel notify_to lists: the notice goes to each, and is queued only if
// none took it. A notice too long for one post, an unregistered channel, a
// channel with no notify_to entry and a failed send queue instead, with the
// reason.
func (d *Daemon) sendNotification(ctx context.Context, channel, text string) error {
    if utf8.RuneCountInString(text) > MaxPostRunes {
        return d.queueSend(ctx, text, fmt.Sprintf("queued: the notice is longer than one post (%d runes); it is not split", MaxPostRunes))
    }
    if channel != "" {
        if reason := d.deliver(ctx, channel, text); reason != "" {
            return d.queueSend(ctx, text, reason)
        }
        return nil
    }
    var names []string
    for ch := range d.cfg.NotifyTo {
        names = append(names, ch)
    }
    sort.Strings(names)
    if len(names) == 0 {
        return d.queueSend(ctx, text, "queued: the user model names no channel and notify_to lists none")
    }
    var reasons []string
    delivered := false
    for _, ch := range names {
        if reason := d.deliver(ctx, ch, text); reason == "" {
            delivered = true
        } else {
            reasons = append(reasons, reason)
        }
    }
    if delivered {
        return nil
    }
    return d.queueSend(ctx, text, strings.Join(reasons, "; "))
}

// queueSend queues a notice that sendNotification could not deliver. If the
// queue cannot be written either, the error it returns keeps the reason the
// notice was not delivered, which NotifyNotice's second try would otherwise
// replace with the write's.
func (d *Daemon) queueSend(ctx context.Context, text, reason string) error {
    if q, ok := ctx.Value(noticeQueuedKey{}).(*atomic.Bool); ok {
        q.Store(true) // chapter 49: sendNotice counts this notice as queued, whatever its verdict's Reason says
    }
    if err := d.queueNotification(ctx, text, reason); err != nil {
        return fmt.Errorf("%s (the queue write failed: %w)", strings.TrimPrefix(reason, "queued: "), err)
    }
    return nil
}

// deliver sends text on one channel; "" is delivered, anything else is the
// reason it was not.
func (d *Daemon) deliver(ctx context.Context, channel, text string) string {
    text = d.redactValues(text) // chapter 48: a brokered value does not go out on a channel
    d.gw.mu.Lock()
    r := d.gw.chans[channel]
    d.gw.mu.Unlock()
    if r == nil {
        return "queued: no channel " + channel + " is registered"
    }
    conv, ok := d.cfg.NotifyTo[channel]
    if !ok {
        return "queued: notify_to has no conversation for channel " + channel
    }
    to := gateway.Address{Channel: channel, Conversation: conv, Peer: r.cfg.Principal}
    if err := r.ch.Send(ctx, to, text); err != nil {
        return "queued: " + channel + ": " + err.Error()
    }
    if o, own := ctx.Value(auditNoticeKey{}).(*noticeOutcome); own {
        o.sent.Store(true) // the anchor notice reached the channel (and is not itself a send record)
    } else {
        d.record(audit.Record{Kind: "send", Actor: "daemon", Subject: channel, // chapter 48: a notice, by channel and length
            Attrs: map[string]string{"conversation": conv, "bytes": strconv.Itoa(len(text))}})
    }
    d.logf("notify: sent on %s", channel)
    return ""
}

The queue. A notice that did not interrupt, or could not be delivered, is one line of Dir/notify.jsonl: the time, the notice and the reason, written 0600, through a no-follow open, and fsynced. It keeps the newest 1,000 entries, trimmed at start and whenever an append takes the file past 2,000. aecd queue prints the newest 20, oldest first, and says when older ones exist; -all prints everything.

// Queued is one line of Dir/notify.jsonl.
type Queued struct {
    At     time.Time `json:"at"`
    Text   string    `json:"text"`
    Reason string    `json:"reason"`
}

// MaxQueueEntries is how many entries notify.jsonl keeps at start: the
// newest.
const MaxQueueEntries = 1000

// queueAppend writes one line of the queue; a test replaces it.
var queueAppend = appendLine

// queueNotification appends to Dir/notify.jsonl (0600, no symlink,
// fsynced): the daemon's own words, with the model's text fenced.
func (d *Daemon) queueNotification(ctx context.Context, text, reason string) error {
    owner, owned := ctx.Value(noticeOwnerKey{}).(*noticeOwner)
    if owned && !owner.claimed.CompareAndSwap(false, true) {
        return nil // the deadline already queued this notice
    }
    if detail, _ := ctx.Value(noticeDetailKey{}).(string); detail != "" {
        if suffix := " (job error: " + detail + ")"; !strings.HasSuffix(reason, suffix) {
            reason += suffix
        }
    }
    st := &d.schedStat
    st.qmu.Lock()
    defer st.qmu.Unlock()
    f, err := openAppend(filepath.Join(d.cfg.Dir, "notify.jsonl"))
    if err != nil {
        if owned {
            owner.claimed.Store(false) // nothing was queued: the notifier's second try may
        }
        return err
    }
    b, err := json.Marshal(Queued{At: d.Now(), Text: text, Reason: reason})
    if err == nil {
        err = queueAppend(f, b)
    }
    f.Close()
    if err != nil {
        if owned {
            owner.claimed.Store(false) // a write that failed at its fsync left the line: the retry may queue it twice
        }
        return err
    }
    st.qcount++
    if st.qcount > 2*MaxQueueEntries {
        d.trimQueueLocked() // past twice the kept number: back to the newest MaxQueueEntries
    }
    return nil
}

The terminal needs a filter of its own although the chat has the fence. The fence protects a markdown renderer, and a terminal is not one: it obeys escape sequences, and it prints bidirectional controls and zero-width characters that reorder or hide text. What reaches aecd queue, aecd jobs and aecd status, aecd send’s final text and the questions of -confirm and -approve tty, aecd resolve, every error line, and the daemon’s stderr sinks, includes model text, a provider’s error, a server’s words inside an error, a call id read back from the ledger, and a job’s name and reason. All of it goes through the filter (termtext.Line, in a package of its own because chapter 26’s aec, chapter 37’s aec-eval, chapter 39’s aec-judge and chapter 24’s aec-capture print a model’s final text or a provider’s error and use it too), which escapes C0 (a tab as \t), DEL, C1, U+2028 and U+2029, every character of Unicode category Cf and invalid UTF-8, doubles a backslash so an escape in the text cannot pass for one of the filter’s, and cuts a line at 4,096 runes with a count. A newline is escaped like any control character, so aecd queue splits a text into lines first. Two rules say when it is applied. A final text, an error line and a line of the resolve table are written through it only when the stream is a terminal (a character device); to a pipe or a file they are written byte for byte, so a redirect, a golden and the kill -9 rig see what the model wrote. A final text has lines of its own, so it is filtered line by line with a tab kept and no line cut (termtext.Text: a reader who loses the end of a long line has lost the answer); an error and a resolve line are one message each, so they go through termtext.Line whole and a newline in a call id or a server’s words is escaped, and cannot start a line that looks like another. A question to the principal, which has no other reader, filters the call’s name, id and arguments whatever the stream is.

// MaxLineRunes caps a line Line returns.
const MaxLineRunes = 4096

// Line renders a string that can carry model or provider text so a
// terminal cannot be driven by it: every control character (C0, DEL, C1) and
// every bidirectional control, the line and paragraph separators and any
// byte that is not UTF-8 becomes an escape (\x1b, \u202e), and a backslash
// is doubled so an escape in the text cannot pass for one of ours. Every
// character of Unicode category Cf (zero-width characters, the word joiner, the
// byte order mark, soft hyphen, the invisible operators, the tag block, as
// well as the bidirectional controls) is escaped too: none drives a terminal,
// but they hide text. A tab is shown as \t. A newline is escaped like any
// control character, so a text with lines is split first (aecd queue does)
// and a one-line message is not broken by it. A line is capped at
// MaxLineRunes runes, then a marker with the count of those left out.
func Line(s string) string {
    if n := utf8.RuneCountInString(s); n > MaxLineRunes {
        i := 0
        for k := 0; k < MaxLineRunes; k++ {
            _, w := utf8.DecodeRuneInString(s[i:])
            i += w
        }
        return escape(s[:i], false) + fmt.Sprintf(" [%d more runes not shown]", n-MaxLineRunes)
    }
    return escape(s, false)
}

// escape is the rule Line states, without the cap. keepTab leaves a tab as
// itself: a final text's columns are the reader's to read.
func escape(s string, keepTab bool) string {
    var b strings.Builder
    for i := 0; i < len(s); {
        r, n := utf8.DecodeRuneInString(s[i:])
        switch {
        case r == utf8.RuneError && n <= 1:
            fmt.Fprintf(&b, `\x%02x`, s[i])
        case r == '\\':
            b.WriteString(`\\`)
        case r == '\t' && keepTab:
            b.WriteByte('\t')
        case r == '\t':
            b.WriteString(`\t`)
        case r < 0x20 || r == 0x7f:
            fmt.Fprintf(&b, `\x%02x`, r)
        case r >= 0x80 && r <= 0x9f:
            fmt.Fprintf(&b, `\u%04x`, r)
        case r == 0x2028, r == 0x2029, unicode.Is(unicode.Cf, r):
            if r > 0xffff {
                fmt.Fprintf(&b, `\U%08x`, r)
            } else {
                fmt.Fprintf(&b, `\u%04x`, r)
            }
        default:
            b.WriteString(s[i : i+n])
        }
        i += n
    }
    return b.String()
}

What the reader must see goes to stderr whatever -v says. The daemon has two sinks. Log carries every ledger event and decision and needs -v. Warn is always on, through the filter. It carries a quiet window read in UTC because zone is unset (stated once: sched: the quiet window 22 to 07 is being read in UTC because "zone" is not set in aecd.json; set "zone" (for example "America/Los_Angeles") to read it in your local time, at start if the window was stated before, else when a decision first meets it), a scheduler that stopped and when it will restart, an abandoned or suspended job, a state file removed or quarantined, a job’s turn that stopped any way but final, a maintenance job that failed (once per episode), a re-run after an orderly stop and a newer slot that folded in a stopped one, a heartbeat that could not be written (once per episode), and a notice that could not be queued. The zone line exists because of the zone’s two readings: chapter 35 calls the hours local, an unset zone is UTC (chapter 40), and a reader who stated “between 22 and 7” on a host in Pacific time would otherwise have a window eight hours away from the one they meant without being told. An unset zone also means fire times in UTC, and nothing says so unless there is a quiet window.

The heartbeat. Heartbeat{Every, Task} is a job with a rounded period. Every rounds down to a cron period, the largest divisor of 60 minutes at most Every when it is under an hour (45m becomes */30), else the largest divisor of 24 hours at most Every, so the job fires at least as often as asked. It is an ordinary job (policy skip, timeout two minutes, notify, session job-__heartbeat) whose default task asks what has changed since the last run, and its result is an ordinary notice, through the gate. The file is another matter. Dir/heartbeat is written by the scheduler’s loop, at the check (Scheduler.Checked), atomically and through a no-follow writer: at the daemon’s first check, when a fire time of the heartbeat’s schedule lies after the last write and not after the check, and when the clock stepped back past the last write. The loop checks at every job’s fire times, a running job’s included.

// Heartbeat is the job that shows the scheduler's loop is alive: every Every
// it runs Task on its own session, and the daemon writes Dir/heartbeat
// (the liveness file a supervisor can check) at the loop's check when a fire time of the
// heartbeat's schedule has passed since the last write (Scheduler.Checked),
// apart from the run and whatever the run slot is doing. A fresh file proves
// the loop was alive at the time it holds; a check that is held up or a
// write that fails leaves the file older, and no bound on staleness is
// promised. It proves nothing about the run, a model, a channel or the control socket.
// Every is rounded down to a cron
// period: the largest divisor of 60 minutes that is at most Every when
// Every is under an hour, else the largest divisor of 24 hours that is at
// most Every, so the job always fires at least as often as asked.
type Heartbeat struct {
    Every time.Duration
    Task  string
}

// DefaultHeartbeatTask is the task when none is given.
const DefaultHeartbeatTask = "Heartbeat. In one line, say what has changed since your last run that the reader should know about, or that nothing has."

// HeartbeatName is the job's name and the stem of its session id.
const HeartbeatName = "__heartbeat"

// ErrHeartbeatEvery is a Heartbeat with no positive period: not "every
// minute" (a model turn a minute), an error.
var ErrHeartbeatEvery = errors.New("sched: a heartbeat needs a positive period")

// Err reports a Heartbeat that cannot be a job.
func (h Heartbeat) Err() error {
    if h.Every <= 0 {
        return ErrHeartbeatEvery
    }
    return nil
}

// Job is the heartbeat as a scheduler job (Skip: a heartbeat that was
// missed is not run late). A Heartbeat with no positive period yields a job
// with an empty cron line, which Check refuses.
func (h Heartbeat) Job() Job {
    task := h.Task
    if task == "" {
        task = DefaultHeartbeatTask
    }
    cron := ""
    if h.Err() == nil {
        cron = h.cron()
    }
    return Job{Name: HeartbeatName, Cron: cron, Task: task, Policy: Skip, Timeout: 2 * time.Minute, Notify: true}
}

// cron is the line Every rounds to (a sub-minute period is a minute).
func (h Heartbeat) cron() string {
    every := h.Every
    if every < time.Minute {
        every = time.Minute
    }
    if every < time.Hour {
        m := int(every / time.Minute)
        for ; 60%m != 0; m-- {
        }
        if m == 1 {
            return "* * * * *"
        }
        return fmt.Sprintf("*/%d * * * *", m)
    }
    hrs := int(every / time.Hour)
    if hrs > 24 {
        hrs = 24
    }
    for ; 24%hrs != 0; hrs-- {
    }
    if hrs == 1 {
        return "0 * * * *"
    }
    if hrs == 24 {
        return "0 0 * * *"
    }
    return fmt.Sprintf("0 */%d * * *", hrs)
}
// HeartbeatFile is the heartbeat's file name under Config.Dir.
const HeartbeatFile = "heartbeat"

// checked is Scheduler.Checked: called once per iteration of the scheduler's
// loop with the check time. It writes Dir/heartbeat when a fire time of the
// heartbeat's schedule lies in (the last touch, now] (and at the first check
// of the daemon's life, and when the clock stepped back past the last touch),
// whether or not the heartbeat's own run could start. A fresh file therefore
// proves one thing: the scheduler's loop was alive at the time written in it
// (the loop wakes at every fire time of every job, a running one included; a
// check that is held up or a write that fails leaves the file older, and no
// bound on staleness is promised). It does not prove that the
// heartbeat's run, or any run, started or finished, that a model answered,
// that a channel works, or that the control socket answers; and a file that
// is not fresh does not by itself prove the daemon is dead (a scheduler that
// stopped, or a check blocked on the state directory, leaves it stale too).
func (d *Daemon) checked(now time.Time) {
    st := &d.schedStat
    if !st.hbOn {
        return
    }
    st.hbMu.Lock()
    due := st.hbLast.IsZero() || now.Before(st.hbLast)
    if !due {
        n, ok := st.hbSpec.Next(st.hbLast)
        due = ok && !n.After(now)
    }
    st.hbMu.Unlock()
    if !due {
        return
    }
    if err := touch(filepath.Join(d.cfg.Dir, HeartbeatFile), now); err != nil {
        st.hbMu.Lock()
        first := !st.hbBad
        st.hbBad = true
        st.hbMu.Unlock()
        if first { // once per episode of failures, not at every check
            d.warnf("heartbeat: %v (not warned of again until a write succeeds)", err)
        }
        return
    }
    st.hbMu.Lock()
    st.hbLast, st.hbBad = now, false
    st.hbMu.Unlock()
}

What a fresh file proves is one thing: the scheduler’s loop was alive at the time written in it. A check that is held up leaves the file older (the state directory; a suspension or abandonment notice that is being sent, which is cut off after NoticeDeadline, 30 seconds, and queued), and so does a write that fails, so no bound on staleness is promised. It does not prove that the heartbeat’s run started or finished, that a model answered, that a channel works or that the control socket does, and a stale file does not by itself prove the daemon dead. No later chapter reads it: chapter 51’s module renders whatever heartbeat the reader’s settings give, and its VM test sets none, because a heartbeat is a model turn that would consume a scripted reply. A watchdog that reads the file is the reader’s to write, and it may conclude no more than the above.

The two maintenance jobs. __derive runs chapter 35’s Derive when a memory service exists, snapshot.derive is positive and a deriver is configured; __rotate runs chapter 40’s Maintain (the log cut, the snapshot and the generation switch; listing ch40-memsvc-maintain) when snapshot.rotate is positive. Each is a job with the heartbeat’s rounding of its own period, policy skip and a ten-minute timeout, its own state file, and its own place on the one clock, so the lab can advance both by advancing the clock. A failed __derive or __rotate writes one warning per episode of failures and tells nobody. Names that begin with __ are the daemon’s and refused in aecd.json. A daemon whose embedder is "" has no memory service: no user model (the default one, which has soon as its level, no window and no channel), no maintenance jobs, and no urgency head. An ordinary notice from such a daemon is queued with “no decision model configured”, and a critical one is delivered to every notify_to channel.

Running one by hand. aecd jobs -run NAME sends job/run over the control socket, which only the principal’s uid can reach, and the scheduler runs the job once at its next check. The run stands for the check time and for no slot: it moves LL nowhere, has its own record in the state file (manual), and is served by a suspended job, since it is the way out. It is also how the lab’s crash tests start a run in a daemon whose clock is frozen, below.

The interruption rule

A run’s output reaches the reader only through Notifier, which reads the user model and, for a result notice, the urgency head. The user model is chapter 35’s: four forms matched as whole lines of the reader’s own messages, never read by a model. The urgency head is chapter 21’s registered urgency question, a proportional-odds head over four ordered levels, ignore, later, soon and now, with at_least[k] the probability of reaching level kk and level the median. Write pj=P(Y=j)p_j = P(Y = j) for the head’s four probabilities, shape (4,)(4,), and Fj=P(Y≤j)=∑i≤jpiF_j = P(Y \le j) = \sum_{i \le j} p_i, with F−1=0F_{-1} = 0. Since YY takes whole values, P(Y≥k)=1−P(Y≤k−1)=1−Fk−1P(Y \ge k) = 1 - P(Y \le k - 1) = 1 - F_{k-1}, which is at_least[k].

// Notifier decides whether a message from an unattended run interrupts the
// principal. It reads the deterministic user model (chapter 35: whole
// lines of the principal's own messages, never a model's reading of them)
// for the lowest level that may interrupt, the channels and the quiet
// hours. Quiet hours are the reader's: inside the window only a notice
// from a job the reader marked critical interrupts, and no score is
// consulted for anything else (no path from a model's score to the quiet
// window exists). Outside it a notice the daemon wrote itself (Notice.Own)
// interrupts with no score; for any other notice the notifier asks chapter
// 21's registered urgency head through chapter 28's decide for P(Y >= k),
// and interrupts when that probability reaches Threshold, the ratio of the
// two costs derived in the chapter (0.5 when unset: the median rule). An
// answer decide did not calibrate, or could not give, is queued with its
// reason.
// Send delivers an interruption to a channel (a readable user model that
// names none gives "", which the daemon reads as every channel the reader
// listed in notify_to); Queue records a message that did not interrupt. NotifyNotice
// queues the notice on every path that does not end in a delivery, so
// nothing is dropped. Clock is required (the window is read in the
// Location of the time it returns: the daemon's configured zone).
type Notifier struct {
    Model     *decide.Model
    Embedder  decide.Embedder
    User      func(ctx context.Context) (memsvc.UserModel, error)
    Threshold float64
    Clock     func() time.Time
    Send      func(ctx context.Context, channel, text string) error
    Queue     func(ctx context.Context, text, reason string) error
    // Warn, when set, receives what the reader must see whatever the log's
    // level: a critical notice, or the daemon's own, held because the allowed
    // channels could not be known, and a notice that could not be queued.
    Warn func(format string, args ...any)
}

// Verdict is one decision. Level is the head's median level; AtLeast is
// P(Y >= K) where K is the index of the level that may interrupt (after the
// quiet-hours rule); Reason says why, in the words the queue records.
type Verdict struct {
    Interrupt bool
    Channel   string
    Level     string  // the median level
    AtLeast   float64 // P(Y >= k)
    K         int
    Reason    string
}

The reader’s marking comes first. DecideNotice reads the user model for its channels and then, before any score is taken, decides a critical notice. Job.Critical is a boolean in aecd.json; the daemon copies it into Notice.Critical and nowhere else does. A critical notice interrupts in the quiet window and under the threshold alike, on the user model’s first channel, and no model is consulted: a daemon with no gate weights delivers it, and a result notice it queues. If the user model cannot be read, the channels the reader allows are unknown, so nothing is sent, the notice is queued with that reason, and the warning sink says so.

What cannot set the flag, with the test for each. A task’s text: critical: true as a line of a task is a line of a task (TestCritical plants a notice whose text begins with that line and sees it held). A job’s name: a job called critical is an unmarked job (TestCriticalIsNotInTheName). A model’s output: the final text is inside the notice and never read for the flag. A peer: jobs are configuration, and nothing in memsvc, a gateway or a session can create one. A scheduled run’s own session: nothing in a turn reaches Config. The file: the marking is as safe as aecd.json, which an approved write_file or terminal call in the reader’s own session can edit (the same edit clears a suspension); in an unattended run terminal is always marked and refused, and write_file is marked for any path outside the session’s workspace, so the file is out of a job’s reach as long as it is not kept inside a workspace (a job reaches write_file only by naming it).

Everything else is the gate (a notice the daemon wrote itself is decided before it, as the quiet-hours paragraph below says), and its core is a decision under two costs. Let p=P(Y≥k)p = P(Y \ge k) for kk the index of the user model’s MinUrgency, ci>0c_i > 0 the cost of an interruption the reader did not want and cm>0c_m > 0 the cost of a wanted one that did not happen. Interrupting costs cic_i when the message was below kk, which has probability 1−p1 - p, so its expected cost is ci(1−p)c_i (1 - p). Not interrupting costs cmc_m when the message was at least kk, expected cmpc_m p. Interrupt when cmp≥ci(1−p)c_m p \ge c_i (1 - p), that is, when p(ci+cm)≥cip (c_i + c_m) \ge c_i, that is,

p≥τ=cici+cm. p \ge \tau = \frac{c_i}{c_i + c_m}.

The threshold depends on the ratio of the costs and on nothing else. threshold in aecd.json is τ\tau, in (0,1](0, 1], and 0.5 when it is left out. At τ=1/2\tau = 1/2 this is the median rule. p≥1/2p \ge 1/2 is 1−Fk−1≥1/21 - F_{k-1} \ge 1/2, which is Fk−1≤1/2F_{k-1} \le 1/2. The median is m=min{j:Fj≥1/2}m = \min\{j : F_j \ge 1/2\} (the running sum in decide’s scoreAnswer), and m≥km \ge k exactly when Fk−1<1/2F_{k-1} < 1/2. The two agree except where Fk−1=1/2F_{k-1} = 1/2 exactly. There the threshold rule interrupts and the median rule does not, a tie the code breaks toward interrupting because the derivation’s inequality is ≥\ge; at the tie the two expected costs are equal, so either action is Bayes-optimal. TestThresholdRule finds no disagreement on 10,000 random four-level distributions and builds the tie (p=(0.25,0.25,0.25,0.25)p = (0.25, 0.25, 0.25, 0.25), k=2k = 2). Why it matters: chapter 21 proved that level does not move with the head’s temperature, so at τ=1/2\tau = 1/2 the rule inherits that. At any other τ\tau the rule depends on the probabilities being calibrated, which is why the notifier queues an answer decide did not calibrate (RequireCalibrated) and why chapter 20’s calibration is not optional here.

// Decide applies the rule to text without sending anything (a notice from
// no job, not critical).
func (n *Notifier) Decide(ctx context.Context, text string) (Verdict, error) {
    return n.DecideNotice(ctx, Notice{Text: text})
}

// ErrNoClock is a notice not marked critical, judged by a Notifier with no Clock: the
// quiet window cannot be read, and "no clock" must not mean "no window".
var ErrNoClock = errors.New("sched: the notifier has no clock, so the quiet window cannot be read")

// DecideNotice applies the rule to one notice. The reader's own marking
// is decided first, as a deterministic branch that consults no score and
// consults the reader's model only for the channel: a critical job's notice
// interrupts, in quiet hours and under the threshold alike, on the user
// model's first channel (a readable model that names none gives the empty
// channel, which the daemon reads as every channel the reader listed). If the
// model cannot be read the channels the reader allows are unknown, so
// nothing is sent: the verdict is a queueing, with the reason, and Warn is
// told.
// Then the quiet window, which is the reader's own marking: inside it the
// notice is queued and NO score is taken. Outside it a notice the daemon wrote
// itself (Own) interrupts on the user model's first channel and no score is
// taken: neither the head, the embedder, the threshold nor the user model's
// minimum level is consulted, so a daemon with no decision model delivers it.
// If the user model cannot be read, an Own notice is queued, as a critical one
// is (the channels the reader allows are unknown), and Warn is told.
// Everything else is the gate: the user model's level, then the urgency
// head's P(Y >= k) against the threshold.
func (n *Notifier) DecideNotice(ctx context.Context, no Notice) (Verdict, error) {
    var um memsvc.UserModel // no User: the reader has said nothing
    var userErr error
    if n.User != nil {
        um, userErr = n.User(ctx)
    }
    min := um.Interrupt.MinUrgency
    if min == "" {
        min = DefaultMinUrgency
    }
    k := levelIndex(min)
    if userErr == nil && k < 0 {
        userErr = fmt.Errorf("sched: the user model names an urgency level %q that is not one of %v", min, memsvc.Levels)
    }
    v := Verdict{K: k}
    if userErr == nil && len(um.Interrupt.Channels) > 0 {
        v.Channel = um.Interrupt.Channels[0]
    }
    if no.Critical {
        if userErr != nil {
            v.Channel = ""
            v.Reason = fmt.Sprintf("queued: job %q is marked critical, but the user model could not be read, so the channels the reader allows are unknown and nothing was sent (%v)", no.Job, userErr)
            n.warnf("notify: job %s: %s", no.Job, v.Reason)
            return v, nil
        }
        v.Interrupt = true
        v.Reason = fmt.Sprintf("interrupt: job %q is marked critical in the configuration; no score consulted", no.Job)
        return v, nil
    }
    if userErr != nil {
        if no.Own {
            v.Channel = ""
            v.Reason = fmt.Sprintf("queued: the daemon's own notice from job %q, but the user model could not be read, so the channels the reader allows are unknown and nothing was sent (%v)", no.Job, userErr)
            n.warnf("notify: job %s: %s", no.Job, v.Reason)
            return v, nil
        }
        return Verdict{}, userErr
    }
    if n.Clock == nil {
        return Verdict{}, ErrNoClock
    }
    if now := n.Clock(); InQuiet(um.Interrupt.Quiet, now.Hour()) {
        v.Reason = fmt.Sprintf("queued: quiet hours (%02d to %02d, read in %s): only a job the reader marked critical interrupts; no score consulted",
            um.Interrupt.Quiet[0], um.Interrupt.Quiet[1], now.Location())
        return v, nil
    }
    if no.Own {
        v.Interrupt = true
        v.Reason = fmt.Sprintf("interrupt: the daemon's own notice from job %q, outside quiet hours; no score consulted", no.Job)
        return v, nil
    }
    if n.Model == nil || n.Embedder == nil {
        return Verdict{}, ErrNoModel
    }
    text := cutRunes(no.Text, MaxNotifyText)
    input, err := json.Marshal(map[string]any{"state": text, "questions": map[string]any{"urgency": Urgency}})
    if err != nil {
        return Verdict{}, err
    }
    resp, err := n.Model.Decide(ctx, n.Embedder, input, "")
    if err != nil {
        v.Reason = "queued: the urgency head did not answer: " + err.Error()
        return v, nil
    }
    if err := decide.RequireCalibrated(resp); err != nil {
        v.Reason = "queued: " + err.Error()
        return v, nil
    }
    a := resp.Answers["urgency"]
    // decide's Level is the legend text ("soon: deal with it within the
    // hour"); the verdict names the level alone.
    if med, ok := a.Decision.(int); ok && med >= 0 && med < len(memsvc.Levels) {
        v.Level = memsvc.Levels[med]
    } else {
        v.Level, _, _ = strings.Cut(a.Level, ":")
    }
    v.AtLeast = 1 // P(Y >= 0)
    if v.K > 0 {
        v.AtLeast = a.AtLeast[strconv.Itoa(v.K)]
    }
    tau := n.Threshold
    if tau <= 0 {
        tau = DefaultThreshold
    }
    v.Interrupt = v.AtLeast >= tau
    if v.Interrupt {
        v.Reason = fmt.Sprintf("interrupt: P(at least %s) = %.3f >= %.3f", memsvc.Levels[v.K], v.AtLeast, tau)
    } else {
        v.Reason = fmt.Sprintf("queued: P(at least %s) = %.3f < %.3f", memsvc.Levels[v.K], v.AtLeast, tau)
    }
    return v, nil
}

// cutRunes shortens text to at most max bytes without splitting a rune.
func cutRunes(text string, max int) string {
    if len(text) <= max {
        return text
    }
    i := max
    for i > 0 && !utf8.RuneStart(text[i]) {
        i--
    }
    return text[:i]
}

// Notify decides and then sends or queues; the Verdict is what it did.
func (n *Notifier) Notify(ctx context.Context, text string) (Verdict, error) {
    return n.NotifyNotice(ctx, Notice{Text: text})
}

// NotifyNotice is Notify for a notice with a job and a marking. Every path
// that does not end in a delivery queues the notice with its reason: a
// decision that failed (no model, no clock, an unreadable user model, a
// head that did not answer) and a Send that failed. The returned error is
// non-nil only when the notice could not be queued either.
func (n *Notifier) NotifyNotice(ctx context.Context, no Notice) (Verdict, error) {
    queue := func(reason string) error {
        if no.Detail != "" {
            reason += " (job error: " + no.Detail + ")"
        }
        return n.enqueue(ctx, no.Text, reason)
    }
    v, err := n.DecideNotice(ctx, no)
    if err != nil {
        v.Interrupt = false
        v.Reason = "queued: " + err.Error()
        if errors.Is(err, ErrNoModel) {
            v.Reason = "queued: no decision model configured"
        }
        return v, queue(v.Reason)
    }
    if v.Interrupt {
        if n.Send == nil {
            return v, queue("queued: no Send")
        }
        if serr := n.Send(ctx, v.Channel, no.Text); serr != nil {
            v.Reason = "queued: send failed: " + serr.Error()
            return v, queue(v.Reason)
        }
        return v, nil
    }
    return v, queue(v.Reason)
}

func (n *Notifier) enqueue(ctx context.Context, text, reason string) error {
    if n.Queue == nil {
        return errors.New("sched: no Queue, and a notice that did not interrupt was not delivered: " + reason)
    }
    return n.Queue(ctx, text, reason)
}

Three more details of the listing. With nothing in the user model the level is soon, k=2k = 2. At k=0k = 0, P(Y≥0)=1P(Y \ge 0) = 1 is at least any τ≤1\tau \le 1, so “Interrupt me only for urgency ignore or above” interrupts on every message the head answers for. And every path on which the rule cannot be applied holds the notice back: a user model that cannot be read is an error (for a notice the daemon wrote itself, a queueing and a warning) and not the default model, a level in it that is not one of the four is an error, a notifier with no clock is ErrNoClock and not “no window”, and a head that did not answer or was not calibrated queues the notice with the reason. NotifyNotice turns each into a queueing, so nothing is dropped; the one way to lose a notice is a queue that cannot be written, and that is warned of.

Whether a notice from a job interrupts, in the order DecideNotice asks A decision in four questions, top to bottom on the left, with the outcome of a yes on the right. First: is the job marked critical in aecd.json. If yes, the notice interrupts, no score is taken, and it goes to the user model's first channel, or to every notify_to channel if the model names none. If no, second: is the hour inside the quiet window, read in the zone of aecd.json. If yes, the notice is queued and no score is taken, so only a critical job gets through the window. If no, third: did the daemon write the whole notice, which is true of every kind but a result that holds model text (a private session's result notice is the daemon's whole text). If yes, the notice interrupts on the user model's first channel, or on every notify_to channel if the model names none, with no score taken, so a daemon with no decision model delivers it. If no, fourth: does the urgency head's probability of at least level k reach the threshold tau, where k is the user model's MinUrgency and the head scores the framed notice text. If yes, the notice interrupts on the user model's first channel. If no, it is queued with the probability in its reason. A separate dashed box says that any failure on the way, an unreadable user model, no clock, a head that does not answer or is not calibrated, queues the notice with the reason; an unreadable user model queues a notice the daemon wrote itself too. Is the job marked critical in aecd.json? Is the hour in the quiet window? Read in the zone of aecd.json. Did the daemon write the whole text? Every kind but a result that holds model text. Does the head's P(Y at least k) reach τ? It scores the framed text. k: MinUrgency. τ: threshold. no no no no yes yes yes yes Interrupt. No score is taken. The user model's first channel, else every notify_to channel. Queue. No score is taken. Only a critical job gets through the window. Interrupt. No score is taken. The user model's first channel, else all notify_to channels. Interrupt, on the user model's first channel. Queue, with the probability and τ in the reason. Any failure on the way queues the notice with its reason: user model, clock or head.

Quiet hours. Inside the window no score is consulted, and only a critical job gets through. Outside it, a notice the daemon wrote itself (Own) interrupts on the user model’s first channel, again with no score: neither the head, the embedder, the threshold nor the user model’s minimum urgency level is consulted, so a daemon with no decision model delivers it. The order in DecideNotice is therefore critical, the user model, the clock, the window, the daemon’s own notice, the head. The window is chapter 35’s form, “Interrupt me only for urgency now between HH and HH”: hours, half-open [from,to)[\text{from}, \text{to}), wrapping midnight when from is after to, and from == to is no window. An edge is an hour: 06:59 is inside [22,7)[22, 7) and 07:00 is not, and a minute does not move it. It is read in the Location of the notifier’s clock, the daemon’s configured zone. The earlier reading of the form, in which a message whose urgency was now could still interrupt inside the window, is gone: the first version of this code let the head’s P(Y≥now)P(Y \ge \text{now}) reach the threshold and break through, and the review of it put the question to the reader, who answered that only critical jobs get through.

A model-scored now that opens the window is not built. The reader’s instruction was to build in user markings and discuss the pathway to a model urgency score without building it. What would have to be true before a model’s now could open the quiet window, the way a marking does:

  1. Calibration evidence on the reader’s own traffic. The head was fitted on a synthetic set (chapter 21’s 960 items) with a temperature from a held-out split of that set. Nothing says its probabilities mean anything on a job’s output at 03:00. The evidence is chapter 20’s reliability, and chapter 39’s discipline of a gold set the reader labelled, restricted to what matters: night-time messages the head scores at the top level, with the reader’s own verdict on each. How much that takes has a floor. With zero false interruptions among nn labelled top-level messages, the largest false-interruption rate still consistent at the 5% level solves (1−p)n=0.05(1 - p)^n = 0.05, so the data have to contain n=⌈ln0.05/ln(1−p)⌉n = \lceil \ln 0.05 / \ln(1 - p) \rceil of them to bound the rate by pp: 59 messages for p=0.05p = 0.05, 149 for 0.020.02 and 299 for 0.010.01 (a script, wntrmute), every one of them labelled by the reader, with no false interruption among them.
  2. An abstention rule. The head returns a distribution for any text, including text unlike anything it was fitted on. The rule has to say what the notifier does in the middle of the range, and at night the only safe answer is to queue; today the only abstention is calibrated: false, which is a property of the question and not of the input.
  3. A bound on the cost of a false “now”. At night cic_i is not the daytime cic_i, since the interruption is a wake-up, so τ\tau for the window is a different number from τ\tau outside it, and aecd.json has one threshold. A calibrated rate does not survive text an attacker writes, so the bound that would be needed is a cap, such as at most one score-opened interruption a night, and not a number in (0,1](0, 1].
  4. Who can write what is scored. The head scores the notice, and the notice carries the model’s text from a run that read tool results, a page or a message that someone else wrote. A score is a function of text an attacker can write; a marking in aecd.json is not. Whether injected text can raise the score is chapter 46’s question and has to have an answer before the first sentence of this list is worth anything. Chapter 46’s answer: for the stand-in head, book-authored text does (three of three payloads crossed the threshold), and for jev-lite it is not measured. The other direction is open in the built gate already: text a run read can lower the score and queue a notice the reader wanted. What limits it is that a queued notice is never dropped, and that the daemon’s own notices, which carry no model text, are never scored.
  5. Chapter 35’s rule. Only the reader’s own lines are policy. A score that opens the window would be the first exception, and the exception would be a model’s.

None of it is built, and the code says so by its shape: no path from a score to the quiet window exists. What the head gives today is the ordinal P(Y≥k)P(Y \ge k) consulted only outside the window and only for a result notice, and the text it scores is the framed notice (the daemon’s frame, the fence and the model’s text, to 8 KiB) and not the bare text of the job’s output. The head was fitted on chat-style messages, so a framed block of a job’s output is a different input from the one it was fitted on, which is one more reason the calibration evidence has to come from the reader’s own notices.

The worked example. TestLiveNotify is the chapter’s one live contact. It runs four messages through Notifier.DecideNotice twice, once with the real embedder (honcho-embed on dixie, through decide.HTTPEmbedder) and once with chapter 21’s hash stand-in on wntrmute, with a user model that says “Interrupt me only for urgency soon or above.” and a clock at noon, so no window. The embedder reads GET /v1/models immediately before every batch and refuses unless honcho-embed is exactly loaded, and sends ?autoload=false. It also runs chapter 28’s CheckEmbedder, which embeds the head’s probe texts and the card’s check texts and compares them with the vectors stored in the weights. Each of the two runs made 13 requests to dixie, 7 reads of /v1/models and 6 batches of embeddings, and loaded nothing. The file below is the test’s own output, go/labs/ch42/testdata/notify-dixie.txt; the two runs produced byte-identical files, and honcho-embed read loaded before each.

message                                                        level   P(>= soon)     verdict   stand-in: level P
Nightly backup finished; 0 files changed.                      later   0.000          queue     later 0.103
Reminder: the certificate on orion expires in 30 days.         later   0.261          queue     later 0.002
The build on hollis failed and the release is blocked.         now     1.000          interrupt later 0.163
Disk on straylight is at 99% and the router is refusing loads. now     1.000          interrupt soon 0.744

The left half is the head on honcho-embed’s vectors (embeddings from dixie, the head evaluated on wntrmute): the first two messages are queued, the certificate reminder at P(Y≥soon)=0.261P(Y \ge \text{soon}) = 0.261, and the last two interrupt at 1.0001.000 each. The right half is the same head fed the hash stand-in’s vectors, which are not honcho-embed’s, so the head is being asked about vectors it was never fitted on: its levels and probabilities carry no meaning beyond being deterministic (against τ=0.5\tau = 0.5 it would interrupt on the disk message, soon at 0.744, and queue the other three, and that means nothing). Two cautions on the left half. The probabilities are printed to three decimals, and 1.000 is a value of at least 0.9995, not a certainty. And the four texts are bare: the daemon would send each inside its frame and fence, and what the head makes of that is not measured here.

Walkthrough

The configuration. The chapter-specific keys of an aecd.json, an excerpt:

{
  "zone": "America/Los_Angeles",
  "heartbeat": "30m",
  "notify_to": {"mattermost": "<the conversation the principal reads>"},
  "jobs": [
    {"name": "summary", "cron": "@daily", "task": "Summarise what changed in the workspace today.",
     "missed": "catch_up_one", "notify": true, "critical": true},
    {"name": "check", "cron": "*/15 * * * *", "task": "Report any failing check.",
     "missed": "catch_up_all", "timeout": "5m"}
  ]
}

threshold is unset, so τ=0.5\tau = 0.5. summary runs at 00:00 Pacific; if the daemon was down at midnight it runs once when it comes up, with the task told which days it covers, and its result goes to the reader at any hour. check has no tools key, so it has the six default tools, and no notify, so its result is not sent; a failure of its turn raises a notice all the same. The heartbeat rounds 30m to */30 * * * *. aecd jobs prints one line per job, NAME cron="…" missed=POLICY last=T next=T, then in_flight=, last_stop=, dropped=, failed=, stops=, suppressed= and suspended when they apply, and quarantined (…) for a state file that cannot be read, and critical last (the shape TestJobsAndQueueCommands asserts: nightly cron="*/15 * * * *" missed=skip last= … critical).

A slot killed mid-run. The first trace runs through real processes: TestJobCrash (labs/ch42/crash_test.go) runs on chapter 40’s rig: the real aecd, the write barrier variant (a tool that holds a call in flight and records each time it runs), a scripted model, and one job, nightly, */15 * * * *, catch_up_all, tools ["barrier"]. The rig’s clock is frozen at 2026-10-01T00:00:00Z (-deterministic), so no timer can fire a slot. The test therefore starts the slot from a planted state file: a first daemon starts and stops, and the test writes nightly.json with last at 23:45 the day before, which makes the 00:00 slot missed at the next daemon’s first check. That is how a scheduled run reaches a real process under this clock; it is not a timer-fired slot, which TestTimerFiresASlot runs separately (in the lab, below).

  1. The daemon logs job nightly: 1 due and then barrier: in flight "c1". The state file now says in_flight 2026-10-01T00:00:00Z, attempts 1, crashes 1, and last still 23:45; the ledger has a begin for the call and no end.
  2. The test sends SIGKILL. The barrier’s counter file has one ran line.
  3. Offline, aecd resolve -session job-nightly prints a line containing -> abort:: chapter 40’s rule for a call in flight with an unknown outcome.
  4. A second daemon on the same directory logs job nightly: a run for 2026-10-01T00:00:00Z was in flight at the last stop (attempt 1) and job nightly: 1 due. The session has been opened and resolved by the time the run starts, so the model’s history ends with the aborted call answered. The scripted model starts over, so the barrier holds "c1" again; the test releases it and the log says job nightly: run for 2026-10-01T00:00:00Z: final.
  5. session/list shows job-nightly with a Resolved entry, action abort, name barrier. The counter file has two ran lines. aecd jobs shows last=2026-10-01T00:00:00Z and last_stop=final and no in_flight, and the state file has zero attempts and crashes and no suspended.

Two rules produced those lines and neither reaches into the other. Chapter 40’s closed the killed turn at the session’s open (step 3 and the Resolved entry): the write tool’s outcome was unknown, so nothing was re-run by the session and the model was told so. This chapter’s policy read in_flight (step 4) and, because the policy is catch_up_all, ran the slot again. A skip job would have run it only inside its grace, and the rig’s frozen clock makes the lateness zero. The tests cover the two variants beside it. TestJobCrashHeld never releases the barrier and stops the daemon with aecd shutdown: three orderly stops in a row leave in_flight kept, last_stop cancelled, attempts and crashes at 0 and failed at 0, so the stop counted toward neither bound, and the fourth daemon, the fourth start of one slot, finishes the run. TestJobCrashTwice kills the daemon in the barrier twice: the third daemon logs that the job’s last two runs were started and never ended, aecd jobs shows suspended and the slot still in_flight=, aecd queue holds the suspension notice, and the barrier ran twice and not three times; a run on request that ends releases it, after which the slot, started twice, is recorded as failed and not started a third time. -race covers the test process and not the aecd child, which is a separate binary.

A critical notice. The second trace is in-process: TestNotifyQueueAndSend (internal/daemon) gives a critical job ship and an ordinary one sweep, both with notify, a daemon with no urgency head, and a user model that says “Interrupt me only on channel mm.” The critical notice is sent on mm, to the conversation notify_to names, as the channel’s principal, and the text on the wire is the frame and the fenced result:

aecd job ship: result
```
all shipped
```

The ordinary one is queued, with the reason queued: no decision model configured and its own frame and fence; a failure notice from sweep would have been sent, since the daemon’s own notice is not scored and this daemon has no head to ask. With notify_to emptied, the same critical job’s next notice is queued with queued: notify_to has no conversation for channel mm, and a torn tail of notify.jsonl is dropped on read and is not an error.

Exercises

(a) The missed set for 0 */2 * * *. With LL at phase φ\varphi hours past a fire time (0≤φ<20 \le \varphi < 2) and a gap of gg hours, in a zone with no transition in the gap, how many runs does catch_up_all ask for, and for which φ\varphi is that one more than ⌊g/2⌋\lfloor g/2 \rfloor?

Answer

The */15 argument with two hours for the period gives ∣M∣=⌊(g+φ)/2⌋|M| = \lfloor (g + \varphi)/2 \rfloor. It exceeds ⌊g/2⌋\lfloor g/2 \rfloor exactly when the phase carries the fractional part of g/2g/2 over the next fire time: φ≥2−(gmod2)\varphi \ge 2 - (g \bmod 2). For g=3g = 3 and φ=1.5\varphi = 1.5: ⌊4.5/2⌋=2\lfloor 4.5/2 \rfloor = 2 against ⌊1.5⌋=1\lfloor 1.5 \rfloor = 1.

(b) A 30 1 * * * job in Europe/London, daemon up all day on 2026-03-29, the day clocks go forward from 01:00 to 02:00. When does it run? What does */30 1 * * * do on 2026-03-29 to 2026-03-31?

Answer

The wall time 01:30 does not exist on the 29th. The fixed-time rule fires it once, at the first instant after the gap, 02:00 BST, and then at 01:30 on the 30th and 31st (Next printed Mar 29 02:00 BST | Mar 30 01:30 BST | Mar 31 01:30 BST on wntrmute). */30 1 * * * is a wildcard line, so the wall clock is read as it is: there is no 01:xx on the 29th, nothing fires that day, and the next fires are 01:00 and 01:30 BST on the 30th and 01:00 on the 31st.

(c) A */15 job under skip kills the daemon during every run, and the daemon is restarted 20 minutes after each kill. Trace attempts, crashes and the slots from the first run, which starts at 10:15. Which bound stops it, and why does the other not?

Answer

The 10:15 run is started (attempts 1, crashes 1) and the daemon dies at 10:16. It comes back at 10:36: 10:15 is in flight and counts as missed, so M={10:15,10:30}M = \{10{:}15, 10{:}30\} and the newest, 10:30, is 6 minutes late against a grace of 7.5 and runs, with 10:15 dropped. That is a different slot, so attempts is 1 again, while crashes is 2. The daemon dies again, and at the next restart crashes has reached 2: the job is suspended and starts nothing. The per-slot bound never fired, since no slot was started twice; the per-job one did. With restarts right after each kill the same slot is started twice, and at the third restart both bounds have been reached at once; suspension takes precedence over abandonment, so the reader gets one notice.

(d) Show that τ\tau is unchanged when both costs are scaled by the same factor, and that τ>1/2\tau > 1/2 exactly when ci>cmc_i > c_m. For threshold: 0.8, say what the reader has said about the costs, and whether a message with p=0.7p = 0.7 interrupts.

Answer

τ=λci/(λci+λcm)=ci/(ci+cm)\tau = \lambda c_i / (\lambda c_i + \lambda c_m) = c_i/(c_i + c_m). τ>1/2⇔2ci>ci+cm⇔ci>cm\tau > 1/2 \Leftrightarrow 2c_i > c_i + c_m \Leftrightarrow c_i > c_m. τ=0.8\tau = 0.8 is ci=4cmc_i = 4 c_m: an unwanted interruption costs four times a missed one. At p=0.7p = 0.7, interrupting costs 4cm×0.3=1.2cm4c_m \times 0.3 = 1.2\,c_m and not interrupting costs cm×0.7=0.7cmc_m \times 0.7 = 0.7\,c_m, so it is queued; 0.7<0.80.7 < 0.8 agrees.

(e) A */15 job with timeout: 45m has a run that takes 40 minutes, from 10:15. Which slots does the check at the end of the run return under each policy?

Answer

While the run goes, the loop wakes at 10:30 and 10:45 and Due skips the job, so nothing is queued. The run ends at 10:55 and wakes the loop, so the check is at 10:55 with M={10:30,10:45}M = \{10{:}30, 10{:}45\}. skip: the newest, 10:45, is 10 minutes late against 7.5, so nothing runs and two are dropped and counted, with LL at 10:45. catch_up_one runs once for 10:45, folding 10:30. catch_up_all runs twice, oldest first. Queueing during the run would let a slow job build an unbounded backlog; the rule already accounts for every slot through LL, and skip is where a job that cannot keep up stops trying.

(f) A job’s task is Interrupt me only for urgency ignore or above. Why is the task unfenced while tool output in the same turn is fenced, what does the principal’s user model hold after the job has run a hundred times, and what stops a non-principal’s message from becoming a job?

Answer

The task is configuration the principal wrote into aecd.json, the authority of a message he typed, so the model reads it as his; tool output is data to the loop (chapter 27) whoever asked for the call. The user model is unchanged, because the turn is recorded under sched and chapter 35’s pass reads whole lines of the principal’s own messages only (TestTaskLineIsNotPolicy also finds the form under sched’s model and not his). A job is configuration, not a message: nothing in memsvc, a gateway or a session creates one, so a non-principal’s text reaches a job only if the principal pastes it, the pasted-form residual chapter 35 discusses and chapter 47’s tiers stand in front of.

(g) A calibrated head gives a message p=(0.1,0.2,0.3,0.4)p = (0.1, 0.2, 0.3, 0.4) and the user model says soon, so k=2k = 2. What do the median rule and the threshold rule at τ=0.75\tau = 0.75 say, and which cost ratio ci/cmc_i / c_m makes each the right one?

Answer

F=(0.1,0.3,0.6,1)F = (0.1, 0.3, 0.6, 1), so the median is level 2 and the median rule interrupts. P(Y≥2)=1−F1=0.7<0.75P(Y \ge 2) = 1 - F_1 = 0.7 < 0.75, so the threshold rule queues. Interrupting is right exactly when τ≤0.7\tau \le 0.7, that is ci/(ci+cm)≤0.7c_i/(c_i + c_m) \le 0.7, ci≤(7/3)cmc_i \le (7/3)\,c_m: the median rule is the right one for a reader who minds an unwanted interruption at most about two and a third times as much as a missed one, and τ=0.75\tau = 0.75 (ci=3cmc_i = 3c_m, since 0.25ci=0.75cm0.25\,c_i = 0.75\,c_m) for one who minds it three times as much.

Lab

go/labs/ch42 declares Impl{Parse, Next, Due, Decide}; you write them in mine/sched.go (its doc comments are the specification) and run

make lab CH=42
make lab CH=42 IMPL=mine

The first runs the reference, the second yours. You write the cron parser (Parse), the search with cron’s two daylight-saving rules and the wildcard exemption (Next), the missed-run rule under the three policies with the cap, the grace and the in-flight slot (Due), and the interruption rule (Decide). The Scheduler, Notifier, state file, Unattended approver, Heartbeat, chapter 21’s registered question and chapter 28’s decide are provided.

  • TestParseAndNext runs the grammar, the refusals (a sixth field, @reboot, a value out of range, a range of names, a zero step) and Next’s fire times.
  • TestNextDST pins the transition days of the chapter’s table in six zones, London among them, where time.Date answers the second of two wall times.
  • TestMissedRunTable is */15 over gaps of 0 to 180 minutes under each policy, the cap, and the in-flight crash case. TestSkipGrace and TestSkipGraceIsTheSchedulersGrace pin the grace, its two clamps and that the scheduler’s own function is the one consulted.
  • TestMissedAcrossDST runs the missed set across the spring gap with the machine’s own zone set to four different ones.
  • TestUserModelForms, TestThreshold, TestQuietHours, TestQuietWindowEdges, TestCriticalNotice, TestCriticalIsNotInTheName, TestNoticeErrorPaths and TestOwnNotice run the notifier through chapter 21’s head with the hash stand-in: the four forms, the threshold at equality, a window in which no score is taken, the marking, the daemon’s own notice (sent outside the window with the embedder forbidden, queued inside it), and every path on which the rule cannot be applied.
  • TestJobCrash, TestJobCrashHeld and TestJobCrashTwice are the crash cases above, against the reference daemon on chapter 40’s rig. They are part of the gate. TestNoSecretsInTestdata scans the capture.

With the starter, the first test to reach a stub reports chapter 42 lab: not implemented. TestTimerFiresASlot runs a timer-fired slot through the reference daemon: the tagged binary holds its clock (AEC_CLOCK_START) a second before a * * * * * fire time until the test lets it run, so the scheduler’s own timer hands the slot out, and the test asserts order and occurrence, never a duration. What the lab cannot do: it cannot show that your state writes are fsynced. TestLiveNotify is the capture, AEC_LIVE=dixie only, and skips with the status it saw if honcho-embed is not loaded.

Further reading

  • crontab(5), Debian bookworm manual page: the grammar, the day rule and its example.
  • cron(8), Debian bookworm manual page: the daylight-saving paragraph.
  • Paul Vixie, cron at commit 9cc8ab1087bb9ab861dd5595c41200683c9f6712: cron.c (the three clock-change cases and the wildcard partition, :195–236, :299–326), entry.c (the star flags, :197–231) and job.c.
  • systemd.timer(5), the Persistent= setting (quoted from wntrmute’s systemd 261 page).
  • Margaret Mitchell, Avijit Ghosh and Samir Passi, AI Agents Push Humans Out of the Loop, arXiv 2608.23642, 2026: the thesis that oversight capacity degrades with use, from the abstract.
  • James O. Berger, Statistical Decision Theory and Bayesian Analysis, 2nd edition, Springer, 1985: the expected-cost decision rule (verified through its Crossref record; the chapter does not name a chapter of the book).
  • Nous Research, Hermes Agent at commit cca83848ec79a4a6a2ecc10285725559bf72c97c: cron/jobs.py, cron/scheduler_tick.py, cron/occurrences.py, cron/scheduler_provider.py and hermes_cli/config_defaults.py, as cited; and its cron documentation.
  • Rohit Ghumare, AI Engineering from Scratch, at commit 56c886c8821fc488b6f9608895c983d18f0d1ea3 (the head of main on 2026-10-11): the survey whose Phase 15 lessons 12 to 16 the scope paragraph answers.

results matching ""

    No results matching ""