Skip to content

feat: scheduled tasks — Phase 2b: settings.yaml schedules + CLI management + metrics (#233) - #238

Merged
JAORMX merged 5 commits into
mainfrom
feat/phase-2b-schedules
Jul 6, 2026
Merged

JAORMX merged 5 commits into
mainfrom
feat/phase-2b-schedules

Conversation

@JAORMX

@JAORMX JAORMX commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Summary

Implements Phase 2b of the scheduled-tasks feature (#189): the settings.yaml schedules: block (operator-tier), mecated schedules CLI management subcommands, and schedule metrics. Closes #233.

Phase 1 (#211) landed the durable foundation. Phase 2a (#237) landed the gRPC/HTTP ScheduleService + EvSchedule* events. This PR adds the declarative + CLI + observability layer on top.

What landed (4 commits, one dev-pipeline wave each)

Wave Commit What
1 6a30e77 settings.yaml schedules: block — operator-tier ONLY (mirrors the guardrails discipline: capture from user-global + CLI tiers only, WARN + ignore on project-tier, strict unknown-key parse per declaration). SchedulesSection + ScheduleDecl in permconfig/schema.go. foldOperatorSchedules + toScheduleSpec mapper + reconcileSchedules (idempotent upsert, no-delete) in internal/app. configgen subtree. UpdateSchedule preserves CreatedAt (pre-existing bug amplified by reconcile).
2 ed908f4 mecated schedules <create|list|inspect|pause|resume|delete|fire> CLI subcommands over the Phase 2a HTTP API. schedulePath helper (url.PathEscape) + validateScheduleName guard (path-injection defense). Follows the existing manual os.Args + stdlib flag pattern. mecak8s deliberately omits CLI subcommands (parity with existing policy).
3 f69afd4 Schedule metrics via a callback seam (Config.ScheduleMetrics, mirroring EmitScheduleEvent). mecatl.schedule.fires_total{outcome} counter + mecatl.schedule.fire_duration_seconds histogram. Scheduler stays telemetry-import-free; composition closes over Metrics.EmitSchedule. NOT a role-family (fires mint fresh sessions whose own runs carry role=main). The 'registered' polled gauge deferred (separate observable-gauge seam).
4 8fad8d5 Docs: PRODUCTION-READINESS ⛔ → ✅, IMPLEMENTATION-NOTES Phase 2b subsection, usage.md syntax + CLI examples, architecture.md section. E2e test through app.Build (operator-tier settings.yaml → fold → reconcile → store; idempotent re-reconcile; project-tier ignored).

Design

  • Operator-tier-only — a project-tier file's schedules: block is IGNORED with a WARN (a project repo cannot register schedules; mirror of the guardrails discipline). Enforced in permconfig.Resolver: captureSchedules runs only from loadUserRules, never loadProjectRules.
  • Idempotent upsert, no delete — reconcileSchedules creates missing schedules and updates differing ones, but does NOT delete schedules removed from the YAML (an operator must delete explicitly via the API/CLI). Documented honestly. A future provenance-tagged Origin field could enable symmetric reconcile.
  • Strict unknown-key parse — each ScheduleDecl uses decodeStrictMapping (the same helper as GuardrailsSection/Permissions). A typo like cronn: is a hard parse error.
  • Metrics callback seam — the scheduler package never imports telemetry; Config.ScheduleMetrics is a plain func(session.SchedulePayload, time.Duration) callback. Fire latency = time.Since(claim-now) measured on the injected Clock.

Verification

  • task lint — 0 issues (golangci-lint v2 + go vet, root + engine modules)
  • task test — full suite green, -race (root + engine + GOWORK=off engine-standalone)
  • task api:check — green (no engine public API changed)
  • task docs — llms.txt regenerated, strict link gate 0 broken
  • go run ./cmd/mecademo — full offline session (regression)
  • E2e (internal/app/schedules_declarative_test.go) — operator-tier settings.yaml → reconcile → store; idempotent re-reconcile; project-tier ignored

Layering

No engine/ changes. The config block, reconcile, CLI, and metrics are all composition-layer (internal/app + internal/adapter/permconfig + cmd/mecated + internal/adapter/telemetry). The scheduler package stays EventSink-free and telemetry-import-free (the callback seam).

What's NOT in this PR (tracked follow-ups)

Co-Authored-By

Juan Osorio Ortiz [email protected]

JAORMX and others added 5 commits July 3, 2026 21:09
…ier) + declarative reconcile

Add an operator-tier-only 'schedules:' block to settings.yaml, mirroring the
guardrails operator-tier-only discipline: capture from user-global + CLI tiers
only, WARN + ignore on project-tier, strict unknown-key parse per declaration.

- internal/adapter/permconfig/schema.go: SchedulesSection (YAML sequence) +
  ScheduleDecl (strict strictFields/UnmarshalYAML), top-level Config field
- internal/adapter/permconfig/resolve.go: operatorSchedules field +
  captureSchedules (first-non-nil, CLI outranks user-global) +
  OperatorSchedules() accessor + project-tier WARN
- internal/app/schedules.go: foldOperatorSchedules + toScheduleSpec mapper
  (defaults Mode=plan for non-mutating; fail-soft per decl) +
  reconcileSchedules (idempotent upsert; no delete — documented)
- internal/app/build.go: DeclaredSchedules cfg field + fold + reconcile after
  scheduler start, gated on SchedulerEnabled
- internal/adapter/server/schedule.go: UpdateSchedule preserves CreatedAt
  (pre-existing bug amplified by the reconcile path)
- configgen: schedules subtree (TierOperator, ListBody) + skeleton/reference
- Tests: operator-tier honoured, project ignored, strict-key, CLI outranks,
  reconcile idempotency (singleton:false), mutating-false-defaults-plan,
  CreatedAt preservation

Part of #189. Closes the settings.yaml pillar of #233.

Co-Authored-By: Juan Osorio Ortiz <[email protected]>
…ect/pause/resume/delete/fire)

Add 'mecated schedules <verb>' subcommands that dial the running server's
HTTP API (/v1/schedules...). Follows the existing manual os.Args dispatch +
stdlib flag pattern (peer of 'mecated config init' / 'mecated skills promote').

- cmd/mecated/main.go: dispatchSubcommand refactor + 'schedules' dispatch
- cmd/mecated/schedules_cmd.go: 7 verbs over the Phase 2a REST surface;
  --server-addr, --output json|text; schedulePath helper (url.PathEscape)
  + validateScheduleName guard (path-injection defense)
- cmd/mecated/schedules_cmd_test.go: httptest-backed tests for all verbs,
  body-shape assertions, missing-flag errors, invalid-name rejection,
  JSON output, server-error propagation

mecak8s deliberately omits CLI subcommands (parity with its existing policy);
k8s users manage schedules via the gRPC/HTTP API.

Part of #189. Closes the CLI management pillar of #233.

Co-Authored-By: Juan Osorio Ortiz <[email protected]>
…fire latency)

