Skip to content

feat(schedule-tool): in-chat scheduled tasks — model-facing Schedule tool, on-by-default scheduler - #307

Merged
JAORMX merged 33 commits into
mainfrom
acc/schedule-tool
Jul 26, 2026
Merged

JAORMX merged 33 commits into
mainfrom
acc/schedule-tool

Conversation

@JAORMX

@JAORMX JAORMX commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

What

Makes scheduled tasks usable from inside the conversation — the original motivation: the operator-only surfaces (a settings.yaml block, a mecated schedules CLI) were no better than cron/systemd, so this replaces them with a model-facing tool and turns the scheduler on by default.

  • Schedule catalog tool (engine/agent, over a new consumer-local engine/port.ScheduleManager): the model calls create/list/inspect/pause/resume/delete/fire in-chat. Split into a read-only ScheduleQuery (list/inspect, ReadOnly()==true) and a mutating Schedule (the rest, ReadOnly()==false) so dispatch stays read-parallel/mutate-serial. Rides the SAME validated create-seam as the REST/gRPC handlers — no second validation path. Floor-scoped ScopeBuiltinDefault Allow (memory-tool precedent), config-overridable.
  • Scheduler ON by default on any ScheduleStore-capable store (--store-dir / --redis-url); --scheduler deleted (clean, no deprecated alias), --no-scheduler added. In-memory stores stay byte-identical no-scheduling. mecatui's embedded server auto-fires on its default store.
  • Cadence floor enforced at create (--scheduler-min-interval, now defaults to 1m) + provider-selector validation fail-closed at the shared create-seam — so the in-chat create can't mint an unbounded or unconfigured fire.
  • Removed the operator-tier settings.yaml schedules: block and the mecated schedules <verb> CLI outright (no WARN shim/presence marker). The gRPC ScheduleService + REST /v1/schedules API is retained (the mecatui /schedule overlay consumes it).
  • Model-visible affordance (ADR 0070): a schedulePostureNote + plan-mode gate (mutating create AND mutating fire denied in plan mode).

Plan + verification

  • Acceptance plan: docs/acceptance/schedule-tool.md (landed). ADR: docs/adr/0073-schedule-tool.md.
  • 18 numbered ACs, each with a verify: test; task ac-trace-strict green.
  • Gates on the assembled branch: task lint ✅ · task test ✅ (both modules, -race, engine-standalone) · task api:check ✅ · task ac-trace-strict ✅ · matlatl --strict ✅ · go run ./cmd/mecademo ✅.
  • Inline panel-review: 2 ship-blockers found + fixed in a repair wave (the AC1.4 ReadOnly partition — now a real two-tool split; stale docs still advertising the removed surfaces — scrubbed). Security-default judgement calls folded in (1m cadence-floor default, plan-mode mutating-fire gate). Floor-Allow scope for create/fire kept as designed.

Notes / breaking changes

  • --scheduler removed (fails fast as unknown flag); use --no-scheduler to disable.
  • The settings.yaml schedules: block and mecated schedules CLI are gone; a residual schedules: key is silently ignored. Manage schedules via the in-chat tool or the REST/gRPC API.
  • The 7d --schedule-fire-retention default now activates on the default path (set --schedule-fire-retention=0 to keep fire sessions forever).
  • Out of scope (deferred): fire-result delivery back into the originating chat ("ping me when X").

Relates to #189 (scheduled tasks follow-up).

JAORMX and others added 30 commits July 24, 2026 16:05
Model-facing Schedule tool, on-by-default scheduler, removal of the
declarative settings block + mecated schedules CLI (clean removal, no
deprecated aliases or WARN shims).

Co-Authored-By: mecatl <[email protected]>
…ScheduleManager)

ADR 0073's in-chat affordance: a Schedule catalog tool the model calls to
create/list/inspect/pause/resume/delete/fire scheduled tasks, riding the SAME
validated create-seam the REST/gRPC handlers use — never a second path (one
store, one truth).

