kanade_shared/manifest.rs
1use serde::{Deserialize, Serialize};
2
3use crate::ipc::jobs::JobCategory;
4use crate::wire::{RunAs, Shell, Staleness};
5
6/// YAML job manifest (= registered "what to run", v0.18.0+).
7///
8/// Owns only script-intrinsic fields. **Who** (`target`), **how to
9/// phase fanout** (`rollout`), and **when to stagger start**
10/// (`jitter`) all moved to the Schedule / exec request side — same
11/// script can now be fired against different targets / rollouts
12/// without copying the script body.
13///
14/// #492: these types are READ fleet-wide (agents decode them from
15/// BUCKET_JOBS / BUCKET_SCHEDULES and inside live Commands), so they
16/// must tolerate unknown fields — `deny_unknown_fields` here made a
17/// gradually-upgrading fleet's OLD agents reject the whole object
18/// the moment a newer backend added any field. Operator typo
19/// protection (the old reason for the attribute) lives at the WRITE
20/// boundaries instead: `kanade job/schedule create` and the backend
21/// POST extractor parse via [`crate::strict`], which rejects unknown
22/// keys with their full paths. The wire rule: new fields always get
23/// `#[serde(default)]` (+ `skip_serializing_if` while old readers
24/// may still be strict).
25#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
26pub struct Manifest {
27 pub id: String,
28 pub version: String,
29 #[serde(default)]
30 pub description: Option<String>,
31 pub execute: Execute,
32 #[serde(default)]
33 pub require_approval: bool,
34 /// Opt-in marker that this job produces a JSON inventory fact
35 /// payload on stdout. When present, the backend's results
36 /// projector parses `ExecResult.stdout` as JSON and upserts an
37 /// `inventory_facts` row keyed by `(pc_id, manifest.id)`. The
38 /// `display` sub-config drives the SPA's Inventory page render.
39 #[serde(default)]
40 pub inventory: Option<InventoryHint>,
41 /// Issue #246: opt-in marker that this job emits per-line
42 /// observability events on stdout (one JSON `ObsEvent` per
43 /// newline). When present, the agent — after the script exits
44 /// successfully — parses each non-empty stdout line as an
45 /// `ObsEvent`, publishes it on `obs.<pc_id>` via the
46 /// `obs_outbox`, and (intentionally) **omits the stdout from
47 /// the `ExecResult`** so the timeline data doesn't double up
48 /// in `execution_results.stdout` (which would multiply rows
49 /// by ~50/day/PC of noise).
50 ///
51 /// Distinct from `inventory:` (single JSON object → projector
52 /// upsert) — events are append-only timeline points consumed
53 /// by the dedicated `obs_events` table.
54 #[serde(default)]
55 pub emit: Option<EmitConfig>,
56 /// #290: opt-in marker that this job is an operator-defined
57 /// **health check** whose result feeds the Client App's Health
58 /// tab over KLP (`StateSnapshot.checks`). The script prints a
59 /// free-form JSON object on stdout (like any inventory job); the
60 /// agent reads the [`CheckHint::status_field`] value dynamically
61 /// into a [`crate::ipc::state::Check`] named `check.name`.
62 /// Cadence / windows / conditions come from
63 /// the job's Schedule (exactly like inventory) — there is
64 /// deliberately no interval here. **Composes with `inventory:`**:
65 /// the script's stdout is one JSON object, so a check can also
66 /// carry an `inventory:` block to project the rest of that object
67 /// (incl. `explode` sub-tables) for SPA fleet-querying. Only
68 /// `emit:` (NDJSON stdout) is incompatible.
69 #[serde(default)]
70 pub check: Option<CheckHint>,
71 /// v0.26: Layer 2 staleness policy (SPEC.md §2.6.2). Controls
72 /// what the agent does at fire time when it can't verify the
73 /// `script_current` / `script_status` KV values are fresh —
74 /// especially relevant for `runs_on: agent` schedules where
75 /// the agent may fire from cache while offline. Defaults to
76 /// `Staleness::Cached` (silently use cached values), which
77 /// matches every pre-v0.26 Manifest.
78 #[serde(default)]
79 pub staleness: Staleness,
80 /// #291: opt-in marker that this job is offered to **end users**
81 /// in the Client App's job tabs over KLP (`jobs.list` →
82 /// `jobs.execute`). Parallel to [`inventory`] / [`check`] /
83 /// [`emit`]: the block's mere presence is the opt-in, and it
84 /// groups the end-user presentation fields (name / category /
85 /// icon) that only make sense for a user-facing job. `None`
86 /// (the default) ⇒ an operator-only job — inventory, checks,
87 /// scheduled maintenance — that never surfaces in the catalog.
88 ///
89 /// The agent re-reads this at every `jobs.list` / `jobs.execute`
90 /// (SPEC §2.1), so removing the block takes a job out of a
91 /// running client on its next action.
92 ///
93 /// [`inventory`]: Manifest::inventory
94 /// [`check`]: Manifest::check
95 /// [`emit`]: Manifest::emit
96 #[serde(default, skip_serializing_if = "Option::is_none")]
97 pub client: Option<ClientHint>,
98}
99
100/// "Who + how + when-to-stagger" — the fanout-plan side of an exec.
101/// Used both as the POST `/api/exec/{job_id}` body and as the embedded
102/// `target` / `rollout` / `jitter` slot on [`Schedule`]. Centralising
103/// here keeps the validation + serialisation logic in one place.
104#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default)]
105pub struct FanoutPlan {
106 #[serde(default)]
107 pub target: Target,
108 /// Optional wave rollout — when present, the backend publishes
109 /// each wave's group subject on its own delay schedule instead
110 /// of fanning out the `target` block in one go. `target` then
111 /// only labels the deploy for the audit log.
112 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub rollout: Option<Rollout>,
114 /// Optional humantime jitter; agent uses it to randomise
115 /// execution start. Lives here (not on the script) so different
116 /// schedules / ad-hoc fires of the same job can pick different
117 /// stagger windows.
118 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub jitter: Option<String>,
120 /// Absolute time the scheduler stamps on each emitted Command
121 /// when this exec was driven by a [`Schedule`] with
122 /// `starting_deadline`. Agents receiving a Command after this
123 /// instant publish a synthetic skipped-result instead of
124 /// running the script. `None` (default) = no deadline / catch
125 /// up whenever delivered. Operators don't usually set this
126 /// directly — the scheduler computes it from `tick_at +
127 /// starting_deadline`.
128 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub deadline_at: Option<chrono::DateTime<chrono::Utc>>,
130}
131
132/// Manifest sub-section: how the SPA should render the inventory
133/// facts this job produces. Each field name (`field`) is a top-level
134/// key in the stdout JSON, e.g. `hostname`, `ram_gb`.
135///
136/// Two render modes:
137/// * `display` — vertical "field / value" per PC, used by the
138/// `/inventory?pc=<id>` detail view. ALL columns the operator
139/// wants visible on the detail page.
140/// * `summary` — horizontal table across the fleet (row = PC,
141/// column = field) on `/inventory`. Optional; when omitted the
142/// SPA falls back to `display`, but operators usually want a
143/// trimmer "hostname / OS / CPU / RAM" set for the fleet view.
144#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
145pub struct InventoryHint {
146 /// Detail-view columns, in order.
147 pub display: Vec<DisplayField>,
148 /// Optional fleet-list columns (row = PC). Defaults to `display`
149 /// when omitted, but operators usually pick a 3-5 column subset.
150 #[serde(default, skip_serializing_if = "Option::is_none")]
151 pub summary: Option<Vec<DisplayField>>,
152 /// v0.31 / #40: payload arrays that should be exploded into
153 /// per-element rows of a derived SQLite table. Lets operators
154 /// answer cross-PC questions ("which PCs still have Chrome <
155 /// 120?", "C: >90% full") with normal SQL filters + indexes
156 /// instead of grepping JSON. The projector creates the derived
157 /// table on register and replaces this PC's rows on each result
158 /// (DELETE WHERE pc_id=? AND job_id=? + bulk INSERT). See
159 /// [`ExplodeSpec`] for the per-spec schema.
160 #[serde(default, skip_serializing_if = "Option::is_none")]
161 pub explode: Option<Vec<ExplodeSpec>>,
162 /// v0.35 / #93: top-level scalar fields whose changes the
163 /// projector logs to `inventory_history` (one event per
164 /// changed field per scan). Pairs with `explode[].track_history`
165 /// — that covers array elements; this covers single-valued
166 /// fields like `ram_bytes` / `os_version` / `cpu_model` /
167 /// `os_build` that operators want to track for "did the RAM
168 /// get upgraded?" / "when did Win 11 land on this PC?" /
169 /// "BIOS / firmware bumped?" questions. Field name = `field_path`
170 /// in the history row, `identity_json` is NULL, `before_json`
171 /// / `after_json` each carry `{"value": <prior or new value>}`.
172 /// First-ever observation of a scalar (no prior facts row)
173 /// emits `added`; subsequent value changes emit `changed`. No
174 /// `removed` events — a scalar disappearing from the payload
175 /// is rare and the operator can still see the last value via
176 /// the `before_json` of the most recent change.
177 #[serde(default, skip_serializing_if = "Option::is_none")]
178 pub history_scalars: Option<Vec<String>>,
179}
180
181/// Manifest sub-section (#290): marks a job as an operator-defined
182/// **health check**. Parallel to [`InventoryHint`] / `EmitConfig`.
183/// The stdout contract is a free-form JSON object (same as any
184/// inventory job) from which the agent reads `status_field` /
185/// `detail_field` to build the KLP [`crate::ipc::state::Check`] shown
186/// on the Client App's Health tab.
187///
188/// There is deliberately **no timing field** — when / how often /
189/// in which window a check runs is driven by the job's Schedule,
190/// exactly like inventory jobs, so operators get the full `when:` /
191/// rollout / `runs_on` expressiveness for free.
192///
193/// A check's stdout is a **free-form inventory object** (arbitrary
194/// key/value pairs + arrays) — same as any inventory job — that also
195/// carries a status field. `check:` adds only the health semantics on
196/// top: which field is the ok/warn/fail/unknown status, an optional
197/// one-line summary field, and a remediation job. Everything else
198/// (rich per-PC detail, `explode` sub-tables like a software list) is
199/// driven by a co-present [`InventoryHint`] and rendered with the
200/// SAME display logic the SPA Inventory page uses — on the Client App
201/// too. This keeps checks maximally expressive without a bespoke
202/// payload type.
203#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
204pub struct CheckHint {
205 /// Stable check id → [`Check.name`](crate::ipc::state::Check),
206 /// the SPA/Client React key + analytics label. Unique within the
207 /// fleet's check set.
208 pub name: String,
209 /// Top-level stdout field whose string value
210 /// (`ok`/`warn`/`fail`/`unknown`) becomes the Health-tab light
211 /// ([`CheckStatus`](crate::ipc::state::CheckStatus)). Defaults to
212 /// `"status"`; a missing / unparseable value → `unknown`.
213 #[serde(default = "default_status_field")]
214 pub status_field: String,
215 /// Top-level stdout field used as the Health-tab row's one-line
216 /// summary. Defaults to `"detail"`; absent in the payload → no
217 /// detail line (the rich breakdown lives in the inventory view).
218 #[serde(default = "default_detail_field")]
219 pub detail_field: String,
220 /// Optional remediation job id →
221 /// [`Check.troubleshoot`](crate::ipc::state::Check). The Client
222 /// App shows a "修復する" button when present; that job must be
223 /// `user_invokable`.
224 #[serde(default, skip_serializing_if = "Option::is_none")]
225 pub troubleshoot: Option<String>,
226 /// #290 PR-E: when `true` (default), the backend also projects this
227 /// check's `status` / `detail` into the `check_status` table so the
228 /// operator SPA gets a fleet-wide compliance view for free — no
229 /// `inventory:` block needed. Set `fleet: false` for a client-only
230 /// check the operator doesn't want surfaced across the fleet.
231 #[serde(default = "default_fleet")]
232 pub fleet: bool,
233}
234
235fn default_status_field() -> String {
236 "status".to_string()
237}
238
239fn default_detail_field() -> String {
240 "detail".to_string()
241}
242
243fn default_fleet() -> bool {
244 true
245}
246
247/// Manifest sub-section (#291): marks a job as **user-invokable**
248/// from the Client App and carries how it presents to the end user.
249/// Parallel to [`InventoryHint`] / [`CheckHint`] / `EmitConfig` —
250/// the block's presence is the opt-in (no separate boolean), and its
251/// required fields (`name`, `category`) are enforced by serde at
252/// parse time, so a half-filled catalog entry fails
253/// `kanade job create` instead of rendering a nameless / tab-less row.
254///
255/// The agent maps this 1:1 into the KLP
256/// [`UserInvokableJob`](crate::ipc::jobs::UserInvokableJob) wire shape
257/// that `jobs.list` returns; the Client App renders one row per job in
258/// the tab named by `category`.
259#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
260pub struct ClientHint {
261 /// End-user-facing title for the job row. The operator-internal
262 /// `Manifest::id` slug is rarely what an end user should read, so
263 /// this is required (and validated non-empty by
264 /// [`Manifest::validate`]). Maps to `UserInvokableJob::display_name`.
265 pub name: String,
266 /// Optional one-line subtitle under `name` in the Client App.
267 /// Distinct from the operator-facing top-level
268 /// [`Manifest::description`] — this one is written for the end
269 /// user. Maps to `UserInvokableJob::display_description`.
270 #[serde(default, skip_serializing_if = "Option::is_none")]
271 pub description: Option<String>,
272 /// Which Client App tab the job lives in (`software_update` →
273 /// アップデート, `troubleshoot` → 困ったとき, `catalog` → software
274 /// catalog). Required — without it the agent can't place the job
275 /// in a tab.
276 pub category: JobCategory,
277 /// Optional icon hint for the job row — a lucide-react icon name
278 /// or a `data:` URL. `None` ⇒ the Client App falls back to the
279 /// category's default icon. Surfaced verbatim in
280 /// `jobs.list[].icon`.
281 #[serde(default, skip_serializing_if = "Option::is_none")]
282 pub icon: Option<String>,
283}
284
285/// Issue #246 — `emit:` manifest block for jobs whose stdout is
286/// NDJSON observability events (one `ObsEvent` per line). Parallel
287/// to `inventory:` but for the append-only timeline pipeline; see
288/// `Manifest::emit` for the full contract.
289#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
290pub struct EmitConfig {
291 /// What kind of payload the agent should expect on stdout. Only
292 /// `events` is defined today (parses each non-empty line as
293 /// `ObsEvent` and publishes on `obs.<pc_id>`); future variants
294 /// (e.g. metrics streams, structured trace events) plug in here.
295 #[serde(rename = "type")]
296 pub kind: EmitKind,
297 /// Operator hint for where the script keeps its own state — the
298 /// watermark file the PowerShell / sh body reads + writes
299 /// between runs so it only emits NEW events since the last
300 /// poll. The agent doesn't read this; it's documentation that
301 /// the SPA (and `kanade job edit`) can surface to operators
302 /// reviewing the manifest. Optional; the script is allowed to
303 /// keep state anywhere (registry, env, etc.) — the field's
304 /// presence makes the convention discoverable.
305 #[serde(default, skip_serializing_if = "Option::is_none")]
306 pub watermark_path: Option<String>,
307}
308
309/// `emit.type` enum. Lowercase serde so manifests read
310/// `type: events` rather than `Events`.
311#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
312#[serde(rename_all = "lowercase")]
313pub enum EmitKind {
314 /// Per-line `ObsEvent` JSON. Agent parses + publishes on
315 /// `obs.<pc_id>`, drops the stdout from the resulting
316 /// `ExecResult`.
317 Events,
318}
319
320/// v0.31 / #40: declarative "flatten this JSON array into a real
321/// SQLite table" spec on an inventory manifest. The projector
322/// creates the table on first registration (CREATE TABLE IF NOT
323/// EXISTS + indexes) and writes a row per element of
324/// `payload[field]` on every result, scoped by (pc_id, job_id) so
325/// each PC's rows replace cleanly without a per-PC schema.
326#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
327pub struct ExplodeSpec {
328 /// JSON array key under the payload to explode. E.g. `"apps"`
329 /// for `payload: { apps: [{...}, {...}] }`.
330 pub field: String,
331 /// Derived SQLite table name. Operators choose this — pick
332 /// something namespaced + stable (`inventory_sw_apps`, not
333 /// `apps`) so multiple inventory manifests don't collide on a
334 /// generic name.
335 pub table: String,
336 /// Element-level fields that uniquely identify a row inside one
337 /// PC's payload. The full PK is `(pc_id, job_id) + these
338 /// columns`. Required — operators must think about uniqueness
339 /// (e.g. `["name", "source"]` for installed apps because the
340 /// same name appears in multiple uninstall hives).
341 ///
342 /// v0.31 / #41: same tuple drives history identity. When
343 /// `track_history` is on, the projector serialises these
344 /// fields' values into `inventory_history.identity_json` for
345 /// every change event, so queries like "every PC that ever
346 /// installed Chrome (any source)" filter on identity_json
347 /// content without a per-manifest schema.
348 pub primary_key: Vec<String>,
349 /// Per-element fields that become columns in the derived table.
350 pub columns: Vec<ExplodeColumn>,
351 /// v0.31 / #41: when true (default false), the projector
352 /// diffs each PC's incoming payload against the prior rows
353 /// for the same (pc_id, job_id) BEFORE the DELETE-then-INSERT
354 /// replace, and writes added / removed / changed events into
355 /// `inventory_history`. Lets operators answer time-dimension
356 /// questions ("when did Chrome 120 first appear on PC X?",
357 /// "what's the Win 11 23H2 rollout curve") without storing
358 /// per-scan snapshots. Off by default so operators opt in
359 /// per-spec — history has a real storage cost on long-lived
360 /// deployments (mitigated by the 90-day default retention
361 /// sweeper, see `cleanup` module).
362 #[serde(default)]
363 pub track_history: bool,
364}
365
366/// One column in an [`ExplodeSpec`]'s derived table.
367#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
368pub struct ExplodeColumn {
369 /// JSON key under each array element. Becomes the column name
370 /// in the derived SQLite table — we don't rename.
371 pub field: String,
372 /// SQLite affinity: `"text"` (default), `"integer"`, `"real"`.
373 /// Storage maps directly via `sqlx::query.bind(...)`; type
374 /// mismatches at INSERT-time fail loudly rather than silently
375 /// dropping the row.
376 #[serde(default, skip_serializing_if = "Option::is_none")]
377 #[serde(rename = "type")]
378 pub kind: Option<String>,
379 /// When true, the projector creates a `CREATE INDEX` on this
380 /// column at table-creation time. Boost for the common-filter
381 /// columns (`name`, `version`) — operators mark them
382 /// explicitly, the projector won't guess.
383 #[serde(default)]
384 pub index: bool,
385}
386
387#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
388pub struct DisplayField {
389 /// Top-level key in the stdout JSON.
390 pub field: String,
391 /// Human-readable column header.
392 pub label: String,
393 /// Optional render hint — `"number"`, `"bytes"`, `"timestamp"`,
394 /// or `"table"` (#39). Defaults to plain text rendering on the
395 /// SPA side. `"table"` expects the field's value to be a JSON
396 /// array of objects and renders a nested sub-table on the
397 /// per-PC detail page using `columns` as the schema; the fleet
398 /// summary view falls back to showing the row count for
399 /// `"table"` cells so the wide list stays compact.
400 #[serde(default, skip_serializing_if = "Option::is_none")]
401 #[serde(rename = "type")]
402 pub kind: Option<String>,
403 /// v0.30 / #39: when `kind == "table"`, the SPA renders the
404 /// field's value (an array of objects like
405 /// `disks: [{ device_id, size_bytes, ... }]`) as a nested
406 /// sub-table using these columns. Each column is itself a
407 /// `DisplayField`, so the nested cells reuse the same render
408 /// hints (`bytes`, `number`, `timestamp`) — no parallel format
409 /// pipeline. Ignored for any other `kind`.
410 #[serde(default, skip_serializing_if = "Option::is_none")]
411 pub columns: Option<Vec<DisplayField>>,
412}
413
414#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
415pub struct Rollout {
416 #[serde(default)]
417 pub strategy: RolloutStrategy,
418 pub waves: Vec<Wave>,
419}
420
421#[derive(
422 Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
423)]
424#[serde(rename_all = "lowercase")]
425pub enum RolloutStrategy {
426 #[default]
427 Wave,
428}
429
430#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
431pub struct Wave {
432 pub group: String,
433 /// humantime delay measured from the deploy's publish time. wave[0]
434 /// typically has "0s"; subsequent waves use minutes / hours.
435 pub delay: String,
436}
437
438#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default)]
439pub struct Target {
440 #[serde(default)]
441 pub groups: Vec<String>,
442 #[serde(default)]
443 pub pcs: Vec<String>,
444 #[serde(default)]
445 pub all: bool,
446}
447
448impl Target {
449 /// At least one of all / groups / pcs is set.
450 pub fn is_specified(&self) -> bool {
451 self.all || !self.groups.is_empty() || !self.pcs.is_empty()
452 }
453}
454
455#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
456pub struct Execute {
457 pub shell: ExecuteShell,
458 /// Inline script body. Mutually exclusive with [`script_file`]
459 /// and [`script_object`]; exactly one of the three must be set
460 /// (enforced by [`Execute::validate_script_source`] at the
461 /// write-side parse boundaries — `kanade job create` and
462 /// `POST /api/jobs`).
463 ///
464 /// Empty string is treated as **unset** so operators can swap
465 /// to a `script_file:` / `script_object:` alternative just by
466 /// commenting out the body, without having to also drop the
467 /// `script:` key entirely.
468 ///
469 /// [`script_file`]: Self::script_file
470 /// [`script_object`]: Self::script_object
471 #[serde(default, skip_serializing_if = "Option::is_none")]
472 pub script: Option<String>,
473 /// Repo-local file path resolved by the operator-side CLI at
474 /// `kanade job create` time. The CLI reads the file, slots its
475 /// contents into `script`, and clears this field before
476 /// POSTing — so the backend / agents never see `script_file`
477 /// in stored manifests. SPEC §2.4.1.
478 ///
479 /// Resolver lands in a follow-up PR
480 /// (yukimemi/kanade#210); today this field passes parse-time
481 /// validation but the operator-side CLI bails with "not yet
482 /// implemented" until the resolver ships, so manifests that
483 /// reach the backend with `script_file` set are treated as a
484 /// schema-bug.
485 #[serde(default, skip_serializing_if = "Option::is_none")]
486 pub script_file: Option<String>,
487 /// Object Store reference (`<name>/<version>`) into the
488 /// `scripts` bucket (`OBJECT_SCRIPTS`). Agents fetch the body
489 /// at Execute time via `/api/script-objects/{name}/{version}`
490 /// and cache it locally. SPEC §2.4.1.
491 ///
492 /// Resolver lands in the same follow-up PR as `script_file`;
493 /// today this field passes parse-time validation but the
494 /// backend / agent exec paths bail with "not yet implemented"
495 /// when they see it.
496 #[serde(default, skip_serializing_if = "Option::is_none")]
497 pub script_object: Option<String>,
498 /// humantime duration string (e.g. "30s", "10m"). Script-intrinsic
499 /// — represents how long this script reasonably takes to run.
500 pub timeout: String,
501 /// Token + session combination the agent uses to launch the
502 /// script (v0.21). Default = [`RunAs::System`] (Session 0,
503 /// LocalSystem privileges, no GUI) — matches pre-v0.21 behavior.
504 #[serde(default)]
505 pub run_as: RunAs,
506 /// Working directory for the spawned child (v0.21.1). When
507 /// unset, the child inherits the agent's cwd — on Windows that
508 /// means `%SystemRoot%\System32` for the prod service, which is
509 /// almost never what operators actually want. Use an absolute
510 /// path; relative paths are passed through to the OS verbatim.
511 /// `%PROGRAMDATA%` works for `run_as: system`; for `run_as: user`
512 /// you'd want `%USERPROFILE%` (but expansion happens in the
513 /// shell, so write `$env:USERPROFILE` for PowerShell, or set
514 /// it via teravars before `kanade job create`).
515 #[serde(default, skip_serializing_if = "Option::is_none")]
516 pub cwd: Option<String>,
517}
518
519impl Execute {
520 /// Treat an empty `script:` body as "intentionally unset". Operators
521 /// commenting out a block-scalar tend to leave the key behind, and
522 /// failing the validator on `script: ""` would surprise them.
523 fn has_inline_script(&self) -> bool {
524 matches!(&self.script, Some(s) if !s.is_empty())
525 }
526
527 /// Enforce that exactly one of `script` / `script_file` /
528 /// `script_object` is set. Called at the write-side parse
529 /// boundaries (CLI `kanade job create` + backend
530 /// `POST /api/jobs`) so ambiguous YAML is rejected before it
531 /// reaches the JOBS KV. Read paths (projector, agent
532 /// scheduler, list endpoints) skip this check — they only ever
533 /// see what the write path already validated.
534 pub fn validate_script_source(&self) -> Result<(), String> {
535 let inline = self.has_inline_script();
536 let file = self.script_file.is_some();
537 let obj = self.script_object.is_some();
538 let set = [inline, file, obj].into_iter().filter(|b| *b).count();
539 match set {
540 1 => Ok(()),
541 0 => Err("execute: one of `script`, `script_file`, `script_object` must be set".into()),
542 _ => Err(format!(
543 "execute: only one of `script` / `script_file` / `script_object` may be set \
544 (got script={inline}, script_file={file}, script_object={obj})"
545 )),
546 }
547 }
548}
549
550impl Manifest {
551 /// Cross-field semantic checks that don't fit into pure serde
552 /// derive. Currently delegates to
553 /// [`Execute::validate_script_source`] — see that method's
554 /// docs for the rationale on which call sites should run this.
555 pub fn validate(&self) -> Result<(), String> {
556 self.execute.validate_script_source()?;
557 // Stdout-format compatibility. `inventory:` and `check:` both
558 // consume the SAME single JSON object — they COMPOSE: a check
559 // can extract `status`/`detail` for the Health tab while the
560 // projector explodes the rest into SPA sub-tables. `emit:` is
561 // different — its stdout is NDJSON and the agent omits it from
562 // the result entirely — so it can't be paired with either.
563 if self.emit.is_some() && (self.inventory.is_some() || self.check.is_some()) {
564 return Err(
565 "`emit:` is incompatible with `inventory:` / `check:` — emit's stdout is NDJSON \
566 timeline events (and omitted from the result), while inventory/check read a \
567 single JSON object from stdout"
568 .to_string(),
569 );
570 }
571 // A check's `name` is the Health-tab row id (React key); the
572 // field names tell the agent where to read status/detail.
573 // An empty value is an invisible runtime bug, and the serde
574 // defaults don't guard an operator who writes `status_field:
575 // ""` explicitly — reject all three here.
576 if let Some(check) = &self.check {
577 for (label, value) in [
578 ("check.name", &check.name),
579 ("check.status_field", &check.status_field),
580 ("check.detail_field", &check.detail_field),
581 ] {
582 if value.trim().is_empty() {
583 return Err(format!("{label} must not be empty"));
584 }
585 }
586 // A present-but-blank `troubleshoot` is a broken
587 // remediation job id (the "修復する" button would target
588 // an empty manifest id) — reject it too.
589 if let Some(troubleshoot) = &check.troubleshoot {
590 if troubleshoot.trim().is_empty() {
591 return Err("check.troubleshoot must not be empty when set".to_string());
592 }
593 }
594 }
595 // #291: a `client:` job is rendered in the Client App's
596 // catalog (`jobs.list` → `jobs.execute`). serde already makes
597 // `name` + `category` required at parse time; the only gap is
598 // a present-but-blank `name`, which would render an empty row
599 // title — reject it like the other display-id fields.
600 if let Some(client) = &self.client {
601 if client.name.trim().is_empty() {
602 return Err("client.name must not be empty".to_string());
603 }
604 // Optional display fields, when present, must be
605 // meaningful: a blank `description` renders an empty
606 // subtitle and a blank `icon` is a dangling lucide name.
607 // Same present-but-blank guard the `check:` block applies
608 // to its optional `troubleshoot` id.
609 for (label, value) in [
610 ("client.description", &client.description),
611 ("client.icon", &client.icon),
612 ] {
613 if let Some(v) = value {
614 if v.trim().is_empty() {
615 return Err(format!("{label} must not be empty when set"));
616 }
617 }
618 }
619 }
620 Ok(())
621 }
622}
623
624#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
625#[serde(rename_all = "lowercase")]
626pub enum ExecuteShell {
627 Powershell,
628 Cmd,
629}
630
631impl From<ExecuteShell> for Shell {
632 fn from(s: ExecuteShell) -> Self {
633 match s {
634 ExecuteShell::Powershell => Shell::Powershell,
635 ExecuteShell::Cmd => Shell::Cmd,
636 }
637 }
638}
639
640#[cfg(test)]
641mod tests {
642 use super::*;
643
644 /// The example check-job + schedule YAMLs shipped under `configs/`
645 /// must stay valid as the schema evolves (#290 PR-C). `include_str!`
646 /// pins them at compile time so a breaking edit fails `cargo test`
647 /// rather than only `kanade job create` at deploy time.
648 #[test]
649 fn example_check_job_yamls_parse_and_validate() {
650 let jobs = [
651 (
652 "check-bitlocker",
653 include_str!("../../../configs/jobs/check-bitlocker.yaml"),
654 ),
655 (
656 "check-av-signature",
657 include_str!("../../../configs/jobs/check-av-signature.yaml"),
658 ),
659 (
660 "check-cert-expiry",
661 include_str!("../../../configs/jobs/check-cert-expiry.yaml"),
662 ),
663 ];
664 for (name, yaml) in jobs {
665 let m: Manifest =
666 serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} parse: {e}"));
667 m.validate()
668 .unwrap_or_else(|e| panic!("{name} validate: {e}"));
669 let check = m
670 .check
671 .as_ref()
672 .unwrap_or_else(|| panic!("{name} must carry a check: hint"));
673 assert!(!check.name.trim().is_empty(), "{name} check.name empty");
674 // These three examples all read admin-only WMI namespaces,
675 // so they run_as system. NOTE: that's a property of these
676 // particular checks, NOT of the `check:` contract — a check
677 // probing user-session state could legitimately run_as user.
678 assert_eq!(
679 m.execute.run_as,
680 RunAs::System,
681 "{name} should run_as system"
682 );
683 }
684 }
685
686 /// The example user-invokable job YAMLs (#291) shipped under
687 /// `configs/jobs/` must stay valid as the `client:` schema
688 /// evolves. `include_str!` pins them at compile time so a breaking
689 /// edit fails `cargo test`, not `kanade job create` at deploy.
690 #[test]
691 fn example_client_job_yamls_parse_and_validate() {
692 let jobs = [
693 (
694 "fix-teams-cache",
695 JobCategory::Troubleshoot,
696 include_str!("../../../configs/jobs/fix-teams-cache.yaml"),
697 ),
698 (
699 "chrome-update",
700 JobCategory::SoftwareUpdate,
701 include_str!("../../../configs/jobs/chrome-update.yaml"),
702 ),
703 (
704 "install-slack",
705 JobCategory::Catalog,
706 include_str!("../../../configs/jobs/install-slack.yaml"),
707 ),
708 ];
709 for (id, category, yaml) in jobs {
710 let m: Manifest =
711 serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
712 m.validate()
713 .unwrap_or_else(|e| panic!("{id} validate: {e}"));
714 assert_eq!(m.id, id, "{id} id mismatch");
715 let client = m
716 .client
717 .as_ref()
718 .unwrap_or_else(|| panic!("{id} must carry a client: block"));
719 assert!(!client.name.trim().is_empty(), "{id} client.name empty");
720 assert_eq!(client.category, category, "{id} category");
721 }
722 }
723
724 #[test]
725 fn example_check_schedule_yamls_parse_and_validate() {
726 let schedules = [
727 (
728 "check-bitlocker",
729 include_str!("../../../configs/schedules/check-bitlocker.yaml"),
730 ),
731 (
732 "check-av-signature",
733 include_str!("../../../configs/schedules/check-av-signature.yaml"),
734 ),
735 (
736 "check-cert-expiry",
737 include_str!("../../../configs/schedules/check-cert-expiry.yaml"),
738 ),
739 ];
740 for (name, yaml) in schedules {
741 let s: Schedule =
742 serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
743 s.validate()
744 .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
745 assert_eq!(s.job_id, name, "{name} schedule must reference its job");
746 }
747 }
748
749 #[test]
750 fn target_is_specified_requires_at_least_one_field() {
751 let empty = Target::default();
752 assert!(!empty.is_specified());
753
754 let with_all = Target {
755 all: true,
756 ..Target::default()
757 };
758 assert!(with_all.is_specified());
759
760 let with_groups = Target {
761 groups: vec!["canary".into()],
762 ..Target::default()
763 };
764 assert!(with_groups.is_specified());
765
766 let with_pcs = Target {
767 pcs: vec!["pc-01".into()],
768 ..Target::default()
769 };
770 assert!(with_pcs.is_specified());
771 }
772
773 #[test]
774 fn manifest_deserialises_minimal_yaml() {
775 // Matches jobs/echo-test.yaml. v0.18: no target/rollout/jitter
776 // — those live on the schedule / exec request now.
777 let yaml = r#"
778id: echo-test
779version: 0.0.1
780execute:
781 shell: powershell
782 script: "echo 'kanade'"
783 timeout: 30s
784"#;
785 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
786 assert_eq!(m.id, "echo-test");
787 assert_eq!(m.version, "0.0.1");
788 assert!(matches!(m.execute.shell, ExecuteShell::Powershell));
789 assert_eq!(
790 m.execute.script.as_deref().map(str::trim),
791 Some("echo 'kanade'")
792 );
793 assert!(m.execute.script_file.is_none());
794 assert!(m.execute.script_object.is_none());
795 assert_eq!(m.execute.timeout, "30s");
796 assert!(!m.require_approval);
797 m.validate()
798 .expect("inline-script manifest passes validation");
799 }
800
801 #[test]
802 fn manifest_parses_check_job_and_validates() {
803 // An operator-defined health check (#290): a `check:` hint +
804 // a PowerShell script that prints {status, detail}.
805 let yaml = r#"
806id: check-bitlocker
807version: 0.1.0
808execute:
809 shell: powershell
810 run_as: system
811 timeout: 15s
812 script: |
813 [pscustomobject]@{ status = 'ok'; detail = 'all volumes protected' } | ConvertTo-Json -Compress
814check:
815 name: bitlocker
816 troubleshoot: fix-bitlocker
817"#;
818 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
819 let check = m.check.as_ref().expect("check hint present");
820 assert_eq!(check.name, "bitlocker");
821 assert_eq!(check.troubleshoot.as_deref(), Some("fix-bitlocker"));
822 // Field names default to the conventional "status" / "detail".
823 assert_eq!(check.status_field, "status");
824 assert_eq!(check.detail_field, "detail");
825 assert!(m.inventory.is_none() && m.emit.is_none());
826 m.validate().expect("check-only manifest passes validation");
827 }
828
829 #[test]
830 fn manifest_check_defaults_and_custom_fields() {
831 // Minimal: only `name`; status/detail fields default.
832 let m: Manifest = serde_yaml::from_str(
833 r#"
834id: check-disk
835version: 0.1.0
836execute:
837 shell: powershell
838 script: "[pscustomobject]@{ status = 'ok' } | ConvertTo-Json -Compress"
839 timeout: 10s
840check:
841 name: disk_free
842"#,
843 )
844 .expect("parse");
845 let c = m.check.as_ref().unwrap();
846 assert_eq!(c.name, "disk_free");
847 assert_eq!(c.status_field, "status");
848 assert_eq!(c.detail_field, "detail");
849 assert!(c.troubleshoot.is_none());
850 m.validate().expect("validates");
851
852 // The operator can point status/detail at any field of their
853 // free-form inventory object.
854 let m2: Manifest = serde_yaml::from_str(
855 r#"
856id: check-custom
857version: 0.1.0
858execute:
859 shell: powershell
860 script: "echo x"
861 timeout: 10s
862check:
863 name: patch_level
864 status_field: compliance
865 detail_field: summary
866"#,
867 )
868 .expect("parse");
869 let c2 = m2.check.as_ref().unwrap();
870 assert_eq!(c2.status_field, "compliance");
871 assert_eq!(c2.detail_field, "summary");
872 }
873
874 #[test]
875 fn manifest_allows_check_composed_with_inventory() {
876 // `check:` + `inventory:` COMPOSE on the same stdout object:
877 // status/detail → Health tab, the rest → SPA projection +
878 // explode sub-tables. Must pass validation.
879 let yaml = r#"
880id: check-bitlocker-detailed
881version: 0.1.0
882execute:
883 shell: powershell
884 script: "echo x"
885 timeout: 10s
886check:
887 name: bitlocker
888inventory:
889 display:
890 - { field: status, label: Status }
891"#;
892 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
893 assert!(m.check.is_some() && m.inventory.is_some());
894 m.validate().expect("check + inventory compose");
895 }
896
897 #[test]
898 fn manifest_rejects_check_combined_with_emit() {
899 // `emit:` stdout is NDJSON (and omitted from the result), so
900 // it can't pair with `check:` (which needs a single JSON
901 // object on stdout).
902 let yaml = r#"
903id: bad-mix
904version: 0.1.0
905execute:
906 shell: powershell
907 script: "echo x"
908 timeout: 10s
909check:
910 name: bitlocker
911emit:
912 type: events
913"#;
914 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
915 let err = m.validate().expect_err("emit + check must fail");
916 assert!(err.contains("incompatible"), "err: {err}");
917 }
918
919 #[test]
920 fn manifest_rejects_emit_combined_with_inventory() {
921 // The other half of the emit-incompatibility condition.
922 let yaml = r#"
923id: bad-mix-2
924version: 0.1.0
925execute:
926 shell: powershell
927 script: "echo x"
928 timeout: 10s
929emit:
930 type: events
931inventory:
932 display:
933 - { field: status, label: Status }
934"#;
935 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
936 let err = m.validate().expect_err("emit + inventory must fail");
937 assert!(err.contains("incompatible"), "err: {err}");
938 }
939
940 #[test]
941 fn manifest_rejects_empty_check_field_names() {
942 // Empty name / status_field / detail_field are invisible
943 // runtime bugs (empty React key, agent reads the wrong field)
944 // — reject them even though serde supplies non-empty defaults.
945 let base = |inner: &str| {
946 format!(
947 "id: c\nversion: 0.1.0\nexecute:\n shell: powershell\n script: \"echo x\"\n timeout: 10s\ncheck:\n{inner}"
948 )
949 };
950 for inner in [
951 " name: \"\"\n",
952 " name: ok\n status_field: \"\"\n",
953 " name: ok\n detail_field: \" \"\n",
954 // present-but-blank troubleshoot → broken remediation id.
955 " name: ok\n troubleshoot: \" \"\n",
956 ] {
957 let m: Manifest = serde_yaml::from_str(&base(inner)).expect("parse");
958 let err = m.validate().expect_err("empty field must fail");
959 assert!(err.contains("must not be empty"), "err: {err}");
960 }
961 }
962
963 #[test]
964 fn manifest_client_absent_by_default() {
965 // A plain operator job (the overwhelming majority) carries no
966 // `client:` block, so it never surfaces in the end-user
967 // catalog.
968 let yaml = r#"
969id: echo-test
970version: 0.0.1
971execute:
972 shell: powershell
973 script: "echo 'kanade'"
974 timeout: 30s
975"#;
976 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
977 assert!(m.client.is_none());
978 m.validate().expect("operator-only job validates");
979 }
980
981 #[test]
982 fn manifest_client_parses_and_validates() {
983 // The Client App "困ったとき" remediation job shape: a
984 // user-invokable troubleshoot job with the end-user fields the
985 // KLP `jobs.list` wire needs, grouped under `client:`.
986 let yaml = r#"
987id: fix-teams-cache
988version: 1.0.0
989execute:
990 shell: powershell
991 script: "echo clearing"
992 timeout: 60s
993client:
994 name: "Teams のキャッシュをクリア"
995 description: "Teams が重いときに試してください"
996 category: troubleshoot
997 icon: brush-cleaning
998"#;
999 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
1000 let c = m.client.as_ref().expect("client block present");
1001 assert_eq!(c.name, "Teams のキャッシュをクリア");
1002 assert_eq!(
1003 c.description.as_deref(),
1004 Some("Teams が重いときに試してください")
1005 );
1006 assert_eq!(c.category, JobCategory::Troubleshoot);
1007 assert_eq!(c.icon.as_deref(), Some("brush-cleaning"));
1008 m.validate().expect("user-invokable job validates");
1009 }
1010
1011 #[test]
1012 fn manifest_client_minimal_only_name_and_category() {
1013 // description + icon are optional; name + category are the
1014 // serde-required minimum.
1015 let yaml = r#"
1016id: install-slack
1017version: 1.0.0
1018execute:
1019 shell: powershell
1020 script: "echo install"
1021 timeout: 600s
1022client:
1023 name: Slack
1024 category: catalog
1025"#;
1026 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
1027 let c = m.client.as_ref().expect("client present");
1028 assert_eq!(c.category, JobCategory::Catalog);
1029 assert!(c.description.is_none() && c.icon.is_none());
1030 m.validate().expect("minimal client validates");
1031 }
1032
1033 #[test]
1034 fn manifest_client_rejects_blank_name() {
1035 // serde guarantees `name`/`category` are present; the one gap
1036 // is a present-but-blank name → empty catalog row title.
1037 let yaml = r#"
1038id: j
1039version: 1.0.0
1040execute:
1041 shell: powershell
1042 script: "echo x"
1043 timeout: 30s
1044client:
1045 name: " "
1046 category: catalog
1047"#;
1048 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
1049 let err = m.validate().expect_err("blank name must fail");
1050 assert!(err.contains("client.name"), "err: {err}");
1051 }
1052
1053 #[test]
1054 fn manifest_client_rejects_blank_optional_fields() {
1055 // description / icon are optional, but a present-but-blank
1056 // value is a bug (empty subtitle / dangling icon name) — reject
1057 // it, mirroring the check: block's troubleshoot guard.
1058 for (field, line) in [
1059 ("client.description", " description: \" \"\n"),
1060 ("client.icon", " icon: \"\"\n"),
1061 ] {
1062 let yaml = format!(
1063 "id: j\nversion: 1.0.0\nexecute:\n shell: powershell\n script: \"echo x\"\n timeout: 30s\nclient:\n name: A\n category: catalog\n{line}"
1064 );
1065 let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
1066 let err = m.validate().expect_err("blank optional field must fail");
1067 assert!(err.contains(field), "expected {field} in err: {err}");
1068 }
1069 }
1070
1071 #[test]
1072 fn manifest_client_requires_category_at_parse() {
1073 // A `client:` block missing `category` is a hard parse error
1074 // (serde required field) — no manual validate() needed.
1075 let yaml = r#"
1076id: j
1077version: 1.0.0
1078execute:
1079 shell: powershell
1080 script: "echo x"
1081 timeout: 30s
1082client:
1083 name: "A job"
1084"#;
1085 let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
1086 assert!(
1087 r.is_err(),
1088 "missing category must be a parse error, got {r:?}"
1089 );
1090 }
1091
1092 #[test]
1093 fn manifest_client_rejects_unknown_field() {
1094 // #492: the strict create boundary catches a fat-fingered
1095 // `displayname:` (with its path) instead of silently
1096 // dropping it; the tolerant read path accepts it.
1097 let yaml = r#"
1098id: j
1099version: 1.0.0
1100execute:
1101 shell: powershell
1102 script: "echo x"
1103 timeout: 30s
1104client:
1105 name: "A job"
1106 category: catalog
1107 displayname: oops
1108"#;
1109 let r = crate::strict::from_yaml_str::<Manifest>(yaml);
1110 let err = r.expect_err("unknown client field must be rejected at the write boundary");
1111 // serde_ignored renders the Option layer as `?`:
1112 // `client.?.displayname`. Assert on the leaf key.
1113 assert!(err.contains("displayname"), "{err}");
1114 // The READ path tolerates the same payload (gradual-upgrade
1115 // contract: an old agent must accept a newer writer's field).
1116 let m: Manifest = serde_yaml::from_str(yaml).expect("tolerant read");
1117 assert_eq!(m.client.as_ref().map(|c| c.name.as_str()), Some("A job"));
1118 }
1119
1120 fn execute_with(
1121 script: Option<&str>,
1122 script_file: Option<&str>,
1123 script_object: Option<&str>,
1124 ) -> Execute {
1125 Execute {
1126 shell: ExecuteShell::Powershell,
1127 script: script.map(str::to_owned),
1128 script_file: script_file.map(str::to_owned),
1129 script_object: script_object.map(str::to_owned),
1130 timeout: "30s".into(),
1131 run_as: RunAs::default(),
1132 cwd: None,
1133 }
1134 }
1135
1136 #[test]
1137 fn validate_accepts_inline_script() {
1138 let e = execute_with(Some("echo hi"), None, None);
1139 assert!(e.validate_script_source().is_ok());
1140 }
1141
1142 #[test]
1143 fn validate_accepts_script_file_alone() {
1144 let e = execute_with(None, Some("scripts/cleanup.ps1"), None);
1145 assert!(e.validate_script_source().is_ok());
1146 }
1147
1148 #[test]
1149 fn validate_accepts_script_object_alone() {
1150 let e = execute_with(None, None, Some("cleanup/1.0.0"));
1151 assert!(e.validate_script_source().is_ok());
1152 }
1153
1154 #[test]
1155 fn validate_treats_empty_inline_script_as_unset() {
1156 // `script: ""` + `script_object` set is the natural shape
1157 // when an operator comments out the YAML block-scalar body
1158 // but leaves the key. Should pass.
1159 let e = execute_with(Some(""), None, Some("cleanup/1.0.0"));
1160 assert!(e.validate_script_source().is_ok());
1161 }
1162
1163 #[test]
1164 fn validate_rejects_zero_sources() {
1165 let e = execute_with(None, None, None);
1166 let err = e.validate_script_source().unwrap_err();
1167 assert!(err.contains("must be set"), "got: {err}");
1168 }
1169
1170 #[test]
1171 fn validate_rejects_empty_inline_only() {
1172 let e = execute_with(Some(""), None, None);
1173 let err = e.validate_script_source().unwrap_err();
1174 assert!(err.contains("must be set"), "got: {err}");
1175 }
1176
1177 #[test]
1178 fn validate_rejects_inline_plus_file() {
1179 let e = execute_with(Some("echo hi"), Some("scripts/cleanup.ps1"), None);
1180 let err = e.validate_script_source().unwrap_err();
1181 assert!(err.contains("only one of"), "got: {err}");
1182 }
1183
1184 #[test]
1185 fn validate_rejects_inline_plus_object() {
1186 let e = execute_with(Some("echo hi"), None, Some("cleanup/1.0.0"));
1187 let err = e.validate_script_source().unwrap_err();
1188 assert!(err.contains("only one of"), "got: {err}");
1189 }
1190
1191 #[test]
1192 fn validate_rejects_file_plus_object() {
1193 let e = execute_with(None, Some("scripts/cleanup.ps1"), Some("cleanup/1.0.0"));
1194 let err = e.validate_script_source().unwrap_err();
1195 assert!(err.contains("only one of"), "got: {err}");
1196 }
1197
1198 #[test]
1199 fn validate_rejects_all_three() {
1200 let e = execute_with(
1201 Some("echo hi"),
1202 Some("scripts/cleanup.ps1"),
1203 Some("cleanup/1.0.0"),
1204 );
1205 let err = e.validate_script_source().unwrap_err();
1206 assert!(err.contains("only one of"), "got: {err}");
1207 }
1208
1209 #[test]
1210 fn manifest_deserialises_script_object_yaml() {
1211 // SPEC §2.4.1 example shape with the Object Store
1212 // reference picked over inline.
1213 let yaml = r#"
1214id: cleanup-disk-temp
1215version: 1.0.1
1216execute:
1217 shell: powershell
1218 script_object: cleanup-disk-temp/1.0.1
1219 timeout: 600s
1220"#;
1221 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
1222 assert_eq!(
1223 m.execute.script_object.as_deref(),
1224 Some("cleanup-disk-temp/1.0.1")
1225 );
1226 assert!(m.execute.script.is_none());
1227 m.validate()
1228 .expect("script_object-only manifest passes validation");
1229 }
1230
1231 #[test]
1232 fn manifest_rejects_typo_in_script_field_name() {
1233 // #492: the strict create boundary catches `script_objectt`
1234 // and similar fat-fingers (with the full path) instead of
1235 // letting them silently fall through to "all three unset".
1236 let yaml = r#"
1237id: typo
1238version: 1.0.0
1239execute:
1240 shell: powershell
1241 script_objectt: oops
1242 timeout: 30s
1243"#;
1244 let err = crate::strict::from_yaml_str::<Manifest>(yaml)
1245 .expect_err("typo'd execute field must be rejected at the write boundary");
1246 assert!(err.contains("execute.script_objectt"), "{err}");
1247 }
1248
1249 #[test]
1250 fn schedule_carries_target_and_rollout() {
1251 let yaml = r#"
1252id: hourly-cleanup-canary
1253when:
1254 per_pc: { every: 1h }
1255job_id: cleanup
1256enabled: true
1257target:
1258 groups: [canary, wave1]
1259jitter: 30s
1260rollout:
1261 strategy: wave
1262 waves:
1263 - { group: canary, delay: 0s }
1264 - { group: wave1, delay: 5s }
1265"#;
1266 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
1267 assert_eq!(s.id, "hourly-cleanup-canary");
1268 assert_eq!(s.job_id, "cleanup");
1269 assert_eq!(s.plan.target.groups, vec!["canary", "wave1"]);
1270 assert_eq!(s.plan.jitter.as_deref(), Some("30s"));
1271 let rollout = s.plan.rollout.expect("rollout present");
1272 assert_eq!(rollout.waves.len(), 2);
1273 assert_eq!(rollout.waves[0].group, "canary");
1274 assert_eq!(rollout.waves[1].delay, "5s");
1275 assert_eq!(rollout.strategy, RolloutStrategy::Wave);
1276 }
1277
1278 #[test]
1279 fn schedule_minimal_target_all() {
1280 let yaml = r#"
1281id: kitting
1282when:
1283 per_pc: once
1284enabled: true
1285job_id: scheduled-echo
1286target: { all: true }
1287"#;
1288 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
1289 assert_eq!(s.id, "kitting");
1290 assert_eq!(s.when, When::PerPc(PerPolicy::Once(OnceLiteral::Once)));
1291 assert!(s.enabled);
1292 assert_eq!(s.job_id, "scheduled-echo");
1293 assert!(s.plan.target.all);
1294 assert!(s.plan.rollout.is_none());
1295 assert!(s.plan.jitter.is_none());
1296 assert!(s.active.is_empty());
1297 }
1298
1299 #[test]
1300 fn schedule_enabled_defaults_to_true() {
1301 let yaml = r#"
1302id: x
1303when:
1304 per_pc: once
1305job_id: y
1306target: { all: true }
1307"#;
1308 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
1309 assert!(s.enabled);
1310 }
1311
1312 // ---- `when` parsing (#418 Phase 1) ----
1313
1314 fn schedule_yaml_with(when_block: &str) -> String {
1315 format!(
1316 r#"
1317id: x
1318when:
1319{when_block}
1320job_id: y
1321target: {{ all: true }}
1322"#
1323 )
1324 }
1325
1326 #[test]
1327 fn when_per_pc_every_parses_unquoted_humantime() {
1328 // `6h` is digit-led but non-numeric → YAML string, same as
1329 // the old `cooldown: 6h` convention. No quotes needed.
1330 let s: Schedule =
1331 serde_yaml::from_str(&schedule_yaml_with(" per_pc: { every: 6h }")).expect("parse");
1332 assert_eq!(
1333 s.when,
1334 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() }))
1335 );
1336 }
1337
1338 #[test]
1339 fn when_per_target_every_parses() {
1340 let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(" per_target: { every: 24h }"))
1341 .expect("parse");
1342 assert_eq!(
1343 s.when,
1344 When::PerTarget(PerPolicy::Every(EverySpec {
1345 every: "24h".into()
1346 }))
1347 );
1348 }
1349
1350 #[test]
1351 fn when_per_target_once_parses() {
1352 // Falls out of the shared PerPolicy shape and decide_fire
1353 // already implements it ("any one pc succeeds → skip the
1354 // target forever"), so it is allowed, not rejected.
1355 let s: Schedule =
1356 serde_yaml::from_str(&schedule_yaml_with(" per_target: once")).expect("parse");
1357 assert_eq!(s.when, When::PerTarget(PerPolicy::Once(OnceLiteral::Once)));
1358 }
1359
1360 #[test]
1361 fn when_calendar_time_parses() {
1362 let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(
1363 " calendar:\n at: \"09:00\"\n days: [mon-fri]",
1364 ))
1365 .expect("parse");
1366 match &s.when {
1367 When::Calendar(c) => {
1368 assert_eq!(c.at, "09:00");
1369 assert_eq!(c.days, vec!["mon-fri"]);
1370 }
1371 other => panic!("expected calendar, got {other:?}"),
1372 }
1373 }
1374
1375 #[test]
1376 fn when_calendar_days_default_empty() {
1377 let s: Schedule =
1378 serde_yaml::from_str(&schedule_yaml_with(" calendar:\n at: \"09:00\""))
1379 .expect("parse");
1380 match &s.when {
1381 When::Calendar(c) => assert!(c.days.is_empty(), "days defaults to empty (= daily)"),
1382 other => panic!("expected calendar, got {other:?}"),
1383 }
1384 }
1385
1386 #[test]
1387 fn when_calendar_datetime_parses_all_separators() {
1388 // one-shot: date+time in hyphen / ISO-T / slash forms
1389 for at in ["2026-06-10 09:00", "2026-06-10T09:00", "2026/06/10 09:00"] {
1390 let block = format!(" calendar:\n at: \"{at}\"");
1391 let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(&block))
1392 .unwrap_or_else(|e| panic!("parse '{at}': {e}"));
1393 match &s.when {
1394 When::Calendar(c) => {
1395 use chrono::Datelike;
1396 let p = c.parse_at().expect("parse_at");
1397 let d = p.date.expect("datetime at carries a date");
1398 assert_eq!((d.year(), d.month(), d.day()), (2026, 6, 10), "for '{at}'");
1399 }
1400 other => panic!("expected calendar, got {other:?}"),
1401 }
1402 }
1403 }
1404
1405 #[test]
1406 fn when_rejects_bad_once_keyword() {
1407 // `onec` must be a parse error, not a silently-absorbed
1408 // string (OnceLiteral is a single-variant enum for exactly
1409 // this reason).
1410 let r: Result<Schedule, _> = serde_yaml::from_str(&schedule_yaml_with(" per_pc: onec"));
1411 assert!(r.is_err(), "expected parse error, got {r:?}");
1412 }
1413
1414 #[test]
1415 fn when_rejects_unknown_key_in_every() {
1416 // `{ evry: 6h }` still fails on the tolerant read path: the
1417 // required `every` key is missing, so no PerPolicy variant
1418 // matches (#492 removed deny_unknown_fields, but required
1419 // keys keep the untagged disambiguation honest).
1420 let r: Result<Schedule, _> =
1421 serde_yaml::from_str(&schedule_yaml_with(" per_pc: { evry: 6h }"));
1422 assert!(r.is_err(), "expected parse error, got {r:?}");
1423 }
1424
1425 #[test]
1426 fn when_rejects_unknown_variant() {
1427 let r: Result<Schedule, _> =
1428 serde_yaml::from_str(&schedule_yaml_with(" per_galaxy: once"));
1429 assert!(r.is_err(), "expected parse error, got {r:?}");
1430 }
1431
1432 #[test]
1433 fn when_rejects_old_top_level_cron_field() {
1434 // Pre-#418 shape: top-level `cron:` + no `when:`. Must fail
1435 // loudly (missing `when`), which is what turns stale KV
1436 // blobs into warn-skips after the upgrade.
1437 let yaml = r#"
1438id: x
1439cron: "* * * * * *"
1440job_id: y
1441target: { all: true }
1442"#;
1443 let r: Result<Schedule, _> = serde_yaml::from_str(yaml);
1444 assert!(r.is_err(), "expected parse error, got {r:?}");
1445 }
1446
1447 #[test]
1448 fn when_rejects_retired_cron_escape_hatch() {
1449 // #418 Phase 2 retired `when: { cron: "..." }`. A raw cron
1450 // is now an unknown variant → parse error (operators use the
1451 // calendar form instead).
1452 let r: Result<Schedule, _> =
1453 serde_yaml::from_str(&schedule_yaml_with(" cron: \"0 0 9 * * mon-fri\""));
1454 assert!(
1455 r.is_err(),
1456 "expected parse error for retired cron, got {r:?}"
1457 );
1458 }
1459
1460 #[test]
1461 fn when_round_trips_json_and_yaml() {
1462 // Round-trip through the full Schedule: that is the wire
1463 // unit for both stores (JSON catalog KV + YAML mirror), and
1464 // it exercises the singleton_map field attribute that keeps
1465 // serde_yaml on the map shape instead of `!per_pc` tags.
1466 for when in [
1467 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
1468 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
1469 When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
1470 When::PerTarget(PerPolicy::Every(EverySpec {
1471 every: "24h".into(),
1472 })),
1473 calendar("09:00", &["mon-fri"]),
1474 calendar("2026-06-10 09:00", &[]),
1475 ] {
1476 let s = schedule_with(when.clone(), RunsOn::Backend);
1477
1478 let json = serde_json::to_string(&s).expect("json serialise");
1479 let back: Schedule = serde_json::from_str(&json).expect("json deserialise");
1480 assert_eq!(back.when, when, "json round-trip for {when}");
1481
1482 let yaml = serde_yaml::to_string(&s).expect("yaml serialise");
1483 assert!(
1484 !yaml.contains('!'),
1485 "yaml must use the map shape, not tags: {yaml}"
1486 );
1487 let back: Schedule = serde_yaml::from_str(&yaml).expect("yaml deserialise");
1488 assert_eq!(back.when, when, "yaml round-trip for {when}");
1489 }
1490 }
1491
1492 #[test]
1493 fn when_once_serialises_as_bare_keyword() {
1494 // The wire shape operators see in the YAML mirror must stay
1495 // the ergonomic `per_pc: once`, not a one-variant map.
1496 let json = serde_json::to_value(When::PerPc(PerPolicy::Once(OnceLiteral::Once)))
1497 .expect("serialise");
1498 assert_eq!(json, serde_json::json!({ "per_pc": "once" }));
1499 }
1500
1501 #[test]
1502 fn when_displays_operator_summary() {
1503 for (when, expected) in [
1504 (
1505 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
1506 "per_pc once",
1507 ),
1508 (
1509 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
1510 "per_pc every 6h",
1511 ),
1512 (
1513 When::PerTarget(PerPolicy::Every(EverySpec {
1514 every: "24h".into(),
1515 })),
1516 "per_target every 24h",
1517 ),
1518 (calendar("09:00", &["mon-fri"]), "at 09:00 [mon-fri]"),
1519 (calendar("2026-06-10 09:00", &[]), "at 2026-06-10 09:00"),
1520 ] {
1521 assert_eq!(when.to_string(), expected);
1522 }
1523 }
1524
1525 // ---- lowering (#418: when → engine vocabulary) ----
1526
1527 fn schedule_with(when: When, runs_on: RunsOn) -> Schedule {
1528 Schedule {
1529 id: "x".into(),
1530 when,
1531 job_id: "y".into(),
1532 plan: FanoutPlan::default(),
1533 active: Active::default(),
1534 constraints: Constraints::default(),
1535 on_failure: OnFailure::default(),
1536 tz: ScheduleTz::default(),
1537 starting_deadline: None,
1538 runs_on,
1539 enabled: true,
1540 }
1541 }
1542
1543 fn calendar(at: &str, days: &[&str]) -> When {
1544 When::Calendar(CalendarSpec {
1545 at: at.into(),
1546 days: days.iter().map(|d| (*d).to_string()).collect(),
1547 })
1548 }
1549
1550 #[test]
1551 fn lowering_matches_the_418_table() {
1552 let cases = [
1553 (
1554 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
1555 (POLL_CRON, ExecMode::OncePerPc, None),
1556 ),
1557 (
1558 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
1559 (POLL_CRON, ExecMode::OncePerPc, Some("6h")),
1560 ),
1561 (
1562 When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
1563 (POLL_CRON, ExecMode::OncePerTarget, None),
1564 ),
1565 (
1566 When::PerTarget(PerPolicy::Every(EverySpec {
1567 every: "24h".into(),
1568 })),
1569 (POLL_CRON, ExecMode::OncePerTarget, Some("24h")),
1570 ),
1571 // calendar repeating → 6-field cron
1572 (
1573 calendar("09:00", &["mon-fri"]),
1574 ("0 0 9 * * mon-fri", ExecMode::EveryTick, None),
1575 ),
1576 // calendar daily (no days) → DOW *
1577 (
1578 calendar("18:30", &[]),
1579 ("0 30 18 * * *", ExecMode::EveryTick, None),
1580 ),
1581 // calendar one-shot → 7-field year cron
1582 (
1583 calendar("2026-06-10 09:00", &[]),
1584 ("0 0 9 10 6 * 2026", ExecMode::EveryTick, None),
1585 ),
1586 ];
1587 for (when, (cron, mode, cooldown)) in cases {
1588 let l = schedule_with(when.clone(), RunsOn::Backend).lowered();
1589 assert_eq!(l.cron, cron, "cron for {when}");
1590 assert_eq!(l.mode, mode, "mode for {when}");
1591 assert_eq!(l.cooldown.as_deref(), cooldown, "cooldown for {when}");
1592 }
1593 }
1594
1595 #[test]
1596 fn lowered_carries_schedule_tz() {
1597 for (tz, want) in [
1598 (ScheduleTz::Local, ScheduleTz::Local),
1599 (ScheduleTz::Utc, ScheduleTz::Utc),
1600 ] {
1601 let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
1602 s.tz = tz;
1603 assert_eq!(s.lowered().tz, want, "calendar carries tz");
1604 // reconcile shapes carry tz too (for the active-window check)
1605 let mut s = schedule_with(
1606 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
1607 RunsOn::Backend,
1608 );
1609 s.tz = tz;
1610 assert_eq!(s.lowered().tz, want, "reconcile carries tz");
1611 }
1612 }
1613
1614 #[test]
1615 fn poll_cron_is_accepted_by_the_engine_parser() {
1616 // POLL_CRON is system-generated — if the engine's parser
1617 // ever rejected it every reconcile schedule would die at
1618 // register time. Validate it with the same croner config
1619 // (Seconds::Required, dom_and_dow, year optional).
1620 croner::parser::CronParser::builder()
1621 .seconds(croner::parser::Seconds::Required)
1622 .dom_and_dow(true)
1623 .build()
1624 .parse(POLL_CRON)
1625 .expect("POLL_CRON must parse");
1626 }
1627
1628 // ---- Schedule::validate() (#418 decision F) ----
1629
1630 #[test]
1631 fn validate_accepts_reconcile_shapes() {
1632 for when in [
1633 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
1634 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
1635 When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
1636 When::PerTarget(PerPolicy::Every(EverySpec {
1637 every: "24h".into(),
1638 })),
1639 ] {
1640 schedule_with(when.clone(), RunsOn::Backend)
1641 .validate()
1642 .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
1643 }
1644 }
1645
1646 #[test]
1647 fn validate_accepts_per_pc_on_agent() {
1648 schedule_with(
1649 When::PerPc(PerPolicy::Every(EverySpec { every: "1h".into() })),
1650 RunsOn::Agent,
1651 )
1652 .validate()
1653 .expect("per_pc + agent is the offline-inventory shape");
1654 }
1655
1656 #[test]
1657 fn validate_rejects_per_target_on_agent() {
1658 let err = schedule_with(
1659 When::PerTarget(PerPolicy::Every(EverySpec {
1660 every: "24h".into(),
1661 })),
1662 RunsOn::Agent,
1663 )
1664 .validate()
1665 .unwrap_err();
1666 assert!(err.contains("per_target"), "got: {err}");
1667 assert!(err.contains("runs_on: agent"), "got: {err}");
1668
1669 // per_target: once is also backend-only.
1670 let err = schedule_with(
1671 When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
1672 RunsOn::Agent,
1673 )
1674 .validate()
1675 .unwrap_err();
1676 assert!(err.contains("per_target"), "got (once): {err}");
1677 assert!(err.contains("runs_on: agent"), "got (once): {err}");
1678 }
1679
1680 #[test]
1681 fn validate_rejects_bad_every_duration() {
1682 let err = schedule_with(
1683 When::PerPc(PerPolicy::Every(EverySpec { every: "6x".into() })),
1684 RunsOn::Backend,
1685 )
1686 .validate()
1687 .unwrap_err();
1688 assert!(err.contains("when.every"), "got: {err}");
1689 }
1690
1691 #[test]
1692 fn validate_rejects_bad_jitter_and_starting_deadline() {
1693 let mut s = schedule_with(
1694 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
1695 RunsOn::Backend,
1696 );
1697 s.plan.jitter = Some("5x".into());
1698 let err = s.validate().unwrap_err();
1699 assert!(err.contains("jitter"), "got: {err}");
1700
1701 let mut s = schedule_with(
1702 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
1703 RunsOn::Backend,
1704 );
1705 s.starting_deadline = Some("soon".into());
1706 let err = s.validate().unwrap_err();
1707 assert!(err.contains("starting_deadline"), "got: {err}");
1708 }
1709
1710 #[test]
1711 fn validate_accepts_calendar_shapes() {
1712 for when in [
1713 calendar("09:00", &["mon-fri"]), // weekday morning
1714 calendar("00:00", &["sun"]), // weekly
1715 calendar("18:30", &[]), // daily
1716 calendar("2026-06-10 09:00", &[]), // one-shot
1717 calendar("2026/12/25 00:00", &[]), // one-shot, slash form
1718 ] {
1719 schedule_with(when.clone(), RunsOn::Backend)
1720 .validate()
1721 .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
1722 }
1723 }
1724
1725 #[test]
1726 fn validate_rejects_bad_at() {
1727 for bad in ["25:00", "09:60", "9", "noon", "2026-13-01 09:00"] {
1728 let err = schedule_with(calendar(bad, &[]), RunsOn::Backend)
1729 .validate()
1730 .unwrap_err();
1731 assert!(err.contains("when.at"), "for '{bad}', got: {err}");
1732 }
1733 }
1734
1735 #[test]
1736 fn validate_rejects_datetime_at_with_days() {
1737 // A dated `at` is a one-shot — pairing it with days is a
1738 // contradiction (the date already pins the day).
1739 let err = schedule_with(calendar("2026-06-10 09:00", &["mon"]), RunsOn::Backend)
1740 .validate()
1741 .unwrap_err();
1742 assert!(
1743 err.contains("one-shot") && err.contains("days"),
1744 "got: {err}"
1745 );
1746 }
1747
1748 #[test]
1749 fn validate_rejects_bad_day_name() {
1750 // A garbage DOW token is caught by the days pre-flight and
1751 // reported against `when.days`, not the confusing
1752 // "when.at lowered to invalid cron" (claude #432 review).
1753 let err = schedule_with(calendar("09:00", &["funday"]), RunsOn::Backend)
1754 .validate()
1755 .unwrap_err();
1756 assert!(err.contains("when.days"), "got: {err}");
1757 assert!(err.contains("funday"), "names the bad token: {err}");
1758 // a degenerate range like `mon-` reports the whole token, not
1759 // a cryptic empty part (claude #432 follow-up)
1760 let err = schedule_with(calendar("09:00", &["mon-"]), RunsOn::Backend)
1761 .validate()
1762 .unwrap_err();
1763 assert!(err.contains("'mon-'"), "names the whole token: {err}");
1764 // valid names / ranges / numeric / * all pass
1765 for ok in [
1766 calendar("09:00", &["mon-fri"]),
1767 calendar("09:00", &["mon", "wed", "sun"]),
1768 calendar("09:00", &["1-5"]),
1769 ] {
1770 schedule_with(ok.clone(), RunsOn::Backend)
1771 .validate()
1772 .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
1773 }
1774 }
1775
1776 #[test]
1777 fn validate_accepts_nth_weekday() {
1778 // #418: nth-weekday (Patch Tuesday). validate() also lowers to
1779 // a cron and parses it with croner, so passing here proves the
1780 // whole chain — token → DOW field → engine-acceptable cron.
1781 for ok in [
1782 calendar("09:00", &["tue#2"]), // 2nd Tuesday
1783 calendar("09:00", &["fri#1"]), // 1st Friday
1784 calendar("03:00", &["sun#5"]), // 5th Sunday
1785 calendar("09:00", &["tue#2", "thu#2"]), // a list of nths
1786 calendar("09:00", &["2#2"]), // numeric DOW + ordinal
1787 // Case-insensitive both sides: validate lowercases, croner
1788 // upper-cases the whole pattern before aliasing (claude #547).
1789 calendar("09:00", &["TUE#2"]),
1790 ] {
1791 schedule_with(ok.clone(), RunsOn::Backend)
1792 .validate()
1793 .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
1794 }
1795 }
1796
1797 #[test]
1798 fn validate_rejects_bad_nth_weekday() {
1799 // ordinal out of 1..5, a range with #, and a bad day before #.
1800 for bad in ["tue#0", "tue#6", "tue#x", "mon-fri#2", "funday#2"] {
1801 let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
1802 .validate()
1803 .unwrap_err();
1804 assert!(err.contains("when.days"), "for '{bad}', got: {err}");
1805 }
1806 }
1807
1808 #[test]
1809 fn validate_accepts_last_weekday() {
1810 // #418: last-weekday (`friL` = last Friday). Like the nth case,
1811 // validate() lowers to a cron and round-trips it through croner,
1812 // so passing proves token → DOW field → engine-acceptable cron
1813 // with the verified last-<dow>-of-month semantics.
1814 for ok in [
1815 calendar("09:00", &["friL"]), // last Friday
1816 calendar("03:00", &["sunL"]), // last Sunday
1817 calendar("22:00", &["5L"]), // numeric DOW + last
1818 calendar("00:00", &["0L"]), // numeric Sunday (0…
1819 calendar("00:00", &["7L"]), // …and its 7 alias)
1820 calendar("09:00", &["monL", "friL"]), // a list of last-weekdays
1821 // Case-insensitive both the weekday and the `L` suffix:
1822 // validate lowercases the day, croner upper-cases the whole
1823 // pattern before aliasing (claude #547).
1824 calendar("09:00", &["FRIL"]),
1825 calendar("09:00", &["fril"]),
1826 ] {
1827 schedule_with(ok.clone(), RunsOn::Backend)
1828 .validate()
1829 .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
1830 }
1831 }
1832
1833 #[test]
1834 fn validate_rejects_bad_last_weekday() {
1835 // bare `L` (no weekday — a footgun croner reads as Saturday), a
1836 // range with L, a bad day before L, and an internal space that
1837 // would otherwise leak a malformed cron downstream (gemini #560).
1838 for bad in ["L", "l", "mon-friL", "fundayL", "8L", "*L", "fri L"] {
1839 let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
1840 .validate()
1841 .unwrap_err();
1842 assert!(err.contains("when.days"), "for '{bad}', got: {err}");
1843 }
1844 }
1845
1846 #[test]
1847 fn calendar_oneshot_instant_detects_past() {
1848 use chrono::TimeZone;
1849 // a dated `at` resolves to an absolute instant…
1850 let c = CalendarSpec {
1851 at: "2024-01-01 09:00".into(),
1852 days: vec![],
1853 };
1854 let t = c
1855 .oneshot_instant(ScheduleTz::Utc)
1856 .expect("one-shot instant");
1857 assert_eq!(
1858 t,
1859 chrono::Utc.with_ymd_and_hms(2024, 1, 1, 9, 0, 0).unwrap()
1860 );
1861 assert!(t < chrono::Utc::now(), "2024 is in the past");
1862 // …while a repeating (time-only) calendar has no instant
1863 let rep = CalendarSpec {
1864 at: "09:00".into(),
1865 days: vec!["mon-fri".into()],
1866 };
1867 assert!(rep.oneshot_instant(ScheduleTz::Utc).is_none());
1868 }
1869
1870 fn schedule_with_active(from: Option<&str>, until: Option<&str>) -> Schedule {
1871 let mut s = schedule_with(
1872 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
1873 RunsOn::Backend,
1874 );
1875 s.active = Active {
1876 from: from.map(str::to_owned),
1877 until: until.map(str::to_owned),
1878 };
1879 s
1880 }
1881
1882 #[test]
1883 fn validate_accepts_active_window() {
1884 schedule_with_active(Some("2026-07-01"), Some("2026-08-01T12:00:00+09:00"))
1885 .validate()
1886 .expect("date + rfc3339 bounds should validate");
1887 }
1888
1889 #[test]
1890 fn validate_rejects_unparseable_active_bound() {
1891 let err = schedule_with_active(Some("July 1st"), None)
1892 .validate()
1893 .unwrap_err();
1894 assert!(err.contains("active"), "got: {err}");
1895 }
1896
1897 #[test]
1898 fn validate_rejects_from_not_before_until() {
1899 let err = schedule_with_active(Some("2026-08-01"), Some("2026-07-01"))
1900 .validate()
1901 .unwrap_err();
1902 assert!(err.contains("strictly before"), "got: {err}");
1903
1904 let err = schedule_with_active(Some("2026-07-01"), Some("2026-07-01"))
1905 .validate()
1906 .unwrap_err();
1907 assert!(err.contains("strictly before"), "got: {err}");
1908 }
1909
1910 // ---- Active window semantics ----
1911
1912 #[test]
1913 fn active_window_is_half_open() {
1914 use chrono::TimeZone;
1915 let active = Active {
1916 from: Some("2026-07-01".into()),
1917 until: Some("2026-08-01".into()),
1918 };
1919 // UTC tz so the date bounds are UTC midnight.
1920 let at = |y, m, d, h| chrono::Utc.with_ymd_and_hms(y, m, d, h, 0, 0).unwrap();
1921 let c = |t| active.contains(t, ScheduleTz::Utc);
1922 assert!(!c(at(2026, 6, 30, 23)), "before from");
1923 assert!(c(at(2026, 7, 1, 0)), "at from (inclusive)");
1924 assert!(c(at(2026, 7, 15, 12)), "inside");
1925 assert!(!c(at(2026, 8, 1, 0)), "at until (exclusive)");
1926 assert!(!c(at(2026, 8, 2, 0)), "after until");
1927 }
1928
1929 #[test]
1930 fn active_empty_window_is_always_active() {
1931 assert!(Active::default().contains(chrono::Utc::now(), ScheduleTz::Local));
1932 }
1933
1934 #[test]
1935 fn active_rfc3339_bound_honours_offset_regardless_of_tz() {
1936 use chrono::TimeZone;
1937 let active = Active {
1938 from: Some("2026-07-01T09:00:00+09:00".into()),
1939 until: None,
1940 };
1941 // RFC3339 carries its own offset → tz arg is ignored.
1942 // 09:00 JST = 00:00 UTC.
1943 for tz in [ScheduleTz::Utc, ScheduleTz::Local] {
1944 assert!(
1945 !active.contains(
1946 chrono::Utc
1947 .with_ymd_and_hms(2026, 6, 30, 23, 59, 0)
1948 .unwrap(),
1949 tz
1950 )
1951 );
1952 assert!(active.contains(
1953 chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap(),
1954 tz
1955 ));
1956 }
1957 }
1958
1959 #[test]
1960 fn active_date_bound_respects_tz() {
1961 // A bare `YYYY-MM-DD` bound is midnight *in the schedule's
1962 // tz* (#418 Phase 2). The UTC interpretation is exact and
1963 // host-independent; assert that precisely.
1964 use chrono::TimeZone;
1965 let utc = Active::parse_bound("2026-07-01", ScheduleTz::Utc).expect("utc");
1966 assert_eq!(
1967 utc,
1968 chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap()
1969 );
1970
1971 // The local interpretation must equal what chrono::Local
1972 // computes for the same wall-clock midnight — proves the tz
1973 // path is wired to the host zone (the magnitude vs UTC is
1974 // host-dependent, so we compare against Local directly rather
1975 // than hard-coding the JST offset, keeping CI green on UTC
1976 // runners).
1977 let local = Active::parse_bound("2026-07-01", ScheduleTz::Local).expect("local");
1978 let want = chrono::Local
1979 .with_ymd_and_hms(2026, 7, 1, 0, 0, 0)
1980 .single()
1981 .expect("local midnight is unambiguous")
1982 .with_timezone(&chrono::Utc);
1983 assert_eq!(local, want, "date bound resolved in host-local tz");
1984 }
1985
1986 #[test]
1987 fn active_empty_is_skipped_when_serialising() {
1988 let s = schedule_with(
1989 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
1990 RunsOn::Backend,
1991 );
1992 let json = serde_json::to_value(&s).expect("serialise");
1993 assert!(
1994 json.get("active").is_none(),
1995 "empty active must not appear on the wire: {json}"
1996 );
1997 }
1998
1999 // ---- constraints.window (#418 Phase 3) ----
2000
2001 fn with_window(win: &str) -> Schedule {
2002 let mut s = schedule_with(
2003 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
2004 RunsOn::Backend,
2005 );
2006 s.constraints.window = Some(win.into());
2007 s
2008 }
2009
2010 #[test]
2011 fn constraints_window_parses_and_round_trips() {
2012 let yaml = r#"
2013id: x
2014when:
2015 per_pc: { every: 6h }
2016job_id: y
2017target: { all: true }
2018constraints:
2019 window: "22:00-05:00"
2020"#;
2021 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
2022 assert_eq!(s.constraints.window.as_deref(), Some("22:00-05:00"));
2023 let back: Schedule =
2024 serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
2025 assert_eq!(back.constraints.window.as_deref(), Some("22:00-05:00"));
2026 }
2027
2028 #[test]
2029 fn constraints_empty_is_skipped_when_serialising() {
2030 let s = schedule_with(
2031 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
2032 RunsOn::Backend,
2033 );
2034 let json = serde_json::to_value(&s).expect("serialise");
2035 assert!(
2036 json.get("constraints").is_none(),
2037 "empty constraints must not appear on the wire: {json}"
2038 );
2039 }
2040
2041 #[test]
2042 fn window_no_constraint_always_allows() {
2043 let c = Constraints::default();
2044 assert!(c.allows(chrono::Utc::now(), ScheduleTz::Local));
2045 }
2046
2047 #[test]
2048 fn window_same_day_is_half_open() {
2049 use chrono::TimeZone;
2050 let s = with_window("09:00-17:00");
2051 let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
2052 let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
2053 assert!(!a(at(8, 59)), "before start");
2054 assert!(a(at(9, 0)), "at start (inclusive)");
2055 assert!(a(at(16, 59)), "inside");
2056 assert!(!a(at(17, 0)), "at end (exclusive)");
2057 assert!(!a(at(23, 0)), "after end");
2058 }
2059
2060 #[test]
2061 fn window_crossing_midnight() {
2062 use chrono::TimeZone;
2063 let s = with_window("22:00-05:00");
2064 let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
2065 let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
2066 assert!(a(at(22, 0)), "at start tonight");
2067 assert!(a(at(23, 30)), "late tonight");
2068 assert!(a(at(3, 0)), "early tomorrow");
2069 assert!(!a(at(5, 0)), "at end (exclusive)");
2070 assert!(!a(at(12, 0)), "midday outside");
2071 assert!(!a(at(21, 59)), "just before start");
2072 }
2073
2074 #[test]
2075 fn window_respects_tz() {
2076 // The same instant is inside the window under one tz and may
2077 // be outside under another. Compare UTC vs Local via the
2078 // host's own offset (kept CI-green on UTC runners like the
2079 // active tz test does).
2080 use chrono::TimeZone;
2081 let s = with_window("09:00-17:00");
2082 let noon_utc = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 12, 0, 0).unwrap();
2083 // Under UTC, 12:00 is inside 09:00-17:00.
2084 assert!(s.constraints.allows(noon_utc, ScheduleTz::Utc));
2085 // Under Local, the verdict tracks the host wall-clock time;
2086 // assert it matches a direct wall_time membership check.
2087 let local_t = noon_utc.with_timezone(&chrono::Local).time();
2088 let in_local = local_t >= chrono::NaiveTime::from_hms_opt(9, 0, 0).unwrap()
2089 && local_t < chrono::NaiveTime::from_hms_opt(17, 0, 0).unwrap();
2090 assert_eq!(s.constraints.allows(noon_utc, ScheduleTz::Local), in_local);
2091 }
2092
2093 #[test]
2094 fn validate_accepts_good_window() {
2095 for w in ["09:00-17:00", "22:00-05:00", "00:00-23:59"] {
2096 with_window(w)
2097 .validate()
2098 .unwrap_or_else(|e| panic!("'{w}' should validate: {e}"));
2099 }
2100 }
2101
2102 #[test]
2103 fn validate_rejects_bad_window() {
2104 for bad in ["9-5", "22:00", "22:00-22:00", "25:00-05:00", "09:00_17:00"] {
2105 let err = with_window(bad).validate().unwrap_err();
2106 assert!(
2107 err.contains("constraints.window"),
2108 "for '{bad}', got: {err}"
2109 );
2110 }
2111 }
2112
2113 // ---- constraints.max_concurrent (#418) ----
2114
2115 fn with_max_concurrent(max: u32, runs_on: RunsOn) -> Schedule {
2116 let mut s = schedule_with(
2117 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
2118 runs_on,
2119 );
2120 s.constraints.max_concurrent = Some(max);
2121 s
2122 }
2123
2124 #[test]
2125 fn validate_accepts_backend_max_concurrent() {
2126 with_max_concurrent(5, RunsOn::Backend)
2127 .validate()
2128 .expect("backend max_concurrent should validate");
2129 }
2130
2131 #[test]
2132 fn validate_rejects_max_concurrent_on_agent() {
2133 // Decision E: a central running-instance cap needs a central
2134 // counter, which agents don't have.
2135 let err = with_max_concurrent(5, RunsOn::Agent)
2136 .validate()
2137 .unwrap_err();
2138 assert!(err.contains("constraints.max_concurrent"), "got: {err}");
2139 assert!(err.contains("runs_on: agent"), "got: {err}");
2140 }
2141
2142 #[test]
2143 fn validate_rejects_zero_max_concurrent() {
2144 let err = with_max_concurrent(0, RunsOn::Backend)
2145 .validate()
2146 .unwrap_err();
2147 assert!(err.contains("max_concurrent must be >= 1"), "got: {err}");
2148 }
2149
2150 #[test]
2151 fn max_concurrent_round_trips_and_skips_when_absent() {
2152 let s = with_max_concurrent(3, RunsOn::Backend);
2153 let json = serde_json::to_value(&s.constraints).expect("ser");
2154 assert_eq!(json.get("max_concurrent").and_then(|v| v.as_u64()), Some(3));
2155 // A schedule with no constraints omits the whole block.
2156 let bare = schedule_with(
2157 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
2158 RunsOn::Backend,
2159 );
2160 assert!(bare.constraints.is_empty());
2161 }
2162
2163 #[test]
2164 fn window_fail_closed_on_corrupt_blob() {
2165 // A malformed window (only reachable via a hand-edited KV
2166 // blob — validate() rejects it at create) must BLOCK, not
2167 // silently allow fires during a change-freeze (gemini #452).
2168 let s = with_window("22:00_05:00");
2169 assert!(
2170 !s.constraints.allows(chrono::Utc::now(), ScheduleTz::Utc),
2171 "corrupt window fails closed"
2172 );
2173 // …and the scheduler can surface why it's stuck.
2174 assert!(
2175 s.bad_window().is_some(),
2176 "bad_window reports the parse error"
2177 );
2178 assert!(with_window("22:00-05:00").bad_window().is_none());
2179 }
2180
2181 #[test]
2182 fn calendar_outside_window_is_flagged() {
2183 // at 09:00 can never fall in 22:00-05:00 → never fires.
2184 let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
2185 s.constraints.window = Some("22:00-05:00".into());
2186 assert!(s.calendar_outside_window(), "09:00 is not in 22:00-05:00");
2187
2188 // at 23:00 IS inside the overnight window → fine.
2189 let mut s = schedule_with(calendar("23:00", &[]), RunsOn::Backend);
2190 s.constraints.window = Some("22:00-05:00".into());
2191 assert!(!s.calendar_outside_window(), "23:00 is in 22:00-05:00");
2192
2193 // reconcile shapes are never flagged (they poll every minute).
2194 let mut s = schedule_with(
2195 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
2196 RunsOn::Backend,
2197 );
2198 s.constraints.window = Some("22:00-05:00".into());
2199 assert!(!s.calendar_outside_window(), "reconcile is unaffected");
2200
2201 // no window → never flagged.
2202 let s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
2203 assert!(!s.calendar_outside_window());
2204 }
2205
2206 // ---- on_failure.retry (#418 Phase 4) ----
2207
2208 fn with_retry(max: u32, backoff: &str) -> Schedule {
2209 let mut s = schedule_with(
2210 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
2211 RunsOn::Backend,
2212 );
2213 s.on_failure.retry = Some(Retry {
2214 max,
2215 backoff: backoff.into(),
2216 });
2217 s
2218 }
2219
2220 #[test]
2221 fn on_failure_parses_and_round_trips() {
2222 let yaml = r#"
2223id: x
2224when:
2225 per_pc: { every: 6h }
2226job_id: y
2227target: { all: true }
2228on_failure:
2229 retry: { max: 3, backoff: 10m }
2230"#;
2231 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
2232 let r = s.on_failure.retry.as_ref().expect("retry present");
2233 assert_eq!(r.max, 3);
2234 assert_eq!(r.backoff, "10m");
2235 let back: Schedule =
2236 serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
2237 assert_eq!(back.on_failure, s.on_failure);
2238 }
2239
2240 #[test]
2241 fn on_failure_empty_is_skipped_when_serialising() {
2242 let s = schedule_with(
2243 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
2244 RunsOn::Backend,
2245 );
2246 let json = serde_json::to_value(&s).expect("serialise");
2247 assert!(
2248 json.get("on_failure").is_none(),
2249 "empty on_failure must not appear on the wire: {json}"
2250 );
2251 }
2252
2253 #[test]
2254 fn validate_accepts_good_retry() {
2255 for (max, backoff) in [(1, "30s"), (3, "10m"), (10, "1h")] {
2256 with_retry(max, backoff)
2257 .validate()
2258 .unwrap_or_else(|e| panic!("retry {{max:{max}, backoff:{backoff}}}: {e}"));
2259 }
2260 }
2261
2262 #[test]
2263 fn validate_rejects_bad_backoff() {
2264 let err = with_retry(3, "soon").validate().unwrap_err();
2265 assert!(err.contains("on_failure.retry.backoff"), "got: {err}");
2266 }
2267
2268 #[test]
2269 fn validate_rejects_sub_second_backoff() {
2270 // "500ms" parses as humantime but lowers to 0s on the wire —
2271 // reject it so the operator doesn't get a silent no-wait
2272 // (coderabbit #466).
2273 for bad in ["500ms", "0s", "999ms"] {
2274 let err = with_retry(3, bad).validate().unwrap_err();
2275 assert!(
2276 err.contains("on_failure.retry.backoff must be >= 1s"),
2277 "for '{bad}', got: {err}"
2278 );
2279 }
2280 }
2281
2282 #[test]
2283 fn validate_rejects_out_of_range_max() {
2284 for bad in [0u32, 11, 1000] {
2285 let err = with_retry(bad, "10m").validate().unwrap_err();
2286 assert!(
2287 err.contains("on_failure.retry.max"),
2288 "for max={bad}, got: {err}"
2289 );
2290 }
2291 }
2292
2293 #[test]
2294 fn lowered_retry_reduces_backoff_to_seconds() {
2295 let s = with_retry(3, "10m");
2296 let spec = s.on_failure.lowered_retry().expect("a retry policy");
2297 assert_eq!(spec.max, 3);
2298 assert_eq!(spec.backoff_secs, 600);
2299 }
2300
2301 #[test]
2302 fn lowered_retry_is_none_without_policy() {
2303 let s = schedule_with(
2304 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
2305 RunsOn::Backend,
2306 );
2307 assert!(s.on_failure.lowered_retry().is_none());
2308 }
2309
2310 // ---- global change-freeze (#418 Phase 5) ----
2311
2312 #[test]
2313 fn freeze_empty_window_is_always_active() {
2314 // The big-red-button shape: no bounds = frozen until cleared.
2315 let f = Freeze::default();
2316 assert!(f.is_active(chrono::Utc::now()));
2317 }
2318
2319 #[test]
2320 fn freeze_window_is_half_open() {
2321 use chrono::TimeZone;
2322 let f = Freeze {
2323 from: Some("2026-12-20T00:00:00+00:00".into()),
2324 until: Some("2027-01-05T00:00:00+00:00".into()),
2325 reason: Some("year-end".into()),
2326 tz: ScheduleTz::Utc,
2327 };
2328 let at = |y, mo, d| chrono::Utc.with_ymd_and_hms(y, mo, d, 0, 0, 0).unwrap();
2329 assert!(!f.is_active(at(2026, 12, 19)), "before from = not frozen");
2330 assert!(f.is_active(at(2026, 12, 20)), "from is inclusive");
2331 assert!(f.is_active(at(2026, 12, 31)), "inside window");
2332 assert!(!f.is_active(at(2027, 1, 5)), "until is exclusive");
2333 assert!(!f.is_active(at(2027, 1, 6)), "after until = not frozen");
2334 }
2335
2336 #[test]
2337 fn freeze_fails_closed_on_corrupt_bound() {
2338 // A freeze is a safety switch: an unparseable bound (only
2339 // reachable via a hand-edited KV blob) must read as FROZEN, not
2340 // "fire normally" (coderabbit #472) — the opposite of `active`,
2341 // which fail-opens.
2342 let f = Freeze {
2343 from: Some("not-a-date".into()),
2344 until: None,
2345 reason: None,
2346 tz: ScheduleTz::Utc,
2347 };
2348 assert!(f.is_active(chrono::Utc::now()), "corrupt bound → frozen");
2349 }
2350
2351 #[test]
2352 fn freeze_validate_accepts_good_bounds() {
2353 Freeze {
2354 from: Some("2026-12-20".into()),
2355 until: Some("2027-01-05T12:00:00+09:00".into()),
2356 reason: None,
2357 tz: ScheduleTz::Local,
2358 }
2359 .validate()
2360 .expect("date + rfc3339 bounds should validate");
2361 // Empty (indefinite) freeze is valid.
2362 Freeze::default().validate().expect("empty freeze is valid");
2363 }
2364
2365 #[test]
2366 fn freeze_validate_rejects_bad_bound_and_inverted_window() {
2367 let err = Freeze {
2368 from: Some("never".into()),
2369 ..Default::default()
2370 }
2371 .validate()
2372 .unwrap_err();
2373 assert!(err.contains("freeze:"), "got: {err}");
2374
2375 let inverted = Freeze {
2376 from: Some("2027-01-05".into()),
2377 until: Some("2026-12-20".into()),
2378 ..Default::default()
2379 }
2380 .validate()
2381 .unwrap_err();
2382 assert!(inverted.contains("freeze.from"), "got: {inverted}");
2383 }
2384
2385 #[test]
2386 fn freeze_round_trips_and_skips_empty_fields() {
2387 let f = Freeze {
2388 from: None,
2389 until: Some("2027-01-05".into()),
2390 reason: Some("INC-1234".into()),
2391 tz: ScheduleTz::Utc,
2392 };
2393 let json = serde_json::to_value(&f).expect("serialise");
2394 assert!(json.get("from").is_none(), "empty from omitted: {json}");
2395 let back: Freeze = serde_json::from_value(json).expect("round-trip");
2396 assert_eq!(back, f);
2397 }
2398
2399 #[test]
2400 fn shipped_schedule_configs_parse_and_validate() {
2401 // Every YAML under configs/schedules/ must parse with the
2402 // current Schedule serde AND pass validate() — keeps the
2403 // shipped examples from drifting out of sync with the model
2404 // (#418 removed back-compat, so drift = broken at create).
2405 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../configs/schedules");
2406 let mut seen = 0;
2407 for entry in std::fs::read_dir(&dir).expect("read configs/schedules") {
2408 let path = entry.expect("dir entry").path();
2409 if path.extension().and_then(|e| e.to_str()) != Some("yaml") {
2410 continue;
2411 }
2412 let body = std::fs::read_to_string(&path).expect("read yaml");
2413 let s: Schedule = serde_yaml::from_str(&body)
2414 .unwrap_or_else(|e| panic!("{} failed to parse: {e}", path.display()));
2415 s.validate()
2416 .unwrap_or_else(|e| panic!("{} failed validate(): {e}", path.display()));
2417 seen += 1;
2418 }
2419 assert!(seen > 0, "no schedule YAMLs found in {}", dir.display());
2420 }
2421
2422 // ---- pre-existing enum wire formats (unchanged by #418) ----
2423
2424 #[test]
2425 fn exec_mode_serialises_snake_case() {
2426 for (mode, expected) in [
2427 (ExecMode::EveryTick, "every_tick"),
2428 (ExecMode::OncePerPc, "once_per_pc"),
2429 (ExecMode::OncePerTarget, "once_per_target"),
2430 ] {
2431 let s = serde_json::to_value(mode).expect("serialise");
2432 assert_eq!(s, serde_json::Value::String(expected.into()));
2433 let back: ExecMode = serde_json::from_value(serde_json::Value::String(expected.into()))
2434 .expect("deserialise");
2435 assert_eq!(back, mode, "round-trip for {expected}");
2436 }
2437 }
2438
2439 #[test]
2440 fn schedule_runs_on_defaults_to_backend() {
2441 let yaml = r#"
2442id: x
2443when:
2444 per_pc: once
2445job_id: y
2446target: { all: true }
2447"#;
2448 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
2449 assert_eq!(s.runs_on, RunsOn::Backend);
2450 }
2451
2452 #[test]
2453 fn schedule_runs_on_agent_parses() {
2454 let yaml = r#"
2455id: offline-inv
2456when:
2457 per_pc: { every: 1h }
2458job_id: inventory-hw
2459target: { all: true }
2460runs_on: agent
2461"#;
2462 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
2463 assert_eq!(s.runs_on, RunsOn::Agent);
2464 assert_eq!(s.lowered().mode, ExecMode::OncePerPc);
2465 }
2466
2467 #[test]
2468 fn runs_on_serialises_snake_case() {
2469 for (mode, expected) in [(RunsOn::Backend, "backend"), (RunsOn::Agent, "agent")] {
2470 let s = serde_json::to_value(mode).expect("serialise");
2471 assert_eq!(s, serde_json::Value::String(expected.into()));
2472 let back: RunsOn = serde_json::from_value(serde_json::Value::String(expected.into()))
2473 .expect("deserialise");
2474 assert_eq!(back, mode);
2475 }
2476 }
2477
2478 #[test]
2479 fn execute_shell_into_wire_shell() {
2480 assert_eq!(Shell::from(ExecuteShell::Powershell), Shell::Powershell);
2481 assert_eq!(Shell::from(ExecuteShell::Cmd), Shell::Cmd);
2482 }
2483
2484 #[test]
2485 fn manifest_staleness_defaults_to_cached() {
2486 let yaml = r#"
2487id: x
2488version: 1.0.0
2489execute:
2490 shell: powershell
2491 script: "echo"
2492 timeout: 1s
2493"#;
2494 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2495 assert_eq!(m.staleness, Staleness::Cached);
2496 }
2497
2498 #[test]
2499 fn manifest_strict_staleness_parses() {
2500 let yaml = r#"
2501id: urgent-patch
2502version: 2.5.1
2503execute:
2504 shell: powershell
2505 script: Install-Hotfix
2506 timeout: 5m
2507staleness:
2508 mode: strict
2509 max_cache_age: 0s
2510"#;
2511 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2512 match m.staleness {
2513 Staleness::Strict { max_cache_age } => assert_eq!(max_cache_age, "0s"),
2514 other => panic!("expected strict, got {other:?}"),
2515 }
2516 }
2517
2518 #[test]
2519 fn manifest_unchecked_staleness_parses() {
2520 let yaml = r#"
2521id: legacy
2522version: 0.1.0
2523execute:
2524 shell: cmd
2525 script: "echo"
2526 timeout: 1s
2527staleness:
2528 mode: unchecked
2529"#;
2530 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2531 assert_eq!(m.staleness, Staleness::Unchecked);
2532 }
2533
2534 #[test]
2535 fn missing_required_field_errors() {
2536 // `id` missing.
2537 let yaml = r#"
2538version: 1.0.0
2539target: { all: true }
2540execute:
2541 shell: powershell
2542 script: "echo"
2543 timeout: 1s
2544"#;
2545 let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
2546 assert!(r.is_err(), "expected error, got {:?}", r);
2547 }
2548
2549 #[test]
2550 fn display_field_table_kind_round_trips_with_nested_columns() {
2551 // #39: `type: table` + `columns:` on a DisplayField gets
2552 // round-tripped through serde so the SPA receives the
2553 // nested schema verbatim. Nested columns themselves are
2554 // DisplayFields so they can carry `type: bytes` /
2555 // `type: number` for cell formatting.
2556 let yaml = r#"
2557id: inv-hw
2558version: 1.0.0
2559execute:
2560 shell: powershell
2561 script: "echo"
2562 timeout: 60s
2563inventory:
2564 display:
2565 - field: hostname
2566 label: Hostname
2567 - field: disks
2568 label: Disks
2569 type: table
2570 columns:
2571 - field: device_id
2572 label: Drive
2573 - field: size_bytes
2574 label: Size
2575 type: bytes
2576 - field: free_bytes
2577 label: Free
2578 type: bytes
2579 - field: file_system
2580 label: FS
2581"#;
2582 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2583 let inv = m.inventory.as_ref().expect("inventory hint");
2584 let disks = inv
2585 .display
2586 .iter()
2587 .find(|d| d.field == "disks")
2588 .expect("disks display row");
2589 assert_eq!(disks.kind.as_deref(), Some("table"));
2590 let cols = disks.columns.as_ref().expect("table needs columns");
2591 assert_eq!(cols.len(), 4);
2592 assert_eq!(cols[1].field, "size_bytes");
2593 assert_eq!(cols[1].kind.as_deref(), Some("bytes"));
2594 }
2595
2596 #[test]
2597 fn display_field_scalar_kind_keeps_columns_none() {
2598 // Defensive: when type is a scalar (`bytes` / `number` /
2599 // `timestamp`) the `columns` field stays None — the SPA
2600 // uses its presence as the "render nested table" signal,
2601 // so it must not leak in via serde defaults.
2602 let yaml = r#"
2603id: x
2604version: 1.0.0
2605execute:
2606 shell: powershell
2607 script: "echo"
2608 timeout: 5s
2609inventory:
2610 display:
2611 - { field: ram_bytes, label: RAM, type: bytes }
2612"#;
2613 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2614 let inv = m.inventory.as_ref().unwrap();
2615 assert!(inv.display[0].columns.is_none());
2616 }
2617}
2618
2619/// Periodic schedule (spec §2.4.3). v0.18.0 carries the fanout plan
2620/// (target + optional rollout + optional jitter) inline; the
2621/// referenced job (`job_id` → [`BUCKET_JOBS`]) supplies only the
2622/// script body. Two schedules of the same job can target different
2623/// groups on different cadences without copying the manifest.
2624///
2625/// #418 Phase 1: the cadence is the single [`When`] field. The old
2626/// `cron` × `mode` × `cooldown` × `auto_disable_when_done` quartet
2627/// is gone (no back-compat — pre-Phase-1 KV blobs fail to parse and
2628/// are warn-skipped; re-`schedule create` to upgrade them). The
2629/// engine underneath is unchanged: [`Schedule::lowered`] maps `when`
2630/// onto the same (cron, ExecMode, cooldown) trio the scheduler and
2631/// `decide_fire` always ran on.
2632#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2633pub struct Schedule {
2634 pub id: String,
2635 /// When to fire — a reconcile cadence (`per_pc` / `per_target`)
2636 /// or a calendar time trigger (`at` / `days`). See [`When`].
2637 ///
2638 /// `singleton_map`: serde_yaml 0.9 renders externally-tagged
2639 /// enums as `!per_pc` YAML tags by default; this keeps the
2640 /// operator-facing map shape (`when: { per_pc: once }`). JSON
2641 /// output is identical either way, and the schemars schema
2642 /// (external tagging = oneOf of single-key objects) already
2643 /// matches the singleton-map wire shape.
2644 #[serde(with = "serde_yaml::with::singleton_map")]
2645 #[schemars(with = "When")]
2646 pub when: When,
2647 /// Key into [`crate::kv::BUCKET_JOBS`]. Must equal a registered
2648 /// Manifest's `id`.
2649 pub job_id: String,
2650 /// Who + how-to-phase + when-to-stagger. The Manifest doesn't
2651 /// carry these any more — same job + different fanout = different
2652 /// schedule.
2653 #[serde(flatten)]
2654 pub plan: FanoutPlan,
2655 /// Optional validity window. Outside `[from, until)` the
2656 /// schedule is dormant — still registered, still visible, but
2657 /// every tick is skipped (deleted ≠ dormant: a campaign that
2658 /// ended stays inspectable and can be re-armed by editing the
2659 /// window). Checked at tick time on both the backend scheduler
2660 /// and the agent's local scheduler.
2661 #[serde(default, skip_serializing_if = "Active::is_empty")]
2662 pub active: Active,
2663 /// #418 Phase 3: operational constraints gating *when within an
2664 /// active period* a fire may happen. Currently just `window`
2665 /// (a maintenance time-of-day window); future `require`
2666 /// (env gates) and `max_concurrent` land in the same namespace.
2667 /// Evaluated in the schedule's `tz` like the other wall-clock
2668 /// fields. Checked at tick time on both schedulers.
2669 #[serde(default, skip_serializing_if = "Constraints::is_empty")]
2670 pub constraints: Constraints,
2671 /// #418 Phase 4: what to do after a fire's script comes back
2672 /// failed. Currently just `retry` (fixed-backoff in-process
2673 /// re-run); future `notify` / `disable` join the same namespace.
2674 /// Applied fire-side in `handle_command` (the retry policy is
2675 /// lowered onto every Command this schedule produces), so it
2676 /// covers both `runs_on` locations.
2677 #[serde(default, skip_serializing_if = "OnFailure::is_empty")]
2678 pub on_failure: OnFailure,
2679 /// #418 Phase 2: the timezone this schedule's wall-clock fields
2680 /// are evaluated in — both the calendar `at` firing time AND the
2681 /// `active.{from,until}` window bounds. `local` (default) = the
2682 /// running host's TZ (the agent's for `runs_on: agent`, the
2683 /// backend server's otherwise); `utc` for TZ-independent
2684 /// schedules. Reconcile shapes (`per_pc`/`per_target`) ignore it
2685 /// for firing (poll cron runs every minute regardless) but still
2686 /// honor it for the `active` window.
2687 #[serde(default)]
2688 pub tz: ScheduleTz,
2689 /// v0.22: optional humantime window after a cron tick during
2690 /// which the Command is still considered "live". The scheduler
2691 /// computes `tick_at + starting_deadline` and stamps it onto
2692 /// each Command as `deadline_at`; agents skip Commands they
2693 /// receive after that absolute time. `None` (default) = no
2694 /// deadline, meaning a Command queued in the broker / stream
2695 /// during agent downtime runs whenever the agent reconnects —
2696 /// good for kitting / inventory / cleanup. Set this for
2697 /// time-of-day notifications, lunch reminders, etc., where
2698 /// "fire 3 hours late" would be wrong.
2699 #[serde(default, skip_serializing_if = "Option::is_none")]
2700 pub starting_deadline: Option<String>,
2701 /// v0.23: where does the cron tick happen? `Backend` (default,
2702 /// historical) = backend's scheduler fires Commands via NATS;
2703 /// agents passively receive. `Agent` = each targeted agent runs
2704 /// its own internal cron and fires locally, so the schedule
2705 /// keeps ticking even when the broker is unreachable (laptop on
2706 /// the train, broker maintenance window, full WAN outage). The
2707 /// two locations are mutually exclusive — when `Agent`, the
2708 /// backend scheduler stays out and just keeps the definition in
2709 /// KV for agents to read.
2710 #[serde(default)]
2711 pub runs_on: RunsOn,
2712 #[serde(default = "default_true")]
2713 pub enabled: bool,
2714}
2715
2716/// v0.23 — where the cron tick fires from.
2717#[derive(
2718 Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
2719)]
2720#[serde(rename_all = "snake_case")]
2721pub enum RunsOn {
2722 /// Backend's central scheduler ticks and publishes Commands to
2723 /// NATS. Historical default, what every pre-v0.23 schedule
2724 /// uses. Agent offline ⇒ Command queued in STREAM_EXEC; agent
2725 /// reconnects ⇒ catch-up via [`command_replay`](crate)
2726 /// (see kanade-agent's command_replay module).
2727 #[default]
2728 Backend,
2729 /// Each targeted agent runs the cron tick locally. Survives
2730 /// broker / WAN outages. Best for laptops / mobile devices that
2731 /// roam off the corporate network. Agent must be online for the
2732 /// initial schedule + job-catalog pull, but once cached the
2733 /// agent fires the script standalone.
2734 Agent,
2735}
2736
2737/// Per-pc/per-target dedup semantics for a [`Schedule`] (v0.19).
2738#[derive(
2739 Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
2740)]
2741#[serde(rename_all = "snake_case")]
2742pub enum ExecMode {
2743 /// Fire on every cron tick at the whole target. Historical
2744 /// (pre-v0.19) behavior; no dedup.
2745 #[default]
2746 EveryTick,
2747 /// Fire at each pc until that pc succeeds; then skip it until
2748 /// the optional cooldown elapses (or forever if no cooldown).
2749 /// Use for kitting / first-boot / per-pc compliance checks.
2750 OncePerPc,
2751 /// Fire at the whole target until **any** pc succeeds; then
2752 /// skip the whole target until the optional cooldown elapses
2753 /// (or forever if no cooldown). Use for "one delegate is
2754 /// enough" tasks like license check-in.
2755 OncePerTarget,
2756}
2757
2758/// #418 Phase 1 — the single "when does this fire" axis.
2759///
2760/// Replaces the old `cron` + `mode` + `cooldown` trio whose
2761/// interactions were implicit (cron doubled as both a real
2762/// time-of-day trigger and a reconcile poll period; contradictory
2763/// combinations silently no-opped). Two shapes:
2764///
2765/// * **reconcile** (`per_pc` / `per_target`) — desired-state: "each
2766/// pc (or one delegate) should have run this within `every`".
2767/// The poll period is system-generated ([`POLL_CRON`], every
2768/// minute) and no longer the operator's concern.
2769/// * **calendar** (`{ at, days }`) — a wall-clock time trigger
2770/// (#418 Phase 2, replacing the old raw-cron escape hatch). Fires
2771/// the whole target at the given time, no dedup. `at: "09:00"` +
2772/// `days` repeats; `at: "2026-06-10 09:00"` (a date+time) fires
2773/// exactly once. Evaluated in the schedule's top-level `tz`.
2774#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
2775#[serde(rename_all = "snake_case")]
2776pub enum When {
2777 /// Fire at each targeted pc: `once` (kitting — succeed once,
2778 /// skip forever, forever catching brand-new / re-imaged pcs)
2779 /// or `{ every: <humantime> }` (patrol — re-arm per pc after
2780 /// the interval).
2781 PerPc(PerPolicy),
2782 /// Fire until **any** one pc of the target succeeds, then skip
2783 /// the whole target (`once`) or re-arm after `every`. Needs
2784 /// fleet-wide completion data, so it is backend-only —
2785 /// `runs_on: agent` + `per_target` is rejected by
2786 /// [`Schedule::validate`].
2787 PerTarget(PerPolicy),
2788 /// Calendar time trigger: `{ at: "09:00", days: [mon-fri] }`
2789 /// (repeating) or `{ at: "2026-06-10 09:00" }` (one-shot). Fires
2790 /// the whole target at that wall-clock time in the schedule's
2791 /// `tz` — no dedup, no cooldown.
2792 Calendar(CalendarSpec),
2793}
2794
2795/// Calendar time trigger (#418 Phase 2). `at` is either a time of
2796/// day (`"HH:MM"`, repeating — combine with `days`) or a full
2797/// date+time (`"YYYY-MM-DD HH:MM"`, a one-shot that fires once and
2798/// never again). Evaluated in the schedule's top-level `tz`.
2799#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
2800pub struct CalendarSpec {
2801 /// `"HH:MM"` (24h) for a repeating trigger, or
2802 /// `"YYYY-MM-DD HH:MM"` (hyphen / slash / `T` separators all
2803 /// accepted) for a one-shot. Parsed lazily —
2804 /// [`Schedule::validate`] rejects garbage at create time.
2805 pub at: String,
2806 /// Day-of-week filter for a time-of-day `at`: `["mon-fri"]`,
2807 /// `["mon","wed","fri"]`, … (passed verbatim to the cron DOW
2808 /// field, so ranges and names both work). An **nth-weekday**
2809 /// `["tue#2"]` fires only on the 2nd Tuesday of each month
2810 /// ("Patch Tuesday"); the ordinal is `1..5`. A **last-weekday**
2811 /// `["friL"]` fires only on the last Friday of each month (handy
2812 /// for monthly maintenance). Empty = every day. Must be empty
2813 /// when `at` carries a date (the date already pins the day).
2814 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2815 pub days: Vec<String>,
2816}
2817
2818/// Parsed `CalendarSpec.at`: the wall-clock minute/hour, plus the
2819/// date for a one-shot (`None` = repeating time-of-day).
2820struct ParsedAt {
2821 minute: u32,
2822 hour: u32,
2823 date: Option<chrono::NaiveDate>,
2824}
2825
2826impl CalendarSpec {
2827 /// Parse `at`: a date+time (`YYYY-MM-DD HH:MM`, hyphen / slash /
2828 /// `T` separators) is a one-shot; a bare `HH:MM` is repeating.
2829 fn parse_at(&self) -> Result<ParsedAt, String> {
2830 use chrono::Timelike;
2831 let s = self.at.trim();
2832 for fmt in ["%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y/%m/%d %H:%M"] {
2833 if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, fmt) {
2834 return Ok(ParsedAt {
2835 minute: dt.minute(),
2836 hour: dt.hour(),
2837 date: Some(dt.date()),
2838 });
2839 }
2840 }
2841 if let Ok(t) = chrono::NaiveTime::parse_from_str(s, "%H:%M") {
2842 return Ok(ParsedAt {
2843 minute: t.minute(),
2844 hour: t.hour(),
2845 date: None,
2846 });
2847 }
2848 Err(format!(
2849 "when.at: unparseable '{}' (want HH:MM or YYYY-MM-DD HH:MM)",
2850 self.at
2851 ))
2852 }
2853
2854 /// Pre-flight check on the `days` tokens so a bad day name gives
2855 /// a `when.days:`-scoped error instead of croner's confusing
2856 /// "when.at lowered to invalid cron" (claude #432 review). Each
2857 /// token is a day name (`mon`..`sun`), a numeric DOW (`0`..`7`),
2858 /// `*`, a `-` range of those, an **nth-weekday** like `tue#2`
2859 /// (2nd Tuesday of the month — "Patch Tuesday"), or a
2860 /// **last-weekday** like `friL` (last Friday of the month).
2861 fn validate_days(&self) -> Result<(), String> {
2862 const NAMES: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
2863 let is_day = |p: &str| NAMES.contains(&p) || p.parse::<u8>().is_ok_and(|n| n <= 7);
2864 for tok in &self.days {
2865 // Report the whole token on a malformed range like `mon-`
2866 // (which would otherwise split to a cryptic empty part —
2867 // claude #432 follow-up).
2868 let invalid = |reason: &str| {
2869 Err(format!(
2870 "when.days: invalid day token '{tok}' ({reason}; \
2871 want mon..sun, 0-7, a range like mon-fri, an nth-weekday \
2872 like tue#2, a last-weekday like friL, or *)"
2873 ))
2874 };
2875 // #418: nth-weekday suffix (`tue#2` = 2nd Tuesday). Croner
2876 // accepts `<dow>#<n>` (n = 1..5) in the DOW field, and
2877 // `to_cron` passes the token through verbatim, so the
2878 // engine fires only on that occurrence. It's a single
2879 // weekday + ordinal — not combinable with a range.
2880 if let Some((day_part, nth_part)) = tok.split_once('#') {
2881 // Normalize once and use `d` consistently (gemini #547);
2882 // the outer `invalid` already echoes the raw `tok`.
2883 let d = day_part.trim().to_ascii_lowercase();
2884 if d.contains('-') || !is_day(&d) {
2885 return invalid("the part before # must be a single weekday");
2886 }
2887 match nth_part.trim().parse::<u8>() {
2888 Ok(n) if (1..=5).contains(&n) => {}
2889 _ => return invalid("the # ordinal must be 1..5 (e.g. tue#2 = 2nd Tuesday)"),
2890 }
2891 continue;
2892 }
2893 // #418: last-weekday suffix (`friL` = last Friday of the
2894 // month — the monthly-maintenance sibling of Patch Tuesday).
2895 // Croner accepts `<dow>L` in the DOW field with verified
2896 // last-<dow>-of-month semantics, and `to_cron` passes it
2897 // through verbatim. A single weekday + `L` — bare `L` and
2898 // ranges are rejected (croner would read bare `L` as
2899 // Saturday, which is a confusing footgun).
2900 if let Some(day_part) = tok.strip_suffix(['L', 'l']) {
2901 // No `.trim()`: a cron DOW token can't carry internal
2902 // whitespace, so `"fri L"` must be *rejected* here (its
2903 // strip leaves `"fri "`, and `is_day` catches the space)
2904 // rather than trimmed into a clean `"fri"` that then
2905 // produces a malformed `fri L` cron downstream and a
2906 // confusing croner error (gemini #560).
2907 let d = day_part.to_ascii_lowercase();
2908 if d.is_empty() {
2909 return invalid("`L` (last-weekday) needs a weekday before it, e.g. friL");
2910 }
2911 if d.contains('-') || !is_day(&d) {
2912 return invalid(
2913 "the part before L must be a single weekday (e.g. friL = last Friday)",
2914 );
2915 }
2916 continue;
2917 }
2918 for part in tok.split('-') {
2919 let p = part.trim().to_ascii_lowercase();
2920 if p.is_empty() {
2921 return invalid("empty range bound");
2922 }
2923 if p != "*" && !is_day(&p) {
2924 return invalid(&format!("'{part}' is not a day"));
2925 }
2926 }
2927 }
2928 Ok(())
2929 }
2930
2931 /// For a one-shot (`at` carries a date), the absolute instant it
2932 /// fires in `tz`. `None` for a repeating calendar. Used to warn
2933 /// about a one-shot whose date is already in the past (it would
2934 /// never fire).
2935 pub fn oneshot_instant(&self, tz: ScheduleTz) -> Option<chrono::DateTime<chrono::Utc>> {
2936 let p = self.parse_at().ok()?;
2937 let date = p.date?;
2938 let naive = date.and_hms_opt(p.hour, p.minute, 0)?;
2939 tz.naive_to_utc(naive)
2940 }
2941
2942 /// The wall-clock time-of-day this calendar fires at (`None` if
2943 /// `at` is unparseable — validate() guards that). Used to detect
2944 /// a calendar whose fire time can never fall inside its
2945 /// `constraints.window` (claude #452 review).
2946 pub fn fire_time(&self) -> Option<chrono::NaiveTime> {
2947 let p = self.parse_at().ok()?;
2948 chrono::NaiveTime::from_hms_opt(p.hour, p.minute, 0)
2949 }
2950
2951 /// Lower to the cron string the scheduler engine runs. Repeating
2952 /// → 6-field `0 {min} {hour} * * {dow}`; one-shot → 7-field
2953 /// `0 {min} {hour} {day} {month} * {year}` (a past year never
2954 /// fires — that's what makes it one-shot).
2955 fn to_cron(&self) -> Result<String, String> {
2956 use chrono::Datelike;
2957 let ParsedAt { minute, hour, date } = self.parse_at()?;
2958 match date {
2959 Some(d) => {
2960 if !self.days.is_empty() {
2961 return Err(
2962 "when.at with a date is a one-shot and cannot be combined with days".into(),
2963 );
2964 }
2965 Ok(format!(
2966 "0 {minute} {hour} {} {} * {}",
2967 d.day(),
2968 d.month(),
2969 d.year()
2970 ))
2971 }
2972 None => {
2973 let dow = if self.days.is_empty() {
2974 "*".to_string()
2975 } else {
2976 self.validate_days()?;
2977 self.days.join(",")
2978 };
2979 Ok(format!("0 {minute} {hour} * * {dow}"))
2980 }
2981 }
2982 }
2983}
2984
2985/// The timezone a schedule's wall-clock fields (`when.at`,
2986/// `active.{from,until}`) are evaluated in (#418 Phase 2).
2987#[derive(
2988 Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
2989)]
2990#[serde(rename_all = "snake_case")]
2991pub enum ScheduleTz {
2992 /// The running host's local timezone — the agent's for
2993 /// `runs_on: agent`, the backend server's otherwise. Default.
2994 #[default]
2995 Local,
2996 /// UTC — for timezone-independent schedules.
2997 Utc,
2998}
2999
3000impl ScheduleTz {
3001 /// Interpret a naive (zoneless) datetime as being in this tz and
3002 /// convert to UTC. On a DST *fold* (the local time occurs twice
3003 /// when clocks go back) we pick `.earliest()` rather than
3004 /// rejecting it; `None` is reserved for a true DST *gap* (a local
3005 /// time that never exists). `Utc` is fixed-offset so neither ever
3006 /// happens; `Local` is whatever timezone the running host is set
3007 /// to and *can* hit a gap/fold on any DST-observing host — not
3008 /// just the JST we run today (gemini + claude #432 review).
3009 fn naive_to_utc(self, naive: chrono::NaiveDateTime) -> Option<chrono::DateTime<chrono::Utc>> {
3010 use chrono::TimeZone;
3011 match self {
3012 ScheduleTz::Utc => Some(chrono::DateTime::from_naive_utc_and_offset(
3013 naive,
3014 chrono::Utc,
3015 )),
3016 ScheduleTz::Local => chrono::Local
3017 .from_local_datetime(&naive)
3018 .earliest()
3019 .map(|dt| dt.with_timezone(&chrono::Utc)),
3020 }
3021 }
3022
3023 /// The wall-clock time-of-day `now` reads as in this tz — used by
3024 /// [`Constraints::allows`] to test a maintenance window
3025 /// (#418 Phase 3). `Utc` is the naive UTC time; `Local` is the
3026 /// running host's local time.
3027 fn wall_time(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveTime {
3028 match self {
3029 ScheduleTz::Utc => now.time(),
3030 ScheduleTz::Local => now.with_timezone(&chrono::Local).time(),
3031 }
3032 }
3033}
3034
3035/// `once` vs `{ every: <humantime> }` — shared by `per_pc` /
3036/// `per_target`. Untagged so the YAML stays the bare keyword or a
3037/// one-key map, nothing more ceremonial.
3038#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
3039#[serde(untagged)]
3040pub enum PerPolicy {
3041 /// The bare string `once`: succeed once, then skip permanently
3042 /// (cooldown = infinity).
3043 Once(OnceLiteral),
3044 /// Re-arm after the humantime interval, e.g. `{ every: 6h }`.
3045 Every(EverySpec),
3046}
3047
3048/// Single-variant enum so serde accepts exactly the string `once`
3049/// (a free-form `String` would swallow typos like `onec`).
3050#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
3051#[serde(rename_all = "snake_case")]
3052pub enum OnceLiteral {
3053 Once,
3054}
3055
3056/// `{ every: <humantime> }`. Standalone struct (not an inline
3057/// struct variant). `{ evry: 6h }` still fails to parse (the
3058/// required `every` key is missing), and the create boundaries
3059/// reject the unknown `evry` via [`crate::strict`] with its path —
3060/// while agents reading a future writer's extra fields tolerate
3061/// them (#492).
3062#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
3063pub struct EverySpec {
3064 /// Humantime interval (`10m`, `6h`, `1d`...). Parsed lazily —
3065 /// [`Schedule::validate`] rejects garbage at create time.
3066 pub every: String,
3067}
3068
3069impl PerPolicy {
3070 /// The cooldown this policy lowers to: `once` = `None`
3071 /// (permanent skip), `every` = the interval.
3072 fn cooldown(&self) -> Option<String> {
3073 match self {
3074 PerPolicy::Once(_) => None,
3075 PerPolicy::Every(EverySpec { every }) => Some(every.clone()),
3076 }
3077 }
3078}
3079
3080impl std::fmt::Display for When {
3081 /// Operator-facing one-liner (`per_pc once` / `per_pc every 6h`
3082 /// / `at 09:00 [mon-fri]` / `at 2026-06-10 09:00`) for log
3083 /// lines, audit payloads and the API's `ScheduleSummary`.
3084 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3085 let policy = |p: &PerPolicy| match p {
3086 PerPolicy::Once(_) => "once".to_string(),
3087 PerPolicy::Every(EverySpec { every }) => format!("every {every}"),
3088 };
3089 match self {
3090 When::PerPc(p) => write!(f, "per_pc {}", policy(p)),
3091 When::PerTarget(p) => write!(f, "per_target {}", policy(p)),
3092 When::Calendar(c) if c.days.is_empty() => write!(f, "at {}", c.at),
3093 When::Calendar(c) => write!(f, "at {} [{}]", c.at, c.days.join(",")),
3094 }
3095 }
3096}
3097
3098/// Optional validity window for a [`Schedule`] (#418 decision G).
3099/// Half-open `[from, until)`; either bound may be omitted. Bounds
3100/// are `YYYY-MM-DD` (= that day's 00:00 in the schedule's `tz`) or
3101/// full RFC3339 (offset is honored as-is, `tz` ignored). Kept as
3102/// strings so the JSON Schema the SPA editor consumes stays two
3103/// plain string fields, mirroring `jitter` / `starting_deadline`.
3104///
3105/// #418 Phase 2: bounds are evaluated in the schedule's top-level
3106/// `tz` (was UTC-only in Phase 1) so `tz: local` makes both the
3107/// calendar `at` AND the `active` window local — one consistent
3108/// timezone per schedule.
3109#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
3110pub struct Active {
3111 /// Dormant before this instant.
3112 #[serde(default, skip_serializing_if = "Option::is_none")]
3113 pub from: Option<String>,
3114 /// Dormant from this instant on (exclusive).
3115 #[serde(default, skip_serializing_if = "Option::is_none")]
3116 pub until: Option<String>,
3117}
3118
3119impl Active {
3120 /// `skip_serializing_if` helper — an empty window means "always
3121 /// active" and is omitted from the wire format entirely.
3122 pub fn is_empty(&self) -> bool {
3123 self.from.is_none() && self.until.is_none()
3124 }
3125
3126 /// Parse one bound: RFC3339 first (offset honored, `tz`
3127 /// ignored), then bare `YYYY-MM-DD` (00:00 in `tz`).
3128 pub fn parse_bound(s: &str, tz: ScheduleTz) -> Result<chrono::DateTime<chrono::Utc>, String> {
3129 if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
3130 return Ok(dt.with_timezone(&chrono::Utc));
3131 }
3132 if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
3133 let midnight = d.and_hms_opt(0, 0, 0).expect("00:00:00 is always valid");
3134 return tz.naive_to_utc(midnight).ok_or_else(|| {
3135 format!("active: bound '{s}' falls in a DST gap for the schedule's tz")
3136 });
3137 }
3138 Err(format!(
3139 "active: unparseable bound '{s}' (want YYYY-MM-DD or RFC3339)"
3140 ))
3141 }
3142
3143 /// Is `now` inside the window? Unparseable bounds are treated
3144 /// as absent here (fail-open) — [`Schedule::validate`] is the
3145 /// place that rejects them loudly; this runs on every tick and
3146 /// must never panic on a stale KV blob.
3147 pub fn contains(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
3148 let bound = |s: &Option<String>| s.as_deref().and_then(|s| Self::parse_bound(s, tz).ok());
3149 if bound(&self.from).is_some_and(|from| now < from) {
3150 return false;
3151 }
3152 if bound(&self.until).is_some_and(|until| now >= until) {
3153 return false;
3154 }
3155 true
3156 }
3157}
3158
3159/// Operational constraints on a [`Schedule`] (#418 Phase 3). Where
3160/// [`Active`] decides *over what date range* a schedule is live,
3161/// `Constraints` decides *when, within an active period,* a fire is
3162/// allowed. `window` (a maintenance time-of-day window) and
3163/// `max_concurrent` (a fleet-wide running-instance cap) so far;
3164/// `require` (env gates) joins this struct in a later phase.
3165#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
3166pub struct Constraints {
3167 /// `"HH:MM-HH:MM"` wall-clock window (evaluated in the schedule's
3168 /// `tz`). Fires outside it are skipped — mainly for reconcile
3169 /// cadences ("patrol every 6h, but only fire overnight") and
3170 /// daytime change-freezes. `start > end` crosses midnight
3171 /// (`"22:00-05:00"` = 22:00 through 05:00 next morning). Parsed
3172 /// lazily; [`Schedule::validate`] rejects garbage at create time.
3173 #[serde(default, skip_serializing_if = "Option::is_none")]
3174 pub window: Option<String>,
3175 /// Fleet-wide cap on how many instances of this schedule's job may
3176 /// run **at the same time** (#418 "同時実行ハード上限"). The
3177 /// backend scheduler counts the job's still-in-flight runs
3178 /// (`execution_results.finished_at IS NULL`) each tick and only
3179 /// dispatches to as many remaining pcs as there are free slots —
3180 /// a rolling window that refills as runs complete. Useful for
3181 /// disk/CPU/network-heavy jobs you don't want hammering the whole
3182 /// fleet at once.
3183 ///
3184 /// **Backend-only** (it needs a central counter): combining it
3185 /// with `runs_on: agent` is rejected by [`Schedule::validate`]
3186 /// (#418 decision E — "中央上限には中央が要る"). Most meaningful
3187 /// for `per_pc` reconcile cadences, where the poll re-ticks and
3188 /// refills slots. `None` (default) = no cap.
3189 #[serde(default, skip_serializing_if = "Option::is_none")]
3190 pub max_concurrent: Option<u32>,
3191}
3192
3193impl Constraints {
3194 /// `skip_serializing_if` helper — empty constraints are omitted
3195 /// from the wire format entirely.
3196 pub fn is_empty(&self) -> bool {
3197 self.window.is_none() && self.max_concurrent.is_none()
3198 }
3199
3200 /// Parse `"HH:MM-HH:MM"` into `(start, end)`. Equal bounds are an
3201 /// error (a zero-width or all-day window is ambiguous — write no
3202 /// window for "always").
3203 pub fn parse_window(s: &str) -> Result<(chrono::NaiveTime, chrono::NaiveTime), String> {
3204 let (a, b) = s
3205 .split_once('-')
3206 .ok_or_else(|| format!("constraints.window: '{s}' must be 'HH:MM-HH:MM'"))?;
3207 let parse = |part: &str| {
3208 chrono::NaiveTime::parse_from_str(part.trim(), "%H:%M")
3209 .map_err(|e| format!("constraints.window: invalid time '{}': {e}", part.trim()))
3210 };
3211 let (start, end) = (parse(a)?, parse(b)?);
3212 if start == end {
3213 return Err(format!(
3214 "constraints.window: start and end are equal ('{s}'); omit window for 'always'"
3215 ));
3216 }
3217 Ok((start, end))
3218 }
3219
3220 /// Is a fire allowed at `now` (evaluated in `tz`)? No window =
3221 /// always allowed. Half-open `[start, end)`; `start > end`
3222 /// crosses midnight.
3223 ///
3224 /// **Fail-closed** on an unparseable window (returns `false`,
3225 /// gemini #452 review): a window is a *restrictive* constraint
3226 /// (change-freeze / overnight-only), so a corrupt one must NOT
3227 /// silently allow fires during the restricted hours. Bad windows
3228 /// are rejected at create time by [`Schedule::validate`]; this
3229 /// only bites a hand-edited KV blob, where blocking is the safe
3230 /// direction. The scheduler warns at register time
3231 /// ([`Schedule::bad_window`]) so a stuck schedule is diagnosable.
3232 /// The tick path never panics regardless.
3233 pub fn allows(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
3234 match self.window.as_deref() {
3235 // No window → always allowed.
3236 None => true,
3237 // Window set: membership, or fail-closed if unparseable
3238 // (`window_contains` returns None for a corrupt window).
3239 Some(_) => self.window_contains(tz.wall_time(now)).unwrap_or(false),
3240 }
3241 }
3242
3243 /// Membership of a wall-clock time-of-day in the window. `None`
3244 /// when there is no window or it's unparseable (callers decide
3245 /// the failure direction). `start > end` crosses midnight.
3246 fn window_contains(&self, t: chrono::NaiveTime) -> Option<bool> {
3247 let (start, end) = Self::parse_window(self.window.as_deref()?).ok()?;
3248 Some(if start <= end {
3249 start <= t && t < end
3250 } else {
3251 t >= start || t < end
3252 })
3253 }
3254}
3255
3256/// What to do when a fire's script fails (#418 Phase 4 — the "高"
3257/// retry/backoff gap). Where [`Constraints`] gates *whether* a fire
3258/// happens, `OnFailure` decides what happens *after* one ran and
3259/// came back bad. Only `retry` so far; future `notify` / `disable`
3260/// would join the same namespace.
3261#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
3262pub struct OnFailure {
3263 /// Re-run the script in-process when it exits non-zero (or times
3264 /// out), up to a cap, with a fixed backoff between attempts.
3265 /// `None` (default) = no retry: a failed run is published as-is
3266 /// and (for reconcile cadences) simply re-fires on the next poll
3267 /// tick. See [`Retry`].
3268 #[serde(default, skip_serializing_if = "Option::is_none")]
3269 pub retry: Option<Retry>,
3270}
3271
3272impl OnFailure {
3273 /// `skip_serializing_if` helper — an empty policy is omitted from
3274 /// the wire format entirely.
3275 pub fn is_empty(&self) -> bool {
3276 self.retry.is_none()
3277 }
3278
3279 /// Lower the operator-facing `retry` (humantime backoff) onto the
3280 /// engine vocabulary the agent's executor runs on (backoff in
3281 /// whole seconds). Single seam shared by the backend command
3282 /// builder and the agent's local scheduler so the two stamp the
3283 /// same [`crate::wire::RetrySpec`] onto every Command. Returns
3284 /// `None` when there is no retry policy or the backoff is
3285 /// unparseable (validate() rejects the latter at create time;
3286 /// this stays fail-safe = "no retry" for a hand-edited KV blob
3287 /// rather than panicking on the fire path).
3288 pub fn lowered_retry(&self) -> Option<crate::wire::RetrySpec> {
3289 let r = self.retry.as_ref()?;
3290 let backoff_secs = humantime::parse_duration(&r.backoff).ok()?.as_secs();
3291 Some(crate::wire::RetrySpec {
3292 max: r.max,
3293 backoff_secs,
3294 })
3295 }
3296}
3297
3298/// Fixed-backoff retry policy (#418 Phase 4). `max` is the number of
3299/// *additional* attempts after the first run (so `max: 3` = up to 4
3300/// total executions); `backoff` is the humantime delay slept between
3301/// attempts. The retry happens fire-side (inside `kanade fire` /
3302/// `handle_command`) on every OS for the PoC — the Windows-native
3303/// "restart on failure" Task Scheduler path is deferred to the
3304/// native-delegation phase (#418 decision H).
3305#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
3306pub struct Retry {
3307 /// Max additional attempts after the first failure. Bounded
3308 /// `1..=10` by [`Schedule::validate`] — a typo'd `max: 1000`
3309 /// with a short backoff would otherwise pin a flapping script in
3310 /// a tight loop for the whole window.
3311 pub max: u32,
3312 /// Humantime delay slept between attempts (`"10m"`, `"30s"`).
3313 pub backoff: String,
3314}
3315
3316/// Fleet-wide change-freeze (#418 Phase 5 — the "メンテナンス窓 /
3317/// 変更凍結" gap's global half). Where [`Constraints::window`] is a
3318/// *per-schedule* time-of-day gate, a `Freeze` is a *single, fleet-
3319/// global* "stop all automated change" switch the operator flips
3320/// during an incident or a year-end change-freeze. It lives in its
3321/// own KV singleton ([`crate::kv::KEY_FREEZE`]); when present and
3322/// active, both the backend scheduler and every agent's local
3323/// scheduler skip *every* fire.
3324///
3325/// Shapes:
3326/// * `{}` (no bounds) — frozen indefinitely until the operator
3327/// clears it (incident "big red button").
3328/// * `{ from, until }` — frozen only within `[from, until)`,
3329/// evaluated in `tz` (planned change-freeze; auto-thaws).
3330///
3331/// The KV key being *absent* means "not frozen" — so clearing the
3332/// freeze is a KV delete, and `is_active` only ever runs on a freeze
3333/// the operator actually set.
3334#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
3335pub struct Freeze {
3336 /// Frozen from this instant (RFC3339 or bare `YYYY-MM-DD` in
3337 /// `tz`). `None` ⇒ frozen from the beginning of time.
3338 #[serde(default, skip_serializing_if = "Option::is_none")]
3339 pub from: Option<String>,
3340 /// Thawed from this instant on, exclusive. `None` ⇒ frozen with
3341 /// no scheduled end (manual clear required).
3342 #[serde(default, skip_serializing_if = "Option::is_none")]
3343 pub until: Option<String>,
3344 /// Operator-supplied note surfaced on the freeze-skip log and the
3345 /// SPA banner ("year-end change freeze", "INC-1234"). Advisory.
3346 #[serde(default, skip_serializing_if = "Option::is_none")]
3347 pub reason: Option<String>,
3348 /// Timezone the bare-date bounds are evaluated in (RFC3339 bounds
3349 /// carry their own offset). Defaults to host-local like a
3350 /// schedule's `tz`.
3351 #[serde(default)]
3352 pub tz: ScheduleTz,
3353}
3354
3355impl Freeze {
3356 /// Is the fleet frozen at `now`? An empty window (`from`/`until`
3357 /// both absent) is frozen unconditionally; otherwise membership of
3358 /// `[from, until)` in `tz`. Half-open like [`Active::contains`],
3359 /// but **fails CLOSED** on an unparseable bound — a freeze is a
3360 /// safety switch, so a corrupt window (only reachable via a
3361 /// hand-edited KV blob; `validate` rejects it at set time) must
3362 /// mean "frozen", not "fire normally" (coderabbit #472). This is
3363 /// the one deliberate divergence from `active`'s fail-OPEN
3364 /// behaviour, where an unparseable bound dormant-skips a schedule.
3365 pub fn is_active(&self, now: chrono::DateTime<chrono::Utc>) -> bool {
3366 // Parse a bound; an unparseable one short-circuits the whole
3367 // check to `true` (frozen) via the closure's `None` sentinel
3368 // handled below.
3369 let bound = |s: &Option<String>| -> Result<Option<chrono::DateTime<chrono::Utc>>, ()> {
3370 match s.as_deref() {
3371 None => Ok(None),
3372 Some(raw) => Active::parse_bound(raw, self.tz).map(Some).map_err(|_| ()),
3373 }
3374 };
3375 let (from, until) = match (bound(&self.from), bound(&self.until)) {
3376 (Ok(f), Ok(u)) => (f, u),
3377 // Any corrupt bound → fail closed (frozen).
3378 _ => return true,
3379 };
3380 if from.is_some_and(|f| now < f) {
3381 return false;
3382 }
3383 if until.is_some_and(|u| now >= u) {
3384 return false;
3385 }
3386 true
3387 }
3388
3389 /// Reject unparseable bounds / `from >= until` at set time (the
3390 /// API + CLI counterpart to [`Schedule::validate`]).
3391 pub fn validate(&self) -> Result<(), String> {
3392 let from = self
3393 .from
3394 .as_deref()
3395 .map(|s| Active::parse_bound(s, self.tz))
3396 .transpose()
3397 .map_err(|e| e.replace("active:", "freeze:"))?;
3398 let until = self
3399 .until
3400 .as_deref()
3401 .map(|s| Active::parse_bound(s, self.tz))
3402 .transpose()
3403 .map_err(|e| e.replace("active:", "freeze:"))?;
3404 if let (Some(f), Some(u)) = (from, until) {
3405 if f >= u {
3406 return Err(format!(
3407 "freeze.from ({}) must be strictly before freeze.until ({})",
3408 self.from.as_deref().unwrap_or_default(),
3409 self.until.as_deref().unwrap_or_default(),
3410 ));
3411 }
3412 }
3413 Ok(())
3414 }
3415}
3416
3417/// The system-generated poll cadence every reconcile-shaped `when`
3418/// lowers to. Operators never write this: the real inter-run
3419/// spacing is the `every` cooldown; this only bounds "how soon do
3420/// we notice somebody is due" (#418 decision B took the poll
3421/// period away from the operator).
3422pub const POLL_CRON: &str = "0 * * * * *";
3423
3424/// What a [`When`] lowers to — the exact (cron, mode, cooldown)
3425/// trio the pre-#418 engine ran on. Keeping the engine vocabulary
3426/// unchanged is what lets Phase 1 swap the operator surface without
3427/// touching the tick / dedup machinery.
3428pub struct Lowered {
3429 /// Cron handed to `tokio-cron-scheduler` — [`POLL_CRON`] for
3430 /// reconcile shapes, a 6/7-field cron for calendar shapes.
3431 pub cron: String,
3432 /// Dedup semantics for `decide_fire`.
3433 pub mode: ExecMode,
3434 /// Humantime re-arm interval (`None` = succeed once, skip
3435 /// forever).
3436 pub cooldown: Option<String>,
3437 /// Timezone to evaluate `cron` in (#418 Phase 2). The scheduler
3438 /// passes this to `Job::new_async_tz`. Reconcile shapes carry
3439 /// the schedule's tz too even though POLL_CRON is tz-agnostic,
3440 /// so the same value drives the `active`-window check.
3441 pub tz: ScheduleTz,
3442}
3443
3444impl Schedule {
3445 /// The error message if this schedule's `constraints.window` is
3446 /// set but unparseable, else `None`. The scheduler logs this at
3447 /// register time so a fail-closed (never-firing) schedule from a
3448 /// hand-edited KV blob is diagnosable (gemini #452 review).
3449 pub fn bad_window(&self) -> Option<String> {
3450 let w = self.constraints.window.as_deref()?;
3451 Constraints::parse_window(w).err()
3452 }
3453
3454 /// True when this is a `calendar` schedule whose fire time can
3455 /// never fall inside its `constraints.window` — the cron fires,
3456 /// the window check rejects it, and (firing only at that
3457 /// time-of-day) it effectively never runs. An easy misconfig to
3458 /// set up by accident; the scheduler warns at register time
3459 /// (claude #452 review). Reconcile shapes poll every minute, so
3460 /// they always catch the window opening and aren't affected.
3461 pub fn calendar_outside_window(&self) -> bool {
3462 let When::Calendar(c) = &self.when else {
3463 return false;
3464 };
3465 let Some(t) = c.fire_time() else {
3466 return false;
3467 };
3468 matches!(self.constraints.window_contains(t), Some(false))
3469 }
3470
3471 /// Lower the operator-facing `when` onto the engine vocabulary.
3472 /// Single seam shared by the backend scheduler and the agent's
3473 /// local scheduler so the two can never drift.
3474 pub fn lowered(&self) -> Lowered {
3475 let tz = self.tz;
3476 match &self.when {
3477 When::PerPc(p) => Lowered {
3478 cron: POLL_CRON.into(),
3479 mode: ExecMode::OncePerPc,
3480 cooldown: p.cooldown(),
3481 tz,
3482 },
3483 When::PerTarget(p) => Lowered {
3484 cron: POLL_CRON.into(),
3485 mode: ExecMode::OncePerTarget,
3486 cooldown: p.cooldown(),
3487 tz,
3488 },
3489 // `to_cron` only fails on a malformed `at` (rejected by
3490 // validate() at create time). For a hand-edited KV blob
3491 // that slipped past, emit a deliberately-invalid cron so
3492 // register()'s Job::new_async_tz fails → warn+skip,
3493 // rather than firing at the wrong time.
3494 When::Calendar(c) => Lowered {
3495 cron: c
3496 .to_cron()
3497 .unwrap_or_else(|_| "# invalid calendar at".into()),
3498 mode: ExecMode::EveryTick,
3499 cooldown: None,
3500 tz,
3501 },
3502 }
3503 }
3504
3505 /// Cross-field semantic checks that don't fit pure serde derive
3506 /// — the [`Manifest::validate`] counterpart (#418 decision F;
3507 /// pre-Phase-1 a broken schedule was accepted at create time
3508 /// and silently warn-skipped at tick time). Run at every create
3509 /// site: `kanade schedule create` (client-side) and
3510 /// `POST /api/schedules`. The job_id-exists check lives in the
3511 /// API handler instead — it needs the JOBS KV.
3512 pub fn validate(&self) -> Result<(), String> {
3513 if matches!(self.runs_on, RunsOn::Agent) && matches!(self.when, When::PerTarget(_)) {
3514 return Err(
3515 "when.per_target needs fleet-wide completion data and is backend-only; \
3516 it cannot be combined with runs_on: agent (each agent self-schedules, \
3517 so per-target dedup would be deduping across a target of 1)"
3518 .into(),
3519 );
3520 }
3521 if let Some(cd) = self.lowered().cooldown.as_deref() {
3522 humantime::parse_duration(cd)
3523 .map_err(|e| format!("when.every: invalid duration '{cd}': {e}"))?;
3524 }
3525 if let When::Calendar(c) = &self.when {
3526 // Lower the calendar form to its cron (catches a bad `at`
3527 // and the date+days conflict), then validate that cron
3528 // with the same parser configuration tokio-cron-scheduler
3529 // 0.15 uses internally (croner, seconds required,
3530 // DOM-and-DOW both honored, year optional) — create-time
3531 // validation can never accept what register() rejects.
3532 let cron = c.to_cron()?;
3533 croner::parser::CronParser::builder()
3534 .seconds(croner::parser::Seconds::Required)
3535 .dom_and_dow(true)
3536 .build()
3537 .parse(&cron)
3538 .map_err(|e| format!("when.at lowered to invalid cron '{cron}': {e}"))?;
3539 }
3540 // The other humantime strings on the schedule (claude #419
3541 // review): runtime degrades gracefully on both (bad jitter →
3542 // silent no-op, bad starting_deadline → warn + skipped tick),
3543 // but "rejected at create time" should cover every field the
3544 // operator can typo, not just `when`.
3545 if let Some(j) = &self.plan.jitter {
3546 humantime::parse_duration(j)
3547 .map_err(|e| format!("jitter: invalid duration '{j}': {e}"))?;
3548 }
3549 if let Some(sd) = &self.starting_deadline {
3550 humantime::parse_duration(sd)
3551 .map_err(|e| format!("starting_deadline: invalid duration '{sd}': {e}"))?;
3552 }
3553 let from = self
3554 .active
3555 .from
3556 .as_deref()
3557 .map(|s| Active::parse_bound(s, self.tz))
3558 .transpose()?;
3559 let until = self
3560 .active
3561 .until
3562 .as_deref()
3563 .map(|s| Active::parse_bound(s, self.tz))
3564 .transpose()?;
3565 if let (Some(f), Some(u)) = (from, until) {
3566 if f >= u {
3567 return Err(format!(
3568 "active.from ({}) must be strictly before active.until ({})",
3569 self.active.from.as_deref().unwrap_or_default(),
3570 self.active.until.as_deref().unwrap_or_default(),
3571 ));
3572 }
3573 }
3574 // #418 Phase 3: a bad maintenance window is rejected at create
3575 // time (parse_window also catches equal bounds).
3576 if let Some(w) = self.constraints.window.as_deref() {
3577 Constraints::parse_window(w)?;
3578 }
3579 // #418: constraints.max_concurrent is a central running-instance
3580 // cap, so it needs the backend's counter — reject it on
3581 // runs_on: agent (decision E), and reject a meaningless 0.
3582 if let Some(mc) = self.constraints.max_concurrent {
3583 // Check the structural incompatibility (agent has no central
3584 // counter) before the value range, so a `max_concurrent: 0`
3585 // + `runs_on: agent` combo reports the more fundamental
3586 // problem first (claude #542).
3587 if matches!(self.runs_on, RunsOn::Agent) {
3588 return Err(
3589 "constraints.max_concurrent needs a central counter and is backend-only; \
3590 it cannot be combined with runs_on: agent (each agent self-schedules, \
3591 so there is no fleet-wide count to cap against)"
3592 .into(),
3593 );
3594 }
3595 if mc == 0 {
3596 return Err(
3597 "constraints.max_concurrent must be >= 1 (0 would never fire; \
3598 omit it for no cap)"
3599 .into(),
3600 );
3601 }
3602 }
3603 // #418 Phase 4: a bad on_failure.retry is rejected at create
3604 // time — backoff must be valid humantime, and max is bounded
3605 // so a typo can't pin a flapping script in a tight loop.
3606 if let Some(r) = &self.on_failure.retry {
3607 let backoff = humantime::parse_duration(&r.backoff).map_err(|e| {
3608 format!(
3609 "on_failure.retry.backoff: invalid duration '{}': {e}",
3610 r.backoff
3611 )
3612 })?;
3613 // The wire form lowers backoff to whole seconds, so a
3614 // sub-second value would silently become a 0s no-wait
3615 // (coderabbit #466). Reject it rather than honour a backoff
3616 // the operator can't actually get.
3617 if backoff.as_secs() < 1 {
3618 return Err(format!(
3619 "on_failure.retry.backoff must be >= 1s (got '{}'); sub-second backoffs \
3620 round to 0 on the wire",
3621 r.backoff
3622 ));
3623 }
3624 if !(1..=10).contains(&r.max) {
3625 return Err(format!(
3626 "on_failure.retry.max must be 1..=10 (got {}); it counts additional \
3627 attempts after the first run",
3628 r.max
3629 ));
3630 }
3631 }
3632 Ok(())
3633 }
3634}
3635
3636fn default_true() -> bool {
3637 true
3638}