Add schedule-fire metrics via a callback seam (Config.ScheduleMetrics), keeping
the scheduler package telemetry-import-free (mirrors EmitScheduleEvent). Composition
closes over telemetry.Metrics.EmitSchedule.

- internal/adapter/telemetry/metrics.go: scheduleFires counter (outcome label:
  fired/skipped/failed) + scheduleFireDuration histogram (in latencyInstruments
  for explicit-bucket views) + EmitSchedule(payload, duration); nil-safe
- internal/adapter/scheduler/scheduler.go: Config.ScheduleMetrics callback +
  SetScheduleMetrics late-bind + emitScheduleMetrics chokepoint in fireClaimed
  (fired/failed, time.Since(claim-now)) and fireOne/FireNow skip paths (duration=0);
  extracted scheduleKindFired/Skipped/Failed constants
- internal/app/build.go: ScheduleMetricsEmitter cfg field + wired in startScheduler
- cmd/mecated + cmd/mecatui/embed: closure over metrics.EmitSchedule (mirrors
  MetricsRoleScoper); mecak8s/mecatequi nil (byte-identical metrics-silent default)
- Tests: scrape assertions + fired/failed/skipped callback invocation with
  deterministic fake-clock durations

Schedule metrics are NOT a role-family (no 'schedule' in roleFamily — fires mint
fresh sessions whose own runs already carry role=main). The 'registered' polled
gauge deferred (a separate observable-gauge seam; core scope covered).