- engine/port: the consumer-local ScheduleManager interface (the verbs the
  tool needs, satisfied verbatim by the server Service's schedule methods) +
  the port-level ErrFireNowOverlap sentinel (the singleton-overlap rejection a
  layer that may not import the scheduler adapter matches via errors.Is).
- engine/agent: the ScheduleTool (verbs create/list/inspect/pause/resume/
  delete/fire). ReadOnly()==false — the conservative shape for a tool carrying
  both read-only and mutating verbs: every Schedule call serialises, so a
  mutating verb never overlaps a sibling read (the dispatch invariant).
- composition (internal/app): register the tool when the session's store backs
  a ScheduleStore, via a late-bound scheduleManagerFactory on the catalog
  assets (set in Build after NewService — the Service it closes over doesn't
  exist at catalog-assembly time); a ScopeBuiltinDefault floor Allow so it is
  pre-approved but config-overridable (the memory-tool posture).
- server: Service.ScheduleManager() (nil unless the store backs a
  ScheduleStore, agreeing with ServerCapabilities.Scheduling);
  ErrFireNowOverlap now wraps port.ErrFireNowOverlap.

Out of scope (later tasks): the cadence-floor create-seam plumbing + selector
validation (Task 03), the on-by-default flip (Task 03), the settings/CLI
removal (Task 04), the posture note + plan-mode gate (Task 05).

Pins (offline): TestScheduleTool_RegisteredOnlyWhenStoreBacked (AC1.1),
TestScheduleTool_ReadOnlyPartition (AC1.4),
TestScheduleTool_FireAndInspectRoundTrip (AC1.5),
TestScheduleTool_FireOverlapRejected (AC1.5b),
TestScheduleTool_SharesStoreWithRESTSurface (AC1.6).

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…hedule tool

AC1.2 + AC1.2b: the Schedule tool's create verb rides the EXISTING
create-seam (validateScheduleSpec + applyScheduleDefaults over the real
Service), never a second path.

- TestScheduleTool_CreateValidatesLikeRESTSeam pins the cron happy path
  (enabled schedule, cronparse-computed NextFireAt recomputed
  independently) and the fail-closed rejections (invalid cron, non-plan
  non-mutating mode incl. the unset-mode seam default via a raw-spec
  injection, empty workspace on a default-profile schedule) both DIRECTLY
  against the seam (errors.Is ErrInvalidArgument, not-saved) and THROUGH
  the tool over the real seam.
- TestScheduleTool_CreateEnforcesPhase2FieldRules pins the Phase-2 field
  rules by name: one_shot_retry on a cron is rejected fail-closed, and a
  one-shot with one_shot_retry + no max retries gets the seam default 3
  on the saved spec.

The red phase exposed a genuine seam-carrier gap: the tool's args->spec
mapping had no one_shot_retry/one_shot_max_retries fields, so
oneShotRetry:true on a cron was silently dropped (accepted) instead of
rejected fail-closed. Fixed at the args->spec mapping (fields map through
verbatim; all rule enforcement stays in the shared create-seam) — no
parallel validation in the tool, no edit to the shared seam files.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ules CLI (task 04)

Delete the two redundant operator authoring surfaces the in-chat Schedule
tool replaces (ADR 0073 decision 3), clean — no deprecated aliases, no WARN
shims, no presence markers:

- permconfig: the schedules: schema (SchedulesSection, ScheduleDecl,
  Config.Schedules, Resolver.OperatorSchedules, captureSchedules, the
  project-tier-ignore WARN) and its strict-parse tests. A residual
  schedules: key in an old config is silently ignored by the lenient
  top-level decode (pinned by TestScheduleTool_SettingsSchedulesBlockRemoved).
- composition: foldOperatorSchedules + reconcileSchedules
  (internal/app/schedules.go), Config.DeclaredSchedules, and the
  declarative/reconcile/fold tests. Startup no longer reconciles declared
  schedules.
- cmd/mecated: the schedules <verb> subcommand group (schedules_cmd.go +
  tests), the os.Args[1]==schedules dispatch, and the usage-banner line
  (pinned by TestScheduleTool_SchedulesCLIRemoved).
- configgen: the schedules subtree from the model + the source skeleton;
  docs/configuration-reference.md regenerated.
- docs: usage.md drops the declarative + CLI sections (a pointer to the
  in-chat Schedule tool + the gRPC/REST API remains); architecture.md's
  scheduled-tasks section reflects the removal; IMPLEMENTATION-NOTES Phase
  2b records the removal; ADR 0073's citation updated for the deleted file.

The gRPC ScheduleService + REST /v1/schedules surface is RETAINED (the
mecatui /schedule overlay's transport) — pinned end-to-end by
TestScheduleTool_WireSurvivesSettingsCLIRemoval.

Co-Authored-By: mecatl <[email protected]>
…resolve

The task-04 worker left resolve.go referencing the deleted SchedulesSection
(schema removed, references intact — broken build). Remove the residual
operatorSchedules field, OperatorSchedules accessor, project-tier WARN,
both captureSchedules call sites, and the captureSchedules func.

Co-Authored-By: mecatl <[email protected]>
…tion on the default path (AC2.5, task 03)

The scheduler is going ON by default on any schedule-capable store (ADR
0073 decision 2), so the opt-in flag is DELETED outright -- no deprecated
alias, no no-op shim: `mecated --scheduler` fails fast with the standard
unknown-flag error (pinned by TestScheduleTool_SchedulerFlagRemoved,
AC2.5). The disable knob is --no-scheduler (mecak8s keeps its own
equivalent). The --schedule-fire-retention 7d default, previously keyed on
the opt-in flag, now activates whenever the operator did not set it
explicitly -- an explicit =0 still disables the sweep (AC2.1b cmd half).

Co-Authored-By: Claude <[email protected]>
…es (AC2.1/2.1b/2.2/2.3, task 03)

buildScheduler flips to the ADR-0073 decision-2 posture: SchedulerEnabled
true (the cmd default, = !--no-scheduler) + a store exposing a
ScheduleStore ticks with no opt-in; a store with no ScheduleStore (the
in-memory default: mecademo, mecatequi, offline tests) is now SILENTLY
INERT -- the byte-identical no-scheduling path -- instead of failing
startup loud (the pre-flip enabled-but-no-store error). --no-scheduler
restores the pre-change no-tick behaviour while the create/list/fire API
and the Schedule tool registration stay live (their gate is the store,
not the tick loop).

Named pins: TestScheduleTool_SchedulerOnByDefault (AC2.1),
TestScheduleTool_FireRetentionDefaultActiveOnDefaultPath (AC2.1b),
TestScheduleTool_NoSchedulerDisablesTickOnly (AC2.2),
TestScheduleTool_InMemoryStoreByteIdentical (AC2.3), plus the
buildScheduler seam pins in scheduler_default_test.go.

Co-Authored-By: Claude <[email protected]>
…d create-seam (AC1.3/AC1.2c service half, task 03)

validateScheduleSpec becomes a Service method so the SHARED seam (the
Schedule tool's create AND the REST/gRPC create) enforces the two new
deployment-level checks:

- AC1.3: the SchedulerMinInterval cadence floor, previously inert, is now
  CONSULTED at create time -- two consecutive cronparse-computed fires
  give the true cadence (fixed-field AND @every forms), and a tighter
  cadence is rejected fail-closed. 0 = no floor (byte-identical). The
  floor rides the new Service.SetScheduleMinInterval, independent of the
  tick loop (a --no-scheduler deployment still validates).
- AC1.2c: a non-empty provider+model selector is resolved against the
  projected selectable-model inventory (the same snapshot ListModels
  advertises, live-swapped by SetModels) and rejected fail-closed when
  unknown/uncatalogued -- a schedule fire must not silently target a
  provider the deployment never configured. An empty selector (the
  deployment default) is always valid.

Co-Authored-By: Claude <[email protected]>
…ough the tool (AC1.3/AC1.2c, task 03)

Build threads Config.SchedulerMinInterval into the Service create path
UNCONDITIONALLY (svc.SetScheduleMinInterval), so the floor guards the
shared create-seam whether or not the tick loop runs. The selector
validation resolves against the same selectable-model inventory
composition projects (svcCfg.Models / SetModels), so a chat- or
API-created schedule can never pin a provider+model the deployment does
not serve.

Named pins: TestScheduleTool_CreateRejectsUnknownSelector (AC1.2c) and
TestScheduleTool_CreateEnforcesMinInterval (AC1.3), both driven THROUGH
the Schedule tool over the REAL Service seam (a tool wired to a subset
of the seam goes red).

Co-Authored-By: Claude <[email protected]>
…ross the docs (task 03)

- usage.md / user-docs: the scheduler is ON by default on a
  schedule-capable store; --no-scheduler is the opt-out; the deleted
  --scheduler fails fast as an unknown flag; the 7d fire-retention default
  applies whenever unset; --scheduler-min-interval is enforced at the
  create-seam (no longer inert). user-docs/what-you-get/scheduled-tasks.md
  also drops the task-04-removed settings.yaml block + schedules CLI
  sections (stale on the accumulator) and names the in-chat Schedule tool.
- configuration-reference.md: regenerated from configgen (drops the stale
  schedules: section task 04 removed from the generator).
- architecture.md / IMPLEMENTATION-NOTES.md / PRODUCTION-READINESS.md:
  buildScheduler on-by-default + silently-inert no-store path, the
  create-seam's new deployment-level gates (cadence floor + selector
  validation).
- mecatui comments: the --scheduler references become the on-by-default
  tick loop.
- llms.txt regenerated; matlatl strict link gate green.

Co-Authored-By: Claude <[email protected]>
…o, gci, dead citation)

- buildScheduler drops the now-unreachable error return (with the opt-in
  flag gone, enabled-but-no-store is silently inert, so the function
  cannot fail) -- the unparam gate.
- validateScheduleSpec's cron arm extracted to validateCronTrigger (the
  gocyclo cap) -- the selector + floor checks live on the Service method.
