kanade_shared/manifest.rs
1use serde::{Deserialize, Serialize};
2
3use crate::wire::{FinalizeCommand, RunAs, Shell, Staleness};
4
5/// YAML job manifest (= registered "what to run", v0.18.0+).
6///
7/// Owns only script-intrinsic fields. **Who** (`target`), **how to
8/// phase fanout** (`rollout`), and **when to stagger start**
9/// (`jitter`) all moved to the Schedule / exec request side — same
10/// script can now be fired against different targets / rollouts
11/// without copying the script body.
12///
13/// #492: these types are READ fleet-wide (agents decode them from
14/// BUCKET_JOBS / BUCKET_SCHEDULES and inside live Commands), so they
15/// must tolerate unknown fields — `deny_unknown_fields` here made a
16/// gradually-upgrading fleet's OLD agents reject the whole object
17/// the moment a newer backend added any field. Operator typo
18/// protection (the old reason for the attribute) lives at the WRITE
19/// boundaries instead: `kanade job/schedule create` and the backend
20/// POST extractor parse via [`crate::strict`], which rejects unknown
21/// keys with their full paths. The wire rule: new fields always get
22/// `#[serde(default)]` (+ `skip_serializing_if` while old readers
23/// may still be strict).
24#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
25pub struct Manifest {
26 pub id: String,
27 pub version: String,
28 #[serde(default)]
29 pub description: Option<String>,
30 pub execute: Execute,
31 #[serde(default)]
32 pub require_approval: bool,
33 /// Opt-in marker that this job produces a JSON inventory fact
34 /// payload on stdout. When present, the backend's results
35 /// projector parses `ExecResult.stdout` as JSON and upserts an
36 /// `inventory_facts` row keyed by `(pc_id, manifest.id)`. The
37 /// `display` sub-config drives the SPA's Inventory page render.
38 #[serde(default)]
39 pub inventory: Option<InventoryHint>,
40 /// Issue #246: opt-in marker that this job emits per-line
41 /// observability events on stdout (one JSON `ObsEvent` per
42 /// newline). When present, the agent — after the script exits
43 /// successfully — parses each non-empty stdout line as an
44 /// `ObsEvent`, publishes it on `obs.<pc_id>` via the
45 /// `obs_outbox`, and (intentionally) **omits the stdout from
46 /// the `ExecResult`** so the timeline data doesn't double up
47 /// in `execution_results.stdout` (which would multiply rows
48 /// by ~50/day/PC of noise).
49 ///
50 /// Distinct from `inventory:` (single JSON object → projector
51 /// upsert) — events are append-only timeline points consumed
52 /// by the dedicated `obs_events` table.
53 #[serde(default)]
54 pub emit: Option<EmitConfig>,
55 /// #290: opt-in marker that this job is an operator-defined
56 /// **health check** whose result feeds the Client App's Health
57 /// tab over KLP (`StateSnapshot.checks`). The script prints a
58 /// free-form JSON object on stdout (like any inventory job); the
59 /// agent reads the [`CheckHint::status_field`] value dynamically
60 /// into a [`crate::ipc::state::Check`] named `check.name`.
61 /// Cadence / windows / conditions come from
62 /// the job's Schedule (exactly like inventory) — there is
63 /// deliberately no interval here. **Composes with `inventory:` and
64 /// `collect:`** (#821): each reads its own `#KANADE-<KIND>`-fenced
65 /// stdout block, so one job can drive a check, project inventory
66 /// facts, and collect files in a single run. Only `emit:` (NDJSON
67 /// stdout) is incompatible. A check-only job may skip the fence
68 /// (whole stdout is the JSON); a multi-hint job fences each block.
69 #[serde(default)]
70 pub check: Option<CheckHint>,
71 /// #219: opt-in marker that this job COLLECTS files into a bundle.
72 /// The script does the collection work and prints a single JSON
73 /// object on stdout carrying a `files` array of paths (the field
74 /// name is [`CollectHint::files_field`], default `"files"`); the
75 /// agent — after the script exits successfully — zips those files,
76 /// uploads the archive to the `OBJECT_COLLECTIONS` Object Store
77 /// bucket (key `<pc_id>/<job_id>/<timestamp>.zip`), and records the
78 /// key in [`crate::wire::ExecResult::collect_object`]. The operator
79 /// downloads bundles from the SPA Collect page.
80 ///
81 /// Like `inventory:` / `check:` this reads a JSON object from stdout.
82 /// #821: it reads its own `#KANADE-COLLECT-BEGIN/END`-fenced block,
83 /// so it **composes with `inventory:` / `check:`** (and a user
84 /// message) on one stdout — only `emit:` (NDJSON) is incompatible
85 /// (enforced in [`Manifest::validate`]). A collect-only job may skip
86 /// the fence. It also composes with `client:` — a `collect:` +
87 /// `client:` job lets an end user trigger a collection from the
88 /// Client App (the same-host agent runs it).
89 #[serde(default, skip_serializing_if = "Option::is_none")]
90 pub collect: Option<CollectHint>,
91 /// #720: opt-in declarative aggregation over `obs_events` that drives
92 /// the SPA **Analytics** page. Unlike the other hints this one never
93 /// touches stdout and is never delivered to the agent — it's a pure
94 /// *read spec* the backend reads from `BUCKET_JOBS` at query time and
95 /// turns into `json_extract` aggregation SQL. Each entry is one widget
96 /// (a `dashboard:` tab groups them); `scope:` selects per-PC vs
97 /// fleet-wide rollup. Because it consumes nothing at run time it
98 /// composes with every other hint (typically paired with `emit:`,
99 /// which produces the events it reads). See [`AggregateWidget`].
100 ///
101 /// New field ⇒ #492 wire rule (`default` + `skip_serializing_if`).
102 #[serde(default, skip_serializing_if = "Option::is_none")]
103 pub aggregate: Option<Vec<AggregateWidget>>,
104 /// v0.26: Layer 2 staleness policy (SPEC.md §2.6.2). Controls
105 /// what the agent does at fire time when it can't verify the
106 /// `script_current` / `script_status` KV values are fresh —
107 /// especially relevant for `runs_on: agent` schedules where
108 /// the agent may fire from cache while offline. Defaults to
109 /// `Staleness::Cached` (silently use cached values), which
110 /// matches every pre-v0.26 Manifest.
111 #[serde(default)]
112 pub staleness: Staleness,
113 /// #291: opt-in marker that this job is offered to **end users**
114 /// in the Client App's job tabs over KLP (`jobs.list` →
115 /// `jobs.execute`). Parallel to [`inventory`] / [`check`] /
116 /// [`emit`]: the block's mere presence is the opt-in, and it
117 /// groups the end-user presentation fields (name / category /
118 /// icon) that only make sense for a user-facing job. `None`
119 /// (the default) ⇒ an operator-only job — inventory, checks,
120 /// scheduled maintenance — that never surfaces in the catalog.
121 ///
122 /// The agent re-reads this at every `jobs.list` / `jobs.execute`
123 /// (SPEC §2.1), so removing the block takes a job out of a
124 /// running client on its next action.
125 ///
126 /// [`inventory`]: Manifest::inventory
127 /// [`check`]: Manifest::check
128 /// [`emit`]: Manifest::emit
129 #[serde(default, skip_serializing_if = "Option::is_none")]
130 pub client: Option<ClientHint>,
131 /// Free-form operator taxonomy for the Jobs catalog. Purely a
132 /// SPA-side organisational aid — agents / scheduler / projector
133 /// never read it — so it carries no runtime semantics and any
134 /// string is allowed (`security`, `weekly`, `windows`, …). Jobs
135 /// cross-cut (a `check-bitlocker` is at once a health-check, a
136 /// security control, and Windows-specific), which is why this is
137 /// a multi-valued list rather than the single closed-enum
138 /// [`ClientHint::category`] (whose values are the end-user Client
139 /// App's tabs, a different concern). The operator Jobs page groups
140 /// rows by id-prefix for free; tags add the orthogonal filter axis
141 /// prefixes can't express.
142 ///
143 /// Empty by default (the overwhelming majority of jobs), and a
144 /// new field, so it follows the #492 wire rule: `serde(default)`
145 /// plus `skip_serializing_if` keep gradually-upgrading old readers
146 /// from tripping over its absence / presence.
147 #[serde(default, skip_serializing_if = "Vec::is_empty")]
148 pub tags: Vec<String>,
149 /// GitOps provenance (#678) — see [`RepoOrigin`]. Stamped by
150 /// `kanade job create` when the source YAML lives inside a Git work
151 /// tree, so the SPA can render the job read-only and point edits
152 /// back at the repo instead of letting a ClickOps edit silently
153 /// diverge from Git (SPEC design principle #3: 設定駆動 YAML + Git).
154 /// `None` for SPA-born jobs and for manifests applied from outside
155 /// any Git repo. Purely informational: agents / scheduler /
156 /// projector never read it, and it survives `script_file:` inlining
157 /// (it's orthogonal to the exactly-one-of script-source rule). New
158 /// field ⇒ #492 wire rule (`default` + `skip_serializing_if`).
159 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub origin: Option<RepoOrigin>,
161 /// Job-generic post-step hook. When set, the agent runs this script
162 /// AFTER the main `execute:` script exits cleanly (and, for a
163 /// `collect:` job, after the bundle finishes uploading), so the
164 /// operator can delete / move / notify based on what the step
165 /// produced. Best-effort: a finalize failure is logged but never
166 /// fails the run — the upload (if any) already succeeded.
167 ///
168 /// For `collect:` jobs the agent injects the environment variable
169 /// `KANADE_COLLECT_RESULT` — a JSON object
170 /// `{ "ok": true, "bundles": [ { "key", "uploaded", "files": [...] } ] }`
171 /// — so the hook acts on exactly the files that were bundled and
172 /// uploaded (e.g. deletes only the `uploaded` ones). Composes with
173 /// every hint. New field ⇒ #492 wire rule (`default` +
174 /// `skip_serializing_if`).
175 #[serde(default, skip_serializing_if = "Option::is_none")]
176 pub finalize: Option<FinalizeSpec>,
177 /// #vuln-roadmap: declarative **external-data feeds**. Each entry fetches
178 /// global reference data (a vulnerability catalog, an EOL table, a license
179 /// roster) and projects it into the shared `feeds` table keyed
180 /// `(feed_id, item_id)` — fleet-wide, with no `pc_id`, unlike the per-PC
181 /// inventory [`ExplodeSpec`]. The job's script (run on the trusted
182 /// controller tier) fetches + shapes the data and prints the array under
183 /// each spec's [`field`](FeedSpec::field) inside a
184 /// `#KANADE-FEED-BEGIN/END` fence; the projector replaces that feed's rows
185 /// wholesale. A non-empty `feed:` **implies** `tier: controller` (the
186 /// dispatch guard treats it as such), so an external fetch never lands on
187 /// an employee endpoint. Composes with the other fenced hints. New field ⇒
188 /// #492 wire rule (`default` + `skip_serializing_if`). See [`FeedSpec`].
189 #[serde(default, skip_serializing_if = "Vec::is_empty")]
190 pub feed: Vec<FeedSpec>,
191 /// Execution tier (#vuln-roadmap). `None` / `endpoint` (default) ⇒ the
192 /// job dispatches to the targeted fleet agents like any job. `controller`
193 /// ⇒ it may run ONLY on trusted infra hosts — the backend constrains
194 /// dispatch to members of the operator-configured `controller_group`
195 /// (`server_settings` KV), and refuses to run anywhere if that group is
196 /// unset (fail-safe). This keeps `feed:` (external-fetch) and future
197 /// privileged hints off employee endpoints. The `feed:` hint implies
198 /// `controller`; it can also be set explicitly. New field ⇒ #492 wire
199 /// rule (`default` + `skip_serializing_if`).
200 #[serde(default, skip_serializing_if = "Option::is_none")]
201 pub tier: Option<Tier>,
202}
203
204/// Execution tier for a [`Manifest`] — see [`Manifest::tier`]. `endpoint`
205/// is the default (a normal fleet job); `controller` restricts dispatch to
206/// the trusted `controller_group`. `Unknown` is the #492 forward-compat
207/// catch-all: an older reader still *decodes* a job that names a future
208/// tier (so it doesn't fail the whole document), but `Manifest::validate()`
209/// **rejects** it — for a security field we fail closed rather than fall
210/// back to unrestricted `endpoint` dispatch (a future tier is presumably
211/// *more* restrictive, and a typo'd `controller` must not silently widen).
212#[derive(
213 Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
214)]
215#[serde(rename_all = "snake_case")]
216#[non_exhaustive]
217pub enum Tier {
218 /// Dispatch to the targeted fleet agents (the default).
219 #[default]
220 Endpoint,
221 /// Dispatch only to members of the configured `controller_group`.
222 Controller,
223 /// #492 forward-compat catch-all (a future tier this build can't act on).
224 #[serde(other)]
225 Unknown,
226}
227
228/// GitOps provenance for a repo-managed YAML artifact — a [`Manifest`]
229/// (#678) or a [`Schedule`] (#695). Populated by `kanade job create` /
230/// `kanade schedule create` from the Git context of the source YAML;
231/// the SPA reads it to render Git-managed entries read-only and link
232/// the operator back at the repo. Never consulted by the runtime.
233#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
234pub struct RepoOrigin {
235 /// Repo-relative path of the source YAML — the primary edit target
236 /// the SPA surfaces (e.g. `configs/jobs/foo.yaml`). Forward slashes
237 /// regardless of the authoring OS.
238 pub path: String,
239 /// `origin` remote URL, when the repo has one. Lets the SPA turn
240 /// `path` into a clickable link; `None` for remote-less repos.
241 #[serde(default, skip_serializing_if = "Option::is_none")]
242 pub repo: Option<String>,
243 /// Repo-relative path of the `script_file:` a job manifest inlined,
244 /// when it used one — a secondary pointer shown beneath `path`.
245 /// Always `None` for schedules (they carry no script).
246 #[serde(default, skip_serializing_if = "Option::is_none")]
247 pub script_file: Option<String>,
248}
249
250/// "Who + how + when-to-stagger" — the fanout-plan side of an exec.
251/// Used both as the POST `/api/exec/{job_id}` body and as the embedded
252/// `target` / `rollout` / `jitter` slot on [`Schedule`]. Centralising
253/// here keeps the validation + serialisation logic in one place.
254#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default)]
255pub struct FanoutPlan {
256 #[serde(default)]
257 pub target: Target,
258 /// Optional wave rollout — when present, the backend publishes
259 /// each wave's group subject on its own delay schedule instead
260 /// of fanning out the `target` block in one go. `target` then
261 /// only labels the deploy for the audit log.
262 #[serde(default, skip_serializing_if = "Option::is_none")]
263 pub rollout: Option<Rollout>,
264 /// Optional humantime jitter; agent uses it to randomise
265 /// execution start. Lives here (not on the script) so different
266 /// schedules / ad-hoc fires of the same job can pick different
267 /// stagger windows.
268 #[serde(default, skip_serializing_if = "Option::is_none")]
269 pub jitter: Option<String>,
270 /// Absolute time the scheduler stamps on each emitted Command
271 /// when this exec was driven by a [`Schedule`] with
272 /// `starting_deadline`. Agents receiving a Command after this
273 /// instant publish a synthetic skipped-result instead of
274 /// running the script. `None` (default) = no deadline / catch
275 /// up whenever delivered. Computed by the scheduler from
276 /// `tick_at + starting_deadline` and overwritten on every fire —
277 /// on a Schedule, setting it by hand is rejected at create time
278 /// (#917, use `starting_deadline`); it remains settable on an
279 /// ad-hoc POST /api/exec body.
280 #[serde(default, skip_serializing_if = "Option::is_none")]
281 pub deadline_at: Option<chrono::DateTime<chrono::Utc>>,
282}
283
284/// Sentinel lines that fence a hint's structured JSON payload inside an
285/// otherwise human-readable job stdout. Each stdout-reading hint
286/// (`inventory:` / `check:` / `collect:`) has its OWN `#KANADE-<KIND>-
287/// BEGIN`/`-END` pair, so one job can carry several of them at once
288/// (and/or a user-facing message) on its single stdout stream — every
289/// consumer extracts only its own block via [`fenced_payload`].
290///
291/// Originated for inventory (#793): a `client:` job couldn't put both a
292/// friendly message and a JSON object on one stdout (the Client App
293/// renders stdout verbatim, the projector needs JSON). #821 generalised
294/// it so inventory / check / collect can coexist. `emit:` is the
295/// exception — its stdout is line-delimited NDJSON consumed whole, so it
296/// never fences and never coexists with the others.
297///
298/// A job carrying a SINGLE hint may still skip the fence —
299/// [`fenced_payload`] falls back to the whole stdout — but a job
300/// COMBINING hints must fence each block (else every consumer would try
301/// to parse the same whole stdout).
302pub const INVENTORY_BLOCK_BEGIN: &str = "#KANADE-INVENTORY-BEGIN";
303/// Closing marker — see [`INVENTORY_BLOCK_BEGIN`].
304pub const INVENTORY_BLOCK_END: &str = "#KANADE-INVENTORY-END";
305/// Check-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
306pub const CHECK_BLOCK_BEGIN: &str = "#KANADE-CHECK-BEGIN";
307/// Check-payload closing marker.
308pub const CHECK_BLOCK_END: &str = "#KANADE-CHECK-END";
309/// Collect-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
310pub const COLLECT_BLOCK_BEGIN: &str = "#KANADE-COLLECT-BEGIN";
311/// Collect-payload closing marker.
312pub const COLLECT_BLOCK_END: &str = "#KANADE-COLLECT-END";
313/// Feed-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
314pub const FEED_BLOCK_BEGIN: &str = "#KANADE-FEED-BEGIN";
315/// Feed-payload closing marker.
316pub const FEED_BLOCK_END: &str = "#KANADE-FEED-END";
317
318/// Extract a hint's fenced block when the `begin` marker is present, else
319/// `None`. An unterminated fence (closing marker missing, e.g. truncated
320/// output) takes everything after the opener. Trimmed so surrounding
321/// message text / whitespace never reaches the JSON parser.
322pub fn fenced_payload_if_present<'a>(stdout: &'a str, begin: &str, end: &str) -> Option<&'a str> {
323 let b = find_line_marker(stdout, begin)?;
324 let after = &stdout[b + begin.len()..];
325 let inner = match find_line_marker(after, end) {
326 Some(e) => &after[..e],
327 None => after,
328 };
329 Some(inner.trim())
330}
331
332/// True if stdout carries ANY `#KANADE-<KIND>-BEGIN` fence at a line
333/// start — i.e. the script opted into fenced output. Used to decide
334/// whether a missing fence means "single-hint, use the whole stdout" or
335/// "multi-hint author error / truncation, this hint just has no block".
336pub fn has_any_hint_fence(stdout: &str) -> bool {
337 [
338 INVENTORY_BLOCK_BEGIN,
339 CHECK_BLOCK_BEGIN,
340 COLLECT_BLOCK_BEGIN,
341 FEED_BLOCK_BEGIN,
342 ]
343 .iter()
344 .any(|m| find_line_marker(stdout, m).is_some())
345}
346
347/// Extract one hint's JSON payload from a job's stdout. When the hint's
348/// own `#KANADE-<KIND>` fence is present, return that block. When it's
349/// absent, fall back to the WHOLE stdout only for an unfenced (single-
350/// hint) job; if any OTHER hint's fence is present (#821 multi-hint
351/// output) return `""` instead — the script opted into fences but this
352/// block is missing (author error or truncation), so this consumer must
353/// NOT grab a sibling hint's block. An empty payload fails the consumer's
354/// JSON parse and degrades to "no data for this hint", never cross-parse.
355pub fn fenced_payload<'a>(stdout: &'a str, begin: &str, end: &str) -> &'a str {
356 if let Some(p) = fenced_payload_if_present(stdout, begin, end) {
357 return p;
358 }
359 if has_any_hint_fence(stdout) {
360 ""
361 } else {
362 stdout.trim()
363 }
364}
365
366/// Inventory's fenced payload — [`fenced_payload`] with the inventory
367/// markers. Kept as a named helper for the projector call site.
368pub fn inventory_payload(stdout: &str) -> &str {
369 fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END)
370}
371
372/// Feed's fenced payload — [`fenced_payload`] with the feed markers. Kept as
373/// a named helper for the projector call site.
374pub fn feed_payload(stdout: &str) -> &str {
375 fenced_payload(stdout, FEED_BLOCK_BEGIN, FEED_BLOCK_END)
376}
377
378/// Find `needle` only where it begins a line (start of `hay` or right
379/// after a `\n`). Anchoring to line start means a script echoing the
380/// literal sentinel mid-message (e.g. printing a command name) can't
381/// false-trigger the fence (Claude #793).
382fn find_line_marker(hay: &str, needle: &str) -> Option<usize> {
383 if hay.starts_with(needle) {
384 return Some(0);
385 }
386 hay.find(&format!("\n{needle}")).map(|p| p + 1)
387}
388
389/// Manifest sub-section: how the SPA should render the inventory
390/// facts this job produces. Each field name (`field`) is a top-level
391/// key in the stdout JSON, e.g. `hostname`, `ram_gb`.
392///
393/// Two render modes:
394/// * `display` — vertical "field / value" per PC, used by the
395/// `/inventory?pc=<id>` detail view. ALL columns the operator
396/// wants visible on the detail page.
397/// * `summary` — horizontal table across the fleet (row = PC,
398/// column = field) on `/inventory`. Optional; when omitted the
399/// SPA falls back to `display`, but operators usually want a
400/// trimmer "hostname / OS / CPU / RAM" set for the fleet view.
401#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
402pub struct InventoryHint {
403 /// Detail-view columns, in order.
404 pub display: Vec<DisplayField>,
405 /// Optional fleet-list columns (row = PC). Defaults to `display`
406 /// when omitted, but operators usually pick a 3-5 column subset.
407 #[serde(default, skip_serializing_if = "Option::is_none")]
408 pub summary: Option<Vec<DisplayField>>,
409 /// v0.31 / #40: payload arrays that should be exploded into
410 /// per-element rows of a derived SQLite table. Lets operators
411 /// answer cross-PC questions ("which PCs still have Chrome <
412 /// 120?", "C: >90% full") with normal SQL filters + indexes
413 /// instead of grepping JSON. The projector creates the derived
414 /// table on register and replaces this PC's rows on each result
415 /// (DELETE WHERE pc_id=? AND job_id=? + bulk INSERT). See
416 /// [`ExplodeSpec`] for the per-spec schema.
417 #[serde(default, skip_serializing_if = "Option::is_none")]
418 pub explode: Option<Vec<ExplodeSpec>>,
419 /// v0.35 / #93: top-level scalar fields whose changes the
420 /// projector logs to `inventory_history` (one event per
421 /// changed field per scan). Pairs with `explode[].track_history`
422 /// — that covers array elements; this covers single-valued
423 /// fields like `ram_bytes` / `os_version` / `cpu_model` /
424 /// `os_build` that operators want to track for "did the RAM
425 /// get upgraded?" / "when did Win 11 land on this PC?" /
426 /// "BIOS / firmware bumped?" questions. Field name = `field_path`
427 /// in the history row, `identity_json` is NULL, `before_json`
428 /// / `after_json` each carry `{"value": <prior or new value>}`.
429 /// First-ever observation of a scalar (no prior facts row)
430 /// emits `added`; subsequent value changes emit `changed`. No
431 /// `removed` events — a scalar disappearing from the payload
432 /// is rare and the operator can still see the last value via
433 /// the `before_json` of the most recent change.
434 #[serde(default, skip_serializing_if = "Option::is_none")]
435 pub history_scalars: Option<Vec<String>>,
436}
437
438/// Manifest sub-section (#290): marks a job as an operator-defined
439/// **health check**. Parallel to [`InventoryHint`] / `EmitConfig`.
440/// The stdout contract is a free-form JSON object (same as any
441/// inventory job) from which the agent reads `status_field` /
442/// `detail_field` to build the KLP [`crate::ipc::state::Check`] shown
443/// on the Client App's Health tab.
444///
445/// There is deliberately **no timing field** — when / how often /
446/// in which window a check runs is driven by the job's Schedule,
447/// exactly like inventory jobs, so operators get the full `when:` /
448/// rollout / `runs_on` expressiveness for free.
449///
450/// A check's stdout is a **free-form inventory object** (arbitrary
451/// key/value pairs + arrays) — same as any inventory job — that also
452/// carries a status field. `check:` adds only the health semantics on
453/// top: which field is the ok/warn/fail/unknown status, an optional
454/// one-line summary field, and a remediation job. Everything else
455/// (rich per-PC detail, `explode` sub-tables like a software list) is
456/// driven by a co-present [`InventoryHint`] and rendered with the
457/// SAME display logic the SPA Inventory page uses — on the Client App
458/// too. This keeps checks maximally expressive without a bespoke
459/// payload type.
460#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
461pub struct CheckHint {
462 /// Stable check id → [`Check.name`](crate::ipc::state::Check),
463 /// the SPA/Client React key + analytics label. Unique within the
464 /// fleet's check set. Machine-friendly slug (`disk_space`,
465 /// `defender_rtp`); for the human-facing row title see [`label`].
466 ///
467 /// [`label`]: CheckHint::label
468 pub name: String,
469 /// Optional human-facing display title →
470 /// [`Check.label`](crate::ipc::state::Check). The Client App's
471 /// Health tab and the operator SPA's Compliance page render this
472 /// instead of the [`name`](CheckHint::name) slug when set
473 /// (`"ウイルス対策のリアルタイム保護"` reads better than
474 /// `defender_rtp`). Falls back to the slug when absent, so it's
475 /// purely additive. Author it in the check's language — there's no
476 /// per-locale variant; checks are operator-defined per fleet.
477 #[serde(default, skip_serializing_if = "Option::is_none")]
478 pub label: Option<String>,
479 /// Top-level stdout field whose string value
480 /// (`ok`/`warn`/`fail`/`unknown`) becomes the Health-tab light
481 /// ([`CheckStatus`](crate::ipc::state::CheckStatus)). Defaults to
482 /// `"status"`; a missing / unparseable value → `unknown`.
483 #[serde(default = "default_status_field")]
484 pub status_field: String,
485 /// Top-level stdout field used as the Health-tab row's one-line
486 /// summary. Defaults to `"detail"`; absent in the payload → no
487 /// detail line (the rich breakdown lives in the inventory view).
488 #[serde(default = "default_detail_field")]
489 pub detail_field: String,
490 /// Optional remediation job id →
491 /// [`Check.troubleshoot`](crate::ipc::state::Check). The Client
492 /// App shows a "修復する" button when present; that job must be
493 /// `user_invokable`.
494 #[serde(default, skip_serializing_if = "Option::is_none")]
495 pub troubleshoot: Option<String>,
496 /// #290 PR-E: when `true` (default), the backend also projects this
497 /// check's `status` / `detail` into the `check_status` table so the
498 /// operator SPA gets a fleet-wide compliance view for free — no
499 /// `inventory:` block needed. Set `fleet: false` for a client-only
500 /// check the operator doesn't want surfaced across the fleet.
501 #[serde(default = "default_true")]
502 pub fleet: bool,
503 /// When `true` (default), this check is shown on the Client App's
504 /// Health tab (the end user sees its ok/warn/fail row). Set
505 /// `health: false` for a **gate-only** check — one that exists purely
506 /// to drive a `client.show_when` display gate (e.g. `myapp-up-to-date`)
507 /// and would just be noise as a Health row. The agent still records it
508 /// into `StateSnapshot.checks` (so `show_when` can read it and the gate
509 /// keeps working); only the Client App's Health *rendering* skips it,
510 /// via the [`Check.health_hidden`](crate::ipc::state::Check::health_hidden)
511 /// wire flag. Orthogonal to [`fleet`](CheckHint::fleet): `fleet` gates
512 /// the operator SPA fleet view, `health` gates the end-user Health tab,
513 /// so a pure gate detector typically sets neither (`fleet: false` +
514 /// `health: false`) to stay invisible everywhere while still driving
515 /// the gate.
516 #[serde(default = "default_true")]
517 pub health: bool,
518 /// Optional auto-notification on a compliance transition. When set, the
519 /// backend publishes an end-user notification the moment this check
520 /// transitions *into* one of [`CheckAlert::on`] (e.g. ok → fail) — to
521 /// the failing PC's user and/or operator groups. Fired once per
522 /// transition (not on every poll). Requires `fleet: true` (the alert
523 /// rides the same projection that fills `check_status`).
524 #[serde(default, skip_serializing_if = "Option::is_none")]
525 pub alert: Option<CheckAlert>,
526}
527
528/// Auto-notification rule for a [`CheckHint`] (compliance alerting). When a
529/// check's status transitions into one of [`on`](Self::on), the backend
530/// publishes a notification to the failing PC's user
531/// ([`notify_user`](Self::notify_user)) and/or operator groups
532/// ([`notify_groups`](Self::notify_groups)). Deliberately config-driven:
533/// who gets told, how loud, and the wording all live in the manifest, not
534/// hardcoded in the backend.
535#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
536pub struct CheckAlert {
537 /// Statuses that fire the alert on *transition into* them (a check that
538 /// stays failing doesn't re-alert every poll). Defaults to `[fail]`.
539 /// `ok` is not representable — [`CheckAlertStatus`] has no `Ok` variant,
540 /// so a YAML `on: [ok]` fails to deserialize (before `validate()` is
541 /// even reached); "recovered" notifications are out of scope.
542 #[serde(default = "default_alert_on")]
543 pub on: Vec<CheckAlertStatus>,
544 /// Notify the user(s) on the failing PC (`notifications.pc.<pc_id>`).
545 #[serde(default)]
546 pub notify_user: bool,
547 /// Notify these operator groups (`notifications.group.<name>`).
548 #[serde(default, skip_serializing_if = "Vec::is_empty")]
549 pub notify_groups: Vec<String>,
550 /// Notification priority (colour/label only — toasting is the separate
551 /// `toast` flag). Defaults to `warn`.
552 #[serde(default = "default_alert_priority")]
553 pub priority: crate::ipc::notifications::NotificationPriority,
554 /// Require the recipient to click 確認 to dismiss.
555 #[serde(default)]
556 pub require_ack: bool,
557 /// Surface an OS toast (launches a closed Client App, Action Center
558 /// while locked). Recommended `true` for `notify_user` so a
559 /// non-emergency "your PC is non-compliant" nudge still reaches a user
560 /// whose app is closed.
561 #[serde(default)]
562 pub toast: bool,
563 /// Also send the alert by email, to every address mapped to the
564 /// `notify_groups` (via the `group_contacts` KV, edited on the SPA
565 /// Groups page). Opt-in: defaults to `false`, so an existing alert
566 /// never starts emailing on its own. Requires `notify_groups` to be
567 /// non-empty (there is no per-PC user email) and the backend's
568 /// `[mail]` config to be present; otherwise the email is a logged
569 /// no-op while the in-app/toast notification still fires.
570 #[serde(default)]
571 pub email: bool,
572 /// Notification title (required). May use the same `{…}` placeholders
573 /// as [`body`](Self::body).
574 pub title: String,
575 /// Notification body template. Placeholders: `{pc_id}`, `{name}` (check
576 /// slug), `{label}` (check label, falls back to slug), `{status}`,
577 /// `{detail}` (the check's one-line summary), `{last_logon}` (the PC's
578 /// last sign-in account). Absent → empty body.
579 #[serde(default, skip_serializing_if = "Option::is_none")]
580 pub body: Option<String>,
581}
582
583/// A check status that can trigger a [`CheckAlert`]. Mirrors the
584/// projected `check_status.status` values minus `ok` (alerting on `ok` is
585/// rejected at validation).
586#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash)]
587#[serde(rename_all = "snake_case")]
588pub enum CheckAlertStatus {
589 Warn,
590 Fail,
591 Unknown,
592}
593
594impl CheckAlertStatus {
595 /// The wire string, matching the projected `check_status.status`.
596 pub fn as_str(self) -> &'static str {
597 match self {
598 Self::Warn => "warn",
599 Self::Fail => "fail",
600 Self::Unknown => "unknown",
601 }
602 }
603}
604
605fn default_alert_on() -> Vec<CheckAlertStatus> {
606 vec![CheckAlertStatus::Fail]
607}
608
609fn default_alert_priority() -> crate::ipc::notifications::NotificationPriority {
610 crate::ipc::notifications::NotificationPriority::Warn
611}
612
613fn default_status_field() -> String {
614 "status".to_string()
615}
616
617fn default_detail_field() -> String {
618 "detail".to_string()
619}
620
621fn default_files_field() -> String {
622 "files".to_string()
623}
624
625/// Fallback cap on a collect bundle's total input size when the
626/// manifest's `collect.max_size` is unset. 50 MB (decimal).
627pub const DEFAULT_COLLECT_MAX_SIZE: u64 = 50 * 1_000_000;
628
629/// Manifest sub-section (#219): marks a job as a **file collector** and
630/// carries how the collected bundle presents in the SPA. Parallel to
631/// [`InventoryHint`] / [`CheckHint`] — the block's presence is the
632/// opt-in. The script prints a single JSON object on stdout whose
633/// [`files_field`](CollectHint::files_field) key holds an array of file
634/// paths to bundle (env vars are expanded); the agent zips them and
635/// uploads to `OBJECT_COLLECTIONS`. See [`Manifest::collect`].
636#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
637pub struct CollectHint {
638 /// Operator/end-user-facing title for the collection, shown as the
639 /// bundle's heading on the SPA Collect page (and the Client App row
640 /// when paired with `client:`). Required; validated non-empty.
641 pub name: String,
642 /// Optional one-line description of what the bundle contains.
643 #[serde(default, skip_serializing_if = "Option::is_none")]
644 pub description: Option<String>,
645 /// Human-readable cap on the bundle's total input size
646 /// (`"50MB"`, `"500KB"`, `"1GiB"`). The agent refuses to build a
647 /// bundle whose listed files exceed this. `None` ⇒
648 /// [`DEFAULT_COLLECT_MAX_SIZE`]. Parsed by [`parse_size_bytes`];
649 /// [`Manifest::validate`] rejects an unparseable value at create
650 /// time.
651 ///
652 /// Note: this bounds the **uncompressed** bytes the agent reads off
653 /// disk, not the resulting zip. Text logs compress well, so the
654 /// download is usually much smaller; many tiny files add a little
655 /// per-entry zip overhead. Read it as "how much the agent reads +
656 /// packs", not "the exact download size".
657 #[serde(default, skip_serializing_if = "Option::is_none")]
658 pub max_size: Option<String>,
659 /// Top-level stdout JSON key holding the array of file paths to
660 /// bundle. Defaults to `"files"`.
661 #[serde(default = "default_files_field")]
662 pub files_field: String,
663}
664
665impl CollectHint {
666 /// The effective size cap in bytes — the parsed `max_size` or
667 /// [`DEFAULT_COLLECT_MAX_SIZE`] when unset. Assumes `max_size` (if
668 /// present) already passed [`Manifest::validate`]; falls back to the
669 /// default on a parse error rather than panicking on the fire path.
670 pub fn max_size_bytes(&self) -> u64 {
671 match &self.max_size {
672 Some(s) => parse_size_bytes(s).unwrap_or(DEFAULT_COLLECT_MAX_SIZE),
673 None => DEFAULT_COLLECT_MAX_SIZE,
674 }
675 }
676}
677
678/// Parse a human-readable byte size (`"50MB"`, `"500 KB"`, `"1GiB"`,
679/// `"1024"`). Decimal units (KB/MB/GB) are 1000-based; binary units
680/// (KiB/MiB/GiB) are 1024-based; a bare number (or `B`) is bytes.
681/// Case-insensitive. Shared by `collect.max_size` validation and the
682/// agent's bundle-size enforcement.
683pub fn parse_size_bytes(s: &str) -> Result<u64, String> {
684 let t = s.trim();
685 if t.is_empty() {
686 return Err("size must not be empty".to_string());
687 }
688 let split = t.find(|c: char| !c.is_ascii_digit()).unwrap_or(t.len());
689 let (num_str, unit_raw) = t.split_at(split);
690 if num_str.is_empty() {
691 return Err(format!("size '{s}': missing leading number"));
692 }
693 let num: u64 = num_str
694 .parse()
695 .map_err(|_| format!("size '{s}': bad number '{num_str}'"))?;
696 let mult: u64 = match unit_raw.trim().to_ascii_lowercase().as_str() {
697 "" | "b" => 1,
698 "kb" => 1_000,
699 "mb" => 1_000_000,
700 "gb" => 1_000_000_000,
701 "kib" => 1024,
702 "mib" => 1024 * 1024,
703 "gib" => 1024 * 1024 * 1024,
704 other => {
705 return Err(format!(
706 "size '{s}': unknown unit '{other}' (use B/KB/MB/GB/KiB/MiB/GiB)"
707 ));
708 }
709 };
710 num.checked_mul(mult)
711 .ok_or_else(|| format!("size '{s}': overflow"))
712}
713
714/// Manifest sub-section (#291): marks a job as **user-invokable**
715/// from the Client App and carries how it presents to the end user.
716/// Parallel to [`InventoryHint`] / [`CheckHint`] / `EmitConfig` —
717/// the block's presence is the opt-in (no separate boolean), and its
718/// required fields (`name`, `category`) are enforced by serde at
719/// parse time, so a half-filled catalog entry fails
720/// `kanade job create` instead of rendering a nameless / tab-less row.
721///
722/// The agent maps this 1:1 into the KLP
723/// [`UserInvokableJob`](crate::ipc::jobs::UserInvokableJob) wire shape
724/// that `jobs.list` returns; the Client App renders one row per job in
725/// the tab named by `category`.
726#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
727pub struct ClientHint {
728 /// End-user-facing title for the job row. The operator-internal
729 /// `Manifest::id` slug is rarely what an end user should read, so
730 /// this is required (and validated non-empty by
731 /// [`Manifest::validate`]). Maps to `UserInvokableJob::display_name`.
732 pub name: String,
733 /// Optional one-line subtitle under `name` in the Client App.
734 /// Distinct from the operator-facing top-level
735 /// [`Manifest::description`] — this one is written for the end
736 /// user. Maps to `UserInvokableJob::display_description`.
737 #[serde(default, skip_serializing_if = "Option::is_none")]
738 pub description: Option<String>,
739 /// Which Client App tab the job lives in — a **free-form category
740 /// key** (#792). The Client App renders one tab per distinct key.
741 /// Well-known keys (`software_update`, `troubleshoot`, `catalog`)
742 /// carry built-in tab labels/icons; any other key defines a new tab
743 /// (style it with `category_label` / `category_icon`). Required and
744 /// validated non-empty — without it the agent can't place the job.
745 /// Note: the `software_update` key also drives the agent's
746 /// maintenance / auto-reboot grouping.
747 pub category: String,
748 /// Optional display name for the category's TAB. Set it on (at least
749 /// one of) a custom category's jobs to name the tab; `None` ⇒ a
750 /// built-in default for a well-known key, else the key itself.
751 #[serde(default, skip_serializing_if = "Option::is_none")]
752 pub category_label: Option<String>,
753 /// Optional icon for the category's TAB (lucide name or `data:` URL).
754 /// `None` ⇒ Client App default for the key.
755 #[serde(default, skip_serializing_if = "Option::is_none")]
756 pub category_icon: Option<String>,
757 /// Optional sort order for the TAB; lower sorts first. `None` ⇒
758 /// default (well-known keys keep their familiar order; custom keys
759 /// sort after, then by label).
760 #[serde(default, skip_serializing_if = "Option::is_none")]
761 pub category_order: Option<i64>,
762 /// Optional icon hint for the job ROW — a lucide-react icon name
763 /// or a `data:` URL. `None` ⇒ the Client App falls back to the
764 /// category's icon. Surfaced verbatim in `jobs.list[].icon`.
765 #[serde(default, skip_serializing_if = "Option::is_none")]
766 pub icon: Option<String>,
767 /// Optional visibility scope for the end-user Client App (#816).
768 ///
769 /// `None` ⇒ visible to every PC (current behavior). When set, only
770 /// agents whose `pc_id` / group membership match the [`Target`] list
771 /// the job in `jobs.list` and may run it via KLP `jobs.execute`.
772 ///
773 /// This gates the END-USER surface ONLY. Operators are unaffected:
774 /// `POST /api/exec/{job_id}` (SPA / `kanade exec`) is a separate path
775 /// that never consults `client:`, so an operator can still run the
776 /// job on any PC regardless of `visible_to`. Reuses the schedule
777 /// `Target` shape (`all` / `groups` / `pcs`); a present-but-empty
778 /// target is rejected by [`Manifest::validate`].
779 #[serde(default, skip_serializing_if = "Option::is_none")]
780 pub visible_to: Option<Target>,
781 /// Optional **dynamic display gate** keyed on a health check's result.
782 ///
783 /// `None` ⇒ always listed (current behavior). When set, the agent
784 /// lists the job in `jobs.list` ONLY while the named [`check:`] slug's
785 /// latest result is one of [`ShowWhen::is`]. The canonical use is an
786 /// update action that hides itself once the machine is already current:
787 /// pair the update job with a `check:` that reports `ok` when up to
788 /// date and gate on `is: [fail]`.
789 ///
790 /// Evaluated agent-side at `jobs.list` time against the live
791 /// `StateSnapshot.checks`, which is **keyed by check name** — so the
792 /// detector `check:` and this job may live in *different* manifests and
793 /// still share one slug. Distinct from [`visible_to`](ClientHint::visible_to):
794 /// that gates BOTH listing and `jobs.execute` (an authorization
795 /// boundary); `show_when` gates listing ONLY (a UX hint), so it can't
796 /// cause a list/execute race. New field ⇒ #492 wire rule.
797 ///
798 /// [`check:`]: crate::manifest::CheckHint
799 #[serde(default, skip_serializing_if = "Option::is_none")]
800 pub show_when: Option<ShowWhen>,
801 /// Optional **confirmation-dialog** config for the Client App's 実行
802 /// button.
803 ///
804 /// `None` ⇒ the historical default: the client shows a modal
805 /// confirmation with a built-in 「「{name}」を実行しますか?」 message
806 /// before firing the job (a mis-click guard for a possibly heavy /
807 /// destructive action). When set, the operator controls it:
808 /// - a bare bool — `confirm: false` runs immediately with **no** prompt;
809 /// `confirm: true` is the same as omitting the block (default message);
810 /// - a struct — `confirm: { message: "…" }` shows the dialog with a
811 /// custom message (and, redundantly with the scalar, `enabled: false`
812 /// to suppress it).
813 ///
814 /// Gates the END-USER Client App surface only — the operator `POST
815 /// /api/exec` path never consults `client:`, so an operator-driven run
816 /// is unaffected. New field ⇒ #492 wire rule (`serde(default)` +
817 /// `skip_serializing_if`). Deserializes from bool-or-struct via
818 /// [`de_confirm`]; the JSON schema advertises the struct form (the
819 /// scalar is author ergonomics, like [`ShowWhen::is`]).
820 #[serde(
821 default,
822 deserialize_with = "de_confirm",
823 skip_serializing_if = "Option::is_none"
824 )]
825 pub confirm: Option<ConfirmHint>,
826}
827
828/// Confirmation-dialog config for a [`ClientHint`] — see
829/// [`ClientHint::confirm`]. Controls the Client App's pre-run modal:
830/// whether it appears at all (`enabled`) and what it says (`message`).
831///
832/// Authored as either a bare bool (`confirm: false` / `true`) or a struct
833/// (`confirm: { message: "…" }`); both normalise here via [`de_confirm`].
834#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
835pub struct ConfirmHint {
836 /// Whether the Client App shows the confirmation dialog before running.
837 /// `false` fires the job immediately with no prompt. Defaults to `true`
838 /// (so an author who only sets `message` still gets the dialog, and the
839 /// struct form never accidentally suppresses it).
840 #[serde(default = "default_confirm_enabled")]
841 pub enabled: bool,
842 /// Custom dialog message. `None` ⇒ the client's built-in
843 /// 「「{name}」を実行しますか?」. Only meaningful while `enabled`;
844 /// rejected if present-but-blank by [`Manifest::validate`].
845 #[serde(default, skip_serializing_if = "Option::is_none")]
846 pub message: Option<String>,
847}
848
849/// `enabled` defaults to `true`: the historical behaviour is "always
850/// confirm", so a struct form that omits `enabled` (e.g. sets only
851/// `message`) still shows the dialog.
852fn default_confirm_enabled() -> bool {
853 true
854}
855
856/// Accept either a bare bool (`confirm: false` / `confirm: true`) or a
857/// struct (`confirm: { message: "…" }`) for [`ClientHint::confirm`],
858/// normalising to a [`ConfirmHint`]. The bool is pure author ergonomics —
859/// `false` ⇒ suppress the dialog, `true` ⇒ default message — while the
860/// struct carries a custom message. Called only when the key is present
861/// (absence is handled by `serde(default)` ⇒ `None`). An explicit
862/// `confirm: null` — which the generated schema permits (the field is
863/// `Option`) — maps to `None` too, so it can't produce a parse error;
864/// deserializing through `Option<BoolOrHint>` handles that cleanly (Gemini
865/// #960).
866fn de_confirm<'de, D>(d: D) -> Result<Option<ConfirmHint>, D::Error>
867where
868 D: serde::Deserializer<'de>,
869{
870 #[derive(Deserialize)]
871 #[serde(untagged)]
872 enum BoolOrHint {
873 Bool(bool),
874 Hint(ConfirmHint),
875 }
876 Ok(Option::<BoolOrHint>::deserialize(d)?.map(|b| match b {
877 BoolOrHint::Bool(enabled) => ConfirmHint {
878 enabled,
879 message: None,
880 },
881 BoolOrHint::Hint(h) => h,
882 }))
883}
884
885/// Dynamic display gate for a [`ClientHint`] — see
886/// [`ClientHint::show_when`]. Shows the job only while the named check's
887/// latest status is one of [`is`](ShowWhen::is).
888#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
889pub struct ShowWhen {
890 /// The `check:` slug (a [`CheckHint::name`](crate::manifest::CheckHint::name))
891 /// whose latest status gates this job. May be defined by a *different*
892 /// manifest: checks are keyed by name in the agent's snapshot, so a
893 /// standalone detector job and this one can share a slug. A check that
894 /// has never run (absent from the snapshot) does NOT match — the job
895 /// stays hidden until the detector first reports (fails closed, like
896 /// `visible_to`).
897 pub check: String,
898 /// The check status(es) in which the job is SHOWN. Accepts a single
899 /// status (`is: fail`) or a list (`is: [fail, unknown]`); both
900 /// deserialize to a `Vec`. The `length(min = 1)` schema constraint +
901 /// [`Manifest::validate`] both reject an empty set (it would match
902 /// nothing and silently hide the job) so schema-driven tooling and the
903 /// write path agree.
904 #[serde(deserialize_with = "de_one_or_many_check_status")]
905 #[schemars(length(min = 1))]
906 pub is: Vec<crate::ipc::state::CheckStatus>,
907}
908
909/// Accept either a single `CheckStatus` (`is: fail`) or a sequence
910/// (`is: [fail, unknown]`) for [`ShowWhen::is`], normalising to a `Vec`.
911/// The scalar form is purely author ergonomics; the JSON schema advertises
912/// the canonical array form (`#[schemars(with = ...)]`).
913fn de_one_or_many_check_status<'de, D>(
914 d: D,
915) -> Result<Vec<crate::ipc::state::CheckStatus>, D::Error>
916where
917 D: serde::Deserializer<'de>,
918{
919 use crate::ipc::state::CheckStatus;
920 #[derive(Deserialize)]
921 #[serde(untagged)]
922 enum OneOrMany {
923 One(CheckStatus),
924 Many(Vec<CheckStatus>),
925 }
926 Ok(match OneOrMany::deserialize(d)? {
927 OneOrMany::One(c) => vec![c],
928 OneOrMany::Many(v) => v,
929 })
930}
931
932/// #720 — one widget on the SPA **Analytics** page: a declarative
933/// aggregation over the `obs_events` table. The backend reads these off
934/// `Manifest::aggregate` (from `BUCKET_JOBS`) at query time and builds
935/// the `json_extract` GROUP BY / time-bucket SQL from these generic
936/// primitives, so an operator can chart any emitted event without a Rust
937/// change. The reference shapes are the attendance dashboards
938/// (presence / app_sample / web_visit), but the same DSL covers logon /
939/// reboot / agent-health trends, etc.
940#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
941pub struct AggregateWidget {
942 /// Tab this widget lives under on the Analytics page. Widgets from
943 /// every job are collected and grouped by this label, so the same
944 /// string across jobs builds one multi-source dashboard. Required.
945 pub dashboard: String,
946 /// Widget heading. Required, validated non-empty.
947 pub title: String,
948 /// Optional one-line subtitle shown muted under the `title` on the
949 /// Analytics page — room for a unit, a caveat, or what the number
950 /// means ("samples × 2 min", "Security 4624 only"). Rejected if
951 /// present-but-blank.
952 #[serde(default, skip_serializing_if = "Option::is_none")]
953 pub description: Option<String>,
954 /// Optional sort weight (#743). Once the order-aware sort lands (PR2)
955 /// widgets render in `(order, dashboard, title)` order, so a lower
956 /// `order` pulls a widget — and its tab — earlier; equal/absent `order`
957 /// falls back to the alphabetical `(dashboard, title)` ordering. Treated
958 /// as `0` when unset, so a fleet with no `order` anywhere stays purely
959 /// alphabetical (today's behaviour); negatives are allowed to pin
960 /// something first. (This field only carries the value; the backend
961 /// applies it.)
962 #[serde(default, skip_serializing_if = "Option::is_none")]
963 pub order: Option<i32>,
964 /// Promote this widget to the main Dashboard, not just the Analytics
965 /// page (#vuln-roadmap PR3). The Dashboard fetches the pinned subset
966 /// (`/api/analytics?pinned=true`, fleet scope) and renders it with the
967 /// same widget components. Operator-controlled, so any config-driven
968 /// view (e.g. a future vulnerability rollup) can surface up front
969 /// without a bespoke card. Defaults to `false`. Pin a `scope: fleet`
970 /// widget — a `pc`-scoped one needs a selected PC and won't render on
971 /// the fleet Dashboard.
972 // `Not::not` is `!self`, so this skips serializing the field when it's
973 // `false` — keeps `pin_dashboard: false` out of the stored job/view JSON,
974 // matching how the optional fields above omit their defaults.
975 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
976 pub pin_dashboard: bool,
977 /// `pc` rolls up a single selected PC; `fleet` rolls up all PCs
978 /// (and unlocks `group_by: pc_id` to rank PCs against each other).
979 /// Defaults to `pc`.
980 #[serde(default)]
981 pub scope: AggregateScope,
982 /// `obs_events.kind` this widget reads (e.g. `app_sample`,
983 /// `presence`, `unexpected_shutdown`). Required for every aggregation
984 /// render (`bar`/`gauge`/`timeline`/`stat`); rejected for
985 /// `op_timeline`, which reconstructs a fixed multi-kind operational
986 /// swimlane (power/session/sleep) baked into the SPA and so reads no
987 /// single `kind`.
988 #[serde(default, skip_serializing_if = "Option::is_none")]
989 pub kind: Option<String>,
990 /// Optional `obs_events.source` filter, when one `kind` is emitted by
991 /// more than one collector.
992 #[serde(default, skip_serializing_if = "Option::is_none")]
993 pub source: Option<String>,
994 /// How to roll the matching events up. See [`AggregateAgg`]. Required
995 /// for every aggregation render; rejected for `op_timeline` (which
996 /// performs no rollup — it returns the raw operational events and the
997 /// SPA folds them into lane spans).
998 #[serde(default, skip_serializing_if = "Option::is_none")]
999 pub agg: Option<AggregateAgg>,
1000 /// Dotted JSON path (no `$.` prefix) to group by for `agg: count` /
1001 /// `sum` — e.g. `foreground.app`. The literal `pc_id` is special:
1002 /// it groups by the `pc_id` column (fleet ranking), not a payload
1003 /// field. Omit for a single total. Required when `agg: sum` needs a
1004 /// breakdown; for `agg: count` omitting it yields the grand total.
1005 #[serde(default, skip_serializing_if = "Option::is_none")]
1006 pub group_by: Option<String>,
1007 /// Dotted JSON path to a boolean for `agg: ratio` (e.g. `active`):
1008 /// the widget reports `true_count / total`. Required when `agg: ratio`.
1009 #[serde(default, skip_serializing_if = "Option::is_none")]
1010 pub bool_path: Option<String>,
1011 /// Dotted JSON path to a number for `agg: sum`. Required when `agg: sum`.
1012 #[serde(default, skip_serializing_if = "Option::is_none")]
1013 pub value_path: Option<String>,
1014 /// Optional value transform applied before grouping. Currently only
1015 /// `host` (parse a URL down to its host) — used by the top-sites
1016 /// widget, where SQLite can't parse a URL so the backend does it in
1017 /// Rust. See [`AggregateTransform`].
1018 #[serde(default, skip_serializing_if = "Option::is_none")]
1019 pub transform: Option<AggregateTransform>,
1020 /// Optional sampling cadence in minutes. When set, a `count` is also
1021 /// reported as estimated time (`count × sample_minutes`) — e.g. a
1022 /// 2-minute app sampler turns 11 samples into ~22 minutes. Must be ≥ 1.
1023 #[serde(default, skip_serializing_if = "Option::is_none")]
1024 #[schemars(range(min = 1))]
1025 pub sample_minutes: Option<u32>,
1026 /// Grouped values to drop from the rollup (e.g. `["LockApp"]` so the
1027 /// lock screen doesn't top the app ranking). Empty by default.
1028 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1029 pub exclude: Vec<String>,
1030 /// Optional time bucketing — `hour` buckets events by local
1031 /// hour-of-day for a `timeline` render. See [`AggregateTimeBucket`].
1032 #[serde(default, skip_serializing_if = "Option::is_none")]
1033 pub time_bucket: Option<AggregateTimeBucket>,
1034 /// Top-N cap for grouped renders (`bar`). Defaults to 10 when unset.
1035 #[serde(default, skip_serializing_if = "Option::is_none")]
1036 #[schemars(range(min = 1))]
1037 pub limit: Option<u32>,
1038 /// Which widget the SPA draws. See [`AggregateRender`].
1039 pub render: AggregateRender,
1040}
1041
1042/// Per-PC vs fleet-wide rollup for an [`AggregateWidget`].
1043#[derive(
1044 Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
1045)]
1046#[serde(rename_all = "lowercase")]
1047#[non_exhaustive]
1048pub enum AggregateScope {
1049 /// Roll up the single PC the operator selected. The default.
1050 #[default]
1051 Pc,
1052 /// Roll up across every PC. Unlocks `group_by: pc_id`.
1053 Fleet,
1054 /// #492 forward-compat catch-all — a Manifest is read fleet-wide, so
1055 /// an older reader must tolerate a future variant rather than failing
1056 /// to decode the whole job. The backend skips an `Unknown` widget.
1057 #[serde(other)]
1058 Unknown,
1059}
1060
1061/// The rollup function for an [`AggregateWidget`].
1062#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1063#[serde(rename_all = "lowercase")]
1064#[non_exhaustive]
1065pub enum AggregateAgg {
1066 /// Row count, optionally grouped (`group_by`) and time-estimated
1067 /// (`sample_minutes`).
1068 Count,
1069 /// `true_count / total` over `bool_path`.
1070 Ratio,
1071 /// Sum of `value_path`, optionally grouped.
1072 Sum,
1073 /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1074 #[serde(other)]
1075 Unknown,
1076}
1077
1078/// Optional pre-grouping value transform for an [`AggregateWidget`].
1079#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1080#[serde(rename_all = "lowercase")]
1081#[non_exhaustive]
1082pub enum AggregateTransform {
1083 /// Parse the grouped value as a URL and keep only its host.
1084 Host,
1085 /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1086 #[serde(other)]
1087 Unknown,
1088}
1089
1090/// Time bucketing for an [`AggregateWidget`] (drives a `timeline`).
1091#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1092#[serde(rename_all = "lowercase")]
1093#[non_exhaustive]
1094pub enum AggregateTimeBucket {
1095 /// Bucket by local hour-of-day (0–23), summed over the window.
1096 Hour,
1097 /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1098 #[serde(other)]
1099 Unknown,
1100}
1101
1102/// Which visual the SPA renders an [`AggregateWidget`] as.
1103#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1104#[serde(rename_all = "lowercase")]
1105#[non_exhaustive]
1106pub enum AggregateRender {
1107 /// Ranked horizontal bars (a grouped `count` / `sum`).
1108 Bar,
1109 /// A single ratio dial (`agg: ratio`).
1110 Gauge,
1111 /// 24-hour activity strip (`time_bucket: hour`).
1112 Timeline,
1113 /// A single headline number (an ungrouped total).
1114 Stat,
1115 /// Per-PC operational swimlane (power / session / sleep) reconstructed
1116 /// from a fixed multi-kind event set. Unlike the aggregation renders it
1117 /// reads no single `kind`/`agg`: the backend returns the raw events in
1118 /// the window and the SPA folds them into lane spans (shared with the
1119 /// Events page strip). Per-PC only (`scope: pc`).
1120 #[serde(rename = "op_timeline")]
1121 OpTimeline,
1122 /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1123 #[serde(other)]
1124 Unknown,
1125}
1126
1127/// True if `p` is a well-formed dotted JSON path of `[A-Za-z0-9_]`
1128/// segments joined by single dots — the shape safe to bind into
1129/// `json_extract(payload, '$.' || ?)`. The charset blocks injection; the
1130/// segment check additionally rejects `"."`, `".foo"`, `"foo."`,
1131/// `"foo..bar"`, which would pass the charset but produce a malformed
1132/// `$.` path that errors at query time. Accepts `pc_id`, `foreground.app`,
1133/// `active`, etc.
1134fn is_valid_json_path(p: &str) -> bool {
1135 !p.is_empty()
1136 && p.split('.').all(|seg| {
1137 !seg.is_empty() && seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
1138 })
1139}
1140
1141/// Per-widget validation for a list of [`AggregateWidget`]s — shared by
1142/// the `aggregate:` job hint ([`Manifest::validate`]) and the standalone
1143/// [`View`] resource (#743) so the two can't diverge. `field` names the
1144/// containing key for error messages (`"aggregate"` or `"widgets"`).
1145///
1146/// Enforces: non-empty list; non-empty dashboard/title (and `kind`/`agg`
1147/// for every aggregation render); a blank-when-set `source`; rejection of
1148/// any #492 `Unknown` enum (an operator typo at create time); safe dotted
1149/// JSON paths; the value path each `agg` needs (and rejection of mis-paired
1150/// ones); `pc_id` grouping only in `fleet` scope; `transform`/`limit`/
1151/// `exclude` only with a `group_by`; positive `limit`/`sample_minutes`;
1152/// `gauge`⇔`ratio`; and `timeline`⇔`time_bucket`. A `render: op_timeline`
1153/// widget is validated separately (per-PC, no aggregation knobs) — see
1154/// [`validate_op_timeline_widget`].
1155pub fn validate_aggregate_widgets(widgets: &[AggregateWidget], field: &str) -> Result<(), String> {
1156 if widgets.is_empty() {
1157 return Err(format!(
1158 "`{field}:` must list at least one widget when present"
1159 ));
1160 }
1161 for (i, w) in widgets.iter().enumerate() {
1162 let at = format!("{field}[{i}]");
1163 for (label, value) in [("dashboard", &w.dashboard), ("title", &w.title)] {
1164 if value.trim().is_empty() {
1165 return Err(format!("{at}.{label} must not be empty"));
1166 }
1167 }
1168 // A present-but-blank `description` renders an empty muted line —
1169 // reject it so the subtitle only shows when it says something.
1170 if let Some(description) = &w.description {
1171 if description.trim().is_empty() {
1172 return Err(format!("{at}.description must not be empty when set"));
1173 }
1174 }
1175 // Reject values that fell through to the #492 `Unknown` catch-all:
1176 // at create time on the current version that's an operator typo. (A
1177 // genuinely-future variant only reaches an older reader via a stored
1178 // resource, which is never re-validated, so forward-compat holds.)
1179 if w.scope == AggregateScope::Unknown {
1180 return Err(format!("{at}.scope is not a known value (pc | fleet)"));
1181 }
1182 if w.render == AggregateRender::Unknown {
1183 return Err(format!(
1184 "{at}.render is not a known value (bar | gauge | timeline | stat | op_timeline)"
1185 ));
1186 }
1187 // `op_timeline` reconstructs a fixed per-PC operational swimlane
1188 // (power/session/sleep) from a baked-in multi-kind set — it uses none
1189 // of the aggregation knobs, so validate it on its own terms (per-PC,
1190 // no `kind`/`agg`/grouping) and skip the rollup rules below.
1191 if w.render == AggregateRender::OpTimeline {
1192 validate_op_timeline_widget(w, &at)?;
1193 continue;
1194 }
1195 // Every other render is an aggregation over a single `kind`.
1196 if w.kind.as_deref().map(str::trim).unwrap_or("").is_empty() {
1197 return Err(format!("{at}.kind must not be empty"));
1198 }
1199 let agg = match w.agg {
1200 Some(AggregateAgg::Unknown) => {
1201 return Err(format!(
1202 "{at}.agg is not a known value (count | ratio | sum)"
1203 ));
1204 }
1205 Some(agg) => agg,
1206 None => return Err(format!("{at}.agg is required")),
1207 };
1208 // A present-but-blank `source` is a no-op filter — reject like the
1209 // other blank-when-set guards.
1210 if let Some(source) = &w.source {
1211 if source.trim().is_empty() {
1212 return Err(format!("{at}.source must not be empty when set"));
1213 }
1214 }
1215 if w.transform == Some(AggregateTransform::Unknown) {
1216 return Err(format!("{at}.transform is not a known value (host)"));
1217 }
1218 if w.time_bucket == Some(AggregateTimeBucket::Unknown) {
1219 return Err(format!("{at}.time_bucket is not a known value (hour)"));
1220 }
1221 for (label, path) in [
1222 ("group_by", &w.group_by),
1223 ("bool_path", &w.bool_path),
1224 ("value_path", &w.value_path),
1225 ] {
1226 if let Some(p) = path {
1227 if !is_valid_json_path(p) {
1228 return Err(format!(
1229 "{at}.{label} '{p}' must be a dotted JSON path of [A-Za-z0-9_] segments"
1230 ));
1231 }
1232 }
1233 }
1234 // Each agg uses exactly one value path; reject a mis-paired path so
1235 // a typo fails at create rather than being ignored.
1236 match agg {
1237 // count: grouped → ranking, ungrouped → grand total.
1238 AggregateAgg::Count => {
1239 for (label, path) in [("bool_path", &w.bool_path), ("value_path", &w.value_path)] {
1240 if path.is_some() {
1241 return Err(format!("{at}.agg=count does not use `{label}`"));
1242 }
1243 }
1244 }
1245 AggregateAgg::Ratio => {
1246 if w.bool_path.is_none() {
1247 return Err(format!("{at}.agg=ratio requires `bool_path`"));
1248 }
1249 if w.value_path.is_some() {
1250 return Err(format!("{at}.agg=ratio does not use `value_path`"));
1251 }
1252 }
1253 AggregateAgg::Sum => {
1254 if w.value_path.is_none() {
1255 return Err(format!("{at}.agg=sum requires `value_path`"));
1256 }
1257 if w.bool_path.is_some() {
1258 return Err(format!("{at}.agg=sum does not use `bool_path`"));
1259 }
1260 }
1261 // Rejected above; arm exists only for exhaustiveness.
1262 AggregateAgg::Unknown => {}
1263 }
1264 // Ranking PCs against each other only means something across the
1265 // fleet — within one PC it's a single bar.
1266 if w.group_by.as_deref() == Some("pc_id") && w.scope != AggregateScope::Fleet {
1267 return Err(format!(
1268 "{at}.group_by: pc_id is only valid with scope: fleet"
1269 ));
1270 }
1271 // `transform` rewrites the grouped PAYLOAD value (URL→host); it's
1272 // meaningless on a `pc_id` grouping (the pc_id column, not a payload
1273 // field), so reject the combo at create time.
1274 if w.transform.is_some() && w.group_by.as_deref() == Some("pc_id") {
1275 return Err(format!("{at}.transform is not valid with group_by: pc_id"));
1276 }
1277 // limit / transform / exclude all operate on grouped values, so
1278 // without a `group_by` they're silent no-ops — reject.
1279 if w.group_by.is_none() {
1280 if w.limit.is_some() {
1281 return Err(format!("{at}.limit requires `group_by`"));
1282 }
1283 if w.transform.is_some() {
1284 return Err(format!("{at}.transform requires `group_by`"));
1285 }
1286 if !w.exclude.is_empty() {
1287 return Err(format!("{at}.exclude requires `group_by`"));
1288 }
1289 }
1290 if w.limit == Some(0) {
1291 return Err(format!("{at}.limit must be > 0"));
1292 }
1293 if w.sample_minutes == Some(0) {
1294 return Err(format!("{at}.sample_minutes must be > 0"));
1295 }
1296 for ex in &w.exclude {
1297 if ex.trim().is_empty() {
1298 return Err(format!("{at}.exclude must not contain empty entries"));
1299 }
1300 }
1301 // A gauge draws a single ratio dial — only meaningful for agg: ratio.
1302 if w.render == AggregateRender::Gauge && agg != AggregateAgg::Ratio {
1303 return Err(format!("{at}.render=gauge is only valid with agg: ratio"));
1304 }
1305 // A timeline needs a bucket; a bucket on any other render is a no-op
1306 // that signals operator confusion — reject both.
1307 match (w.render, &w.time_bucket) {
1308 (AggregateRender::Timeline, None) => {
1309 return Err(format!("{at}.render=timeline requires `time_bucket`"));
1310 }
1311 (r, Some(_)) if r != AggregateRender::Timeline => {
1312 return Err(format!(
1313 "{at}.time_bucket is only valid with render: timeline"
1314 ));
1315 }
1316 _ => {}
1317 }
1318 }
1319 Ok(())
1320}
1321
1322/// Validate a `render: op_timeline` widget. It draws a fixed per-PC
1323/// operational swimlane (power / session / sleep) reconstructed by the SPA
1324/// from a baked-in multi-kind event set, so it uses none of the aggregation
1325/// knobs: require `scope: pc` and reject every field that only makes sense
1326/// for a rollup (`kind`/`source`/`agg`/`group_by`/`bool_path`/`value_path`/
1327/// `transform`/`sample_minutes`/`exclude`/`time_bucket`/`limit`). Rejecting
1328/// the unused fields (rather than ignoring them) keeps an operator typo from
1329/// silently doing nothing, matching the rest of this validator.
1330fn validate_op_timeline_widget(w: &AggregateWidget, at: &str) -> Result<(), String> {
1331 // Per-PC only: a fleet-wide swimlane of every PC's spans is unbounded
1332 // and unreadable, and the backend only computes it in per-PC scope.
1333 if w.scope != AggregateScope::Pc {
1334 return Err(format!("{at}.render=op_timeline requires scope: pc"));
1335 }
1336 // Each unused field, with the name the operator wrote, so the error
1337 // points at exactly what to delete.
1338 if w.kind.is_some() {
1339 return Err(format!("{at}.render=op_timeline does not use `kind`"));
1340 }
1341 if w.source.is_some() {
1342 return Err(format!("{at}.render=op_timeline does not use `source`"));
1343 }
1344 if w.agg.is_some() {
1345 return Err(format!("{at}.render=op_timeline does not use `agg`"));
1346 }
1347 for (label, set) in [
1348 ("group_by", w.group_by.is_some()),
1349 ("bool_path", w.bool_path.is_some()),
1350 ("value_path", w.value_path.is_some()),
1351 ("transform", w.transform.is_some()),
1352 ("sample_minutes", w.sample_minutes.is_some()),
1353 ("time_bucket", w.time_bucket.is_some()),
1354 ("limit", w.limit.is_some()),
1355 ("exclude", !w.exclude.is_empty()),
1356 ] {
1357 if set {
1358 return Err(format!("{at}.render=op_timeline does not use `{label}`"));
1359 }
1360 }
1361 Ok(())
1362}
1363
1364/// Default materialization cadence for a [`SqlWidget`] whose `refresh` is
1365/// unset — 1 hour. A view over feed/inventory tables changes only as fast as
1366/// its underlying feed refresh (often daily), so an hour is fresh enough while
1367/// keeping an expensive correlation join off the ~30s Dashboard poll path.
1368pub const DEFAULT_VIEW_REFRESH: std::time::Duration = std::time::Duration::from_secs(3600);
1369
1370/// #vuln-roadmap PR3: a **SQL-backed, materialized** widget on a [`View`].
1371///
1372/// Where an [`AggregateWidget`] encodes an `obs_events` rollup in structured
1373/// YAML fields, a `SqlWidget` carries a raw read-only `SELECT`/`WITH` over the
1374/// projector's tables (inventory `explode:` tables, `feeds`, `check_status`,
1375/// …) — the correlation that powers a vulnerability / EOL / license dashboard
1376/// is just a `JOIN`, far more expressive than a YAML DSL. The backend runs the
1377/// query in the read-only sandbox (`api::query`), caches the result on the
1378/// `refresh` cadence, and maps it to the same render-ready shape the existing
1379/// widget components consume, via [`RenderSpec`]. See [`View::sql_widgets`].
1380#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1381pub struct SqlWidget {
1382 /// Widget heading. Required, validated non-empty.
1383 pub title: String,
1384 /// Optional muted subtitle (a unit, a caveat). Rejected if present-blank.
1385 #[serde(default, skip_serializing_if = "Option::is_none")]
1386 pub description: Option<String>,
1387 /// The read-only SQL. Executed in the `api::query` sandbox: a single
1388 /// `SELECT`/`WITH` on a `SQLITE_OPEN_READONLY` connection, row-capped and
1389 /// time-bounded. The backend validates it read-only at `view create` and
1390 /// again at run time; a write verb / stacked statement is rejected.
1391 pub query: String,
1392 /// How the query's result columns map to a visual — see [`RenderSpec`].
1393 pub render: RenderSpec,
1394 /// Materialization cadence as a humantime duration (`"6h"`, `"30m"`).
1395 /// Absent ⇒ [`DEFAULT_VIEW_REFRESH`]. The backend re-runs the query at
1396 /// most this often; reads in between hit the cache.
1397 #[serde(default, skip_serializing_if = "Option::is_none")]
1398 pub refresh: Option<String>,
1399 /// Where the widget surfaces — an Analytics tab and/or a pinned Dashboard
1400 /// card. At least one must be set (else it renders nowhere).
1401 pub placement: Placement,
1402}
1403
1404impl SqlWidget {
1405 /// The effective refresh cadence — the parsed `refresh` or
1406 /// [`DEFAULT_VIEW_REFRESH`]. Falls back to the default on an unparseable
1407 /// value rather than panicking on the read path (validation already
1408 /// rejected a bad value at `view create`).
1409 pub fn refresh_interval(&self) -> std::time::Duration {
1410 self.refresh
1411 .as_deref()
1412 .and_then(|s| humantime::parse_duration(s).ok())
1413 .unwrap_or(DEFAULT_VIEW_REFRESH)
1414 }
1415}
1416
1417/// How a [`SqlWidget`]'s SQL result columns map onto a visual. A `kind` names
1418/// the chart; the channel fields (`value`, `label`, `columns`, …) name which
1419/// result columns feed it. Only the channels a `kind` uses are read; the
1420/// backend validates the named columns exist in the result. New chart types
1421/// are "one renderer + the same mapping", so this stays a flat, additive shape.
1422#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Hash)]
1423pub struct RenderSpec {
1424 /// Which visual to render the result as.
1425 pub kind: RenderKind,
1426 /// `table` only: the columns to show, in order. Absent ⇒ every result
1427 /// column (the universal default).
1428 #[serde(default, skip_serializing_if = "Option::is_none")]
1429 pub columns: Option<Vec<String>>,
1430 /// `table` only: optional per-column header relabelling (result column →
1431 /// display name). Columns not listed keep their SQL name.
1432 #[serde(default, skip_serializing_if = "Option::is_none")]
1433 pub labels: Option<std::collections::BTreeMap<String, String>>,
1434 /// `stat` / `bar` / `pie` / `gauge`: the result column holding the numeric
1435 /// value (`stat`/`gauge` read the first row; `bar`/`pie` read every row).
1436 #[serde(default, skip_serializing_if = "Option::is_none")]
1437 pub value: Option<String>,
1438 /// `bar` / `pie`: the result column holding each row's category label.
1439 #[serde(default, skip_serializing_if = "Option::is_none")]
1440 pub label: Option<String>,
1441 /// `bar` / `pie`: keep only the top-N rows (by value). Absent ⇒ all rows.
1442 #[serde(default, skip_serializing_if = "Option::is_none")]
1443 pub limit: Option<u32>,
1444 /// `pie` only: render as a donut (a hole with the total in the centre).
1445 #[serde(default, skip_serializing_if = "Option::is_none")]
1446 pub donut: Option<bool>,
1447 /// `gauge` only: the numerator column (paired with `den`). Alternative to
1448 /// a precomputed `value` ratio.
1449 #[serde(default, skip_serializing_if = "Option::is_none")]
1450 pub num: Option<String>,
1451 /// `gauge` only: the denominator column (paired with `num`).
1452 #[serde(default, skip_serializing_if = "Option::is_none")]
1453 pub den: Option<String>,
1454}
1455
1456/// The chart kind for a [`RenderSpec`]. `table` and `pie` are new in PR3; the
1457/// rest reuse the existing `obs_events` widget renderers.
1458#[derive(
1459 Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash, Default,
1460)]
1461#[serde(rename_all = "lowercase")]
1462pub enum RenderKind {
1463 /// The full result grid (new renderer). The universal default.
1464 #[default]
1465 Table,
1466 /// A single headline number from the first row's `value` cell.
1467 Stat,
1468 /// Ranked horizontal bars — `label` + `value` per row, optional top-N.
1469 Bar,
1470 /// Parts-of-a-whole (new renderer) — `label` + `value` per row.
1471 Pie,
1472 /// A ratio dial — a `value` ratio, or a `num`/`den` pair.
1473 Gauge,
1474 /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1475 #[serde(other)]
1476 Unknown,
1477}
1478
1479/// Where a [`SqlWidget`] surfaces in the SPA. Mirrors the placement an
1480/// [`AggregateWidget`] expresses via `dashboard` + `pin_dashboard`, but as an
1481/// explicit block since a SQL widget lives on a standalone view.
1482#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1483pub struct Placement {
1484 /// The Analytics tab this widget groups under (the `AggregateWidget`
1485 /// `dashboard` analogue). Absent ⇒ not shown on the Analytics page.
1486 #[serde(default, skip_serializing_if = "Option::is_none")]
1487 pub analytics: Option<String>,
1488 /// Promote to the main Dashboard (reuses #900's pinned section). Absent ⇒
1489 /// not pinned.
1490 #[serde(default, skip_serializing_if = "Option::is_none")]
1491 pub dashboard: Option<DashboardPlacement>,
1492}
1493
1494impl Placement {
1495 /// True when the widget is pinned to the main Dashboard.
1496 pub fn is_pinned(&self) -> bool {
1497 self.dashboard.as_ref().is_some_and(|d| d.pin)
1498 }
1499 /// The Analytics tab name, or a fallback so a dashboard-only widget still
1500 /// carries a group label for the shared widget list.
1501 pub fn tab(&self) -> &str {
1502 self.analytics.as_deref().unwrap_or("Dashboard")
1503 }
1504}
1505
1506/// The `placement.dashboard` block — see [`Placement::dashboard`].
1507#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1508pub struct DashboardPlacement {
1509 /// Pin this widget to the main Dashboard's promoted section.
1510 #[serde(default)]
1511 pub pin: bool,
1512}
1513
1514/// Per-widget validation for a list of [`SqlWidget`]s — shared by the
1515/// [`View`] resource so authoring errors surface at `view create`. `field`
1516/// names the containing key for error messages. The read-only SQL check is
1517/// NOT here (it lives in the backend `api::query` sandbox, which kanade-shared
1518/// can't depend on) — this validates structure: non-empty title/query, a
1519/// known `kind`, the channels each `kind` needs, a real placement, and a
1520/// parseable `refresh`.
1521pub fn validate_sql_widgets(widgets: &[SqlWidget], field: &str) -> Result<(), String> {
1522 for (i, w) in widgets.iter().enumerate() {
1523 let at = format!("{field}[{i}]");
1524 if w.title.trim().is_empty() {
1525 return Err(format!("{at}.title must not be empty"));
1526 }
1527 if w.query.trim().is_empty() {
1528 return Err(format!("{at}.query must not be empty"));
1529 }
1530 if let Some(description) = &w.description {
1531 if description.trim().is_empty() {
1532 return Err(format!("{at}.description must not be empty when set"));
1533 }
1534 }
1535 if let Some(refresh) = &w.refresh {
1536 humantime::parse_duration(refresh)
1537 .map_err(|e| format!("{at}.refresh '{refresh}' is not a valid duration: {e}"))?;
1538 }
1539 // A widget that surfaces nowhere is an invisible no-op. A
1540 // `dashboard:` block with `pin: false` doesn't count — it pins
1541 // nowhere — so gate on the effective pin, not the block's presence
1542 // (Gemini / CodeRabbit).
1543 if w.placement.analytics.is_none() && !w.placement.is_pinned() {
1544 return Err(format!(
1545 "{at}.placement must set `analytics` and/or pin to `dashboard` (else the widget renders nowhere)"
1546 ));
1547 }
1548 if let Some(tab) = &w.placement.analytics {
1549 if tab.trim().is_empty() {
1550 return Err(format!(
1551 "{at}.placement.analytics must not be empty when set"
1552 ));
1553 }
1554 }
1555 // A per-PC widget (its query binds `:pc_id`) renders only in the
1556 // per-PC Analytics scope, bound to the selected PC. The Dashboard's
1557 // pinned section is fleet-scope and never sends a PC, so a pinned
1558 // per-PC widget would be silently dropped on every request — reject
1559 // the contradiction at create time rather than let it vanish (claude
1560 // review). Literal-aware so a `:pc_id` inside a string literal doesn't
1561 // trip it (see [`rewrite_pc_id_param`]).
1562 if w.placement.is_pinned() && rewrite_pc_id_param(&w.query).1 > 0 {
1563 return Err(format!(
1564 "{at}: a per-PC widget (its query binds `:pc_id`) cannot pin to the Dashboard \
1565 (the Dashboard is fleet-scope, it never selects a PC) — use `analytics` placement only"
1566 ));
1567 }
1568 validate_render_spec(&w.render, &at)?;
1569 }
1570 Ok(())
1571}
1572
1573/// The named parameter a per-PC [`SqlWidget`] binds to the selected PC. Its
1574/// presence in a widget's query is what makes the widget per-PC.
1575pub const PC_ID_PARAM: &str = ":pc_id";
1576
1577/// Rewrite every *real* `:pc_id` parameter in a widget query to a positional
1578/// `?`, returning `(rewritten_sql, count)`. "Real" = OUTSIDE string literals,
1579/// quoted identifiers and comments, and a whole token (the char after `:pc_id`
1580/// isn't a word char, so `:pc_idx` is left alone). One scanner shared by three
1581/// call sites so they can't disagree on how many `?` SQLite will actually see:
1582/// * per-PC scope detection (`count > 0` ⇒ the widget is per-PC),
1583/// * the backend's bind path (sqlx-sqlite binds POSITIONAL `?` only, not
1584/// `:name`, so the token must be rewritten and bound once per occurrence),
1585/// * and `validate_sql_widgets`' pinned-per-PC rejection above.
1586///
1587/// The literal/comment skipping mirrors the read-only sandbox's
1588/// `strip_sql_noise`, so a `:pc_id` inside `SELECT 'see :pc_id docs'` is copied
1589/// verbatim and NOT counted — it would otherwise be miscounted (a bind-count
1590/// mismatch → `SQLITE_RANGE`) and misclassify the widget's scope (Gemini /
1591/// claude review).
1592pub fn rewrite_pc_id_param(sql: &str) -> (String, usize) {
1593 let mut out = String::with_capacity(sql.len());
1594 let mut count = 0usize;
1595 let mut chars = sql.char_indices().peekable();
1596 while let Some((idx, c)) = chars.next() {
1597 match c {
1598 // String literal / quoted identifier — copy verbatim, honouring the
1599 // doubled-quote escape (`''` / `""` stays inside).
1600 '\'' | '"' => {
1601 out.push(c);
1602 let quote = c;
1603 while let Some((_, d)) = chars.next() {
1604 out.push(d);
1605 if d == quote {
1606 if chars.peek().map(|&(_, e)| e) == Some(quote) {
1607 let (_, e) = chars.next().unwrap();
1608 out.push(e);
1609 } else {
1610 break;
1611 }
1612 }
1613 }
1614 }
1615 // Line comment — copy to end of line.
1616 '-' if chars.peek().map(|&(_, e)| e) == Some('-') => {
1617 out.push(c);
1618 for (_, d) in chars.by_ref() {
1619 out.push(d);
1620 if d == '\n' {
1621 break;
1622 }
1623 }
1624 }
1625 // Block comment — copy to `*/`.
1626 '/' if chars.peek().map(|&(_, e)| e) == Some('*') => {
1627 out.push(c);
1628 let (_, star) = chars.next().unwrap();
1629 out.push(star);
1630 let mut prev = ' ';
1631 for (_, d) in chars.by_ref() {
1632 out.push(d);
1633 if prev == '*' && d == '/' {
1634 break;
1635 }
1636 prev = d;
1637 }
1638 }
1639 // A `:pc_id` token outside any literal/comment — rewrite if it's a
1640 // whole token (not the prefix of `:pc_idx`).
1641 ':' if sql[idx..].starts_with(PC_ID_PARAM) => {
1642 let after = idx + PC_ID_PARAM.len();
1643 let next_is_word = sql[after..]
1644 .chars()
1645 .next()
1646 .is_some_and(|w| w.is_alphanumeric() || w == '_');
1647 if next_is_word {
1648 out.push(c);
1649 } else {
1650 out.push('?');
1651 count += 1;
1652 for _ in 0..PC_ID_PARAM.chars().count() - 1 {
1653 chars.next();
1654 }
1655 }
1656 }
1657 _ => out.push(c),
1658 }
1659 }
1660 (out, count)
1661}
1662
1663/// Validate a [`RenderSpec`]: reject the #492 `Unknown` catch-all (an operator
1664/// typo at create time) and require the channel columns each `kind` reads.
1665fn validate_render_spec(r: &RenderSpec, at: &str) -> Result<(), String> {
1666 // A channel column is "given" when present and non-blank.
1667 let given = |v: &Option<String>| v.as_deref().map(str::trim).is_some_and(|s| !s.is_empty());
1668 match r.kind {
1669 RenderKind::Unknown => {
1670 return Err(format!(
1671 "{at}.render.kind is not a known value (table | stat | bar | pie | gauge)"
1672 ));
1673 }
1674 RenderKind::Table => {
1675 // `columns` optional; if given, each name must be non-blank.
1676 if let Some(cols) = &r.columns {
1677 if cols.iter().any(|c| c.trim().is_empty()) {
1678 return Err(format!("{at}.render.columns must not contain blank names"));
1679 }
1680 }
1681 if let Some(labels) = &r.labels {
1682 for (k, v) in labels {
1683 if k.trim().is_empty() || v.trim().is_empty() {
1684 return Err(format!(
1685 "{at}.render.labels keys and values must be non-empty"
1686 ));
1687 }
1688 }
1689 }
1690 }
1691 RenderKind::Stat => {
1692 if !given(&r.value) {
1693 return Err(format!("{at}.render.value is required for kind=stat"));
1694 }
1695 }
1696 RenderKind::Bar | RenderKind::Pie => {
1697 let kind = if r.kind == RenderKind::Bar {
1698 "bar"
1699 } else {
1700 "pie"
1701 };
1702 if !given(&r.label) {
1703 return Err(format!("{at}.render.label is required for kind={kind}"));
1704 }
1705 if !given(&r.value) {
1706 return Err(format!("{at}.render.value is required for kind={kind}"));
1707 }
1708 // `limit: 0` truncates to no rows — an invisible widget, almost
1709 // certainly a typo. Omit `limit` for "all rows" (CodeRabbit).
1710 if r.limit == Some(0) {
1711 return Err(format!(
1712 "{at}.render.limit must be >= 1 (omit it to keep all rows)"
1713 ));
1714 }
1715 }
1716 RenderKind::Gauge => {
1717 // Either a precomputed `value` ratio, or a `num`/`den` pair —
1718 // exactly one of the two forms.
1719 match (given(&r.value), given(&r.num), given(&r.den)) {
1720 (true, false, false) => {}
1721 (false, true, true) => {}
1722 _ => {
1723 return Err(format!(
1724 "{at}.render for kind=gauge needs either `value` (a ratio) or both `num` and `den`"
1725 ));
1726 }
1727 }
1728 }
1729 }
1730 Ok(())
1731}
1732
1733/// A standalone declarative read/aggregation for the Analytics page (#743).
1734///
1735/// A **view** aggregates stored fleet data (`obs_events`, …) without an
1736/// `execute` or a schedule — unlike a [`Manifest`] it only declares
1737/// [`AggregateWidget`]s. (The first line is concise on purpose: `schemars`
1738/// uses it as the generated schema's `title`.) The backend reads views from
1739/// `BUCKET_VIEWS` at
1740/// query time and merges their widgets with the co-located `aggregate:`
1741/// hints on jobs, so a cross-cutting dashboard (one that charts events
1742/// emitted by several other jobs / the agent) has a home that doesn't need
1743/// a noop job carrier. Stored JSON in `BUCKET_VIEWS`, keyed by `id`.
1744#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1745pub struct View {
1746 /// Stable identifier (the KV key). Required, validated non-empty.
1747 pub id: String,
1748 /// Optional human description shown on the Views admin page.
1749 #[serde(default, skip_serializing_if = "Option::is_none")]
1750 pub description: Option<String>,
1751 /// The `obs_events` aggregate widgets this view contributes to the
1752 /// Analytics page. Optional since PR3 — a view may instead (or also)
1753 /// carry [`sql_widgets`](View::sql_widgets); a view must have at least one
1754 /// widget across the two lists.
1755 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1756 pub widgets: Vec<AggregateWidget>,
1757 /// #vuln-roadmap PR3: SQL-backed, materialized widgets — raw read-only SQL
1758 /// over the projector tables (inventory/feeds/…) mapped to a visual. This
1759 /// is how a correlation dashboard (vulnerability / EOL / license) is
1760 /// expressed as config. See [`SqlWidget`].
1761 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1762 pub sql_widgets: Vec<SqlWidget>,
1763 /// Free-form operator taxonomy (same role as [`Manifest::tags`]).
1764 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1765 pub tags: Vec<String>,
1766 /// GitOps provenance (#678), stamped by `kanade view create` from the
1767 /// source YAML's Git context — same as [`Manifest::origin`].
1768 #[serde(default, skip_serializing_if = "Option::is_none")]
1769 pub origin: Option<RepoOrigin>,
1770}
1771
1772/// True if `id` is a safe resource identifier — non-empty and only
1773/// `[A-Za-z0-9._-]`. A view `id` becomes a NATS KV key *and* a URL path
1774/// segment (`/api/views/{id}`), so this blocks `/`, `..`, whitespace and
1775/// other characters that would break the KV key or let a CLI arg wander
1776/// the URL space. (#743 / #744 follow-up — a deliberately small charset
1777/// rather than the looser set NATS technically allows.)
1778pub fn is_valid_resource_id(id: &str) -> bool {
1779 !id.is_empty()
1780 && id
1781 .chars()
1782 .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-')
1783}
1784
1785impl View {
1786 pub fn validate(&self) -> Result<(), String> {
1787 if !is_valid_resource_id(self.id.trim()) {
1788 return Err(
1789 "view.id must be non-empty and only [A-Za-z0-9._-] (it's a KV key + URL segment)"
1790 .to_string(),
1791 );
1792 }
1793 // A view must contribute at least one widget across the two lists;
1794 // `validate_aggregate_widgets` rejects an empty `widgets` on its own,
1795 // so only call it when that list is non-empty (a pure-SQL view is
1796 // valid with an empty `widgets`).
1797 if self.widgets.is_empty() && self.sql_widgets.is_empty() {
1798 return Err(
1799 "view must declare at least one widget (`widgets:` and/or `sql_widgets:`)"
1800 .to_string(),
1801 );
1802 }
1803 if !self.widgets.is_empty() {
1804 validate_aggregate_widgets(&self.widgets, "widgets")?;
1805 }
1806 validate_sql_widgets(&self.sql_widgets, "sql_widgets")?;
1807 for tag in &self.tags {
1808 if tag.trim().is_empty() {
1809 return Err("tags must not contain empty entries".to_string());
1810 }
1811 }
1812 Ok(())
1813 }
1814}
1815
1816/// Issue #246 — `emit:` manifest block for jobs whose stdout is
1817/// NDJSON observability events (one `ObsEvent` per line). Parallel
1818/// to `inventory:` but for the append-only timeline pipeline; see
1819/// `Manifest::emit` for the full contract.
1820#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1821pub struct EmitConfig {
1822 /// What kind of payload the agent should expect on stdout. Only
1823 /// `events` is defined today (parses each non-empty line as
1824 /// `ObsEvent` and publishes on `obs.<pc_id>`); future variants
1825 /// (e.g. metrics streams, structured trace events) plug in here.
1826 #[serde(rename = "type")]
1827 pub kind: EmitKind,
1828 /// Operator hint for where the script keeps its own state — the
1829 /// watermark file the PowerShell / sh body reads + writes
1830 /// between runs so it only emits NEW events since the last
1831 /// poll. The agent doesn't read this; it's documentation that
1832 /// the SPA (and `kanade job edit`) can surface to operators
1833 /// reviewing the manifest. Optional; the script is allowed to
1834 /// keep state anywhere (registry, env, etc.) — the field's
1835 /// presence makes the convention discoverable.
1836 #[serde(default, skip_serializing_if = "Option::is_none")]
1837 pub watermark_path: Option<String>,
1838}
1839
1840/// `emit.type` enum. Lowercase serde so manifests read
1841/// `type: events` rather than `Events`.
1842#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1843#[serde(rename_all = "lowercase")]
1844pub enum EmitKind {
1845 /// Per-line `ObsEvent` JSON. Agent parses + publishes on
1846 /// `obs.<pc_id>`, drops the stdout from the resulting
1847 /// `ExecResult`.
1848 Events,
1849}
1850
1851/// v0.31 / #40: declarative "flatten this JSON array into a real
1852/// SQLite table" spec on an inventory manifest. The projector
1853/// creates the table on first registration (CREATE TABLE IF NOT
1854/// EXISTS + indexes) and writes a row per element of
1855/// `payload[field]` on every result, scoped by (pc_id, job_id) so
1856/// each PC's rows replace cleanly without a per-PC schema.
1857#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1858pub struct ExplodeSpec {
1859 /// JSON array key under the payload to explode. E.g. `"apps"`
1860 /// for `payload: { apps: [{...}, {...}] }`.
1861 pub field: String,
1862 /// Derived SQLite table name. Operators choose this — pick
1863 /// something namespaced + stable (`inventory_sw_apps`, not
1864 /// `apps`) so multiple inventory manifests don't collide on a
1865 /// generic name.
1866 pub table: String,
1867 /// Element-level fields that uniquely identify a row inside one
1868 /// PC's payload. The full PK is `(pc_id, job_id) + these
1869 /// columns`. Required — operators must think about uniqueness
1870 /// (e.g. `["name", "source"]` for installed apps because the
1871 /// same name appears in multiple uninstall hives).
1872 ///
1873 /// v0.31 / #41: same tuple drives history identity. When
1874 /// `track_history` is on, the projector serialises these
1875 /// fields' values into `inventory_history.identity_json` for
1876 /// every change event, so queries like "every PC that ever
1877 /// installed Chrome (any source)" filter on identity_json
1878 /// content without a per-manifest schema.
1879 pub primary_key: Vec<String>,
1880 /// Per-element fields that become columns in the derived table.
1881 pub columns: Vec<ExplodeColumn>,
1882 /// v0.31 / #41: when true (default false), the projector
1883 /// diffs each PC's incoming payload against the prior rows
1884 /// for the same (pc_id, job_id) BEFORE the DELETE-then-INSERT
1885 /// replace, and writes added / removed / changed events into
1886 /// `inventory_history`. Lets operators answer time-dimension
1887 /// questions ("when did Chrome 120 first appear on PC X?",
1888 /// "what's the Win 11 23H2 rollout curve") without storing
1889 /// per-scan snapshots. Off by default so operators opt in
1890 /// per-spec — history has a real storage cost on long-lived
1891 /// deployments (mitigated by the 90-day default retention
1892 /// sweeper, see `cleanup` module).
1893 #[serde(default)]
1894 pub track_history: bool,
1895}
1896
1897/// One column in an [`ExplodeSpec`]'s derived table.
1898#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1899pub struct ExplodeColumn {
1900 /// JSON key under each array element. Becomes the column name
1901 /// in the derived SQLite table — we don't rename.
1902 pub field: String,
1903 /// SQLite affinity: `"text"` (default), `"integer"`, `"real"`.
1904 /// Storage maps directly via `sqlx::query.bind(...)`; type
1905 /// mismatches at INSERT-time fail loudly rather than silently
1906 /// dropping the row.
1907 #[serde(default, skip_serializing_if = "Option::is_none")]
1908 #[serde(rename = "type")]
1909 pub kind: Option<String>,
1910 /// When true, the projector creates a `CREATE INDEX` on this
1911 /// column at table-creation time. Boost for the common-filter
1912 /// columns (`name`, `version`) — operators mark them
1913 /// explicitly, the projector won't guess.
1914 #[serde(default)]
1915 pub index: bool,
1916}
1917
1918/// #vuln-roadmap: one declarative **external-data feed** on a `feed:`
1919/// manifest — see [`Manifest::feed`]. Unlike inventory [`ExplodeSpec`]
1920/// (keyed per `(pc_id, job_id)`), a feed is GLOBAL fleet-wide reference
1921/// data: the controller-tier job's script fetches + shapes it, prints the
1922/// array under [`field`](FeedSpec::field) inside a `#KANADE-FEED-BEGIN/END`
1923/// fence, and the projector REPLACES that feed's rows wholesale in the
1924/// shared `feeds` table keyed `(feed_id, item_id)`. The full element JSON
1925/// lands in a `data` column, so a `view:` SQL `json_extract`s whatever
1926/// shape the feed carries — no per-feed schema, no dynamic DDL. One
1927/// manifest may declare several feeds.
1928#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1929pub struct FeedSpec {
1930 /// Stable feed identifier — the `feed_id` partition in the shared
1931 /// `feeds` table. Operators choose this; namespace it (`cisa-kev`,
1932 /// `endoflife-windows`) so feeds don't collide. A new result for the
1933 /// same id replaces that partition wholesale.
1934 pub id: String,
1935 /// JSON array key under the (fenced) payload to ingest. E.g.
1936 /// `"vulnerabilities"` for `{ vulnerabilities: [{...}, {...}] }`.
1937 pub field: String,
1938 /// Element-level field(s) whose values uniquely identify an item
1939 /// within the feed — they form the `item_id` key (joined for a
1940 /// composite key). Required: operators must think about uniqueness
1941 /// (e.g. `["cveID"]` for CISA KEV). An element missing any of these is
1942 /// skipped (it has no stable identity).
1943 pub primary_key: Vec<String>,
1944}
1945
1946#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1947pub struct DisplayField {
1948 /// Top-level key in the stdout JSON.
1949 pub field: String,
1950 /// Human-readable column header.
1951 pub label: String,
1952 /// Optional render hint — `"number"`, `"bytes"`, `"timestamp"`,
1953 /// or `"table"` (#39). Defaults to plain text rendering on the
1954 /// SPA side. `"table"` expects the field's value to be a JSON
1955 /// array of objects and renders a nested sub-table on the
1956 /// per-PC detail page using `columns` as the schema; the fleet
1957 /// summary view falls back to showing the row count for
1958 /// `"table"` cells so the wide list stays compact.
1959 #[serde(default, skip_serializing_if = "Option::is_none")]
1960 #[serde(rename = "type")]
1961 pub kind: Option<String>,
1962 /// v0.30 / #39: when `kind == "table"`, the SPA renders the
1963 /// field's value (an array of objects like
1964 /// `disks: [{ device_id, size_bytes, ... }]`) as a nested
1965 /// sub-table using these columns. Each column is itself a
1966 /// `DisplayField`, so the nested cells reuse the same render
1967 /// hints (`bytes`, `number`, `timestamp`) — no parallel format
1968 /// pipeline. Ignored for any other `kind`.
1969 #[serde(default, skip_serializing_if = "Option::is_none")]
1970 pub columns: Option<Vec<DisplayField>>,
1971}
1972
1973#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1974pub struct Rollout {
1975 #[serde(default)]
1976 pub strategy: RolloutStrategy,
1977 pub waves: Vec<Wave>,
1978}
1979
1980#[derive(
1981 Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
1982)]
1983#[serde(rename_all = "lowercase")]
1984pub enum RolloutStrategy {
1985 #[default]
1986 Wave,
1987}
1988
1989#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1990pub struct Wave {
1991 pub group: String,
1992 /// humantime delay measured from the deploy's publish time. wave[0]
1993 /// typically has "0s"; subsequent waves use minutes / hours.
1994 pub delay: String,
1995}
1996
1997#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default)]
1998pub struct Target {
1999 #[serde(default)]
2000 pub groups: Vec<String>,
2001 #[serde(default)]
2002 pub pcs: Vec<String>,
2003 #[serde(default)]
2004 pub all: bool,
2005}
2006
2007impl Target {
2008 /// At least one of all / groups / pcs is set.
2009 pub fn is_specified(&self) -> bool {
2010 self.all || !self.groups.is_empty() || !self.pcs.is_empty()
2011 }
2012
2013 /// Whether a PC (its `pc_id` + group membership) falls in this target:
2014 /// `all`, or the pc is listed, or it belongs to a listed group. Used
2015 /// by the agent to scope `client.visible_to` (#816). An unspecified
2016 /// target matches nobody (callers should treat "no target" as
2017 /// "visible to all" before calling this).
2018 pub fn matches(&self, pc_id: &str, groups: &[String]) -> bool {
2019 self.all
2020 || self.pcs.iter().any(|p| p == pc_id)
2021 || self.groups.iter().any(|g| groups.contains(g))
2022 }
2023}
2024
2025#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2026pub struct Execute {
2027 pub shell: ExecuteShell,
2028 /// Inline script body. Mutually exclusive with [`script_file`]
2029 /// and [`script_object`]; exactly one of the three must be set
2030 /// (enforced by [`Execute::validate_script_source`] at the
2031 /// write-side parse boundaries — `kanade job create` and
2032 /// `POST /api/jobs`).
2033 ///
2034 /// Empty string is treated as **unset** so operators can swap
2035 /// to a `script_file:` / `script_object:` alternative just by
2036 /// commenting out the body, without having to also drop the
2037 /// `script:` key entirely.
2038 ///
2039 /// [`script_file`]: Self::script_file
2040 /// [`script_object`]: Self::script_object
2041 #[serde(default, skip_serializing_if = "Option::is_none")]
2042 pub script: Option<String>,
2043 /// Repo-local file path resolved by the operator-side CLI at
2044 /// `kanade job create` time. The CLI reads the file, slots its
2045 /// contents into `script`, and clears this field before
2046 /// POSTing — so the backend / agents never see `script_file`
2047 /// in stored manifests. SPEC §2.4.1.
2048 ///
2049 /// The resolver shipped with #210: `kanade job create` /
2050 /// `kanade job validate` inline this field end-to-end. Because
2051 /// resolution is CLI-side (it needs the operator's filesystem),
2052 /// `POST /api/jobs` rejects a manifest that still carries it
2053 /// (#918) — a stored `script_file` job would 400 at every exec.
2054 /// Inline the script or use `script_object` when writing through
2055 /// the API / SPA editor.
2056 #[serde(default, skip_serializing_if = "Option::is_none")]
2057 pub script_file: Option<String>,
2058 /// Object Store reference (`<name>/<version>`) into the
2059 /// `scripts` bucket (`OBJECT_SCRIPTS`). Agents fetch the body
2060 /// at Execute time via `/api/script-objects/{name}/{version}`
2061 /// and cache it locally. SPEC §2.4.1.
2062 ///
2063 /// Fully wired (#210/#211): the backend resolves the digest at
2064 /// exec submission (`api::exec::resolve_script_source`), the agent
2065 /// fetches + sha-verifies + caches the body (`script_cache`), and
2066 /// `kanade script` CRUDs the store. Unlike `script_file:` (inlined
2067 /// CLI-side, git-managed), this keeps the body in versioned,
2068 /// digest-pinned object storage — the ops-managed counterpart.
2069 #[serde(default, skip_serializing_if = "Option::is_none")]
2070 pub script_object: Option<String>,
2071 /// humantime duration string (e.g. "30s", "10m"). Script-intrinsic
2072 /// — represents how long this script reasonably takes to run.
2073 pub timeout: String,
2074 /// Token + session combination the agent uses to launch the
2075 /// script (v0.21). Default = [`RunAs::System`] (Session 0,
2076 /// LocalSystem privileges, no GUI) — matches pre-v0.21 behavior.
2077 #[serde(default)]
2078 pub run_as: RunAs,
2079 /// Working directory for the spawned child (v0.21.1). When
2080 /// unset, the child inherits the agent's cwd — on Windows that
2081 /// means `%SystemRoot%\System32` for the prod service, which is
2082 /// almost never what operators actually want. Use an absolute
2083 /// path; relative paths are passed through to the OS verbatim.
2084 /// `%PROGRAMDATA%` works for `run_as: system`; for `run_as: user`
2085 /// you'd want `%USERPROFILE%` (but expansion happens in the
2086 /// shell, so write `$env:USERPROFILE` for PowerShell, or set
2087 /// it via teravars before `kanade job create`).
2088 #[serde(default, skip_serializing_if = "Option::is_none")]
2089 pub cwd: Option<String>,
2090}
2091
2092impl Execute {
2093 /// Treat an empty — or whitespace-only (#918) — `script:` body as
2094 /// "intentionally unset". Operators commenting out a block-scalar
2095 /// tend to leave the key behind, and failing the validator on
2096 /// `script: ""` would surprise them; a body of blank lines can't
2097 /// be a real script either, only a commented-out one, and letting
2098 /// it count as "set" shipped a validated do-nothing job.
2099 fn has_inline_script(&self) -> bool {
2100 matches!(&self.script, Some(s) if !s.trim().is_empty())
2101 }
2102
2103 /// Enforce that exactly one of `script` / `script_file` /
2104 /// `script_object` is set. Called at the write-side parse
2105 /// boundaries (CLI `kanade job create` + backend
2106 /// `POST /api/jobs`) so ambiguous YAML is rejected before it
2107 /// reaches the JOBS KV. Read paths (projector, agent
2108 /// scheduler, list endpoints) skip this check — they only ever
2109 /// see what the write path already validated.
2110 pub fn validate_script_source(&self) -> Result<(), String> {
2111 // #918: a blank-but-present alternate source is a typo, not a
2112 // choice — `script_file: ""` used to count as "set", pass the
2113 // exactly-one check, and only fail at use time (the CLI reads
2114 // a file named ""; a stored blank script_object 404s on every
2115 // exec). Reject it with the field named. Inline `script` keeps
2116 // its documented empty-means-unset semantics instead — see
2117 // `has_inline_script`.
2118 if matches!(&self.script_file, Some(s) if s.trim().is_empty()) {
2119 return Err(
2120 "execute.script_file must not be blank when set (drop the key to use \
2121 another source)"
2122 .into(),
2123 );
2124 }
2125 if matches!(&self.script_object, Some(s) if s.trim().is_empty()) {
2126 return Err(
2127 "execute.script_object must not be blank when set (drop the key to use \
2128 another source)"
2129 .into(),
2130 );
2131 }
2132 let inline = self.has_inline_script();
2133 let file = self.script_file.is_some();
2134 let obj = self.script_object.is_some();
2135 let set = [inline, file, obj].into_iter().filter(|b| *b).count();
2136 match set {
2137 1 => {}
2138 0 => {
2139 return Err(
2140 "execute: one of `script`, `script_file`, `script_object` must be set".into(),
2141 );
2142 }
2143 _ => {
2144 return Err(format!(
2145 "execute: only one of `script` / `script_file` / `script_object` may be set \
2146 (got script={inline}, script_file={file}, script_object={obj})"
2147 ));
2148 }
2149 }
2150 // #918: a script_object ref is `<name>/<version>` — the agent
2151 // fetches the body via `/api/script-objects/{name}/{version}`
2152 // and the backend uses the ref *verbatim* as the Object Store
2153 // key (`resolve_script_source`), so each half must be a
2154 // well-formed resource id: exactly one slash, and both halves
2155 // [A-Za-z0-9._-]. `is_valid_resource_id` also rejects a half
2156 // that's blank OR merely whitespace-padded (`"foo/bar "`) —
2157 // padding survives a JSON POST body (unlike a YAML plain
2158 // scalar) and would 404 on every exec (gemini/claude #943).
2159 if let Some(obj_ref) = self.script_object.as_deref() {
2160 let parts: Vec<&str> = obj_ref.split('/').collect();
2161 if parts.len() != 2 || parts.iter().any(|p| !is_valid_resource_id(p)) {
2162 return Err(format!(
2163 "execute.script_object must be `<name>/<version>` with each half \
2164 [A-Za-z0-9._-] (got '{obj_ref}'); publish bodies with \
2165 `kanade script publish <name> <version>`"
2166 ));
2167 }
2168 }
2169 Ok(())
2170 }
2171}
2172
2173/// Job-generic post-step hook (see [`Manifest::finalize`]). Runs after
2174/// the main `execute:` script (and the collect upload) on a clean exit,
2175/// with the step's structured result injected via an environment
2176/// variable. P1 supports an inline `script:` only — `script_file:` /
2177/// `script_object:` are follow-ups.
2178#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2179pub struct FinalizeSpec {
2180 pub shell: ExecuteShell,
2181 /// Inline script body (required; inline-only in P1).
2182 pub script: String,
2183 /// humantime duration string (e.g. `"60s"`, `"5m"`). Defaults to
2184 /// `60s` when unset.
2185 #[serde(default = "default_finalize_timeout")]
2186 pub timeout: String,
2187 /// Token + session combination, like [`Execute::run_as`]. Defaults
2188 /// to [`RunAs::System`].
2189 #[serde(default)]
2190 pub run_as: RunAs,
2191 /// Working directory for the hook child, like [`Execute::cwd`].
2192 #[serde(default, skip_serializing_if = "Option::is_none")]
2193 pub cwd: Option<String>,
2194 /// #965: for a `collect:` job, run this hook once per uploaded
2195 /// bundle (with a single-bundle `KANADE_COLLECT_RESULT`) as each
2196 /// bundle uploads, instead of once after the whole set. Lets an
2197 /// interrupted collect still clean up the days it managed to
2198 /// upload (partial progress sticks), breaking the
2199 /// offline-before-finalize backlog spiral.
2200 ///
2201 /// **Opt-in** (default `false` = one call after all bundles, the
2202 /// established contract) because per-bundle changes the hook's
2203 /// payload (all → one) and invocation count (1 → N), which would
2204 /// break a hook written for the all-at-once assumption (cross-bundle
2205 /// aggregation, once-only side effects, all-or-nothing). Only valid
2206 /// with a `collect:` hint — [`Manifest::validate`] rejects it
2207 /// otherwise, since a non-collect finalize has no bundles to iterate.
2208 #[serde(default)]
2209 pub on_each_bundle: bool,
2210}
2211
2212/// Default `finalize.timeout` when the operator omits it.
2213fn default_finalize_timeout() -> String {
2214 "60s".to_string()
2215}
2216
2217impl FinalizeSpec {
2218 /// Lower to the wire form forwarded onto a [`Command`]. The timeout
2219 /// parse falls back to 60s — [`Manifest::validate`] already rejects
2220 /// an unparseable value at create time, so the fire path uses a safe
2221 /// default rather than failing (mirrors
2222 /// [`CollectHint::max_size_bytes`]). A sub-second timeout floors at
2223 /// 1s for the same reason `build_command` does.
2224 pub fn lower(&self) -> FinalizeCommand {
2225 let timeout_secs = humantime::parse_duration(&self.timeout)
2226 .map(|d| d.as_secs().max(1))
2227 .unwrap_or(60);
2228 FinalizeCommand {
2229 shell: self.shell.into(),
2230 script: self.script.clone(),
2231 timeout_secs,
2232 run_as: self.run_as,
2233 cwd: self.cwd.clone(),
2234 on_each_bundle: self.on_each_bundle,
2235 }
2236 }
2237}
2238
2239impl Manifest {
2240 /// Cross-field semantic checks that don't fit into pure serde
2241 /// derive. Currently delegates to
2242 /// [`Execute::validate_script_source`] — see that method's
2243 /// docs for the rationale on which call sites should run this.
2244 pub fn validate(&self) -> Result<(), String> {
2245 self.execute.validate_script_source()?;
2246 // Fail CLOSED on an unrecognised execution tier. `#[serde(other)]`
2247 // turns a typo (`tier: controler`) or a future tier into
2248 // `Tier::Unknown`; without this check the controller gate would
2249 // fall back to normal endpoint dispatch, so an operator who *meant*
2250 // to confine a job to the controller tier would silently get
2251 // fleet-wide dispatch (CodeRabbit #905). Rejecting it at the write
2252 // boundary surfaces the typo at `job create`, and — since
2253 // `exec_manifest` re-validates — a hand-poked KV manifest can't slip
2254 // a controller-tier job onto endpoints either.
2255 if matches!(self.tier, Some(Tier::Unknown)) {
2256 return Err(
2257 "tier: unrecognised execution tier — use `endpoint` or `controller` \
2258 (this is a typo, or a tier a newer kanade supports that this backend does not)"
2259 .to_string(),
2260 );
2261 }
2262 // #vuln-roadmap: a `feed:` spec drives the global `feeds`
2263 // projection. id / item_id are stored as *values* (the `feeds`
2264 // table is fixed-schema — no identifier splicing), but blank
2265 // values are silent projection bugs: a blank id collides every
2266 // feed under "", a blank field never matches the payload array,
2267 // and an empty primary_key yields no item_id (every row dropped).
2268 // Reject them at the write boundary so `kanade job create` surfaces
2269 // the typo instead of producing an empty/garbled feed at run time.
2270 let mut seen_feed_ids: Vec<&str> = Vec::new();
2271 for spec in &self.feed {
2272 let id = spec.id.trim();
2273 if id.is_empty() {
2274 return Err("feed.id must not be empty".to_string());
2275 }
2276 if spec.field.trim().is_empty() {
2277 return Err(format!("feed '{id}' field must not be empty"));
2278 }
2279 if spec.primary_key.is_empty() {
2280 return Err(format!("feed '{id}' needs at least one primary_key field"));
2281 }
2282 if spec.primary_key.iter().any(|k| k.trim().is_empty()) {
2283 return Err(format!(
2284 "feed '{id}' primary_key must not contain blank entries"
2285 ));
2286 }
2287 // Two specs sharing an id both target the same `feeds`
2288 // partition and would clobber each other on every run —
2289 // reject the ambiguity rather than let last-write-wins.
2290 if seen_feed_ids.contains(&id) {
2291 return Err(format!("feed id '{id}' is declared more than once"));
2292 }
2293 seen_feed_ids.push(id);
2294 }
2295 // A `feed:` job fetches external data and MUST run on the trusted
2296 // controller tier — the dispatch guard (`requires_controller`) treats
2297 // a non-empty `feed:` as implying `controller`. An explicit
2298 // `tier: endpoint` contradicts that intent; reject it rather than
2299 // silently overriding, so the operator can't believe a feed runs on
2300 // endpoints. Omitting `tier:` (the default) is fine — the implication
2301 // confines it; `tier: controller` is the redundant-but-explicit form.
2302 if !self.feed.is_empty() && matches!(self.tier, Some(Tier::Endpoint)) {
2303 return Err(
2304 "feed: requires the controller tier — remove `tier: endpoint` (a feed: job \
2305 fetches external data and is confined to the controller_group)"
2306 .to_string(),
2307 );
2308 }
2309 // A present-but-empty finalize script is an invisible no-op
2310 // (the hook would run an empty body); reject it at the write
2311 // boundary. Inline-only in P1, so `script` is the sole source.
2312 if let Some(finalize) = &self.finalize {
2313 if finalize.script.trim().is_empty() {
2314 return Err("finalize.script must not be empty".to_string());
2315 }
2316 // Reject an unparseable timeout at the write boundary so the
2317 // operator sees the error at `job create` rather than getting
2318 // a silent fire-time fallback (`FinalizeSpec::lower` floors to
2319 // 60s, which would otherwise mask a typo).
2320 if humantime::parse_duration(&finalize.timeout).is_err() {
2321 return Err(format!(
2322 "finalize.timeout '{}' is not a valid duration",
2323 finalize.timeout
2324 ));
2325 }
2326 // Disallow cmd for finalize: the agent injects the result JSON
2327 // into the hook's environment, and cmd.exe quoting doesn't
2328 // nest — JSON's `"` plus shell metacharacters in a collected
2329 // path/key could break out into command injection at the
2330 // agent's (often LocalSystem) privilege. PowerShell's
2331 // single-quote escaping is safe, and finalize hooks are
2332 // PowerShell by convention anyway.
2333 if finalize.shell == ExecuteShell::Cmd {
2334 return Err(
2335 "finalize.shell: cmd is not supported for finalize hooks (shell-injection \
2336 risk when the result JSON is injected into the environment); use powershell"
2337 .to_string(),
2338 );
2339 }
2340 // #965: per-bundle finalize only means anything for a
2341 // collect: job — a non-collect finalize has no bundles to
2342 // iterate (it runs once after the script). Reject the
2343 // combination at the write boundary so a confused operator
2344 // is told rather than silently getting a no-op.
2345 if finalize.on_each_bundle && self.collect.is_none() {
2346 return Err(
2347 "finalize.on_each_bundle: true requires a collect: hint — a non-collect \
2348 finalize has no bundles to iterate (it runs once after the script)"
2349 .to_string(),
2350 );
2351 }
2352 }
2353 // Stdout-format compatibility (#821). `inventory:` / `check:` /
2354 // `collect:` now COMPOSE: each reads its own `#KANADE-<KIND>-
2355 // BEGIN/END`-fenced JSON block from stdout, so a single job can
2356 // project inventory facts, drive a Health-tab check, AND collect
2357 // files in one run. (A single-hint job may still skip the fence;
2358 // a multi-hint job must fence each block.)
2359 //
2360 // `emit:` remains the exception — its stdout is line-delimited
2361 // NDJSON consumed whole and then omitted from the result — so it
2362 // can't share stdout with any fenced hint. `feed:` is another fenced
2363 // stdout consumer (`#KANADE-FEED`), so it belongs in this exclusion
2364 // too: with `emit:` present the projector never sees the feed's fence
2365 // (CodeRabbit).
2366 if self.emit.is_some()
2367 && (self.inventory.is_some()
2368 || self.check.is_some()
2369 || self.collect.is_some()
2370 || !self.feed.is_empty())
2371 {
2372 return Err(
2373 "`emit:` is incompatible with `inventory:` / `check:` / `collect:` / `feed:` — \
2374 emit's stdout is NDJSON timeline events (consumed whole and omitted from the \
2375 result), while the others read fenced JSON blocks from stdout"
2376 .to_string(),
2377 );
2378 }
2379 // A check's `name` is the Health-tab row id (React key); the
2380 // field names tell the agent where to read status/detail.
2381 // An empty value is an invisible runtime bug, and the serde
2382 // defaults don't guard an operator who writes `status_field:
2383 // ""` explicitly — reject all three here.
2384 if let Some(check) = &self.check {
2385 for (label, value) in [
2386 ("check.name", &check.name),
2387 ("check.status_field", &check.status_field),
2388 ("check.detail_field", &check.detail_field),
2389 ] {
2390 if value.trim().is_empty() {
2391 return Err(format!("{label} must not be empty"));
2392 }
2393 }
2394 // A present-but-blank `troubleshoot` is a broken
2395 // remediation job id (the "修復する" button would target
2396 // an empty manifest id) — reject it too.
2397 if let Some(troubleshoot) = &check.troubleshoot {
2398 if troubleshoot.trim().is_empty() {
2399 return Err("check.troubleshoot must not be empty when set".to_string());
2400 }
2401 }
2402 // A present-but-blank `label` would render an empty row
2403 // title on the Health tab / Compliance page — reject it so
2404 // the slug fallback only ever kicks in when label is absent.
2405 if let Some(label) = &check.label {
2406 if label.trim().is_empty() {
2407 return Err("check.label must not be empty when set".to_string());
2408 }
2409 }
2410 if let Some(alert) = &check.alert {
2411 // An alert that names no recipient is a silent no-op.
2412 if !alert.notify_user && alert.notify_groups.is_empty() {
2413 return Err("check.alert must set notify_user and/or notify_groups".to_string());
2414 }
2415 if alert.title.trim().is_empty() {
2416 return Err("check.alert.title must not be empty".to_string());
2417 }
2418 // `on: []` would never fire; an empty group name resolves to
2419 // a malformed `notifications.group.` subject.
2420 if alert.on.is_empty() {
2421 return Err("check.alert.on must list at least one status".to_string());
2422 }
2423 if alert.notify_groups.iter().any(|g| g.trim().is_empty()) {
2424 return Err("check.alert.notify_groups must not contain blanks".to_string());
2425 }
2426 // Email is addressed via group_contacts (group → email), so
2427 // there must be a group to map. notify_user has no email.
2428 if alert.email && alert.notify_groups.is_empty() {
2429 return Err(
2430 "check.alert.email requires notify_groups (email is addressed per group, not per user)"
2431 .to_string(),
2432 );
2433 }
2434 // The alert rides the `check_status` projection, which only
2435 // runs for `fleet: true`.
2436 if !check.fleet {
2437 return Err(
2438 "check.alert requires fleet: true (the alert rides the compliance projection)"
2439 .to_string(),
2440 );
2441 }
2442 }
2443 }
2444 // #291: a `client:` job is rendered in the Client App's
2445 // catalog (`jobs.list` → `jobs.execute`). serde already makes
2446 // `name` + `category` required at parse time; the only gap is
2447 // a present-but-blank `name`, which would render an empty row
2448 // title — reject it like the other display-id fields.
2449 if let Some(client) = &self.client {
2450 if client.name.trim().is_empty() {
2451 return Err("client.name must not be empty".to_string());
2452 }
2453 // #792: category is a free-form key now, so a blank one would
2454 // group the job under an empty tab — reject it like `name`.
2455 if client.category.trim().is_empty() {
2456 return Err("client.category must not be empty".to_string());
2457 }
2458 // Optional display fields, when present, must be
2459 // meaningful: a blank `description` renders an empty
2460 // subtitle and a blank `icon` is a dangling lucide name.
2461 // Same present-but-blank guard the `check:` block applies
2462 // to its optional `troubleshoot` id.
2463 for (label, value) in [
2464 ("client.description", &client.description),
2465 ("client.icon", &client.icon),
2466 ("client.category_label", &client.category_label),
2467 ("client.category_icon", &client.category_icon),
2468 ] {
2469 if let Some(v) = value {
2470 if v.trim().is_empty() {
2471 return Err(format!("{label} must not be empty when set"));
2472 }
2473 }
2474 }
2475 // #816: a present-but-empty `visible_to` (no all/groups/pcs)
2476 // would hide the job from everyone in the Client App — almost
2477 // certainly a mistake. Require at least one selector; omit the
2478 // whole block to mean "visible to all".
2479 if let Some(t) = &client.visible_to {
2480 if !t.is_specified() {
2481 return Err(
2482 "client.visible_to must set at least one of all / groups / pcs (omit it for all PCs)"
2483 .to_string(),
2484 );
2485 }
2486 }
2487 // show_when: a dynamic display gate keyed on a check result. A
2488 // malformed check slug matches nothing and an empty status list
2489 // matches nothing — both would silently hide the job forever,
2490 // so reject them at create time rather than at a confused
2491 // "why isn't my job showing?" later. The slug must be a clean
2492 // resource id (same charset checks/jobs use): a typo with spaces
2493 // or punctuation can never match a real check name, so catch it
2494 // here instead of failing closed at runtime. (Whether the slug
2495 // names a check that actually EXISTS can't be checked here —
2496 // checks are keyed by name across manifests — so a valid-but-
2497 // unknown slug stays a runtime miss = hidden, the documented
2498 // fail-closed behavior.)
2499 if let Some(sw) = &client.show_when {
2500 if !is_valid_resource_id(sw.check.trim()) {
2501 return Err(
2502 "client.show_when.check must be a non-empty check slug ([A-Za-z0-9._-])"
2503 .to_string(),
2504 );
2505 }
2506 if sw.is.is_empty() {
2507 return Err(
2508 "client.show_when.is must list at least one check status".to_string()
2509 );
2510 }
2511 }
2512 // confirm: a present-but-blank custom message would render an
2513 // empty dialog title — reject it like the other display fields.
2514 // (A `confirm: false` / `enabled: false` with no message is fine:
2515 // the dialog is suppressed, so there's nothing to render.)
2516 if let Some(c) = &client.confirm {
2517 if let Some(msg) = &c.message {
2518 if msg.trim().is_empty() {
2519 return Err("client.confirm.message must not be empty when set".to_string());
2520 }
2521 }
2522 }
2523 }
2524 // #219: a `collect:` job's `name` heads the bundle on the SPA
2525 // Collect page (and the Client App row when paired with
2526 // `client:`), `files_field` tells the agent where to read the
2527 // path list, and `max_size` must be a parseable size so a typo
2528 // is caught at create time rather than silently capping the
2529 // bundle at the default on the fire path.
2530 if let Some(collect) = &self.collect {
2531 if collect.name.trim().is_empty() {
2532 return Err("collect.name must not be empty".to_string());
2533 }
2534 if collect.files_field.trim().is_empty() {
2535 return Err("collect.files_field must not be empty".to_string());
2536 }
2537 if let Some(description) = &collect.description {
2538 if description.trim().is_empty() {
2539 return Err("collect.description must not be empty when set".to_string());
2540 }
2541 }
2542 if let Some(max_size) = &collect.max_size {
2543 parse_size_bytes(max_size).map_err(|e| format!("collect.max_size: {e}"))?;
2544 }
2545 }
2546 // #720/#743: `aggregate:` is a pure read-spec (it never touches
2547 // stdout and is never sent to an agent), so it composes with every
2548 // other hint. The per-widget rules are shared with the standalone
2549 // `view` resource — see [`validate_aggregate_widgets`].
2550 if let Some(widgets) = &self.aggregate {
2551 validate_aggregate_widgets(widgets, "aggregate")?;
2552 }
2553 // A blank / whitespace-only tag is an invisible operator typo
2554 // that would render an empty filter chip on the Jobs page —
2555 // reject it like the other present-but-blank display fields.
2556 for tag in &self.tags {
2557 if tag.trim().is_empty() {
2558 return Err("tags must not contain empty entries".to_string());
2559 }
2560 }
2561 Ok(())
2562 }
2563}
2564
2565#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
2566#[serde(rename_all = "lowercase")]
2567pub enum ExecuteShell {
2568 Powershell,
2569 Cmd,
2570}
2571
2572impl From<ExecuteShell> for Shell {
2573 fn from(s: ExecuteShell) -> Self {
2574 match s {
2575 ExecuteShell::Powershell => Shell::Powershell,
2576 ExecuteShell::Cmd => Shell::Cmd,
2577 }
2578 }
2579}
2580
2581#[cfg(test)]
2582mod tests {
2583 use super::*;
2584
2585 #[test]
2586 fn inventory_payload_extracts_fenced_block() {
2587 // Readable message + fenced JSON → only the JSON, trimmed.
2588 let stdout = "Wi-Fi 設定を適用しました。\n\
2589 #KANADE-INVENTORY-BEGIN\n\
2590 {\"applied\": true}\n\
2591 #KANADE-INVENTORY-END\n";
2592 assert_eq!(inventory_payload(stdout), "{\"applied\": true}");
2593 }
2594
2595 #[test]
2596 fn inventory_payload_falls_back_to_whole_stdout() {
2597 // No fence (a plain inventory job) → whole stdout, trimmed.
2598 assert_eq!(
2599 inventory_payload(" {\"ram_gb\": 16}\n"),
2600 "{\"ram_gb\": 16}"
2601 );
2602 }
2603
2604 #[test]
2605 fn inventory_payload_handles_unterminated_fence() {
2606 // Closing marker missing (e.g. truncated) → everything after the
2607 // opener, trimmed.
2608 let stdout = "msg\n#KANADE-INVENTORY-BEGIN\n{\"a\": 1}";
2609 assert_eq!(inventory_payload(stdout), "{\"a\": 1}");
2610 }
2611
2612 #[test]
2613 fn inventory_payload_ignores_mid_line_sentinel() {
2614 // The marker echoed mid-line (not at a line start) must NOT be
2615 // treated as a fence — fall back to the whole stdout.
2616 let stdout = "see #KANADE-INVENTORY-BEGIN in the docs\nnot json";
2617 assert_eq!(inventory_payload(stdout), stdout.trim());
2618 }
2619
2620 #[test]
2621 fn fenced_payload_extracts_each_hint_block_independently() {
2622 // #821: one stdout carrying a user message + all three fenced
2623 // blocks — every consumer pulls only its own.
2624 let stdout = "\
2625done!
2626#KANADE-INVENTORY-BEGIN
2627{\"os\":\"win\"}
2628#KANADE-INVENTORY-END
2629#KANADE-CHECK-BEGIN
2630{\"status\":\"ok\"}
2631#KANADE-CHECK-END
2632#KANADE-COLLECT-BEGIN
2633{\"files\":[\"a\"]}
2634#KANADE-COLLECT-END
2635";
2636 assert_eq!(
2637 fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
2638 "{\"os\":\"win\"}"
2639 );
2640 assert_eq!(
2641 fenced_payload(stdout, CHECK_BLOCK_BEGIN, CHECK_BLOCK_END),
2642 "{\"status\":\"ok\"}"
2643 );
2644 assert_eq!(
2645 fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2646 "{\"files\":[\"a\"]}"
2647 );
2648 }
2649
2650 #[test]
2651 fn fenced_payload_falls_back_to_whole_stdout_without_fence() {
2652 // A single-hint job needs no fence — the whole (trimmed) stdout is
2653 // the payload.
2654 let stdout = " {\"files\":[\"a\"]} ";
2655 assert_eq!(
2656 fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2657 "{\"files\":[\"a\"]}"
2658 );
2659 }
2660
2661 #[test]
2662 fn fenced_payload_returns_empty_when_other_fences_present_but_mine_missing() {
2663 // Multi-hint output (inventory + check fenced) but the COLLECT
2664 // fence is missing — collect must NOT fall back to the whole
2665 // stdout (which holds the inventory/check blocks) and cross-parse
2666 // a sibling block; it gets "" → its JSON parse fails → no data.
2667 let stdout = "\
2668#KANADE-INVENTORY-BEGIN
2669{\"os\":\"win\"}
2670#KANADE-INVENTORY-END
2671#KANADE-CHECK-BEGIN
2672{\"status\":\"ok\"}
2673#KANADE-CHECK-END
2674";
2675 assert_eq!(
2676 fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2677 ""
2678 );
2679 // ...while the hints that DID fence still extract correctly.
2680 assert_eq!(
2681 fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
2682 "{\"os\":\"win\"}"
2683 );
2684 }
2685
2686 /// The example check-job + schedule YAMLs shipped under `configs/`
2687 /// must stay valid as the schema evolves (#290 PR-C). `include_str!`
2688 /// pins them at compile time so a breaking edit fails `cargo test`
2689 /// rather than only `kanade job create` at deploy time.
2690 #[test]
2691 fn example_check_job_yamls_parse_and_validate() {
2692 let jobs = [
2693 (
2694 "check-bitlocker",
2695 include_str!("../../../configs/jobs/check-bitlocker.yaml"),
2696 ),
2697 (
2698 "check-av-signature",
2699 include_str!("../../../configs/jobs/check-av-signature.yaml"),
2700 ),
2701 (
2702 "check-cert-expiry",
2703 include_str!("../../../configs/jobs/check-cert-expiry.yaml"),
2704 ),
2705 (
2706 "check-disk-space",
2707 include_str!("../../../configs/jobs/check-disk-space.yaml"),
2708 ),
2709 (
2710 "check-pending-reboot",
2711 include_str!("../../../configs/jobs/check-pending-reboot.yaml"),
2712 ),
2713 (
2714 "check-defender-rtp",
2715 include_str!("../../../configs/jobs/check-defender-rtp.yaml"),
2716 ),
2717 (
2718 "check-firewall",
2719 include_str!("../../../configs/jobs/check-firewall.yaml"),
2720 ),
2721 ];
2722 for (name, yaml) in jobs {
2723 let m: Manifest =
2724 serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} parse: {e}"));
2725 m.validate()
2726 .unwrap_or_else(|e| panic!("{name} validate: {e}"));
2727 let check = m
2728 .check
2729 .as_ref()
2730 .unwrap_or_else(|| panic!("{name} must carry a check: hint"));
2731 assert!(!check.name.trim().is_empty(), "{name} check.name empty");
2732 // These examples all read admin-only WMI / registry / netsh
2733 // state, so they run_as system. NOTE: that's a property of
2734 // these particular checks, NOT of the `check:` contract — a
2735 // check probing user-session state could run_as user.
2736 assert_eq!(
2737 m.execute.run_as,
2738 RunAs::System,
2739 "{name} should run_as system"
2740 );
2741 }
2742 }
2743
2744 /// The example user-invokable job YAMLs (#291) shipped under
2745 /// `configs/jobs/` must stay valid as the `client:` schema
2746 /// evolves. `include_str!` pins them at compile time so a breaking
2747 /// edit fails `cargo test`, not `kanade job create` at deploy.
2748 #[test]
2749 fn example_client_job_yamls_parse_and_validate() {
2750 let jobs = [
2751 (
2752 "fix-teams-cache",
2753 "troubleshoot",
2754 include_str!("../../../configs/jobs/fix-teams-cache.yaml"),
2755 ),
2756 (
2757 "chrome-update",
2758 "software_update",
2759 include_str!("../../../configs/jobs/chrome-update.yaml"),
2760 ),
2761 (
2762 "install-slack",
2763 "catalog",
2764 include_str!("../../../configs/jobs/install-slack.yaml"),
2765 ),
2766 (
2767 "fix-defender-rtp",
2768 "troubleshoot",
2769 include_str!("../../../configs/jobs/fix-defender-rtp.yaml"),
2770 ),
2771 // #792 custom category ("settings") + #809 message/inventory.
2772 (
2773 "example-power-plan",
2774 "settings",
2775 include_str!("../../../configs/jobs/example-power-plan.yaml"),
2776 ),
2777 // #792: diagnostics moved to its own "support" tab.
2778 (
2779 "collect-diagnostics",
2780 "support",
2781 include_str!("../../../configs/jobs/collect-diagnostics.yaml"),
2782 ),
2783 ];
2784 for (id, category, yaml) in jobs {
2785 let m: Manifest =
2786 serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
2787 m.validate()
2788 .unwrap_or_else(|e| panic!("{id} validate: {e}"));
2789 assert_eq!(m.id, id, "{id} id mismatch");
2790 let client = m
2791 .client
2792 .as_ref()
2793 .unwrap_or_else(|| panic!("{id} must carry a client: block"));
2794 assert!(!client.name.trim().is_empty(), "{id} client.name empty");
2795 assert_eq!(client.category, category, "{id} category");
2796 }
2797 }
2798
2799 /// #219: the shipped `collect:` example must stay valid as the
2800 /// schema evolves. `include_str!` pins it at compile time so a
2801 /// breaking edit (or a YAML typo in the PowerShell block) fails
2802 /// `cargo test` rather than `kanade job create` at deploy. It carries
2803 /// both `collect:` and `client:` (end-user-triggerable), which must
2804 /// compose.
2805 #[test]
2806 fn example_collect_job_yaml_parses_and_validates() {
2807 let yaml = include_str!("../../../configs/jobs/collect-diagnostics.yaml");
2808 let m: Manifest = serde_yaml::from_str(yaml).expect("collect-diagnostics parse");
2809 m.validate().expect("collect-diagnostics validate");
2810 assert_eq!(m.id, "collect-diagnostics");
2811 let collect = m.collect.as_ref().expect("collect: block present");
2812 assert!(!collect.name.trim().is_empty());
2813 assert_eq!(collect.files_field, "files");
2814 assert_eq!(collect.max_size_bytes(), 50_000_000);
2815 // collect + client compose — the Client App can trigger it.
2816 assert!(
2817 m.client.is_some(),
2818 "collect-diagnostics also carries client:"
2819 );
2820 }
2821
2822 /// The `emit: { type: events }` collector jobs under
2823 /// `configs/jobs/` feed the obs_events timeline. `include_str!`
2824 /// pins them at compile time so a breaking edit (e.g. an `emit:`
2825 /// paired with `check:`/`inventory:`, a bad watermark field, or a
2826 /// YAML typo in the PowerShell block) fails `cargo test` rather
2827 /// than `kanade job create` at deploy. Every one must carry an
2828 /// `emit.type=events` block and NO check/inventory (validate()
2829 /// rejects the pairing).
2830 #[test]
2831 fn example_event_collector_job_yamls_parse_and_validate() {
2832 let jobs = [
2833 // collect-winlog-events was retired in #841 PR2 — the scheduled
2834 // human-session / power timeline is now read natively by the
2835 // agent (kanade-agent `winlog` module via EvtQuery), no
2836 // PowerShell job. collect-winlog-logons-all stays as the
2837 // on-demand forensic all-token-logons companion.
2838 (
2839 "collect-winlog-logons-all",
2840 include_str!("../../../configs/jobs/collect-winlog-logons-all.yaml"),
2841 ),
2842 (
2843 "collect-wlan-events",
2844 include_str!("../../../configs/jobs/collect-wlan-events.yaml"),
2845 ),
2846 ];
2847 for (id, yaml) in jobs {
2848 // Strict parse so an unknown-key typo in these fixtures fails
2849 // here (not silently at deploy) — the runtime Manifest is
2850 // unknown-key-tolerant, so the lenient serde_yaml::from_str
2851 // wouldn't catch fixture drift (CodeRabbit #689).
2852 let m: Manifest =
2853 crate::strict::from_yaml_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
2854 m.validate()
2855 .unwrap_or_else(|e| panic!("{id} validate: {e}"));
2856 assert_eq!(m.id, id, "{id} id mismatch");
2857 let emit = m
2858 .emit
2859 .as_ref()
2860 .unwrap_or_else(|| panic!("{id} must carry an emit: block"));
2861 assert_eq!(emit.kind, EmitKind::Events, "{id} emit.type");
2862 assert!(
2863 m.check.is_none() && m.inventory.is_none(),
2864 "{id}: emit jobs must not pair with check/inventory"
2865 );
2866 }
2867 }
2868
2869 /// The `inventory:` snapshot jobs under `configs/jobs/` project
2870 /// facts into `inventory_facts` + exploded tables. `include_str!`
2871 /// pins them at compile time so a breaking edit (bad explode
2872 /// schema, a YAML typo in the PowerShell block, an `inventory:`
2873 /// accidentally paired with `emit:`) fails `cargo test` rather
2874 /// than the projector at deploy. Each must carry an `inventory:`
2875 /// block and NO emit (validate() rejects the pairing).
2876 #[test]
2877 fn example_inventory_job_yamls_parse_and_validate() {
2878 let jobs = [
2879 (
2880 "inventory-hw",
2881 include_str!("../../../configs/jobs/inventory-hw.yaml"),
2882 ),
2883 (
2884 "inventory-sw",
2885 include_str!("../../../configs/jobs/inventory-sw.yaml"),
2886 ),
2887 (
2888 "inventory-driver",
2889 include_str!("../../../configs/jobs/inventory-driver.yaml"),
2890 ),
2891 ];
2892 for (id, yaml) in jobs {
2893 let m: Manifest =
2894 serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
2895 m.validate()
2896 .unwrap_or_else(|e| panic!("{id} validate: {e}"));
2897 assert_eq!(m.id, id, "{id} id mismatch");
2898 assert!(m.inventory.is_some(), "{id} must carry an inventory: block");
2899 assert!(m.emit.is_none(), "{id}: inventory jobs must not set emit:");
2900 }
2901 }
2902
2903 #[test]
2904 fn example_check_schedule_yamls_parse_and_validate() {
2905 let schedules = [
2906 (
2907 "check-bitlocker",
2908 include_str!("../../../configs/schedules/check-bitlocker.yaml"),
2909 ),
2910 (
2911 "check-av-signature",
2912 include_str!("../../../configs/schedules/check-av-signature.yaml"),
2913 ),
2914 (
2915 "check-cert-expiry",
2916 include_str!("../../../configs/schedules/check-cert-expiry.yaml"),
2917 ),
2918 (
2919 "check-disk-space",
2920 include_str!("../../../configs/schedules/check-disk-space.yaml"),
2921 ),
2922 (
2923 "check-pending-reboot",
2924 include_str!("../../../configs/schedules/check-pending-reboot.yaml"),
2925 ),
2926 (
2927 "check-defender-rtp",
2928 include_str!("../../../configs/schedules/check-defender-rtp.yaml"),
2929 ),
2930 (
2931 "check-firewall",
2932 include_str!("../../../configs/schedules/check-firewall.yaml"),
2933 ),
2934 ];
2935 for (name, yaml) in schedules {
2936 let s: Schedule =
2937 serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
2938 s.validate()
2939 .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
2940 assert_eq!(s.job_id, name, "{name} schedule must reference its job");
2941 }
2942 }
2943
2944 /// Inventory schedule wrappers (`per_pc` cadence) must stay valid
2945 /// alongside the schedule schema. `include_str!` pins them so a
2946 /// breaking edit fails `cargo test`, not `kanade schedule create`.
2947 #[test]
2948 fn example_inventory_schedule_yamls_parse_and_validate() {
2949 let schedules = [
2950 (
2951 "inventory-hw",
2952 include_str!("../../../configs/schedules/inventory-hw.yaml"),
2953 ),
2954 (
2955 "inventory-sw",
2956 include_str!("../../../configs/schedules/inventory-sw.yaml"),
2957 ),
2958 (
2959 "inventory-driver",
2960 include_str!("../../../configs/schedules/inventory-driver.yaml"),
2961 ),
2962 ];
2963 for (name, yaml) in schedules {
2964 let s: Schedule =
2965 serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
2966 s.validate()
2967 .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
2968 assert_eq!(s.job_id, name, "{name} schedule must reference its job");
2969 }
2970 }
2971
2972 #[test]
2973 fn target_is_specified_requires_at_least_one_field() {
2974 let empty = Target::default();
2975 assert!(!empty.is_specified());
2976
2977 let with_all = Target {
2978 all: true,
2979 ..Target::default()
2980 };
2981 assert!(with_all.is_specified());
2982
2983 let with_groups = Target {
2984 groups: vec!["canary".into()],
2985 ..Target::default()
2986 };
2987 assert!(with_groups.is_specified());
2988
2989 let with_pcs = Target {
2990 pcs: vec!["pc-01".into()],
2991 ..Target::default()
2992 };
2993 assert!(with_pcs.is_specified());
2994 }
2995
2996 #[test]
2997 fn manifest_deserialises_minimal_yaml() {
2998 // Matches jobs/echo-test.yaml. v0.18: no target/rollout/jitter
2999 // — those live on the schedule / exec request now.
3000 let yaml = r#"
3001id: echo-test
3002version: 0.0.1
3003execute:
3004 shell: powershell
3005 script: "echo 'kanade'"
3006 timeout: 30s
3007"#;
3008 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3009 assert_eq!(m.id, "echo-test");
3010 assert_eq!(m.version, "0.0.1");
3011 assert!(matches!(m.execute.shell, ExecuteShell::Powershell));
3012 assert_eq!(
3013 m.execute.script.as_deref().map(str::trim),
3014 Some("echo 'kanade'")
3015 );
3016 assert!(m.execute.script_file.is_none());
3017 assert!(m.execute.script_object.is_none());
3018 assert_eq!(m.execute.timeout, "30s");
3019 assert!(!m.require_approval);
3020 m.validate()
3021 .expect("inline-script manifest passes validation");
3022 }
3023
3024 #[test]
3025 fn manifest_parses_check_job_and_validates() {
3026 // An operator-defined health check (#290): a `check:` hint +
3027 // a PowerShell script that prints {status, detail}.
3028 let yaml = r#"
3029id: check-bitlocker
3030version: 0.1.0
3031execute:
3032 shell: powershell
3033 run_as: system
3034 timeout: 15s
3035 script: |
3036 [pscustomobject]@{ status = 'ok'; detail = 'all volumes protected' } | ConvertTo-Json -Compress
3037check:
3038 name: bitlocker
3039 troubleshoot: fix-bitlocker
3040"#;
3041 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3042 let check = m.check.as_ref().expect("check hint present");
3043 assert_eq!(check.name, "bitlocker");
3044 assert_eq!(check.troubleshoot.as_deref(), Some("fix-bitlocker"));
3045 // Field names default to the conventional "status" / "detail".
3046 assert_eq!(check.status_field, "status");
3047 assert_eq!(check.detail_field, "detail");
3048 assert!(m.inventory.is_none() && m.emit.is_none());
3049 m.validate().expect("check-only manifest passes validation");
3050 }
3051
3052 #[test]
3053 fn manifest_check_defaults_and_custom_fields() {
3054 // Minimal: only `name`; status/detail fields default.
3055 let m: Manifest = serde_yaml::from_str(
3056 r#"
3057id: check-disk
3058version: 0.1.0
3059execute:
3060 shell: powershell
3061 script: "[pscustomobject]@{ status = 'ok' } | ConvertTo-Json -Compress"
3062 timeout: 10s
3063check:
3064 name: disk_free
3065"#,
3066 )
3067 .expect("parse");
3068 let c = m.check.as_ref().unwrap();
3069 assert_eq!(c.name, "disk_free");
3070 assert_eq!(c.status_field, "status");
3071 assert_eq!(c.detail_field, "detail");
3072 assert!(c.troubleshoot.is_none());
3073 m.validate().expect("validates");
3074
3075 // The operator can point status/detail at any field of their
3076 // free-form inventory object.
3077 let m2: Manifest = serde_yaml::from_str(
3078 r#"
3079id: check-custom
3080version: 0.1.0
3081execute:
3082 shell: powershell
3083 script: "echo x"
3084 timeout: 10s
3085check:
3086 name: patch_level
3087 status_field: compliance
3088 detail_field: summary
3089"#,
3090 )
3091 .expect("parse");
3092 let c2 = m2.check.as_ref().unwrap();
3093 assert_eq!(c2.status_field, "compliance");
3094 assert_eq!(c2.detail_field, "summary");
3095 }
3096
3097 #[test]
3098 fn manifest_allows_check_composed_with_inventory() {
3099 // `check:` + `inventory:` COMPOSE on the same stdout object:
3100 // status/detail → Health tab, the rest → SPA projection +
3101 // explode sub-tables. Must pass validation.
3102 let yaml = r#"
3103id: check-bitlocker-detailed
3104version: 0.1.0
3105execute:
3106 shell: powershell
3107 script: "echo x"
3108 timeout: 10s
3109check:
3110 name: bitlocker
3111inventory:
3112 display:
3113 - { field: status, label: Status }
3114"#;
3115 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3116 assert!(m.check.is_some() && m.inventory.is_some());
3117 m.validate().expect("check + inventory compose");
3118 }
3119
3120 #[test]
3121 fn manifest_parses_collect_job_and_validates() {
3122 // #219: a `collect:` hint + a script that lists files on stdout.
3123 let yaml = r#"
3124id: collect-diagnostics
3125version: 0.1.0
3126execute:
3127 shell: powershell
3128 run_as: system
3129 timeout: 120s
3130 script: |
3131 @{ files = @("$env:KANADE_COLLECT_DIR/system.csv") } | ConvertTo-Json
3132collect:
3133 name: "Full diagnostics"
3134 description: "Event logs + process"
3135 max_size: 50MB
3136"#;
3137 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3138 let c = m.collect.as_ref().expect("collect hint present");
3139 assert_eq!(c.name, "Full diagnostics");
3140 assert_eq!(c.files_field, "files"); // default
3141 assert_eq!(c.max_size_bytes(), 50_000_000);
3142 m.validate().expect("collect-only manifest validates");
3143 }
3144
3145 #[test]
3146 fn manifest_finalize_powershell_validates_and_lowers() {
3147 let yaml = r#"
3148id: collect-fin
3149version: 0.1.0
3150execute:
3151 shell: powershell
3152 timeout: 120s
3153 script: |
3154 @{ files = @() } | ConvertTo-Json
3155collect:
3156 name: "diag"
3157 max_size: 50MB
3158finalize:
3159 shell: powershell
3160 timeout: 30s
3161 run_as: system
3162 script: |
3163 Write-Output "cleanup"
3164"#;
3165 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3166 m.validate().expect("powershell finalize validates");
3167 let lowered = m.finalize.as_ref().expect("finalize present").lower();
3168 assert_eq!(lowered.timeout_secs, 30);
3169 assert!(matches!(lowered.shell, Shell::Powershell));
3170 // #965: default is the one-call-after-all contract.
3171 assert!(!lowered.on_each_bundle);
3172 }
3173
3174 #[test]
3175 fn manifest_finalize_on_each_bundle_validates_with_collect_and_lowers() {
3176 // #965: on_each_bundle + a collect hint is the intended
3177 // combination — validates, and the flag survives lowering.
3178 let yaml = r#"
3179id: collect-fin-each
3180version: 0.1.0
3181execute:
3182 shell: powershell
3183 timeout: 120s
3184 script: |
3185 @{ files = @() } | ConvertTo-Json
3186collect:
3187 name: "diag"
3188 max_size: 50MB
3189finalize:
3190 shell: powershell
3191 on_each_bundle: true
3192 script: |
3193 Write-Output "cleanup"
3194"#;
3195 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3196 m.validate().expect("on_each_bundle + collect validates");
3197 let lowered = m.finalize.as_ref().expect("finalize present").lower();
3198 assert!(lowered.on_each_bundle, "flag survives lowering");
3199 }
3200
3201 #[test]
3202 fn manifest_finalize_on_each_bundle_without_collect_rejected() {
3203 // #965: a non-collect finalize has no bundles to iterate, so
3204 // on_each_bundle is a no-op — reject it at the write boundary so
3205 // the operator is told rather than silently getting nothing.
3206 let yaml = r#"
3207id: fin-each-no-collect
3208version: 0.1.0
3209execute:
3210 shell: powershell
3211 timeout: 120s
3212 script: |
3213 Write-Output "hi"
3214finalize:
3215 shell: powershell
3216 on_each_bundle: true
3217 script: |
3218 Write-Output "cleanup"
3219"#;
3220 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3221 let err = m
3222 .validate()
3223 .expect_err("on_each_bundle without collect rejected");
3224 assert!(err.contains("on_each_bundle"), "got: {err}");
3225 assert!(err.contains("collect"), "got: {err}");
3226 }
3227
3228 #[test]
3229 fn manifest_finalize_rejects_cmd_shell() {
3230 // cmd finalize is an injection risk (the agent injects JSON into
3231 // the hook's env; cmd.exe quoting doesn't nest) — validate must
3232 // reject it.
3233 let yaml = r#"
3234id: collect-fin-cmd
3235version: 0.1.0
3236execute:
3237 shell: powershell
3238 timeout: 120s
3239 script: |
3240 @{ files = @() } | ConvertTo-Json
3241finalize:
3242 shell: cmd
3243 script: |
3244 echo hi
3245"#;
3246 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3247 let err = m.validate().expect_err("cmd finalize rejected");
3248 assert!(err.contains("finalize.shell"), "got: {err}");
3249 }
3250
3251 #[test]
3252 fn manifest_finalize_rejects_empty_script() {
3253 let yaml = r#"
3254id: collect-fin-empty
3255version: 0.1.0
3256execute:
3257 shell: powershell
3258 timeout: 120s
3259 script: |
3260 @{ files = @() } | ConvertTo-Json
3261finalize:
3262 shell: powershell
3263 script: " "
3264"#;
3265 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3266 let err = m.validate().expect_err("empty finalize script rejected");
3267 assert!(err.contains("finalize.script"), "got: {err}");
3268 }
3269
3270 #[test]
3271 fn manifest_collect_max_size_defaults_when_unset() {
3272 let m: Manifest = serde_yaml::from_str(
3273 r#"
3274id: collect-min
3275version: 0.1.0
3276execute:
3277 shell: powershell
3278 script: "echo x"
3279 timeout: 10s
3280collect:
3281 name: minimal
3282"#,
3283 )
3284 .expect("parse");
3285 let c = m.collect.as_ref().unwrap();
3286 assert!(c.max_size.is_none());
3287 assert_eq!(c.max_size_bytes(), DEFAULT_COLLECT_MAX_SIZE);
3288 m.validate().expect("validates");
3289 }
3290
3291 #[test]
3292 fn manifest_allows_collect_with_client() {
3293 // collect composes with client (client doesn't touch stdout):
3294 // an end user can trigger a collection from the Client App.
3295 let yaml = r#"
3296id: collect-diag-client
3297version: 0.1.0
3298execute:
3299 shell: powershell
3300 script: "echo x"
3301 timeout: 10s
3302collect:
3303 name: diagnostics
3304client:
3305 name: "Send diagnostics"
3306 category: troubleshoot
3307"#;
3308 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3309 assert!(m.collect.is_some() && m.client.is_some());
3310 m.validate().expect("collect + client compose");
3311 }
3312
3313 #[test]
3314 fn manifest_allows_inventory_check_collect_coexistence() {
3315 // #821: the three fenced hints now COMPOSE — each reads its own
3316 // `#KANADE-<KIND>` stdout block, so one job can do all three.
3317 let yaml = r#"
3318id: multi-hint
3319version: 0.1.0
3320execute:
3321 shell: powershell
3322 script: "echo x"
3323 timeout: 10s
3324inventory:
3325 display:
3326 - { field: status, label: Status }
3327check:
3328 name: health
3329collect:
3330 name: diag
3331"#;
3332 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3333 m.validate()
3334 .expect("inventory + check + collect coexist after #821");
3335 }
3336
3337 #[test]
3338 fn manifest_rejects_emit_combined_with_fenced_hints() {
3339 // `emit:` consumes stdout as NDJSON (and blanks it), so it still
3340 // can't share with any fenced hint — inventory, check, OR collect.
3341 for extra in [
3342 "inventory:\n display:\n - { field: s, label: S }\n",
3343 "check:\n name: health\n",
3344 "collect:\n name: diag\n",
3345 ] {
3346 let yaml = format!(
3347 "id: bad-emit-mix\nversion: 0.1.0\nexecute:\n shell: powershell\n \
3348 script: \"echo x\"\n timeout: 10s\nemit:\n type: events\n{extra}"
3349 );
3350 let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
3351 let err = m
3352 .validate()
3353 .expect_err("emit + fenced hint must be rejected");
3354 assert!(err.contains("emit"), "error mentions emit: {err}");
3355 }
3356 }
3357
3358 #[test]
3359 fn manifest_rejects_collect_empty_name_and_bad_size() {
3360 let empty_name: Manifest = serde_yaml::from_str(
3361 r#"
3362id: c
3363version: 0.1.0
3364execute: { shell: powershell, script: "echo x", timeout: 10s }
3365collect: { name: " " }
3366"#,
3367 )
3368 .expect("parse");
3369 assert!(
3370 empty_name.validate().is_err(),
3371 "blank collect.name rejected"
3372 );
3373
3374 let bad_size: Manifest = serde_yaml::from_str(
3375 r#"
3376id: c
3377version: 0.1.0
3378execute: { shell: powershell, script: "echo x", timeout: 10s }
3379collect: { name: diag, max_size: "50 quux" }
3380"#,
3381 )
3382 .expect("parse");
3383 let err = bad_size.validate().expect_err("bad max_size rejected");
3384 assert!(err.contains("max_size"), "error mentions max_size: {err}");
3385 }
3386
3387 #[test]
3388 fn parse_size_bytes_units() {
3389 assert_eq!(parse_size_bytes("1024").unwrap(), 1024);
3390 assert_eq!(parse_size_bytes("1B").unwrap(), 1);
3391 assert_eq!(parse_size_bytes("50MB").unwrap(), 50_000_000);
3392 assert_eq!(parse_size_bytes("500 KB").unwrap(), 500_000);
3393 assert_eq!(parse_size_bytes("1GiB").unwrap(), 1024 * 1024 * 1024);
3394 assert_eq!(parse_size_bytes("2mib").unwrap(), 2 * 1024 * 1024);
3395 assert!(parse_size_bytes("").is_err());
3396 assert!(parse_size_bytes("MB").is_err());
3397 assert!(parse_size_bytes("12 zonks").is_err());
3398 }
3399
3400 #[test]
3401 fn manifest_rejects_check_combined_with_emit() {
3402 // `emit:` stdout is NDJSON (and omitted from the result), so
3403 // it can't pair with `check:` (which needs a single JSON
3404 // object on stdout).
3405 let yaml = r#"
3406id: bad-mix
3407version: 0.1.0
3408execute:
3409 shell: powershell
3410 script: "echo x"
3411 timeout: 10s
3412check:
3413 name: bitlocker
3414emit:
3415 type: events
3416"#;
3417 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3418 let err = m.validate().expect_err("emit + check must fail");
3419 assert!(err.contains("incompatible"), "err: {err}");
3420 }
3421
3422 #[test]
3423 fn manifest_rejects_emit_combined_with_inventory() {
3424 // The other half of the emit-incompatibility condition.
3425 let yaml = r#"
3426id: bad-mix-2
3427version: 0.1.0
3428execute:
3429 shell: powershell
3430 script: "echo x"
3431 timeout: 10s
3432emit:
3433 type: events
3434inventory:
3435 display:
3436 - { field: status, label: Status }
3437"#;
3438 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3439 let err = m.validate().expect_err("emit + inventory must fail");
3440 assert!(err.contains("incompatible"), "err: {err}");
3441 }
3442
3443 #[test]
3444 fn manifest_rejects_empty_check_field_names() {
3445 // Empty name / status_field / detail_field are invisible
3446 // runtime bugs (empty React key, agent reads the wrong field)
3447 // — reject them even though serde supplies non-empty defaults.
3448 let base = |inner: &str| {
3449 format!(
3450 "id: c\nversion: 0.1.0\nexecute:\n shell: powershell\n script: \"echo x\"\n timeout: 10s\ncheck:\n{inner}"
3451 )
3452 };
3453 for inner in [
3454 " name: \"\"\n",
3455 " name: ok\n status_field: \"\"\n",
3456 " name: ok\n detail_field: \" \"\n",
3457 // present-but-blank troubleshoot → broken remediation id.
3458 " name: ok\n troubleshoot: \" \"\n",
3459 ] {
3460 let m: Manifest = serde_yaml::from_str(&base(inner)).expect("parse");
3461 let err = m.validate().expect_err("empty field must fail");
3462 assert!(err.contains("must not be empty"), "err: {err}");
3463 }
3464 }
3465
3466 #[test]
3467 fn check_alert_decodes_with_defaults_and_validates() {
3468 let yaml = r#"
3469id: c
3470version: 0.1.0
3471execute:
3472 shell: powershell
3473 script: "echo x"
3474 timeout: 10s
3475check:
3476 name: bitlocker
3477 alert:
3478 notify_user: true
3479 title: "BitLocker 未準拠"
3480"#;
3481 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3482 m.validate().expect("valid alert");
3483 let alert = m.check.unwrap().alert.unwrap();
3484 // Defaults: on = [fail], priority = warn, body = None.
3485 assert_eq!(alert.on, vec![CheckAlertStatus::Fail]);
3486 assert_eq!(
3487 alert.priority,
3488 crate::ipc::notifications::NotificationPriority::Warn
3489 );
3490 assert!(alert.body.is_none());
3491 assert!(alert.notify_user);
3492 }
3493
3494 #[test]
3495 fn check_alert_validation_rejects_bad_configs() {
3496 let base = |alert: &str| {
3497 format!(
3498 "id: c\nversion: 0.1.0\nexecute:\n shell: powershell\n script: \"echo x\"\n timeout: 10s\ncheck:\n name: bitlocker\n alert:\n{alert}"
3499 )
3500 };
3501 let cases = [
3502 // No recipient.
3503 (" title: t\n", "notify_user and/or notify_groups"),
3504 // Empty title.
3505 (
3506 " notify_user: true\n title: \" \"\n",
3507 "title must not be empty",
3508 ),
3509 // Empty `on`.
3510 (
3511 " notify_user: true\n title: t\n on: []\n",
3512 "on must list at least one status",
3513 ),
3514 // Blank group name.
3515 (
3516 " notify_groups: [\" \"]\n title: t\n",
3517 "notify_groups must not contain blanks",
3518 ),
3519 // alert requires fleet: true.
3520 (
3521 " notify_user: true\n title: t\n fleet: false\n",
3522 "requires fleet: true",
3523 ),
3524 // email opt-in without a group to address.
3525 (
3526 " notify_user: true\n email: true\n title: t\n",
3527 "email requires notify_groups",
3528 ),
3529 ];
3530 for (alert, want) in cases {
3531 let m: Manifest = serde_yaml::from_str(&base(alert)).expect("parse");
3532 let err = m.validate().expect_err("bad alert must fail");
3533 assert!(err.contains(want), "for {alert:?}: got {err}");
3534 }
3535 }
3536
3537 #[test]
3538 fn manifest_client_absent_by_default() {
3539 // A plain operator job (the overwhelming majority) carries no
3540 // `client:` block, so it never surfaces in the end-user
3541 // catalog.
3542 let yaml = r#"
3543id: echo-test
3544version: 0.0.1
3545execute:
3546 shell: powershell
3547 script: "echo 'kanade'"
3548 timeout: 30s
3549"#;
3550 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3551 assert!(m.client.is_none());
3552 m.validate().expect("operator-only job validates");
3553 }
3554
3555 #[test]
3556 fn manifest_client_parses_and_validates() {
3557 // The Client App "困ったとき" remediation job shape: a
3558 // user-invokable troubleshoot job with the end-user fields the
3559 // KLP `jobs.list` wire needs, grouped under `client:`.
3560 let yaml = r#"
3561id: fix-teams-cache
3562version: 1.0.0
3563execute:
3564 shell: powershell
3565 script: "echo clearing"
3566 timeout: 60s
3567client:
3568 name: "Teams のキャッシュをクリア"
3569 description: "Teams が重いときに試してください"
3570 category: troubleshoot
3571 icon: brush-cleaning
3572"#;
3573 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3574 let c = m.client.as_ref().expect("client block present");
3575 assert_eq!(c.name, "Teams のキャッシュをクリア");
3576 assert_eq!(
3577 c.description.as_deref(),
3578 Some("Teams が重いときに試してください")
3579 );
3580 assert_eq!(c.category, "troubleshoot");
3581 assert_eq!(c.icon.as_deref(), Some("brush-cleaning"));
3582 m.validate().expect("user-invokable job validates");
3583 }
3584
3585 #[test]
3586 fn manifest_client_minimal_only_name_and_category() {
3587 // description + icon are optional; name + category are the
3588 // serde-required minimum.
3589 let yaml = r#"
3590id: install-slack
3591version: 1.0.0
3592execute:
3593 shell: powershell
3594 script: "echo install"
3595 timeout: 600s
3596client:
3597 name: Slack
3598 category: catalog
3599"#;
3600 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3601 let c = m.client.as_ref().expect("client present");
3602 assert_eq!(c.category, "catalog");
3603 assert!(c.description.is_none() && c.icon.is_none());
3604 m.validate().expect("minimal client validates");
3605 }
3606
3607 #[test]
3608 fn manifest_client_rejects_blank_name() {
3609 // serde guarantees `name`/`category` are present; the one gap
3610 // is a present-but-blank name → empty catalog row title.
3611 let yaml = r#"
3612id: j
3613version: 1.0.0
3614execute:
3615 shell: powershell
3616 script: "echo x"
3617 timeout: 30s
3618client:
3619 name: " "
3620 category: catalog
3621"#;
3622 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3623 let err = m.validate().expect_err("blank name must fail");
3624 assert!(err.contains("client.name"), "err: {err}");
3625 }
3626
3627 #[test]
3628 fn manifest_client_rejects_blank_optional_fields() {
3629 // description / icon are optional, but a present-but-blank
3630 // value is a bug (empty subtitle / dangling icon name) — reject
3631 // it, mirroring the check: block's troubleshoot guard.
3632 for (field, line) in [
3633 ("client.description", " description: \" \"\n"),
3634 ("client.icon", " icon: \"\"\n"),
3635 // #792: the new category tab-metadata fields get the same
3636 // present-but-blank guard.
3637 ("client.category_label", " category_label: \" \"\n"),
3638 ("client.category_icon", " category_icon: \"\"\n"),
3639 ] {
3640 let yaml = format!(
3641 "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}"
3642 );
3643 let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
3644 let err = m.validate().expect_err("blank optional field must fail");
3645 assert!(err.contains(field), "expected {field} in err: {err}");
3646 }
3647 }
3648
3649 #[test]
3650 fn manifest_client_rejects_blank_category() {
3651 // #792: category is a free-form key now; serde keeps it required,
3652 // but a present-but-blank value would group the job under an empty
3653 // tab — validate() must reject it.
3654 let yaml = r#"
3655id: j
3656version: 1.0.0
3657execute:
3658 shell: powershell
3659 script: "echo x"
3660 timeout: 30s
3661client:
3662 name: "A job"
3663 category: " "
3664"#;
3665 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3666 let err = m.validate().expect_err("blank category must fail");
3667 assert!(err.contains("client.category"), "err: {err}");
3668 }
3669
3670 #[test]
3671 fn target_matches_pc_group_and_all() {
3672 // #816: pc match, group match, all, and the no-match case.
3673 let by_pc = Target {
3674 pcs: vec!["PC1".into()],
3675 ..Default::default()
3676 };
3677 assert!(by_pc.matches("PC1", &[]));
3678 assert!(!by_pc.matches("PC2", &["g1".into()]));
3679
3680 let by_group = Target {
3681 groups: vec!["g1".into()],
3682 ..Default::default()
3683 };
3684 assert!(by_group.matches("PC2", &["g1".into()]));
3685 assert!(!by_group.matches("PC2", &["g2".into()]));
3686
3687 let all = Target {
3688 all: true,
3689 ..Default::default()
3690 };
3691 assert!(all.matches("anyPC", &[]));
3692 }
3693
3694 #[test]
3695 fn manifest_client_rejects_empty_visible_to() {
3696 // #816: a present-but-empty visible_to (no all/groups/pcs) would
3697 // hide the job from everyone — validate() must reject it.
3698 let yaml = r#"
3699id: j
3700version: 1.0.0
3701execute:
3702 shell: powershell
3703 script: "echo x"
3704 timeout: 30s
3705client:
3706 name: "A job"
3707 category: troubleshoot
3708 visible_to: {}
3709"#;
3710 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3711 let err = m.validate().expect_err("empty visible_to must fail");
3712 assert!(err.contains("client.visible_to"), "err: {err}");
3713 }
3714
3715 #[test]
3716 fn manifest_client_accepts_visible_to_groups() {
3717 let yaml = r#"
3718id: j
3719version: 1.0.0
3720execute:
3721 shell: powershell
3722 script: "echo x"
3723 timeout: 30s
3724client:
3725 name: "A job"
3726 category: settings
3727 visible_to:
3728 groups: [wifi-affected]
3729"#;
3730 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3731 m.validate().expect("visible_to with a group validates");
3732 let vt = m.client.unwrap().visible_to.unwrap();
3733 assert_eq!(vt.groups, vec!["wifi-affected".to_string()]);
3734 }
3735
3736 #[test]
3737 fn manifest_client_show_when_accepts_scalar_and_seq() {
3738 use crate::ipc::state::CheckStatus;
3739 // `is:` accepts a single status (author ergonomics) ...
3740 let scalar = r#"
3741id: office-update
3742version: 1.0.0
3743execute:
3744 shell: powershell
3745 script: "echo x"
3746 timeout: 30s
3747client:
3748 name: "Office を最新に更新"
3749 category: software_update
3750 show_when:
3751 check: office-up-to-date
3752 is: fail
3753"#;
3754 let m: Manifest = serde_yaml::from_str(scalar).expect("parse scalar");
3755 m.validate().expect("scalar show_when validates");
3756 let sw = m.client.unwrap().show_when.unwrap();
3757 assert_eq!(sw.check, "office-up-to-date");
3758 assert_eq!(sw.is, vec![CheckStatus::Fail]);
3759
3760 // ... and a list (e.g. fail-open on a not-yet-run check).
3761 let seq = scalar.replace("is: fail", "is: [fail, unknown]");
3762 let m: Manifest = serde_yaml::from_str(&seq).expect("parse seq");
3763 m.validate().expect("seq show_when validates");
3764 assert_eq!(
3765 m.client.unwrap().show_when.unwrap().is,
3766 vec![CheckStatus::Fail, CheckStatus::Unknown]
3767 );
3768 }
3769
3770 #[test]
3771 fn manifest_client_show_when_rejects_empty() {
3772 // A malformed check slug (here: internal spaces — a typo that could
3773 // never match a real check name) or an empty status list would
3774 // silently hide the job forever — validate() must reject both.
3775 let bad_check = r#"
3776id: j
3777version: 1.0.0
3778execute:
3779 shell: powershell
3780 script: "echo x"
3781 timeout: 30s
3782client:
3783 name: "A job"
3784 category: software_update
3785 show_when:
3786 check: "office up to date"
3787 is: fail
3788"#;
3789 let m: Manifest = serde_yaml::from_str(bad_check).expect("parse");
3790 let err = m.validate().expect_err("malformed check slug must fail");
3791 assert!(err.contains("client.show_when.check"), "err: {err}");
3792
3793 let empty_is = r#"
3794id: j
3795version: 1.0.0
3796execute:
3797 shell: powershell
3798 script: "echo x"
3799 timeout: 30s
3800client:
3801 name: "A job"
3802 category: software_update
3803 show_when:
3804 check: office-up-to-date
3805 is: []
3806"#;
3807 let m: Manifest = serde_yaml::from_str(empty_is).expect("parse");
3808 let err = m.validate().expect_err("empty is[] must fail");
3809 assert!(err.contains("client.show_when.is"), "err: {err}");
3810 }
3811
3812 #[test]
3813 fn manifest_client_confirm_accepts_bool_and_struct() {
3814 // `confirm:` deserializes from a bare bool or a struct. A bool
3815 // sets `enabled` (message stays default); a struct carries a custom
3816 // message and defaults `enabled` to true.
3817 let base = r#"
3818id: j
3819version: 1.0.0
3820execute:
3821 shell: powershell
3822 script: "echo x"
3823 timeout: 30s
3824client:
3825 name: "Wi-Fi 省電力を切る"
3826 category: settings
3827"#;
3828 // `confirm: false` ⇒ dialog suppressed.
3829 let off: Manifest =
3830 serde_yaml::from_str(&format!("{base} confirm: false\n")).expect("parse false");
3831 off.validate().expect("confirm: false validates");
3832 let c = off.client.unwrap().confirm.unwrap();
3833 assert!(!c.enabled);
3834 assert!(c.message.is_none());
3835
3836 // `confirm: true` ⇒ same as omitting (dialog shown, default message).
3837 let on: Manifest =
3838 serde_yaml::from_str(&format!("{base} confirm: true\n")).expect("parse true");
3839 let c = on.client.unwrap().confirm.unwrap();
3840 assert!(c.enabled);
3841 assert!(c.message.is_none());
3842
3843 // Struct with only a message ⇒ enabled defaults true, custom text.
3844 let msg: Manifest = serde_yaml::from_str(&format!(
3845 "{base} confirm:\n message: \"再インストールには数分かかります。よろしいですか?\"\n"
3846 ))
3847 .expect("parse struct");
3848 msg.validate().expect("confirm message validates");
3849 let c = msg.client.unwrap().confirm.unwrap();
3850 assert!(c.enabled);
3851 assert_eq!(
3852 c.message.as_deref(),
3853 Some("再インストールには数分かかります。よろしいですか?")
3854 );
3855
3856 // Absent ⇒ None (historical default handled by the client).
3857 let none: Manifest = serde_yaml::from_str(base).expect("parse none");
3858 assert!(none.client.unwrap().confirm.is_none());
3859
3860 // Explicit `confirm: null` is schema-valid (the field is Option) and
3861 // must map to None, not a parse error (Gemini #960).
3862 let null: Manifest =
3863 serde_yaml::from_str(&format!("{base} confirm: null\n")).expect("parse null");
3864 assert!(null.client.unwrap().confirm.is_none());
3865 }
3866
3867 #[test]
3868 fn manifest_client_confirm_rejects_blank_message() {
3869 // A present-but-blank custom message would render an empty dialog
3870 // title — validate() must reject it, like the other display fields.
3871 let yaml = r#"
3872id: j
3873version: 1.0.0
3874execute:
3875 shell: powershell
3876 script: "echo x"
3877 timeout: 30s
3878client:
3879 name: "A job"
3880 category: settings
3881 confirm:
3882 message: " "
3883"#;
3884 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3885 let err = m.validate().expect_err("blank confirm.message must fail");
3886 assert!(err.contains("client.confirm.message"), "err: {err}");
3887 }
3888
3889 #[test]
3890 fn manifest_client_requires_category_at_parse() {
3891 // A `client:` block missing `category` is a hard parse error
3892 // (serde required field) — no manual validate() needed.
3893 let yaml = r#"
3894id: j
3895version: 1.0.0
3896execute:
3897 shell: powershell
3898 script: "echo x"
3899 timeout: 30s
3900client:
3901 name: "A job"
3902"#;
3903 let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
3904 assert!(
3905 r.is_err(),
3906 "missing category must be a parse error, got {r:?}"
3907 );
3908 }
3909
3910 #[test]
3911 fn manifest_client_rejects_unknown_field() {
3912 // #492: the strict create boundary catches a fat-fingered
3913 // `displayname:` (with its path) instead of silently
3914 // dropping it; the tolerant read path accepts it.
3915 let yaml = r#"
3916id: j
3917version: 1.0.0
3918execute:
3919 shell: powershell
3920 script: "echo x"
3921 timeout: 30s
3922client:
3923 name: "A job"
3924 category: catalog
3925 displayname: oops
3926"#;
3927 let r = crate::strict::from_yaml_str::<Manifest>(yaml);
3928 let err = r.expect_err("unknown client field must be rejected at the write boundary");
3929 // serde_ignored renders the Option layer as `?`:
3930 // `client.?.displayname`. Assert on the leaf key.
3931 assert!(err.contains("displayname"), "{err}");
3932 // The READ path tolerates the same payload (gradual-upgrade
3933 // contract: an old agent must accept a newer writer's field).
3934 let m: Manifest = serde_yaml::from_str(yaml).expect("tolerant read");
3935 assert_eq!(m.client.as_ref().map(|c| c.name.as_str()), Some("A job"));
3936 }
3937
3938 #[test]
3939 fn manifest_tags_default_empty() {
3940 // The overwhelming majority of jobs carry no tags; the field
3941 // must default to an empty Vec (not fail to parse) and skip
3942 // serialisation so old readers never see the key.
3943 let yaml = r#"
3944id: echo-test
3945version: 0.0.1
3946execute:
3947 shell: powershell
3948 script: "echo 'kanade'"
3949 timeout: 30s
3950"#;
3951 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3952 assert!(m.tags.is_empty());
3953 m.validate().expect("tag-less job validates");
3954 // skip_serializing_if = empty ⇒ the key is absent from JSON.
3955 let json = serde_json::to_string(&m).expect("serialize");
3956 assert!(
3957 !json.contains("tags"),
3958 "empty tags must not serialise: {json}"
3959 );
3960 }
3961
3962 #[test]
3963 fn manifest_parses_and_validates_tags() {
3964 let yaml = r#"
3965id: check-bitlocker
3966version: 0.1.0
3967execute:
3968 shell: powershell
3969 script: "echo x"
3970 timeout: 30s
3971tags: [security, windows, health-check]
3972"#;
3973 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3974 assert_eq!(m.tags, vec!["security", "windows", "health-check"]);
3975 m.validate().expect("tagged job validates");
3976 // Round-trips through JSON (the wire format the SPA reads).
3977 let json = serde_json::to_string(&m).expect("serialize");
3978 assert!(json.contains("\"tags\""), "non-empty tags must serialise");
3979 }
3980
3981 #[test]
3982 fn manifest_rejects_blank_tag() {
3983 // A whitespace-only tag renders an empty filter chip — reject
3984 // it at the write boundary like the other blank display fields.
3985 let yaml = r#"
3986id: j
3987version: 0.1.0
3988execute:
3989 shell: powershell
3990 script: "echo x"
3991 timeout: 30s
3992tags: [ok, " "]
3993"#;
3994 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3995 let err = m.validate().expect_err("blank tag must fail");
3996 assert!(err.contains("tags must not contain empty"), "err: {err}");
3997 }
3998
3999 #[test]
4000 fn validate_rejects_unknown_tier_and_accepts_known() {
4001 let base =
4002 "id: t\nversion: 0.0.1\nexecute:\n shell: powershell\n script: x\n timeout: 30s\n";
4003 // A typo / future tier decodes to Tier::Unknown (#[serde(other)]) and
4004 // must FAIL CLOSED — never fall back to unrestricted endpoint dispatch.
4005 let bogus: Manifest =
4006 serde_yaml::from_str(&format!("{base}tier: controler\n")).expect("parse");
4007 let err = bogus.validate().expect_err("unknown tier must be rejected");
4008 assert!(err.contains("tier"), "err: {err}");
4009 // The two known tiers pass.
4010 serde_yaml::from_str::<Manifest>(&format!("{base}tier: controller\n"))
4011 .unwrap()
4012 .validate()
4013 .expect("controller tier is valid");
4014 serde_yaml::from_str::<Manifest>(&format!("{base}tier: endpoint\n"))
4015 .unwrap()
4016 .validate()
4017 .expect("endpoint tier is valid");
4018 }
4019
4020 #[test]
4021 fn feed_payload_extracts_fenced_block() {
4022 let stdout = "fetched 1500 KEV entries\n\
4023 #KANADE-FEED-BEGIN\n\
4024 {\"vulnerabilities\": []}\n\
4025 #KANADE-FEED-END\n";
4026 assert_eq!(feed_payload(stdout), "{\"vulnerabilities\": []}");
4027 }
4028
4029 #[test]
4030 fn validate_feed_rules() {
4031 let base =
4032 "id: f\nversion: 0.0.1\nexecute:\n shell: powershell\n script: x\n timeout: 30s\n";
4033 // A well-formed feed (controller implied; no explicit tier) passes.
4034 serde_yaml::from_str::<Manifest>(&format!(
4035 "{base}feed:\n - id: cisa-kev\n field: vulnerabilities\n primary_key: [cveID]\n"
4036 ))
4037 .unwrap()
4038 .validate()
4039 .expect("a well-formed feed is valid");
4040
4041 // Empty primary_key is rejected (no item_id → every row dropped).
4042 let err = serde_yaml::from_str::<Manifest>(&format!(
4043 "{base}feed:\n - id: cisa-kev\n field: vulnerabilities\n primary_key: []\n"
4044 ))
4045 .unwrap()
4046 .validate()
4047 .expect_err("empty primary_key must be rejected");
4048 assert!(err.contains("primary_key"), "err: {err}");
4049
4050 // A duplicate feed id clobbers a partition — rejected.
4051 let err = serde_yaml::from_str::<Manifest>(&format!(
4052 "{base}feed:\n - id: dup\n field: a\n primary_key: [k]\n - id: dup\n field: b\n primary_key: [k]\n"
4053 ))
4054 .unwrap()
4055 .validate()
4056 .expect_err("duplicate feed id must be rejected");
4057 assert!(err.contains("more than once"), "err: {err}");
4058
4059 // `feed:` + explicit `tier: endpoint` is contradictory — rejected.
4060 let err = serde_yaml::from_str::<Manifest>(&format!(
4061 "{base}tier: endpoint\nfeed:\n - id: cisa-kev\n field: vulnerabilities\n primary_key: [cveID]\n"
4062 ))
4063 .unwrap()
4064 .validate()
4065 .expect_err("feed + tier: endpoint must be rejected");
4066 assert!(err.contains("controller tier"), "err: {err}");
4067
4068 // `feed:` + `emit:` is incompatible — emit consumes stdout whole, so
4069 // the feed's fence never reaches the projector.
4070 let err = serde_yaml::from_str::<Manifest>(&format!(
4071 "{base}emit:\n type: events\nfeed:\n - id: cisa-kev\n field: vulnerabilities\n primary_key: [cveID]\n"
4072 ))
4073 .unwrap()
4074 .validate()
4075 .expect_err("feed + emit must be rejected");
4076 assert!(err.contains("emit"), "err: {err}");
4077 }
4078
4079 // #720 — wrap an `aggregate:` YAML block (already indented as a
4080 // top-level key body) into an otherwise-minimal valid manifest.
4081 fn manifest_with_aggregate(aggregate_block: &str) -> Manifest {
4082 let yaml = format!(
4083 "id: t\nversion: 0.0.1\nexecute:\n shell: powershell\n script: echo hi\n timeout: 30s\n{aggregate_block}"
4084 );
4085 serde_yaml::from_str(&yaml).expect("parse aggregate manifest")
4086 }
4087
4088 #[test]
4089 fn aggregate_accepts_full_valid_spec() {
4090 // count+group_by+exclude+sample_minutes, ratio+bool_path,
4091 // timeline+time_bucket, fleet ranking via group_by: pc_id, and a
4092 // bare total stat — alongside emit (composes with every hint).
4093 let m = manifest_with_aggregate(
4094 "emit:\n type: events\naggregate:\n\
4095 - { dashboard: Utilization, title: Top apps, kind: app_sample, agg: count, group_by: foreground.app, sample_minutes: 2, exclude: [LockApp], render: bar }\n\
4096 - { dashboard: Utilization, title: Active ratio, kind: presence, agg: ratio, bool_path: active, sample_minutes: 5, render: gauge }\n\
4097 - { dashboard: Utilization, title: By hour, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: timeline }\n\
4098 - { dashboard: Reliability, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
4099 - { dashboard: Reliability, title: Total crashes, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
4100 );
4101 m.validate().expect("valid aggregate spec");
4102 }
4103
4104 #[test]
4105 fn aggregate_rejects_empty_list() {
4106 let m = manifest_with_aggregate("aggregate: []\n");
4107 let err = m.validate().expect_err("empty list must fail");
4108 assert!(err.contains("at least one widget"), "err: {err}");
4109 }
4110
4111 #[test]
4112 fn aggregate_rejects_ratio_without_bool_path() {
4113 let m = manifest_with_aggregate(
4114 "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, render: gauge }\n",
4115 );
4116 let err = m.validate().expect_err("ratio needs bool_path");
4117 assert!(err.contains("agg=ratio requires `bool_path`"), "err: {err}");
4118 }
4119
4120 #[test]
4121 fn aggregate_rejects_sum_without_value_path() {
4122 let m = manifest_with_aggregate(
4123 "aggregate:\n- { dashboard: D, title: T, kind: io, agg: sum, render: bar }\n",
4124 );
4125 let err = m.validate().expect_err("sum needs value_path");
4126 assert!(err.contains("agg=sum requires `value_path`"), "err: {err}");
4127 }
4128
4129 #[test]
4130 fn aggregate_rejects_pc_id_group_without_fleet() {
4131 let m = manifest_with_aggregate(
4132 "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: count, group_by: pc_id, render: bar }\n",
4133 );
4134 let err = m.validate().expect_err("pc_id grouping needs fleet");
4135 assert!(
4136 err.contains("pc_id is only valid with scope: fleet"),
4137 "err: {err}"
4138 );
4139 }
4140
4141 #[test]
4142 fn aggregate_rejects_transform_with_pc_id_group() {
4143 let m = manifest_with_aggregate(
4144 "aggregate:\n- { dashboard: D, title: T, scope: fleet, kind: web_visit, agg: count, group_by: pc_id, transform: host, render: bar }\n",
4145 );
4146 let err = m
4147 .validate()
4148 .expect_err("transform on pc_id grouping must fail");
4149 assert!(
4150 err.contains("transform is not valid with group_by: pc_id"),
4151 "err: {err}"
4152 );
4153 }
4154
4155 #[test]
4156 fn aggregate_rejects_timeline_without_bucket() {
4157 let m = manifest_with_aggregate(
4158 "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, bool_path: active, render: timeline }\n",
4159 );
4160 let err = m.validate().expect_err("timeline needs a bucket");
4161 assert!(
4162 err.contains("render=timeline requires `time_bucket`"),
4163 "err: {err}"
4164 );
4165 }
4166
4167 #[test]
4168 fn aggregate_rejects_bucket_on_non_timeline() {
4169 let m = manifest_with_aggregate(
4170 "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: gauge }\n",
4171 );
4172 let err = m.validate().expect_err("bucket only on timeline");
4173 assert!(
4174 err.contains("time_bucket is only valid with render: timeline"),
4175 "err: {err}"
4176 );
4177 }
4178
4179 #[test]
4180 fn aggregate_rejects_unsafe_json_path() {
4181 // A path with characters outside [A-Za-z0-9_.] could break out of
4182 // the `'$.' || ?` bind — reject at create time.
4183 let m = manifest_with_aggregate(
4184 "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: \"foo'; DROP\", render: bar }\n",
4185 );
4186 let err = m.validate().expect_err("unsafe path must fail");
4187 assert!(err.contains("dotted JSON path"), "err: {err}");
4188 }
4189
4190 #[test]
4191 fn aggregate_rejects_blank_title() {
4192 let m = manifest_with_aggregate(
4193 "aggregate:\n- { dashboard: D, title: \" \", kind: k, agg: count, render: stat }\n",
4194 );
4195 let err = m.validate().expect_err("blank title must fail");
4196 assert!(err.contains("title must not be empty"), "err: {err}");
4197 }
4198
4199 #[test]
4200 fn aggregate_rejects_blank_kind() {
4201 let m = manifest_with_aggregate(
4202 "aggregate:\n- { dashboard: D, title: T, kind: \" \", agg: count, render: stat }\n",
4203 );
4204 let err = m.validate().expect_err("blank kind must fail");
4205 assert!(err.contains("kind must not be empty"), "err: {err}");
4206 }
4207
4208 #[test]
4209 fn aggregate_rejects_blank_source_when_set() {
4210 let m = manifest_with_aggregate(
4211 "aggregate:\n- { dashboard: D, title: T, kind: k, source: \"\", agg: count, render: stat }\n",
4212 );
4213 let err = m.validate().expect_err("blank source must fail");
4214 assert!(
4215 err.contains("source must not be empty when set"),
4216 "err: {err}"
4217 );
4218 }
4219
4220 #[test]
4221 fn aggregate_accepts_description_and_rejects_blank() {
4222 let ok = manifest_with_aggregate(
4223 "aggregate:\n- { dashboard: D, title: T, description: \"samples x 2 min\", kind: k, agg: count, render: stat }\n",
4224 );
4225 ok.validate()
4226 .expect("description is a valid optional field");
4227 assert_eq!(
4228 ok.aggregate.as_ref().unwrap()[0].description.as_deref(),
4229 Some("samples x 2 min")
4230 );
4231 let bad = manifest_with_aggregate(
4232 "aggregate:\n- { dashboard: D, title: T, description: \" \", kind: k, agg: count, render: stat }\n",
4233 );
4234 let err = bad.validate().expect_err("blank description must fail");
4235 assert!(
4236 err.contains("description must not be empty when set"),
4237 "err: {err}"
4238 );
4239 }
4240
4241 #[test]
4242 fn aggregate_rejects_count_with_value_path() {
4243 let m = manifest_with_aggregate(
4244 "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, value_path: bytes, render: stat }\n",
4245 );
4246 let err = m.validate().expect_err("count must not use value_path");
4247 assert!(
4248 err.contains("agg=count does not use `value_path`"),
4249 "err: {err}"
4250 );
4251 }
4252
4253 #[test]
4254 fn aggregate_rejects_ratio_with_value_path() {
4255 let m = manifest_with_aggregate(
4256 "aggregate:\n- { dashboard: D, title: T, kind: k, agg: ratio, bool_path: active, value_path: bytes, render: gauge }\n",
4257 );
4258 let err = m.validate().expect_err("ratio must not use value_path");
4259 assert!(
4260 err.contains("agg=ratio does not use `value_path`"),
4261 "err: {err}"
4262 );
4263 }
4264
4265 #[test]
4266 fn aggregate_rejects_gauge_without_ratio() {
4267 let m = manifest_with_aggregate(
4268 "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, render: gauge }\n",
4269 );
4270 let err = m.validate().expect_err("gauge needs ratio");
4271 assert!(
4272 err.contains("render=gauge is only valid with agg: ratio"),
4273 "err: {err}"
4274 );
4275 }
4276
4277 #[test]
4278 fn aggregate_rejects_limit_without_group_by() {
4279 let m = manifest_with_aggregate(
4280 "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, limit: 5, render: stat }\n",
4281 );
4282 let err = m.validate().expect_err("limit needs group_by");
4283 assert!(err.contains("limit requires `group_by`"), "err: {err}");
4284 }
4285
4286 #[test]
4287 fn aggregate_rejects_exclude_without_group_by() {
4288 let m = manifest_with_aggregate(
4289 "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, exclude: [x], render: stat }\n",
4290 );
4291 let err = m.validate().expect_err("exclude needs group_by");
4292 assert!(err.contains("exclude requires `group_by`"), "err: {err}");
4293 }
4294
4295 #[test]
4296 fn aggregate_rejects_zero_limit_and_zero_sample_minutes() {
4297 let m = manifest_with_aggregate(
4298 "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, limit: 0, render: bar }\n",
4299 );
4300 assert!(m.validate().unwrap_err().contains("limit must be > 0"));
4301 let m = manifest_with_aggregate(
4302 "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, sample_minutes: 0, render: bar }\n",
4303 );
4304 assert!(
4305 m.validate()
4306 .unwrap_err()
4307 .contains("sample_minutes must be > 0")
4308 );
4309 }
4310
4311 #[test]
4312 fn aggregate_rejects_empty_exclude_entry() {
4313 let m = manifest_with_aggregate(
4314 "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, exclude: [\" \"], render: bar }\n",
4315 );
4316 let err = m.validate().expect_err("blank exclude entry must fail");
4317 assert!(
4318 err.contains("exclude must not contain empty entries"),
4319 "err: {err}"
4320 );
4321 }
4322
4323 #[test]
4324 fn aggregate_rejects_malformed_dotted_paths() {
4325 for bad in [".foo", "foo.", "foo..bar", "."] {
4326 let m = manifest_with_aggregate(&format!(
4327 "aggregate:\n- {{ dashboard: D, title: T, kind: k, agg: count, group_by: \"{bad}\", render: bar }}\n"
4328 ));
4329 let err = m.validate().expect_err("malformed path must fail");
4330 assert!(err.contains("dotted JSON path"), "path {bad}: {err}");
4331 }
4332 }
4333
4334 #[test]
4335 fn aggregate_rejects_unknown_enum_value() {
4336 // An unrecognised render string deserialises to the #492 Unknown
4337 // catch-all (so old readers don't choke); validate() rejects it as
4338 // a typo at create time.
4339 let m = manifest_with_aggregate(
4340 "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, render: heatmap }\n",
4341 );
4342 let err = m.validate().expect_err("unknown render must fail");
4343 assert!(err.contains("render is not a known value"), "err: {err}");
4344 }
4345
4346 #[test]
4347 fn aggregate_accepts_order_field() {
4348 let m = manifest_with_aggregate(
4349 "aggregate:\n- { dashboard: D, title: T, order: -5, kind: k, agg: count, render: stat }\n",
4350 );
4351 m.validate().expect("order is a valid optional field");
4352 let w = &m.aggregate.as_ref().unwrap()[0];
4353 assert_eq!(w.order, Some(-5));
4354 }
4355
4356 #[test]
4357 fn aggregate_accepts_minimal_op_timeline() {
4358 // op_timeline needs no kind/agg — it reconstructs a fixed multi-kind
4359 // swimlane. A bare per-PC spec is valid, and `kind`/`agg` stay None.
4360 let m = manifest_with_aggregate(
4361 "aggregate:\n- { dashboard: Uptime, title: Operational state, scope: pc, render: op_timeline }\n",
4362 );
4363 m.validate().expect("minimal op_timeline is valid");
4364 let w = &m.aggregate.as_ref().unwrap()[0];
4365 assert_eq!(w.render, AggregateRender::OpTimeline);
4366 assert!(w.kind.is_none());
4367 assert!(w.agg.is_none());
4368 }
4369
4370 #[test]
4371 fn aggregate_rejects_op_timeline_with_fleet_scope() {
4372 let m = manifest_with_aggregate(
4373 "aggregate:\n- { dashboard: Uptime, title: T, scope: fleet, render: op_timeline }\n",
4374 );
4375 let err = m.validate().expect_err("op_timeline must be per-PC");
4376 assert!(
4377 err.contains("render=op_timeline requires scope: pc"),
4378 "err: {err}"
4379 );
4380 }
4381
4382 #[test]
4383 fn aggregate_rejects_op_timeline_with_aggregation_fields() {
4384 // Each aggregation knob the operator might paste in is rejected
4385 // (rather than silently ignored), pointing at the field to delete.
4386 for (block, field) in [
4387 ("kind: boot", "kind"),
4388 ("agg: count", "agg"),
4389 ("source: winlog:Security", "source"),
4390 ("group_by: pc_id", "group_by"),
4391 ("bool_path: active", "bool_path"),
4392 ("time_bucket: hour", "time_bucket"),
4393 ("limit: 5", "limit"),
4394 ] {
4395 let m = manifest_with_aggregate(&format!(
4396 "aggregate:\n- {{ dashboard: Uptime, title: T, scope: pc, {block}, render: op_timeline }}\n"
4397 ));
4398 let err = m
4399 .validate()
4400 .expect_err(&format!("op_timeline must reject {field}"));
4401 assert!(
4402 err.contains(&format!("render=op_timeline does not use `{field}`")),
4403 "field {field}: {err}"
4404 );
4405 }
4406 }
4407
4408 // ── #743 View resource ───────────────────────────────────────────
4409 fn view_from(yaml_body: &str) -> View {
4410 serde_yaml::from_str(&format!("id: v1\n{yaml_body}")).expect("parse view")
4411 }
4412
4413 #[test]
4414 fn view_accepts_valid_widgets() {
4415 let v = view_from(
4416 "widgets:\n\
4417 - { dashboard: Reliability, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
4418 - { dashboard: Reliability, title: Total, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
4419 );
4420 v.validate().expect("valid view");
4421 }
4422
4423 #[test]
4424 fn view_rejects_empty_widgets() {
4425 let v = view_from("widgets: []\n");
4426 let err = v.validate().expect_err("empty widgets must fail");
4427 assert!(err.contains("at least one widget"), "err: {err}");
4428 }
4429
4430 #[test]
4431 fn view_rejects_blank_id() {
4432 let v: View = serde_yaml::from_str(
4433 "id: \" \"\nwidgets:\n- { dashboard: D, title: T, kind: k, agg: count, render: stat }\n",
4434 )
4435 .expect("parse");
4436 let err = v.validate().expect_err("blank id must fail");
4437 assert!(err.contains("view.id must"), "err: {err}");
4438 }
4439
4440 #[test]
4441 fn view_rejects_unsafe_id() {
4442 // A `/` or `..` in the id would break the KV key and the
4443 // `/api/views/{id}` URL segment — reject at create time.
4444 for bad in ["../etc", "a/b", "has space", "x;y"] {
4445 let v: View = serde_yaml::from_str(&format!(
4446 "id: \"{bad}\"\nwidgets:\n- {{ dashboard: D, title: T, kind: k, agg: count, render: stat }}\n",
4447 ))
4448 .expect("parse");
4449 let err = v.validate().expect_err("unsafe id must fail");
4450 assert!(err.contains("[A-Za-z0-9._-]"), "id {bad}: {err}");
4451 }
4452 assert!(is_valid_resource_id("dashboards-fleet.v1_2"));
4453 }
4454
4455 #[test]
4456 fn view_reuses_shared_widget_validation() {
4457 // The same per-widget rule the job hint enforces (ratio needs
4458 // bool_path), reported under the `widgets[..]` field.
4459 let v = view_from(
4460 "widgets:\n- { dashboard: D, title: T, kind: presence, agg: ratio, render: gauge }\n",
4461 );
4462 let err = v.validate().expect_err("ratio without bool_path must fail");
4463 assert!(
4464 err.contains("widgets[0].agg=ratio requires `bool_path`"),
4465 "err: {err}"
4466 );
4467 }
4468
4469 // ── #vuln-roadmap PR3 SQL-backed views ───────────────────────────
4470 #[test]
4471 fn view_accepts_pure_sql_widgets() {
4472 // A view with only sql_widgets (no obs_events aggregate widgets) is
4473 // valid — the vulnerability-dashboard shape.
4474 let v = view_from(
4475 "sql_widgets:
4476 - title: KEV-affected hosts
4477 query: \"SELECT pc_id, 1 AS cves FROM inventory_sw_apps\"
4478 refresh: 6h
4479 render: { kind: table, columns: [pc_id, cves], labels: { cves: CVE count } }
4480 placement: { analytics: Security, dashboard: { pin: true } }
4481",
4482 );
4483 v.validate().expect("valid sql view");
4484 // refresh parses; pin/tab helpers read the placement.
4485 let w = &v.sql_widgets[0];
4486 assert_eq!(
4487 w.refresh_interval(),
4488 std::time::Duration::from_secs(6 * 3600)
4489 );
4490 assert!(w.placement.is_pinned());
4491 assert_eq!(w.placement.tab(), "Security");
4492 }
4493
4494 #[test]
4495 fn sql_widget_defaults_and_mix() {
4496 // No refresh ⇒ default; a view can mix aggregate + sql widgets.
4497 let v = view_from(
4498 "widgets:
4499 - { dashboard: D, title: T, kind: k, agg: count, render: stat }
4500sql_widgets:
4501 - title: N affected
4502 query: \"SELECT count(*) AS n FROM feeds\"
4503 render: { kind: stat, value: n }
4504 placement: { dashboard: { pin: true } }
4505",
4506 );
4507 v.validate().expect("mixed view is valid");
4508 assert_eq!(v.sql_widgets[0].refresh_interval(), DEFAULT_VIEW_REFRESH);
4509 // dashboard-only placement (no analytics tab) falls back to a label.
4510 assert_eq!(v.sql_widgets[0].placement.tab(), "Dashboard");
4511 }
4512
4513 #[test]
4514 fn sql_widget_validation_rules() {
4515 // helper: build a view with one sql_widget from an inline render+placement
4516 let mk = |render: &str, placement: &str| -> Result<(), String> {
4517 view_from(&format!(
4518 "sql_widgets:
4519 - title: W
4520 query: \"SELECT 1 AS a\"
4521 render: {render}
4522 placement: {placement}
4523"
4524 ))
4525 .validate()
4526 };
4527 // bar needs label + value
4528 let err = mk("{ kind: bar, value: a }", "{ analytics: T }").unwrap_err();
4529 assert!(
4530 err.contains("render.label is required for kind=bar"),
4531 "err: {err}"
4532 );
4533 // pie needs value
4534 let err = mk("{ kind: pie, label: a }", "{ analytics: T }").unwrap_err();
4535 assert!(
4536 err.contains("render.value is required for kind=pie"),
4537 "err: {err}"
4538 );
4539 // stat needs value
4540 let err = mk("{ kind: stat }", "{ analytics: T }").unwrap_err();
4541 assert!(
4542 err.contains("render.value is required for kind=stat"),
4543 "err: {err}"
4544 );
4545 // gauge needs value XOR num+den
4546 let err = mk("{ kind: gauge, num: a }", "{ analytics: T }").unwrap_err();
4547 assert!(err.contains("needs either `value`"), "err: {err}");
4548 mk("{ kind: gauge, value: a }", "{ analytics: T }").expect("gauge value ok");
4549 mk("{ kind: gauge, num: a, den: a }", "{ analytics: T }").expect("gauge num/den ok");
4550 // unknown kind rejected
4551 let err = mk("{ kind: sunburst }", "{ analytics: T }").unwrap_err();
4552 assert!(
4553 err.contains("render.kind is not a known value"),
4554 "err: {err}"
4555 );
4556 // placement must surface somewhere
4557 let err = mk("{ kind: table }", "{}").unwrap_err();
4558 assert!(err.contains("placement must set"), "err: {err}");
4559 // a `dashboard: { pin: false }` block still surfaces nowhere.
4560 let err = mk("{ kind: table }", "{ dashboard: { pin: false } }").unwrap_err();
4561 assert!(err.contains("placement must set"), "err: {err}");
4562 mk("{ kind: table }", "{ dashboard: { pin: true } }").expect("pinned dashboard ok");
4563 // limit: 0 on a bar/pie is an invisible widget — rejected.
4564 let err = mk(
4565 "{ kind: bar, label: a, value: a, limit: 0 }",
4566 "{ analytics: T }",
4567 )
4568 .unwrap_err();
4569 assert!(err.contains("limit must be >= 1"), "err: {err}");
4570 // bad refresh duration rejected
4571 let err = view_from(
4572 "sql_widgets:
4573 - { title: W, query: \"SELECT 1\", refresh: \"6 sidereal days\", render: { kind: table }, placement: { analytics: T } }
4574",
4575 )
4576 .validate()
4577 .unwrap_err();
4578 assert!(
4579 err.contains("refresh") && err.contains("not a valid duration"),
4580 "err: {err}"
4581 );
4582 // table is fine with no channels
4583 mk("{ kind: table }", "{ analytics: T }").expect("bare table ok");
4584 }
4585
4586 #[test]
4587 fn rewrite_pc_id_param_is_literal_and_boundary_aware() {
4588 // A real param outside any literal is rewritten + counted.
4589 let (sql, n) = rewrite_pc_id_param("SELECT * FROM t WHERE pc_id = :pc_id");
4590 assert_eq!(n, 1);
4591 assert!(sql.ends_with("pc_id = ?"), "sql: {sql}");
4592 // Appearing twice → two `?`, count 2 (one bind each — the caller binds
4593 // pc_id per occurrence since sqlx-sqlite has no named params).
4594 let (sql, n) = rewrite_pc_id_param("WHERE a = :pc_id AND (:pc_id IS NOT NULL)");
4595 assert_eq!(n, 2);
4596 assert_eq!(sql, "WHERE a = ? AND (? IS NOT NULL)");
4597 // Inside a string literal → copied verbatim, NOT counted (would else be
4598 // a bind-count mismatch → SQLITE_RANGE, and misclassify scope).
4599 let (sql, n) = rewrite_pc_id_param("SELECT 'see :pc_id docs' AS hint");
4600 assert_eq!(n, 0);
4601 assert_eq!(sql, "SELECT 'see :pc_id docs' AS hint");
4602 // Inside a comment → left alone.
4603 let (_, n) = rewrite_pc_id_param("SELECT 1 -- filter by :pc_id\n");
4604 assert_eq!(n, 0);
4605 // A longer identifier prefix (`:pc_idx`) is not our token.
4606 let (sql, n) = rewrite_pc_id_param("WHERE x = :pc_idx");
4607 assert_eq!(n, 0);
4608 assert_eq!(sql, "WHERE x = :pc_idx");
4609 }
4610
4611 #[test]
4612 fn validate_rejects_pinned_per_pc_widget() {
4613 // A per-PC widget (binds :pc_id) that also pins to the Dashboard is a
4614 // create-time contradiction (Dashboard is fleet-scope) — rejected.
4615 let err = view_from(
4616 "sql_widgets:
4617 - title: W
4618 query: \"SELECT count(*) AS n FROM inventory_sw_apps WHERE pc_id = :pc_id\"
4619 render: { kind: stat, value: n }
4620 placement: { analytics: Security, dashboard: { pin: true } }
4621",
4622 )
4623 .validate()
4624 .unwrap_err();
4625 assert!(err.contains("per-PC widget"), "err: {err}");
4626 // The same widget WITHOUT the pin is fine (per-PC, analytics only).
4627 view_from(
4628 "sql_widgets:
4629 - title: W
4630 query: \"SELECT count(*) AS n FROM inventory_sw_apps WHERE pc_id = :pc_id\"
4631 render: { kind: stat, value: n }
4632 placement: { analytics: Security }
4633",
4634 )
4635 .validate()
4636 .expect("per-PC analytics-only widget is valid");
4637 }
4638
4639 fn execute_with(
4640 script: Option<&str>,
4641 script_file: Option<&str>,
4642 script_object: Option<&str>,
4643 ) -> Execute {
4644 Execute {
4645 shell: ExecuteShell::Powershell,
4646 script: script.map(str::to_owned),
4647 script_file: script_file.map(str::to_owned),
4648 script_object: script_object.map(str::to_owned),
4649 timeout: "30s".into(),
4650 run_as: RunAs::default(),
4651 cwd: None,
4652 }
4653 }
4654
4655 #[test]
4656 fn validate_accepts_inline_script() {
4657 let e = execute_with(Some("echo hi"), None, None);
4658 assert!(e.validate_script_source().is_ok());
4659 }
4660
4661 #[test]
4662 fn validate_accepts_script_file_alone() {
4663 let e = execute_with(None, Some("scripts/cleanup.ps1"), None);
4664 assert!(e.validate_script_source().is_ok());
4665 }
4666
4667 #[test]
4668 fn validate_accepts_script_object_alone() {
4669 let e = execute_with(None, None, Some("cleanup/1.0.0"));
4670 assert!(e.validate_script_source().is_ok());
4671 }
4672
4673 #[test]
4674 fn validate_treats_empty_inline_script_as_unset() {
4675 // `script: ""` + `script_object` set is the natural shape
4676 // when an operator comments out the YAML block-scalar body
4677 // but leaves the key. Should pass.
4678 let e = execute_with(Some(""), None, Some("cleanup/1.0.0"));
4679 assert!(e.validate_script_source().is_ok());
4680 }
4681
4682 #[test]
4683 fn validate_rejects_zero_sources() {
4684 let e = execute_with(None, None, None);
4685 let err = e.validate_script_source().unwrap_err();
4686 assert!(err.contains("must be set"), "got: {err}");
4687 }
4688
4689 #[test]
4690 fn validate_rejects_empty_inline_only() {
4691 let e = execute_with(Some(""), None, None);
4692 let err = e.validate_script_source().unwrap_err();
4693 assert!(err.contains("must be set"), "got: {err}");
4694 }
4695
4696 #[test]
4697 fn validate_rejects_inline_plus_file() {
4698 let e = execute_with(Some("echo hi"), Some("scripts/cleanup.ps1"), None);
4699 let err = e.validate_script_source().unwrap_err();
4700 assert!(err.contains("only one of"), "got: {err}");
4701 }
4702
4703 #[test]
4704 fn validate_rejects_inline_plus_object() {
4705 let e = execute_with(Some("echo hi"), None, Some("cleanup/1.0.0"));
4706 let err = e.validate_script_source().unwrap_err();
4707 assert!(err.contains("only one of"), "got: {err}");
4708 }
4709
4710 #[test]
4711 fn validate_rejects_file_plus_object() {
4712 let e = execute_with(None, Some("scripts/cleanup.ps1"), Some("cleanup/1.0.0"));
4713 let err = e.validate_script_source().unwrap_err();
4714 assert!(err.contains("only one of"), "got: {err}");
4715 }
4716
4717 #[test]
4718 fn validate_rejects_all_three() {
4719 let e = execute_with(
4720 Some("echo hi"),
4721 Some("scripts/cleanup.ps1"),
4722 Some("cleanup/1.0.0"),
4723 );
4724 let err = e.validate_script_source().unwrap_err();
4725 assert!(err.contains("only one of"), "got: {err}");
4726 }
4727
4728 #[test]
4729 fn validate_rejects_blank_script_file() {
4730 // #918: a blank `script_file` used to count as "set" and pass
4731 // the exactly-one check, then fail at use time (the CLI reads
4732 // a file named "").
4733 for blank in ["", " "] {
4734 let e = execute_with(None, Some(blank), None);
4735 let err = e.validate_script_source().unwrap_err();
4736 assert!(err.contains("script_file must not be blank"), "got: {err}");
4737 }
4738 }
4739
4740 #[test]
4741 fn validate_rejects_blank_script_object() {
4742 // #918: same for a blank `script_object` (would 404 every exec).
4743 for blank in ["", " "] {
4744 let e = execute_with(None, None, Some(blank));
4745 let err = e.validate_script_source().unwrap_err();
4746 assert!(
4747 err.contains("script_object must not be blank"),
4748 "got: {err}"
4749 );
4750 }
4751 }
4752
4753 #[test]
4754 fn validate_treats_whitespace_inline_script_as_unset() {
4755 // #918: a whitespace-only inline body is a commented-out block,
4756 // not a real script — with no other source it's "zero sources".
4757 let e = execute_with(Some(" \n "), None, None);
4758 let err = e.validate_script_source().unwrap_err();
4759 assert!(err.contains("must be set"), "got: {err}");
4760 }
4761
4762 #[test]
4763 fn validate_rejects_malformed_script_object_ref() {
4764 // #918: the ref must be `<name>/<version>`; a missing slash,
4765 // extra slash, blank half, or whitespace-padded half (the last
4766 // survives a JSON POST body and 404s at exec — gemini/claude
4767 // #943) can never resolve.
4768 for bad in [
4769 "no-slash", "a/b/c", "/1.0.0", "cleanup/", " / ", "foo/bar ", " foo/bar", "foo /bar",
4770 ] {
4771 let e = execute_with(None, None, Some(bad));
4772 let err = e.validate_script_source().unwrap_err();
4773 assert!(
4774 err.contains("must be `<name>/<version>`"),
4775 "for '{bad}', got: {err}"
4776 );
4777 }
4778 }
4779
4780 #[test]
4781 fn manifest_deserialises_script_object_yaml() {
4782 // SPEC §2.4.1 example shape with the Object Store
4783 // reference picked over inline.
4784 let yaml = r#"
4785id: cleanup-disk-temp
4786version: 1.0.1
4787execute:
4788 shell: powershell
4789 script_object: cleanup-disk-temp/1.0.1
4790 timeout: 600s
4791"#;
4792 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4793 assert_eq!(
4794 m.execute.script_object.as_deref(),
4795 Some("cleanup-disk-temp/1.0.1")
4796 );
4797 assert!(m.execute.script.is_none());
4798 m.validate()
4799 .expect("script_object-only manifest passes validation");
4800 }
4801
4802 #[test]
4803 fn manifest_rejects_typo_in_script_field_name() {
4804 // #492: the strict create boundary catches `script_objectt`
4805 // and similar fat-fingers (with the full path) instead of
4806 // letting them silently fall through to "all three unset".
4807 let yaml = r#"
4808id: typo
4809version: 1.0.0
4810execute:
4811 shell: powershell
4812 script_objectt: oops
4813 timeout: 30s
4814"#;
4815 let err = crate::strict::from_yaml_str::<Manifest>(yaml)
4816 .expect_err("typo'd execute field must be rejected at the write boundary");
4817 assert!(err.contains("execute.script_objectt"), "{err}");
4818 }
4819
4820 #[test]
4821 fn schedule_carries_target_and_rollout() {
4822 let yaml = r#"
4823id: hourly-cleanup-canary
4824when:
4825 per_pc: { every: 1h }
4826job_id: cleanup
4827enabled: true
4828target:
4829 groups: [canary, wave1]
4830jitter: 30s
4831rollout:
4832 strategy: wave
4833 waves:
4834 - { group: canary, delay: 0s }
4835 - { group: wave1, delay: 5s }
4836"#;
4837 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4838 assert_eq!(s.id, "hourly-cleanup-canary");
4839 assert_eq!(s.job_id, "cleanup");
4840 assert_eq!(s.plan.target.groups, vec!["canary", "wave1"]);
4841 assert_eq!(s.plan.jitter.as_deref(), Some("30s"));
4842 let rollout = s.plan.rollout.expect("rollout present");
4843 assert_eq!(rollout.waves.len(), 2);
4844 assert_eq!(rollout.waves[0].group, "canary");
4845 assert_eq!(rollout.waves[1].delay, "5s");
4846 assert_eq!(rollout.strategy, RolloutStrategy::Wave);
4847 }
4848
4849 #[test]
4850 fn schedule_minimal_target_all() {
4851 let yaml = r#"
4852id: kitting
4853when:
4854 per_pc: once
4855enabled: true
4856job_id: scheduled-echo
4857target: { all: true }
4858"#;
4859 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4860 assert_eq!(s.id, "kitting");
4861 assert_eq!(s.when, When::PerPc(PerPolicy::Once(OnceLiteral::Once)));
4862 assert!(s.enabled);
4863 assert_eq!(s.job_id, "scheduled-echo");
4864 assert!(s.plan.target.all);
4865 assert!(s.plan.rollout.is_none());
4866 assert!(s.plan.jitter.is_none());
4867 assert!(s.active.is_empty());
4868 }
4869
4870 #[test]
4871 fn schedule_enabled_defaults_to_true() {
4872 let yaml = r#"
4873id: x
4874when:
4875 per_pc: once
4876job_id: y
4877target: { all: true }
4878"#;
4879 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4880 assert!(s.enabled);
4881 }
4882
4883 fn once_per_version_yaml(runs_on: &str, per: &str) -> String {
4884 format!(
4885 "id: x\nwhen:\n {per}\njob_id: install-kanade-client\n\
4886 target: {{ groups: [dejisen] }}\nruns_on: {runs_on}\n"
4887 )
4888 }
4889
4890 #[test]
4891 fn per_pc_once_per_version_parses() {
4892 let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
4893 "backend",
4894 "per_pc: once_per_version",
4895 ))
4896 .expect("parse");
4897 assert_eq!(
4898 s.when,
4899 When::PerPc(PerPolicy::OncePerVersion(
4900 OncePerVersionLiteral::OncePerVersion
4901 ))
4902 );
4903 }
4904
4905 #[test]
4906 fn per_pc_once_per_version_lowers_to_version_mode_no_cooldown() {
4907 let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
4908 "backend",
4909 "per_pc: once_per_version",
4910 ))
4911 .expect("parse");
4912 let l = s.lowered();
4913 assert_eq!(l.mode, ExecMode::OncePerPcVersion);
4914 assert_eq!(l.cooldown, None, "version re-arm is not a cooldown");
4915 }
4916
4917 #[test]
4918 fn once_per_version_displays_and_serialises() {
4919 let w = When::PerPc(PerPolicy::OncePerVersion(
4920 OncePerVersionLiteral::OncePerVersion,
4921 ));
4922 assert_eq!(w.to_string(), "per_pc once_per_version");
4923 // serde round-trips through the ergonomic bare string.
4924 let json = serde_json::to_value(&w).unwrap();
4925 assert_eq!(json, serde_json::json!({ "per_pc": "once_per_version" }));
4926 }
4927
4928 #[test]
4929 fn once_per_version_rejects_typo() {
4930 // The distinct literal still catches typos (no free-form String).
4931 let r: Result<Schedule, _> = serde_yaml::from_str(&once_per_version_yaml(
4932 "backend",
4933 "per_pc: once_per_verison",
4934 ));
4935 assert!(r.is_err(), "typo should not parse");
4936 }
4937
4938 #[test]
4939 fn validate_accepts_once_per_version_on_backend() {
4940 let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
4941 "backend",
4942 "per_pc: once_per_version",
4943 ))
4944 .expect("parse");
4945 assert!(s.validate().is_ok(), "got: {:?}", s.validate());
4946 }
4947
4948 #[test]
4949 fn validate_rejects_once_per_version_on_agent() {
4950 let s: Schedule =
4951 serde_yaml::from_str(&once_per_version_yaml("agent", "per_pc: once_per_version"))
4952 .expect("parse");
4953 let err = s
4954 .validate()
4955 .expect_err("agent + once_per_version must be rejected");
4956 assert!(err.contains("once_per_version"), "got: {err}");
4957 assert!(err.contains("backend"), "got: {err}");
4958 }
4959
4960 #[test]
4961 fn validate_rejects_once_per_version_on_per_target() {
4962 let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
4963 "backend",
4964 "per_target: once_per_version",
4965 ))
4966 .expect("parse");
4967 let err = s
4968 .validate()
4969 .expect_err("per_target + once_per_version must be rejected");
4970 assert!(err.contains("once_per_version"), "got: {err}");
4971 assert!(err.contains("per_pc"), "got: {err}");
4972 }
4973
4974 #[test]
4975 fn schedule_tags_default_empty_and_skip_serialise() {
4976 let yaml = r#"
4977id: x
4978when:
4979 per_pc: once
4980job_id: y
4981target: { all: true }
4982"#;
4983 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4984 assert!(s.tags.is_empty());
4985 s.validate().expect("tag-less schedule validates");
4986 let json = serde_json::to_string(&s).expect("serialize");
4987 assert!(
4988 !json.contains("tags"),
4989 "empty tags must not serialise: {json}"
4990 );
4991 }
4992
4993 #[test]
4994 fn schedule_parses_and_validates_tags() {
4995 let yaml = r#"
4996id: weekly-cleanup
4997when:
4998 per_pc: { every: 1h }
4999job_id: cleanup
5000target: { all: true }
5001tags: [weekly, maintenance]
5002"#;
5003 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5004 assert_eq!(s.tags, vec!["weekly", "maintenance"]);
5005 s.validate().expect("tagged schedule validates");
5006 }
5007
5008 #[test]
5009 fn schedule_rejects_blank_tag() {
5010 let yaml = r#"
5011id: x
5012when:
5013 per_pc: once
5014job_id: y
5015target: { all: true }
5016tags: [ok, " "]
5017"#;
5018 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5019 let err = s.validate().expect_err("blank tag must fail");
5020 assert!(err.contains("tags must not contain empty"), "err: {err}");
5021 }
5022
5023 // ---- `when` parsing (#418 Phase 1) ----
5024
5025 fn schedule_yaml_with(when_block: &str) -> String {
5026 format!(
5027 r#"
5028id: x
5029when:
5030{when_block}
5031job_id: y
5032target: {{ all: true }}
5033"#
5034 )
5035 }
5036
5037 #[test]
5038 fn when_per_pc_every_parses_unquoted_humantime() {
5039 // `6h` is digit-led but non-numeric → YAML string, same as
5040 // the old `cooldown: 6h` convention. No quotes needed.
5041 let s: Schedule =
5042 serde_yaml::from_str(&schedule_yaml_with(" per_pc: { every: 6h }")).expect("parse");
5043 assert_eq!(
5044 s.when,
5045 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() }))
5046 );
5047 }
5048
5049 #[test]
5050 fn when_per_target_every_parses() {
5051 let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(" per_target: { every: 24h }"))
5052 .expect("parse");
5053 assert_eq!(
5054 s.when,
5055 When::PerTarget(PerPolicy::Every(EverySpec {
5056 every: "24h".into()
5057 }))
5058 );
5059 }
5060
5061 #[test]
5062 fn when_per_target_once_parses() {
5063 // Falls out of the shared PerPolicy shape and decide_fire
5064 // already implements it ("any one pc succeeds → skip the
5065 // target forever"), so it is allowed, not rejected.
5066 let s: Schedule =
5067 serde_yaml::from_str(&schedule_yaml_with(" per_target: once")).expect("parse");
5068 assert_eq!(s.when, When::PerTarget(PerPolicy::Once(OnceLiteral::Once)));
5069 }
5070
5071 #[test]
5072 fn when_calendar_time_parses() {
5073 let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(
5074 " calendar:\n at: \"09:00\"\n days: [mon-fri]",
5075 ))
5076 .expect("parse");
5077 match &s.when {
5078 When::Calendar(c) => {
5079 assert_eq!(c.at, "09:00");
5080 assert_eq!(c.days, vec!["mon-fri"]);
5081 }
5082 other => panic!("expected calendar, got {other:?}"),
5083 }
5084 }
5085
5086 #[test]
5087 fn when_calendar_days_default_empty() {
5088 let s: Schedule =
5089 serde_yaml::from_str(&schedule_yaml_with(" calendar:\n at: \"09:00\""))
5090 .expect("parse");
5091 match &s.when {
5092 When::Calendar(c) => assert!(c.days.is_empty(), "days defaults to empty (= daily)"),
5093 other => panic!("expected calendar, got {other:?}"),
5094 }
5095 }
5096
5097 #[test]
5098 fn when_calendar_datetime_parses_all_separators() {
5099 // one-shot: date+time in hyphen / ISO-T / slash forms
5100 for at in ["2026-06-10 09:00", "2026-06-10T09:00", "2026/06/10 09:00"] {
5101 let block = format!(" calendar:\n at: \"{at}\"");
5102 let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(&block))
5103 .unwrap_or_else(|e| panic!("parse '{at}': {e}"));
5104 match &s.when {
5105 When::Calendar(c) => {
5106 use chrono::Datelike;
5107 let p = c.parse_at().expect("parse_at");
5108 let d = p.date.expect("datetime at carries a date");
5109 assert_eq!((d.year(), d.month(), d.day()), (2026, 6, 10), "for '{at}'");
5110 }
5111 other => panic!("expected calendar, got {other:?}"),
5112 }
5113 }
5114 }
5115
5116 #[test]
5117 fn when_rejects_bad_once_keyword() {
5118 // `onec` must be a parse error, not a silently-absorbed
5119 // string (OnceLiteral is a single-variant enum for exactly
5120 // this reason).
5121 let r: Result<Schedule, _> = serde_yaml::from_str(&schedule_yaml_with(" per_pc: onec"));
5122 assert!(r.is_err(), "expected parse error, got {r:?}");
5123 }
5124
5125 #[test]
5126 fn when_rejects_unknown_key_in_every() {
5127 // `{ evry: 6h }` still fails on the tolerant read path: the
5128 // required `every` key is missing, so no PerPolicy variant
5129 // matches (#492 removed deny_unknown_fields, but required
5130 // keys keep the untagged disambiguation honest).
5131 let r: Result<Schedule, _> =
5132 serde_yaml::from_str(&schedule_yaml_with(" per_pc: { evry: 6h }"));
5133 assert!(r.is_err(), "expected parse error, got {r:?}");
5134 }
5135
5136 #[test]
5137 fn when_rejects_unknown_variant() {
5138 let r: Result<Schedule, _> =
5139 serde_yaml::from_str(&schedule_yaml_with(" per_galaxy: once"));
5140 assert!(r.is_err(), "expected parse error, got {r:?}");
5141 }
5142
5143 #[test]
5144 fn when_rejects_old_top_level_cron_field() {
5145 // Pre-#418 shape: top-level `cron:` + no `when:`. Must fail
5146 // loudly (missing `when`), which is what turns stale KV
5147 // blobs into warn-skips after the upgrade.
5148 let yaml = r#"
5149id: x
5150cron: "* * * * * *"
5151job_id: y
5152target: { all: true }
5153"#;
5154 let r: Result<Schedule, _> = serde_yaml::from_str(yaml);
5155 assert!(r.is_err(), "expected parse error, got {r:?}");
5156 }
5157
5158 #[test]
5159 fn when_rejects_retired_cron_escape_hatch() {
5160 // #418 Phase 2 retired `when: { cron: "..." }`. A raw cron
5161 // is now an unknown variant → parse error (operators use the
5162 // calendar form instead).
5163 let r: Result<Schedule, _> =
5164 serde_yaml::from_str(&schedule_yaml_with(" cron: \"0 0 9 * * mon-fri\""));
5165 assert!(
5166 r.is_err(),
5167 "expected parse error for retired cron, got {r:?}"
5168 );
5169 }
5170
5171 #[test]
5172 fn when_round_trips_json_and_yaml() {
5173 // Round-trip through the full Schedule: that is the wire
5174 // unit for both stores (JSON catalog KV + YAML mirror), and
5175 // it exercises the singleton_map field attribute that keeps
5176 // serde_yaml on the map shape instead of `!per_pc` tags.
5177 for when in [
5178 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5179 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5180 When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5181 When::PerTarget(PerPolicy::Every(EverySpec {
5182 every: "24h".into(),
5183 })),
5184 calendar("09:00", &["mon-fri"]),
5185 calendar("2026-06-10 09:00", &[]),
5186 When::On(vec![OnTrigger::Startup]),
5187 When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
5188 When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
5189 When::On(vec![OnTrigger::NetworkChange]),
5190 ] {
5191 // Event triggers are agent-only; the rest validate on backend.
5192 let runs_on = if matches!(when, When::On(_)) {
5193 RunsOn::Agent
5194 } else {
5195 RunsOn::Backend
5196 };
5197 let s = schedule_with(when.clone(), runs_on);
5198
5199 let json = serde_json::to_string(&s).expect("json serialise");
5200 let back: Schedule = serde_json::from_str(&json).expect("json deserialise");
5201 assert_eq!(back.when, when, "json round-trip for {when}");
5202
5203 let yaml = serde_yaml::to_string(&s).expect("yaml serialise");
5204 assert!(
5205 !yaml.contains('!'),
5206 "yaml must use the map shape, not tags: {yaml}"
5207 );
5208 let back: Schedule = serde_yaml::from_str(&yaml).expect("yaml deserialise");
5209 assert_eq!(back.when, when, "yaml round-trip for {when}");
5210 }
5211 }
5212
5213 #[test]
5214 fn when_once_serialises_as_bare_keyword() {
5215 // The wire shape operators see in the YAML mirror must stay
5216 // the ergonomic `per_pc: once`, not a one-variant map.
5217 let json = serde_json::to_value(When::PerPc(PerPolicy::Once(OnceLiteral::Once)))
5218 .expect("serialise");
5219 assert_eq!(json, serde_json::json!({ "per_pc": "once" }));
5220 }
5221
5222 #[test]
5223 fn when_displays_operator_summary() {
5224 for (when, expected) in [
5225 (
5226 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5227 "per_pc once",
5228 ),
5229 (
5230 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5231 "per_pc every 6h",
5232 ),
5233 (
5234 When::PerTarget(PerPolicy::Every(EverySpec {
5235 every: "24h".into(),
5236 })),
5237 "per_target every 24h",
5238 ),
5239 (calendar("09:00", &["mon-fri"]), "at 09:00 [mon-fri]"),
5240 (calendar("2026-06-10 09:00", &[]), "at 2026-06-10 09:00"),
5241 (When::On(vec![OnTrigger::Startup]), "on [startup]"),
5242 (
5243 When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
5244 "on [startup,logon]",
5245 ),
5246 (
5247 When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
5248 "on [lock,unlock]",
5249 ),
5250 (
5251 When::On(vec![OnTrigger::NetworkChange]),
5252 "on [network_change]",
5253 ),
5254 ] {
5255 assert_eq!(when.to_string(), expected);
5256 }
5257 }
5258
5259 // ---- lowering (#418: when → engine vocabulary) ----
5260
5261 fn schedule_with(when: When, runs_on: RunsOn) -> Schedule {
5262 Schedule {
5263 id: "x".into(),
5264 when,
5265 job_id: "y".into(),
5266 // #917: validate() now rejects a target that dispatches
5267 // nothing, so the baseline helper carries the simplest
5268 // specified target.
5269 plan: FanoutPlan {
5270 target: Target {
5271 all: true,
5272 ..Target::default()
5273 },
5274 ..FanoutPlan::default()
5275 },
5276 active: Active::default(),
5277 constraints: Constraints::default(),
5278 on_failure: OnFailure::default(),
5279 tz: ScheduleTz::default(),
5280 starting_deadline: None,
5281 runs_on,
5282 enabled: true,
5283 tags: Vec::new(),
5284 origin: None,
5285 }
5286 }
5287
5288 fn calendar(at: &str, days: &[&str]) -> When {
5289 When::Calendar(CalendarSpec {
5290 at: at.into(),
5291 days: days.iter().map(|d| (*d).to_string()).collect(),
5292 })
5293 }
5294
5295 #[test]
5296 fn next_calendar_fire_returns_next_utc_occurrence() {
5297 use chrono::TimeZone;
5298 // Daily 09:00, evaluated in UTC. From 08:00 the same day, the
5299 // next strict occurrence is 09:00 that day.
5300 let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5301 s.tz = ScheduleTz::Utc;
5302 let now = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 8, 0, 0).unwrap();
5303 let next = s.next_calendar_fire(now).expect("calendar has a next fire");
5304 assert_eq!(
5305 next,
5306 chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap()
5307 );
5308 }
5309
5310 #[test]
5311 fn next_calendar_fire_is_strictly_after_now() {
5312 use chrono::TimeZone;
5313 // Standing exactly on a fire instant must preview the *next*
5314 // one (inclusive = false), not the one firing right now.
5315 let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5316 s.tz = ScheduleTz::Utc;
5317 let on_fire = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap();
5318 let next = s
5319 .next_calendar_fire(on_fire)
5320 .expect("calendar has a next fire");
5321 assert_eq!(
5322 next,
5323 chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()
5324 );
5325 }
5326
5327 #[test]
5328 fn next_calendar_fire_none_for_reconcile_shapes() {
5329 // `per_pc` / `per_target` lower to the every-minute poll cron —
5330 // no discrete upcoming event to preview, so `None`.
5331 let now = chrono::Utc::now();
5332 for when in [
5333 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5334 When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5335 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5336 When::PerTarget(PerPolicy::Every(EverySpec {
5337 every: "24h".into(),
5338 })),
5339 ] {
5340 let s = schedule_with(when, RunsOn::Backend);
5341 assert!(
5342 s.next_calendar_fire(now).is_none(),
5343 "reconcile shapes have no calendar fire",
5344 );
5345 }
5346 }
5347
5348 // ---- preview_fires (#418 dry-run / preview) ----
5349
5350 fn cal_utc(at: &str, days: &[&str]) -> Schedule {
5351 let mut s = schedule_with(calendar(at, days), RunsOn::Backend);
5352 s.tz = ScheduleTz::Utc; // host-independent assertions
5353 s
5354 }
5355
5356 #[test]
5357 fn preview_lists_next_calendar_occurrences() {
5358 use chrono::TimeZone;
5359 // Weekday 09:00, from Wed 2026-06-10 00:00 UTC: the next five
5360 // fires skip the weekend (Sat 13 / Sun 14).
5361 let s = cal_utc("09:00", &["mon-fri"]);
5362 let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5363 let got = s.preview_fires(now, 5);
5364 let want: Vec<_> = [
5365 (2026, 6, 10), // Wed
5366 (2026, 6, 11), // Thu
5367 (2026, 6, 12), // Fri
5368 (2026, 6, 15), // Mon (skips Sat 13 / Sun 14)
5369 (2026, 6, 16), // Tue
5370 ]
5371 .iter()
5372 .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
5373 .collect();
5374 assert_eq!(got, want);
5375 }
5376
5377 #[test]
5378 fn preview_handles_nth_and_last_weekday() {
5379 use chrono::TimeZone;
5380 let now = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
5381 // 2nd Tuesday (Patch Tuesday): Jun 9, Jul 14 2026.
5382 let nth = cal_utc("09:00", &["tue#2"]).preview_fires(now, 2);
5383 assert_eq!(
5384 nth,
5385 vec![
5386 chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap(),
5387 chrono::Utc.with_ymd_and_hms(2026, 7, 14, 9, 0, 0).unwrap(),
5388 ]
5389 );
5390 // Last Friday of the month: Jun 26, Jul 31 2026.
5391 let last = cal_utc("22:00", &["friL"]).preview_fires(now, 2);
5392 assert_eq!(
5393 last,
5394 vec![
5395 chrono::Utc.with_ymd_and_hms(2026, 6, 26, 22, 0, 0).unwrap(),
5396 chrono::Utc.with_ymd_and_hms(2026, 7, 31, 22, 0, 0).unwrap(),
5397 ]
5398 );
5399 }
5400
5401 #[test]
5402 fn preview_is_empty_for_reconcile_and_zero_count() {
5403 let now = chrono::Utc::now();
5404 // reconcile shapes have no discrete fire times
5405 let recon = schedule_with(
5406 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5407 RunsOn::Backend,
5408 );
5409 assert!(recon.preview_fires(now, 5).is_empty());
5410 // count == 0 yields nothing even for a calendar
5411 assert!(cal_utc("09:00", &[]).preview_fires(now, 0).is_empty());
5412 }
5413
5414 #[test]
5415 fn preview_skips_outside_active_window() {
5416 use chrono::TimeZone;
5417 // Daily 09:00, active only [2026-06-15, 2026-06-17). Occurrences
5418 // before `from` are skipped; `until` is exclusive, so 06-17's
5419 // fire is out — leaving exactly the 15th and 16th.
5420 let mut s = cal_utc("09:00", &[]);
5421 s.active = Active {
5422 from: Some("2026-06-15".into()),
5423 until: Some("2026-06-17".into()),
5424 };
5425 let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5426 let got = s.preview_fires(now, 5);
5427 assert_eq!(
5428 got,
5429 vec![
5430 chrono::Utc.with_ymd_and_hms(2026, 6, 15, 9, 0, 0).unwrap(),
5431 chrono::Utc.with_ymd_and_hms(2026, 6, 16, 9, 0, 0).unwrap(),
5432 ]
5433 );
5434 }
5435
5436 #[test]
5437 fn preview_empty_when_calendar_time_outside_window() {
5438 use chrono::TimeZone;
5439 // Fires at 09:00 but the maintenance window is overnight — it can
5440 // never run, so the preview is empty (matches
5441 // `calendar_outside_window`), and the scan still terminates.
5442 let mut s = cal_utc("09:00", &[]);
5443 s.constraints = Constraints {
5444 window: Some("22:00-05:00".into()),
5445 ..Constraints::default()
5446 };
5447 let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5448 assert!(s.preview_fires(now, 5).is_empty());
5449 // Every candidate tick is rejected, so this also exercises the
5450 // SCAN_CAP bound: a large `count` must still terminate (and
5451 // return empty) rather than spin (claude #578 review).
5452 assert!(s.preview_fires(now, 50).is_empty());
5453 }
5454
5455 #[test]
5456 fn preview_past_one_shot_is_empty() {
5457 use chrono::TimeZone;
5458 // A dated one-shot whose instant has passed never fires again.
5459 let s = cal_utc("2026-06-10 09:00", &[]);
5460 let now = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 0, 0, 0).unwrap();
5461 assert!(s.preview_fires(now, 5).is_empty());
5462 // …but from before it, the single future fire shows up.
5463 let before = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
5464 assert_eq!(
5465 s.preview_fires(before, 5),
5466 vec![chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()]
5467 );
5468 }
5469
5470 #[test]
5471 fn lowering_matches_the_418_table() {
5472 let cases = [
5473 (
5474 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5475 (POLL_CRON, ExecMode::OncePerPc, None),
5476 ),
5477 (
5478 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5479 (POLL_CRON, ExecMode::OncePerPc, Some("6h")),
5480 ),
5481 (
5482 When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5483 (POLL_CRON, ExecMode::OncePerTarget, None),
5484 ),
5485 (
5486 When::PerTarget(PerPolicy::Every(EverySpec {
5487 every: "24h".into(),
5488 })),
5489 (POLL_CRON, ExecMode::OncePerTarget, Some("24h")),
5490 ),
5491 // calendar repeating → 6-field cron
5492 (
5493 calendar("09:00", &["mon-fri"]),
5494 ("0 0 9 * * mon-fri", ExecMode::EveryTick, None),
5495 ),
5496 // calendar daily (no days) → DOW *
5497 (
5498 calendar("18:30", &[]),
5499 ("0 30 18 * * *", ExecMode::EveryTick, None),
5500 ),
5501 // calendar one-shot → 7-field year cron
5502 (
5503 calendar("2026-06-10 09:00", &[]),
5504 ("0 0 9 10 6 * 2026", ExecMode::EveryTick, None),
5505 ),
5506 ];
5507 for (when, (cron, mode, cooldown)) in cases {
5508 let l = schedule_with(when.clone(), RunsOn::Backend).lowered();
5509 assert_eq!(l.cron, cron, "cron for {when}");
5510 assert_eq!(l.mode, mode, "mode for {when}");
5511 assert_eq!(l.cooldown.as_deref(), cooldown, "cooldown for {when}");
5512 }
5513 }
5514
5515 #[test]
5516 fn lowered_carries_schedule_tz() {
5517 for (tz, want) in [
5518 (ScheduleTz::Local, ScheduleTz::Local),
5519 (ScheduleTz::Utc, ScheduleTz::Utc),
5520 ] {
5521 let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
5522 s.tz = tz;
5523 assert_eq!(s.lowered().tz, want, "calendar carries tz");
5524 // reconcile shapes carry tz too (for the active-window check)
5525 let mut s = schedule_with(
5526 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5527 RunsOn::Backend,
5528 );
5529 s.tz = tz;
5530 assert_eq!(s.lowered().tz, want, "reconcile carries tz");
5531 }
5532 }
5533
5534 #[test]
5535 fn poll_cron_is_accepted_by_the_engine_parser() {
5536 // POLL_CRON is system-generated — if the engine's parser
5537 // ever rejected it every reconcile schedule would die at
5538 // register time. Validate it with the same croner config
5539 // (Seconds::Required, dom_and_dow, year optional).
5540 croner::parser::CronParser::builder()
5541 .seconds(croner::parser::Seconds::Required)
5542 .dom_and_dow(true)
5543 .build()
5544 .parse(POLL_CRON)
5545 .expect("POLL_CRON must parse");
5546 }
5547
5548 // ---- Schedule::validate() (#418 decision F) ----
5549
5550 #[test]
5551 fn validate_accepts_reconcile_shapes() {
5552 for when in [
5553 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5554 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5555 When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5556 When::PerTarget(PerPolicy::Every(EverySpec {
5557 every: "24h".into(),
5558 })),
5559 ] {
5560 schedule_with(when.clone(), RunsOn::Backend)
5561 .validate()
5562 .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
5563 }
5564 }
5565
5566 #[test]
5567 fn validate_accepts_per_pc_on_agent() {
5568 schedule_with(
5569 When::PerPc(PerPolicy::Every(EverySpec { every: "1h".into() })),
5570 RunsOn::Agent,
5571 )
5572 .validate()
5573 .expect("per_pc + agent is the offline-inventory shape");
5574 }
5575
5576 // ---- #418 event triggers (when: { on }) ----
5577
5578 #[test]
5579 fn validate_accepts_event_on_agent() {
5580 for triggers in [
5581 vec![OnTrigger::Startup],
5582 vec![OnTrigger::Logon],
5583 vec![OnTrigger::Lock],
5584 vec![OnTrigger::Unlock],
5585 vec![OnTrigger::NetworkChange],
5586 vec![
5587 OnTrigger::Startup,
5588 OnTrigger::Logon,
5589 OnTrigger::Lock,
5590 OnTrigger::Unlock,
5591 OnTrigger::NetworkChange,
5592 ],
5593 ] {
5594 schedule_with(When::On(triggers), RunsOn::Agent)
5595 .validate()
5596 .expect("when.on is valid on runs_on: agent");
5597 }
5598 }
5599
5600 #[test]
5601 fn validate_rejects_event_on_backend() {
5602 let err = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Backend)
5603 .validate()
5604 .unwrap_err();
5605 assert!(err.contains("when.on"), "got: {err}");
5606 assert!(err.contains("runs_on: agent"), "got: {err}");
5607 }
5608
5609 #[test]
5610 fn validate_rejects_empty_event_list() {
5611 let err = schedule_with(When::On(vec![]), RunsOn::Agent)
5612 .validate()
5613 .unwrap_err();
5614 assert!(err.contains("when.on"), "got: {err}");
5615 assert!(err.contains("at least one"), "got: {err}");
5616 }
5617
5618 #[test]
5619 fn event_schedule_lowers_to_event_mode_and_is_event() {
5620 let s = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Agent);
5621 assert!(s.is_event());
5622 assert_eq!(s.lowered().mode, ExecMode::Event);
5623 assert_eq!(s.event_triggers(), &[OnTrigger::Startup]);
5624 // non-event schedules report no triggers.
5625 let cal = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5626 assert!(!cal.is_event());
5627 assert!(cal.event_triggers().is_empty());
5628 }
5629
5630 // ---- #418 constraints.require (env gates) ----
5631
5632 fn require_schedule(req: Require, runs_on: RunsOn) -> Schedule {
5633 let mut s = schedule_with(
5634 When::PerPc(PerPolicy::Every(EverySpec { every: "1m".into() })),
5635 runs_on,
5636 );
5637 s.constraints.require = Some(req);
5638 s
5639 }
5640
5641 #[test]
5642 fn require_met_combinations() {
5643 use std::time::Duration;
5644 let idle = |m: u64| Some(Duration::from_secs(m * 60));
5645 // Builder for the sensed state: (ac, idle, cpu, network).
5646 let env = |ac, idle, cpu, net| EnvState {
5647 ac_online: ac,
5648 idle,
5649 cpu_pct: cpu,
5650 network_up: net,
5651 };
5652 // Empty require — always met regardless of sensed state.
5653 assert!(require_met(
5654 &Require::default(),
5655 &env(false, None, None, false)
5656 ));
5657 // ac_power: only on AC.
5658 let ac = Require {
5659 ac_power: true,
5660 ..Default::default()
5661 };
5662 assert!(!require_met(&ac, &env(false, None, None, true)));
5663 assert!(require_met(&ac, &env(true, None, None, false)));
5664 // idle: needs >= the configured min; None idle never satisfies.
5665 let idle10 = Require {
5666 idle: Some("10m".into()),
5667 ..Default::default()
5668 };
5669 assert!(!require_met(&idle10, &env(true, None, None, true)));
5670 assert!(!require_met(&idle10, &env(true, idle(5), None, true)));
5671 assert!(require_met(&idle10, &env(true, idle(15), None, true)));
5672 assert!(require_met(&idle10, &env(true, idle(10), None, true))); // boundary inclusive
5673 // cpu_below: needs CPU strictly < threshold; None cpu never satisfies.
5674 let cpu20 = Require {
5675 cpu_below: Some(20.0),
5676 ..Default::default()
5677 };
5678 assert!(!require_met(&cpu20, &env(true, None, None, true))); // no sample → fail-closed
5679 assert!(!require_met(&cpu20, &env(true, None, Some(20.0), true))); // == threshold
5680 assert!(!require_met(&cpu20, &env(true, None, Some(55.0), true))); // busy
5681 assert!(require_met(&cpu20, &env(true, None, Some(5.0), true))); // quiet
5682 // network: only when online.
5683 let net = Require {
5684 network: true,
5685 ..Default::default()
5686 };
5687 assert!(!require_met(&net, &env(true, None, None, false))); // offline
5688 assert!(require_met(&net, &env(true, None, None, true))); // online
5689 // all four: AND.
5690 let all = Require {
5691 ac_power: true,
5692 idle: Some("10m".into()),
5693 cpu_below: Some(20.0),
5694 network: true,
5695 };
5696 assert!(!require_met(&all, &env(false, idle(20), Some(5.0), true))); // on battery
5697 assert!(!require_met(&all, &env(true, idle(1), Some(5.0), true))); // not idle enough
5698 assert!(!require_met(&all, &env(true, idle(20), Some(50.0), true))); // busy
5699 assert!(!require_met(&all, &env(true, idle(20), Some(5.0), false))); // offline
5700 assert!(require_met(&all, &env(true, idle(20), Some(5.0), true)));
5701 // An unparseable idle is treated as no-requirement by require_met
5702 // (validate rejects it at create time, so this only guards a
5703 // hand-edited blob): ac still gates.
5704 let bad = Require {
5705 ac_power: true,
5706 idle: Some("garbage".into()),
5707 ..Default::default()
5708 };
5709 assert!(require_met(&bad, &env(true, None, None, true)));
5710 assert!(!require_met(&bad, &env(false, None, None, true)));
5711 }
5712
5713 #[test]
5714 fn validate_accepts_and_rejects_cpu_below() {
5715 // In-range accepted.
5716 require_schedule(
5717 Require {
5718 cpu_below: Some(20.0),
5719 ..Default::default()
5720 },
5721 RunsOn::Agent,
5722 )
5723 .validate()
5724 .expect("cpu_below 20 is valid");
5725 // Upper boundary: 100.0 is accepted (fires unless CPU is exactly
5726 // 100%). Pins the inclusive upper bound against a future c < 100.0.
5727 require_schedule(
5728 Require {
5729 cpu_below: Some(100.0),
5730 ..Default::default()
5731 },
5732 RunsOn::Agent,
5733 )
5734 .validate()
5735 .expect("cpu_below 100 is valid");
5736 // Out of range rejected (0 and >100).
5737 for bad in [0.0, -5.0, 100.1] {
5738 let err = require_schedule(
5739 Require {
5740 cpu_below: Some(bad),
5741 ..Default::default()
5742 },
5743 RunsOn::Agent,
5744 )
5745 .validate()
5746 .unwrap_err();
5747 assert!(
5748 err.contains("constraints.require.cpu_below"),
5749 "cpu_below {bad}: {err}"
5750 );
5751 }
5752 }
5753
5754 #[test]
5755 fn validate_accepts_require_on_agent() {
5756 require_schedule(
5757 Require {
5758 ac_power: true,
5759 idle: Some("10m".into()),
5760 cpu_below: Some(20.0),
5761 network: true,
5762 },
5763 RunsOn::Agent,
5764 )
5765 .validate()
5766 .expect("constraints.require is valid on runs_on: agent");
5767 }
5768
5769 #[test]
5770 fn validate_rejects_require_on_backend() {
5771 let err = require_schedule(
5772 Require {
5773 ac_power: true,
5774 ..Default::default()
5775 },
5776 RunsOn::Backend,
5777 )
5778 .validate()
5779 .unwrap_err();
5780 assert!(err.contains("constraints.require"), "got: {err}");
5781 assert!(err.contains("runs_on: agent"), "got: {err}");
5782
5783 // An idle-only require (ac_power: false) is also non-empty
5784 // (is_empty folds the fields) and must reject on backend too —
5785 // guards against a regression in Require::is_empty.
5786 let err = require_schedule(
5787 Require {
5788 idle: Some("10m".into()),
5789 ..Default::default()
5790 },
5791 RunsOn::Backend,
5792 )
5793 .validate()
5794 .unwrap_err();
5795 assert!(
5796 err.contains("constraints.require"),
5797 "idle-only on backend: {err}"
5798 );
5799 }
5800
5801 #[test]
5802 fn validate_rejects_bad_require_idle() {
5803 let err = require_schedule(
5804 Require {
5805 idle: Some("not-a-duration".into()),
5806 ..Default::default()
5807 },
5808 RunsOn::Agent,
5809 )
5810 .validate()
5811 .unwrap_err();
5812 assert!(err.contains("constraints.require.idle"), "got: {err}");
5813 }
5814
5815 #[test]
5816 fn require_round_trips_and_skips_empty() {
5817 // ac_power: false is skipped; an all-default require nested in
5818 // constraints is omitted (is_empty folds it in).
5819 let yaml = "id: s\nwhen: { per_pc: { every: 1m } }\njob_id: j\nruns_on: agent\n\
5820 constraints: { require: { ac_power: true, idle: 10m, cpu_below: 20, \
5821 network: true } }\n";
5822 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5823 let req = s.constraints.require.as_ref().expect("require present");
5824 assert!(req.ac_power);
5825 assert_eq!(req.idle.as_deref(), Some("10m"));
5826 assert_eq!(req.cpu_below, Some(20.0));
5827 assert!(req.network);
5828 // Re-serialize: idle + cpu_below + network present, ac_power true.
5829 let back = serde_json::to_string(&s.constraints).unwrap();
5830 assert!(back.contains("\"idle\":\"10m\""), "got: {back}");
5831 assert!(back.contains("\"cpu_below\":20"), "got: {back}");
5832 assert!(back.contains("\"network\":true"), "got: {back}");
5833 // An empty require is omitted entirely by is_empty.
5834 let mut empty = s.clone();
5835 empty.constraints.require = Some(Require::default());
5836 assert!(empty.constraints.is_empty());
5837 }
5838
5839 #[test]
5840 fn validate_rejects_per_target_on_agent() {
5841 let err = schedule_with(
5842 When::PerTarget(PerPolicy::Every(EverySpec {
5843 every: "24h".into(),
5844 })),
5845 RunsOn::Agent,
5846 )
5847 .validate()
5848 .unwrap_err();
5849 assert!(err.contains("per_target"), "got: {err}");
5850 assert!(err.contains("runs_on: agent"), "got: {err}");
5851
5852 // per_target: once is also backend-only.
5853 let err = schedule_with(
5854 When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5855 RunsOn::Agent,
5856 )
5857 .validate()
5858 .unwrap_err();
5859 assert!(err.contains("per_target"), "got (once): {err}");
5860 assert!(err.contains("runs_on: agent"), "got (once): {err}");
5861 }
5862
5863 #[test]
5864 fn validate_rejects_bad_every_duration() {
5865 let err = schedule_with(
5866 When::PerPc(PerPolicy::Every(EverySpec { every: "6x".into() })),
5867 RunsOn::Backend,
5868 )
5869 .validate()
5870 .unwrap_err();
5871 assert!(err.contains("when.every"), "got: {err}");
5872 }
5873
5874 #[test]
5875 fn validate_rejects_bad_jitter_and_starting_deadline() {
5876 let mut s = schedule_with(
5877 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5878 RunsOn::Backend,
5879 );
5880 s.plan.jitter = Some("5x".into());
5881 let err = s.validate().unwrap_err();
5882 assert!(err.contains("jitter"), "got: {err}");
5883
5884 let mut s = schedule_with(
5885 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5886 RunsOn::Backend,
5887 );
5888 s.starting_deadline = Some("soon".into());
5889 let err = s.validate().unwrap_err();
5890 assert!(err.contains("starting_deadline"), "got: {err}");
5891 }
5892
5893 #[test]
5894 fn validate_rejects_unspecified_target() {
5895 // #917 (1): an all-default target never dispatches anywhere —
5896 // runs_on: agent silently never fires, runs_on: backend
5897 // warn-fails every tick at the exec boundary. Both rejected.
5898 for runs_on in [RunsOn::Backend, RunsOn::Agent] {
5899 let mut s = schedule_with(When::PerPc(PerPolicy::Once(OnceLiteral::Once)), runs_on);
5900 s.plan.target = Target::default();
5901 let err = s.validate().unwrap_err();
5902 assert!(err.contains("target"), "for {runs_on:?}, got: {err}");
5903 }
5904 }
5905
5906 /// A Schedule with every top-level field populated so each one
5907 /// actually serialises (the optional ones are `skip_serializing_if`).
5908 fn fully_populated_schedule() -> Schedule {
5909 let mut s = schedule_with(
5910 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5911 RunsOn::Backend,
5912 );
5913 s.plan.rollout = Some(Rollout {
5914 strategy: RolloutStrategy::Wave,
5915 waves: vec![Wave {
5916 group: "canary".into(),
5917 delay: "0s".into(),
5918 }],
5919 });
5920 s.plan.jitter = Some("5m".into());
5921 s.plan.deadline_at = Some(chrono::Utc::now());
5922 s.active = Active {
5923 from: Some("2026-01-01 00:00".into()),
5924 until: Some("2026-12-31 00:00".into()),
5925 };
5926 s.constraints = Constraints {
5927 window: Some("09:00-17:00".into()),
5928 ..Constraints::default()
5929 };
5930 s.on_failure = OnFailure {
5931 retry: Some(Retry {
5932 max: 1,
5933 backoff: "10s".into(),
5934 }),
5935 };
5936 s.starting_deadline = Some("30m".into());
5937 s.tags = vec!["health".into()];
5938 s.origin = Some(RepoOrigin {
5939 path: "configs/schedules/x.yaml".into(),
5940 repo: None,
5941 script_file: None,
5942 });
5943 s
5944 }
5945
5946 #[test]
5947 fn schedule_top_level_keys_cover_serialized_fields() {
5948 // #924 drift guard: the hand-maintained TOP_LEVEL_KEYS list must
5949 // match exactly what a fully-populated Schedule serialises — so a
5950 // future field added to Schedule or FanoutPlan can't slip past
5951 // the flatten-aware strict guard by being forgotten here.
5952 let s = fully_populated_schedule();
5953 let value = serde_json::to_value(&s).expect("serialize schedule");
5954 let serialized: std::collections::BTreeSet<String> = value
5955 .as_object()
5956 .expect("schedule serialises to an object")
5957 .keys()
5958 .cloned()
5959 .collect();
5960 let listed: std::collections::BTreeSet<String> = Schedule::TOP_LEVEL_KEYS
5961 .iter()
5962 .map(|s| s.to_string())
5963 .collect();
5964 assert_eq!(
5965 serialized, listed,
5966 "TOP_LEVEL_KEYS is out of sync with Schedule's serialized fields \
5967 (flatten-aware strict guard would miss a real field or reject a valid one)"
5968 );
5969 }
5970
5971 #[test]
5972 fn strict_rejects_flatten_hidden_top_level_typo() {
5973 // #924: a top-level typo on a flattening type (jiter / enabledd)
5974 // is buffered into the flatten target by serde and hidden from
5975 // serde_ignored — the top-level guard must catch it. Verified on
5976 // both the YAML and JSON strict boundaries.
5977 let yaml = "\
5978id: s1
5979job_id: j1
5980when:
5981 per_pc: once
5982target:
5983 all: true
5984jiter: 5m
5985";
5986 let err = crate::strict::from_yaml_str::<Schedule>(yaml).unwrap_err();
5987 assert!(err.contains("jiter"), "got: {err}");
5988
5989 let json = serde_json::json!({
5990 "id": "s1",
5991 "job_id": "j1",
5992 "when": { "per_pc": "once" },
5993 "target": { "all": true },
5994 "enabledd": false,
5995 });
5996 let err = crate::strict::from_json_slice::<Schedule>(&serde_json::to_vec(&json).unwrap())
5997 .unwrap_err();
5998 assert!(err.contains("enabledd"), "got: {err}");
5999 }
6000
6001 #[test]
6002 fn strict_accepts_all_valid_schedule_top_level_keys() {
6003 // The guard must not reject any legitimate key — round-trip a
6004 // fully-populated schedule through the strict YAML boundary.
6005 let s = fully_populated_schedule();
6006 let yaml = serde_yaml::to_string(&s).expect("serialize");
6007 crate::strict::from_yaml_str::<Schedule>(&yaml)
6008 .expect("every serialized key must be accepted by the strict guard");
6009 }
6010
6011 #[test]
6012 fn strict_rejects_non_string_top_level_yaml_key() {
6013 // #924 (gemini #945): a YAML key isn't always a string — an
6014 // unquoted `true:` parses as a boolean, `123:` as a number. A
6015 // `filter_map` on `as_str()` would drop these and let them slip
6016 // past the flatten guard; `yaml_key_label` renders them so they
6017 // are still rejected. (serde_yaml is YAML 1.2, so `on:` stays a
6018 // *string* "on" — also rejected, just via the string path.)
6019 let base = "\
6020id: s1
6021job_id: j1
6022when:
6023 per_pc: once
6024target:
6025 all: true
6026";
6027 for (extra, needle) in [
6028 ("true: x\n", "true"),
6029 ("123: x\n", "123"),
6030 ("on: y\n", "on"),
6031 ] {
6032 let yaml = format!("{base}{extra}");
6033 let err = crate::strict::from_yaml_str::<Schedule>(&yaml).unwrap_err();
6034 assert!(err.contains(needle), "for '{extra}', got: {err}");
6035 }
6036 }
6037
6038 #[test]
6039 fn validate_accepts_waves_instead_of_target_on_backend() {
6040 // #917 (1): the exec boundary accepts rollout-only plans
6041 // (target then just labels the audit row) — so does validate.
6042 let mut s = schedule_with(
6043 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6044 RunsOn::Backend,
6045 );
6046 s.plan.target = Target::default();
6047 s.plan.rollout = Some(Rollout {
6048 strategy: RolloutStrategy::Wave,
6049 waves: vec![Wave {
6050 group: "canary".into(),
6051 delay: "0s".into(),
6052 }],
6053 });
6054 s.validate().expect("rollout-only plan should validate");
6055 }
6056
6057 #[test]
6058 fn validate_rejects_rollout_on_agent() {
6059 // #917 (1): rollout waves are backend-published; a runs_on:
6060 // agent schedule never reads them, so the combination is a
6061 // silent no-op — reject like max_concurrent-on-agent.
6062 let mut s = schedule_with(
6063 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6064 RunsOn::Agent,
6065 );
6066 s.plan.rollout = Some(Rollout {
6067 strategy: RolloutStrategy::Wave,
6068 waves: vec![Wave {
6069 group: "canary".into(),
6070 delay: "0s".into(),
6071 }],
6072 });
6073 let err = s.validate().unwrap_err();
6074 assert!(err.contains("rollout"), "got: {err}");
6075 }
6076
6077 #[test]
6078 fn validate_rejects_bad_waves() {
6079 // #917 (2): empty waves, blank group, unparseable delay — all
6080 // previously accepted and failed (or no-opped) at every fire.
6081 let base = || {
6082 schedule_with(
6083 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6084 RunsOn::Backend,
6085 )
6086 };
6087
6088 let mut s = base();
6089 s.plan.rollout = Some(Rollout {
6090 strategy: RolloutStrategy::Wave,
6091 waves: vec![],
6092 });
6093 let err = s.validate().unwrap_err();
6094 assert!(err.contains("at least one wave"), "got: {err}");
6095
6096 let mut s = base();
6097 s.plan.rollout = Some(Rollout {
6098 strategy: RolloutStrategy::Wave,
6099 waves: vec![Wave {
6100 group: " ".into(),
6101 delay: "0s".into(),
6102 }],
6103 });
6104 let err = s.validate().unwrap_err();
6105 assert!(err.contains("waves[0].group"), "got: {err}");
6106
6107 let mut s = base();
6108 s.plan.rollout = Some(Rollout {
6109 strategy: RolloutStrategy::Wave,
6110 waves: vec![
6111 Wave {
6112 group: "canary".into(),
6113 delay: "0s".into(),
6114 },
6115 Wave {
6116 group: "wave1".into(),
6117 delay: "5 minuts".into(),
6118 },
6119 ],
6120 });
6121 let err = s.validate().unwrap_err();
6122 assert!(err.contains("waves[1].delay"), "got: {err}");
6123 }
6124
6125 #[test]
6126 fn validate_rejects_wave_delay_at_or_past_starting_deadline() {
6127 // #917 (3): the deadline is stamped once at tick time, so a
6128 // wave sleeping >= starting_deadline publishes already-expired
6129 // Commands — dead on arrival, every fire.
6130 let mut s = schedule_with(
6131 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6132 RunsOn::Backend,
6133 );
6134 s.starting_deadline = Some("30m".into());
6135 s.plan.rollout = Some(Rollout {
6136 strategy: RolloutStrategy::Wave,
6137 waves: vec![
6138 Wave {
6139 group: "canary".into(),
6140 delay: "0s".into(),
6141 },
6142 Wave {
6143 group: "wave1".into(),
6144 delay: "30m".into(),
6145 },
6146 ],
6147 });
6148 let err = s.validate().unwrap_err();
6149 assert!(
6150 err.contains("waves[1].delay") && err.contains("starting_deadline"),
6151 "got: {err}"
6152 );
6153
6154 // Strictly shorter is fine.
6155 s.plan.rollout.as_mut().unwrap().waves[1].delay = "29m".into();
6156 s.validate().expect("delay < deadline should validate");
6157 }
6158
6159 #[test]
6160 fn validate_rejects_operator_set_deadline_at() {
6161 // #917 (4): machine-stamped field — the scheduler overwrites it
6162 // on every fire, so a hand-set value is silently discarded.
6163 let mut s = schedule_with(
6164 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6165 RunsOn::Backend,
6166 );
6167 s.plan.deadline_at = Some(chrono::Utc::now());
6168 let err = s.validate().unwrap_err();
6169 assert!(
6170 err.contains("deadline_at") && err.contains("starting_deadline"),
6171 "got: {err}"
6172 );
6173 }
6174
6175 #[test]
6176 fn validate_accepts_calendar_shapes() {
6177 for when in [
6178 calendar("09:00", &["mon-fri"]), // weekday morning
6179 calendar("00:00", &["sun"]), // weekly
6180 calendar("18:30", &[]), // daily
6181 calendar("2026-06-10 09:00", &[]), // one-shot
6182 calendar("2026/12/25 00:00", &[]), // one-shot, slash form
6183 ] {
6184 schedule_with(when.clone(), RunsOn::Backend)
6185 .validate()
6186 .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
6187 }
6188 }
6189
6190 #[test]
6191 fn validate_rejects_bad_at() {
6192 for bad in ["25:00", "09:60", "9", "noon", "2026-13-01 09:00"] {
6193 let err = schedule_with(calendar(bad, &[]), RunsOn::Backend)
6194 .validate()
6195 .unwrap_err();
6196 assert!(err.contains("when.at"), "for '{bad}', got: {err}");
6197 }
6198 }
6199
6200 #[test]
6201 fn validate_rejects_datetime_at_with_days() {
6202 // A dated `at` is a one-shot — pairing it with days is a
6203 // contradiction (the date already pins the day).
6204 let err = schedule_with(calendar("2026-06-10 09:00", &["mon"]), RunsOn::Backend)
6205 .validate()
6206 .unwrap_err();
6207 assert!(
6208 err.contains("one-shot") && err.contains("days"),
6209 "got: {err}"
6210 );
6211 }
6212
6213 #[test]
6214 fn validate_rejects_bad_day_name() {
6215 // A garbage DOW token is caught by the days pre-flight and
6216 // reported against `when.days`, not the confusing
6217 // "when.at lowered to invalid cron" (claude #432 review).
6218 let err = schedule_with(calendar("09:00", &["funday"]), RunsOn::Backend)
6219 .validate()
6220 .unwrap_err();
6221 assert!(err.contains("when.days"), "got: {err}");
6222 assert!(err.contains("funday"), "names the bad token: {err}");
6223 // a degenerate range like `mon-` reports the whole token, not
6224 // a cryptic empty part (claude #432 follow-up)
6225 let err = schedule_with(calendar("09:00", &["mon-"]), RunsOn::Backend)
6226 .validate()
6227 .unwrap_err();
6228 assert!(err.contains("'mon-'"), "names the whole token: {err}");
6229 // valid names / ranges / numeric / * all pass
6230 for ok in [
6231 calendar("09:00", &["mon-fri"]),
6232 calendar("09:00", &["mon", "wed", "sun"]),
6233 calendar("09:00", &["1-5"]),
6234 ] {
6235 schedule_with(ok.clone(), RunsOn::Backend)
6236 .validate()
6237 .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6238 }
6239 }
6240
6241 #[test]
6242 fn validate_accepts_nth_weekday() {
6243 // #418: nth-weekday (Patch Tuesday). validate() also lowers to
6244 // a cron and parses it with croner, so passing here proves the
6245 // whole chain — token → DOW field → engine-acceptable cron.
6246 for ok in [
6247 calendar("09:00", &["tue#2"]), // 2nd Tuesday
6248 calendar("09:00", &["fri#1"]), // 1st Friday
6249 calendar("03:00", &["sun#5"]), // 5th Sunday
6250 calendar("09:00", &["tue#2", "thu#2"]), // a list of nths
6251 calendar("09:00", &["2#2"]), // numeric DOW + ordinal
6252 // Case-insensitive both sides: validate lowercases, croner
6253 // upper-cases the whole pattern before aliasing (claude #547).
6254 calendar("09:00", &["TUE#2"]),
6255 ] {
6256 schedule_with(ok.clone(), RunsOn::Backend)
6257 .validate()
6258 .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6259 }
6260 }
6261
6262 #[test]
6263 fn validate_rejects_bad_nth_weekday() {
6264 // ordinal out of 1..5, a range with #, and a bad day before #.
6265 for bad in ["tue#0", "tue#6", "tue#x", "mon-fri#2", "funday#2"] {
6266 let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
6267 .validate()
6268 .unwrap_err();
6269 assert!(err.contains("when.days"), "for '{bad}', got: {err}");
6270 }
6271 }
6272
6273 #[test]
6274 fn validate_accepts_last_weekday() {
6275 // #418: last-weekday (`friL` = last Friday). Like the nth case,
6276 // validate() lowers to a cron and round-trips it through croner,
6277 // so passing proves token → DOW field → engine-acceptable cron
6278 // with the verified last-<dow>-of-month semantics.
6279 for ok in [
6280 calendar("09:00", &["friL"]), // last Friday
6281 calendar("03:00", &["sunL"]), // last Sunday
6282 calendar("22:00", &["5L"]), // numeric DOW + last
6283 calendar("00:00", &["0L"]), // numeric Sunday (0…
6284 calendar("00:00", &["7L"]), // …and its 7 alias)
6285 calendar("09:00", &["monL", "friL"]), // a list of last-weekdays
6286 // Case-insensitive both the weekday and the `L` suffix:
6287 // validate lowercases the day, croner upper-cases the whole
6288 // pattern before aliasing (claude #547).
6289 calendar("09:00", &["FRIL"]),
6290 calendar("09:00", &["fril"]),
6291 ] {
6292 schedule_with(ok.clone(), RunsOn::Backend)
6293 .validate()
6294 .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6295 }
6296 }
6297
6298 #[test]
6299 fn validate_rejects_bad_last_weekday() {
6300 // bare `L` (no weekday — a footgun croner reads as Saturday), a
6301 // range with L, a bad day before L, and an internal space that
6302 // would otherwise leak a malformed cron downstream (gemini #560).
6303 for bad in ["L", "l", "mon-friL", "fundayL", "8L", "*L", "fri L"] {
6304 let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
6305 .validate()
6306 .unwrap_err();
6307 assert!(err.contains("when.days"), "for '{bad}', got: {err}");
6308 }
6309 }
6310
6311 #[test]
6312 fn calendar_oneshot_instant_detects_past() {
6313 use chrono::TimeZone;
6314 // a dated `at` resolves to an absolute instant…
6315 let c = CalendarSpec {
6316 at: "2024-01-01 09:00".into(),
6317 days: vec![],
6318 };
6319 let t = c
6320 .oneshot_instant(ScheduleTz::Utc)
6321 .expect("one-shot instant");
6322 assert_eq!(
6323 t,
6324 chrono::Utc.with_ymd_and_hms(2024, 1, 1, 9, 0, 0).unwrap()
6325 );
6326 assert!(t < chrono::Utc::now(), "2024 is in the past");
6327 // …while a repeating (time-only) calendar has no instant
6328 let rep = CalendarSpec {
6329 at: "09:00".into(),
6330 days: vec!["mon-fri".into()],
6331 };
6332 assert!(rep.oneshot_instant(ScheduleTz::Utc).is_none());
6333 }
6334
6335 fn schedule_with_active(from: Option<&str>, until: Option<&str>) -> Schedule {
6336 let mut s = schedule_with(
6337 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6338 RunsOn::Backend,
6339 );
6340 s.active = Active {
6341 from: from.map(str::to_owned),
6342 until: until.map(str::to_owned),
6343 };
6344 s
6345 }
6346
6347 #[test]
6348 fn validate_accepts_active_window() {
6349 schedule_with_active(Some("2026-07-01"), Some("2026-08-01T12:00:00+09:00"))
6350 .validate()
6351 .expect("date + rfc3339 bounds should validate");
6352 }
6353
6354 #[test]
6355 fn validate_rejects_unparseable_active_bound() {
6356 let err = schedule_with_active(Some("July 1st"), None)
6357 .validate()
6358 .unwrap_err();
6359 assert!(err.contains("active"), "got: {err}");
6360 }
6361
6362 #[test]
6363 fn validate_rejects_from_not_before_until() {
6364 let err = schedule_with_active(Some("2026-08-01"), Some("2026-07-01"))
6365 .validate()
6366 .unwrap_err();
6367 assert!(err.contains("strictly before"), "got: {err}");
6368
6369 let err = schedule_with_active(Some("2026-07-01"), Some("2026-07-01"))
6370 .validate()
6371 .unwrap_err();
6372 assert!(err.contains("strictly before"), "got: {err}");
6373 }
6374
6375 // ---- Active window semantics ----
6376
6377 #[test]
6378 fn active_window_is_half_open() {
6379 use chrono::TimeZone;
6380 let active = Active {
6381 from: Some("2026-07-01".into()),
6382 until: Some("2026-08-01".into()),
6383 };
6384 // UTC tz so the date bounds are UTC midnight.
6385 let at = |y, m, d, h| chrono::Utc.with_ymd_and_hms(y, m, d, h, 0, 0).unwrap();
6386 let c = |t| active.contains(t, ScheduleTz::Utc);
6387 assert!(!c(at(2026, 6, 30, 23)), "before from");
6388 assert!(c(at(2026, 7, 1, 0)), "at from (inclusive)");
6389 assert!(c(at(2026, 7, 15, 12)), "inside");
6390 assert!(!c(at(2026, 8, 1, 0)), "at until (exclusive)");
6391 assert!(!c(at(2026, 8, 2, 0)), "after until");
6392 }
6393
6394 #[test]
6395 fn active_empty_window_is_always_active() {
6396 assert!(Active::default().contains(chrono::Utc::now(), ScheduleTz::Local));
6397 }
6398
6399 #[test]
6400 fn active_rfc3339_bound_honours_offset_regardless_of_tz() {
6401 use chrono::TimeZone;
6402 let active = Active {
6403 from: Some("2026-07-01T09:00:00+09:00".into()),
6404 until: None,
6405 };
6406 // RFC3339 carries its own offset → tz arg is ignored.
6407 // 09:00 JST = 00:00 UTC.
6408 for tz in [ScheduleTz::Utc, ScheduleTz::Local] {
6409 assert!(
6410 !active.contains(
6411 chrono::Utc
6412 .with_ymd_and_hms(2026, 6, 30, 23, 59, 0)
6413 .unwrap(),
6414 tz
6415 )
6416 );
6417 assert!(active.contains(
6418 chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap(),
6419 tz
6420 ));
6421 }
6422 }
6423
6424 #[test]
6425 fn active_date_bound_respects_tz() {
6426 // A bare `YYYY-MM-DD` bound is midnight *in the schedule's
6427 // tz* (#418 Phase 2). The UTC interpretation is exact and
6428 // host-independent; assert that precisely.
6429 use chrono::TimeZone;
6430 let utc = Active::parse_bound("2026-07-01", ScheduleTz::Utc).expect("utc");
6431 assert_eq!(
6432 utc,
6433 chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap()
6434 );
6435
6436 // The local interpretation must equal what chrono::Local
6437 // computes for the same wall-clock midnight — proves the tz
6438 // path is wired to the host zone (the magnitude vs UTC is
6439 // host-dependent, so we compare against Local directly rather
6440 // than hard-coding the JST offset, keeping CI green on UTC
6441 // runners).
6442 let local = Active::parse_bound("2026-07-01", ScheduleTz::Local).expect("local");
6443 let want = chrono::Local
6444 .with_ymd_and_hms(2026, 7, 1, 0, 0, 0)
6445 .single()
6446 .expect("local midnight is unambiguous")
6447 .with_timezone(&chrono::Utc);
6448 assert_eq!(local, want, "date bound resolved in host-local tz");
6449 }
6450
6451 #[test]
6452 fn active_empty_is_skipped_when_serialising() {
6453 let s = schedule_with(
6454 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6455 RunsOn::Backend,
6456 );
6457 let json = serde_json::to_value(&s).expect("serialise");
6458 assert!(
6459 json.get("active").is_none(),
6460 "empty active must not appear on the wire: {json}"
6461 );
6462 }
6463
6464 // ---- constraints.window (#418 Phase 3) ----
6465
6466 fn with_window(win: &str) -> Schedule {
6467 let mut s = schedule_with(
6468 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6469 RunsOn::Backend,
6470 );
6471 s.constraints.window = Some(win.into());
6472 s
6473 }
6474
6475 #[test]
6476 fn constraints_window_parses_and_round_trips() {
6477 let yaml = r#"
6478id: x
6479when:
6480 per_pc: { every: 6h }
6481job_id: y
6482target: { all: true }
6483constraints:
6484 window: "22:00-05:00"
6485"#;
6486 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6487 assert_eq!(s.constraints.window.as_deref(), Some("22:00-05:00"));
6488 let back: Schedule =
6489 serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
6490 assert_eq!(back.constraints.window.as_deref(), Some("22:00-05:00"));
6491 }
6492
6493 #[test]
6494 fn constraints_empty_is_skipped_when_serialising() {
6495 let s = schedule_with(
6496 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6497 RunsOn::Backend,
6498 );
6499 let json = serde_json::to_value(&s).expect("serialise");
6500 assert!(
6501 json.get("constraints").is_none(),
6502 "empty constraints must not appear on the wire: {json}"
6503 );
6504 }
6505
6506 #[test]
6507 fn window_no_constraint_always_allows() {
6508 let c = Constraints::default();
6509 assert!(c.allows(chrono::Utc::now(), ScheduleTz::Local));
6510 }
6511
6512 #[test]
6513 fn window_same_day_is_half_open() {
6514 use chrono::TimeZone;
6515 let s = with_window("09:00-17:00");
6516 let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
6517 let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
6518 assert!(!a(at(8, 59)), "before start");
6519 assert!(a(at(9, 0)), "at start (inclusive)");
6520 assert!(a(at(16, 59)), "inside");
6521 assert!(!a(at(17, 0)), "at end (exclusive)");
6522 assert!(!a(at(23, 0)), "after end");
6523 }
6524
6525 #[test]
6526 fn window_crossing_midnight() {
6527 use chrono::TimeZone;
6528 let s = with_window("22:00-05:00");
6529 let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
6530 let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
6531 assert!(a(at(22, 0)), "at start tonight");
6532 assert!(a(at(23, 30)), "late tonight");
6533 assert!(a(at(3, 0)), "early tomorrow");
6534 assert!(!a(at(5, 0)), "at end (exclusive)");
6535 assert!(!a(at(12, 0)), "midday outside");
6536 assert!(!a(at(21, 59)), "just before start");
6537 }
6538
6539 #[test]
6540 fn window_respects_tz() {
6541 // The same instant is inside the window under one tz and may
6542 // be outside under another. Compare UTC vs Local via the
6543 // host's own offset (kept CI-green on UTC runners like the
6544 // active tz test does).
6545 use chrono::TimeZone;
6546 let s = with_window("09:00-17:00");
6547 let noon_utc = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 12, 0, 0).unwrap();
6548 // Under UTC, 12:00 is inside 09:00-17:00.
6549 assert!(s.constraints.allows(noon_utc, ScheduleTz::Utc));
6550 // Under Local, the verdict tracks the host wall-clock time;
6551 // assert it matches a direct wall_time membership check.
6552 let local_t = noon_utc.with_timezone(&chrono::Local).time();
6553 let in_local = local_t >= chrono::NaiveTime::from_hms_opt(9, 0, 0).unwrap()
6554 && local_t < chrono::NaiveTime::from_hms_opt(17, 0, 0).unwrap();
6555 assert_eq!(s.constraints.allows(noon_utc, ScheduleTz::Local), in_local);
6556 }
6557
6558 #[test]
6559 fn validate_accepts_good_window() {
6560 for w in ["09:00-17:00", "22:00-05:00", "00:00-23:59"] {
6561 with_window(w)
6562 .validate()
6563 .unwrap_or_else(|e| panic!("'{w}' should validate: {e}"));
6564 }
6565 }
6566
6567 #[test]
6568 fn validate_rejects_bad_window() {
6569 for bad in ["9-5", "22:00", "22:00-22:00", "25:00-05:00", "09:00_17:00"] {
6570 let err = with_window(bad).validate().unwrap_err();
6571 assert!(
6572 err.contains("constraints.window"),
6573 "for '{bad}', got: {err}"
6574 );
6575 }
6576 }
6577
6578 // ---- constraints.skip_dates (#418 holiday exclusion) ----
6579
6580 fn with_skip_dates(dates: &[&str]) -> Schedule {
6581 let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
6582 s.tz = ScheduleTz::Utc; // host-independent date assertions
6583 s.constraints.skip_dates = dates.iter().map(|d| (*d).to_string()).collect();
6584 s
6585 }
6586
6587 #[test]
6588 fn allows_blocks_listed_skip_date() {
6589 use chrono::TimeZone;
6590 let s = with_skip_dates(&["2026-06-10", "2026-12-25"]);
6591 // Any time on a listed date is blocked (whole day).
6592 let on = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap();
6593 assert!(!s.constraints.allows(on, ScheduleTz::Utc));
6594 let on_midnight = chrono::Utc.with_ymd_and_hms(2026, 12, 25, 0, 0, 0).unwrap();
6595 assert!(!s.constraints.allows(on_midnight, ScheduleTz::Utc));
6596 // A date not in the list fires normally.
6597 let off = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
6598 assert!(s.constraints.allows(off, ScheduleTz::Utc));
6599 }
6600
6601 #[test]
6602 fn allows_corrupt_skip_date_fails_closed() {
6603 use chrono::TimeZone;
6604 // A garbled entry (only reachable via hand-edited KV) blocks
6605 // rather than silently re-enabling fires — same posture as a
6606 // corrupt window.
6607 let s = with_skip_dates(&["not-a-date"]);
6608 let any = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
6609 assert!(!s.constraints.allows(any, ScheduleTz::Utc));
6610 }
6611
6612 #[test]
6613 fn validate_accepts_good_skip_dates() {
6614 with_skip_dates(&["2026-01-01", "2026-12-25", "2027-05-03"])
6615 .validate()
6616 .expect("well-formed skip dates should validate");
6617 }
6618
6619 #[test]
6620 fn validate_rejects_bad_skip_date() {
6621 for bad in ["2026-13-01", "01-01-2026", "nope", "2026/01/01"] {
6622 let err = with_skip_dates(&[bad]).validate().unwrap_err();
6623 assert!(
6624 err.contains("constraints.skip_dates"),
6625 "for '{bad}', got: {err}"
6626 );
6627 }
6628 }
6629
6630 #[test]
6631 fn preview_skips_holidays() {
6632 use chrono::TimeZone;
6633 // Daily 09:00 with two of the next five days marked as holidays
6634 // — preview drops exactly those, since it gates on `allows`.
6635 let mut s = cal_utc("09:00", &[]);
6636 s.constraints.skip_dates = vec!["2026-06-11".into(), "2026-06-13".into()];
6637 let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
6638 let got = s.preview_fires(now, 4);
6639 let want: Vec<_> = [
6640 (2026, 6, 10),
6641 (2026, 6, 12), // skips 06-11
6642 (2026, 6, 14), // skips 06-13
6643 (2026, 6, 15),
6644 ]
6645 .iter()
6646 .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
6647 .collect();
6648 assert_eq!(got, want);
6649 }
6650
6651 // ---- constraints.max_concurrent (#418) ----
6652
6653 fn with_max_concurrent(max: u32, runs_on: RunsOn) -> Schedule {
6654 let mut s = schedule_with(
6655 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6656 runs_on,
6657 );
6658 s.constraints.max_concurrent = Some(max);
6659 s
6660 }
6661
6662 #[test]
6663 fn validate_accepts_backend_max_concurrent() {
6664 with_max_concurrent(5, RunsOn::Backend)
6665 .validate()
6666 .expect("backend max_concurrent should validate");
6667 }
6668
6669 #[test]
6670 fn validate_rejects_max_concurrent_on_agent() {
6671 // Decision E: a central running-instance cap needs a central
6672 // counter, which agents don't have.
6673 let err = with_max_concurrent(5, RunsOn::Agent)
6674 .validate()
6675 .unwrap_err();
6676 assert!(err.contains("constraints.max_concurrent"), "got: {err}");
6677 assert!(err.contains("runs_on: agent"), "got: {err}");
6678 }
6679
6680 #[test]
6681 fn validate_rejects_zero_max_concurrent() {
6682 let err = with_max_concurrent(0, RunsOn::Backend)
6683 .validate()
6684 .unwrap_err();
6685 assert!(err.contains("max_concurrent must be >= 1"), "got: {err}");
6686 }
6687
6688 #[test]
6689 fn max_concurrent_round_trips_and_skips_when_absent() {
6690 let s = with_max_concurrent(3, RunsOn::Backend);
6691 let json = serde_json::to_value(&s.constraints).expect("ser");
6692 assert_eq!(json.get("max_concurrent").and_then(|v| v.as_u64()), Some(3));
6693 // A schedule with no constraints omits the whole block.
6694 let bare = schedule_with(
6695 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6696 RunsOn::Backend,
6697 );
6698 assert!(bare.constraints.is_empty());
6699 }
6700
6701 #[test]
6702 fn window_fail_closed_on_corrupt_blob() {
6703 // A malformed window (only reachable via a hand-edited KV
6704 // blob — validate() rejects it at create) must BLOCK, not
6705 // silently allow fires during a change-freeze (gemini #452).
6706 let s = with_window("22:00_05:00");
6707 assert!(
6708 !s.constraints.allows(chrono::Utc::now(), ScheduleTz::Utc),
6709 "corrupt window fails closed"
6710 );
6711 // …and the scheduler can surface why it's stuck.
6712 assert!(
6713 s.bad_window().is_some(),
6714 "bad_window reports the parse error"
6715 );
6716 assert!(with_window("22:00-05:00").bad_window().is_none());
6717 }
6718
6719 #[test]
6720 fn calendar_outside_window_is_flagged() {
6721 // at 09:00 can never fall in 22:00-05:00 → never fires.
6722 let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
6723 s.constraints.window = Some("22:00-05:00".into());
6724 assert!(s.calendar_outside_window(), "09:00 is not in 22:00-05:00");
6725
6726 // at 23:00 IS inside the overnight window → fine.
6727 let mut s = schedule_with(calendar("23:00", &[]), RunsOn::Backend);
6728 s.constraints.window = Some("22:00-05:00".into());
6729 assert!(!s.calendar_outside_window(), "23:00 is in 22:00-05:00");
6730
6731 // reconcile shapes are never flagged (they poll every minute).
6732 let mut s = schedule_with(
6733 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6734 RunsOn::Backend,
6735 );
6736 s.constraints.window = Some("22:00-05:00".into());
6737 assert!(!s.calendar_outside_window(), "reconcile is unaffected");
6738
6739 // no window → never flagged.
6740 let s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
6741 assert!(!s.calendar_outside_window());
6742 }
6743
6744 // ---- on_failure.retry (#418 Phase 4) ----
6745
6746 fn with_retry(max: u32, backoff: &str) -> Schedule {
6747 let mut s = schedule_with(
6748 When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6749 RunsOn::Backend,
6750 );
6751 s.on_failure.retry = Some(Retry {
6752 max,
6753 backoff: backoff.into(),
6754 });
6755 s
6756 }
6757
6758 #[test]
6759 fn on_failure_parses_and_round_trips() {
6760 let yaml = r#"
6761id: x
6762when:
6763 per_pc: { every: 6h }
6764job_id: y
6765target: { all: true }
6766on_failure:
6767 retry: { max: 3, backoff: 10m }
6768"#;
6769 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6770 let r = s.on_failure.retry.as_ref().expect("retry present");
6771 assert_eq!(r.max, 3);
6772 assert_eq!(r.backoff, "10m");
6773 let back: Schedule =
6774 serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
6775 assert_eq!(back.on_failure, s.on_failure);
6776 }
6777
6778 #[test]
6779 fn on_failure_empty_is_skipped_when_serialising() {
6780 let s = schedule_with(
6781 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6782 RunsOn::Backend,
6783 );
6784 let json = serde_json::to_value(&s).expect("serialise");
6785 assert!(
6786 json.get("on_failure").is_none(),
6787 "empty on_failure must not appear on the wire: {json}"
6788 );
6789 }
6790
6791 #[test]
6792 fn validate_accepts_good_retry() {
6793 for (max, backoff) in [(1, "30s"), (3, "10m"), (10, "1h")] {
6794 with_retry(max, backoff)
6795 .validate()
6796 .unwrap_or_else(|e| panic!("retry {{max:{max}, backoff:{backoff}}}: {e}"));
6797 }
6798 }
6799
6800 #[test]
6801 fn validate_rejects_bad_backoff() {
6802 let err = with_retry(3, "soon").validate().unwrap_err();
6803 assert!(err.contains("on_failure.retry.backoff"), "got: {err}");
6804 }
6805
6806 #[test]
6807 fn validate_rejects_sub_second_backoff() {
6808 // "500ms" parses as humantime but lowers to 0s on the wire —
6809 // reject it so the operator doesn't get a silent no-wait
6810 // (coderabbit #466).
6811 for bad in ["500ms", "0s", "999ms"] {
6812 let err = with_retry(3, bad).validate().unwrap_err();
6813 assert!(
6814 err.contains("on_failure.retry.backoff must be >= 1s"),
6815 "for '{bad}', got: {err}"
6816 );
6817 }
6818 }
6819
6820 #[test]
6821 fn validate_rejects_out_of_range_max() {
6822 for bad in [0u32, 11, 1000] {
6823 let err = with_retry(bad, "10m").validate().unwrap_err();
6824 assert!(
6825 err.contains("on_failure.retry.max"),
6826 "for max={bad}, got: {err}"
6827 );
6828 }
6829 }
6830
6831 #[test]
6832 fn lowered_retry_reduces_backoff_to_seconds() {
6833 let s = with_retry(3, "10m");
6834 let spec = s.on_failure.lowered_retry().expect("a retry policy");
6835 assert_eq!(spec.max, 3);
6836 assert_eq!(spec.backoff_secs, 600);
6837 }
6838
6839 #[test]
6840 fn lowered_retry_is_none_without_policy() {
6841 let s = schedule_with(
6842 When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6843 RunsOn::Backend,
6844 );
6845 assert!(s.on_failure.lowered_retry().is_none());
6846 }
6847
6848 // ---- global change-freeze (#418 Phase 5) ----
6849
6850 #[test]
6851 fn freeze_empty_window_is_always_active() {
6852 // The big-red-button shape: no bounds = frozen until cleared.
6853 let f = Freeze::default();
6854 assert!(f.is_active(chrono::Utc::now()));
6855 }
6856
6857 #[test]
6858 fn freeze_window_is_half_open() {
6859 use chrono::TimeZone;
6860 let f = Freeze {
6861 from: Some("2026-12-20T00:00:00+00:00".into()),
6862 until: Some("2027-01-05T00:00:00+00:00".into()),
6863 reason: Some("year-end".into()),
6864 tz: ScheduleTz::Utc,
6865 };
6866 let at = |y, mo, d| chrono::Utc.with_ymd_and_hms(y, mo, d, 0, 0, 0).unwrap();
6867 assert!(!f.is_active(at(2026, 12, 19)), "before from = not frozen");
6868 assert!(f.is_active(at(2026, 12, 20)), "from is inclusive");
6869 assert!(f.is_active(at(2026, 12, 31)), "inside window");
6870 assert!(!f.is_active(at(2027, 1, 5)), "until is exclusive");
6871 assert!(!f.is_active(at(2027, 1, 6)), "after until = not frozen");
6872 }
6873
6874 #[test]
6875 fn freeze_fails_closed_on_corrupt_bound() {
6876 // A freeze is a safety switch: an unparseable bound (only
6877 // reachable via a hand-edited KV blob) must read as FROZEN, not
6878 // "fire normally" (coderabbit #472) — the opposite of `active`,
6879 // which fail-opens.
6880 let f = Freeze {
6881 from: Some("not-a-date".into()),
6882 until: None,
6883 reason: None,
6884 tz: ScheduleTz::Utc,
6885 };
6886 assert!(f.is_active(chrono::Utc::now()), "corrupt bound → frozen");
6887 }
6888
6889 #[test]
6890 fn freeze_validate_accepts_good_bounds() {
6891 Freeze {
6892 from: Some("2026-12-20".into()),
6893 until: Some("2027-01-05T12:00:00+09:00".into()),
6894 reason: None,
6895 tz: ScheduleTz::Local,
6896 }
6897 .validate()
6898 .expect("date + rfc3339 bounds should validate");
6899 // Empty (indefinite) freeze is valid.
6900 Freeze::default().validate().expect("empty freeze is valid");
6901 }
6902
6903 #[test]
6904 fn freeze_validate_rejects_bad_bound_and_inverted_window() {
6905 let err = Freeze {
6906 from: Some("never".into()),
6907 ..Default::default()
6908 }
6909 .validate()
6910 .unwrap_err();
6911 assert!(err.contains("freeze:"), "got: {err}");
6912
6913 let inverted = Freeze {
6914 from: Some("2027-01-05".into()),
6915 until: Some("2026-12-20".into()),
6916 ..Default::default()
6917 }
6918 .validate()
6919 .unwrap_err();
6920 assert!(inverted.contains("freeze.from"), "got: {inverted}");
6921 }
6922
6923 #[test]
6924 fn freeze_round_trips_and_skips_empty_fields() {
6925 let f = Freeze {
6926 from: None,
6927 until: Some("2027-01-05".into()),
6928 reason: Some("INC-1234".into()),
6929 tz: ScheduleTz::Utc,
6930 };
6931 let json = serde_json::to_value(&f).expect("serialise");
6932 assert!(json.get("from").is_none(), "empty from omitted: {json}");
6933 let back: Freeze = serde_json::from_value(json).expect("round-trip");
6934 assert_eq!(back, f);
6935 }
6936
6937 #[test]
6938 fn shipped_schedule_configs_parse_and_validate() {
6939 // Every YAML under configs/schedules/ must parse with the
6940 // current Schedule serde AND pass validate() — keeps the
6941 // shipped examples from drifting out of sync with the model
6942 // (#418 removed back-compat, so drift = broken at create).
6943 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../configs/schedules");
6944 let mut seen = 0;
6945 for entry in std::fs::read_dir(&dir).expect("read configs/schedules") {
6946 let path = entry.expect("dir entry").path();
6947 if path.extension().and_then(|e| e.to_str()) != Some("yaml") {
6948 continue;
6949 }
6950 let body = std::fs::read_to_string(&path).expect("read yaml");
6951 let s: Schedule = serde_yaml::from_str(&body)
6952 .unwrap_or_else(|e| panic!("{} failed to parse: {e}", path.display()));
6953 s.validate()
6954 .unwrap_or_else(|e| panic!("{} failed validate(): {e}", path.display()));
6955 seen += 1;
6956 }
6957 assert!(seen > 0, "no schedule YAMLs found in {}", dir.display());
6958 }
6959
6960 // ---- pre-existing enum wire formats (unchanged by #418) ----
6961
6962 #[test]
6963 fn exec_mode_serialises_snake_case() {
6964 for (mode, expected) in [
6965 (ExecMode::EveryTick, "every_tick"),
6966 (ExecMode::OncePerPc, "once_per_pc"),
6967 (ExecMode::OncePerTarget, "once_per_target"),
6968 ] {
6969 let s = serde_json::to_value(mode).expect("serialise");
6970 assert_eq!(s, serde_json::Value::String(expected.into()));
6971 let back: ExecMode = serde_json::from_value(serde_json::Value::String(expected.into()))
6972 .expect("deserialise");
6973 assert_eq!(back, mode, "round-trip for {expected}");
6974 }
6975 }
6976
6977 #[test]
6978 fn schedule_runs_on_defaults_to_backend() {
6979 let yaml = r#"
6980id: x
6981when:
6982 per_pc: once
6983job_id: y
6984target: { all: true }
6985"#;
6986 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6987 assert_eq!(s.runs_on, RunsOn::Backend);
6988 }
6989
6990 #[test]
6991 fn schedule_runs_on_agent_parses() {
6992 let yaml = r#"
6993id: offline-inv
6994when:
6995 per_pc: { every: 1h }
6996job_id: inventory-hw
6997target: { all: true }
6998runs_on: agent
6999"#;
7000 let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7001 assert_eq!(s.runs_on, RunsOn::Agent);
7002 assert_eq!(s.lowered().mode, ExecMode::OncePerPc);
7003 }
7004
7005 #[test]
7006 fn runs_on_serialises_snake_case() {
7007 for (mode, expected) in [(RunsOn::Backend, "backend"), (RunsOn::Agent, "agent")] {
7008 let s = serde_json::to_value(mode).expect("serialise");
7009 assert_eq!(s, serde_json::Value::String(expected.into()));
7010 let back: RunsOn = serde_json::from_value(serde_json::Value::String(expected.into()))
7011 .expect("deserialise");
7012 assert_eq!(back, mode);
7013 }
7014 }
7015
7016 #[test]
7017 fn execute_shell_into_wire_shell() {
7018 assert_eq!(Shell::from(ExecuteShell::Powershell), Shell::Powershell);
7019 assert_eq!(Shell::from(ExecuteShell::Cmd), Shell::Cmd);
7020 }
7021
7022 #[test]
7023 fn manifest_staleness_defaults_to_cached() {
7024 let yaml = r#"
7025id: x
7026version: 1.0.0
7027execute:
7028 shell: powershell
7029 script: "echo"
7030 timeout: 1s
7031"#;
7032 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7033 assert_eq!(m.staleness, Staleness::Cached);
7034 }
7035
7036 #[test]
7037 fn manifest_strict_staleness_parses() {
7038 let yaml = r#"
7039id: urgent-patch
7040version: 2.5.1
7041execute:
7042 shell: powershell
7043 script: Install-Hotfix
7044 timeout: 5m
7045staleness:
7046 mode: strict
7047 max_cache_age: 0s
7048"#;
7049 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7050 match m.staleness {
7051 Staleness::Strict { max_cache_age } => assert_eq!(max_cache_age, "0s"),
7052 other => panic!("expected strict, got {other:?}"),
7053 }
7054 }
7055
7056 #[test]
7057 fn manifest_unchecked_staleness_parses() {
7058 let yaml = r#"
7059id: legacy
7060version: 0.1.0
7061execute:
7062 shell: cmd
7063 script: "echo"
7064 timeout: 1s
7065staleness:
7066 mode: unchecked
7067"#;
7068 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7069 assert_eq!(m.staleness, Staleness::Unchecked);
7070 }
7071
7072 #[test]
7073 fn missing_required_field_errors() {
7074 // `id` missing.
7075 let yaml = r#"
7076version: 1.0.0
7077target: { all: true }
7078execute:
7079 shell: powershell
7080 script: "echo"
7081 timeout: 1s
7082"#;
7083 let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
7084 assert!(r.is_err(), "expected error, got {:?}", r);
7085 }
7086
7087 #[test]
7088 fn display_field_table_kind_round_trips_with_nested_columns() {
7089 // #39: `type: table` + `columns:` on a DisplayField gets
7090 // round-tripped through serde so the SPA receives the
7091 // nested schema verbatim. Nested columns themselves are
7092 // DisplayFields so they can carry `type: bytes` /
7093 // `type: number` for cell formatting.
7094 let yaml = r#"
7095id: inv-hw
7096version: 1.0.0
7097execute:
7098 shell: powershell
7099 script: "echo"
7100 timeout: 60s
7101inventory:
7102 display:
7103 - field: hostname
7104 label: Hostname
7105 - field: disks
7106 label: Disks
7107 type: table
7108 columns:
7109 - field: device_id
7110 label: Drive
7111 - field: size_bytes
7112 label: Size
7113 type: bytes
7114 - field: free_bytes
7115 label: Free
7116 type: bytes
7117 - field: file_system
7118 label: FS
7119"#;
7120 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7121 let inv = m.inventory.as_ref().expect("inventory hint");
7122 let disks = inv
7123 .display
7124 .iter()
7125 .find(|d| d.field == "disks")
7126 .expect("disks display row");
7127 assert_eq!(disks.kind.as_deref(), Some("table"));
7128 let cols = disks.columns.as_ref().expect("table needs columns");
7129 assert_eq!(cols.len(), 4);
7130 assert_eq!(cols[1].field, "size_bytes");
7131 assert_eq!(cols[1].kind.as_deref(), Some("bytes"));
7132 }
7133
7134 #[test]
7135 fn display_field_scalar_kind_keeps_columns_none() {
7136 // Defensive: when type is a scalar (`bytes` / `number` /
7137 // `timestamp`) the `columns` field stays None — the SPA
7138 // uses its presence as the "render nested table" signal,
7139 // so it must not leak in via serde defaults.
7140 let yaml = r#"
7141id: x
7142version: 1.0.0
7143execute:
7144 shell: powershell
7145 script: "echo"
7146 timeout: 5s
7147inventory:
7148 display:
7149 - { field: ram_bytes, label: RAM, type: bytes }
7150"#;
7151 let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7152 let inv = m.inventory.as_ref().unwrap();
7153 assert!(inv.display[0].columns.is_none());
7154 }
7155
7156 // ---- checked-in JSON Schema freshness (docs/schemas/) ----
7157
7158 /// The JSON Schemas under `docs/schemas/` must match what
7159 /// `schema_for!` produces today — a Cargo.lock-style freshness guard
7160 /// so a `Schedule` / `Manifest` field change can't silently drift
7161 /// the operator-facing schema. The SPA editor, the backend
7162 /// `/api/schemas/*` endpoints, and these files all read the same
7163 /// derived shape; this test fails CI if the checked-in copy lags.
7164 /// Regenerate with:
7165 /// `UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current`
7166 #[test]
7167 fn schema_files_are_current() {
7168 assert_schema_file("schedule.schema.json", &schemars::schema_for!(Schedule));
7169 assert_schema_file("job.schema.json", &schemars::schema_for!(Manifest));
7170 assert_schema_file("view.schema.json", &schemars::schema_for!(View));
7171 }
7172
7173 fn assert_schema_file(name: &str, schema: &schemars::Schema) {
7174 let generated = serde_json::to_string_pretty(schema).expect("serialize schema") + "\n";
7175 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7176 .join("../../docs/schemas")
7177 .join(name);
7178 if std::env::var_os("UPDATE_SCHEMAS").is_some() {
7179 std::fs::create_dir_all(path.parent().unwrap()).expect("mkdir docs/schemas");
7180 std::fs::write(&path, &generated).unwrap_or_else(|e| panic!("write {path:?}: {e}"));
7181 return;
7182 }
7183 // Normalize CRLF→LF before comparing: `.gitattributes` already
7184 // pins these files to `eol=lf`, but a stray CRLF working-tree
7185 // copy (autocrlf, a tool rewrite) shouldn't turn a *content*-
7186 // freshness check into a confusing line-ending failure — that's
7187 // .gitattributes' job, not this test's (gemini #588).
7188 let on_disk = std::fs::read_to_string(&path)
7189 .unwrap_or_else(|e| {
7190 panic!(
7191 "read {path:?}: {e}\n\
7192 generate it with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
7193 )
7194 })
7195 .replace("\r\n", "\n");
7196 assert_eq!(
7197 on_disk, generated,
7198 "{name} is stale — a Schedule/Manifest schema change isn't reflected in docs/schemas/. \
7199 Refresh with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
7200 );
7201 }
7202}
7203
7204/// Periodic schedule (spec §2.4.3). v0.18.0 carries the fanout plan
7205/// (target + optional rollout + optional jitter) inline; the
7206/// referenced job (`job_id` → [`BUCKET_JOBS`]) supplies only the
7207/// script body. Two schedules of the same job can target different
7208/// groups on different cadences without copying the manifest.
7209///
7210/// #418 Phase 1: the cadence is the single [`When`] field. The old
7211/// `cron` × `mode` × `cooldown` × `auto_disable_when_done` quartet
7212/// is gone (no back-compat — pre-Phase-1 KV blobs fail to parse and
7213/// are warn-skipped; re-`schedule create` to upgrade them). The
7214/// engine underneath is unchanged: [`Schedule::lowered`] maps `when`
7215/// onto the same (cron, ExecMode, cooldown) trio the scheduler and
7216/// `decide_fire` always ran on.
7217#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
7218pub struct Schedule {
7219 pub id: String,
7220 /// When to fire — a reconcile cadence (`per_pc` / `per_target`)
7221 /// or a calendar time trigger (`at` / `days`). See [`When`].
7222 ///
7223 /// `singleton_map`: serde_yaml 0.9 renders externally-tagged
7224 /// enums as `!per_pc` YAML tags by default; this keeps the
7225 /// operator-facing map shape (`when: { per_pc: once }`). JSON
7226 /// output is identical either way, and the schemars schema
7227 /// (external tagging = oneOf of single-key objects) already
7228 /// matches the singleton-map wire shape.
7229 #[serde(with = "serde_yaml::with::singleton_map")]
7230 #[schemars(with = "When")]
7231 pub when: When,
7232 /// Key into [`crate::kv::BUCKET_JOBS`]. Must equal a registered
7233 /// Manifest's `id`.
7234 pub job_id: String,
7235 /// Who + how-to-phase + when-to-stagger. The Manifest doesn't
7236 /// carry these any more — same job + different fanout = different
7237 /// schedule.
7238 #[serde(flatten)]
7239 pub plan: FanoutPlan,
7240 /// Optional validity window. Outside `[from, until)` the
7241 /// schedule is dormant — still registered, still visible, but
7242 /// every tick is skipped (deleted ≠ dormant: a campaign that
7243 /// ended stays inspectable and can be re-armed by editing the
7244 /// window). Checked at tick time on both the backend scheduler
7245 /// and the agent's local scheduler.
7246 #[serde(default, skip_serializing_if = "Active::is_empty")]
7247 pub active: Active,
7248 /// #418 operational constraints gating *when within an active
7249 /// period* a fire may happen: a maintenance `window`, a fleet
7250 /// `max_concurrent` cap, and `skip_dates` (holiday exclusion). The
7251 /// wall-clock ones are evaluated in the schedule's `tz`; future
7252 /// `require` (env gates) lands in the same namespace. Checked at
7253 /// tick time on both schedulers (and surfaced by `preview`).
7254 #[serde(default, skip_serializing_if = "Constraints::is_empty")]
7255 pub constraints: Constraints,
7256 /// #418 Phase 4: what to do after a fire's script comes back
7257 /// failed. Currently just `retry` (fixed-backoff in-process
7258 /// re-run); future `notify` / `disable` join the same namespace.
7259 /// Applied fire-side in `handle_command` (the retry policy is
7260 /// lowered onto every Command this schedule produces), so it
7261 /// covers both `runs_on` locations.
7262 #[serde(default, skip_serializing_if = "OnFailure::is_empty")]
7263 pub on_failure: OnFailure,
7264 /// #418 Phase 2: the timezone this schedule's wall-clock fields
7265 /// are evaluated in — both the calendar `at` firing time AND the
7266 /// `active.{from,until}` window bounds. `local` (default) = the
7267 /// running host's TZ (the agent's for `runs_on: agent`, the
7268 /// backend server's otherwise); `utc` for TZ-independent
7269 /// schedules. Reconcile shapes (`per_pc`/`per_target`) ignore it
7270 /// for firing (poll cron runs every minute regardless) but still
7271 /// honor it for the `active` window.
7272 #[serde(default)]
7273 pub tz: ScheduleTz,
7274 /// v0.22: optional humantime window after a cron tick during
7275 /// which the Command is still considered "live". The scheduler
7276 /// computes `tick_at + starting_deadline` and stamps it onto
7277 /// each Command as `deadline_at`; agents skip Commands they
7278 /// receive after that absolute time. `None` (default) = no
7279 /// deadline, meaning a Command queued in the broker / stream
7280 /// during agent downtime runs whenever the agent reconnects —
7281 /// good for kitting / inventory / cleanup. Set this for
7282 /// time-of-day notifications, lunch reminders, etc., where
7283 /// "fire 3 hours late" would be wrong.
7284 #[serde(default, skip_serializing_if = "Option::is_none")]
7285 pub starting_deadline: Option<String>,
7286 /// v0.23: where does the cron tick happen? `Backend` (default,
7287 /// historical) = backend's scheduler fires Commands via NATS;
7288 /// agents passively receive. `Agent` = each targeted agent runs
7289 /// its own internal cron and fires locally, so the schedule
7290 /// keeps ticking even when the broker is unreachable (laptop on
7291 /// the train, broker maintenance window, full WAN outage). The
7292 /// two locations are mutually exclusive — when `Agent`, the
7293 /// backend scheduler stays out and just keeps the definition in
7294 /// KV for agents to read.
7295 #[serde(default)]
7296 pub runs_on: RunsOn,
7297 #[serde(default = "default_true")]
7298 pub enabled: bool,
7299 /// Free-form operator taxonomy for the Schedules page — the
7300 /// schedule-side mirror of `Manifest.tags` (added in #640; a plain
7301 /// code ref rather than an intra-doc link, since that field isn't
7302 /// on this branch until #640 merges). Purely a SPA-side
7303 /// organisational aid (search / filter chips alongside the
7304 /// id-prefix grouping); the scheduler never reads it, so any
7305 /// string is allowed and it carries no firing semantics. A
7306 /// schedule's own tags are independent of its job's: the same job
7307 /// may back a `weekly` maintenance schedule and a `canary` rollout
7308 /// schedule. Empty by default and `skip_serializing_if`-elided per
7309 /// the #492 gradual-upgrade wire rule.
7310 #[serde(default, skip_serializing_if = "Vec::is_empty")]
7311 pub tags: Vec<String>,
7312 /// GitOps provenance (#695) — see [`RepoOrigin`]. Stamped by
7313 /// `kanade schedule create` when the source YAML lives inside a Git
7314 /// work tree, so the SPA renders the schedule read-only and points
7315 /// edits back at the repo (SPEC design principle #3: 設定駆動 YAML +
7316 /// Git), parity with a job's [`Manifest::origin`]. `None` for
7317 /// SPA-born schedules and ones applied from outside any repo. Purely
7318 /// informational — the scheduler never reads it. New field ⇒ #492
7319 /// wire rule (`default` + `skip_serializing_if`).
7320 #[serde(default, skip_serializing_if = "Option::is_none")]
7321 pub origin: Option<RepoOrigin>,
7322}
7323
7324impl Schedule {
7325 /// Every valid top-level key on a Schedule YAML/JSON document —
7326 /// this struct's own fields PLUS the fields of the
7327 /// `#[serde(flatten)] plan: FanoutPlan`. The strict create
7328 /// boundary needs this because serde's flatten buffering hides
7329 /// unknown top-level keys from `serde_ignored`, so a typo like
7330 /// `jiter:` or `enabledd:` would otherwise be silently dropped
7331 /// (#924). Kept in sync with the field list by
7332 /// `schedule_top_level_keys_cover_serialized_fields`.
7333 pub const TOP_LEVEL_KEYS: &'static [&'static str] = &[
7334 // Schedule's own fields:
7335 "id",
7336 "when",
7337 "job_id",
7338 "active",
7339 "constraints",
7340 "on_failure",
7341 "tz",
7342 "starting_deadline",
7343 "runs_on",
7344 "enabled",
7345 "tags",
7346 "origin",
7347 // flattened FanoutPlan:
7348 "target",
7349 "rollout",
7350 "jitter",
7351 "deadline_at",
7352 ];
7353}
7354
7355impl crate::strict::StrictSchema for Schedule {
7356 fn strict_top_level_keys() -> Option<&'static [&'static str]> {
7357 Some(Self::TOP_LEVEL_KEYS)
7358 }
7359}
7360
7361/// Manifest has no `#[serde(flatten)]` field, so `serde_ignored`
7362/// already catches every top-level typo — the default (`None`) is
7363/// correct.
7364impl crate::strict::StrictSchema for Manifest {}
7365
7366/// View likewise has no flattened field.
7367impl crate::strict::StrictSchema for View {}
7368
7369/// v0.23 — where the cron tick fires from.
7370#[derive(
7371 Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
7372)]
7373#[serde(rename_all = "snake_case")]
7374pub enum RunsOn {
7375 /// Backend's central scheduler ticks and publishes Commands to
7376 /// NATS. Historical default, what every pre-v0.23 schedule
7377 /// uses. Agent offline ⇒ Command queued in STREAM_EXEC; agent
7378 /// reconnects ⇒ catch-up via [`command_replay`](crate)
7379 /// (see kanade-agent's command_replay module).
7380 #[default]
7381 Backend,
7382 /// Each targeted agent runs the cron tick locally. Survives
7383 /// broker / WAN outages. Best for laptops / mobile devices that
7384 /// roam off the corporate network. Agent must be online for the
7385 /// initial schedule + job-catalog pull, but once cached the
7386 /// agent fires the script standalone.
7387 Agent,
7388}
7389
7390/// Per-pc/per-target dedup semantics for a [`Schedule`] (v0.19).
7391#[derive(
7392 Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
7393)]
7394#[serde(rename_all = "snake_case")]
7395pub enum ExecMode {
7396 /// Fire on every cron tick at the whole target. Historical
7397 /// (pre-v0.19) behavior; no dedup.
7398 #[default]
7399 EveryTick,
7400 /// Fire at each pc until that pc succeeds; then skip it until
7401 /// the optional cooldown elapses (or forever if no cooldown).
7402 /// Use for kitting / first-boot / per-pc compliance checks.
7403 OncePerPc,
7404 /// Fire at the whole target until **any** pc succeeds; then
7405 /// skip the whole target until the optional cooldown elapses
7406 /// (or forever if no cooldown). Use for "one delegate is
7407 /// enough" tasks like license check-in.
7408 OncePerTarget,
7409 /// Like [`OncePerPc`](ExecMode::OncePerPc), but the "already
7410 /// succeeded ⇒ skip" check is scoped to the CURRENT manifest
7411 /// version: a pc whose only successful run recorded an OLDER
7412 /// manifest version re-fires so the new version reaches it. Bumping
7413 /// the job's YAML `version` is the redistribution trigger. Plain
7414 /// `OncePerPc` (kitting) is version-blind — a pc that ever succeeded
7415 /// is skipped forever; this mode re-arms per version. per_pc only —
7416 /// `Schedule::validate` rejects `per_target: once_per_version`.
7417 OncePerPcVersion,
7418 /// #418 OS-native event trigger (`when: { on: [...] }`). There is
7419 /// no cron — the agent fires it from an OS event source (boot /
7420 /// session-change), not a tick — so the scheduler skips
7421 /// `tokio-cron` registration for it. Each event occurrence fires
7422 /// once, gated by the standard freeze / active / window /
7423 /// skip_dates checks.
7424 Event,
7425}
7426
7427/// #418 Phase 1 — the single "when does this fire" axis.
7428///
7429/// Replaces the old `cron` + `mode` + `cooldown` trio whose
7430/// interactions were implicit (cron doubled as both a real
7431/// time-of-day trigger and a reconcile poll period; contradictory
7432/// combinations silently no-opped). Two shapes:
7433///
7434/// * **reconcile** (`per_pc` / `per_target`) — desired-state: "each
7435/// pc (or one delegate) should have run this within `every`".
7436/// The poll period is system-generated ([`POLL_CRON`], every
7437/// minute) and no longer the operator's concern.
7438/// * **calendar** (`{ at, days }`) — a wall-clock time trigger
7439/// (#418 Phase 2, replacing the old raw-cron escape hatch). Fires
7440/// the whole target at the given time, no dedup. `at: "09:00"` +
7441/// `days` repeats; `at: "2026-06-10 09:00"` (a date+time) fires
7442/// exactly once. Evaluated in the schedule's top-level `tz`.
7443#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7444#[serde(rename_all = "snake_case")]
7445pub enum When {
7446 /// Fire at each targeted pc: `once` (kitting — succeed once,
7447 /// skip forever, forever catching brand-new / re-imaged pcs)
7448 /// or `{ every: <humantime> }` (patrol — re-arm per pc after
7449 /// the interval).
7450 PerPc(PerPolicy),
7451 /// Fire until **any** one pc of the target succeeds, then skip
7452 /// the whole target (`once`) or re-arm after `every`. Needs
7453 /// fleet-wide completion data, so it is backend-only —
7454 /// `runs_on: agent` + `per_target` is rejected by
7455 /// [`Schedule::validate`].
7456 PerTarget(PerPolicy),
7457 /// Calendar time trigger: `{ at: "09:00", days: [mon-fri] }`
7458 /// (repeating) or `{ at: "2026-06-10 09:00" }` (one-shot). Fires
7459 /// the whole target at that wall-clock time in the schedule's
7460 /// `tz` — no dedup, no cooldown.
7461 Calendar(CalendarSpec),
7462 /// #418 OS-native event trigger: `when: { on: [startup, logon] }`.
7463 /// Fires when the agent observes the listed OS event(s) rather than
7464 /// on a clock — there is no cron. `runs_on: agent` only (the agent
7465 /// owns the event source); [`Schedule::validate`] rejects it on
7466 /// `backend` and rejects an empty list. Each event occurrence fires
7467 /// once, gated by the same freeze / active / `constraints.window` /
7468 /// `skip_dates` checks as the cron path. `startup` fires once per OS
7469 /// boot (deduped via the host boot time); a `starting_deadline`, if
7470 /// set, limits it to "agent came up within that long after boot".
7471 On(Vec<OnTrigger>),
7472}
7473
7474/// An OS event the agent can fire a schedule on (#418 `when: { on }`).
7475#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash)]
7476#[serde(rename_all = "snake_case")]
7477pub enum OnTrigger {
7478 /// Once per OS boot (the agent's first run for that boot). Catches
7479 /// freshly-imaged / reinstalled hosts at their next startup.
7480 Startup,
7481 /// On an interactive-session user logon — console, RDP, or
7482 /// auto-logon (Windows `WTS_SESSION_LOGON`). Does not fire for
7483 /// service / network / batch logons (no interactive session).
7484 Logon,
7485 /// When the workstation is locked (Win+L / idle lock; Windows
7486 /// `WTS_SESSION_LOCK`). Use for step-away compliance / cleanup.
7487 Lock,
7488 /// When the workstation is unlocked — the user returns to a locked
7489 /// session (Windows `WTS_SESSION_UNLOCK`). Use to re-check
7490 /// compliance / refresh state when work resumes.
7491 Unlock,
7492 /// When the host's network changes — IP address table change on
7493 /// connect / disconnect / DHCP renew / VPN / Wi-Fi roam (Windows
7494 /// `NotifyAddrChange`). Debounced agent-side (a burst of changes
7495 /// from one transition fires once after the network settles), so
7496 /// use it for "re-check connectivity / re-register on network move"
7497 /// rather than expecting one fire per raw adapter event.
7498 ///
7499 /// IPv4 only: `NotifyAddrChange` watches the IPv4 address table, so a
7500 /// transition that touches only IPv6 addresses won't fire. In practice
7501 /// dual-stack networks change both tables together, but a pure-IPv6
7502 /// move (e.g. an IPv6-only Wi-Fi roam) is not detected.
7503 NetworkChange,
7504}
7505
7506/// Calendar time trigger (#418 Phase 2). `at` is either a time of
7507/// day (`"HH:MM"`, repeating — combine with `days`) or a full
7508/// date+time (`"YYYY-MM-DD HH:MM"`, a one-shot that fires once and
7509/// never again). Evaluated in the schedule's top-level `tz`.
7510#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7511pub struct CalendarSpec {
7512 /// `"HH:MM"` (24h) for a repeating trigger, or
7513 /// `"YYYY-MM-DD HH:MM"` (hyphen / slash / `T` separators all
7514 /// accepted) for a one-shot. Parsed lazily —
7515 /// [`Schedule::validate`] rejects garbage at create time.
7516 pub at: String,
7517 /// Day-of-week filter for a time-of-day `at`: `["mon-fri"]`,
7518 /// `["mon","wed","fri"]`, … (passed verbatim to the cron DOW
7519 /// field, so ranges and names both work). An **nth-weekday**
7520 /// `["tue#2"]` fires only on the 2nd Tuesday of each month
7521 /// ("Patch Tuesday"); the ordinal is `1..5`. A **last-weekday**
7522 /// `["friL"]` fires only on the last Friday of each month (handy
7523 /// for monthly maintenance). Empty = every day. Must be empty
7524 /// when `at` carries a date (the date already pins the day).
7525 #[serde(default, skip_serializing_if = "Vec::is_empty")]
7526 pub days: Vec<String>,
7527}
7528
7529/// Parsed `CalendarSpec.at`: the wall-clock minute/hour, plus the
7530/// date for a one-shot (`None` = repeating time-of-day).
7531struct ParsedAt {
7532 minute: u32,
7533 hour: u32,
7534 date: Option<chrono::NaiveDate>,
7535}
7536
7537impl CalendarSpec {
7538 /// Parse `at`: a date+time (`YYYY-MM-DD HH:MM`, hyphen / slash /
7539 /// `T` separators) is a one-shot; a bare `HH:MM` is repeating.
7540 fn parse_at(&self) -> Result<ParsedAt, String> {
7541 use chrono::Timelike;
7542 let s = self.at.trim();
7543 for fmt in ["%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y/%m/%d %H:%M"] {
7544 if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, fmt) {
7545 return Ok(ParsedAt {
7546 minute: dt.minute(),
7547 hour: dt.hour(),
7548 date: Some(dt.date()),
7549 });
7550 }
7551 }
7552 if let Ok(t) = chrono::NaiveTime::parse_from_str(s, "%H:%M") {
7553 return Ok(ParsedAt {
7554 minute: t.minute(),
7555 hour: t.hour(),
7556 date: None,
7557 });
7558 }
7559 Err(format!(
7560 "when.at: unparseable '{}' (want HH:MM or YYYY-MM-DD HH:MM)",
7561 self.at
7562 ))
7563 }
7564
7565 /// Pre-flight check on the `days` tokens so a bad day name gives
7566 /// a `when.days:`-scoped error instead of croner's confusing
7567 /// "when.at lowered to invalid cron" (claude #432 review). Each
7568 /// token is a day name (`mon`..`sun`), a numeric DOW (`0`..`7`),
7569 /// `*`, a `-` range of those, an **nth-weekday** like `tue#2`
7570 /// (2nd Tuesday of the month — "Patch Tuesday"), or a
7571 /// **last-weekday** like `friL` (last Friday of the month).
7572 fn validate_days(&self) -> Result<(), String> {
7573 const NAMES: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
7574 let is_day = |p: &str| NAMES.contains(&p) || p.parse::<u8>().is_ok_and(|n| n <= 7);
7575 for tok in &self.days {
7576 // Report the whole token on a malformed range like `mon-`
7577 // (which would otherwise split to a cryptic empty part —
7578 // claude #432 follow-up).
7579 let invalid = |reason: &str| {
7580 Err(format!(
7581 "when.days: invalid day token '{tok}' ({reason}; \
7582 want mon..sun, 0-7, a range like mon-fri, an nth-weekday \
7583 like tue#2, a last-weekday like friL, or *)"
7584 ))
7585 };
7586 // #418: nth-weekday suffix (`tue#2` = 2nd Tuesday). Croner
7587 // accepts `<dow>#<n>` (n = 1..5) in the DOW field, and
7588 // `to_cron` passes the token through verbatim, so the
7589 // engine fires only on that occurrence. It's a single
7590 // weekday + ordinal — not combinable with a range.
7591 if let Some((day_part, nth_part)) = tok.split_once('#') {
7592 // Normalize once and use `d` consistently (gemini #547);
7593 // the outer `invalid` already echoes the raw `tok`.
7594 let d = day_part.trim().to_ascii_lowercase();
7595 if d.contains('-') || !is_day(&d) {
7596 return invalid("the part before # must be a single weekday");
7597 }
7598 match nth_part.trim().parse::<u8>() {
7599 Ok(n) if (1..=5).contains(&n) => {}
7600 _ => return invalid("the # ordinal must be 1..5 (e.g. tue#2 = 2nd Tuesday)"),
7601 }
7602 continue;
7603 }
7604 // #418: last-weekday suffix (`friL` = last Friday of the
7605 // month — the monthly-maintenance sibling of Patch Tuesday).
7606 // Croner accepts `<dow>L` in the DOW field with verified
7607 // last-<dow>-of-month semantics, and `to_cron` passes it
7608 // through verbatim. A single weekday + `L` — bare `L` and
7609 // ranges are rejected (croner would read bare `L` as
7610 // Saturday, which is a confusing footgun).
7611 if let Some(day_part) = tok.strip_suffix(['L', 'l']) {
7612 // No `.trim()`: a cron DOW token can't carry internal
7613 // whitespace, so `"fri L"` must be *rejected* here (its
7614 // strip leaves `"fri "`, and `is_day` catches the space)
7615 // rather than trimmed into a clean `"fri"` that then
7616 // produces a malformed `fri L` cron downstream and a
7617 // confusing croner error (gemini #560).
7618 let d = day_part.to_ascii_lowercase();
7619 if d.is_empty() {
7620 return invalid("`L` (last-weekday) needs a weekday before it, e.g. friL");
7621 }
7622 if d.contains('-') || !is_day(&d) {
7623 return invalid(
7624 "the part before L must be a single weekday (e.g. friL = last Friday)",
7625 );
7626 }
7627 continue;
7628 }
7629 for part in tok.split('-') {
7630 let p = part.trim().to_ascii_lowercase();
7631 if p.is_empty() {
7632 return invalid("empty range bound");
7633 }
7634 if p != "*" && !is_day(&p) {
7635 return invalid(&format!("'{part}' is not a day"));
7636 }
7637 }
7638 }
7639 Ok(())
7640 }
7641
7642 /// For a one-shot (`at` carries a date), the absolute instant it
7643 /// fires in `tz`. `None` for a repeating calendar. Used to warn
7644 /// about a one-shot whose date is already in the past (it would
7645 /// never fire).
7646 pub fn oneshot_instant(&self, tz: ScheduleTz) -> Option<chrono::DateTime<chrono::Utc>> {
7647 let p = self.parse_at().ok()?;
7648 let date = p.date?;
7649 let naive = date.and_hms_opt(p.hour, p.minute, 0)?;
7650 tz.naive_to_utc(naive)
7651 }
7652
7653 /// The wall-clock time-of-day this calendar fires at (`None` if
7654 /// `at` is unparseable — validate() guards that). Used to detect
7655 /// a calendar whose fire time can never fall inside its
7656 /// `constraints.window` (claude #452 review).
7657 pub fn fire_time(&self) -> Option<chrono::NaiveTime> {
7658 let p = self.parse_at().ok()?;
7659 chrono::NaiveTime::from_hms_opt(p.hour, p.minute, 0)
7660 }
7661
7662 /// Lower to the cron string the scheduler engine runs. Repeating
7663 /// → 6-field `0 {min} {hour} * * {dow}`; one-shot → 7-field
7664 /// `0 {min} {hour} {day} {month} * {year}` (a past year never
7665 /// fires — that's what makes it one-shot).
7666 fn to_cron(&self) -> Result<String, String> {
7667 use chrono::Datelike;
7668 let ParsedAt { minute, hour, date } = self.parse_at()?;
7669 match date {
7670 Some(d) => {
7671 if !self.days.is_empty() {
7672 return Err(
7673 "when.at with a date is a one-shot and cannot be combined with days".into(),
7674 );
7675 }
7676 Ok(format!(
7677 "0 {minute} {hour} {} {} * {}",
7678 d.day(),
7679 d.month(),
7680 d.year()
7681 ))
7682 }
7683 None => {
7684 let dow = if self.days.is_empty() {
7685 "*".to_string()
7686 } else {
7687 self.validate_days()?;
7688 self.days.join(",")
7689 };
7690 Ok(format!("0 {minute} {hour} * * {dow}"))
7691 }
7692 }
7693 }
7694}
7695
7696/// The timezone a schedule's wall-clock fields (`when.at`,
7697/// `active.{from,until}`) are evaluated in (#418 Phase 2).
7698#[derive(
7699 Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
7700)]
7701#[serde(rename_all = "snake_case")]
7702pub enum ScheduleTz {
7703 /// The running host's local timezone — the agent's for
7704 /// `runs_on: agent`, the backend server's otherwise. Default.
7705 #[default]
7706 Local,
7707 /// UTC — for timezone-independent schedules.
7708 Utc,
7709}
7710
7711impl ScheduleTz {
7712 /// Interpret a naive (zoneless) datetime as being in this tz and
7713 /// convert to UTC. On a DST *fold* (the local time occurs twice
7714 /// when clocks go back) we pick `.earliest()` rather than
7715 /// rejecting it; `None` is reserved for a true DST *gap* (a local
7716 /// time that never exists). `Utc` is fixed-offset so neither ever
7717 /// happens; `Local` is whatever timezone the running host is set
7718 /// to and *can* hit a gap/fold on any DST-observing host — not
7719 /// just the JST we run today (gemini + claude #432 review).
7720 fn naive_to_utc(self, naive: chrono::NaiveDateTime) -> Option<chrono::DateTime<chrono::Utc>> {
7721 use chrono::TimeZone;
7722 match self {
7723 ScheduleTz::Utc => Some(chrono::DateTime::from_naive_utc_and_offset(
7724 naive,
7725 chrono::Utc,
7726 )),
7727 ScheduleTz::Local => chrono::Local
7728 .from_local_datetime(&naive)
7729 .earliest()
7730 .map(|dt| dt.with_timezone(&chrono::Utc)),
7731 }
7732 }
7733
7734 /// The wall-clock time-of-day `now` reads as in this tz — used by
7735 /// [`Constraints::allows`] to test a maintenance window
7736 /// (#418 Phase 3). `Utc` is the naive UTC time; `Local` is the
7737 /// running host's local time.
7738 fn wall_time(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveTime {
7739 match self {
7740 ScheduleTz::Utc => now.time(),
7741 ScheduleTz::Local => now.with_timezone(&chrono::Local).time(),
7742 }
7743 }
7744
7745 /// The wall-clock *date* `now` reads as in this tz — used by
7746 /// [`Constraints::allows`] to test `skip_dates` (#418 holiday
7747 /// exclusion). Same tz semantics as [`Self::wall_time`].
7748 fn wall_date(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveDate {
7749 match self {
7750 ScheduleTz::Utc => now.date_naive(),
7751 ScheduleTz::Local => now.with_timezone(&chrono::Local).date_naive(),
7752 }
7753 }
7754
7755 /// Stable lowercase wire/display label (`local` / `utc`) — matches
7756 /// the serde `snake_case` representation. Used for the preview
7757 /// response's `tz` field so the JSON shape isn't coupled to the
7758 /// `Debug` repr (claude #578 review).
7759 pub fn as_str(self) -> &'static str {
7760 match self {
7761 ScheduleTz::Local => "local",
7762 ScheduleTz::Utc => "utc",
7763 }
7764 }
7765}
7766
7767impl std::fmt::Display for ScheduleTz {
7768 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7769 f.write_str(self.as_str())
7770 }
7771}
7772
7773/// `once` / `once_per_version` / `{ every: <humantime> }` — shared by
7774/// `per_pc` / `per_target`. Untagged so the YAML stays the bare keyword
7775/// or a one-key map, nothing more ceremonial. `once_per_version` is
7776/// per_pc + backend only (see the variant doc and `Schedule::validate`).
7777#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7778#[serde(untagged)]
7779pub enum PerPolicy {
7780 /// The bare string `once`: succeed once, then skip permanently
7781 /// (cooldown = infinity), version-blind.
7782 Once(OnceLiteral),
7783 /// The bare string `once_per_version`: succeed once *per manifest
7784 /// version*, then skip until the job's YAML `version` changes. Like
7785 /// `once` but re-arms each pc when the version it succeeded at is no
7786 /// longer current — the version-aware redistribution shape. per_pc
7787 /// only (`Schedule::validate` rejects it on `per_target`).
7788 OncePerVersion(OncePerVersionLiteral),
7789 /// Re-arm after the humantime interval, e.g. `{ every: 6h }`.
7790 Every(EverySpec),
7791}
7792
7793/// Single-variant enum so serde accepts exactly the string `once`
7794/// (a free-form `String` would swallow typos like `onec`).
7795#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
7796#[serde(rename_all = "snake_case")]
7797pub enum OnceLiteral {
7798 Once,
7799}
7800
7801/// Single-variant enum so serde accepts exactly the string
7802/// `once_per_version` (mirrors [`OnceLiteral`]'s typo-catching). The
7803/// distinct literal — rather than a bool field on `once` — keeps the
7804/// ergonomic bare-string surface (`per_pc: once_per_version`).
7805#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
7806#[serde(rename_all = "snake_case")]
7807pub enum OncePerVersionLiteral {
7808 OncePerVersion,
7809}
7810
7811/// `{ every: <humantime> }`. Standalone struct (not an inline
7812/// struct variant). `{ evry: 6h }` still fails to parse (the
7813/// required `every` key is missing), and the create boundaries
7814/// reject the unknown `evry` via [`crate::strict`] with its path —
7815/// while agents reading a future writer's extra fields tolerate
7816/// them (#492).
7817#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7818pub struct EverySpec {
7819 /// Humantime interval (`10m`, `6h`, `1d`...). Parsed lazily —
7820 /// [`Schedule::validate`] rejects garbage at create time.
7821 pub every: String,
7822}
7823
7824impl PerPolicy {
7825 /// The cooldown this policy lowers to: `once` = `None`
7826 /// (permanent skip), `every` = the interval.
7827 fn cooldown(&self) -> Option<String> {
7828 match self {
7829 // Both `once` shapes lower to "no time-based re-arm". The
7830 // version-aware re-arm for `once_per_version` is not a
7831 // cooldown — it is the version filter the scheduler applies
7832 // to the completion set, so the cooldown stays None here.
7833 PerPolicy::Once(_) | PerPolicy::OncePerVersion(_) => None,
7834 PerPolicy::Every(EverySpec { every }) => Some(every.clone()),
7835 }
7836 }
7837}
7838
7839impl std::fmt::Display for When {
7840 /// Operator-facing one-liner (`per_pc once` / `per_pc every 6h`
7841 /// / `at 09:00 [mon-fri]` / `at 2026-06-10 09:00`) for log
7842 /// lines, audit payloads and the API's `ScheduleSummary`.
7843 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7844 let policy = |p: &PerPolicy| match p {
7845 PerPolicy::Once(_) => "once".to_string(),
7846 PerPolicy::OncePerVersion(_) => "once_per_version".to_string(),
7847 PerPolicy::Every(EverySpec { every }) => format!("every {every}"),
7848 };
7849 match self {
7850 When::PerPc(p) => write!(f, "per_pc {}", policy(p)),
7851 When::PerTarget(p) => write!(f, "per_target {}", policy(p)),
7852 When::Calendar(c) if c.days.is_empty() => write!(f, "at {}", c.at),
7853 When::Calendar(c) => write!(f, "at {} [{}]", c.at, c.days.join(",")),
7854 When::On(triggers) => {
7855 let names: Vec<&str> = triggers.iter().map(|t| t.as_str()).collect();
7856 write!(f, "on [{}]", names.join(","))
7857 }
7858 }
7859 }
7860}
7861
7862impl OnTrigger {
7863 /// Lowercase wire/display label (matches the serde `snake_case`).
7864 pub fn as_str(self) -> &'static str {
7865 match self {
7866 OnTrigger::Startup => "startup",
7867 OnTrigger::Logon => "logon",
7868 OnTrigger::Lock => "lock",
7869 OnTrigger::Unlock => "unlock",
7870 OnTrigger::NetworkChange => "network_change",
7871 }
7872 }
7873}
7874
7875/// Optional validity window for a [`Schedule`] (#418 decision G).
7876/// Half-open `[from, until)`; either bound may be omitted. Bounds
7877/// are `YYYY-MM-DD` (= that day's 00:00 in the schedule's `tz`) or
7878/// full RFC3339 (offset is honored as-is, `tz` ignored). Kept as
7879/// strings so the JSON Schema the SPA editor consumes stays two
7880/// plain string fields, mirroring `jitter` / `starting_deadline`.
7881///
7882/// #418 Phase 2: bounds are evaluated in the schedule's top-level
7883/// `tz` (was UTC-only in Phase 1) so `tz: local` makes both the
7884/// calendar `at` AND the `active` window local — one consistent
7885/// timezone per schedule.
7886#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
7887pub struct Active {
7888 /// Dormant before this instant.
7889 #[serde(default, skip_serializing_if = "Option::is_none")]
7890 pub from: Option<String>,
7891 /// Dormant from this instant on (exclusive).
7892 #[serde(default, skip_serializing_if = "Option::is_none")]
7893 pub until: Option<String>,
7894}
7895
7896impl Active {
7897 /// `skip_serializing_if` helper — an empty window means "always
7898 /// active" and is omitted from the wire format entirely.
7899 pub fn is_empty(&self) -> bool {
7900 self.from.is_none() && self.until.is_none()
7901 }
7902
7903 /// Parse one bound: RFC3339 first (offset honored, `tz`
7904 /// ignored), then bare `YYYY-MM-DD` (00:00 in `tz`).
7905 pub fn parse_bound(s: &str, tz: ScheduleTz) -> Result<chrono::DateTime<chrono::Utc>, String> {
7906 if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
7907 return Ok(dt.with_timezone(&chrono::Utc));
7908 }
7909 if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
7910 let midnight = d.and_hms_opt(0, 0, 0).expect("00:00:00 is always valid");
7911 return tz.naive_to_utc(midnight).ok_or_else(|| {
7912 format!("active: bound '{s}' falls in a DST gap for the schedule's tz")
7913 });
7914 }
7915 Err(format!(
7916 "active: unparseable bound '{s}' (want YYYY-MM-DD or RFC3339)"
7917 ))
7918 }
7919
7920 /// Is `now` inside the window? Unparseable bounds are treated
7921 /// as absent here (fail-open) — [`Schedule::validate`] is the
7922 /// place that rejects them loudly; this runs on every tick and
7923 /// must never panic on a stale KV blob.
7924 pub fn contains(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
7925 let bound = |s: &Option<String>| s.as_deref().and_then(|s| Self::parse_bound(s, tz).ok());
7926 if bound(&self.from).is_some_and(|from| now < from) {
7927 return false;
7928 }
7929 if bound(&self.until).is_some_and(|until| now >= until) {
7930 return false;
7931 }
7932 true
7933 }
7934}
7935
7936/// Host-environment gate (#418 `constraints.require`). Fire only when
7937/// the target host is in the required state. Sensed **in-process by the
7938/// agent** (Win32), so it is `runs_on: agent` only — the backend cannot
7939/// read a target host's power/idle state ([`Schedule::validate`]
7940/// rejects it on `runs_on: backend`, symmetric with `when: { on }`).
7941///
7942/// Evaluated at fire time as a skip-this-tick gate (NOT in
7943/// [`Constraints::allows`], which stays pure for `preview`): a reconcile
7944/// cadence re-checks every minute (so it effectively defers until the
7945/// state is met — the intended pairing); a `calendar` fire that lands
7946/// while the state is unmet is simply missed, same as `window`. It is
7947/// therefore a *runtime* gate and does not appear in `preview`.
7948// No `Eq`: `cpu_below: Option<f64>` is only `PartialEq` (f64 is not Eq).
7949#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
7950pub struct Require {
7951 /// Fire only while on **AC power** (skip on battery). Reads
7952 /// `GetSystemPowerStatus`; an unknown/unreadable status is treated
7953 /// as not-on-AC (fail-closed — a restrictive gate must not fire
7954 /// when it can't confirm the condition). `false` (default) = no
7955 /// power requirement.
7956 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
7957 pub ac_power: bool,
7958 /// Fire only when the active console session has had **no keyboard /
7959 /// mouse input for at least this long** (humantime, e.g. `"10m"`) —
7960 /// "don't run while the user is actively working". Input-based
7961 /// (simpler than Task Scheduler's CPU/disk-aware idle). A
7962 /// headless / disconnected console (no interactive user) trivially
7963 /// satisfies it. `None` (default) = no idle requirement. Parsed
7964 /// lazily; [`Schedule::validate`] rejects garbage at create time.
7965 #[serde(default, skip_serializing_if = "Option::is_none")]
7966 pub idle: Option<String>,
7967 /// Fire only when the **whole-machine CPU usage is below this
7968 /// percent** (0–100; e.g. `20.0` = "system CPU < 20%") — "don't run
7969 /// while the box is busy". Reuses the agent's `host_perf` system CPU%
7970 /// sample (`sysinfo` mean over cores), so the reading is up to one
7971 /// `host_perf` cadence old (default 60s) — fine as a "generally
7972 /// busy?" proxy, and more accurate than a fresh one-shot read (CPU%
7973 /// needs two samples). An unavailable sample (host_perf not warmed
7974 /// up yet, or stale) is treated as "not below" (fail-closed — a
7975 /// restrictive gate must not fire when it can't confirm). `None`
7976 /// (default) = no CPU requirement. [`Schedule::validate`] rejects an
7977 /// out-of-range value at create time.
7978 #[serde(default, skip_serializing_if = "Option::is_none")]
7979 pub cpu_below: Option<f64>,
7980 /// Fire only when the host has **internet connectivity** (Windows
7981 /// `GetNetworkConnectivityHint` reports InternetAccess) — "don't run
7982 /// until online" for jobs that download / phone home. A captive
7983 /// portal (ConstrainedInternetAccess), LAN-only (LocalAccess), or
7984 /// unknown/unreadable state is treated as offline (fail-closed) — a
7985 /// portal would just fail a download, so we hold the run. For VPN /
7986 /// SASE / app-specific conditions, use a custom script gate (separate
7987 /// slice). `false` (default) = no network requirement.
7988 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
7989 pub network: bool,
7990}
7991
7992impl Require {
7993 /// `skip_serializing_if` helper for an embedded empty `require`.
7994 pub fn is_empty(&self) -> bool {
7995 !self.ac_power && self.idle.is_none() && self.cpu_below.is_none() && !self.network
7996 }
7997
7998 /// Parsed minimum-idle duration (`None` = no idle requirement, or an
7999 /// unparseable value — `validate` rejects the latter at create time).
8000 pub fn min_idle(&self) -> Option<std::time::Duration> {
8001 self.idle
8002 .as_deref()
8003 .and_then(|s| humantime::parse_duration(s.trim()).ok())
8004 }
8005
8006 /// First unparseable field for create-time rejection (mirrors
8007 /// [`Constraints::bad_skip_date`]).
8008 pub fn bad_idle(&self) -> Option<String> {
8009 self.idle.as_deref().and_then(|s| {
8010 humantime::parse_duration(s.trim())
8011 .err()
8012 .map(|e| format!("constraints.require.idle: invalid duration '{s}': {e}"))
8013 })
8014 }
8015}
8016
8017/// Host-environment state sensed by the agent, fed to [`require_met`].
8018/// A named struct (not positional args) so the growing set of sensed
8019/// signals — several of them `bool` — can't be transposed at a call
8020/// site. The Win32 sensing lives in `kanade-agent::env_gate`.
8021#[derive(Debug, Clone, Copy, Default)]
8022pub struct EnvState {
8023 /// Is the host on AC power (`false` if on battery or unreadable).
8024 pub ac_online: bool,
8025 /// How long the console has been idle (`None` = couldn't determine).
8026 pub idle: Option<std::time::Duration>,
8027 /// Whole-machine CPU usage 0–100 (`None` = no sample yet).
8028 pub cpu_pct: Option<f64>,
8029 /// Does the host have internet connectivity (`false` if offline /
8030 /// LAN-only / unreadable).
8031 pub network_up: bool,
8032}
8033
8034/// Pure env-gate decision (#418 `constraints.require`). The Win32
8035/// sensing lives in the agent (`kanade-agent::env_gate`); this is the
8036/// testable core, fed the already-sensed [`EnvState`]. Deliberately a
8037/// free fn (not folded into [`Constraints::allows`]) so `allows` stays
8038/// pure and `preview` never evaluates a runtime gate. Each set
8039/// requirement is a restrictive AND: any unmet (or unknown) gate skips.
8040pub fn require_met(req: &Require, env: &EnvState) -> bool {
8041 if req.ac_power && !env.ac_online {
8042 return false;
8043 }
8044 if let Some(min) = req.min_idle() {
8045 match env.idle {
8046 Some(d) if d >= min => {}
8047 _ => return false,
8048 }
8049 }
8050 if let Some(max) = req.cpu_below {
8051 match env.cpu_pct {
8052 Some(p) if p < max => {}
8053 _ => return false,
8054 }
8055 }
8056 if req.network && !env.network_up {
8057 return false;
8058 }
8059 true
8060}
8061
8062/// [`Active`] decides *over what date range* a schedule is live,
8063/// `Constraints` decides *when, within an active period,* a fire is
8064/// allowed: `window` (a maintenance time-of-day window),
8065/// `max_concurrent` (a fleet-wide running-instance cap), `skip_dates`
8066/// (holiday exclusion) and `require` (host-environment gates, agent-only
8067/// — see [`Require`]).
8068// No `Eq`: contains `require: Option<Require>` which holds an f64.
8069#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
8070pub struct Constraints {
8071 /// `"HH:MM-HH:MM"` wall-clock window (evaluated in the schedule's
8072 /// `tz`). Fires outside it are skipped — mainly for reconcile
8073 /// cadences ("patrol every 6h, but only fire overnight") and
8074 /// daytime change-freezes. `start > end` crosses midnight
8075 /// (`"22:00-05:00"` = 22:00 through 05:00 next morning). Parsed
8076 /// lazily; [`Schedule::validate`] rejects garbage at create time.
8077 #[serde(default, skip_serializing_if = "Option::is_none")]
8078 pub window: Option<String>,
8079 /// Fleet-wide cap on how many instances of this schedule's job may
8080 /// run **at the same time** (#418 "同時実行ハード上限"). The
8081 /// backend scheduler counts the job's still-in-flight runs
8082 /// (`execution_results.finished_at IS NULL`) each tick and only
8083 /// dispatches to as many remaining pcs as there are free slots —
8084 /// a rolling window that refills as runs complete. Useful for
8085 /// disk/CPU/network-heavy jobs you don't want hammering the whole
8086 /// fleet at once.
8087 ///
8088 /// **Backend-only** (it needs a central counter): combining it
8089 /// with `runs_on: agent` is rejected by [`Schedule::validate`]
8090 /// (#418 decision E — "中央上限には中央が要る"). Most meaningful
8091 /// for `per_pc` reconcile cadences, where the poll re-ticks and
8092 /// refills slots. `None` (default) = no cap.
8093 #[serde(default, skip_serializing_if = "Option::is_none")]
8094 pub max_concurrent: Option<u32>,
8095 /// Calendar dates the schedule must **not** fire on — holidays,
8096 /// blackout days, one-off freeze dates (#418 "祝日除外"). Each is
8097 /// `YYYY-MM-DD`, evaluated as a wall-clock date in the schedule's
8098 /// `tz`. Applies to every `when` shape (a reconcile cadence skips
8099 /// the whole day; a calendar fire landing on the date is
8100 /// suppressed) and is honored by both the live scheduler and
8101 /// `preview`, since both gate on [`Constraints::allows`]. Empty
8102 /// (default) = no skips. Operator-supplied: there is no built-in
8103 /// holiday calendar — list the dates you care about. Parsed lazily;
8104 /// [`Schedule::validate`] rejects a malformed date at create time.
8105 #[serde(default, skip_serializing_if = "Vec::is_empty")]
8106 pub skip_dates: Vec<String>,
8107 /// Host-environment gate (#418): fire only when the target host is
8108 /// in the required state (on AC power, idle). Agent-sensed at fire
8109 /// time, `runs_on: agent` only. See [`Require`]. `None` (default) =
8110 /// no environment requirement.
8111 #[serde(default, skip_serializing_if = "Option::is_none")]
8112 pub require: Option<Require>,
8113}
8114
8115impl Constraints {
8116 /// `skip_serializing_if` helper — empty constraints are omitted
8117 /// from the wire format entirely.
8118 pub fn is_empty(&self) -> bool {
8119 self.window.is_none()
8120 && self.max_concurrent.is_none()
8121 && self.skip_dates.is_empty()
8122 && self.require.as_ref().is_none_or(Require::is_empty)
8123 }
8124
8125 /// The first unparseable `skip_dates` entry, if any — the
8126 /// scheduler logs it at register time so a fail-closed
8127 /// (never-firing) schedule from a hand-edited KV blob is
8128 /// diagnosable, mirroring [`Schedule::bad_window`].
8129 pub fn bad_skip_date(&self) -> Option<String> {
8130 self.skip_dates.iter().find_map(|s| {
8131 chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d")
8132 .err()
8133 .map(|e| format!("constraints.skip_dates: invalid date '{s}': {e}"))
8134 })
8135 }
8136
8137 /// Parse `"HH:MM-HH:MM"` into `(start, end)`. Equal bounds are an
8138 /// error (a zero-width or all-day window is ambiguous — write no
8139 /// window for "always").
8140 pub fn parse_window(s: &str) -> Result<(chrono::NaiveTime, chrono::NaiveTime), String> {
8141 let (a, b) = s
8142 .split_once('-')
8143 .ok_or_else(|| format!("constraints.window: '{s}' must be 'HH:MM-HH:MM'"))?;
8144 let parse = |part: &str| {
8145 chrono::NaiveTime::parse_from_str(part.trim(), "%H:%M")
8146 .map_err(|e| format!("constraints.window: invalid time '{}': {e}", part.trim()))
8147 };
8148 let (start, end) = (parse(a)?, parse(b)?);
8149 if start == end {
8150 return Err(format!(
8151 "constraints.window: start and end are equal ('{s}'); omit window for 'always'"
8152 ));
8153 }
8154 Ok((start, end))
8155 }
8156
8157 /// Is a fire allowed at `now` (evaluated in `tz`)? No window =
8158 /// always allowed. Half-open `[start, end)`; `start > end`
8159 /// crosses midnight.
8160 ///
8161 /// **Fail-closed** on an unparseable window (returns `false`,
8162 /// gemini #452 review): a window is a *restrictive* constraint
8163 /// (change-freeze / overnight-only), so a corrupt one must NOT
8164 /// silently allow fires during the restricted hours. Bad windows
8165 /// are rejected at create time by [`Schedule::validate`]; this
8166 /// only bites a hand-edited KV blob, where blocking is the safe
8167 /// direction. The scheduler warns at register time
8168 /// ([`Schedule::bad_window`]) so a stuck schedule is diagnosable.
8169 /// The tick path never panics regardless.
8170 pub fn allows(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
8171 // #418 holiday / blackout dates: never fire on a listed wall
8172 // date (in `tz`). Checked before the window since a skipped day
8173 // overrides any within-window allowance. Fail-closed on a
8174 // corrupt entry (same posture as `window`): a skip date is a
8175 // *restrictive* constraint, so a garbled one must not silently
8176 // re-enable fires — it blocks until fixed (`validate` rejects it
8177 // at create time; `bad_skip_date` lets the scheduler warn).
8178 if !self.skip_dates.is_empty() {
8179 let today = tz.wall_date(now);
8180 let blocked = self.skip_dates.iter().any(|s| {
8181 match chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d") {
8182 Ok(d) => d == today,
8183 Err(_) => true, // corrupt entry → fail-closed (block)
8184 }
8185 });
8186 if blocked {
8187 return false;
8188 }
8189 }
8190 match self.window.as_deref() {
8191 // No window → always allowed.
8192 None => true,
8193 // Window set: membership, or fail-closed if unparseable
8194 // (`window_contains` returns None for a corrupt window).
8195 Some(_) => self.window_contains(tz.wall_time(now)).unwrap_or(false),
8196 }
8197 }
8198
8199 /// Membership of a wall-clock time-of-day in the window. `None`
8200 /// when there is no window or it's unparseable (callers decide
8201 /// the failure direction). `start > end` crosses midnight.
8202 fn window_contains(&self, t: chrono::NaiveTime) -> Option<bool> {
8203 let (start, end) = Self::parse_window(self.window.as_deref()?).ok()?;
8204 Some(if start <= end {
8205 start <= t && t < end
8206 } else {
8207 t >= start || t < end
8208 })
8209 }
8210}
8211
8212/// What to do when a fire's script fails (#418 Phase 4 — the "高"
8213/// retry/backoff gap). Where [`Constraints`] gates *whether* a fire
8214/// happens, `OnFailure` decides what happens *after* one ran and
8215/// came back bad. Only `retry` so far; future `notify` / `disable`
8216/// would join the same namespace.
8217#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
8218pub struct OnFailure {
8219 /// Re-run the script in-process when it exits non-zero (or times
8220 /// out), up to a cap, with a fixed backoff between attempts.
8221 /// `None` (default) = no retry: a failed run is published as-is
8222 /// and (for reconcile cadences) simply re-fires on the next poll
8223 /// tick. See [`Retry`].
8224 #[serde(default, skip_serializing_if = "Option::is_none")]
8225 pub retry: Option<Retry>,
8226}
8227
8228impl OnFailure {
8229 /// `skip_serializing_if` helper — an empty policy is omitted from
8230 /// the wire format entirely.
8231 pub fn is_empty(&self) -> bool {
8232 self.retry.is_none()
8233 }
8234
8235 /// Lower the operator-facing `retry` (humantime backoff) onto the
8236 /// engine vocabulary the agent's executor runs on (backoff in
8237 /// whole seconds). Single seam shared by the backend command
8238 /// builder and the agent's local scheduler so the two stamp the
8239 /// same [`crate::wire::RetrySpec`] onto every Command. Returns
8240 /// `None` when there is no retry policy or the backoff is
8241 /// unparseable (validate() rejects the latter at create time;
8242 /// this stays fail-safe = "no retry" for a hand-edited KV blob
8243 /// rather than panicking on the fire path).
8244 pub fn lowered_retry(&self) -> Option<crate::wire::RetrySpec> {
8245 let r = self.retry.as_ref()?;
8246 let backoff_secs = humantime::parse_duration(&r.backoff).ok()?.as_secs();
8247 Some(crate::wire::RetrySpec {
8248 max: r.max,
8249 backoff_secs,
8250 })
8251 }
8252}
8253
8254/// Fixed-backoff retry policy (#418 Phase 4). `max` is the number of
8255/// *additional* attempts after the first run (so `max: 3` = up to 4
8256/// total executions); `backoff` is the humantime delay slept between
8257/// attempts. The retry happens fire-side (inside `kanade fire` /
8258/// `handle_command`) on every OS for the PoC — the Windows-native
8259/// "restart on failure" Task Scheduler path is deferred to the
8260/// native-delegation phase (#418 decision H).
8261#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8262pub struct Retry {
8263 /// Max additional attempts after the first failure. Bounded
8264 /// `1..=10` by [`Schedule::validate`] — a typo'd `max: 1000`
8265 /// with a short backoff would otherwise pin a flapping script in
8266 /// a tight loop for the whole window.
8267 pub max: u32,
8268 /// Humantime delay slept between attempts (`"10m"`, `"30s"`).
8269 pub backoff: String,
8270}
8271
8272/// Fleet-wide change-freeze (#418 Phase 5 — the "メンテナンス窓 /
8273/// 変更凍結" gap's global half). Where [`Constraints::window`] is a
8274/// *per-schedule* time-of-day gate, a `Freeze` is a *single, fleet-
8275/// global* "stop all automated change" switch the operator flips
8276/// during an incident or a year-end change-freeze. It lives in its
8277/// own KV singleton ([`crate::kv::KEY_FREEZE`]); when present and
8278/// active, both the backend scheduler and every agent's local
8279/// scheduler skip *every* fire.
8280///
8281/// Shapes:
8282/// * `{}` (no bounds) — frozen indefinitely until the operator
8283/// clears it (incident "big red button").
8284/// * `{ from, until }` — frozen only within `[from, until)`,
8285/// evaluated in `tz` (planned change-freeze; auto-thaws).
8286///
8287/// The KV key being *absent* means "not frozen" — so clearing the
8288/// freeze is a KV delete, and `is_active` only ever runs on a freeze
8289/// the operator actually set.
8290#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
8291pub struct Freeze {
8292 /// Frozen from this instant (RFC3339 or bare `YYYY-MM-DD` in
8293 /// `tz`). `None` ⇒ frozen from the beginning of time.
8294 #[serde(default, skip_serializing_if = "Option::is_none")]
8295 pub from: Option<String>,
8296 /// Thawed from this instant on, exclusive. `None` ⇒ frozen with
8297 /// no scheduled end (manual clear required).
8298 #[serde(default, skip_serializing_if = "Option::is_none")]
8299 pub until: Option<String>,
8300 /// Operator-supplied note surfaced on the freeze-skip log and the
8301 /// SPA banner ("year-end change freeze", "INC-1234"). Advisory.
8302 #[serde(default, skip_serializing_if = "Option::is_none")]
8303 pub reason: Option<String>,
8304 /// Timezone the bare-date bounds are evaluated in (RFC3339 bounds
8305 /// carry their own offset). Defaults to host-local like a
8306 /// schedule's `tz`.
8307 #[serde(default)]
8308 pub tz: ScheduleTz,
8309}
8310
8311impl Freeze {
8312 /// Is the fleet frozen at `now`? An empty window (`from`/`until`
8313 /// both absent) is frozen unconditionally; otherwise membership of
8314 /// `[from, until)` in `tz`. Half-open like [`Active::contains`],
8315 /// but **fails CLOSED** on an unparseable bound — a freeze is a
8316 /// safety switch, so a corrupt window (only reachable via a
8317 /// hand-edited KV blob; `validate` rejects it at set time) must
8318 /// mean "frozen", not "fire normally" (coderabbit #472). This is
8319 /// the one deliberate divergence from `active`'s fail-OPEN
8320 /// behaviour, where an unparseable bound dormant-skips a schedule.
8321 pub fn is_active(&self, now: chrono::DateTime<chrono::Utc>) -> bool {
8322 // Parse a bound; an unparseable one short-circuits the whole
8323 // check to `true` (frozen) via the closure's `None` sentinel
8324 // handled below.
8325 let bound = |s: &Option<String>| -> Result<Option<chrono::DateTime<chrono::Utc>>, ()> {
8326 match s.as_deref() {
8327 None => Ok(None),
8328 Some(raw) => Active::parse_bound(raw, self.tz).map(Some).map_err(|_| ()),
8329 }
8330 };
8331 let (from, until) = match (bound(&self.from), bound(&self.until)) {
8332 (Ok(f), Ok(u)) => (f, u),
8333 // Any corrupt bound → fail closed (frozen).
8334 _ => return true,
8335 };
8336 if from.is_some_and(|f| now < f) {
8337 return false;
8338 }
8339 if until.is_some_and(|u| now >= u) {
8340 return false;
8341 }
8342 true
8343 }
8344
8345 /// Reject unparseable bounds / `from >= until` at set time (the
8346 /// API + CLI counterpart to [`Schedule::validate`]).
8347 pub fn validate(&self) -> Result<(), String> {
8348 let from = self
8349 .from
8350 .as_deref()
8351 .map(|s| Active::parse_bound(s, self.tz))
8352 .transpose()
8353 .map_err(|e| e.replace("active:", "freeze:"))?;
8354 let until = self
8355 .until
8356 .as_deref()
8357 .map(|s| Active::parse_bound(s, self.tz))
8358 .transpose()
8359 .map_err(|e| e.replace("active:", "freeze:"))?;
8360 if let (Some(f), Some(u)) = (from, until) {
8361 if f >= u {
8362 return Err(format!(
8363 "freeze.from ({}) must be strictly before freeze.until ({})",
8364 self.from.as_deref().unwrap_or_default(),
8365 self.until.as_deref().unwrap_or_default(),
8366 ));
8367 }
8368 }
8369 Ok(())
8370 }
8371}
8372
8373/// The system-generated poll cadence every reconcile-shaped `when`
8374/// lowers to. Operators never write this: the real inter-run
8375/// spacing is the `every` cooldown; this only bounds "how soon do
8376/// we notice somebody is due" (#418 decision B took the poll
8377/// period away from the operator).
8378pub const POLL_CRON: &str = "0 * * * * *";
8379
8380/// What a [`When`] lowers to — the exact (cron, mode, cooldown)
8381/// trio the pre-#418 engine ran on. Keeping the engine vocabulary
8382/// unchanged is what lets Phase 1 swap the operator surface without
8383/// touching the tick / dedup machinery.
8384pub struct Lowered {
8385 /// Cron handed to `tokio-cron-scheduler` — [`POLL_CRON`] for
8386 /// reconcile shapes, a 6/7-field cron for calendar shapes.
8387 pub cron: String,
8388 /// Dedup semantics for `decide_fire`.
8389 pub mode: ExecMode,
8390 /// Humantime re-arm interval (`None` = succeed once, skip
8391 /// forever).
8392 pub cooldown: Option<String>,
8393 /// Timezone to evaluate `cron` in (#418 Phase 2). The scheduler
8394 /// passes this to `Job::new_async_tz`. Reconcile shapes carry
8395 /// the schedule's tz too even though POLL_CRON is tz-agnostic,
8396 /// so the same value drives the `active`-window check.
8397 pub tz: ScheduleTz,
8398}
8399
8400impl Schedule {
8401 /// The error message if this schedule's `constraints.window` is
8402 /// set but unparseable, else `None`. The scheduler logs this at
8403 /// register time so a fail-closed (never-firing) schedule from a
8404 /// hand-edited KV blob is diagnosable (gemini #452 review).
8405 pub fn bad_window(&self) -> Option<String> {
8406 let w = self.constraints.window.as_deref()?;
8407 Constraints::parse_window(w).err()
8408 }
8409
8410 /// True when this is a `calendar` schedule whose fire time can
8411 /// never fall inside its `constraints.window` — the cron fires,
8412 /// the window check rejects it, and (firing only at that
8413 /// time-of-day) it effectively never runs. An easy misconfig to
8414 /// set up by accident; the scheduler warns at register time
8415 /// (claude #452 review). Reconcile shapes poll every minute, so
8416 /// they always catch the window opening and aren't affected.
8417 pub fn calendar_outside_window(&self) -> bool {
8418 let When::Calendar(c) = &self.when else {
8419 return false;
8420 };
8421 let Some(t) = c.fire_time() else {
8422 return false;
8423 };
8424 matches!(self.constraints.window_contains(t), Some(false))
8425 }
8426
8427 /// Up to `count` future instants this schedule will fire, as
8428 /// absolute UTC, strictly after `now` — the dry-run / preview
8429 /// surface (#418 "ドライラン / プレビュー"). Only **calendar**
8430 /// schedules have discrete fire times; reconcile shapes
8431 /// (`per_pc`/`per_target`) poll every minute gated by cooldown, so
8432 /// they return an empty vec and the caller describes the cadence
8433 /// instead. Occurrences outside the `active.{from,until}` window or
8434 /// the `constraints.window` are **skipped**, so the list reflects
8435 /// when the schedule will ACTUALLY run, not the raw cron ticks.
8436 /// Evaluated in the schedule's `tz`, exactly like the scheduler's
8437 /// `Job::new_async_tz`, and with the same croner config the
8438 /// scheduler / [`Schedule::validate`] use, so a preview can never
8439 /// disagree with a real fire. A schedule that can never fire (a
8440 /// calendar time wholly outside its window, a past one-shot,
8441 /// `enabled: false` is *not* considered here — callers gate on
8442 /// `enabled` separately) yields an empty vec.
8443 pub fn preview_fires(
8444 &self,
8445 now: chrono::DateTime<chrono::Utc>,
8446 count: usize,
8447 ) -> Vec<chrono::DateTime<chrono::Utc>> {
8448 use croner::parser::{CronParser, Seconds};
8449 if !matches!(self.when, When::Calendar(_)) {
8450 return Vec::new();
8451 }
8452 // Same lowering + croner config as `next_calendar_fire` and the
8453 // live scheduler, so a preview can never disagree with a real
8454 // fire. `preview_fires` adds the N-occurrence walk and the
8455 // active / window filtering on top of that single seam.
8456 let lowered = self.lowered();
8457 let Ok(cron) = CronParser::builder()
8458 .seconds(Seconds::Required)
8459 .dom_and_dow(true)
8460 .build()
8461 .parse(&lowered.cron)
8462 else {
8463 return Vec::new();
8464 };
8465 let accept = |utc: chrono::DateTime<chrono::Utc>| {
8466 self.active.contains(utc, self.tz) && self.constraints.allows(utc, self.tz)
8467 };
8468 match self.tz {
8469 ScheduleTz::Utc => Self::next_occurrences(&cron, now, count, accept),
8470 ScheduleTz::Local => {
8471 Self::next_occurrences(&cron, now.with_timezone(&chrono::Local), count, accept)
8472 }
8473 }
8474 }
8475
8476 /// Walk croner forward from `after` collecting up to `count`
8477 /// accepted occurrences (converted to UTC). Generic over the tz the
8478 /// cron is evaluated in so `preview_fires` can run it in either
8479 /// `Utc` or `Local` without duplicating the loop.
8480 fn next_occurrences<Tz>(
8481 cron: &croner::Cron,
8482 after: chrono::DateTime<Tz>,
8483 count: usize,
8484 accept: impl Fn(chrono::DateTime<chrono::Utc>) -> bool,
8485 ) -> Vec<chrono::DateTime<chrono::Utc>>
8486 where
8487 Tz: chrono::TimeZone,
8488 {
8489 // Bound the scan so an `active`/window dead-end (every future
8490 // tick rejected) can't spin forever: ~4096 raw ticks covers
8491 // >10y of a daily calendar while staying instant for croner.
8492 const SCAN_CAP: usize = 4096;
8493 let mut out = Vec::with_capacity(count.min(SCAN_CAP));
8494 let mut cursor = after;
8495 let mut scanned = 0usize;
8496 while out.len() < count && scanned < SCAN_CAP {
8497 scanned += 1;
8498 let Ok(next) = cron.find_next_occurrence(&cursor, false) else {
8499 break;
8500 };
8501 let utc = next.with_timezone(&chrono::Utc);
8502 if accept(utc) {
8503 out.push(utc);
8504 }
8505 // `find_next_occurrence(.., inclusive = false)` already
8506 // advances strictly past `cursor`, so handing it `next`
8507 // verbatim gets the following occurrence — no manual +1s
8508 // nudge (and `DateTime<Tz>` is `Copy`, so no clone).
8509 cursor = next;
8510 }
8511 out
8512 }
8513
8514 /// Lower the operator-facing `when` onto the engine vocabulary.
8515 /// Single seam shared by the backend scheduler and the agent's
8516 /// local scheduler so the two can never drift.
8517 pub fn lowered(&self) -> Lowered {
8518 let tz = self.tz;
8519 match &self.when {
8520 When::PerPc(p) => Lowered {
8521 cron: POLL_CRON.into(),
8522 // `once_per_version` re-arms each pc when the manifest
8523 // version changes; the scheduler keys that dedup on
8524 // `execution_results.version`. Plain `once` / `every`
8525 // stay version-blind.
8526 mode: match p {
8527 PerPolicy::OncePerVersion(_) => ExecMode::OncePerPcVersion,
8528 PerPolicy::Once(_) | PerPolicy::Every(_) => ExecMode::OncePerPc,
8529 },
8530 cooldown: p.cooldown(),
8531 tz,
8532 },
8533 When::PerTarget(p) => Lowered {
8534 cron: POLL_CRON.into(),
8535 mode: ExecMode::OncePerTarget,
8536 cooldown: p.cooldown(),
8537 tz,
8538 },
8539 // `to_cron` only fails on a malformed `at` (rejected by
8540 // validate() at create time). For a hand-edited KV blob
8541 // that slipped past, emit a deliberately-invalid cron so
8542 // register()'s Job::new_async_tz fails → warn+skip,
8543 // rather than firing at the wrong time.
8544 When::Calendar(c) => Lowered {
8545 cron: c
8546 .to_cron()
8547 .unwrap_or_else(|_| "# invalid calendar at".into()),
8548 mode: ExecMode::EveryTick,
8549 cooldown: None,
8550 tz,
8551 },
8552 // Event triggers have no cron — the agent fires them from an
8553 // OS event source. The `# event-trigger` cron is never
8554 // registered (the scheduler branches on `is_event()` first),
8555 // but keep it deliberately-invalid as a belt-and-suspenders
8556 // so a stray registration would fail rather than misfire.
8557 When::On(_) => Lowered {
8558 cron: "# event-trigger (no cron)".into(),
8559 mode: ExecMode::Event,
8560 cooldown: None,
8561 tz,
8562 },
8563 }
8564 }
8565
8566 /// True when this schedule fires from an OS event (`when: { on }`)
8567 /// rather than a clock — the agent skips `tokio-cron` registration
8568 /// for these and drives them from boot / session-change instead.
8569 pub fn is_event(&self) -> bool {
8570 matches!(self.when, When::On(_))
8571 }
8572
8573 /// The OS event triggers this schedule listens for, or `&[]` when it
8574 /// is not an event schedule.
8575 pub fn event_triggers(&self) -> &[OnTrigger] {
8576 match &self.when {
8577 When::On(t) => t,
8578 _ => &[],
8579 }
8580 }
8581
8582 /// The next absolute (UTC) time this schedule fires, or `None` when
8583 /// it has no discrete upcoming fire to preview.
8584 ///
8585 /// Used by the KLP `maintenance.list` preview ("what's about to
8586 /// happen on my PC", SPEC §2.1). Returns `None` for:
8587 ///
8588 /// - reconcile shapes (`per_pc` / `per_target`) — they lower to the
8589 /// every-minute [`POLL_CRON`] and re-converge state continuously,
8590 /// so "next fire" is always ~60s away and means nothing to a user
8591 /// previewing upcoming maintenance;
8592 /// - a calendar schedule whose lowered cron won't parse (a
8593 /// hand-edited KV blob that slipped past [`Schedule::validate`]);
8594 /// - a cron with no future occurrence.
8595 ///
8596 /// The wall-clock fire is evaluated in the schedule's own `tz`
8597 /// (matching the live tick's `Job::new_async_tz`) then normalised
8598 /// to UTC for the wire. `inclusive = false`: strictly the *next*
8599 /// fire after `now`, never one matching the current instant.
8600 pub fn next_calendar_fire(
8601 &self,
8602 now: chrono::DateTime<chrono::Utc>,
8603 ) -> Option<chrono::DateTime<chrono::Utc>> {
8604 if !matches!(self.when, When::Calendar(_)) {
8605 return None;
8606 }
8607 let lowered = self.lowered();
8608 // Same parser configuration tokio-cron-scheduler 0.15 uses
8609 // internally, so this can never compute a fire the live
8610 // scheduler wouldn't (seconds required, DOM-and-DOW honored).
8611 let cron = croner::parser::CronParser::builder()
8612 .seconds(croner::parser::Seconds::Required)
8613 .dom_and_dow(true)
8614 .build()
8615 .parse(&lowered.cron)
8616 .ok()?;
8617 match lowered.tz {
8618 ScheduleTz::Utc => cron.find_next_occurrence(&now, false).ok(),
8619 ScheduleTz::Local => {
8620 let now_local = now.with_timezone(&chrono::Local);
8621 cron.find_next_occurrence(&now_local, false)
8622 .ok()
8623 .map(|t| t.with_timezone(&chrono::Utc))
8624 }
8625 }
8626 }
8627
8628 /// Cross-field semantic checks that don't fit pure serde derive
8629 /// — the [`Manifest::validate`] counterpart (#418 decision F;
8630 /// pre-Phase-1 a broken schedule was accepted at create time
8631 /// and silently warn-skipped at tick time). Run at every create
8632 /// site: `kanade schedule create` (client-side) and
8633 /// `POST /api/schedules`. The job_id-exists check lives in the
8634 /// API handler instead — it needs the JOBS KV.
8635 pub fn validate(&self) -> Result<(), String> {
8636 if matches!(self.runs_on, RunsOn::Agent) && matches!(self.when, When::PerTarget(_)) {
8637 return Err(
8638 "when.per_target needs fleet-wide completion data and is backend-only; \
8639 it cannot be combined with runs_on: agent (each agent self-schedules, \
8640 so per-target dedup would be deduping across a target of 1)"
8641 .into(),
8642 );
8643 }
8644 // `once_per_version` is a per_pc-only shape: it re-arms an
8645 // individual pc when the manifest version it succeeded at is no
8646 // longer current. "One delegate per version" for a whole target
8647 // has no clear meaning, so reject it rather than silently
8648 // lowering to plain per_target (version-blind).
8649 if matches!(self.when, When::PerTarget(PerPolicy::OncePerVersion(_))) {
8650 return Err(
8651 "when.per_target: once_per_version is not supported — once_per_version \
8652 re-arms per pc per manifest version, which only makes sense for per_pc. \
8653 Use `per_pc: once_per_version`."
8654 .into(),
8655 );
8656 }
8657 // `once_per_version` keys its dedup on the backend's
8658 // `execution_results.version` history. A runs_on: agent schedule
8659 // self-schedules from the agent's local completion map, which has
8660 // no per-version record, so it is backend-only (symmetric with
8661 // per_target). Reject it rather than silently degrade to
8662 // version-blind kitting-once on the agent.
8663 if matches!(self.runs_on, RunsOn::Agent)
8664 && matches!(self.when, When::PerPc(PerPolicy::OncePerVersion(_)))
8665 {
8666 return Err(
8667 "when.per_pc: once_per_version keys its dedup on the backend's per-version \
8668 completion history and is backend-only; it cannot be combined with \
8669 runs_on: agent (the agent self-schedules with no per-version record). \
8670 Use runs_on: backend."
8671 .into(),
8672 );
8673 }
8674 // #418 event triggers: the agent owns the OS event source
8675 // (boot / session-change), so `when: { on }` is agent-only and
8676 // needs at least one trigger.
8677 if let When::On(triggers) = &self.when {
8678 if !matches!(self.runs_on, RunsOn::Agent) {
8679 return Err(
8680 "when.on (OS event trigger) is fired by the agent's own event \
8681 source, so it requires runs_on: agent"
8682 .into(),
8683 );
8684 }
8685 if triggers.is_empty() {
8686 return Err(
8687 "when.on must list at least one trigger (e.g. [startup, logon])".into(),
8688 );
8689 }
8690 }
8691 if let Some(cd) = self.lowered().cooldown.as_deref() {
8692 humantime::parse_duration(cd)
8693 .map_err(|e| format!("when.every: invalid duration '{cd}': {e}"))?;
8694 }
8695 if let When::Calendar(c) = &self.when {
8696 // Lower the calendar form to its cron (catches a bad `at`
8697 // and the date+days conflict), then validate that cron
8698 // with the same parser configuration tokio-cron-scheduler
8699 // 0.15 uses internally (croner, seconds required,
8700 // DOM-and-DOW both honored, year optional) — create-time
8701 // validation can never accept what register() rejects.
8702 let cron = c.to_cron()?;
8703 croner::parser::CronParser::builder()
8704 .seconds(croner::parser::Seconds::Required)
8705 .dom_and_dow(true)
8706 .build()
8707 .parse(&cron)
8708 .map_err(|e| format!("when.at lowered to invalid cron '{cron}': {e}"))?;
8709 }
8710 // The other humantime strings on the schedule (claude #419
8711 // review): runtime degrades gracefully on both (bad jitter →
8712 // silent no-op, bad starting_deadline → warn + skipped tick),
8713 // but "rejected at create time" should cover every field the
8714 // operator can typo, not just `when`.
8715 if let Some(j) = &self.plan.jitter {
8716 humantime::parse_duration(j)
8717 .map_err(|e| format!("jitter: invalid duration '{j}': {e}"))?;
8718 }
8719 if let Some(sd) = &self.starting_deadline {
8720 humantime::parse_duration(sd)
8721 .map_err(|e| format!("starting_deadline: invalid duration '{sd}': {e}"))?;
8722 }
8723 // #917: the plan side got almost no create-time checks, so
8724 // several never-fires / fails-every-tick shapes were accepted
8725 // and only surfaced at dispatch time — or never:
8726 //
8727 // (1) a target that dispatches nothing. A runs_on: agent
8728 // schedule matches each agent against `target` (rollout waves
8729 // are backend-published and never reach that path), so an
8730 // unspecified target silently never fires; a runs_on: backend
8731 // one warn-fails every tick at the exec boundary, which
8732 // rejects the same shape with the same message.
8733 let has_waves = self
8734 .plan
8735 .rollout
8736 .as_ref()
8737 .is_some_and(|r| !r.waves.is_empty());
8738 if matches!(self.runs_on, RunsOn::Agent) {
8739 if !self.plan.target.is_specified() {
8740 return Err(
8741 "target must specify at least one of `all` / `groups` / `pcs` — a \
8742 runs_on: agent schedule matches each agent against `target`, so an \
8743 unspecified target never fires anywhere"
8744 .into(),
8745 );
8746 }
8747 if self.plan.rollout.is_some() {
8748 return Err(
8749 "rollout waves are published by the backend and are ignored by \
8750 runs_on: agent schedules (each agent self-schedules from `target`); \
8751 drop `rollout:` or use runs_on: backend"
8752 .into(),
8753 );
8754 }
8755 } else if !has_waves && !self.plan.target.is_specified() {
8756 return Err(
8757 "target must specify at least one of `all` / `groups` / `pcs` \
8758 (or set `rollout.waves`) — the exec boundary rejects an \
8759 unspecified target, so the schedule would fail every tick"
8760 .into(),
8761 );
8762 }
8763 // (2) rollout waves were never validated: a blank group or an
8764 // unparseable delay failed at EVERY fire (the CLI doesn't even
8765 // expose waves, so the failure was always deferred to dispatch)
8766 // and an empty list dispatched nothing. (3) A wave delayed to
8767 // or past starting_deadline is dead on arrival: the deadline is
8768 // stamped once at tick time and the Command is serialised
8769 // before the wave sleep, so agents receive it already expired
8770 // (a synthetic exit-125 skip on every fire).
8771 if let Some(rollout) = &self.plan.rollout {
8772 if rollout.waves.is_empty() {
8773 return Err(
8774 "rollout.waves must list at least one wave; omit `rollout:` for a \
8775 one-shot fan-out of `target`"
8776 .into(),
8777 );
8778 }
8779 let deadline = self
8780 .starting_deadline
8781 .as_deref()
8782 .and_then(|sd| humantime::parse_duration(sd).ok());
8783 for (i, wave) in rollout.waves.iter().enumerate() {
8784 if wave.group.trim().is_empty() {
8785 return Err(format!("rollout.waves[{i}].group must not be blank"));
8786 }
8787 let delay = humantime::parse_duration(&wave.delay).map_err(|e| {
8788 format!(
8789 "rollout.waves[{i}].delay: invalid duration '{}': {e}",
8790 wave.delay
8791 )
8792 })?;
8793 if let Some(deadline) = deadline
8794 && delay >= deadline
8795 {
8796 return Err(format!(
8797 "rollout.waves[{i}].delay ('{}') must be shorter than \
8798 starting_deadline ('{}'): the deadline is stamped at tick time, \
8799 so this wave's Commands would already be expired when published \
8800 (skipped by every agent, every fire)",
8801 wave.delay,
8802 self.starting_deadline.as_deref().unwrap_or_default(),
8803 ));
8804 }
8805 }
8806 }
8807 // (4) deadline_at is machine-stamped: the scheduler overwrites
8808 // it from `tick + starting_deadline` on every fire, so an
8809 // operator-set value is silently discarded — reject it and
8810 // point at the knob that does what they meant. (Ad-hoc POST
8811 // /api/exec bodies are a different write path and may still
8812 // carry it.)
8813 if self.plan.deadline_at.is_some() {
8814 return Err(
8815 "deadline_at is computed by the scheduler (tick time + starting_deadline) \
8816 and overwritten on every fire — set `starting_deadline` instead"
8817 .into(),
8818 );
8819 }
8820 let from = self
8821 .active
8822 .from
8823 .as_deref()
8824 .map(|s| Active::parse_bound(s, self.tz))
8825 .transpose()?;
8826 let until = self
8827 .active
8828 .until
8829 .as_deref()
8830 .map(|s| Active::parse_bound(s, self.tz))
8831 .transpose()?;
8832 if let (Some(f), Some(u)) = (from, until) {
8833 if f >= u {
8834 return Err(format!(
8835 "active.from ({}) must be strictly before active.until ({})",
8836 self.active.from.as_deref().unwrap_or_default(),
8837 self.active.until.as_deref().unwrap_or_default(),
8838 ));
8839 }
8840 }
8841 // #418 Phase 3: a bad maintenance window is rejected at create
8842 // time (parse_window also catches equal bounds).
8843 if let Some(w) = self.constraints.window.as_deref() {
8844 Constraints::parse_window(w)?;
8845 }
8846 // #418 holiday exclusion: reject a malformed skip date at create
8847 // time so the fail-closed `allows` path only ever bites a
8848 // hand-edited KV blob, not a fresh `kanade schedule create`.
8849 if let Some(err) = self.constraints.bad_skip_date() {
8850 return Err(err);
8851 }
8852 // #418: constraints.max_concurrent is a central running-instance
8853 // cap, so it needs the backend's counter — reject it on
8854 // runs_on: agent (decision E), and reject a meaningless 0.
8855 if let Some(mc) = self.constraints.max_concurrent {
8856 // Check the structural incompatibility (agent has no central
8857 // counter) before the value range, so a `max_concurrent: 0`
8858 // + `runs_on: agent` combo reports the more fundamental
8859 // problem first (claude #542).
8860 if matches!(self.runs_on, RunsOn::Agent) {
8861 return Err(
8862 "constraints.max_concurrent needs a central counter and is backend-only; \
8863 it cannot be combined with runs_on: agent (each agent self-schedules, \
8864 so there is no fleet-wide count to cap against)"
8865 .into(),
8866 );
8867 }
8868 if mc == 0 {
8869 return Err(
8870 "constraints.max_concurrent must be >= 1 (0 would never fire; \
8871 omit it for no cap)"
8872 .into(),
8873 );
8874 }
8875 }
8876 // #418: constraints.require (host-state env gates: ac_power /
8877 // idle / cpu_below / network) is sensed in-process by the agent,
8878 // so it needs runs_on: agent — the backend can't read a target
8879 // host's power / idle / cpu / connectivity state. Symmetric with
8880 // `when: { on }` (also agent-only); inverse of max_concurrent
8881 // (backend-only).
8882 if let Some(req) = &self.constraints.require {
8883 if !req.is_empty() && matches!(self.runs_on, RunsOn::Backend) {
8884 return Err(
8885 "constraints.require (host-state env gates: ac_power / idle / cpu_below / \
8886 network) is sensed in-process by the agent and needs runs_on: agent; the \
8887 backend cannot read a target host's power / idle / cpu / connectivity state"
8888 .into(),
8889 );
8890 }
8891 // Reject a malformed idle duration at create time so the
8892 // fail-closed runtime path only ever bites a hand-edited
8893 // KV blob (mirror skip_dates / on_failure.retry).
8894 if let Some(err) = req.bad_idle() {
8895 return Err(err);
8896 }
8897 // cpu_below is a percent — reject out-of-range so a typo
8898 // can't make a schedule that never (>=100 is always-busy?
8899 // no — <0 never matches) or trivially fires.
8900 if let Some(c) = req.cpu_below
8901 && !(c > 0.0 && c <= 100.0)
8902 {
8903 return Err(format!(
8904 "constraints.require.cpu_below must be in (0, 100] percent (got {c}); \
8905 omit it for no CPU requirement"
8906 ));
8907 }
8908 }
8909 // #418 Phase 4: a bad on_failure.retry is rejected at create
8910 // time — backoff must be valid humantime, and max is bounded
8911 // so a typo can't pin a flapping script in a tight loop.
8912 if let Some(r) = &self.on_failure.retry {
8913 let backoff = humantime::parse_duration(&r.backoff).map_err(|e| {
8914 format!(
8915 "on_failure.retry.backoff: invalid duration '{}': {e}",
8916 r.backoff
8917 )
8918 })?;
8919 // The wire form lowers backoff to whole seconds, so a
8920 // sub-second value would silently become a 0s no-wait
8921 // (coderabbit #466). Reject it rather than honour a backoff
8922 // the operator can't actually get.
8923 if backoff.as_secs() < 1 {
8924 return Err(format!(
8925 "on_failure.retry.backoff must be >= 1s (got '{}'); sub-second backoffs \
8926 round to 0 on the wire",
8927 r.backoff
8928 ));
8929 }
8930 if !(1..=10).contains(&r.max) {
8931 return Err(format!(
8932 "on_failure.retry.max must be 1..=10 (got {}); it counts additional \
8933 attempts after the first run",
8934 r.max
8935 ));
8936 }
8937 }
8938 // A blank / whitespace-only tag renders an empty filter chip on
8939 // the Schedules page — reject it at create time, mirroring the
8940 // Manifest::validate tag guard.
8941 for tag in &self.tags {
8942 if tag.trim().is_empty() {
8943 return Err("tags must not contain empty entries".to_string());
8944 }
8945 }
8946 Ok(())
8947 }
8948}
8949
8950/// Shared `serde(default)` for `bool` fields that default to `true`
8951/// (e.g. `CheckHint::fleet` / `CheckHint::health`). Generic name so it
8952/// doesn't read as "fleet" when reused for `health`.
8953fn default_true() -> bool {
8954 true
8955}