Part of #189. Closes the metrics pillar of #233.

Co-Authored-By: Juan Osorio Ortiz <[email protected]>
…e declarative test

Update living docs to reflect the three Phase 2b pillars (settings.yaml schedules:
block, mecated schedules CLI, schedule metrics) and add an end-to-end test through
app.Build for the declarative → store path.

- docs/design/PRODUCTION-READINESS.md: ⛔ Phase 2b → ✅ shipped
- docs/design/IMPLEMENTATION-NOTES.md: Phase 2b subsection (config + CLI + metrics)
- docs/usage.md: settings.yaml schedules syntax + CLI examples (shipped status)
- docs/architecture.md: declarative config + CLI section
- internal/app/schedules_declarative_test.go: e2e through app.Build — operator-tier
  settings.yaml → foldOperatorSchedules → reconcileSchedules → store; idempotent
  re-reconcile (no churn); project-tier schedules ignored (operator-tier-only)

Part of #189. Closes #233.

Co-Authored-By: Juan Osorio Ortiz <[email protected]>
…de/workspace, profile-aware workspace + singleton honesty

Addresses the review findings on the Phase 2b schedules work (create path, CLI,
metrics, docs). A live end-to-end run against OpenRouter surfaced two of these.

- H1 (server): decode the schedule create/update HTTP body with protojson into
  *mecatlv1.ScheduleSpec (the shape the struct's own comment already claimed)
  instead of a stdlib-json decode of a hand-rolled struct. The old path returned
  HTTP 400 on ANY one-shot trigger (RFC3339 string vs *timestamppb.Timestamp).
  Deletes the now-unused scheduleSpecBody + toProto. Regression test: one-shot
  create round-trip.

- CLI: add --mode and --workspace to `mecated schedules create` and default a
  non-mutating schedule to plan mode (mirroring the declarative fold), so the
  documented basic `create --cron ... --prompt ...` works instead of tripping the
  server's non-mutating-must-be-plan invariant. --mode word -> protojson enum name.

- NEW: validate the workspace PROFILE-AWARE at the schedule create-seam
  (validateScheduleSpec), mirroring the session create-seam — a default-profile
  schedule requires a workspace, a no-fs schedule must not carry one. Fail-closed:
  previously an empty-workspace schedule was accepted at create but failed at FIRE
  time ("workspace is required"), i.e. a schedule that could never fire. Test
  fixtures updated; new TestCreateScheduleWorkspaceProfileInvariant.

- M1 (honesty): foldOperatorSchedules WARNs when a declared singleton:false is
  coerced to true (a bare bool cannot express the opt-out; deferred), and the docs
  + the ScheduleDecl doc-comment (the configref source) state the v1 limitation.

- L2 (CLI): validateScheduleName rejects bare "." / "..".
- L3 (metrics): cover the singleton-overlap skip metric emit path.
- N1/N2 (docs): CLI body-comment honesty; the fire duration is due->terminal, not
  Claim->terminal (metrics.go + architecture / observability / impl-notes).

Verified: task lint + task test green (root + engine + GOWORK=off standalone);
mecademo full offline session; and a LIVE end-to-end run against OpenRouter
(create -> force-fire -> real agent turn "Hello from a scheduled task!" ->
stop=end_turn -> mecatl_schedule_fires_total{outcome="fired"}).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@JAORMX
JAORMX merged commit 55e1808 into main Jul 6, 2026
14 checks passed
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.

Scheduled tasks — Phase 2b: settings.yaml schedules: block (operator-tier) + CLI management + metrics

2 participants