Condition Monitor

Finishing a task is often only half the story. Sometimes you need an outcome to keep holding for the next two weeks, or you are waiting for one external milestone to finally happen. Left in your head, that turns into opening dashboards every morning — and the week you get busy, silence looks identical to "everything is fine."

Condition Monitor moves recurring verification off the requester's calendar and into the hub. You state in one sentence what should stay true (a condition monitor) or what single milestone you are waiting for (an event monitor); the hub runs fresh checks on a schedule until a firm end date, tells you only when the state actually changes, and uses an independent supervisor timer so a missing check shows up as unknown instead of hiding behind quiet skies.

Group Human in the loop
Also known as Alerting Rule, Dead Man's Switch
Core rule Never let a missing check look like a passing check
Defines records Monitor, Monitor check

Why manual habits — and silent scheduled jobs — both fail

After a billing fix ships, a vendor contract goes out for signature, or an operational policy takes effect, a requester naturally says "I'll keep an eye on that." Whether you check manually every morning or set up a quick cron script that emails you when something breaks, both approaches share the same blind spot: no news looks identical whether the check passed or nobody checked at all.

Skip two busy mornings and a regression sits unnoticed until a customer complains. Let an API token expire on a naive alert script and the script quietly crashes every hour while your inbox stays reassuringly empty.

Condition Monitor turns "I'll check on that later" into durable hub state governed by three structural rules:

  1. Store the check, cadence, grace window, and end date. Every monitor is either a condition (must keep holding) or an event (waits for one milestone), with a mandatory ends_at deadline so checks never burn budget forever.
  2. Separate the check timer from the supervisor timer. One timer launches fresh checkers when next_check_at arrives; an independent supervisor compares next_check_at + grace_seconds against the clock and records a missed check if no result arrives in time.
  3. Keep ok, triggered, error, and missed apart — and notify only on transitions. A failed or missed check moves the monitor to unknown and alerts its assignee to repair it, rather than faking healthy status or triggering a false alarm.

Why must the supervisor run on its own timer? If the code that detects missing checks asks the same job queue that launches checkers, a stalled scheduler or dropped queue job blinds both at once. Reading durable next_check_at timestamps directly against wall-clock time catches every failure mode from scheduler outages to crashed checkers.

Manual habit or naive cron Check lives in head or script Only alerts when a check sees trouble Days get busy or auth expires Scheduled checks stop completing No alert arrives in inbox Silence looks identical to all clear Regression found by a customer No record of when checking stopped Condition Monitor Hub stores Monitor & deadline Spec, interval, grace window, ends_at Check timer Starts checker Supervisor Flags missed Distinct check outcomes ok | triggered | error | missed Honest board & single notices Alerts on transitions; routes gaps to fix
Manual checks and naive cron alerts go silent whenever a check stops running. Condition Monitor pairs scheduled checker runs with an independent supervisor timer so blind spots become explicit missed checks routed for repair.

Architecture and participants

The requester states what to watch in one plain sentence. The lead agent turns that sentence into a Monitor record with a repeatable check_spec, cadence, grace window, and end date — and normally serves as the monitor's durable assignee_id so it can repair broken checks. The hub runs two independent timers, appends one Monitor check per due time, and computes the requester's status board directly from those two tables.

Requester States what to watch Hub Owns records & timers Lead agent Assignee & repairs Hub durable records & dual timers Monitor kind, spec, interval, grace, status, ends_at Monitor check (1 per due_at) outcome, notify, alert_assignee Check timer: starts fresh checker at due_at Supervisor timer: writes missed after grace Computed view (read-only) Checker (fresh session) Runs one check, reports outcome, exits Derived status board Watched rule, status, since, last check
The hub owns both records and both timers. A fresh checker runs one check and exits; if no result arrives within grace_seconds, the supervisor writes a missed check and alerts the assignee while the derived status board reflects the exact gap.
Requester
States in one sentence what should keep holding or which event to watch for; reads the derived status board and receives notices only when status changes or the monitor ends.
Lead agent (assignee)
Translates the requester's sentence into a deterministic check_spec, cadence, and end date, confirms the wording back to the requester, and repairs the monitor whenever checks error or are missed.
Checker
A short-lived agent or deterministic evaluator started by the hub for one due time. Observes the target, reports structured findings plus a one-sentence summary, and exits.
Hub (two timers)
Stores Monitor and Monitor check rows in one transaction per evaluation. Its Check timer starts due checks; its independent Supervisor timer records overdue checks as missed.
Derived status board
Read-only view computed directly from monitors and monitor_checks showing what is watched, how it stands, since when, and when it was last successfully checked.

Execution flow

Toggle between the normal condition flow — where steady passing checks stay quiet and the requester hears once on a break and once on recovery — and the missed-check path — where a checker fails silently, the supervisor timer flips status to unknown, and the lead agent repairs access while the board records the exact unchecked window.

Requester Hub Lead agent Checker 1. Watch: duplicate invoices stay at zero 2. Create monitor (60m, grace 10m, ends Dec 1) 3. 4:00 PM due -> start fresh checker 4. Report ok (0 found) -> silent (notify: false) 5. Thu 9:00 AM due -> start fresh checker 6. Report triggered (4 duplicates found) 7. Notify once: status changed to triggered 8. After fix: report ok (0 duplicates) 9. Notify once: condition holds again

The first passing check moves a new monitor from unknown to ok silently (notify: false). The hub notifies the requester once when the condition breaks and once when it holds again.

Interrupt vs. check-in: Setting notify: true marks that the requester must be told. Whether that notice interrupts immediately or waits for the next scheduled check-in is governed by Question Inbox interrupt rules.

Concrete examples

Condition Monitor supports two flavors using the exact same tables: an event monitor waiting for a single milestone before a deadline, and a condition monitor guarding a rule that must keep holding after work closes.

Example 1 — External security sign-off deadline

No code · Event monitor
Statement
"Let me know when the security team approves the release, or on Friday if they haven't."
Monitor setup
The lead agent registers an event monitor checking the shared approval tracker every 2 hours (grace_seconds: 600, ends_at: Friday 17:00). While approval is still pending, each check records ok silently.
Resolution
If the security team approves on Thursday at 2:00 PM, the check records triggered, notifies the requester once, and ends the monitor immediately (ended_at set, next_check_at cleared). If Friday at 5:00 PM arrives with no approval, the final check sets notify: true so the requester still gets a definitive closing update.

Example 2 — Duplicate invoices stay at zero

Simple ops/engineering · Condition monitor
Statement
"After the billing fix ships, duplicate invoices stay at zero through December 1."
Monitor setup
The lead agent creates a condition monitor running every 60 minutes (interval_seconds: 3600, grace_seconds: 600, ends_at: Dec 1) with the lead agent as assignee_id.
Trigger & gap
Steady zero counts remain quiet on the board. When database credentials expire on Wednesday at 5:00 PM and the checker exits silently, the supervisor writes a missed check at 5:10 PM, flips status to unknown, and alerts the lead agent to renew access. When four duplicates appear Thursday at 9:00 AM, status flips to triggered and notifies the requester once — and once again on Friday when a second fix restores the count to zero.

What this pattern is NOT — Job waits or worker liveness checks

Negative example
Situation
Pausing a worker job until CI passes so that same job restarts automatically, watching whether an active worker is hung mid-task, or creating a monitor whose only action is "please open this dashboard and look."
Why skip it
A condition that restarts a paused job belongs to Resumable Wait; liveness tracking of active workers belongs to Progress Heartbeat. And a check that still needs the requester's own eyes removes no cognitive load at all.

When to use and when to skip

Use Condition Monitor when

  • The requester says "I'll keep checking on that later," or a guarantee must keep holding after its original job closes.
  • The hub or an agent can evaluate the check autonomously from data it is authorized to read.
  • The check is deterministic enough that two runs over the same data produce the same outcome.
  • Knowing when the check last succeeded matters just as much as knowing when it failed.

Skip it when

  • The event should automatically restart a paused job (use Resumable Wait instead).
  • You are monitoring whether an active worker is still making progress (use Progress Heartbeat).
  • The check requires human judgment or eyeballs every time ("please look at this chart").
  • No bounded end date makes sense and the rule belongs in permanent infrastructure monitoring rather than a requester-scoped watch.

Data model and hub invariants

Condition Monitor defines two durable tables — monitors and monitor_checks — referencing parties and requests from Orchestrator-Workers. Storing each evaluation in monitor_checks alongside the current state on monitors lets the hub update both in one database transaction while preserving a complete audit trail of every due slot, including missed ones.

Monitor PK id FK requester_id FK request_id? FK assignee_id kind statement check_spec interval_seconds grace_seconds status status_since next_check_at? ends_at ended_at? created_at Monitor check PK id FK monitor_id due_at ran_at? FK ran_by_id? outcome observed? summary notify alert_assignee notified_at? Party PK id Request PK id 1 n monitor_id 1 n 1? n 1? Key uniqueness rule UNIQUE(monitor_id, due_at) Late reports never overwrite missed Fields ending in ? may be null · Dashed connectors denote optional foreign keys
Each Monitor names one requester, one durable assignee, and an optional Request, and owns one Monitor check per scheduled due time. Cardinalities follow the catalog convention (1, 1?, n).

Table: monitors

Column Postgres type Nullability Notes
id uuid NOT NULL, PK Unique monitor identifier.
requester_id uuid NOT NULL, FK References parties(id); recipient of status-change notices.
request_id uuid NULLABLE, FK References requests(id); null for standalone watches.
assignee_id uuid NOT NULL, FK References parties(id); durable owner (lead agent or hub) that repairs missed/errored checks.
kind text NOT NULL CHECK (kind IN ('condition', 'event')).
statement text NOT NULL Requester's plain-English sentence (e.g., "After the fix, duplicate invoices stay at zero.").
check_spec jsonb NOT NULL Deterministic query, threshold, or checker instructions.
interval_seconds integer NOT NULL Cadence between due times (CHECK (interval_seconds > 0)).
grace_seconds integer NOT NULL Allowed delay past due_at before supervisor records missed (CHECK (grace_seconds >= 0)).
status text NOT NULL CHECK (status IN ('ok', 'triggered', 'unknown')); starts as unknown.
status_since timestamptz NOT NULL Starts as created_at; updates only when status changes.
next_check_at timestamptz NULLABLE Next scheduled due time; null if and only if ended_at IS NOT NULL.
ends_at timestamptz NOT NULL Required deadline after which no further checks are scheduled.
ended_at timestamptz NULLABLE Timestamp when the monitor ended; null while active.
created_at timestamptz NOT NULL Creation timestamp; defaults to now().

Table: monitor_checks

Column Postgres type Nullability Notes
id uuid NOT NULL, PK Unique check evaluation identifier.
monitor_id uuid NOT NULL, FK References monitors(id).
due_at timestamptz NOT NULL Scheduled slot; UNIQUE (monitor_id, due_at).
ran_at timestamptz NULLABLE Actual execution time; null if and only if outcome = 'missed'.
ran_by_id uuid NULLABLE, FK References parties(id); checker or hub; null if and only if outcome = 'missed'.
outcome text NOT NULL CHECK (outcome IN ('ok', 'triggered', 'error', 'missed')).
observed jsonb NULLABLE Structured measurement (e.g., {"duplicates": 4, "customers": 1}); null when missed.
summary text NOT NULL One plain sentence shown to the requester on the status board.
notify boolean NOT NULL True when this check requires notifying the requester.
alert_assignee boolean NOT NULL True on every error or missed check so the assignee is alerted to repair — even when a brand-new monitor fails on its very first run.
notified_at timestamptz NULLABLE When the requester notice was delivered; stays null when notify = false.

Eight hub invariants

  1. 01
    One requester and one durable assignee per monitor Database constraint

    requester_id and assignee_id are NOT NULL foreign keys to parties(id). The assignee outlives any single checker session (always the lead agent or hub, never an ephemeral checker).

  2. 02
    At most one check per scheduled due time Database constraint

    UNIQUE (monitor_id, due_at) ensures every scheduled slot has a single authoritative outcome. If a sluggish checker reports after the supervisor already recorded that slot as missed, the hub rejects the late write with duplicate_due_at.

  3. 03
    Status derives strictly from the newest check outcome Hub guard

    ok maps to ok, triggered maps to triggered, and both error and missed map to unknown. A new monitor starts unknown with status_since = created_at.

  4. 04
    status_since advances only when status changes Hub guard

    Repeated ok checks keep the original timestamp, while recovering from unknown resets status_since to the recovery check — so a monitor never falsely claims a condition held across an unchecked gap.

  5. 05
    Runner fields match missed vs. executed outcomes Database constraint

    A CHECK constraint (mirrored by hub guards runner_required and missed_must_not_have_runner) ensures ran_at and ran_by_id are present if and only if outcome != 'missed'. Only the supervisor writes missed checks, and only once now > due_at + grace_seconds.

  6. 06
    Notify only on meaningful transitions or final check Hub guard

    notify is set true on any status transition or when the monitor ends, except the very first transition of a new monitor from unknown to ok (detected via status_since == created_at), which confirms baseline health without disturbing the requester.

  7. 07
    Ended monitors schedule no further checks Hub guard

    An event monitor ends on its first triggered check, and every monitor ends once due_at + interval_seconds > ends_at. Ending sets ended_at and clears next_check_at; further reports or repairs are rejected with monitor_ended.

  8. 08
    Error and missed checks always alert the assignee; only the assignee may schedule a repair re-check Hub guard

    record_check sets alert_assignee = true whenever outcome is error or missed, regardless of whether status changed — so a brand-new monitor that fails on its very first run (unknown → unknown) alerts its assignee immediately instead of staying silent until ends_at. Once fixed, only assignee_id may call mark_repaired (else only_assignee_may_repair), and only while status == 'unknown' (else monitor_not_unknown), returning an immediate replacement due_at (now when before next_check_at, otherwise the already-due next_check_at) so the out-of-band check runs right away without shifting the regular next_check_at grid.

Reference implementation

The same minimal monitor state machine, independent supervisor sweep, and assignee repair command in Lean, TypeScript, Python, and Elixir. Notice how cleanly the first-ok suppression, assignee repair alert, immediate re-check, and end-of-life rules fit into three pure transitions.

-- Hub guards, supervisor sweep & assignee repair for Condition Monitor (timestamps in epoch seconds)
import Std.Data.HashMap
import Std.Data.HashSet
open Std

inductive MonitorKind where
  | condition | event
  deriving Repr, BEq

inductive MonitorStatus where
  | ok | triggered | unknown
  deriving Repr, BEq, DecidableEq

inductive CheckOutcome where
  | ok | triggered | error | missed
  deriving Repr, BEq

structure Monitor where
  id : String
  requesterId : String
  assigneeId : String
  kind : MonitorKind
  statement : String
  intervalSeconds : Nat
  graceSeconds : Nat
  status : MonitorStatus := .unknown
  statusSince : Nat
  nextCheckAt : Option Nat
  endsAt : Nat
  endedAt : Option Nat := none
  createdAt : Nat
  deriving Repr

structure MonitorCheck where
  id : String
  monitorId : String
  dueAt : Nat
  ranAt : Option Nat := none
  ranById : Option String := none
  outcome : CheckOutcome
  summary : String
  notify : Bool := false
  alertAssignee : Bool := false
  deriving Repr

inductive HubError where
  | unknownMonitor | monitorEnded | duplicateDueAt | missedMustNotHaveRunner
  | runnerRequired | onlyAssigneeMayRepair | monitorNotUnknown
  deriving Repr, BEq

structure MonitorHub where
  monitors : HashMap String Monitor := {}
  recordedSlots : HashSet (String × Nat) := {}  -- (monitorId, dueAt)

namespace MonitorHub

def statusAfter : CheckOutcome → MonitorStatus
  | .ok => .ok
  | .triggered => .triggered
  | .error | .missed => .unknown

def getMonitor (hub : MonitorHub) (monitorId : String) : Except HubError Monitor :=
  match hub.monitors[monitorId]? with
  | some m => pure m
  | none => throw .unknownMonitor

def recordCheck (hub : MonitorHub) (monitorId : String) (check : MonitorCheck) (now : Nat) :
    Except HubError (Monitor × MonitorCheck × MonitorHub) := do
  let m ← hub.getMonitor monitorId
  if m.endedAt.isSome then throw .monitorEnded

  let slot := (monitorId, check.dueAt)
  if hub.recordedSlots.contains slot then throw .duplicateDueAt

  if check.outcome == .missed then
    if check.ranAt.isSome || check.ranById.isSome then throw .missedMustNotHaveRunner
  else
    if check.ranAt.isNone || check.ranById.isNone then throw .runnerRequired

  let nextStatus := statusAfter check.outcome
  let changed := nextStatus != m.status
  -- A new monitor's first passing check confirms baseline health without alerting.
  let firstOk := nextStatus == .ok && m.status == .unknown && m.statusSince == m.createdAt
  -- An out-of-band repair check before nextCheckAt keeps the regular schedule grid intact.
  let nextDue := match m.nextCheckAt with
    | some next => if check.dueAt < next then next else check.dueAt + m.intervalSeconds
    | none => check.dueAt + m.intervalSeconds
  let ended := (m.kind == .event && nextStatus == .triggered) || nextDue > m.endsAt

  let monitor := { m with
    status := nextStatus
    statusSince := if changed then now else m.statusSince
    nextCheckAt := if ended then none else some nextDue
    endedAt := if ended then some now else none }
  let check := { check with
    notify := (changed && !firstOk) || ended
    -- Always alert the assignee on error/missed, even when a new monitor fails on its first run.
    alertAssignee := check.outcome == .error || check.outcome == .missed }
  let hub := { hub with
    monitors := hub.monitors.insert monitorId monitor
    recordedSlots := hub.recordedSlots.insert slot }
  pure (monitor, check, hub)

-- Assignee triggers an immediate replacement check while keeping nextCheckAt on the regular grid.
def markRepaired (hub : MonitorHub) (monitorId actorId : String) (now : Nat) :
    Except HubError (Monitor × Nat) := do
  let m ← hub.getMonitor monitorId
  if m.endedAt.isSome || now > m.endsAt then throw .monitorEnded
  if m.assigneeId != actorId then throw .onlyAssigneeMayRepair
  if m.status != .unknown then throw .monitorNotUnknown

  let immediateDueAt := match m.nextCheckAt with
    | some next => if now < next then now else next
    | none => now
  pure (m, immediateDueAt)

-- Independent supervisor timer: sweeps overdue monitors directly by nextCheckAt + graceSeconds.
-- `newId` stands in for a UUID generator; it is given a running count of missed checks.
def sweepOverdue (hub : MonitorHub) (now : Nat) (newId : Nat → String) :
    Except HubError (List MonitorCheck × MonitorHub) :=
  hub.monitors.values.foldlM (init := ([], hub)) fun (missed, hub) m => do
    match m.endedAt, m.nextCheckAt with
    -- Nat subtraction stops at 0, so a check that isn't due yet is never overdue
    | none, some next =>
      if now - next > m.graceSeconds then
        let chk : MonitorCheck := {
          id := newId missed.length, monitorId := m.id, dueAt := next, outcome := .missed
          summary := "The scheduled check did not report within its grace period." }
        let (_, saved, hub) ← hub.recordCheck m.id chk now
        pure (missed ++ [saved], hub)
      else
        pure (missed, hub)
    | _, _ => pure (missed, hub)

-- An error or missed check always leaves the monitor's status unknown.
theorem statusAfter_failure (o : CheckOutcome) (h : o = .error ∨ o = .missed) :
    statusAfter o = .unknown := by
  cases h <;> simp_all [statusAfter]

end MonitorHub

Trigger, missed check, repair, and late-report trace

Walking Example 2 (duplicate invoices stay at zero) through these guards shows quiet initial health, a supervisor-recorded missed check setting alert_assignee: true after the 10-minute grace window, rejection of a late report with duplicate_due_at, an immediate mark_repaired replacement check, and transition-only requester notifications:

Execution trace: Example 2 (duplicate invoices stay at zero)
1. hub.recordCheck(mon_dup_inv, chk_tue_1600: { dueAt: 16:00, outcome: "ok", ranBy: checker_1 })
   -> ok (status: unknown -> ok; first_ok suppresses alert: notify = false, alertAssignee = false; next = 17:00)

2. # Wed 17:00 checker fails auth and exits without reporting
   hub.sweepOverdue(now: Wed 17:10:01)  # 10m grace_seconds elapsed
   -> missed check recorded (status: ok -> unknown; notify = true, alertAssignee = true -> lead_1 alerted)

3. hub.recordCheck(mon_dup_inv, chk_wed_1700_late: { dueAt: Wed 17:00, outcome: "ok", ranBy: checker_2 })
   -> error: duplicate_due_at (slot Wed 17:00 is already finalized as missed)

4. hub.markRepaired(mon_dup_inv, actor: lead_1, now: Wed 17:40)
   -> immediateDueAt: Wed 17:40 (next_check_at stays on hourly grid: Wed 18:00)
   hub.recordCheck(mon_dup_inv, chk_wed_1740: { dueAt: Wed 17:40, outcome: "ok", ranBy: checker_3 })
   -> status: ok (next_check_at stays Wed 18:00; board records unchecked gap 16:00-17:40)

5. hub.recordCheck(mon_dup_inv, chk_thu_0900: { dueAt: Thu 09:00, outcome: "triggered",
     observed: { duplicates: 4, customers: 1 }, ranBy: checker_4 })
   -> status: triggered (status_since = Thu 09:00:21; notify = true -> requester told once)

6. hub.recordCheck(mon_dup_inv, chk_fri_1100: { dueAt: Fri 11:00, outcome: "ok",
     observed: { duplicates: 0 }, ranBy: checker_5 })
   -> status: ok (status_since = Fri 11:00:15; notify = true -> recovery notice sent once)

Tradeoffs and practical guidance

Condition Monitor frees the requester from manual polling while keeping blind spots honest. Weigh three practical costs before registering a monitor:

  • Ongoing check cost until ends_at: every scheduled run that launches an agent costs compute and tokens. Prefer lightweight deterministic queries where possible and always set a realistic end date.
  • Checking the wrong thing with high confidence: if the lead agent translates a requester's sentence into a buggy query or wrong table, the monitor will cheerfully report ok while the real problem grows.
  • Who watches the supervisor? An independent supervisor timer catches stalled checkers and dropped jobs, but if the hub itself goes down, external uptime monitoring must still watch the hub.

Practical implementation notes

  • Restate the monitor in plain English before activating: have the lead agent echo back its exact interpretation ("I will count duplicate invoices every 60 minutes until December 1 and tell you if the count exceeds zero") so misread criteria are caught before run one.
  • Debounce noisy thresholds: if a metric hovers near a threshold, require it to breach across consecutive checks or a minimum window (like Prometheus's for clause) before emitting triggered.
  • Query durable due times, never the job queue: the supervisor timer should sweep monitors directly where ended_at IS NULL AND next_check_at + grace_seconds < now(), because a lost queue entry is the exact failure it exists to expose.
  • Never merge triggered, error, and missed: treating a database timeout as triggered pages the requester about an infrastructure hiccup as if customer invoices broke; treating it as ok hides a real outage.

Known uses and related patterns

  • Prometheus alerting rules: evaluates conditions on a cadence and uses a for duration so transient spikes do not flap alerts before Alertmanager routes a notification.
  • Grafana Alerting: explicitly distinguishes NoData and Error evaluation states from threshold breaches so a broken data source is not mistaken for a healthy check.
  • Healthchecks.io: implements the classic dead man's switch with per-check intervals and grace periods, alerting whenever an expected heartbeat fails to arrive on time.
  • LangSmith Agent Server cron jobs: invokes an agent on a schedule with fixed input, though condition state transitions and missed-run tracking must be added by the surrounding application.
  • Volgenic: combines scheduled agent runs with dedicated threshold alarms for infrastructure health; Condition Monitor unifies those capabilities under one requester-facing state machine with explicit missed-check visibility.
  • Martin Fowler's HeartBeat pattern: in Patterns of Distributed Systems, a missing periodic signal triggers supervisor investigation; Condition Monitor applies that same principle to recurring business and engineering checks.

Related patterns

  • Derived Status Board — renders one computed status row per monitor so missed checks and unchecked gaps become immediately visible.
  • Question Inbox — decides whether a monitor's notify: true check waits for the next check-in or interrupts immediately via an interrupt rule.
  • Resumable Wait — most easily confused with Condition Monitor: a wait belongs to a job and resumes that job, whereas a monitor belongs to the requester and reports status changes.
  • Progress Heartbeat — watches every active worker automatically for execution progress, rather than watching a requester-defined condition.
  • Delegation Policy — lets the lead agent automatically reopen a fix when a monitor triggers, without waiting for human approval.
  • Orchestrator-Workers — defines the Party and Request records referenced by every monitor.