Repository navigation
Description
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:
- 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.
- 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.
- 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.
- Frequency floor + "at most one catch-up" are deliberate safety/cost levers. Nobody replays a backlog. → Default misfire policy = fire-once-now; configurable floor.
- 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).
- 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/@dailymacros (IANA timezone) and one-shot future time. - Surfaces:
mecated+mecak8s(server-side scheduler + schedules API), andmecatui(a/scheduleslash 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(reuseRunOptions+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
EvResultcaptured 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 unlessmutating: trueis 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 viaRunOptions(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:
- Leader gate: reuse
port.SessionLeaseon a well-known typed-constant scheduler id; only the lease holder ticks. (The id need not be a UUID —session.SessionIDis 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.) - Slot claim: the claim-before-fire
NextFireAtadvance is the durable exactly-once record. - Cross-replica overlap (singleton): before firing, the leader takes a trial
SessionLeaseonLastFireSessionID;ErrSessionLeasedElsewhere⇒ the prior fire is still live on any replica ⇒ skip (the leader's ownService.runsonly 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
NextFireAtis in the past: default fire-once-now (run once, recompute next from now; log the missed intervals).skipconfigurable. (No catch-up/backlog replay — see scope.) - Singleton/overlap: before firing, the leader takes a trial
SessionLeaseon the schedule'sLastFireSessionID; if it's held (ErrSessionLeasedElsewhere) the prior fire is still live on any replica → skip. This is the cross-replica-correct check;Service.runsalone 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
- Tick loop (leader only) calls
ScheduleStore.Due(now). - For each due schedule, claim the per-fire dedup key.
CreateSessionWithProfile(...)with the schedule's selector/profile/workspace/mode/limits → fresh session id (e.g.sched-<id>-<fire_ts>).StartRunContent(ctx, sessID, prompt, parts)→ run drives to terminal.- Capture
EvResult(+ final report) to the event log / per-fire artifact; updateLastFireAt, recomputeNextFireAt(or disable if one-shot /Repeatexhausted). - Emit a new
EvScheduleFiredevent (andEvScheduleSkipped/EvScheduleFailed) for observability.
API & UX surface
- gRPC/HTTP: a
ScheduleService(Create / Get / List / Update / Delete / FireNow / Pause / Resume) on the server, mirroringSessionServiceshape. Returns the per-fire session id / URL so a client can open the resulting transcript (Claude Routines pattern). - Driver protocol: optionally a
ScheduleStoreServiceincontracts/proto/mecatl/driver/v1/so the registry can be remote (consistent with the other driver stores). Likely v2. - CLI (
mecated/mecak8sflags +settings.yaml): operator-tierschedules:block to declare schedules in config (GitOps-friendly), plus--schedulerenable flag and tick/lease knobs. Follows the--session-lease-*wiring precedent (internal/app/build.gobuildSessionLease). mecatui: a/scheduleslash 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 (
MaxRunTokensetc.) bound cost. - Model pinning is fail-closed by construction. Because provider is fixed per session (a core invariant), a schedule that pins its
Selectornever 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 asEvScheduleFailed(an unknown model is passed through and fails at the provider call today;CreateSessionWithProfiledoes no pre-flight availability check). An optional pre-flightListModelscheck 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, likeEvNoProgress/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(neverslog).
Phasing
- Phase 1 — durable registry + tick:
port.ScheduleStore+ mem/jsonl/redis adapters + conformance; in-process tick loop gated byport.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 intomecated+mecak8sbehind--scheduler. Fresh-session-per-fire with subagent-grade defaults. Gates: ADR 0037 api-compat (task api:update+engine/CHANGELOG.md) for the newengine/porttype; 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 —
mecatuiUX:/scheduleslash command + overlay; jump-to-transcript. - Later (v2): natural-language → cron; persistent-session continuation (carried context) toggle;
context_from-style chaining; driverScheduleStoreService; event/webhook triggers; per-fire egress allowlist; "no-LLM gate" (run a cheap check, only wake the agent on a real change — HermeswakeAgent).
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):
- Firing semantics → at-most-once (claim-before-fire). Durable
NextFireAtadvance 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. ScheduleStorelocation →engine/port(consistent withSessionLease/EventLog; reference adapters + conformance inengine/adapter), with an engine-localScheduleProviderSelectorvalue object. Triggers the ADR 0037 api-compat gate.- Default per-fire posture → read-leaning + explicit
mutating: trueopt-in. Coherent with headless auto-deny; prevents a misconfigured schedule writing to prod. - Frequency floor → operator-configurable, no hard floor in the binary. A
MinIntervalbuild option with a sane default; document the cost. - Schedule registry → reuse the configured
Storeby type-assertion (theSessionLease/PrunableStoreprecedent). No separate--schedule-store-*on the common path. - 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 withSessionLease. - Per-fire session id →
sched-<id>-<fire_ts>, retained viaPrunableStoreunder a distinctScheduleFireRetention(e.g. 30 days), separate from normal session retention. - Result delivery → pull-only v1 (event log / transcript). Push/webhook is v2.
- Model pinning → Phase 1, fail-closed by construction (provider fixed-per-session); see Safety.
- Struct cleanups:
MaxFires(notRepeat); one-shot is a singleTriggerSpecvariant (no redundantMaxFires: 1);__scheduler__leader-lease id is a named typed constant (noSessionIDvalidation 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.
Activity
rdimitrov commentedon Jun 25, 2026
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.ScheduleStoresketchengine/port/schedule.gocan only import$gostd+ siblingengine/packages.ProviderSelectorandSessionProfileare both defined ininternal/adapter/server/service.go— they can't appear in anengine/porttype without a depguard violation. Two options:ScheduleProviderSelectorvalue object inengine/portwith plainProviderID/ModelID stringfields (mirrors howport.LLMRequest.Modelis an "opaque string") — the store stays inengine/port.ScheduleStoretointernal/adapter/serveror a newinternal/portlayer, alongsideProviderSelector. ThePrunableStore/SessionLeaseprecedent suggests the port lives inengine/portand 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 onport.SessionLeasedoesn'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.SessionIDfield toSchedule. The scheduler sets it (viaPut) atomically when it mints the session, and clears it (viaPut) on fire completion. Before firing, the scheduler acquires a trial lease onActiveFireSessionID;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 whenStartRunContentcompletes, 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.mdinventory obligationFrom 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
CreateSessionWithProfilealready accepts aProviderSelectorand the per-session engine factory handles the resolution path, wiring a "pinned model not available → fail the fire withEvScheduleFailed" check costs almost nothing at Phase 1 and avoids a silent foot-gun.Open questions — suggested answers
Default posture — Read-leaning + explicit
mutating: trueopt-in is the right call. Mirrors Cursor staged-diffs and Routines branch restriction; is coherent withheadlessauto-deny; prevents a misconfigured schedule accidentally writing to prod.Frequency floor — Operator-configurable with a sane default (1 min is the industry floor for local daemon; add a
MinIntervalbuild option and document the cost). No hard floor in the binary itself.Schedule registry location — Reuse the configured
Storebackend by type assertion (same pattern asPrunableStore/SessionLease). A distinct--schedule-store-*flag adds operational burden for no benefit on the common path.gocronvs 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.Per-fire session id + retention —
sched-<id>-<fire_ts>is fine. WirePrunableStoreretention for per-fire sessions — a separateScheduleFireRetentionduration in the operator config (e.g. 30 days) distinct from normal session retention.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 intis slightly ambiguous.MaxFires int(0 = forever) is clearer.Spec(a future timestamp trigger) and viaRepeat: 1. Pick one canonical representation to avoid a footgun.session.SessionIDaccepts a non-UUID value for the__scheduler__leader lease id, or define a distinct typed constant to avoid silent validation failures.JAORMX commentedon Jun 25, 2026
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 (
ScheduleStoresketch). Confirmed —ProviderSelector(internal/adapter/server/service.go:49) andSessionProfile(internal/adapter/server/profile.go:12) both live ininternal/, so anengine/porttype can't reference them. Going with your first option:ScheduleStorestays inengine/portwith aScheduleProviderSelectorengine value object (plainProviderID/ModelID string, mirroring theport.LLMRequest.Modelopaque-string discipline) — consistent withSessionLease/EventLogand keeps the reference adapters + conformance suite inengine/adapter.One obligation to flag that wasn't in the comment: adding a type to
engine/portcrosses the api-compat gate (ADR 0037) — it needstask api:update+ anengine/CHANGELOG.mdnote (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 yourActiveFireSessionID+ 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
Storeby type-assertion — the established pattern (build.go:1787forSessionLease,childgc.go:333forPrunableStore). No separate--schedule-store-*flag on the common path.Open-Q answers 1, 2, 4, 5, 6 and the minors (
MaxFiresrename; pull-only delivery; parser-onlyrobfig/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/LastFireAtin the store before firing, so a peer'sDue()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 —
CreateSessionWithProfileonly 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-flightListModelscheck (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:
TriggerSpecbecomes a sum type{Cron | OneShot}; a one-shot fires once by definition, andMaxFiresapplies only to the cron variant (0 = forever). No redundantRepeat: 1.__scheduler__leader-lease id (minor). Checked this one — the "silent validation failure" risk is essentially nil:SessionIDis a barestringwith 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.
jbeda commentedon Jun 25, 2026
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:
ScheduleRunentity that is a child of theSchedule. That would then reference theSession(?) to get details of the run. Or something like that./schedulecommand? Claude Code has CronCreate/CronDelete/CronList tools (https://code.claude.com/docs/en/tools-reference).fix(scheduler): panel-review fixes — singleton trial-lease, read-lean…
fix(scheduler): bound the singleton trial-lease acquire with a 5s tim…
feat(port): add ScheduleStore port for scheduled tasks (#189, phase 1a)
feat(adapter/cronparse): parser-only cron helper + robfig dep (#189, …
feat(adapter): ScheduleStore conformance suite + mem reference adapter (
feat(adapter): jsonl + redis ScheduleStore backends (#189, phase 1d)
feat(scheduler): tick loop + leader-lease + fire seam (#189, phase 1e)
feat(app): wire scheduler into composition + FireFunc + --scheduler f…
23 remaining items
feat(mecated): Phase 2b — schedules CLI subcommands (create/list/insp…
feat(scheduler): Phase 2b — schedule metrics (fires/skips/failures + …
docs(scheduler): Phase 2b — flip production-readiness to shipped + e2…
feat: scheduled tasks — Phase 2b: settings.yaml schedules + CLI manag…
JAORMX commentedon Jul 13, 2026
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:
cmd/mecatui/schedparse)sched--GC retention family (session-id override onCreateSessionWithProfile+ScheduleFireRetentionGC partition)OneShotRetry+ScheduleOneShotReArmer) + carried-context toggle (opt-inCarryContext— fenced untrusted preamble, NOT seeded history)Five focused follow-up issues filed for the items that are each full features:
ScheduleStoreServicecontext_from-style chaining#236 is closed (completed — the v2 items are either landed in #256 or spun to focused issues). This umbrella will close when #256 merges.
feat: scheduled tasks v2 finish — Create form, NL→cron, sched-- GC, o…
feat(scheduler): Phase 2b — settings.yaml schedules block (operator-t…
feat(mecated): Phase 2b — schedules CLI subcommands (create/list/insp…
feat(scheduler): Phase 2b — schedule metrics (fires/skips/failures + …
docs(scheduler): Phase 2b — flip production-readiness to shipped + e2…
feat(mecatui): scheduled tasks Phase 3b — in-overlay Create form + NL…
feat(scheduler): sched-- GC retention family (#236)
feat(scheduler): one-shot crash-loss retry + carried-context toggle (#…