- internal/configgen/build.go: gci trailing-newline (pre-existing on the
  accumulator, flagged once the phantom /tmp worktree cache cleared).
- ADR 0073: the cmd/mecated/schedules_cmd.go citation becomes prose (task
  04 deleted the file; the docs/lint citation gate).

Co-Authored-By: Claude <[email protected]>
…ler + full in-chat flow (AC2.4/4.1/4.2/4.3/4.4, task 05)

- ADR 0070 affordance: schedulePostureNote + applySchedulePosture (the
  applyNoFSPosture/applyPlanModePosture idiom) appended to the session Role in
  sessionEngineFactory, gated on the SAME scheduleManagerPresent gate the
  registration uses — AC4.1 pins the note lands VERBATIM on the built engine's
  StablePrefix via the REAL factory path (mutation-proven: removing the wiring
  goes red; generic create/list/fire clauses were vacuous against the
  tool-inventory block).
- Floor posture: TestScheduleTool_FloorScopedAllowAllTiers pins the
  ScopeBuiltinDefault Allow across strict/trusted/auto/yolo (through
  applyPosture over the production mainRules) + config-overridable deny/ask.
- Plan-mode gate: agent.NewPlanAwareScheduleTool (ReadOnly()==true so the
  plan-mode catalog projection advertises it) hard-denies a mutating:true
  create per call before the base tool runs; composition registers it only for
  a plan-mode session's catalog (catalogSession.mode). AC4.3 pinned at the
  engine unit level AND end-to-end through the factory-built plan-mode engine
  (mutation-proven: registering the default tool in plan mode goes red).
- mecatui embedded scheduler (AC2.4): embeddedConfig feeds SchedulerEnabled
  (the on-by-default fold), so the TUI's default per-workspace jsonlstore
  advertises Scheduling AND auto-fires with no flag.
- AC4.4 scenario: offline mockllm drives create→list→fire through the
  factory-built engine; the fire mints a sched-- session run to StopEndTurn.

Engine API: NewPlanAwareScheduleTool is Added (minor) — engine/api/agent.txt +
CHANGELOG note; task api:update run. llms.txt regenerated via offline-built
matlatl; matlatl check --strict green; actrace --strict green (18/18 ACs).

Co-Authored-By: mecatl <[email protected]>
…s, posture defaults

Panel-review ship-blockers on the assembled acc/schedule-tool branch:

1. AC1.4 plan/code deviation (ship-blocker). The plan asserts list/inspect
   report ReadOnly()==true and the mutating verbs false, but the single
   Schedule tool reported false for ALL verbs. Realised the per-verb
   partition as TWO catalog entries over the one port.ScheduleManager: a
   read-only ScheduleQueryTool (list/inspect, ReadOnly()==true, read-parallel)
   and the mutating ScheduleTool (create/pause/resume/delete/fire,
   ReadOnly()==false, serialize). A single tool's no-arg ReadOnly() cannot
   express the split. TestScheduleTool_ReadOnlyPartition now asserts the real
   per-verb split (watched red both directions via planted violations). New
   exported ScheduleQueryTool/NewScheduleQueryTool/ScheduleQueryToolName →
   task api:update + CHANGELOG Added note.

2. Stale living docs (ship-blocker). Scrubbed docs/usage.md,
   docs/architecture.md, docs/design/IMPLEMENTATION-NOTES.md,
   docs/design/PRODUCTION-READINESS.md, docs/tui.md of the REMOVED
   operator-tier settings.yaml schedules: block, the declarative reconcile
   (foldOperatorSchedules/reconcileSchedules), and the mecated schedules CLI.
   The management-surface paragraph names ONLY the surviving surfaces (the
   in-chat Schedule tool, the gRPC ScheduleService + REST /v1/schedules API,
   the mecatui /schedule overlay). On-by-default / --no-scheduler docs kept.
   task docs green (configref + llms.txt regen + matlatl check --strict, 0
   broken/orphan/unreachable).

3. Cadence floor default (security default). --scheduler-min-interval now
   defaults to 1m (was 0/off) in cmd/mecated + cmd/mecak8s, so an
   on-by-default scheduler + the floor-Allow Schedule tool cannot mint an
   unbounded tight-cadence recurring fire out of the box. Pinned by
   TestParseFlagsSchedulerMinIntervalDefault (mecated, watched red at 0) +
   TestParseFlagsK8sDefaults (mecak8s).

4. Plan-mode fire gate (LOW security). schedulePlanModeDeny only blocked
   create+mutating:true; fire passed through. NewPlanAwareScheduleTool now
   takes the ScheduleManager and ALSO denies fire of a mutating schedule
   (reads the create-time Mutating opt-in), consistent with the plan-mode
   hard-deny-on-mutations invariant. A fire of a read-leaning schedule still
   drives through. TestScheduleTool_MutatingCreateGatedByPlanMode extended.

The ScopeBuiltinDefault floor-Allow for create/fire is UNCHANGED per the
brief (deliberate memory-tool-floor precedent).

Gates: task lint=0, task test=0 (both modules + engine-standalone),
task docs=0, task api:check=0, task ac-trace-strict=0.

Co-Authored-By: mecatl <[email protected]>
…, no CrashLoop

Root cause of the k8s e2e BeforeSuite failure: with the scheduler on-by-default
(ADR 0073), a multi-replica mecak8s deployment runs ≥2 replicas over one store;
the replica that loses the __scheduler__ leader-lease race got ErrLeaseHeld from
Scheduler.Start, which startScheduler propagated as a fatal Build error — so
every non-leader replica exited and CrashLooped, never reporting Ready.

Fix (architectural, per the operator's 'correct implementation, no deferrals'):
- Scheduler.Start is now INFALLIBLE-AT-LAUNCH. With a lease backend it launches
  a background LEADERSHIP LOOP that keeps the replica in LEADER (tick+renew) or
  STANDBY (serve RPCs, retry acquire on a backoff, promote when the leader
  lapses). A definitive lease loss demotes to standby; a standby promotes on
  acquire. A transient acquire fault degrades to standby+retry instead of a
  fatal start error.
- FireNow is gated on leadership (ErrNotLeader) so a standby fails a manual
  fire fast rather than double-firing against the leader; mapped to
  ErrScheduleNotLeader → FailedPrecondition/412 on both wire surfaces.
- startScheduler no longer treats the leader race as fatal; the leadership loop
  owns availability.

Co-Authored-By: mecatl <[email protected]>
The standby refactor (Scheduler.Start infallible-at-launch, demote ->
standby -> re-acquire failover, Stop joins the leadership loop) broke two
tests, and their leaks cascaded goleak failures across the whole package:

- TestStandDownOnLeaseHeld -> TestStandbyOnLeaseHeld: Start no longer
  returns ErrLeaseHeld on contention. Rewritten to the standby contract:
  Start returns nil, a due schedule never fires while a peer holds the
  leader lease, LeaderOwner reports leader=false, and Stop joins the
  standby leadership-loop goroutine (the old test never Stopped, leaking
  it into every other test's goleak).
- TestRenewLeaderDefinitiveLossStopsTicking ->
  TestRenewLeaderDefinitiveLossDemotesThenRecovers: a definitive renew
  loss now demotes the epoch and the replica RETRIES the acquire, so the
  old "fires after loss == 1" assertion was pinning pre-failover
  behaviour (and its Fatalf-before-Stop leaked the epoch goroutines,
  cascading goleak onto ~24 tests). Rewritten to the failover contract:
  the replica demotes (WARN proves it), then re-acquires and resumes
  ticking — a schedule made due after the loss eventually fires.

No coverage deleted: at-most-once, singleton overlap, misfire policy,
re-arm, metrics, and FireNow paths are untouched. goleak.VerifyNone is
not weakened — every Start'ed scheduler has a matching Stop.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
JAORMX and others added 3 commits July 25, 2026 19:22
…ticky-unsupported, jitter

Findings from the kimi-k3 software-architect review of the standby loop:

- [High] releaseLeader cleared leader state without demoting: a standby could
  promote and tick while the outgoing epoch still fired. releaseLeader now
  demotes FIRST (cancels the epoch ctx) then releases; tickOnce also gates on
  LeaderOwner as belt-and-braces (a standby never polls Due, even if a tick is
  in flight past the epoch cancel).
- [Medium] ErrScheduleUnsupported 'sticky' stop was defeated by the epoch
  lifecycle: the tick loop cancelled only the current epoch, so the leadership
  loop looped back to acquireLeader and churned a fresh failing epoch every
  TickInterval. A stickyUnsupported flag now stops the leadership loop.
- [Low] Fixed 2s standby backoff had no jitter (thundering-herd on leader
  death): now ±25% uniform jitter (math/rand/v2, the llmresilience precedent).
- [Low] Hand-balanced epochWg.Add(2) replaced with Add(1)-per-goroutine.

Pins: TestStickyUnsupportedStopsLeadershipLoop, TestReleaseLeaderDemotesBeforeRelease,
TestTickOnceNoFireWhenNotLeader.

Co-Authored-By: mecatl <[email protected]>
…0059/0073/0074

Records the operator's previously-folklore stance (one server hosts many
concurrent sessions; scale vertically by session density + horizontally by
replicas; the per-session SessionLease is the exclusion primitive across both)
and the scheduler scaling shape (single global leader for the cheap tick; the
expensive fire drive decoupled into a bounded pool, sharded per-schedule only
if throughput later demands it; CAS-Save token consumption owed as the
split-brain guard). Also indexes the previously-unindexed ADR 0059 + 0073 in
the ADR README so matlatl reachability holds.

Co-Authored-By: mecatl <[email protected]>
The repair wave updated docs/ but not the public user-docs/ tree:
- --scheduler-min-interval default 0 -> 1m (both scheduled-tasks.md + mecated.md)
- mecated.md still documented the removed 'mecated schedules' CLI subcommand;
  now points at the in-chat Schedule tool + ScheduleService API.

Co-Authored-By: mecatl <[email protected]>
@JAORMX
JAORMX merged commit 5053247 into main Jul 26, 2026
22 of 23 checks passed
@JAORMX
JAORMX deleted the acc/schedule-tool branch July 26, 2026 09:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant