Skip to content

Scheduled tasks: fire an agent run on a cron schedule or at a future time, autonomously and durably #189

Closed
1 of 1 issue completed

Description

@JAORMX

Summary

Add a scheduler subsystem so an operator can register a saved prompt to run on a cron schedule (0 9 * * *, @every 30m) or once at a future time, and have mecatl drive that run autonomously, durably, and exactly-once across a multi-replica deployment — with no human present at fire time.

A scheduled fire mints a fresh top-level session per fire that goes through the normal run-entry funnel, but with "subagent-grade" defaults: bounded turn/token budgets, conservative posture, headless-safe ask handling, and a single captured deliverable. (See Session model for why it is a top-level session and not a literal child Subagent.)

This is the natural next capability on top of the cloud-native infrastructure already shipped in ADR 0027 (durable event log, session leasing, snapshot rehydration) and ADR 0048 (mecak8s, Redis store, k8s lease, drain gate). The hard parts — durable session state, single-writer exclusion across replicas, restart rehydration — are already solved; a scheduler is mostly a durable trigger registry plus a tick loop that calls the existing entry point.

Labels: enhancement, research, config, ui


Motivation

Autonomous, unattended recurring work is now a baseline expectation for agent platforms. Concrete uses for mecatl:

  • Nightly/periodic repo hygiene (dependency bumps, stale-branch cleanup, doc-drift sync).
  • Scheduled PR review or triage at the start of the workday.
  • One-shot "deferred work" / reminders ("in one week, remove this feature flag").
  • Monitoring-style checks that only escalate on a meaningful change.

Today mecatl can only run when a client drives a prompt. There is no way to say "run this every weekday at 9am" or "run this once next Tuesday."


Prior art (distilled from a cross-product survey)

We surveyed how other agent clients/harnesses do this. Key findings that shaped the design below:

Product Trigger Execution Per-fire context Notable
Hermes Agent (Nous, MIT) rel/interval/5-field cron/ISO/NL local daemon, 60s tick fresh isolated session; cron tools disabled inside cron sessions; optional context_from chaining atomic jobs.json; per-run output archive; fail-closed provider pinning; workdir jobs serialized (cwd is process-global)
ChatGPT Tasks NL only OpenAI cloud fresh 1-hour floor; per-plan active-task caps; push/email delivery
Claude Code Routines (/schedule) NL → UTC, presets, raw cron, API /fire, GH webhooks Anthropic cloud, fresh repo clone fresh; saved prompt primary 1-hour floor; no permission prompts (fully autonomous); writes only claude/* branches; network allowlist default
Claude Code /loop interval → 5-field cron in current CLI session carries session context max 50/session, 7-day auto-expire, 30-min jitter, Monitor tool to watch instead of poll
Goose (Block) 6-field cron local, tokio-cron-scheduler fresh session from recipe schedule.json; max_retries; pause/unpause/run_now
Devin / Cursor / Manus / Cline NL + 5-field cron + events cloud (Cline: local daemon) mix; Devin/Manus carry state Cursor 30-min run cap + egress allowlist + staged diffs; Cline daemon survives restart
Temporal / LangGraph Schedules / crons (cron + IANA TZ) durable-execution backend stateful vs stateless flavors event-history replay; the durability reference model

Cross-cutting patterns we are adopting:

  1. Cron is the machine interface; NL/presets are sugar on top. Everyone compiles NL down to cron. → We expose cron + one-shot first; NL parsing is a later layer.
  2. Two camps: bolt agents onto an external schedule trigger (n8n/Zapier/k8s CronJob) vs. make scheduled runs first-class with durability. The serious-platform differentiator is the second. → We build it first-class, reusing ADR 0027/0048 durability.
  3. Fresh-context-per-fire is the dominant default; carried-state is the premium opt-in. → Fresh per fire (v1); persistent-session continuation deferred to v2.
  4. Frequency floor + "at most one catch-up" are deliberate safety/cost levers. Nobody replays a backlog. → Default misfire policy = fire-once-now; configurable floor.
  5. Overlap is handled by locking/serialization, especially for filesystem/cwd-stateful jobs (Hermes serializes workdir jobs). → mecatl is already mutate-serial; we add singleton-per-schedule (skip if still running).
  6. Unattended-safety converges on a small gate set: scoped writes, egress allowlists, secrets in a vault, per-run resource caps, fail-closed provider pinning, explicit autonomy flags. → We reuse mecatl's posture ladder, headless ask model, secret-scrubbed env, and per-run budgets; add fail-closed model pinning.

Sources captured during research (selected): Hermes cron.md, Claude Routines, OpenAI Scheduled Tasks, Goose Scheduler, Temporal Schedules, LangGraph cron.


Design

Scope (v1)

  • Topology: in-process scheduler component (no separate binary).
  • Triggers: 5-field cron + @every/@daily macros (IANA timezone) and one-shot future time.
  • Surfaces: mecated + mecak8s (server-side scheduler + schedules API), and mecatui (a /schedule slash command + overlay to create/list/inspect).
  • Per-fire: fresh top-level session with subagent-grade defaults.

Session model (the "subagent" question)

A scheduled fire is a fresh top-level session per fire driven through Service.StartRunContent — not a literal child Subagent.

Why not a literal subagent: a mecatl Subagent only exists as a child of a live parent run (spawned inside the loop via the Subagent tool, lives in run.children, returns its result to a parent). At fire time there is no parent — that is the defining property of a schedule. Routing the fire through the normal session run-entry funnel is also what earns durability, leasing, and rehydration for free.

What we keep from the subagent spirit (its defaults are exactly the unattended-safety gates we want):

  • Bounded: per-schedule MaxTurns / MaxToolCalls / MaxRunTokens (reuse RunOptions + session.Limits).
  • Conservative posture: default to a read-leaning posture; mutations require an explicit per-schedule opt-in (and, when interactive approval is impossible, the existing headless ask model auto-denies or routes to the opt-in --subagent-ask-reviewer).
  • Discrete deliverable: the run's final report + terminal EvResult captured to the durable event log / a per-fire artifact.
  • Fresh context: no carried conversation by default.

Open question (please confirm): default per-fire posture. Proposal: inherit the operator's configured posture but default the schedule to read-only/strict-leaning unless mutating: true is set on the schedule. A scheduled run that wants to do work (open a PR, edit files) opts in explicitly — matching Cursor's "staged diffs by default" and Claude Routines' claude/*-branch restriction.

A scheduled session is of course free to use the Subagent/Team/Parallel tools internally — that is the agent's runtime choice, orthogonal to the scheduler.

Architecture & seams

The scheduler is a composition-layer subsystem that owns one process-wide tick loop and reuses the existing run-entry funnel — no engine/ (domain/loop) changes. It mirrors the lease-renewer ownership pattern already on Service.

                       ┌─────────────────────────────────────────┐
                       │  Scheduler (internal/adapter/scheduler)   │
   port.ScheduleStore  │   • tick loop (gocron / robfig parser)    │
   (durable registry)──┤   • leader-gated (port.SessionLease on a  │
        │              │     well-known "scheduler" id)            │
        │              │   • on due: resolve schedule → fire       │
        ▼              └───────────────────┬───────────────────────┘
   redis / jsonl / mem                     │ Service.StartRunContent(ctx, sessID, prompt, parts)
                                           ▼
                              existing run-entry funnel
                       (loadAndReopen → lease → engine → drive)

Run-entry funnel (reuse verbatim):

  • Service.StartRunContent(ctx, id, text, parts) — the single PROMPT entry point (internal/adapter/server/service.go). A fire is just a server-initiated call to this.
  • Service.CreateSessionWithProfile(...) — mint the per-fire session (internal/adapter/server/service.go).
  • Engine.RunContentWith(ctx, sess, ws, text, parts, RunOptions{...}) — per-run budgets/limits via RunOptions (engine/agent/loop.go).
  • Run tracking / drain / lease already exist (Service.runs, Service.Drain, acquireLease/renewLoop/releaseLease).

New durable primitive — port.ScheduleStore:
A new engine port (peer of port.EventLog / port.SessionStore), with conformance suite, and adapters for redis (internal/adapter/redisstore, the mecak8s path), jsonl (internal/adapter/store/jsonlstore, single-host), mem (reference/tests), and optionally a driver service. It lives in engine/port for consistency with SessionLease/EventLog (reference adapters + conformance in engine/adapter); because it crosses the importable surface it triggers the api-compat gate (ADR 0037) — task api:update + an engine/CHANGELOG.md note. The schedule's provider/model is carried by an engine-local value object (ScheduleProviderSelector, plain strings, mirroring port.LLMRequest.Model's opaque-string discipline) rather than internal's ProviderSelector/SessionProfile (which can't appear in engine/port). Sketch:

// engine/port/schedule.go (NEW)

// ScheduleProviderSelector mirrors the opaque-string discipline of
// port.LLMRequest.Model; composition maps it to the internal ProviderSelector.
type ScheduleProviderSelector struct{ ProviderID, ModelID string }

type Schedule struct {
    ID         string            // stable id
    Spec       TriggerSpec       // SUM TYPE: {Cron(expr,tz) | OneShot(time)} — one canonical rep
    Prompt     string            // saved prompt
    Parts      []session.Content // optional multimodal prompt
    Selector   ScheduleProviderSelector // provider/model, PINNED at creation
    Profile    string            // "" (default) | "no-fs"
    Workspace  string            // optional working dir
    Mode       session.PermissionMode
    Limits     session.Limits    // bounded budgets
    Mutating   bool              // explicit write opt-in (default false = read-leaning)
    Misfire    MisfirePolicy     // fire-once-now (default) | skip
    Singleton  bool              // skip next fire if prior still running (default true)
    MaxFires   int               // 0 = forever (cron only; OneShot fires once by definition)
    Enabled    bool
    NextFireAt time.Time         // ground-truth next fire; ADVANCED before firing (claim-before-fire)
    LastFireAt time.Time
    // LastFireSessionID is the prior fire's session id; the per-session LEASE on it
    // is the authoritative cross-replica liveness oracle for the singleton check.
    LastFireSessionID session.SessionID
    CreatedAt  time.Time
}

type ScheduleStore interface {
    Put(ctx, Schedule) error
    Get(ctx, id string) (Schedule, error)
    List(ctx) ([]Schedule, error)
    Delete(ctx, id string) error
    // Due returns schedules with NextFireAt <= now (the poll-the-store pattern).
    Due(ctx, now time.Time) ([]Schedule, error)
}

Ground-truth durability: the schedule store is the source of truth (survives restart). The in-memory cron timer is a derived lookahead, rebuilt from the store on startup. (This is the Temporal/Hermes principle: never let the only copy of a schedule live in a goroutine's timer.)

Exactly-once across replicas — at-most-once via claim-before-fire. The primary mechanism is the durable store claim, not a lease: the leader atomically advances NextFireAt/LastFireAt in the store before firing, so a peer's Due() query can never re-return the same slot. This makes the semantics at-most-once — a crash mid-fire skips that slot (recurring schedules self-heal via the fire-once-now misfire policy; a one-shot can be lost). We choose at-most-once deliberately: for side-effecting agent runs (open a PR, push a branch, send a message) a skipped nightly run is recoverable, a double-run that opens two PRs is not. Layers:

  1. Leader gate: reuse port.SessionLease on a well-known typed-constant scheduler id; only the lease holder ticks. (The id need not be a UUID — session.SessionID is an unvalidated string, k8slease hashes arbitrary ids to RFC-1123 names, and real ids are hex so a sentinel can't collide. A named constant is used for hygiene.)
  2. Slot claim: the claim-before-fire NextFireAt advance is the durable exactly-once record.
  3. Cross-replica overlap (singleton): before firing, the leader takes a trial SessionLease on LastFireSessionID; ErrSessionLeasedElsewhere ⇒ the prior fire is still live on any replica ⇒ skip (the leader's own Service.runs only sees its own process). The lease is authoritative, so the field needs no atomic clear-on-completion — a stale pointer to a finished fire just yields a free trial-acquire (= not skipped).

A per-fire dedup key is now optional belt-and-suspenders (the slot claim already prevents re-fire), which dissolves the "when to release it" question. The k8s/flock/redis lease backends from ADR 0027 cover single-host and multi-replica.

Tick & misfire:

  • Tick interval ~30–60s (poll ScheduleStore.Due), matching the precision floor we expose.
  • On gaining leadership/startup, apply the misfire policy for schedules whose NextFireAt is in the past: default fire-once-now (run once, recompute next from now; log the missed intervals). skip configurable. (No catch-up/backlog replay — see scope.)
  • Singleton/overlap: before firing, the leader takes a trial SessionLease on the schedule's LastFireSessionID; if it's held (ErrSessionLeasedElsewhere) the prior fire is still live on any replica → skip. This is the cross-replica-correct check; Service.runs alone would only see the leader's own process. mecatl is already mutate-serial within a run.

Timezone: store IANA tz per schedule; default UTC. Document the 1–3am DST danger zone; recommend UTC for infra schedules.

Library choice

Prefer go-co-op/gocron v2 (MIT, actively maintained) for the in-memory next-fire timer + cron parsing (it wraps robfig/cron/v3), OR a thin parser-only dependency on robfig/cron/v3 with our own tick loop over ScheduleStore.Due. Either way the store is ground truth, the timer is derived. We do not need gocron's distributed locker — we already own a stronger primitive (port.SessionLease). Temporal is overkill given the existing durable event log + lease.

Data flow at fire time

  1. Tick loop (leader only) calls ScheduleStore.Due(now).
  2. For each due schedule, claim the per-fire dedup key.
  3. CreateSessionWithProfile(...) with the schedule's selector/profile/workspace/mode/limits → fresh session id (e.g. sched-<id>-<fire_ts>).
  4. StartRunContent(ctx, sessID, prompt, parts) → run drives to terminal.
  5. Capture EvResult (+ final report) to the event log / per-fire artifact; update LastFireAt, recompute NextFireAt (or disable if one-shot / Repeat exhausted).
  6. Emit a new EvScheduleFired event (and EvScheduleSkipped/EvScheduleFailed) for observability.

API & UX surface

  • gRPC/HTTP: a ScheduleService (Create / Get / List / Update / Delete / FireNow / Pause / Resume) on the server, mirroring SessionService shape. Returns the per-fire session id / URL so a client can open the resulting transcript (Claude Routines pattern).
  • Driver protocol: optionally a ScheduleStoreService in contracts/proto/mecatl/driver/v1/ so the registry can be remote (consistent with the other driver stores). Likely v2.
  • CLI (mecated/mecak8s flags + settings.yaml): operator-tier schedules: block to declare schedules in config (GitOps-friendly), plus --scheduler enable flag and tick/lease knobs. Follows the --session-lease-* wiring precedent (internal/app/build.go buildSessionLease).
  • mecatui: a /schedule slash command + an overlay (peer of /agents, /team) to create/list/inspect/pause schedules and jump to a fire's transcript. NL-time entry in the composer can compile to cron client-side later.

Safety for unattended runs (reuse existing gates)

  • Secret-scrubbed env already applies to every agent shell (envscrub) — unchanged.
  • Headless ask model already auto-denies or routes mutating asks when no human is present; a scheduled run is headless by definition.
  • Posture ladder (strict < trusted < auto < yolo) governs autonomy; scheduled runs default read-leaning (see open question).
  • Per-run token/turn budgets (MaxRunTokens etc.) bound cost.
  • Model pinning is fail-closed by construction. Because provider is fixed per session (a core invariant), a schedule that pins its Selector never silently migrates to a different/paid model — there is no silent fallback to guard against. So Phase-1 pinning is just persist an explicit selector + surface a provider/model-unavailable failure as EvScheduleFailed (an unknown model is passed through and fails at the provider call today; CreateSessionWithProfile does no pre-flight availability check). An optional pre-flight ListModels check is later polish (it's a live network call, not free).
  • Drain gate (ADR 0048) — the scheduler must respect Service.draining (stop firing new runs during graceful shutdown) and stop ticking when it loses the scheduler lease.

Observability

  • New events: EvScheduleFired / EvScheduleSkipped / EvScheduleFailed (string-passthrough, like EvNoProgress/StopBudget).
  • Per-fire artifact (final report) archived alongside the session.
  • Metrics: schedules registered, fires, skips (overlap/misfire), failures, fire latency.
  • Diagnostics via injected port.Diagnostics (never slog).

Phasing

  • Phase 1 — durable registry + tick: port.ScheduleStore + mem/jsonl/redis adapters + conformance; in-process tick loop gated by port.SessionLease; cron + one-shot; claim-before-fire (at-most-once); misfire fire-once-now; cross-replica singleton via trial-lease; fail-closed model pinning (persist selector + EvScheduleFailed). Wire into mecated + mecak8s behind --scheduler. Fresh-session-per-fire with subagent-grade defaults. Gates: ADR 0037 api-compat (task api:update + engine/CHANGELOG.md) for the new engine/port type; CLOUD-NATIVE.md List 1 rows (tick goroutine, derived lookahead timer, leader-lease renewer) + List 2 row (leader lease = reset-by-design); docs/lint citation gate for the ADR.
  • Phase 2 — API + config: ScheduleService (gRPC/HTTP) + settings.yaml schedules: block + CLI management. EvSchedule* events + metrics.
  • Phase 3 — mecatui UX: /schedule slash command + overlay; jump-to-transcript.
  • Later (v2): natural-language → cron; persistent-session continuation (carried context) toggle; context_from-style chaining; driver ScheduleStoreService; event/webhook triggers; per-fire egress allowlist; "no-LLM gate" (run a cheap check, only wake the agent on a real change — Hermes wakeAgent).

Out of scope (v1)

  • Natural-language schedule parsing (cron + one-shot only).
  • Carried-context / persistent recurring session (fresh per fire only).
  • Event/webhook triggers (GitHub, Slack, etc.).
  • A separate scheduler binary/sidecar (in-process only).
  • Backfill/catch-up replay of a missed backlog (fire-once-now only).

Decisions resolved in review

These were converged in the issue thread (see the review discussion):

  1. Firing semantics → at-most-once (claim-before-fire). Durable NextFireAt advance is the primary exactly-once record; a crash mid-fire skips the slot (recoverable for recurring via fire-once-now; a one-shot can be lost). Chosen so a bad leadership handover never double-runs a side-effecting agent.
  2. ScheduleStore location → engine/port (consistent with SessionLease/EventLog; reference adapters + conformance in engine/adapter), with an engine-local ScheduleProviderSelector value object. Triggers the ADR 0037 api-compat gate.
  3. Default per-fire posture → read-leaning + explicit mutating: true opt-in. Coherent with headless auto-deny; prevents a misconfigured schedule writing to prod.
  4. Frequency floor → operator-configurable, no hard floor in the binary. A MinInterval build option with a sane default; document the cost.
  5. Schedule registry → reuse the configured Store by type-assertion (the SessionLease/PrunableStore precedent). No separate --schedule-store-* on the common path.
  6. Cron library → parser-only (robfig/cron/v3). Store is ground truth; the in-memory timer is a derived lookahead; gocron's distributed locker is redundant with SessionLease.
  7. Per-fire session id → sched-<id>-<fire_ts>, retained via PrunableStore under a distinct ScheduleFireRetention (e.g. 30 days), separate from normal session retention.
  8. Result delivery → pull-only v1 (event log / transcript). Push/webhook is v2.
  9. Model pinning → Phase 1, fail-closed by construction (provider fixed-per-session); see Safety.
  10. Struct cleanups: MaxFires (not Repeat); one-shot is a single TriggerSpec variant (no redundant MaxFires: 1); __scheduler__ leader-lease id is a named typed constant (no SessionID validation exists and ids are collision-proof — hygiene, not correctness).

Open questions

  • One-shot crash-loss tolerance. At-most-once means a one-shot whose fire crashes mid-run is lost (not retried). Acceptable for v1, or do one-shots warrant an opt-in at-least-once retry?
  • Tick precision vs floor. A 30–60s Due() poll caps schedule precision; confirm that's acceptable given the configurable interval floor (sub-minute cron would need a tighter tick).

Research basis: cross-product survey (Hermes, ChatGPT Tasks, Claude Code Routines//loop, Goose, Devin, Cursor, Cline, Temporal, LangGraph) + Go scheduling-library/distributed-scheduling/durable-timer survey + a codebase map of the run-entry funnel, session lifecycle, and ADR 0027/0048 cloud-native primitives. Full notes available on request.

Sub-issues

Sub-issues

1 of 1 Issues completed
Loading 1 sub-issues

Activity

  1. added
    enhancement
    config
    on Jun 25, 2026
  2. rdimitrov commented on Jun 25, 2026

    @rdimitrov
    Member

    Good issue — the prior-art survey is solid and the architecture correctly identifies that the scheduler is a composition-layer subsystem reusing the existing run-entry funnel. A few targeted observations:


    Layering violation in the port.ScheduleStore sketch

    engine/port/schedule.go can only import $gostd + sibling engine/ packages. ProviderSelector and SessionProfile are both defined in internal/adapter/server/service.go — they can't appear in an engine/port type without a depguard violation. Two options:

    • Define a ScheduleProviderSelector value object in engine/port with plain ProviderID/ModelID string fields (mirrors how port.LLMRequest.Model is an "opaque string") — the store stays in engine/port.
    • Move ScheduleStore to internal/adapter/server or a new internal/port layer, alongside ProviderSelector. The PrunableStore / SessionLease precedent suggests the port lives in engine/port and the value object uses only engine types — lean toward the first fix.

    Cross-replica overlap detection gap

    The singleton/overlap check says "if a schedule's prior fire is still running … skip." In a multi-replica deployment the leader only sees its own Service.runs. The per-fire dedup key on port.SessionLease doesn't help here — it deduplicates a fire slot, not whether the prior fire (different session id) is still in progress.

    The simplest cross-replica fix: add an optional ActiveFireSessionID session.SessionID field to Schedule. The scheduler sets it (via Put) atomically when it mints the session, and clears it (via Put) on fire completion. Before firing, the scheduler acquires a trial lease on ActiveFireSessionID; ErrSessionLeasedElsewhere = prior fire still live, skip. This reuses the existing lease primitive without new infrastructure.

    Dedup lease must NOT be released on fire completion

    The per-fire lease on sched-<id>-<fire_ts> is only useful if it is held past the fire's lifetime (until the next tick cycle, or until it expires naturally). If the scheduler releases it when StartRunContent completes, a leadership handover could re-fire that slot before the TTL window. The ADR / implementation note should be explicit: the dedup lease is released only at fire expiry time / next tick, not at completion.

    CLOUD-NATIVE.md inventory obligation

    From the repo contract: "Added an outlives-a-call resource? Inventory it in docs/adr/0027-cloud-native.md." The scheduler introduces at minimum: the tick goroutine (lifetime = Build → shutdown), the in-memory next-fire lookahead timer (derived from store, rebuilt on leader gain), and the leader lease renewer goroutine. These need List 1 (resource inventory) rows before the first commit. The scheduler lease state also touches List 2 (rehydrate-fidelity) — it resets cleanly on restart (leader election re-runs), which is the deliberate "reset-by-design" classification.

    Model pinning should be Phase 1, not Phase 2

    Fail-closed model pinning is listed as Phase 2. But a scheduled run that silently falls back to a different model when the pinned model is unavailable is an unattended cost/behaviour surprise — exactly the scenario Hermes warns about. Since CreateSessionWithProfile already accepts a ProviderSelector and the per-session engine factory handles the resolution path, wiring a "pinned model not available → fail the fire with EvScheduleFailed" check costs almost nothing at Phase 1 and avoids a silent foot-gun.


    Open questions — suggested answers

    1. Default posture — Read-leaning + explicit mutating: true opt-in is the right call. Mirrors Cursor staged-diffs and Routines branch restriction; is coherent with headless auto-deny; prevents a misconfigured schedule accidentally writing to prod.

    2. Frequency floor — Operator-configurable with a sane default (1 min is the industry floor for local daemon; add a MinInterval build option and document the cost). No hard floor in the binary itself.

    3. Schedule registry location — Reuse the configured Store backend by type assertion (same pattern as PrunableStore / SessionLease). A distinct --schedule-store-* flag adds operational burden for no benefit on the common path.

    4. gocron vs parser-only — Parser-only (robfig/cron/v3) is correct. The store is ground truth; the in-memory timer is a derived lookahead. gocron's distributed locker is redundant with the existing lease primitive.

    5. Per-fire session id + retention — sched-<id>-<fire_ts> is fine. Wire PrunableStore retention for per-fire sessions — a separate ScheduleFireRetention duration in the operator config (e.g. 30 days) distinct from normal session retention.

    6. Result delivery — Pull-only (event log / transcript) is right for v1. The existing EvResult + durable log already gives observability. Push/webhook is v2.


    Minor

    • Repeat int is slightly ambiguous. MaxFires int (0 = forever) is clearer.
    • One-shot is modelled both via Spec (a future timestamp trigger) and via Repeat: 1. Pick one canonical representation to avoid a footgun.
    • Confirm that session.SessionID accepts a non-UUID value for the __scheduler__ leader lease id, or define a distinct typed constant to avoid silent validation failures.
  3. JAORMX commented on Jun 25, 2026

    @JAORMX
    ContributorAuthor

    Thanks @rdimitrov — went through each point against the code. Most hold up exactly; a couple need a small reframe. Summary of where we land:

    Accepted as-is

    Layering violation (ScheduleStore sketch). Confirmed — ProviderSelector (internal/adapter/server/service.go:49) and SessionProfile (internal/adapter/server/profile.go:12) both live in internal/, so an engine/port type can't reference them. Going with your first option: ScheduleStore stays in engine/port with a ScheduleProviderSelector engine value object (plain ProviderID/ModelID string, mirroring the port.LLMRequest.Model opaque-string discipline) — consistent with SessionLease/EventLog and keeps the reference adapters + conformance suite in engine/adapter.

    One obligation to flag that wasn't in the comment: adding a type to engine/port crosses the api-compat gate (ADR 0037) — it needs task api:update + an engine/CHANGELOG.md note (Added = minor). Folding that into the Phase 1 checklist.

    Cross-replica overlap gap. Confirmed — Service.runs (service.go:534) is a per-process in-memory map (ADR 0027 List 1 row 9: "lost; run dies with process"), so the leader can't see a peer's live fire. Taking your ActiveFireSessionID + trial-lease fix. One refinement: since the per-session lease is the liveness oracle, the field is really just "last fire's session id" and we don't need atomic clear-on-completion — a stale pointer to a finished fire yields a free trial-acquire (→ not skipped). The lease, not the field, is authoritative.

    CLOUD-NATIVE.md inventory. Correct and non-negotiable per CLAUDE.md. Phase 1 adds List 1 rows for the tick goroutine, the derived in-memory next-fire timer, and the scheduler-leader lease renewer; List 2 gets the scheduler-leader lease state classified reset-by-design (leader election re-runs on restart). Also noting the docs/lint citation gate for any ADR/design citations.

    Registry location (Q3). Reuse the configured Store by type-assertion — the established pattern (build.go:1787 for SessionLease, childgc.go:333 for PrunableStore). No separate --schedule-store-* flag on the common path.

    Open-Q answers 1, 2, 4, 5, 6 and the minors (MaxFires rename; pull-only delivery; parser-only robfig/cron/v3): agreed.

    Reframed (premise was slightly off, conclusion mostly survives)

    Firing semantics — the decision underneath the dedup-lease point. Your "hold the dedup lease past completion" advice and the overlap fix both orbit a choice we hadn't made explicit: at-most-once vs at-least-once. We're committing to at-most-once via claim-before-fire — atomically advance NextFireAt/LastFireAt in the store before firing, so a peer's Due() can't re-return the slot. That makes the durable store claim the primary exactly-once mechanism and the per-fire dedup lease optional belt-and-suspenders, which dissolves the "when do I release it" hazard entirely. The trade is that a crash mid-fire skips that slot (recurring schedules self-heal via fire-once-now; a one-shot can be lost) — and for side-effecting agent runs we'd rather skip a nightly run than double-open a PR. Calling the semantics out explicitly in the design.

    Model pinning at Phase 1. Agreed it belongs in Phase 1, but the mechanism is different (and stronger) than "the factory handles resolution." There's no pre-flight availability check — CreateSessionWithProfile only rejects model-without-provider (service.go:835); an unknown model is passed through and fails at the provider call. What actually saves us is that provider is fixed-per-session (CLAUDE.md) — a pinned selector never silently migrates to a paid default by construction. So Phase-1 "pinning" reduces to persist an explicit selector + map provider-unavailable → EvScheduleFailed, which is genuinely cheap. A pre-flight ListModels check (modellister.go:184) is optional polish and a live network call, not free — I'd leave it for later.

    One-shot double-representation (minor). Agreed it's a footgun. Resolution: TriggerSpec becomes a sum type {Cron | OneShot}; a one-shot fires once by definition, and MaxFires applies only to the cron variant (0 = forever). No redundant Repeat: 1.

    __scheduler__ leader-lease id (minor). Checked this one — the "silent validation failure" risk is essentially nil: SessionID is a bare string with no validation (session.go:12), k8slease hashes arbitrary ids into RFC-1123 names (k8slease.go:14-17, so underscores are fine), and real ids are hex (service.go:2382) so a __scheduler__ constant can't collide. Still using a named typed constant — good hygiene — just not for the stated reason.

    Will fold all of this into the issue body / the eventual ADR. Thanks for the thorough pass.

  4. jbeda commented on Jun 25, 2026

    @jbeda
    Contributor

    Lot to read here so I may not have the details right.

    I think this is implemented cleanly on top of the engine in a way such that it is just another caller of the engine. I like that and it means that we can extend this over time with other types of triggers and it starts to bleed into A2A type behavior.

    Some questions:

    1. As we look to enable this type of behavior in atrium, we will want to have UI there. It is worth thinking through the domain model there and making sure we are building for that. Specifically, should past runs be full entities? How do I practically click on a schedule and see the list of past runs and examine the session to see how things went? I would expect a ScheduleRun entity that is a child of the Schedule. That would then reference the Session (?) to get details of the run. Or something like that.
    2. Right now we run the schedule in proc with the rest of the modulith. But because it executes on it's own local pod, there are scalability limits if you end up with too many scheduled events. At some point we want to make the trigger mechanism go through some sort of load balancer and maybe even break out the scheduler into it's own microservice. Worth noting this limitation and that we'll need to make some arch changes to deal with larger scale deployments (and maybe some sort of redis based distributed scheduling instead of doing a tick based thing in a go process. We could also shard schedules so that they are evenly distributed across pods and still load locally.)
    3. Configuring these is something that the agent itself may want to do. Is there thought about re-exposing the scheduling mechanisms from being a tool the agent can call to manage schedules in addition to offering the /schedule command? Claude Code has CronCreate/CronDelete/CronList tools (https://code.claude.com/docs/en/tools-reference).
    4. At what point do we want to put more capabilities into this repo and when do we want to start breaking these out? This is mostly a service that sits outside of the core. This is clearly something that we might run out-of-proc for scalable systems in atrium. Unclear to me how to structure the repo/code. Especially as we add more and more systems that sit outside the core and integrate. Do we want to stay monorepo? For how long?
  5. 23 remaining items

  6. JAORMX commented on Jul 13, 2026

    @JAORMX
    ContributorAuthor

    All v1 phases (#231–235) shipped previously. The remaining v2 items from #236 are now addressed:

    PR #256 lands the feasible-now v2 items across three dev-pipeline waves:

    • Wave 1: mecatui in-overlay Create form + NL→cron client-side compiler (cmd/mecatui/schedparse)
    • Wave 2: sched-- GC retention family (session-id override on CreateSessionWithProfile + ScheduleFireRetention GC partition)
    • Wave 3: One-shot crash-loss retry (opt-in OneShotRetry + ScheduleOneShotReArmer) + carried-context toggle (opt-in CarryContext — fenced untrusted preamble, NOT seeded history)

    Five focused follow-up issues filed for the items that are each full features:

    #236 is closed (completed — the v2 items are either landed in #256 or spun to focused issues). This umbrella will close when #256 merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    configenhancementresearchui

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions