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 When::On(vec![OnTrigger::Startup]),
1476 When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
1477 ] {
1478 // Event triggers are agent-only; the rest validate on backend.
1479 let runs_on = if matches!(when, When::On(_)) {
1480 RunsOn::Agent
1481 } else {
1482 RunsOn::Backend
1483 };
1484 let s = schedule_with(when.clone(), runs_on);
1485
1486 let json = serde_json::to_string(&s).expect("json serialise");
1487 let back: Schedule = serde_json::from_str(&json).expect("json deserialise");
1488 assert_eq!(back.when, when, "json round-trip for {when}");
1489
1490 let yaml = serde_yaml::to_string(&s).expect("yaml serialise");
1491 assert!(
1492 !yaml.contains('!'),
1493 "yaml must use the map shape, not tags: {yaml}"
1494 );
1495 let back: Schedule = serde_yaml::from_str(&yaml).expect("yaml deserialise");
1496 assert_eq!(back.when, when, "yaml round-trip for {when}");
1497 }
1498 }
1499
1500 #[test]
1501 fn when_once_serialises_as_bare_keyword() {
1502 // The wire shape operators see in the YAML mirror must stay
1503 // the ergonomic `per_pc: once`, not a one-variant map.
1504 let json = serde_json::to_value(When::PerPc(PerPolicy::Once(OnceLiteral::Once)))
1505 .expect("serialise");
1506 assert_eq!(json, serde_json::json!({ "per_pc": "once" }));
1507 }
1508
1509 #[test]
1510 fn when_displays_operator_summary() {
1511 for (when, expected) in [
1512 (
1513 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
1514 "per_pc once",
1515 ),
1516 (
1517 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
1518 "per_pc every 6h",
1519 ),
1520 (
1521 When::PerTarget(PerPolicy::Every(EverySpec {
1522 every: "24h".into(),
1523 })),
1524 "per_target every 24h",
1525 ),
1526 (calendar("09:00", &["mon-fri"]), "at 09:00 [mon-fri]"),
1527 (calendar("2026-06-10 09:00", &[]), "at 2026-06-10 09:00"),
1528 (When::On(vec![OnTrigger::Startup]), "on [startup]"),
1529 (
1530 When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
1531 "on [startup,logon]",
1532 ),
1533 ] {
1534 assert_eq!(when.to_string(), expected);
1535 }
1536 }
1537
1538 // ---- lowering (#418: when → engine vocabulary) ----
1539
1540 fn schedule_with(when: When, runs_on: RunsOn) -> Schedule {
1541 Schedule {
1542 id: "x".into(),
1543 when,
1544 job_id: "y".into(),
1545 plan: FanoutPlan::default(),
1546 active: Active::default(),
1547 constraints: Constraints::default(),
1548 on_failure: OnFailure::default(),
1549 tz: ScheduleTz::default(),
1550 starting_deadline: None,
1551 runs_on,
1552 enabled: true,
1553 }
1554 }
1555
1556 fn calendar(at: &str, days: &[&str]) -> When {
1557 When::Calendar(CalendarSpec {
1558 at: at.into(),
1559 days: days.iter().map(|d| (*d).to_string()).collect(),
1560 })
1561 }
1562
1563 #[test]
1564 fn next_calendar_fire_returns_next_utc_occurrence() {
1565 use chrono::TimeZone;
1566 // Daily 09:00, evaluated in UTC. From 08:00 the same day, the
1567 // next strict occurrence is 09:00 that day.
1568 let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
1569 s.tz = ScheduleTz::Utc;
1570 let now = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 8, 0, 0).unwrap();
1571 let next = s.next_calendar_fire(now).expect("calendar has a next fire");
1572 assert_eq!(
1573 next,
1574 chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap()
1575 );
1576 }
1577
1578 #[test]
1579 fn next_calendar_fire_is_strictly_after_now() {
1580 use chrono::TimeZone;
1581 // Standing exactly on a fire instant must preview the *next*
1582 // one (inclusive = false), not the one firing right now.
1583 let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
1584 s.tz = ScheduleTz::Utc;
1585 let on_fire = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap();
1586 let next = s
1587 .next_calendar_fire(on_fire)
1588 .expect("calendar has a next fire");
1589 assert_eq!(
1590 next,
1591 chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()
1592 );
1593 }
1594
1595 #[test]
1596 fn next_calendar_fire_none_for_reconcile_shapes() {
1597 // `per_pc` / `per_target` lower to the every-minute poll cron —
1598 // no discrete upcoming event to preview, so `None`.
1599 let now = chrono::Utc::now();
1600 for when in [
1601 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
1602 When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
1603 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
1604 When::PerTarget(PerPolicy::Every(EverySpec {
1605 every: "24h".into(),
1606 })),
1607 ] {
1608 let s = schedule_with(when, RunsOn::Backend);
1609 assert!(
1610 s.next_calendar_fire(now).is_none(),
1611 "reconcile shapes have no calendar fire",
1612 );
1613 }
1614 }
1615
1616 // ---- preview_fires (#418 dry-run / preview) ----
1617
1618 fn cal_utc(at: &str, days: &[&str]) -> Schedule {
1619 let mut s = schedule_with(calendar(at, days), RunsOn::Backend);
1620 s.tz = ScheduleTz::Utc; // host-independent assertions
1621 s
1622 }
1623
1624 #[test]
1625 fn preview_lists_next_calendar_occurrences() {
1626 use chrono::TimeZone;
1627 // Weekday 09:00, from Wed 2026-06-10 00:00 UTC: the next five
1628 // fires skip the weekend (Sat 13 / Sun 14).
1629 let s = cal_utc("09:00", &["mon-fri"]);
1630 let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
1631 let got = s.preview_fires(now, 5);
1632 let want: Vec<_> = [
1633 (2026, 6, 10), // Wed
1634 (2026, 6, 11), // Thu
1635 (2026, 6, 12), // Fri
1636 (2026, 6, 15), // Mon (skips Sat 13 / Sun 14)
1637 (2026, 6, 16), // Tue
1638 ]
1639 .iter()
1640 .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
1641 .collect();
1642 assert_eq!(got, want);
1643 }
1644
1645 #[test]
1646 fn preview_handles_nth_and_last_weekday() {
1647 use chrono::TimeZone;
1648 let now = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
1649 // 2nd Tuesday (Patch Tuesday): Jun 9, Jul 14 2026.
1650 let nth = cal_utc("09:00", &["tue#2"]).preview_fires(now, 2);
1651 assert_eq!(
1652 nth,
1653 vec![
1654 chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap(),
1655 chrono::Utc.with_ymd_and_hms(2026, 7, 14, 9, 0, 0).unwrap(),
1656 ]
1657 );
1658 // Last Friday of the month: Jun 26, Jul 31 2026.
1659 let last = cal_utc("22:00", &["friL"]).preview_fires(now, 2);
1660 assert_eq!(
1661 last,
1662 vec![
1663 chrono::Utc.with_ymd_and_hms(2026, 6, 26, 22, 0, 0).unwrap(),
1664 chrono::Utc.with_ymd_and_hms(2026, 7, 31, 22, 0, 0).unwrap(),
1665 ]
1666 );
1667 }
1668
1669 #[test]
1670 fn preview_is_empty_for_reconcile_and_zero_count() {
1671 let now = chrono::Utc::now();
1672 // reconcile shapes have no discrete fire times
1673 let recon = schedule_with(
1674 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
1675 RunsOn::Backend,
1676 );
1677 assert!(recon.preview_fires(now, 5).is_empty());
1678 // count == 0 yields nothing even for a calendar
1679 assert!(cal_utc("09:00", &[]).preview_fires(now, 0).is_empty());
1680 }
1681
1682 #[test]
1683 fn preview_skips_outside_active_window() {
1684 use chrono::TimeZone;
1685 // Daily 09:00, active only [2026-06-15, 2026-06-17). Occurrences
1686 // before `from` are skipped; `until` is exclusive, so 06-17's
1687 // fire is out — leaving exactly the 15th and 16th.
1688 let mut s = cal_utc("09:00", &[]);
1689 s.active = Active {
1690 from: Some("2026-06-15".into()),
1691 until: Some("2026-06-17".into()),
1692 };
1693 let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
1694 let got = s.preview_fires(now, 5);
1695 assert_eq!(
1696 got,
1697 vec![
1698 chrono::Utc.with_ymd_and_hms(2026, 6, 15, 9, 0, 0).unwrap(),
1699 chrono::Utc.with_ymd_and_hms(2026, 6, 16, 9, 0, 0).unwrap(),
1700 ]
1701 );
1702 }
1703
1704 #[test]
1705 fn preview_empty_when_calendar_time_outside_window() {
1706 use chrono::TimeZone;
1707 // Fires at 09:00 but the maintenance window is overnight — it can
1708 // never run, so the preview is empty (matches
1709 // `calendar_outside_window`), and the scan still terminates.
1710 let mut s = cal_utc("09:00", &[]);
1711 s.constraints = Constraints {
1712 window: Some("22:00-05:00".into()),
1713 ..Constraints::default()
1714 };
1715 let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
1716 assert!(s.preview_fires(now, 5).is_empty());
1717 // Every candidate tick is rejected, so this also exercises the
1718 // SCAN_CAP bound: a large `count` must still terminate (and
1719 // return empty) rather than spin (claude #578 review).
1720 assert!(s.preview_fires(now, 50).is_empty());
1721 }
1722
1723 #[test]
1724 fn preview_past_one_shot_is_empty() {
1725 use chrono::TimeZone;
1726 // A dated one-shot whose instant has passed never fires again.
1727 let s = cal_utc("2026-06-10 09:00", &[]);
1728 let now = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 0, 0, 0).unwrap();
1729 assert!(s.preview_fires(now, 5).is_empty());
1730 // …but from before it, the single future fire shows up.
1731 let before = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
1732 assert_eq!(
1733 s.preview_fires(before, 5),
1734 vec![chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()]
1735 );
1736 }
1737
1738 #[test]
1739 fn lowering_matches_the_418_table() {
1740 let cases = [
1741 (
1742 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
1743 (POLL_CRON, ExecMode::OncePerPc, None),
1744 ),
1745 (
1746 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
1747 (POLL_CRON, ExecMode::OncePerPc, Some("6h")),
1748 ),
1749 (
1750 When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
1751 (POLL_CRON, ExecMode::OncePerTarget, None),
1752 ),
1753 (
1754 When::PerTarget(PerPolicy::Every(EverySpec {
1755 every: "24h".into(),
1756 })),
1757 (POLL_CRON, ExecMode::OncePerTarget, Some("24h")),
1758 ),
1759 // calendar repeating → 6-field cron
1760 (
1761 calendar("09:00", &["mon-fri"]),
1762 ("0 0 9 * * mon-fri", ExecMode::EveryTick, None),
1763 ),
1764 // calendar daily (no days) → DOW *
1765 (
1766 calendar("18:30", &[]),
1767 ("0 30 18 * * *", ExecMode::EveryTick, None),
1768 ),
1769 // calendar one-shot → 7-field year cron
1770 (
1771 calendar("2026-06-10 09:00", &[]),
1772 ("0 0 9 10 6 * 2026", ExecMode::EveryTick, None),
1773 ),
1774 ];
1775 for (when, (cron, mode, cooldown)) in cases {
1776 let l = schedule_with(when.clone(), RunsOn::Backend).lowered();
1777 assert_eq!(l.cron, cron, "cron for {when}");
1778 assert_eq!(l.mode, mode, "mode for {when}");
1779 assert_eq!(l.cooldown.as_deref(), cooldown, "cooldown for {when}");
1780 }
1781 }
1782
1783 #[test]
1784 fn lowered_carries_schedule_tz() {
1785 for (tz, want) in [
1786 (ScheduleTz::Local, ScheduleTz::Local),
1787 (ScheduleTz::Utc, ScheduleTz::Utc),
1788 ] {
1789 let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
1790 s.tz = tz;
1791 assert_eq!(s.lowered().tz, want, "calendar carries tz");
1792 // reconcile shapes carry tz too (for the active-window check)
1793 let mut s = schedule_with(
1794 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
1795 RunsOn::Backend,
1796 );
1797 s.tz = tz;
1798 assert_eq!(s.lowered().tz, want, "reconcile carries tz");
1799 }
1800 }
1801
1802 #[test]
1803 fn poll_cron_is_accepted_by_the_engine_parser() {
1804 // POLL_CRON is system-generated — if the engine's parser
1805 // ever rejected it every reconcile schedule would die at
1806 // register time. Validate it with the same croner config
1807 // (Seconds::Required, dom_and_dow, year optional).
1808 croner::parser::CronParser::builder()
1809 .seconds(croner::parser::Seconds::Required)
1810 .dom_and_dow(true)
1811 .build()
1812 .parse(POLL_CRON)
1813 .expect("POLL_CRON must parse");
1814 }
1815
1816 // ---- Schedule::validate() (#418 decision F) ----
1817
1818 #[test]
1819 fn validate_accepts_reconcile_shapes() {
1820 for when in [
1821 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
1822 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
1823 When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
1824 When::PerTarget(PerPolicy::Every(EverySpec {
1825 every: "24h".into(),
1826 })),
1827 ] {
1828 schedule_with(when.clone(), RunsOn::Backend)
1829 .validate()
1830 .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
1831 }
1832 }
1833
1834 #[test]
1835 fn validate_accepts_per_pc_on_agent() {
1836 schedule_with(
1837 When::PerPc(PerPolicy::Every(EverySpec { every: "1h".into() })),
1838 RunsOn::Agent,
1839 )
1840 .validate()
1841 .expect("per_pc + agent is the offline-inventory shape");
1842 }
1843
1844 // ---- #418 event triggers (when: { on }) ----
1845
1846 #[test]
1847 fn validate_accepts_event_on_agent() {
1848 for triggers in [
1849 vec![OnTrigger::Startup],
1850 vec![OnTrigger::Logon],
1851 vec![OnTrigger::Startup, OnTrigger::Logon],
1852 ] {
1853 schedule_with(When::On(triggers), RunsOn::Agent)
1854 .validate()
1855 .expect("when.on is valid on runs_on: agent");
1856 }
1857 }
1858
1859 #[test]
1860 fn validate_rejects_event_on_backend() {
1861 let err = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Backend)
1862 .validate()
1863 .unwrap_err();
1864 assert!(err.contains("when.on"), "got: {err}");
1865 assert!(err.contains("runs_on: agent"), "got: {err}");
1866 }
1867
1868 #[test]
1869 fn validate_rejects_empty_event_list() {
1870 let err = schedule_with(When::On(vec![]), RunsOn::Agent)
1871 .validate()
1872 .unwrap_err();
1873 assert!(err.contains("when.on"), "got: {err}");
1874 assert!(err.contains("at least one"), "got: {err}");
1875 }
1876
1877 #[test]
1878 fn event_schedule_lowers_to_event_mode_and_is_event() {
1879 let s = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Agent);
1880 assert!(s.is_event());
1881 assert_eq!(s.lowered().mode, ExecMode::Event);
1882 assert_eq!(s.event_triggers(), &[OnTrigger::Startup]);
1883 // non-event schedules report no triggers.
1884 let cal = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
1885 assert!(!cal.is_event());
1886 assert!(cal.event_triggers().is_empty());
1887 }
1888
1889 #[test]
1890 fn validate_rejects_per_target_on_agent() {
1891 let err = schedule_with(
1892 When::PerTarget(PerPolicy::Every(EverySpec {
1893 every: "24h".into(),
1894 })),
1895 RunsOn::Agent,
1896 )
1897 .validate()
1898 .unwrap_err();
1899 assert!(err.contains("per_target"), "got: {err}");
1900 assert!(err.contains("runs_on: agent"), "got: {err}");
1901
1902 // per_target: once is also backend-only.
1903 let err = schedule_with(
1904 When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
1905 RunsOn::Agent,
1906 )
1907 .validate()
1908 .unwrap_err();
1909 assert!(err.contains("per_target"), "got (once): {err}");
1910 assert!(err.contains("runs_on: agent"), "got (once): {err}");
1911 }
1912
1913 #[test]
1914 fn validate_rejects_bad_every_duration() {
1915 let err = schedule_with(
1916 When::PerPc(PerPolicy::Every(EverySpec { every: "6x".into() })),
1917 RunsOn::Backend,
1918 )
1919 .validate()
1920 .unwrap_err();
1921 assert!(err.contains("when.every"), "got: {err}");
1922 }
1923
1924 #[test]
1925 fn validate_rejects_bad_jitter_and_starting_deadline() {
1926 let mut s = schedule_with(
1927 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
1928 RunsOn::Backend,
1929 );
1930 s.plan.jitter = Some("5x".into());
1931 let err = s.validate().unwrap_err();
1932 assert!(err.contains("jitter"), "got: {err}");
1933
1934 let mut s = schedule_with(
1935 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
1936 RunsOn::Backend,
1937 );
1938 s.starting_deadline = Some("soon".into());
1939 let err = s.validate().unwrap_err();
1940 assert!(err.contains("starting_deadline"), "got: {err}");
1941 }
1942
1943 #[test]
1944 fn validate_accepts_calendar_shapes() {
1945 for when in [
1946 calendar("09:00", &["mon-fri"]), // weekday morning
1947 calendar("00:00", &["sun"]), // weekly
1948 calendar("18:30", &[]), // daily
1949 calendar("2026-06-10 09:00", &[]), // one-shot
1950 calendar("2026/12/25 00:00", &[]), // one-shot, slash form
1951 ] {
1952 schedule_with(when.clone(), RunsOn::Backend)
1953 .validate()
1954 .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
1955 }
1956 }
1957
1958 #[test]
1959 fn validate_rejects_bad_at() {
1960 for bad in ["25:00", "09:60", "9", "noon", "2026-13-01 09:00"] {
1961 let err = schedule_with(calendar(bad, &[]), RunsOn::Backend)
1962 .validate()
1963 .unwrap_err();
1964 assert!(err.contains("when.at"), "for '{bad}', got: {err}");
1965 }
1966 }
1967
1968 #[test]
1969 fn validate_rejects_datetime_at_with_days() {
1970 // A dated `at` is a one-shot — pairing it with days is a
1971 // contradiction (the date already pins the day).
1972 let err = schedule_with(calendar("2026-06-10 09:00", &["mon"]), RunsOn::Backend)
1973 .validate()
1974 .unwrap_err();
1975 assert!(
1976 err.contains("one-shot") && err.contains("days"),
1977 "got: {err}"
1978 );
1979 }
1980
1981 #[test]
1982 fn validate_rejects_bad_day_name() {
1983 // A garbage DOW token is caught by the days pre-flight and
1984 // reported against `when.days`, not the confusing
1985 // "when.at lowered to invalid cron" (claude #432 review).
1986 let err = schedule_with(calendar("09:00", &["funday"]), RunsOn::Backend)
1987 .validate()
1988 .unwrap_err();
1989 assert!(err.contains("when.days"), "got: {err}");
1990 assert!(err.contains("funday"), "names the bad token: {err}");
1991 // a degenerate range like `mon-` reports the whole token, not
1992 // a cryptic empty part (claude #432 follow-up)
1993 let err = schedule_with(calendar("09:00", &["mon-"]), RunsOn::Backend)
1994 .validate()
1995 .unwrap_err();
1996 assert!(err.contains("'mon-'"), "names the whole token: {err}");
1997 // valid names / ranges / numeric / * all pass
1998 for ok in [
1999 calendar("09:00", &["mon-fri"]),
2000 calendar("09:00", &["mon", "wed", "sun"]),
2001 calendar("09:00", &["1-5"]),
2002 ] {
2003 schedule_with(ok.clone(), RunsOn::Backend)
2004 .validate()
2005 .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
2006 }
2007 }
2008
2009 #[test]
2010 fn validate_accepts_nth_weekday() {
2011 // #418: nth-weekday (Patch Tuesday). validate() also lowers to
2012 // a cron and parses it with croner, so passing here proves the
2013 // whole chain — token → DOW field → engine-acceptable cron.
2014 for ok in [
2015 calendar("09:00", &["tue#2"]), // 2nd Tuesday
2016 calendar("09:00", &["fri#1"]), // 1st Friday
2017 calendar("03:00", &["sun#5"]), // 5th Sunday
2018 calendar("09:00", &["tue#2", "thu#2"]), // a list of nths
2019 calendar("09:00", &["2#2"]), // numeric DOW + ordinal
2020 // Case-insensitive both sides: validate lowercases, croner
2021 // upper-cases the whole pattern before aliasing (claude #547).
2022 calendar("09:00", &["TUE#2"]),
2023 ] {
2024 schedule_with(ok.clone(), RunsOn::Backend)
2025 .validate()
2026 .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
2027 }
2028 }
2029
2030 #[test]
2031 fn validate_rejects_bad_nth_weekday() {
2032 // ordinal out of 1..5, a range with #, and a bad day before #.
2033 for bad in ["tue#0", "tue#6", "tue#x", "mon-fri#2", "funday#2"] {
2034 let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
2035 .validate()
2036 .unwrap_err();
2037 assert!(err.contains("when.days"), "for '{bad}', got: {err}");
2038 }
2039 }
2040
2041 #[test]
2042 fn validate_accepts_last_weekday() {
2043 // #418: last-weekday (`friL` = last Friday). Like the nth case,
2044 // validate() lowers to a cron and round-trips it through croner,
2045 // so passing proves token → DOW field → engine-acceptable cron
2046 // with the verified last-<dow>-of-month semantics.
2047 for ok in [
2048 calendar("09:00", &["friL"]), // last Friday
2049 calendar("03:00", &["sunL"]), // last Sunday
2050 calendar("22:00", &["5L"]), // numeric DOW + last
2051 calendar("00:00", &["0L"]), // numeric Sunday (0…
2052 calendar("00:00", &["7L"]), // …and its 7 alias)
2053 calendar("09:00", &["monL", "friL"]), // a list of last-weekdays
2054 // Case-insensitive both the weekday and the `L` suffix:
2055 // validate lowercases the day, croner upper-cases the whole
2056 // pattern before aliasing (claude #547).
2057 calendar("09:00", &["FRIL"]),
2058 calendar("09:00", &["fril"]),
2059 ] {
2060 schedule_with(ok.clone(), RunsOn::Backend)
2061 .validate()
2062 .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
2063 }
2064 }
2065
2066 #[test]
2067 fn validate_rejects_bad_last_weekday() {
2068 // bare `L` (no weekday — a footgun croner reads as Saturday), a
2069 // range with L, a bad day before L, and an internal space that
2070 // would otherwise leak a malformed cron downstream (gemini #560).
2071 for bad in ["L", "l", "mon-friL", "fundayL", "8L", "*L", "fri L"] {
2072 let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
2073 .validate()
2074 .unwrap_err();
2075 assert!(err.contains("when.days"), "for '{bad}', got: {err}");
2076 }
2077 }
2078
2079 #[test]
2080 fn calendar_oneshot_instant_detects_past() {
2081 use chrono::TimeZone;
2082 // a dated `at` resolves to an absolute instant…
2083 let c = CalendarSpec {
2084 at: "2024-01-01 09:00".into(),
2085 days: vec![],
2086 };
2087 let t = c
2088 .oneshot_instant(ScheduleTz::Utc)
2089 .expect("one-shot instant");
2090 assert_eq!(
2091 t,
2092 chrono::Utc.with_ymd_and_hms(2024, 1, 1, 9, 0, 0).unwrap()
2093 );
2094 assert!(t < chrono::Utc::now(), "2024 is in the past");
2095 // …while a repeating (time-only) calendar has no instant
2096 let rep = CalendarSpec {
2097 at: "09:00".into(),
2098 days: vec!["mon-fri".into()],
2099 };
2100 assert!(rep.oneshot_instant(ScheduleTz::Utc).is_none());
2101 }
2102
2103 fn schedule_with_active(from: Option<&str>, until: Option<&str>) -> Schedule {
2104 let mut s = schedule_with(
2105 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
2106 RunsOn::Backend,
2107 );
2108 s.active = Active {
2109 from: from.map(str::to_owned),
2110 until: until.map(str::to_owned),
2111 };
2112 s
2113 }
2114
2115 #[test]
2116 fn validate_accepts_active_window() {
2117 schedule_with_active(Some("2026-07-01"), Some("2026-08-01T12:00:00+09:00"))
2118 .validate()
2119 .expect("date + rfc3339 bounds should validate");
2120 }
2121
2122 #[test]
2123 fn validate_rejects_unparseable_active_bound() {
2124 let err = schedule_with_active(Some("July 1st"), None)
2125 .validate()
2126 .unwrap_err();
2127 assert!(err.contains("active"), "got: {err}");
2128 }
2129
2130 #[test]
2131 fn validate_rejects_from_not_before_until() {
2132 let err = schedule_with_active(Some("2026-08-01"), Some("2026-07-01"))
2133 .validate()
2134 .unwrap_err();
2135 assert!(err.contains("strictly before"), "got: {err}");
2136
2137 let err = schedule_with_active(Some("2026-07-01"), Some("2026-07-01"))
2138 .validate()
2139 .unwrap_err();
2140 assert!(err.contains("strictly before"), "got: {err}");
2141 }
2142
2143 // ---- Active window semantics ----
2144
2145 #[test]
2146 fn active_window_is_half_open() {
2147 use chrono::TimeZone;
2148 let active = Active {
2149 from: Some("2026-07-01".into()),
2150 until: Some("2026-08-01".into()),
2151 };
2152 // UTC tz so the date bounds are UTC midnight.
2153 let at = |y, m, d, h| chrono::Utc.with_ymd_and_hms(y, m, d, h, 0, 0).unwrap();
2154 let c = |t| active.contains(t, ScheduleTz::Utc);
2155 assert!(!c(at(2026, 6, 30, 23)), "before from");
2156 assert!(c(at(2026, 7, 1, 0)), "at from (inclusive)");
2157 assert!(c(at(2026, 7, 15, 12)), "inside");
2158 assert!(!c(at(2026, 8, 1, 0)), "at until (exclusive)");
2159 assert!(!c(at(2026, 8, 2, 0)), "after until");
2160 }
2161
2162 #[test]
2163 fn active_empty_window_is_always_active() {
2164 assert!(Active::default().contains(chrono::Utc::now(), ScheduleTz::Local));
2165 }
2166
2167 #[test]
2168 fn active_rfc3339_bound_honours_offset_regardless_of_tz() {
2169 use chrono::TimeZone;
2170 let active = Active {
2171 from: Some("2026-07-01T09:00:00+09:00".into()),
2172 until: None,
2173 };
2174 // RFC3339 carries its own offset → tz arg is ignored.
2175 // 09:00 JST = 00:00 UTC.
2176 for tz in [ScheduleTz::Utc, ScheduleTz::Local] {
2177 assert!(
2178 !active.contains(
2179 chrono::Utc
2180 .with_ymd_and_hms(2026, 6, 30, 23, 59, 0)
2181 .unwrap(),
2182 tz
2183 )
2184 );
2185 assert!(active.contains(
2186 chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap(),
2187 tz
2188 ));
2189 }
2190 }
2191
2192 #[test]
2193 fn active_date_bound_respects_tz() {
2194 // A bare `YYYY-MM-DD` bound is midnight *in the schedule's
2195 // tz* (#418 Phase 2). The UTC interpretation is exact and
2196 // host-independent; assert that precisely.
2197 use chrono::TimeZone;
2198 let utc = Active::parse_bound("2026-07-01", ScheduleTz::Utc).expect("utc");
2199 assert_eq!(
2200 utc,
2201 chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap()
2202 );
2203
2204 // The local interpretation must equal what chrono::Local
2205 // computes for the same wall-clock midnight — proves the tz
2206 // path is wired to the host zone (the magnitude vs UTC is
2207 // host-dependent, so we compare against Local directly rather
2208 // than hard-coding the JST offset, keeping CI green on UTC
2209 // runners).
2210 let local = Active::parse_bound("2026-07-01", ScheduleTz::Local).expect("local");
2211 let want = chrono::Local
2212 .with_ymd_and_hms(2026, 7, 1, 0, 0, 0)
2213 .single()
2214 .expect("local midnight is unambiguous")
2215 .with_timezone(&chrono::Utc);
2216 assert_eq!(local, want, "date bound resolved in host-local tz");
2217 }
2218
2219 #[test]
2220 fn active_empty_is_skipped_when_serialising() {
2221 let s = schedule_with(
2222 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
2223 RunsOn::Backend,
2224 );
2225 let json = serde_json::to_value(&s).expect("serialise");
2226 assert!(
2227 json.get("active").is_none(),
2228 "empty active must not appear on the wire: {json}"
2229 );
2230 }
2231
2232 // ---- constraints.window (#418 Phase 3) ----
2233
2234 fn with_window(win: &str) -> Schedule {
2235 let mut s = schedule_with(
2236 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
2237 RunsOn::Backend,
2238 );
2239 s.constraints.window = Some(win.into());
2240 s
2241 }
2242
2243 #[test]
2244 fn constraints_window_parses_and_round_trips() {
2245 let yaml = r#"
2246id: x
2247when:
2248 per_pc: { every: 6h }
2249job_id: y
2250target: { all: true }
2251constraints:
2252 window: "22:00-05:00"
2253"#;
2254 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
2255 assert_eq!(s.constraints.window.as_deref(), Some("22:00-05:00"));
2256 let back: Schedule =
2257 serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
2258 assert_eq!(back.constraints.window.as_deref(), Some("22:00-05:00"));
2259 }
2260
2261 #[test]
2262 fn constraints_empty_is_skipped_when_serialising() {
2263 let s = schedule_with(
2264 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
2265 RunsOn::Backend,
2266 );
2267 let json = serde_json::to_value(&s).expect("serialise");
2268 assert!(
2269 json.get("constraints").is_none(),
2270 "empty constraints must not appear on the wire: {json}"
2271 );
2272 }
2273
2274 #[test]
2275 fn window_no_constraint_always_allows() {
2276 let c = Constraints::default();
2277 assert!(c.allows(chrono::Utc::now(), ScheduleTz::Local));
2278 }
2279
2280 #[test]
2281 fn window_same_day_is_half_open() {
2282 use chrono::TimeZone;
2283 let s = with_window("09:00-17:00");
2284 let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
2285 let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
2286 assert!(!a(at(8, 59)), "before start");
2287 assert!(a(at(9, 0)), "at start (inclusive)");
2288 assert!(a(at(16, 59)), "inside");
2289 assert!(!a(at(17, 0)), "at end (exclusive)");
2290 assert!(!a(at(23, 0)), "after end");
2291 }
2292
2293 #[test]
2294 fn window_crossing_midnight() {
2295 use chrono::TimeZone;
2296 let s = with_window("22:00-05:00");
2297 let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
2298 let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
2299 assert!(a(at(22, 0)), "at start tonight");
2300 assert!(a(at(23, 30)), "late tonight");
2301 assert!(a(at(3, 0)), "early tomorrow");
2302 assert!(!a(at(5, 0)), "at end (exclusive)");
2303 assert!(!a(at(12, 0)), "midday outside");
2304 assert!(!a(at(21, 59)), "just before start");
2305 }
2306
2307 #[test]
2308 fn window_respects_tz() {
2309 // The same instant is inside the window under one tz and may
2310 // be outside under another. Compare UTC vs Local via the
2311 // host's own offset (kept CI-green on UTC runners like the
2312 // active tz test does).
2313 use chrono::TimeZone;
2314 let s = with_window("09:00-17:00");
2315 let noon_utc = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 12, 0, 0).unwrap();
2316 // Under UTC, 12:00 is inside 09:00-17:00.
2317 assert!(s.constraints.allows(noon_utc, ScheduleTz::Utc));
2318 // Under Local, the verdict tracks the host wall-clock time;
2319 // assert it matches a direct wall_time membership check.
2320 let local_t = noon_utc.with_timezone(&chrono::Local).time();
2321 let in_local = local_t >= chrono::NaiveTime::from_hms_opt(9, 0, 0).unwrap()
2322 && local_t < chrono::NaiveTime::from_hms_opt(17, 0, 0).unwrap();
2323 assert_eq!(s.constraints.allows(noon_utc, ScheduleTz::Local), in_local);
2324 }
2325
2326 #[test]
2327 fn validate_accepts_good_window() {
2328 for w in ["09:00-17:00", "22:00-05:00", "00:00-23:59"] {
2329 with_window(w)
2330 .validate()
2331 .unwrap_or_else(|e| panic!("'{w}' should validate: {e}"));
2332 }
2333 }
2334
2335 #[test]
2336 fn validate_rejects_bad_window() {
2337 for bad in ["9-5", "22:00", "22:00-22:00", "25:00-05:00", "09:00_17:00"] {
2338 let err = with_window(bad).validate().unwrap_err();
2339 assert!(
2340 err.contains("constraints.window"),
2341 "for '{bad}', got: {err}"
2342 );
2343 }
2344 }
2345
2346 // ---- constraints.skip_dates (#418 holiday exclusion) ----
2347
2348 fn with_skip_dates(dates: &[&str]) -> Schedule {
2349 let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
2350 s.tz = ScheduleTz::Utc; // host-independent date assertions
2351 s.constraints.skip_dates = dates.iter().map(|d| (*d).to_string()).collect();
2352 s
2353 }
2354
2355 #[test]
2356 fn allows_blocks_listed_skip_date() {
2357 use chrono::TimeZone;
2358 let s = with_skip_dates(&["2026-06-10", "2026-12-25"]);
2359 // Any time on a listed date is blocked (whole day).
2360 let on = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap();
2361 assert!(!s.constraints.allows(on, ScheduleTz::Utc));
2362 let on_midnight = chrono::Utc.with_ymd_and_hms(2026, 12, 25, 0, 0, 0).unwrap();
2363 assert!(!s.constraints.allows(on_midnight, ScheduleTz::Utc));
2364 // A date not in the list fires normally.
2365 let off = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
2366 assert!(s.constraints.allows(off, ScheduleTz::Utc));
2367 }
2368
2369 #[test]
2370 fn allows_corrupt_skip_date_fails_closed() {
2371 use chrono::TimeZone;
2372 // A garbled entry (only reachable via hand-edited KV) blocks
2373 // rather than silently re-enabling fires — same posture as a
2374 // corrupt window.
2375 let s = with_skip_dates(&["not-a-date"]);
2376 let any = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
2377 assert!(!s.constraints.allows(any, ScheduleTz::Utc));
2378 }
2379
2380 #[test]
2381 fn validate_accepts_good_skip_dates() {
2382 with_skip_dates(&["2026-01-01", "2026-12-25", "2027-05-03"])
2383 .validate()
2384 .expect("well-formed skip dates should validate");
2385 }
2386
2387 #[test]
2388 fn validate_rejects_bad_skip_date() {
2389 for bad in ["2026-13-01", "01-01-2026", "nope", "2026/01/01"] {
2390 let err = with_skip_dates(&[bad]).validate().unwrap_err();
2391 assert!(
2392 err.contains("constraints.skip_dates"),
2393 "for '{bad}', got: {err}"
2394 );
2395 }
2396 }
2397
2398 #[test]
2399 fn preview_skips_holidays() {
2400 use chrono::TimeZone;
2401 // Daily 09:00 with two of the next five days marked as holidays
2402 // — preview drops exactly those, since it gates on `allows`.
2403 let mut s = cal_utc("09:00", &[]);
2404 s.constraints.skip_dates = vec!["2026-06-11".into(), "2026-06-13".into()];
2405 let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
2406 let got = s.preview_fires(now, 4);
2407 let want: Vec<_> = [
2408 (2026, 6, 10),
2409 (2026, 6, 12), // skips 06-11
2410 (2026, 6, 14), // skips 06-13
2411 (2026, 6, 15),
2412 ]
2413 .iter()
2414 .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
2415 .collect();
2416 assert_eq!(got, want);
2417 }
2418
2419 // ---- constraints.max_concurrent (#418) ----
2420
2421 fn with_max_concurrent(max: u32, runs_on: RunsOn) -> Schedule {
2422 let mut s = schedule_with(
2423 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
2424 runs_on,
2425 );
2426 s.constraints.max_concurrent = Some(max);
2427 s
2428 }
2429
2430 #[test]
2431 fn validate_accepts_backend_max_concurrent() {
2432 with_max_concurrent(5, RunsOn::Backend)
2433 .validate()
2434 .expect("backend max_concurrent should validate");
2435 }
2436
2437 #[test]
2438 fn validate_rejects_max_concurrent_on_agent() {
2439 // Decision E: a central running-instance cap needs a central
2440 // counter, which agents don't have.
2441 let err = with_max_concurrent(5, RunsOn::Agent)
2442 .validate()
2443 .unwrap_err();
2444 assert!(err.contains("constraints.max_concurrent"), "got: {err}");
2445 assert!(err.contains("runs_on: agent"), "got: {err}");
2446 }
2447
2448 #[test]
2449 fn validate_rejects_zero_max_concurrent() {
2450 let err = with_max_concurrent(0, RunsOn::Backend)
2451 .validate()
2452 .unwrap_err();
2453 assert!(err.contains("max_concurrent must be >= 1"), "got: {err}");
2454 }
2455
2456 #[test]
2457 fn max_concurrent_round_trips_and_skips_when_absent() {
2458 let s = with_max_concurrent(3, RunsOn::Backend);
2459 let json = serde_json::to_value(&s.constraints).expect("ser");
2460 assert_eq!(json.get("max_concurrent").and_then(|v| v.as_u64()), Some(3));
2461 // A schedule with no constraints omits the whole block.
2462 let bare = schedule_with(
2463 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
2464 RunsOn::Backend,
2465 );
2466 assert!(bare.constraints.is_empty());
2467 }
2468
2469 #[test]
2470 fn window_fail_closed_on_corrupt_blob() {
2471 // A malformed window (only reachable via a hand-edited KV
2472 // blob — validate() rejects it at create) must BLOCK, not
2473 // silently allow fires during a change-freeze (gemini #452).
2474 let s = with_window("22:00_05:00");
2475 assert!(
2476 !s.constraints.allows(chrono::Utc::now(), ScheduleTz::Utc),
2477 "corrupt window fails closed"
2478 );
2479 // …and the scheduler can surface why it's stuck.
2480 assert!(
2481 s.bad_window().is_some(),
2482 "bad_window reports the parse error"
2483 );
2484 assert!(with_window("22:00-05:00").bad_window().is_none());
2485 }
2486
2487 #[test]
2488 fn calendar_outside_window_is_flagged() {
2489 // at 09:00 can never fall in 22:00-05:00 → never fires.
2490 let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
2491 s.constraints.window = Some("22:00-05:00".into());
2492 assert!(s.calendar_outside_window(), "09:00 is not in 22:00-05:00");
2493
2494 // at 23:00 IS inside the overnight window → fine.
2495 let mut s = schedule_with(calendar("23:00", &[]), RunsOn::Backend);
2496 s.constraints.window = Some("22:00-05:00".into());
2497 assert!(!s.calendar_outside_window(), "23:00 is in 22:00-05:00");
2498
2499 // reconcile shapes are never flagged (they poll every minute).
2500 let mut s = schedule_with(
2501 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
2502 RunsOn::Backend,
2503 );
2504 s.constraints.window = Some("22:00-05:00".into());
2505 assert!(!s.calendar_outside_window(), "reconcile is unaffected");
2506
2507 // no window → never flagged.
2508 let s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
2509 assert!(!s.calendar_outside_window());
2510 }
2511
2512 // ---- on_failure.retry (#418 Phase 4) ----
2513
2514 fn with_retry(max: u32, backoff: &str) -> Schedule {
2515 let mut s = schedule_with(
2516 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
2517 RunsOn::Backend,
2518 );
2519 s.on_failure.retry = Some(Retry {
2520 max,
2521 backoff: backoff.into(),
2522 });
2523 s
2524 }
2525
2526 #[test]
2527 fn on_failure_parses_and_round_trips() {
2528 let yaml = r#"
2529id: x
2530when:
2531 per_pc: { every: 6h }
2532job_id: y
2533target: { all: true }
2534on_failure:
2535 retry: { max: 3, backoff: 10m }
2536"#;
2537 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
2538 let r = s.on_failure.retry.as_ref().expect("retry present");
2539 assert_eq!(r.max, 3);
2540 assert_eq!(r.backoff, "10m");
2541 let back: Schedule =
2542 serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
2543 assert_eq!(back.on_failure, s.on_failure);
2544 }
2545
2546 #[test]
2547 fn on_failure_empty_is_skipped_when_serialising() {
2548 let s = schedule_with(
2549 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
2550 RunsOn::Backend,
2551 );
2552 let json = serde_json::to_value(&s).expect("serialise");
2553 assert!(
2554 json.get("on_failure").is_none(),
2555 "empty on_failure must not appear on the wire: {json}"
2556 );
2557 }
2558
2559 #[test]
2560 fn validate_accepts_good_retry() {
2561 for (max, backoff) in [(1, "30s"), (3, "10m"), (10, "1h")] {
2562 with_retry(max, backoff)
2563 .validate()
2564 .unwrap_or_else(|e| panic!("retry {{max:{max}, backoff:{backoff}}}: {e}"));
2565 }
2566 }
2567
2568 #[test]
2569 fn validate_rejects_bad_backoff() {
2570 let err = with_retry(3, "soon").validate().unwrap_err();
2571 assert!(err.contains("on_failure.retry.backoff"), "got: {err}");
2572 }
2573
2574 #[test]
2575 fn validate_rejects_sub_second_backoff() {
2576 // "500ms" parses as humantime but lowers to 0s on the wire —
2577 // reject it so the operator doesn't get a silent no-wait
2578 // (coderabbit #466).
2579 for bad in ["500ms", "0s", "999ms"] {
2580 let err = with_retry(3, bad).validate().unwrap_err();
2581 assert!(
2582 err.contains("on_failure.retry.backoff must be >= 1s"),
2583 "for '{bad}', got: {err}"
2584 );
2585 }
2586 }
2587
2588 #[test]
2589 fn validate_rejects_out_of_range_max() {
2590 for bad in [0u32, 11, 1000] {
2591 let err = with_retry(bad, "10m").validate().unwrap_err();
2592 assert!(
2593 err.contains("on_failure.retry.max"),
2594 "for max={bad}, got: {err}"
2595 );
2596 }
2597 }
2598
2599 #[test]
2600 fn lowered_retry_reduces_backoff_to_seconds() {
2601 let s = with_retry(3, "10m");
2602 let spec = s.on_failure.lowered_retry().expect("a retry policy");
2603 assert_eq!(spec.max, 3);
2604 assert_eq!(spec.backoff_secs, 600);
2605 }
2606
2607 #[test]
2608 fn lowered_retry_is_none_without_policy() {
2609 let s = schedule_with(
2610 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
2611 RunsOn::Backend,
2612 );
2613 assert!(s.on_failure.lowered_retry().is_none());
2614 }
2615
2616 // ---- global change-freeze (#418 Phase 5) ----
2617
2618 #[test]
2619 fn freeze_empty_window_is_always_active() {
2620 // The big-red-button shape: no bounds = frozen until cleared.
2621 let f = Freeze::default();
2622 assert!(f.is_active(chrono::Utc::now()));
2623 }
2624
2625 #[test]
2626 fn freeze_window_is_half_open() {
2627 use chrono::TimeZone;
2628 let f = Freeze {
2629 from: Some("2026-12-20T00:00:00+00:00".into()),
2630 until: Some("2027-01-05T00:00:00+00:00".into()),
2631 reason: Some("year-end".into()),
2632 tz: ScheduleTz::Utc,
2633 };
2634 let at = |y, mo, d| chrono::Utc.with_ymd_and_hms(y, mo, d, 0, 0, 0).unwrap();
2635 assert!(!f.is_active(at(2026, 12, 19)), "before from = not frozen");
2636 assert!(f.is_active(at(2026, 12, 20)), "from is inclusive");
2637 assert!(f.is_active(at(2026, 12, 31)), "inside window");
2638 assert!(!f.is_active(at(2027, 1, 5)), "until is exclusive");
2639 assert!(!f.is_active(at(2027, 1, 6)), "after until = not frozen");
2640 }
2641
2642 #[test]
2643 fn freeze_fails_closed_on_corrupt_bound() {
2644 // A freeze is a safety switch: an unparseable bound (only
2645 // reachable via a hand-edited KV blob) must read as FROZEN, not
2646 // "fire normally" (coderabbit #472) — the opposite of `active`,
2647 // which fail-opens.
2648 let f = Freeze {
2649 from: Some("not-a-date".into()),
2650 until: None,
2651 reason: None,
2652 tz: ScheduleTz::Utc,
2653 };
2654 assert!(f.is_active(chrono::Utc::now()), "corrupt bound → frozen");
2655 }
2656
2657 #[test]
2658 fn freeze_validate_accepts_good_bounds() {
2659 Freeze {
2660 from: Some("2026-12-20".into()),
2661 until: Some("2027-01-05T12:00:00+09:00".into()),
2662 reason: None,
2663 tz: ScheduleTz::Local,
2664 }
2665 .validate()
2666 .expect("date + rfc3339 bounds should validate");
2667 // Empty (indefinite) freeze is valid.
2668 Freeze::default().validate().expect("empty freeze is valid");
2669 }
2670
2671 #[test]
2672 fn freeze_validate_rejects_bad_bound_and_inverted_window() {
2673 let err = Freeze {
2674 from: Some("never".into()),
2675 ..Default::default()
2676 }
2677 .validate()
2678 .unwrap_err();
2679 assert!(err.contains("freeze:"), "got: {err}");
2680
2681 let inverted = Freeze {
2682 from: Some("2027-01-05".into()),
2683 until: Some("2026-12-20".into()),
2684 ..Default::default()
2685 }
2686 .validate()
2687 .unwrap_err();
2688 assert!(inverted.contains("freeze.from"), "got: {inverted}");
2689 }
2690
2691 #[test]
2692 fn freeze_round_trips_and_skips_empty_fields() {
2693 let f = Freeze {
2694 from: None,
2695 until: Some("2027-01-05".into()),
2696 reason: Some("INC-1234".into()),
2697 tz: ScheduleTz::Utc,
2698 };
2699 let json = serde_json::to_value(&f).expect("serialise");
2700 assert!(json.get("from").is_none(), "empty from omitted: {json}");
2701 let back: Freeze = serde_json::from_value(json).expect("round-trip");
2702 assert_eq!(back, f);
2703 }
2704
2705 #[test]
2706 fn shipped_schedule_configs_parse_and_validate() {
2707 // Every YAML under configs/schedules/ must parse with the
2708 // current Schedule serde AND pass validate() — keeps the
2709 // shipped examples from drifting out of sync with the model
2710 // (#418 removed back-compat, so drift = broken at create).
2711 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../configs/schedules");
2712 let mut seen = 0;
2713 for entry in std::fs::read_dir(&dir).expect("read configs/schedules") {
2714 let path = entry.expect("dir entry").path();
2715 if path.extension().and_then(|e| e.to_str()) != Some("yaml") {
2716 continue;
2717 }
2718 let body = std::fs::read_to_string(&path).expect("read yaml");
2719 let s: Schedule = serde_yaml::from_str(&body)
2720 .unwrap_or_else(|e| panic!("{} failed to parse: {e}", path.display()));
2721 s.validate()
2722 .unwrap_or_else(|e| panic!("{} failed validate(): {e}", path.display()));
2723 seen += 1;
2724 }
2725 assert!(seen > 0, "no schedule YAMLs found in {}", dir.display());
2726 }
2727
2728 // ---- pre-existing enum wire formats (unchanged by #418) ----
2729
2730 #[test]
2731 fn exec_mode_serialises_snake_case() {
2732 for (mode, expected) in [
2733 (ExecMode::EveryTick, "every_tick"),
2734 (ExecMode::OncePerPc, "once_per_pc"),
2735 (ExecMode::OncePerTarget, "once_per_target"),
2736 ] {
2737 let s = serde_json::to_value(mode).expect("serialise");
2738 assert_eq!(s, serde_json::Value::String(expected.into()));
2739 let back: ExecMode = serde_json::from_value(serde_json::Value::String(expected.into()))
2740 .expect("deserialise");
2741 assert_eq!(back, mode, "round-trip for {expected}");
2742 }
2743 }
2744
2745 #[test]
2746 fn schedule_runs_on_defaults_to_backend() {
2747 let yaml = r#"
2748id: x
2749when:
2750 per_pc: once
2751job_id: y
2752target: { all: true }
2753"#;
2754 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
2755 assert_eq!(s.runs_on, RunsOn::Backend);
2756 }
2757
2758 #[test]
2759 fn schedule_runs_on_agent_parses() {
2760 let yaml = r#"
2761id: offline-inv
2762when:
2763 per_pc: { every: 1h }
2764job_id: inventory-hw
2765target: { all: true }
2766runs_on: agent
2767"#;
2768 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
2769 assert_eq!(s.runs_on, RunsOn::Agent);
2770 assert_eq!(s.lowered().mode, ExecMode::OncePerPc);
2771 }
2772
2773 #[test]
2774 fn runs_on_serialises_snake_case() {
2775 for (mode, expected) in [(RunsOn::Backend, "backend"), (RunsOn::Agent, "agent")] {
2776 let s = serde_json::to_value(mode).expect("serialise");
2777 assert_eq!(s, serde_json::Value::String(expected.into()));
2778 let back: RunsOn = serde_json::from_value(serde_json::Value::String(expected.into()))
2779 .expect("deserialise");
2780 assert_eq!(back, mode);
2781 }
2782 }
2783
2784 #[test]
2785 fn execute_shell_into_wire_shell() {
2786 assert_eq!(Shell::from(ExecuteShell::Powershell), Shell::Powershell);
2787 assert_eq!(Shell::from(ExecuteShell::Cmd), Shell::Cmd);
2788 }
2789
2790 #[test]
2791 fn manifest_staleness_defaults_to_cached() {
2792 let yaml = r#"
2793id: x
2794version: 1.0.0
2795execute:
2796 shell: powershell
2797 script: "echo"
2798 timeout: 1s
2799"#;
2800 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2801 assert_eq!(m.staleness, Staleness::Cached);
2802 }
2803
2804 #[test]
2805 fn manifest_strict_staleness_parses() {
2806 let yaml = r#"
2807id: urgent-patch
2808version: 2.5.1
2809execute:
2810 shell: powershell
2811 script: Install-Hotfix
2812 timeout: 5m
2813staleness:
2814 mode: strict
2815 max_cache_age: 0s
2816"#;
2817 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2818 match m.staleness {
2819 Staleness::Strict { max_cache_age } => assert_eq!(max_cache_age, "0s"),
2820 other => panic!("expected strict, got {other:?}"),
2821 }
2822 }
2823
2824 #[test]
2825 fn manifest_unchecked_staleness_parses() {
2826 let yaml = r#"
2827id: legacy
2828version: 0.1.0
2829execute:
2830 shell: cmd
2831 script: "echo"
2832 timeout: 1s
2833staleness:
2834 mode: unchecked
2835"#;
2836 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2837 assert_eq!(m.staleness, Staleness::Unchecked);
2838 }
2839
2840 #[test]
2841 fn missing_required_field_errors() {
2842 // `id` missing.
2843 let yaml = r#"
2844version: 1.0.0
2845target: { all: true }
2846execute:
2847 shell: powershell
2848 script: "echo"
2849 timeout: 1s
2850"#;
2851 let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
2852 assert!(r.is_err(), "expected error, got {:?}", r);
2853 }
2854
2855 #[test]
2856 fn display_field_table_kind_round_trips_with_nested_columns() {
2857 // #39: `type: table` + `columns:` on a DisplayField gets
2858 // round-tripped through serde so the SPA receives the
2859 // nested schema verbatim. Nested columns themselves are
2860 // DisplayFields so they can carry `type: bytes` /
2861 // `type: number` for cell formatting.
2862 let yaml = r#"
2863id: inv-hw
2864version: 1.0.0
2865execute:
2866 shell: powershell
2867 script: "echo"
2868 timeout: 60s
2869inventory:
2870 display:
2871 - field: hostname
2872 label: Hostname
2873 - field: disks
2874 label: Disks
2875 type: table
2876 columns:
2877 - field: device_id
2878 label: Drive
2879 - field: size_bytes
2880 label: Size
2881 type: bytes
2882 - field: free_bytes
2883 label: Free
2884 type: bytes
2885 - field: file_system
2886 label: FS
2887"#;
2888 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2889 let inv = m.inventory.as_ref().expect("inventory hint");
2890 let disks = inv
2891 .display
2892 .iter()
2893 .find(|d| d.field == "disks")
2894 .expect("disks display row");
2895 assert_eq!(disks.kind.as_deref(), Some("table"));
2896 let cols = disks.columns.as_ref().expect("table needs columns");
2897 assert_eq!(cols.len(), 4);
2898 assert_eq!(cols[1].field, "size_bytes");
2899 assert_eq!(cols[1].kind.as_deref(), Some("bytes"));
2900 }
2901
2902 #[test]
2903 fn display_field_scalar_kind_keeps_columns_none() {
2904 // Defensive: when type is a scalar (`bytes` / `number` /
2905 // `timestamp`) the `columns` field stays None — the SPA
2906 // uses its presence as the "render nested table" signal,
2907 // so it must not leak in via serde defaults.
2908 let yaml = r#"
2909id: x
2910version: 1.0.0
2911execute:
2912 shell: powershell
2913 script: "echo"
2914 timeout: 5s
2915inventory:
2916 display:
2917 - { field: ram_bytes, label: RAM, type: bytes }
2918"#;
2919 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2920 let inv = m.inventory.as_ref().unwrap();
2921 assert!(inv.display[0].columns.is_none());
2922 }
2923
2924 // ---- checked-in JSON Schema freshness (docs/schemas/) ----
2925
2926 /// The JSON Schemas under `docs/schemas/` must match what
2927 /// `schema_for!` produces today — a Cargo.lock-style freshness guard
2928 /// so a `Schedule` / `Manifest` field change can't silently drift
2929 /// the operator-facing schema. The SPA editor, the backend
2930 /// `/api/schemas/*` endpoints, and these files all read the same
2931 /// derived shape; this test fails CI if the checked-in copy lags.
2932 /// Regenerate with:
2933 /// `UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current`
2934 #[test]
2935 fn schema_files_are_current() {
2936 assert_schema_file("schedule.schema.json", &schemars::schema_for!(Schedule));
2937 assert_schema_file("job.schema.json", &schemars::schema_for!(Manifest));
2938 }
2939
2940 fn assert_schema_file(name: &str, schema: &schemars::Schema) {
2941 let generated = serde_json::to_string_pretty(schema).expect("serialize schema") + "\n";
2942 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2943 .join("../../docs/schemas")
2944 .join(name);
2945 if std::env::var_os("UPDATE_SCHEMAS").is_some() {
2946 std::fs::create_dir_all(path.parent().unwrap()).expect("mkdir docs/schemas");
2947 std::fs::write(&path, &generated).unwrap_or_else(|e| panic!("write {path:?}: {e}"));
2948 return;
2949 }
2950 // Normalize CRLF→LF before comparing: `.gitattributes` already
2951 // pins these files to `eol=lf`, but a stray CRLF working-tree
2952 // copy (autocrlf, a tool rewrite) shouldn't turn a *content*-
2953 // freshness check into a confusing line-ending failure — that's
2954 // .gitattributes' job, not this test's (gemini #588).
2955 let on_disk = std::fs::read_to_string(&path)
2956 .unwrap_or_else(|e| {
2957 panic!(
2958 "read {path:?}: {e}\n\
2959 generate it with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
2960 )
2961 })
2962 .replace("\r\n", "\n");
2963 assert_eq!(
2964 on_disk, generated,
2965 "{name} is stale — a Schedule/Manifest schema change isn't reflected in docs/schemas/. \
2966 Refresh with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
2967 );
2968 }
2969}
2970
2971/// Periodic schedule (spec §2.4.3). v0.18.0 carries the fanout plan
2972/// (target + optional rollout + optional jitter) inline; the
2973/// referenced job (`job_id` → [`BUCKET_JOBS`]) supplies only the
2974/// script body. Two schedules of the same job can target different
2975/// groups on different cadences without copying the manifest.
2976///
2977/// #418 Phase 1: the cadence is the single [`When`] field. The old
2978/// `cron` × `mode` × `cooldown` × `auto_disable_when_done` quartet
2979/// is gone (no back-compat — pre-Phase-1 KV blobs fail to parse and
2980/// are warn-skipped; re-`schedule create` to upgrade them). The
2981/// engine underneath is unchanged: [`Schedule::lowered`] maps `when`
2982/// onto the same (cron, ExecMode, cooldown) trio the scheduler and
2983/// `decide_fire` always ran on.
2984#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2985pub struct Schedule {
2986 pub id: String,
2987 /// When to fire — a reconcile cadence (`per_pc` / `per_target`)
2988 /// or a calendar time trigger (`at` / `days`). See [`When`].
2989 ///
2990 /// `singleton_map`: serde_yaml 0.9 renders externally-tagged
2991 /// enums as `!per_pc` YAML tags by default; this keeps the
2992 /// operator-facing map shape (`when: { per_pc: once }`). JSON
2993 /// output is identical either way, and the schemars schema
2994 /// (external tagging = oneOf of single-key objects) already
2995 /// matches the singleton-map wire shape.
2996 #[serde(with = "serde_yaml::with::singleton_map")]
2997 #[schemars(with = "When")]
2998 pub when: When,
2999 /// Key into [`crate::kv::BUCKET_JOBS`]. Must equal a registered
3000 /// Manifest's `id`.
3001 pub job_id: String,
3002 /// Who + how-to-phase + when-to-stagger. The Manifest doesn't
3003 /// carry these any more — same job + different fanout = different
3004 /// schedule.
3005 #[serde(flatten)]
3006 pub plan: FanoutPlan,
3007 /// Optional validity window. Outside `[from, until)` the
3008 /// schedule is dormant — still registered, still visible, but
3009 /// every tick is skipped (deleted ≠ dormant: a campaign that
3010 /// ended stays inspectable and can be re-armed by editing the
3011 /// window). Checked at tick time on both the backend scheduler
3012 /// and the agent's local scheduler.
3013 #[serde(default, skip_serializing_if = "Active::is_empty")]
3014 pub active: Active,
3015 /// #418 operational constraints gating *when within an active
3016 /// period* a fire may happen: a maintenance `window`, a fleet
3017 /// `max_concurrent` cap, and `skip_dates` (holiday exclusion). The
3018 /// wall-clock ones are evaluated in the schedule's `tz`; future
3019 /// `require` (env gates) lands in the same namespace. Checked at
3020 /// tick time on both schedulers (and surfaced by `preview`).
3021 #[serde(default, skip_serializing_if = "Constraints::is_empty")]
3022 pub constraints: Constraints,
3023 /// #418 Phase 4: what to do after a fire's script comes back
3024 /// failed. Currently just `retry` (fixed-backoff in-process
3025 /// re-run); future `notify` / `disable` join the same namespace.
3026 /// Applied fire-side in `handle_command` (the retry policy is
3027 /// lowered onto every Command this schedule produces), so it
3028 /// covers both `runs_on` locations.
3029 #[serde(default, skip_serializing_if = "OnFailure::is_empty")]
3030 pub on_failure: OnFailure,
3031 /// #418 Phase 2: the timezone this schedule's wall-clock fields
3032 /// are evaluated in — both the calendar `at` firing time AND the
3033 /// `active.{from,until}` window bounds. `local` (default) = the
3034 /// running host's TZ (the agent's for `runs_on: agent`, the
3035 /// backend server's otherwise); `utc` for TZ-independent
3036 /// schedules. Reconcile shapes (`per_pc`/`per_target`) ignore it
3037 /// for firing (poll cron runs every minute regardless) but still
3038 /// honor it for the `active` window.
3039 #[serde(default)]
3040 pub tz: ScheduleTz,
3041 /// v0.22: optional humantime window after a cron tick during
3042 /// which the Command is still considered "live". The scheduler
3043 /// computes `tick_at + starting_deadline` and stamps it onto
3044 /// each Command as `deadline_at`; agents skip Commands they
3045 /// receive after that absolute time. `None` (default) = no
3046 /// deadline, meaning a Command queued in the broker / stream
3047 /// during agent downtime runs whenever the agent reconnects —
3048 /// good for kitting / inventory / cleanup. Set this for
3049 /// time-of-day notifications, lunch reminders, etc., where
3050 /// "fire 3 hours late" would be wrong.
3051 #[serde(default, skip_serializing_if = "Option::is_none")]
3052 pub starting_deadline: Option<String>,
3053 /// v0.23: where does the cron tick happen? `Backend` (default,
3054 /// historical) = backend's scheduler fires Commands via NATS;
3055 /// agents passively receive. `Agent` = each targeted agent runs
3056 /// its own internal cron and fires locally, so the schedule
3057 /// keeps ticking even when the broker is unreachable (laptop on
3058 /// the train, broker maintenance window, full WAN outage). The
3059 /// two locations are mutually exclusive — when `Agent`, the
3060 /// backend scheduler stays out and just keeps the definition in
3061 /// KV for agents to read.
3062 #[serde(default)]
3063 pub runs_on: RunsOn,
3064 #[serde(default = "default_true")]
3065 pub enabled: bool,
3066}
3067
3068/// v0.23 — where the cron tick fires from.
3069#[derive(
3070 Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
3071)]
3072#[serde(rename_all = "snake_case")]
3073pub enum RunsOn {
3074 /// Backend's central scheduler ticks and publishes Commands to
3075 /// NATS. Historical default, what every pre-v0.23 schedule
3076 /// uses. Agent offline ⇒ Command queued in STREAM_EXEC; agent
3077 /// reconnects ⇒ catch-up via [`command_replay`](crate)
3078 /// (see kanade-agent's command_replay module).
3079 #[default]
3080 Backend,
3081 /// Each targeted agent runs the cron tick locally. Survives
3082 /// broker / WAN outages. Best for laptops / mobile devices that
3083 /// roam off the corporate network. Agent must be online for the
3084 /// initial schedule + job-catalog pull, but once cached the
3085 /// agent fires the script standalone.
3086 Agent,
3087}
3088
3089/// Per-pc/per-target dedup semantics for a [`Schedule`] (v0.19).
3090#[derive(
3091 Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
3092)]
3093#[serde(rename_all = "snake_case")]
3094pub enum ExecMode {
3095 /// Fire on every cron tick at the whole target. Historical
3096 /// (pre-v0.19) behavior; no dedup.
3097 #[default]
3098 EveryTick,
3099 /// Fire at each pc until that pc succeeds; then skip it until
3100 /// the optional cooldown elapses (or forever if no cooldown).
3101 /// Use for kitting / first-boot / per-pc compliance checks.
3102 OncePerPc,
3103 /// Fire at the whole target until **any** pc succeeds; then
3104 /// skip the whole target until the optional cooldown elapses
3105 /// (or forever if no cooldown). Use for "one delegate is
3106 /// enough" tasks like license check-in.
3107 OncePerTarget,
3108 /// #418 OS-native event trigger (`when: { on: [...] }`). There is
3109 /// no cron — the agent fires it from an OS event source (boot /
3110 /// session-change), not a tick — so the scheduler skips
3111 /// `tokio-cron` registration for it. Each event occurrence fires
3112 /// once, gated by the standard freeze / active / window /
3113 /// skip_dates checks.
3114 Event,
3115}
3116
3117/// #418 Phase 1 — the single "when does this fire" axis.
3118///
3119/// Replaces the old `cron` + `mode` + `cooldown` trio whose
3120/// interactions were implicit (cron doubled as both a real
3121/// time-of-day trigger and a reconcile poll period; contradictory
3122/// combinations silently no-opped). Two shapes:
3123///
3124/// * **reconcile** (`per_pc` / `per_target`) — desired-state: "each
3125/// pc (or one delegate) should have run this within `every`".
3126/// The poll period is system-generated ([`POLL_CRON`], every
3127/// minute) and no longer the operator's concern.
3128/// * **calendar** (`{ at, days }`) — a wall-clock time trigger
3129/// (#418 Phase 2, replacing the old raw-cron escape hatch). Fires
3130/// the whole target at the given time, no dedup. `at: "09:00"` +
3131/// `days` repeats; `at: "2026-06-10 09:00"` (a date+time) fires
3132/// exactly once. Evaluated in the schedule's top-level `tz`.
3133#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
3134#[serde(rename_all = "snake_case")]
3135pub enum When {
3136 /// Fire at each targeted pc: `once` (kitting — succeed once,
3137 /// skip forever, forever catching brand-new / re-imaged pcs)
3138 /// or `{ every: <humantime> }` (patrol — re-arm per pc after
3139 /// the interval).
3140 PerPc(PerPolicy),
3141 /// Fire until **any** one pc of the target succeeds, then skip
3142 /// the whole target (`once`) or re-arm after `every`. Needs
3143 /// fleet-wide completion data, so it is backend-only —
3144 /// `runs_on: agent` + `per_target` is rejected by
3145 /// [`Schedule::validate`].
3146 PerTarget(PerPolicy),
3147 /// Calendar time trigger: `{ at: "09:00", days: [mon-fri] }`
3148 /// (repeating) or `{ at: "2026-06-10 09:00" }` (one-shot). Fires
3149 /// the whole target at that wall-clock time in the schedule's
3150 /// `tz` — no dedup, no cooldown.
3151 Calendar(CalendarSpec),
3152 /// #418 OS-native event trigger: `when: { on: [startup, logon] }`.
3153 /// Fires when the agent observes the listed OS event(s) rather than
3154 /// on a clock — there is no cron. `runs_on: agent` only (the agent
3155 /// owns the event source); [`Schedule::validate`] rejects it on
3156 /// `backend` and rejects an empty list. Each event occurrence fires
3157 /// once, gated by the same freeze / active / `constraints.window` /
3158 /// `skip_dates` checks as the cron path. `startup` fires once per OS
3159 /// boot (deduped via the host boot time); a `starting_deadline`, if
3160 /// set, limits it to "agent came up within that long after boot".
3161 On(Vec<OnTrigger>),
3162}
3163
3164/// An OS event the agent can fire a schedule on (#418 `when: { on }`).
3165/// `unlock` / `network_change` are planned follow-ups.
3166#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash)]
3167#[serde(rename_all = "snake_case")]
3168pub enum OnTrigger {
3169 /// Once per OS boot (the agent's first run for that boot). Catches
3170 /// freshly-imaged / reinstalled hosts at their next startup.
3171 Startup,
3172 /// On an interactive-session user logon — console, RDP, or
3173 /// auto-logon (Windows `WTS_SESSION_LOGON`). Does not fire for
3174 /// service / network / batch logons (no interactive session).
3175 Logon,
3176}
3177
3178/// Calendar time trigger (#418 Phase 2). `at` is either a time of
3179/// day (`"HH:MM"`, repeating — combine with `days`) or a full
3180/// date+time (`"YYYY-MM-DD HH:MM"`, a one-shot that fires once and
3181/// never again). Evaluated in the schedule's top-level `tz`.
3182#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
3183pub struct CalendarSpec {
3184 /// `"HH:MM"` (24h) for a repeating trigger, or
3185 /// `"YYYY-MM-DD HH:MM"` (hyphen / slash / `T` separators all
3186 /// accepted) for a one-shot. Parsed lazily —
3187 /// [`Schedule::validate`] rejects garbage at create time.
3188 pub at: String,
3189 /// Day-of-week filter for a time-of-day `at`: `["mon-fri"]`,
3190 /// `["mon","wed","fri"]`, … (passed verbatim to the cron DOW
3191 /// field, so ranges and names both work). An **nth-weekday**
3192 /// `["tue#2"]` fires only on the 2nd Tuesday of each month
3193 /// ("Patch Tuesday"); the ordinal is `1..5`. A **last-weekday**
3194 /// `["friL"]` fires only on the last Friday of each month (handy
3195 /// for monthly maintenance). Empty = every day. Must be empty
3196 /// when `at` carries a date (the date already pins the day).
3197 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3198 pub days: Vec<String>,
3199}
3200
3201/// Parsed `CalendarSpec.at`: the wall-clock minute/hour, plus the
3202/// date for a one-shot (`None` = repeating time-of-day).
3203struct ParsedAt {
3204 minute: u32,
3205 hour: u32,
3206 date: Option<chrono::NaiveDate>,
3207}
3208
3209impl CalendarSpec {
3210 /// Parse `at`: a date+time (`YYYY-MM-DD HH:MM`, hyphen / slash /
3211 /// `T` separators) is a one-shot; a bare `HH:MM` is repeating.
3212 fn parse_at(&self) -> Result<ParsedAt, String> {
3213 use chrono::Timelike;
3214 let s = self.at.trim();
3215 for fmt in ["%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y/%m/%d %H:%M"] {
3216 if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, fmt) {
3217 return Ok(ParsedAt {
3218 minute: dt.minute(),
3219 hour: dt.hour(),
3220 date: Some(dt.date()),
3221 });
3222 }
3223 }
3224 if let Ok(t) = chrono::NaiveTime::parse_from_str(s, "%H:%M") {
3225 return Ok(ParsedAt {
3226 minute: t.minute(),
3227 hour: t.hour(),
3228 date: None,
3229 });
3230 }
3231 Err(format!(
3232 "when.at: unparseable '{}' (want HH:MM or YYYY-MM-DD HH:MM)",
3233 self.at
3234 ))
3235 }
3236
3237 /// Pre-flight check on the `days` tokens so a bad day name gives
3238 /// a `when.days:`-scoped error instead of croner's confusing
3239 /// "when.at lowered to invalid cron" (claude #432 review). Each
3240 /// token is a day name (`mon`..`sun`), a numeric DOW (`0`..`7`),
3241 /// `*`, a `-` range of those, an **nth-weekday** like `tue#2`
3242 /// (2nd Tuesday of the month — "Patch Tuesday"), or a
3243 /// **last-weekday** like `friL` (last Friday of the month).
3244 fn validate_days(&self) -> Result<(), String> {
3245 const NAMES: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
3246 let is_day = |p: &str| NAMES.contains(&p) || p.parse::<u8>().is_ok_and(|n| n <= 7);
3247 for tok in &self.days {
3248 // Report the whole token on a malformed range like `mon-`
3249 // (which would otherwise split to a cryptic empty part —
3250 // claude #432 follow-up).
3251 let invalid = |reason: &str| {
3252 Err(format!(
3253 "when.days: invalid day token '{tok}' ({reason}; \
3254 want mon..sun, 0-7, a range like mon-fri, an nth-weekday \
3255 like tue#2, a last-weekday like friL, or *)"
3256 ))
3257 };
3258 // #418: nth-weekday suffix (`tue#2` = 2nd Tuesday). Croner
3259 // accepts `<dow>#<n>` (n = 1..5) in the DOW field, and
3260 // `to_cron` passes the token through verbatim, so the
3261 // engine fires only on that occurrence. It's a single
3262 // weekday + ordinal — not combinable with a range.
3263 if let Some((day_part, nth_part)) = tok.split_once('#') {
3264 // Normalize once and use `d` consistently (gemini #547);
3265 // the outer `invalid` already echoes the raw `tok`.
3266 let d = day_part.trim().to_ascii_lowercase();
3267 if d.contains('-') || !is_day(&d) {
3268 return invalid("the part before # must be a single weekday");
3269 }
3270 match nth_part.trim().parse::<u8>() {
3271 Ok(n) if (1..=5).contains(&n) => {}
3272 _ => return invalid("the # ordinal must be 1..5 (e.g. tue#2 = 2nd Tuesday)"),
3273 }
3274 continue;
3275 }
3276 // #418: last-weekday suffix (`friL` = last Friday of the
3277 // month — the monthly-maintenance sibling of Patch Tuesday).
3278 // Croner accepts `<dow>L` in the DOW field with verified
3279 // last-<dow>-of-month semantics, and `to_cron` passes it
3280 // through verbatim. A single weekday + `L` — bare `L` and
3281 // ranges are rejected (croner would read bare `L` as
3282 // Saturday, which is a confusing footgun).
3283 if let Some(day_part) = tok.strip_suffix(['L', 'l']) {
3284 // No `.trim()`: a cron DOW token can't carry internal
3285 // whitespace, so `"fri L"` must be *rejected* here (its
3286 // strip leaves `"fri "`, and `is_day` catches the space)
3287 // rather than trimmed into a clean `"fri"` that then
3288 // produces a malformed `fri L` cron downstream and a
3289 // confusing croner error (gemini #560).
3290 let d = day_part.to_ascii_lowercase();
3291 if d.is_empty() {
3292 return invalid("`L` (last-weekday) needs a weekday before it, e.g. friL");
3293 }
3294 if d.contains('-') || !is_day(&d) {
3295 return invalid(
3296 "the part before L must be a single weekday (e.g. friL = last Friday)",
3297 );
3298 }
3299 continue;
3300 }
3301 for part in tok.split('-') {
3302 let p = part.trim().to_ascii_lowercase();
3303 if p.is_empty() {
3304 return invalid("empty range bound");
3305 }
3306 if p != "*" && !is_day(&p) {
3307 return invalid(&format!("'{part}' is not a day"));
3308 }
3309 }
3310 }
3311 Ok(())
3312 }
3313
3314 /// For a one-shot (`at` carries a date), the absolute instant it
3315 /// fires in `tz`. `None` for a repeating calendar. Used to warn
3316 /// about a one-shot whose date is already in the past (it would
3317 /// never fire).
3318 pub fn oneshot_instant(&self, tz: ScheduleTz) -> Option<chrono::DateTime<chrono::Utc>> {
3319 let p = self.parse_at().ok()?;
3320 let date = p.date?;
3321 let naive = date.and_hms_opt(p.hour, p.minute, 0)?;
3322 tz.naive_to_utc(naive)
3323 }
3324
3325 /// The wall-clock time-of-day this calendar fires at (`None` if
3326 /// `at` is unparseable — validate() guards that). Used to detect
3327 /// a calendar whose fire time can never fall inside its
3328 /// `constraints.window` (claude #452 review).
3329 pub fn fire_time(&self) -> Option<chrono::NaiveTime> {
3330 let p = self.parse_at().ok()?;
3331 chrono::NaiveTime::from_hms_opt(p.hour, p.minute, 0)
3332 }
3333
3334 /// Lower to the cron string the scheduler engine runs. Repeating
3335 /// → 6-field `0 {min} {hour} * * {dow}`; one-shot → 7-field
3336 /// `0 {min} {hour} {day} {month} * {year}` (a past year never
3337 /// fires — that's what makes it one-shot).
3338 fn to_cron(&self) -> Result<String, String> {
3339 use chrono::Datelike;
3340 let ParsedAt { minute, hour, date } = self.parse_at()?;
3341 match date {
3342 Some(d) => {
3343 if !self.days.is_empty() {
3344 return Err(
3345 "when.at with a date is a one-shot and cannot be combined with days".into(),
3346 );
3347 }
3348 Ok(format!(
3349 "0 {minute} {hour} {} {} * {}",
3350 d.day(),
3351 d.month(),
3352 d.year()
3353 ))
3354 }
3355 None => {
3356 let dow = if self.days.is_empty() {
3357 "*".to_string()
3358 } else {
3359 self.validate_days()?;
3360 self.days.join(",")
3361 };
3362 Ok(format!("0 {minute} {hour} * * {dow}"))
3363 }
3364 }
3365 }
3366}
3367
3368/// The timezone a schedule's wall-clock fields (`when.at`,
3369/// `active.{from,until}`) are evaluated in (#418 Phase 2).
3370#[derive(
3371 Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
3372)]
3373#[serde(rename_all = "snake_case")]
3374pub enum ScheduleTz {
3375 /// The running host's local timezone — the agent's for
3376 /// `runs_on: agent`, the backend server's otherwise. Default.
3377 #[default]
3378 Local,
3379 /// UTC — for timezone-independent schedules.
3380 Utc,
3381}
3382
3383impl ScheduleTz {
3384 /// Interpret a naive (zoneless) datetime as being in this tz and
3385 /// convert to UTC. On a DST *fold* (the local time occurs twice
3386 /// when clocks go back) we pick `.earliest()` rather than
3387 /// rejecting it; `None` is reserved for a true DST *gap* (a local
3388 /// time that never exists). `Utc` is fixed-offset so neither ever
3389 /// happens; `Local` is whatever timezone the running host is set
3390 /// to and *can* hit a gap/fold on any DST-observing host — not
3391 /// just the JST we run today (gemini + claude #432 review).
3392 fn naive_to_utc(self, naive: chrono::NaiveDateTime) -> Option<chrono::DateTime<chrono::Utc>> {
3393 use chrono::TimeZone;
3394 match self {
3395 ScheduleTz::Utc => Some(chrono::DateTime::from_naive_utc_and_offset(
3396 naive,
3397 chrono::Utc,
3398 )),
3399 ScheduleTz::Local => chrono::Local
3400 .from_local_datetime(&naive)
3401 .earliest()
3402 .map(|dt| dt.with_timezone(&chrono::Utc)),
3403 }
3404 }
3405
3406 /// The wall-clock time-of-day `now` reads as in this tz — used by
3407 /// [`Constraints::allows`] to test a maintenance window
3408 /// (#418 Phase 3). `Utc` is the naive UTC time; `Local` is the
3409 /// running host's local time.
3410 fn wall_time(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveTime {
3411 match self {
3412 ScheduleTz::Utc => now.time(),
3413 ScheduleTz::Local => now.with_timezone(&chrono::Local).time(),
3414 }
3415 }
3416
3417 /// The wall-clock *date* `now` reads as in this tz — used by
3418 /// [`Constraints::allows`] to test `skip_dates` (#418 holiday
3419 /// exclusion). Same tz semantics as [`Self::wall_time`].
3420 fn wall_date(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveDate {
3421 match self {
3422 ScheduleTz::Utc => now.date_naive(),
3423 ScheduleTz::Local => now.with_timezone(&chrono::Local).date_naive(),
3424 }
3425 }
3426
3427 /// Stable lowercase wire/display label (`local` / `utc`) — matches
3428 /// the serde `snake_case` representation. Used for the preview
3429 /// response's `tz` field so the JSON shape isn't coupled to the
3430 /// `Debug` repr (claude #578 review).
3431 pub fn as_str(self) -> &'static str {
3432 match self {
3433 ScheduleTz::Local => "local",
3434 ScheduleTz::Utc => "utc",
3435 }
3436 }
3437}
3438
3439impl std::fmt::Display for ScheduleTz {
3440 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3441 f.write_str(self.as_str())
3442 }
3443}
3444
3445/// `once` vs `{ every: <humantime> }` — shared by `per_pc` /
3446/// `per_target`. Untagged so the YAML stays the bare keyword or a
3447/// one-key map, nothing more ceremonial.
3448#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
3449#[serde(untagged)]
3450pub enum PerPolicy {
3451 /// The bare string `once`: succeed once, then skip permanently
3452 /// (cooldown = infinity).
3453 Once(OnceLiteral),
3454 /// Re-arm after the humantime interval, e.g. `{ every: 6h }`.
3455 Every(EverySpec),
3456}
3457
3458/// Single-variant enum so serde accepts exactly the string `once`
3459/// (a free-form `String` would swallow typos like `onec`).
3460#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
3461#[serde(rename_all = "snake_case")]
3462pub enum OnceLiteral {
3463 Once,
3464}
3465
3466/// `{ every: <humantime> }`. Standalone struct (not an inline
3467/// struct variant). `{ evry: 6h }` still fails to parse (the
3468/// required `every` key is missing), and the create boundaries
3469/// reject the unknown `evry` via [`crate::strict`] with its path —
3470/// while agents reading a future writer's extra fields tolerate
3471/// them (#492).
3472#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
3473pub struct EverySpec {
3474 /// Humantime interval (`10m`, `6h`, `1d`...). Parsed lazily —
3475 /// [`Schedule::validate`] rejects garbage at create time.
3476 pub every: String,
3477}
3478
3479impl PerPolicy {
3480 /// The cooldown this policy lowers to: `once` = `None`
3481 /// (permanent skip), `every` = the interval.
3482 fn cooldown(&self) -> Option<String> {
3483 match self {
3484 PerPolicy::Once(_) => None,
3485 PerPolicy::Every(EverySpec { every }) => Some(every.clone()),
3486 }
3487 }
3488}
3489
3490impl std::fmt::Display for When {
3491 /// Operator-facing one-liner (`per_pc once` / `per_pc every 6h`
3492 /// / `at 09:00 [mon-fri]` / `at 2026-06-10 09:00`) for log
3493 /// lines, audit payloads and the API's `ScheduleSummary`.
3494 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3495 let policy = |p: &PerPolicy| match p {
3496 PerPolicy::Once(_) => "once".to_string(),
3497 PerPolicy::Every(EverySpec { every }) => format!("every {every}"),
3498 };
3499 match self {
3500 When::PerPc(p) => write!(f, "per_pc {}", policy(p)),
3501 When::PerTarget(p) => write!(f, "per_target {}", policy(p)),
3502 When::Calendar(c) if c.days.is_empty() => write!(f, "at {}", c.at),
3503 When::Calendar(c) => write!(f, "at {} [{}]", c.at, c.days.join(",")),
3504 When::On(triggers) => {
3505 let names: Vec<&str> = triggers.iter().map(|t| t.as_str()).collect();
3506 write!(f, "on [{}]", names.join(","))
3507 }
3508 }
3509 }
3510}
3511
3512impl OnTrigger {
3513 /// Lowercase wire/display label (matches the serde `snake_case`).
3514 pub fn as_str(self) -> &'static str {
3515 match self {
3516 OnTrigger::Startup => "startup",
3517 OnTrigger::Logon => "logon",
3518 }
3519 }
3520}
3521
3522/// Optional validity window for a [`Schedule`] (#418 decision G).
3523/// Half-open `[from, until)`; either bound may be omitted. Bounds
3524/// are `YYYY-MM-DD` (= that day's 00:00 in the schedule's `tz`) or
3525/// full RFC3339 (offset is honored as-is, `tz` ignored). Kept as
3526/// strings so the JSON Schema the SPA editor consumes stays two
3527/// plain string fields, mirroring `jitter` / `starting_deadline`.
3528///
3529/// #418 Phase 2: bounds are evaluated in the schedule's top-level
3530/// `tz` (was UTC-only in Phase 1) so `tz: local` makes both the
3531/// calendar `at` AND the `active` window local — one consistent
3532/// timezone per schedule.
3533#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
3534pub struct Active {
3535 /// Dormant before this instant.
3536 #[serde(default, skip_serializing_if = "Option::is_none")]
3537 pub from: Option<String>,
3538 /// Dormant from this instant on (exclusive).
3539 #[serde(default, skip_serializing_if = "Option::is_none")]
3540 pub until: Option<String>,
3541}
3542
3543impl Active {
3544 /// `skip_serializing_if` helper — an empty window means "always
3545 /// active" and is omitted from the wire format entirely.
3546 pub fn is_empty(&self) -> bool {
3547 self.from.is_none() && self.until.is_none()
3548 }
3549
3550 /// Parse one bound: RFC3339 first (offset honored, `tz`
3551 /// ignored), then bare `YYYY-MM-DD` (00:00 in `tz`).
3552 pub fn parse_bound(s: &str, tz: ScheduleTz) -> Result<chrono::DateTime<chrono::Utc>, String> {
3553 if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
3554 return Ok(dt.with_timezone(&chrono::Utc));
3555 }
3556 if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
3557 let midnight = d.and_hms_opt(0, 0, 0).expect("00:00:00 is always valid");
3558 return tz.naive_to_utc(midnight).ok_or_else(|| {
3559 format!("active: bound '{s}' falls in a DST gap for the schedule's tz")
3560 });
3561 }
3562 Err(format!(
3563 "active: unparseable bound '{s}' (want YYYY-MM-DD or RFC3339)"
3564 ))
3565 }
3566
3567 /// Is `now` inside the window? Unparseable bounds are treated
3568 /// as absent here (fail-open) — [`Schedule::validate`] is the
3569 /// place that rejects them loudly; this runs on every tick and
3570 /// must never panic on a stale KV blob.
3571 pub fn contains(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
3572 let bound = |s: &Option<String>| s.as_deref().and_then(|s| Self::parse_bound(s, tz).ok());
3573 if bound(&self.from).is_some_and(|from| now < from) {
3574 return false;
3575 }
3576 if bound(&self.until).is_some_and(|until| now >= until) {
3577 return false;
3578 }
3579 true
3580 }
3581}
3582
3583/// Operational constraints on a [`Schedule`] (#418 Phase 3). Where
3584/// [`Active`] decides *over what date range* a schedule is live,
3585/// `Constraints` decides *when, within an active period,* a fire is
3586/// allowed. `window` (a maintenance time-of-day window) and
3587/// `max_concurrent` (a fleet-wide running-instance cap) so far;
3588/// `require` (env gates) joins this struct in a later phase.
3589#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
3590pub struct Constraints {
3591 /// `"HH:MM-HH:MM"` wall-clock window (evaluated in the schedule's
3592 /// `tz`). Fires outside it are skipped — mainly for reconcile
3593 /// cadences ("patrol every 6h, but only fire overnight") and
3594 /// daytime change-freezes. `start > end` crosses midnight
3595 /// (`"22:00-05:00"` = 22:00 through 05:00 next morning). Parsed
3596 /// lazily; [`Schedule::validate`] rejects garbage at create time.
3597 #[serde(default, skip_serializing_if = "Option::is_none")]
3598 pub window: Option<String>,
3599 /// Fleet-wide cap on how many instances of this schedule's job may
3600 /// run **at the same time** (#418 "同時実行ハード上限"). The
3601 /// backend scheduler counts the job's still-in-flight runs
3602 /// (`execution_results.finished_at IS NULL`) each tick and only
3603 /// dispatches to as many remaining pcs as there are free slots —
3604 /// a rolling window that refills as runs complete. Useful for
3605 /// disk/CPU/network-heavy jobs you don't want hammering the whole
3606 /// fleet at once.
3607 ///
3608 /// **Backend-only** (it needs a central counter): combining it
3609 /// with `runs_on: agent` is rejected by [`Schedule::validate`]
3610 /// (#418 decision E — "中央上限には中央が要る"). Most meaningful
3611 /// for `per_pc` reconcile cadences, where the poll re-ticks and
3612 /// refills slots. `None` (default) = no cap.
3613 #[serde(default, skip_serializing_if = "Option::is_none")]
3614 pub max_concurrent: Option<u32>,
3615 /// Calendar dates the schedule must **not** fire on — holidays,
3616 /// blackout days, one-off freeze dates (#418 "祝日除外"). Each is
3617 /// `YYYY-MM-DD`, evaluated as a wall-clock date in the schedule's
3618 /// `tz`. Applies to every `when` shape (a reconcile cadence skips
3619 /// the whole day; a calendar fire landing on the date is
3620 /// suppressed) and is honored by both the live scheduler and
3621 /// `preview`, since both gate on [`Constraints::allows`]. Empty
3622 /// (default) = no skips. Operator-supplied: there is no built-in
3623 /// holiday calendar — list the dates you care about. Parsed lazily;
3624 /// [`Schedule::validate`] rejects a malformed date at create time.
3625 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3626 pub skip_dates: Vec<String>,
3627}
3628
3629impl Constraints {
3630 /// `skip_serializing_if` helper — empty constraints are omitted
3631 /// from the wire format entirely.
3632 pub fn is_empty(&self) -> bool {
3633 self.window.is_none() && self.max_concurrent.is_none() && self.skip_dates.is_empty()
3634 }
3635
3636 /// The first unparseable `skip_dates` entry, if any — the
3637 /// scheduler logs it at register time so a fail-closed
3638 /// (never-firing) schedule from a hand-edited KV blob is
3639 /// diagnosable, mirroring [`Schedule::bad_window`].
3640 pub fn bad_skip_date(&self) -> Option<String> {
3641 self.skip_dates.iter().find_map(|s| {
3642 chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d")
3643 .err()
3644 .map(|e| format!("constraints.skip_dates: invalid date '{s}': {e}"))
3645 })
3646 }
3647
3648 /// Parse `"HH:MM-HH:MM"` into `(start, end)`. Equal bounds are an
3649 /// error (a zero-width or all-day window is ambiguous — write no
3650 /// window for "always").
3651 pub fn parse_window(s: &str) -> Result<(chrono::NaiveTime, chrono::NaiveTime), String> {
3652 let (a, b) = s
3653 .split_once('-')
3654 .ok_or_else(|| format!("constraints.window: '{s}' must be 'HH:MM-HH:MM'"))?;
3655 let parse = |part: &str| {
3656 chrono::NaiveTime::parse_from_str(part.trim(), "%H:%M")
3657 .map_err(|e| format!("constraints.window: invalid time '{}': {e}", part.trim()))
3658 };
3659 let (start, end) = (parse(a)?, parse(b)?);
3660 if start == end {
3661 return Err(format!(
3662 "constraints.window: start and end are equal ('{s}'); omit window for 'always'"
3663 ));
3664 }
3665 Ok((start, end))
3666 }
3667
3668 /// Is a fire allowed at `now` (evaluated in `tz`)? No window =
3669 /// always allowed. Half-open `[start, end)`; `start > end`
3670 /// crosses midnight.
3671 ///
3672 /// **Fail-closed** on an unparseable window (returns `false`,
3673 /// gemini #452 review): a window is a *restrictive* constraint
3674 /// (change-freeze / overnight-only), so a corrupt one must NOT
3675 /// silently allow fires during the restricted hours. Bad windows
3676 /// are rejected at create time by [`Schedule::validate`]; this
3677 /// only bites a hand-edited KV blob, where blocking is the safe
3678 /// direction. The scheduler warns at register time
3679 /// ([`Schedule::bad_window`]) so a stuck schedule is diagnosable.
3680 /// The tick path never panics regardless.
3681 pub fn allows(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
3682 // #418 holiday / blackout dates: never fire on a listed wall
3683 // date (in `tz`). Checked before the window since a skipped day
3684 // overrides any within-window allowance. Fail-closed on a
3685 // corrupt entry (same posture as `window`): a skip date is a
3686 // *restrictive* constraint, so a garbled one must not silently
3687 // re-enable fires — it blocks until fixed (`validate` rejects it
3688 // at create time; `bad_skip_date` lets the scheduler warn).
3689 if !self.skip_dates.is_empty() {
3690 let today = tz.wall_date(now);
3691 let blocked = self.skip_dates.iter().any(|s| {
3692 match chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d") {
3693 Ok(d) => d == today,
3694 Err(_) => true, // corrupt entry → fail-closed (block)
3695 }
3696 });
3697 if blocked {
3698 return false;
3699 }
3700 }
3701 match self.window.as_deref() {
3702 // No window → always allowed.
3703 None => true,
3704 // Window set: membership, or fail-closed if unparseable
3705 // (`window_contains` returns None for a corrupt window).
3706 Some(_) => self.window_contains(tz.wall_time(now)).unwrap_or(false),
3707 }
3708 }
3709
3710 /// Membership of a wall-clock time-of-day in the window. `None`
3711 /// when there is no window or it's unparseable (callers decide
3712 /// the failure direction). `start > end` crosses midnight.
3713 fn window_contains(&self, t: chrono::NaiveTime) -> Option<bool> {
3714 let (start, end) = Self::parse_window(self.window.as_deref()?).ok()?;
3715 Some(if start <= end {
3716 start <= t && t < end
3717 } else {
3718 t >= start || t < end
3719 })
3720 }
3721}
3722
3723/// What to do when a fire's script fails (#418 Phase 4 — the "高"
3724/// retry/backoff gap). Where [`Constraints`] gates *whether* a fire
3725/// happens, `OnFailure` decides what happens *after* one ran and
3726/// came back bad. Only `retry` so far; future `notify` / `disable`
3727/// would join the same namespace.
3728#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
3729pub struct OnFailure {
3730 /// Re-run the script in-process when it exits non-zero (or times
3731 /// out), up to a cap, with a fixed backoff between attempts.
3732 /// `None` (default) = no retry: a failed run is published as-is
3733 /// and (for reconcile cadences) simply re-fires on the next poll
3734 /// tick. See [`Retry`].
3735 #[serde(default, skip_serializing_if = "Option::is_none")]
3736 pub retry: Option<Retry>,
3737}
3738
3739impl OnFailure {
3740 /// `skip_serializing_if` helper — an empty policy is omitted from
3741 /// the wire format entirely.
3742 pub fn is_empty(&self) -> bool {
3743 self.retry.is_none()
3744 }
3745
3746 /// Lower the operator-facing `retry` (humantime backoff) onto the
3747 /// engine vocabulary the agent's executor runs on (backoff in
3748 /// whole seconds). Single seam shared by the backend command
3749 /// builder and the agent's local scheduler so the two stamp the
3750 /// same [`crate::wire::RetrySpec`] onto every Command. Returns
3751 /// `None` when there is no retry policy or the backoff is
3752 /// unparseable (validate() rejects the latter at create time;
3753 /// this stays fail-safe = "no retry" for a hand-edited KV blob
3754 /// rather than panicking on the fire path).
3755 pub fn lowered_retry(&self) -> Option<crate::wire::RetrySpec> {
3756 let r = self.retry.as_ref()?;
3757 let backoff_secs = humantime::parse_duration(&r.backoff).ok()?.as_secs();
3758 Some(crate::wire::RetrySpec {
3759 max: r.max,
3760 backoff_secs,
3761 })
3762 }
3763}
3764
3765/// Fixed-backoff retry policy (#418 Phase 4). `max` is the number of
3766/// *additional* attempts after the first run (so `max: 3` = up to 4
3767/// total executions); `backoff` is the humantime delay slept between
3768/// attempts. The retry happens fire-side (inside `kanade fire` /
3769/// `handle_command`) on every OS for the PoC — the Windows-native
3770/// "restart on failure" Task Scheduler path is deferred to the
3771/// native-delegation phase (#418 decision H).
3772#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
3773pub struct Retry {
3774 /// Max additional attempts after the first failure. Bounded
3775 /// `1..=10` by [`Schedule::validate`] — a typo'd `max: 1000`
3776 /// with a short backoff would otherwise pin a flapping script in
3777 /// a tight loop for the whole window.
3778 pub max: u32,
3779 /// Humantime delay slept between attempts (`"10m"`, `"30s"`).
3780 pub backoff: String,
3781}
3782
3783/// Fleet-wide change-freeze (#418 Phase 5 — the "メンテナンス窓 /
3784/// 変更凍結" gap's global half). Where [`Constraints::window`] is a
3785/// *per-schedule* time-of-day gate, a `Freeze` is a *single, fleet-
3786/// global* "stop all automated change" switch the operator flips
3787/// during an incident or a year-end change-freeze. It lives in its
3788/// own KV singleton ([`crate::kv::KEY_FREEZE`]); when present and
3789/// active, both the backend scheduler and every agent's local
3790/// scheduler skip *every* fire.
3791///
3792/// Shapes:
3793/// * `{}` (no bounds) — frozen indefinitely until the operator
3794/// clears it (incident "big red button").
3795/// * `{ from, until }` — frozen only within `[from, until)`,
3796/// evaluated in `tz` (planned change-freeze; auto-thaws).
3797///
3798/// The KV key being *absent* means "not frozen" — so clearing the
3799/// freeze is a KV delete, and `is_active` only ever runs on a freeze
3800/// the operator actually set.
3801#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
3802pub struct Freeze {
3803 /// Frozen from this instant (RFC3339 or bare `YYYY-MM-DD` in
3804 /// `tz`). `None` ⇒ frozen from the beginning of time.
3805 #[serde(default, skip_serializing_if = "Option::is_none")]
3806 pub from: Option<String>,
3807 /// Thawed from this instant on, exclusive. `None` ⇒ frozen with
3808 /// no scheduled end (manual clear required).
3809 #[serde(default, skip_serializing_if = "Option::is_none")]
3810 pub until: Option<String>,
3811 /// Operator-supplied note surfaced on the freeze-skip log and the
3812 /// SPA banner ("year-end change freeze", "INC-1234"). Advisory.
3813 #[serde(default, skip_serializing_if = "Option::is_none")]
3814 pub reason: Option<String>,
3815 /// Timezone the bare-date bounds are evaluated in (RFC3339 bounds
3816 /// carry their own offset). Defaults to host-local like a
3817 /// schedule's `tz`.
3818 #[serde(default)]
3819 pub tz: ScheduleTz,
3820}
3821
3822impl Freeze {
3823 /// Is the fleet frozen at `now`? An empty window (`from`/`until`
3824 /// both absent) is frozen unconditionally; otherwise membership of
3825 /// `[from, until)` in `tz`. Half-open like [`Active::contains`],
3826 /// but **fails CLOSED** on an unparseable bound — a freeze is a
3827 /// safety switch, so a corrupt window (only reachable via a
3828 /// hand-edited KV blob; `validate` rejects it at set time) must
3829 /// mean "frozen", not "fire normally" (coderabbit #472). This is
3830 /// the one deliberate divergence from `active`'s fail-OPEN
3831 /// behaviour, where an unparseable bound dormant-skips a schedule.
3832 pub fn is_active(&self, now: chrono::DateTime<chrono::Utc>) -> bool {
3833 // Parse a bound; an unparseable one short-circuits the whole
3834 // check to `true` (frozen) via the closure's `None` sentinel
3835 // handled below.
3836 let bound = |s: &Option<String>| -> Result<Option<chrono::DateTime<chrono::Utc>>, ()> {
3837 match s.as_deref() {
3838 None => Ok(None),
3839 Some(raw) => Active::parse_bound(raw, self.tz).map(Some).map_err(|_| ()),
3840 }
3841 };
3842 let (from, until) = match (bound(&self.from), bound(&self.until)) {
3843 (Ok(f), Ok(u)) => (f, u),
3844 // Any corrupt bound → fail closed (frozen).
3845 _ => return true,
3846 };
3847 if from.is_some_and(|f| now < f) {
3848 return false;
3849 }
3850 if until.is_some_and(|u| now >= u) {
3851 return false;
3852 }
3853 true
3854 }
3855
3856 /// Reject unparseable bounds / `from >= until` at set time (the
3857 /// API + CLI counterpart to [`Schedule::validate`]).
3858 pub fn validate(&self) -> Result<(), String> {
3859 let from = self
3860 .from
3861 .as_deref()
3862 .map(|s| Active::parse_bound(s, self.tz))
3863 .transpose()
3864 .map_err(|e| e.replace("active:", "freeze:"))?;
3865 let until = self
3866 .until
3867 .as_deref()
3868 .map(|s| Active::parse_bound(s, self.tz))
3869 .transpose()
3870 .map_err(|e| e.replace("active:", "freeze:"))?;
3871 if let (Some(f), Some(u)) = (from, until) {
3872 if f >= u {
3873 return Err(format!(
3874 "freeze.from ({}) must be strictly before freeze.until ({})",
3875 self.from.as_deref().unwrap_or_default(),
3876 self.until.as_deref().unwrap_or_default(),
3877 ));
3878 }
3879 }
3880 Ok(())
3881 }
3882}
3883
3884/// The system-generated poll cadence every reconcile-shaped `when`
3885/// lowers to. Operators never write this: the real inter-run
3886/// spacing is the `every` cooldown; this only bounds "how soon do
3887/// we notice somebody is due" (#418 decision B took the poll
3888/// period away from the operator).
3889pub const POLL_CRON: &str = "0 * * * * *";
3890
3891/// What a [`When`] lowers to — the exact (cron, mode, cooldown)
3892/// trio the pre-#418 engine ran on. Keeping the engine vocabulary
3893/// unchanged is what lets Phase 1 swap the operator surface without
3894/// touching the tick / dedup machinery.
3895pub struct Lowered {
3896 /// Cron handed to `tokio-cron-scheduler` — [`POLL_CRON`] for
3897 /// reconcile shapes, a 6/7-field cron for calendar shapes.
3898 pub cron: String,
3899 /// Dedup semantics for `decide_fire`.
3900 pub mode: ExecMode,
3901 /// Humantime re-arm interval (`None` = succeed once, skip
3902 /// forever).
3903 pub cooldown: Option<String>,
3904 /// Timezone to evaluate `cron` in (#418 Phase 2). The scheduler
3905 /// passes this to `Job::new_async_tz`. Reconcile shapes carry
3906 /// the schedule's tz too even though POLL_CRON is tz-agnostic,
3907 /// so the same value drives the `active`-window check.
3908 pub tz: ScheduleTz,
3909}
3910
3911impl Schedule {
3912 /// The error message if this schedule's `constraints.window` is
3913 /// set but unparseable, else `None`. The scheduler logs this at
3914 /// register time so a fail-closed (never-firing) schedule from a
3915 /// hand-edited KV blob is diagnosable (gemini #452 review).
3916 pub fn bad_window(&self) -> Option<String> {
3917 let w = self.constraints.window.as_deref()?;
3918 Constraints::parse_window(w).err()
3919 }
3920
3921 /// True when this is a `calendar` schedule whose fire time can
3922 /// never fall inside its `constraints.window` — the cron fires,
3923 /// the window check rejects it, and (firing only at that
3924 /// time-of-day) it effectively never runs. An easy misconfig to
3925 /// set up by accident; the scheduler warns at register time
3926 /// (claude #452 review). Reconcile shapes poll every minute, so
3927 /// they always catch the window opening and aren't affected.
3928 pub fn calendar_outside_window(&self) -> bool {
3929 let When::Calendar(c) = &self.when else {
3930 return false;
3931 };
3932 let Some(t) = c.fire_time() else {
3933 return false;
3934 };
3935 matches!(self.constraints.window_contains(t), Some(false))
3936 }
3937
3938 /// Up to `count` future instants this schedule will fire, as
3939 /// absolute UTC, strictly after `now` — the dry-run / preview
3940 /// surface (#418 "ドライラン / プレビュー"). Only **calendar**
3941 /// schedules have discrete fire times; reconcile shapes
3942 /// (`per_pc`/`per_target`) poll every minute gated by cooldown, so
3943 /// they return an empty vec and the caller describes the cadence
3944 /// instead. Occurrences outside the `active.{from,until}` window or
3945 /// the `constraints.window` are **skipped**, so the list reflects
3946 /// when the schedule will ACTUALLY run, not the raw cron ticks.
3947 /// Evaluated in the schedule's `tz`, exactly like the scheduler's
3948 /// `Job::new_async_tz`, and with the same croner config the
3949 /// scheduler / [`Schedule::validate`] use, so a preview can never
3950 /// disagree with a real fire. A schedule that can never fire (a
3951 /// calendar time wholly outside its window, a past one-shot,
3952 /// `enabled: false` is *not* considered here — callers gate on
3953 /// `enabled` separately) yields an empty vec.
3954 pub fn preview_fires(
3955 &self,
3956 now: chrono::DateTime<chrono::Utc>,
3957 count: usize,
3958 ) -> Vec<chrono::DateTime<chrono::Utc>> {
3959 use croner::parser::{CronParser, Seconds};
3960 if !matches!(self.when, When::Calendar(_)) {
3961 return Vec::new();
3962 }
3963 // Same lowering + croner config as `next_calendar_fire` and the
3964 // live scheduler, so a preview can never disagree with a real
3965 // fire. `preview_fires` adds the N-occurrence walk and the
3966 // active / window filtering on top of that single seam.
3967 let lowered = self.lowered();
3968 let Ok(cron) = CronParser::builder()
3969 .seconds(Seconds::Required)
3970 .dom_and_dow(true)
3971 .build()
3972 .parse(&lowered.cron)
3973 else {
3974 return Vec::new();
3975 };
3976 let accept = |utc: chrono::DateTime<chrono::Utc>| {
3977 self.active.contains(utc, self.tz) && self.constraints.allows(utc, self.tz)
3978 };
3979 match self.tz {
3980 ScheduleTz::Utc => Self::next_occurrences(&cron, now, count, accept),
3981 ScheduleTz::Local => {
3982 Self::next_occurrences(&cron, now.with_timezone(&chrono::Local), count, accept)
3983 }
3984 }
3985 }
3986
3987 /// Walk croner forward from `after` collecting up to `count`
3988 /// accepted occurrences (converted to UTC). Generic over the tz the
3989 /// cron is evaluated in so `preview_fires` can run it in either
3990 /// `Utc` or `Local` without duplicating the loop.
3991 fn next_occurrences<Tz>(
3992 cron: &croner::Cron,
3993 after: chrono::DateTime<Tz>,
3994 count: usize,
3995 accept: impl Fn(chrono::DateTime<chrono::Utc>) -> bool,
3996 ) -> Vec<chrono::DateTime<chrono::Utc>>
3997 where
3998 Tz: chrono::TimeZone,
3999 {
4000 // Bound the scan so an `active`/window dead-end (every future
4001 // tick rejected) can't spin forever: ~4096 raw ticks covers
4002 // >10y of a daily calendar while staying instant for croner.
4003 const SCAN_CAP: usize = 4096;
4004 let mut out = Vec::with_capacity(count.min(SCAN_CAP));
4005 let mut cursor = after;
4006 let mut scanned = 0usize;
4007 while out.len() < count && scanned < SCAN_CAP {
4008 scanned += 1;
4009 let Ok(next) = cron.find_next_occurrence(&cursor, false) else {
4010 break;
4011 };
4012 let utc = next.with_timezone(&chrono::Utc);
4013 if accept(utc) {
4014 out.push(utc);
4015 }
4016 // `find_next_occurrence(.., inclusive = false)` already
4017 // advances strictly past `cursor`, so handing it `next`
4018 // verbatim gets the following occurrence — no manual +1s
4019 // nudge (and `DateTime<Tz>` is `Copy`, so no clone).
4020 cursor = next;
4021 }
4022 out
4023 }
4024
4025 /// Lower the operator-facing `when` onto the engine vocabulary.
4026 /// Single seam shared by the backend scheduler and the agent's
4027 /// local scheduler so the two can never drift.
4028 pub fn lowered(&self) -> Lowered {
4029 let tz = self.tz;
4030 match &self.when {
4031 When::PerPc(p) => Lowered {
4032 cron: POLL_CRON.into(),
4033 mode: ExecMode::OncePerPc,
4034 cooldown: p.cooldown(),
4035 tz,
4036 },
4037 When::PerTarget(p) => Lowered {
4038 cron: POLL_CRON.into(),
4039 mode: ExecMode::OncePerTarget,
4040 cooldown: p.cooldown(),
4041 tz,
4042 },
4043 // `to_cron` only fails on a malformed `at` (rejected by
4044 // validate() at create time). For a hand-edited KV blob
4045 // that slipped past, emit a deliberately-invalid cron so
4046 // register()'s Job::new_async_tz fails → warn+skip,
4047 // rather than firing at the wrong time.
4048 When::Calendar(c) => Lowered {
4049 cron: c
4050 .to_cron()
4051 .unwrap_or_else(|_| "# invalid calendar at".into()),
4052 mode: ExecMode::EveryTick,
4053 cooldown: None,
4054 tz,
4055 },
4056 // Event triggers have no cron — the agent fires them from an
4057 // OS event source. The `# event-trigger` cron is never
4058 // registered (the scheduler branches on `is_event()` first),
4059 // but keep it deliberately-invalid as a belt-and-suspenders
4060 // so a stray registration would fail rather than misfire.
4061 When::On(_) => Lowered {
4062 cron: "# event-trigger (no cron)".into(),
4063 mode: ExecMode::Event,
4064 cooldown: None,
4065 tz,
4066 },
4067 }
4068 }
4069
4070 /// True when this schedule fires from an OS event (`when: { on }`)
4071 /// rather than a clock — the agent skips `tokio-cron` registration
4072 /// for these and drives them from boot / session-change instead.
4073 pub fn is_event(&self) -> bool {
4074 matches!(self.when, When::On(_))
4075 }
4076
4077 /// The OS event triggers this schedule listens for, or `&[]` when it
4078 /// is not an event schedule.
4079 pub fn event_triggers(&self) -> &[OnTrigger] {
4080 match &self.when {
4081 When::On(t) => t,
4082 _ => &[],
4083 }
4084 }
4085
4086 /// The next absolute (UTC) time this schedule fires, or `None` when
4087 /// it has no discrete upcoming fire to preview.
4088 ///
4089 /// Used by the KLP `maintenance.list` preview ("what's about to
4090 /// happen on my PC", SPEC §2.1). Returns `None` for:
4091 ///
4092 /// - reconcile shapes (`per_pc` / `per_target`) — they lower to the
4093 /// every-minute [`POLL_CRON`] and re-converge state continuously,
4094 /// so "next fire" is always ~60s away and means nothing to a user
4095 /// previewing upcoming maintenance;
4096 /// - a calendar schedule whose lowered cron won't parse (a
4097 /// hand-edited KV blob that slipped past [`Schedule::validate`]);
4098 /// - a cron with no future occurrence.
4099 ///
4100 /// The wall-clock fire is evaluated in the schedule's own `tz`
4101 /// (matching the live tick's `Job::new_async_tz`) then normalised
4102 /// to UTC for the wire. `inclusive = false`: strictly the *next*
4103 /// fire after `now`, never one matching the current instant.
4104 pub fn next_calendar_fire(
4105 &self,
4106 now: chrono::DateTime<chrono::Utc>,
4107 ) -> Option<chrono::DateTime<chrono::Utc>> {
4108 if !matches!(self.when, When::Calendar(_)) {
4109 return None;
4110 }
4111 let lowered = self.lowered();
4112 // Same parser configuration tokio-cron-scheduler 0.15 uses
4113 // internally, so this can never compute a fire the live
4114 // scheduler wouldn't (seconds required, DOM-and-DOW honored).
4115 let cron = croner::parser::CronParser::builder()
4116 .seconds(croner::parser::Seconds::Required)
4117 .dom_and_dow(true)
4118 .build()
4119 .parse(&lowered.cron)
4120 .ok()?;
4121 match lowered.tz {
4122 ScheduleTz::Utc => cron.find_next_occurrence(&now, false).ok(),
4123 ScheduleTz::Local => {
4124 let now_local = now.with_timezone(&chrono::Local);
4125 cron.find_next_occurrence(&now_local, false)
4126 .ok()
4127 .map(|t| t.with_timezone(&chrono::Utc))
4128 }
4129 }
4130 }
4131
4132 /// Cross-field semantic checks that don't fit pure serde derive
4133 /// — the [`Manifest::validate`] counterpart (#418 decision F;
4134 /// pre-Phase-1 a broken schedule was accepted at create time
4135 /// and silently warn-skipped at tick time). Run at every create
4136 /// site: `kanade schedule create` (client-side) and
4137 /// `POST /api/schedules`. The job_id-exists check lives in the
4138 /// API handler instead — it needs the JOBS KV.
4139 pub fn validate(&self) -> Result<(), String> {
4140 if matches!(self.runs_on, RunsOn::Agent) && matches!(self.when, When::PerTarget(_)) {
4141 return Err(
4142 "when.per_target needs fleet-wide completion data and is backend-only; \
4143 it cannot be combined with runs_on: agent (each agent self-schedules, \
4144 so per-target dedup would be deduping across a target of 1)"
4145 .into(),
4146 );
4147 }
4148 // #418 event triggers: the agent owns the OS event source
4149 // (boot / session-change), so `when: { on }` is agent-only and
4150 // needs at least one trigger.
4151 if let When::On(triggers) = &self.when {
4152 if !matches!(self.runs_on, RunsOn::Agent) {
4153 return Err(
4154 "when.on (OS event trigger) is fired by the agent's own event \
4155 source, so it requires runs_on: agent"
4156 .into(),
4157 );
4158 }
4159 if triggers.is_empty() {
4160 return Err(
4161 "when.on must list at least one trigger (e.g. [startup, logon])".into(),
4162 );
4163 }
4164 }
4165 if let Some(cd) = self.lowered().cooldown.as_deref() {
4166 humantime::parse_duration(cd)
4167 .map_err(|e| format!("when.every: invalid duration '{cd}': {e}"))?;
4168 }
4169 if let When::Calendar(c) = &self.when {
4170 // Lower the calendar form to its cron (catches a bad `at`
4171 // and the date+days conflict), then validate that cron
4172 // with the same parser configuration tokio-cron-scheduler
4173 // 0.15 uses internally (croner, seconds required,
4174 // DOM-and-DOW both honored, year optional) — create-time
4175 // validation can never accept what register() rejects.
4176 let cron = c.to_cron()?;
4177 croner::parser::CronParser::builder()
4178 .seconds(croner::parser::Seconds::Required)
4179 .dom_and_dow(true)
4180 .build()
4181 .parse(&cron)
4182 .map_err(|e| format!("when.at lowered to invalid cron '{cron}': {e}"))?;
4183 }
4184 // The other humantime strings on the schedule (claude #419
4185 // review): runtime degrades gracefully on both (bad jitter →
4186 // silent no-op, bad starting_deadline → warn + skipped tick),
4187 // but "rejected at create time" should cover every field the
4188 // operator can typo, not just `when`.
4189 if let Some(j) = &self.plan.jitter {
4190 humantime::parse_duration(j)
4191 .map_err(|e| format!("jitter: invalid duration '{j}': {e}"))?;
4192 }
4193 if let Some(sd) = &self.starting_deadline {
4194 humantime::parse_duration(sd)
4195 .map_err(|e| format!("starting_deadline: invalid duration '{sd}': {e}"))?;
4196 }
4197 let from = self
4198 .active
4199 .from
4200 .as_deref()
4201 .map(|s| Active::parse_bound(s, self.tz))
4202 .transpose()?;
4203 let until = self
4204 .active
4205 .until
4206 .as_deref()
4207 .map(|s| Active::parse_bound(s, self.tz))
4208 .transpose()?;
4209 if let (Some(f), Some(u)) = (from, until) {
4210 if f >= u {
4211 return Err(format!(
4212 "active.from ({}) must be strictly before active.until ({})",
4213 self.active.from.as_deref().unwrap_or_default(),
4214 self.active.until.as_deref().unwrap_or_default(),
4215 ));
4216 }
4217 }
4218 // #418 Phase 3: a bad maintenance window is rejected at create
4219 // time (parse_window also catches equal bounds).
4220 if let Some(w) = self.constraints.window.as_deref() {
4221 Constraints::parse_window(w)?;
4222 }
4223 // #418 holiday exclusion: reject a malformed skip date at create
4224 // time so the fail-closed `allows` path only ever bites a
4225 // hand-edited KV blob, not a fresh `kanade schedule create`.
4226 if let Some(err) = self.constraints.bad_skip_date() {
4227 return Err(err);
4228 }
4229 // #418: constraints.max_concurrent is a central running-instance
4230 // cap, so it needs the backend's counter — reject it on
4231 // runs_on: agent (decision E), and reject a meaningless 0.
4232 if let Some(mc) = self.constraints.max_concurrent {
4233 // Check the structural incompatibility (agent has no central
4234 // counter) before the value range, so a `max_concurrent: 0`
4235 // + `runs_on: agent` combo reports the more fundamental
4236 // problem first (claude #542).
4237 if matches!(self.runs_on, RunsOn::Agent) {
4238 return Err(
4239 "constraints.max_concurrent needs a central counter and is backend-only; \
4240 it cannot be combined with runs_on: agent (each agent self-schedules, \
4241 so there is no fleet-wide count to cap against)"
4242 .into(),
4243 );
4244 }
4245 if mc == 0 {
4246 return Err(
4247 "constraints.max_concurrent must be >= 1 (0 would never fire; \
4248 omit it for no cap)"
4249 .into(),
4250 );
4251 }
4252 }
4253 // #418 Phase 4: a bad on_failure.retry is rejected at create
4254 // time — backoff must be valid humantime, and max is bounded
4255 // so a typo can't pin a flapping script in a tight loop.
4256 if let Some(r) = &self.on_failure.retry {
4257 let backoff = humantime::parse_duration(&r.backoff).map_err(|e| {
4258 format!(
4259 "on_failure.retry.backoff: invalid duration '{}': {e}",
4260 r.backoff
4261 )
4262 })?;
4263 // The wire form lowers backoff to whole seconds, so a
4264 // sub-second value would silently become a 0s no-wait
4265 // (coderabbit #466). Reject it rather than honour a backoff
4266 // the operator can't actually get.
4267 if backoff.as_secs() < 1 {
4268 return Err(format!(
4269 "on_failure.retry.backoff must be >= 1s (got '{}'); sub-second backoffs \
4270 round to 0 on the wire",
4271 r.backoff
4272 ));
4273 }
4274 if !(1..=10).contains(&r.max) {
4275 return Err(format!(
4276 "on_failure.retry.max must be 1..=10 (got {}); it counts additional \
4277 attempts after the first run",
4278 r.max
4279 ));
4280 }
4281 }
4282 Ok(())
4283 }
4284}
4285
4286fn default_true() -> bool {
4287 true
4288}