Skip to main content

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}
802
803/// Dynamic display gate for a [`ClientHint`] — see
804/// [`ClientHint::show_when`]. Shows the job only while the named check's
805/// latest status is one of [`is`](ShowWhen::is).
806#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
807pub struct ShowWhen {
808    /// The `check:` slug (a [`CheckHint::name`](crate::manifest::CheckHint::name))
809    /// whose latest status gates this job. May be defined by a *different*
810    /// manifest: checks are keyed by name in the agent's snapshot, so a
811    /// standalone detector job and this one can share a slug. A check that
812    /// has never run (absent from the snapshot) does NOT match — the job
813    /// stays hidden until the detector first reports (fails closed, like
814    /// `visible_to`).
815    pub check: String,
816    /// The check status(es) in which the job is SHOWN. Accepts a single
817    /// status (`is: fail`) or a list (`is: [fail, unknown]`); both
818    /// deserialize to a `Vec`. The `length(min = 1)` schema constraint +
819    /// [`Manifest::validate`] both reject an empty set (it would match
820    /// nothing and silently hide the job) so schema-driven tooling and the
821    /// write path agree.
822    #[serde(deserialize_with = "de_one_or_many_check_status")]
823    #[schemars(length(min = 1))]
824    pub is: Vec<crate::ipc::state::CheckStatus>,
825}
826
827/// Accept either a single `CheckStatus` (`is: fail`) or a sequence
828/// (`is: [fail, unknown]`) for [`ShowWhen::is`], normalising to a `Vec`.
829/// The scalar form is purely author ergonomics; the JSON schema advertises
830/// the canonical array form (`#[schemars(with = ...)]`).
831fn de_one_or_many_check_status<'de, D>(
832    d: D,
833) -> Result<Vec<crate::ipc::state::CheckStatus>, D::Error>
834where
835    D: serde::Deserializer<'de>,
836{
837    use crate::ipc::state::CheckStatus;
838    #[derive(Deserialize)]
839    #[serde(untagged)]
840    enum OneOrMany {
841        One(CheckStatus),
842        Many(Vec<CheckStatus>),
843    }
844    Ok(match OneOrMany::deserialize(d)? {
845        OneOrMany::One(c) => vec![c],
846        OneOrMany::Many(v) => v,
847    })
848}
849
850/// #720 — one widget on the SPA **Analytics** page: a declarative
851/// aggregation over the `obs_events` table. The backend reads these off
852/// `Manifest::aggregate` (from `BUCKET_JOBS`) at query time and builds
853/// the `json_extract` GROUP BY / time-bucket SQL from these generic
854/// primitives, so an operator can chart any emitted event without a Rust
855/// change. The reference shapes are the attendance dashboards
856/// (presence / app_sample / web_visit), but the same DSL covers logon /
857/// reboot / agent-health trends, etc.
858#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
859pub struct AggregateWidget {
860    /// Tab this widget lives under on the Analytics page. Widgets from
861    /// every job are collected and grouped by this label, so the same
862    /// string across jobs builds one multi-source dashboard. Required.
863    pub dashboard: String,
864    /// Widget heading. Required, validated non-empty.
865    pub title: String,
866    /// Optional one-line subtitle shown muted under the `title` on the
867    /// Analytics page — room for a unit, a caveat, or what the number
868    /// means ("samples × 2 min", "Security 4624 only"). Rejected if
869    /// present-but-blank.
870    #[serde(default, skip_serializing_if = "Option::is_none")]
871    pub description: Option<String>,
872    /// Optional sort weight (#743). Once the order-aware sort lands (PR2)
873    /// widgets render in `(order, dashboard, title)` order, so a lower
874    /// `order` pulls a widget — and its tab — earlier; equal/absent `order`
875    /// falls back to the alphabetical `(dashboard, title)` ordering. Treated
876    /// as `0` when unset, so a fleet with no `order` anywhere stays purely
877    /// alphabetical (today's behaviour); negatives are allowed to pin
878    /// something first. (This field only carries the value; the backend
879    /// applies it.)
880    #[serde(default, skip_serializing_if = "Option::is_none")]
881    pub order: Option<i32>,
882    /// Promote this widget to the main Dashboard, not just the Analytics
883    /// page (#vuln-roadmap PR3). The Dashboard fetches the pinned subset
884    /// (`/api/analytics?pinned=true`, fleet scope) and renders it with the
885    /// same widget components. Operator-controlled, so any config-driven
886    /// view (e.g. a future vulnerability rollup) can surface up front
887    /// without a bespoke card. Defaults to `false`. Pin a `scope: fleet`
888    /// widget — a `pc`-scoped one needs a selected PC and won't render on
889    /// the fleet Dashboard.
890    // `Not::not` is `!self`, so this skips serializing the field when it's
891    // `false` — keeps `pin_dashboard: false` out of the stored job/view JSON,
892    // matching how the optional fields above omit their defaults.
893    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
894    pub pin_dashboard: bool,
895    /// `pc` rolls up a single selected PC; `fleet` rolls up all PCs
896    /// (and unlocks `group_by: pc_id` to rank PCs against each other).
897    /// Defaults to `pc`.
898    #[serde(default)]
899    pub scope: AggregateScope,
900    /// `obs_events.kind` this widget reads (e.g. `app_sample`,
901    /// `presence`, `unexpected_shutdown`). Required for every aggregation
902    /// render (`bar`/`gauge`/`timeline`/`stat`); rejected for
903    /// `op_timeline`, which reconstructs a fixed multi-kind operational
904    /// swimlane (power/session/sleep) baked into the SPA and so reads no
905    /// single `kind`.
906    #[serde(default, skip_serializing_if = "Option::is_none")]
907    pub kind: Option<String>,
908    /// Optional `obs_events.source` filter, when one `kind` is emitted by
909    /// more than one collector.
910    #[serde(default, skip_serializing_if = "Option::is_none")]
911    pub source: Option<String>,
912    /// How to roll the matching events up. See [`AggregateAgg`]. Required
913    /// for every aggregation render; rejected for `op_timeline` (which
914    /// performs no rollup — it returns the raw operational events and the
915    /// SPA folds them into lane spans).
916    #[serde(default, skip_serializing_if = "Option::is_none")]
917    pub agg: Option<AggregateAgg>,
918    /// Dotted JSON path (no `$.` prefix) to group by for `agg: count` /
919    /// `sum` — e.g. `foreground.app`. The literal `pc_id` is special:
920    /// it groups by the `pc_id` column (fleet ranking), not a payload
921    /// field. Omit for a single total. Required when `agg: sum` needs a
922    /// breakdown; for `agg: count` omitting it yields the grand total.
923    #[serde(default, skip_serializing_if = "Option::is_none")]
924    pub group_by: Option<String>,
925    /// Dotted JSON path to a boolean for `agg: ratio` (e.g. `active`):
926    /// the widget reports `true_count / total`. Required when `agg: ratio`.
927    #[serde(default, skip_serializing_if = "Option::is_none")]
928    pub bool_path: Option<String>,
929    /// Dotted JSON path to a number for `agg: sum`. Required when `agg: sum`.
930    #[serde(default, skip_serializing_if = "Option::is_none")]
931    pub value_path: Option<String>,
932    /// Optional value transform applied before grouping. Currently only
933    /// `host` (parse a URL down to its host) — used by the top-sites
934    /// widget, where SQLite can't parse a URL so the backend does it in
935    /// Rust. See [`AggregateTransform`].
936    #[serde(default, skip_serializing_if = "Option::is_none")]
937    pub transform: Option<AggregateTransform>,
938    /// Optional sampling cadence in minutes. When set, a `count` is also
939    /// reported as estimated time (`count × sample_minutes`) — e.g. a
940    /// 2-minute app sampler turns 11 samples into ~22 minutes. Must be ≥ 1.
941    #[serde(default, skip_serializing_if = "Option::is_none")]
942    #[schemars(range(min = 1))]
943    pub sample_minutes: Option<u32>,
944    /// Grouped values to drop from the rollup (e.g. `["LockApp"]` so the
945    /// lock screen doesn't top the app ranking). Empty by default.
946    #[serde(default, skip_serializing_if = "Vec::is_empty")]
947    pub exclude: Vec<String>,
948    /// Optional time bucketing — `hour` buckets events by local
949    /// hour-of-day for a `timeline` render. See [`AggregateTimeBucket`].
950    #[serde(default, skip_serializing_if = "Option::is_none")]
951    pub time_bucket: Option<AggregateTimeBucket>,
952    /// Top-N cap for grouped renders (`bar`). Defaults to 10 when unset.
953    #[serde(default, skip_serializing_if = "Option::is_none")]
954    #[schemars(range(min = 1))]
955    pub limit: Option<u32>,
956    /// Which widget the SPA draws. See [`AggregateRender`].
957    pub render: AggregateRender,
958}
959
960/// Per-PC vs fleet-wide rollup for an [`AggregateWidget`].
961#[derive(
962    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
963)]
964#[serde(rename_all = "lowercase")]
965#[non_exhaustive]
966pub enum AggregateScope {
967    /// Roll up the single PC the operator selected. The default.
968    #[default]
969    Pc,
970    /// Roll up across every PC. Unlocks `group_by: pc_id`.
971    Fleet,
972    /// #492 forward-compat catch-all — a Manifest is read fleet-wide, so
973    /// an older reader must tolerate a future variant rather than failing
974    /// to decode the whole job. The backend skips an `Unknown` widget.
975    #[serde(other)]
976    Unknown,
977}
978
979/// The rollup function for an [`AggregateWidget`].
980#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
981#[serde(rename_all = "lowercase")]
982#[non_exhaustive]
983pub enum AggregateAgg {
984    /// Row count, optionally grouped (`group_by`) and time-estimated
985    /// (`sample_minutes`).
986    Count,
987    /// `true_count / total` over `bool_path`.
988    Ratio,
989    /// Sum of `value_path`, optionally grouped.
990    Sum,
991    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
992    #[serde(other)]
993    Unknown,
994}
995
996/// Optional pre-grouping value transform for an [`AggregateWidget`].
997#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
998#[serde(rename_all = "lowercase")]
999#[non_exhaustive]
1000pub enum AggregateTransform {
1001    /// Parse the grouped value as a URL and keep only its host.
1002    Host,
1003    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1004    #[serde(other)]
1005    Unknown,
1006}
1007
1008/// Time bucketing for an [`AggregateWidget`] (drives a `timeline`).
1009#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1010#[serde(rename_all = "lowercase")]
1011#[non_exhaustive]
1012pub enum AggregateTimeBucket {
1013    /// Bucket by local hour-of-day (0–23), summed over the window.
1014    Hour,
1015    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1016    #[serde(other)]
1017    Unknown,
1018}
1019
1020/// Which visual the SPA renders an [`AggregateWidget`] as.
1021#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1022#[serde(rename_all = "lowercase")]
1023#[non_exhaustive]
1024pub enum AggregateRender {
1025    /// Ranked horizontal bars (a grouped `count` / `sum`).
1026    Bar,
1027    /// A single ratio dial (`agg: ratio`).
1028    Gauge,
1029    /// 24-hour activity strip (`time_bucket: hour`).
1030    Timeline,
1031    /// A single headline number (an ungrouped total).
1032    Stat,
1033    /// Per-PC operational swimlane (power / session / sleep) reconstructed
1034    /// from a fixed multi-kind event set. Unlike the aggregation renders it
1035    /// reads no single `kind`/`agg`: the backend returns the raw events in
1036    /// the window and the SPA folds them into lane spans (shared with the
1037    /// Events page strip). Per-PC only (`scope: pc`).
1038    #[serde(rename = "op_timeline")]
1039    OpTimeline,
1040    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1041    #[serde(other)]
1042    Unknown,
1043}
1044
1045/// True if `p` is a well-formed dotted JSON path of `[A-Za-z0-9_]`
1046/// segments joined by single dots — the shape safe to bind into
1047/// `json_extract(payload, '$.' || ?)`. The charset blocks injection; the
1048/// segment check additionally rejects `"."`, `".foo"`, `"foo."`,
1049/// `"foo..bar"`, which would pass the charset but produce a malformed
1050/// `$.` path that errors at query time. Accepts `pc_id`, `foreground.app`,
1051/// `active`, etc.
1052fn is_valid_json_path(p: &str) -> bool {
1053    !p.is_empty()
1054        && p.split('.').all(|seg| {
1055            !seg.is_empty() && seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
1056        })
1057}
1058
1059/// Per-widget validation for a list of [`AggregateWidget`]s — shared by
1060/// the `aggregate:` job hint ([`Manifest::validate`]) and the standalone
1061/// [`View`] resource (#743) so the two can't diverge. `field` names the
1062/// containing key for error messages (`"aggregate"` or `"widgets"`).
1063///
1064/// Enforces: non-empty list; non-empty dashboard/title (and `kind`/`agg`
1065/// for every aggregation render); a blank-when-set `source`; rejection of
1066/// any #492 `Unknown` enum (an operator typo at create time); safe dotted
1067/// JSON paths; the value path each `agg` needs (and rejection of mis-paired
1068/// ones); `pc_id` grouping only in `fleet` scope; `transform`/`limit`/
1069/// `exclude` only with a `group_by`; positive `limit`/`sample_minutes`;
1070/// `gauge`⇔`ratio`; and `timeline`⇔`time_bucket`. A `render: op_timeline`
1071/// widget is validated separately (per-PC, no aggregation knobs) — see
1072/// [`validate_op_timeline_widget`].
1073pub fn validate_aggregate_widgets(widgets: &[AggregateWidget], field: &str) -> Result<(), String> {
1074    if widgets.is_empty() {
1075        return Err(format!(
1076            "`{field}:` must list at least one widget when present"
1077        ));
1078    }
1079    for (i, w) in widgets.iter().enumerate() {
1080        let at = format!("{field}[{i}]");
1081        for (label, value) in [("dashboard", &w.dashboard), ("title", &w.title)] {
1082            if value.trim().is_empty() {
1083                return Err(format!("{at}.{label} must not be empty"));
1084            }
1085        }
1086        // A present-but-blank `description` renders an empty muted line —
1087        // reject it so the subtitle only shows when it says something.
1088        if let Some(description) = &w.description {
1089            if description.trim().is_empty() {
1090                return Err(format!("{at}.description must not be empty when set"));
1091            }
1092        }
1093        // Reject values that fell through to the #492 `Unknown` catch-all:
1094        // at create time on the current version that's an operator typo. (A
1095        // genuinely-future variant only reaches an older reader via a stored
1096        // resource, which is never re-validated, so forward-compat holds.)
1097        if w.scope == AggregateScope::Unknown {
1098            return Err(format!("{at}.scope is not a known value (pc | fleet)"));
1099        }
1100        if w.render == AggregateRender::Unknown {
1101            return Err(format!(
1102                "{at}.render is not a known value (bar | gauge | timeline | stat | op_timeline)"
1103            ));
1104        }
1105        // `op_timeline` reconstructs a fixed per-PC operational swimlane
1106        // (power/session/sleep) from a baked-in multi-kind set — it uses none
1107        // of the aggregation knobs, so validate it on its own terms (per-PC,
1108        // no `kind`/`agg`/grouping) and skip the rollup rules below.
1109        if w.render == AggregateRender::OpTimeline {
1110            validate_op_timeline_widget(w, &at)?;
1111            continue;
1112        }
1113        // Every other render is an aggregation over a single `kind`.
1114        if w.kind.as_deref().map(str::trim).unwrap_or("").is_empty() {
1115            return Err(format!("{at}.kind must not be empty"));
1116        }
1117        let agg = match w.agg {
1118            Some(AggregateAgg::Unknown) => {
1119                return Err(format!(
1120                    "{at}.agg is not a known value (count | ratio | sum)"
1121                ));
1122            }
1123            Some(agg) => agg,
1124            None => return Err(format!("{at}.agg is required")),
1125        };
1126        // A present-but-blank `source` is a no-op filter — reject like the
1127        // other blank-when-set guards.
1128        if let Some(source) = &w.source {
1129            if source.trim().is_empty() {
1130                return Err(format!("{at}.source must not be empty when set"));
1131            }
1132        }
1133        if w.transform == Some(AggregateTransform::Unknown) {
1134            return Err(format!("{at}.transform is not a known value (host)"));
1135        }
1136        if w.time_bucket == Some(AggregateTimeBucket::Unknown) {
1137            return Err(format!("{at}.time_bucket is not a known value (hour)"));
1138        }
1139        for (label, path) in [
1140            ("group_by", &w.group_by),
1141            ("bool_path", &w.bool_path),
1142            ("value_path", &w.value_path),
1143        ] {
1144            if let Some(p) = path {
1145                if !is_valid_json_path(p) {
1146                    return Err(format!(
1147                        "{at}.{label} '{p}' must be a dotted JSON path of [A-Za-z0-9_] segments"
1148                    ));
1149                }
1150            }
1151        }
1152        // Each agg uses exactly one value path; reject a mis-paired path so
1153        // a typo fails at create rather than being ignored.
1154        match agg {
1155            // count: grouped → ranking, ungrouped → grand total.
1156            AggregateAgg::Count => {
1157                for (label, path) in [("bool_path", &w.bool_path), ("value_path", &w.value_path)] {
1158                    if path.is_some() {
1159                        return Err(format!("{at}.agg=count does not use `{label}`"));
1160                    }
1161                }
1162            }
1163            AggregateAgg::Ratio => {
1164                if w.bool_path.is_none() {
1165                    return Err(format!("{at}.agg=ratio requires `bool_path`"));
1166                }
1167                if w.value_path.is_some() {
1168                    return Err(format!("{at}.agg=ratio does not use `value_path`"));
1169                }
1170            }
1171            AggregateAgg::Sum => {
1172                if w.value_path.is_none() {
1173                    return Err(format!("{at}.agg=sum requires `value_path`"));
1174                }
1175                if w.bool_path.is_some() {
1176                    return Err(format!("{at}.agg=sum does not use `bool_path`"));
1177                }
1178            }
1179            // Rejected above; arm exists only for exhaustiveness.
1180            AggregateAgg::Unknown => {}
1181        }
1182        // Ranking PCs against each other only means something across the
1183        // fleet — within one PC it's a single bar.
1184        if w.group_by.as_deref() == Some("pc_id") && w.scope != AggregateScope::Fleet {
1185            return Err(format!(
1186                "{at}.group_by: pc_id is only valid with scope: fleet"
1187            ));
1188        }
1189        // `transform` rewrites the grouped PAYLOAD value (URL→host); it's
1190        // meaningless on a `pc_id` grouping (the pc_id column, not a payload
1191        // field), so reject the combo at create time.
1192        if w.transform.is_some() && w.group_by.as_deref() == Some("pc_id") {
1193            return Err(format!("{at}.transform is not valid with group_by: pc_id"));
1194        }
1195        // limit / transform / exclude all operate on grouped values, so
1196        // without a `group_by` they're silent no-ops — reject.
1197        if w.group_by.is_none() {
1198            if w.limit.is_some() {
1199                return Err(format!("{at}.limit requires `group_by`"));
1200            }
1201            if w.transform.is_some() {
1202                return Err(format!("{at}.transform requires `group_by`"));
1203            }
1204            if !w.exclude.is_empty() {
1205                return Err(format!("{at}.exclude requires `group_by`"));
1206            }
1207        }
1208        if w.limit == Some(0) {
1209            return Err(format!("{at}.limit must be > 0"));
1210        }
1211        if w.sample_minutes == Some(0) {
1212            return Err(format!("{at}.sample_minutes must be > 0"));
1213        }
1214        for ex in &w.exclude {
1215            if ex.trim().is_empty() {
1216                return Err(format!("{at}.exclude must not contain empty entries"));
1217            }
1218        }
1219        // A gauge draws a single ratio dial — only meaningful for agg: ratio.
1220        if w.render == AggregateRender::Gauge && agg != AggregateAgg::Ratio {
1221            return Err(format!("{at}.render=gauge is only valid with agg: ratio"));
1222        }
1223        // A timeline needs a bucket; a bucket on any other render is a no-op
1224        // that signals operator confusion — reject both.
1225        match (w.render, &w.time_bucket) {
1226            (AggregateRender::Timeline, None) => {
1227                return Err(format!("{at}.render=timeline requires `time_bucket`"));
1228            }
1229            (r, Some(_)) if r != AggregateRender::Timeline => {
1230                return Err(format!(
1231                    "{at}.time_bucket is only valid with render: timeline"
1232                ));
1233            }
1234            _ => {}
1235        }
1236    }
1237    Ok(())
1238}
1239
1240/// Validate a `render: op_timeline` widget. It draws a fixed per-PC
1241/// operational swimlane (power / session / sleep) reconstructed by the SPA
1242/// from a baked-in multi-kind event set, so it uses none of the aggregation
1243/// knobs: require `scope: pc` and reject every field that only makes sense
1244/// for a rollup (`kind`/`source`/`agg`/`group_by`/`bool_path`/`value_path`/
1245/// `transform`/`sample_minutes`/`exclude`/`time_bucket`/`limit`). Rejecting
1246/// the unused fields (rather than ignoring them) keeps an operator typo from
1247/// silently doing nothing, matching the rest of this validator.
1248fn validate_op_timeline_widget(w: &AggregateWidget, at: &str) -> Result<(), String> {
1249    // Per-PC only: a fleet-wide swimlane of every PC's spans is unbounded
1250    // and unreadable, and the backend only computes it in per-PC scope.
1251    if w.scope != AggregateScope::Pc {
1252        return Err(format!("{at}.render=op_timeline requires scope: pc"));
1253    }
1254    // Each unused field, with the name the operator wrote, so the error
1255    // points at exactly what to delete.
1256    if w.kind.is_some() {
1257        return Err(format!("{at}.render=op_timeline does not use `kind`"));
1258    }
1259    if w.source.is_some() {
1260        return Err(format!("{at}.render=op_timeline does not use `source`"));
1261    }
1262    if w.agg.is_some() {
1263        return Err(format!("{at}.render=op_timeline does not use `agg`"));
1264    }
1265    for (label, set) in [
1266        ("group_by", w.group_by.is_some()),
1267        ("bool_path", w.bool_path.is_some()),
1268        ("value_path", w.value_path.is_some()),
1269        ("transform", w.transform.is_some()),
1270        ("sample_minutes", w.sample_minutes.is_some()),
1271        ("time_bucket", w.time_bucket.is_some()),
1272        ("limit", w.limit.is_some()),
1273        ("exclude", !w.exclude.is_empty()),
1274    ] {
1275        if set {
1276            return Err(format!("{at}.render=op_timeline does not use `{label}`"));
1277        }
1278    }
1279    Ok(())
1280}
1281
1282/// Default materialization cadence for a [`SqlWidget`] whose `refresh` is
1283/// unset — 1 hour. A view over feed/inventory tables changes only as fast as
1284/// its underlying feed refresh (often daily), so an hour is fresh enough while
1285/// keeping an expensive correlation join off the ~30s Dashboard poll path.
1286pub const DEFAULT_VIEW_REFRESH: std::time::Duration = std::time::Duration::from_secs(3600);
1287
1288/// #vuln-roadmap PR3: a **SQL-backed, materialized** widget on a [`View`].
1289///
1290/// Where an [`AggregateWidget`] encodes an `obs_events` rollup in structured
1291/// YAML fields, a `SqlWidget` carries a raw read-only `SELECT`/`WITH` over the
1292/// projector's tables (inventory `explode:` tables, `feeds`, `check_status`,
1293/// …) — the correlation that powers a vulnerability / EOL / license dashboard
1294/// is just a `JOIN`, far more expressive than a YAML DSL. The backend runs the
1295/// query in the read-only sandbox (`api::query`), caches the result on the
1296/// `refresh` cadence, and maps it to the same render-ready shape the existing
1297/// widget components consume, via [`RenderSpec`]. See [`View::sql_widgets`].
1298#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1299pub struct SqlWidget {
1300    /// Widget heading. Required, validated non-empty.
1301    pub title: String,
1302    /// Optional muted subtitle (a unit, a caveat). Rejected if present-blank.
1303    #[serde(default, skip_serializing_if = "Option::is_none")]
1304    pub description: Option<String>,
1305    /// The read-only SQL. Executed in the `api::query` sandbox: a single
1306    /// `SELECT`/`WITH` on a `SQLITE_OPEN_READONLY` connection, row-capped and
1307    /// time-bounded. The backend validates it read-only at `view create` and
1308    /// again at run time; a write verb / stacked statement is rejected.
1309    pub query: String,
1310    /// How the query's result columns map to a visual — see [`RenderSpec`].
1311    pub render: RenderSpec,
1312    /// Materialization cadence as a humantime duration (`"6h"`, `"30m"`).
1313    /// Absent ⇒ [`DEFAULT_VIEW_REFRESH`]. The backend re-runs the query at
1314    /// most this often; reads in between hit the cache.
1315    #[serde(default, skip_serializing_if = "Option::is_none")]
1316    pub refresh: Option<String>,
1317    /// Where the widget surfaces — an Analytics tab and/or a pinned Dashboard
1318    /// card. At least one must be set (else it renders nowhere).
1319    pub placement: Placement,
1320}
1321
1322impl SqlWidget {
1323    /// The effective refresh cadence — the parsed `refresh` or
1324    /// [`DEFAULT_VIEW_REFRESH`]. Falls back to the default on an unparseable
1325    /// value rather than panicking on the read path (validation already
1326    /// rejected a bad value at `view create`).
1327    pub fn refresh_interval(&self) -> std::time::Duration {
1328        self.refresh
1329            .as_deref()
1330            .and_then(|s| humantime::parse_duration(s).ok())
1331            .unwrap_or(DEFAULT_VIEW_REFRESH)
1332    }
1333}
1334
1335/// How a [`SqlWidget`]'s SQL result columns map onto a visual. A `kind` names
1336/// the chart; the channel fields (`value`, `label`, `columns`, …) name which
1337/// result columns feed it. Only the channels a `kind` uses are read; the
1338/// backend validates the named columns exist in the result. New chart types
1339/// are "one renderer + the same mapping", so this stays a flat, additive shape.
1340#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Hash)]
1341pub struct RenderSpec {
1342    /// Which visual to render the result as.
1343    pub kind: RenderKind,
1344    /// `table` only: the columns to show, in order. Absent ⇒ every result
1345    /// column (the universal default).
1346    #[serde(default, skip_serializing_if = "Option::is_none")]
1347    pub columns: Option<Vec<String>>,
1348    /// `table` only: optional per-column header relabelling (result column →
1349    /// display name). Columns not listed keep their SQL name.
1350    #[serde(default, skip_serializing_if = "Option::is_none")]
1351    pub labels: Option<std::collections::BTreeMap<String, String>>,
1352    /// `stat` / `bar` / `pie` / `gauge`: the result column holding the numeric
1353    /// value (`stat`/`gauge` read the first row; `bar`/`pie` read every row).
1354    #[serde(default, skip_serializing_if = "Option::is_none")]
1355    pub value: Option<String>,
1356    /// `bar` / `pie`: the result column holding each row's category label.
1357    #[serde(default, skip_serializing_if = "Option::is_none")]
1358    pub label: Option<String>,
1359    /// `bar` / `pie`: keep only the top-N rows (by value). Absent ⇒ all rows.
1360    #[serde(default, skip_serializing_if = "Option::is_none")]
1361    pub limit: Option<u32>,
1362    /// `pie` only: render as a donut (a hole with the total in the centre).
1363    #[serde(default, skip_serializing_if = "Option::is_none")]
1364    pub donut: Option<bool>,
1365    /// `gauge` only: the numerator column (paired with `den`). Alternative to
1366    /// a precomputed `value` ratio.
1367    #[serde(default, skip_serializing_if = "Option::is_none")]
1368    pub num: Option<String>,
1369    /// `gauge` only: the denominator column (paired with `num`).
1370    #[serde(default, skip_serializing_if = "Option::is_none")]
1371    pub den: Option<String>,
1372}
1373
1374/// The chart kind for a [`RenderSpec`]. `table` and `pie` are new in PR3; the
1375/// rest reuse the existing `obs_events` widget renderers.
1376#[derive(
1377    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash, Default,
1378)]
1379#[serde(rename_all = "lowercase")]
1380pub enum RenderKind {
1381    /// The full result grid (new renderer). The universal default.
1382    #[default]
1383    Table,
1384    /// A single headline number from the first row's `value` cell.
1385    Stat,
1386    /// Ranked horizontal bars — `label` + `value` per row, optional top-N.
1387    Bar,
1388    /// Parts-of-a-whole (new renderer) — `label` + `value` per row.
1389    Pie,
1390    /// A ratio dial — a `value` ratio, or a `num`/`den` pair.
1391    Gauge,
1392    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1393    #[serde(other)]
1394    Unknown,
1395}
1396
1397/// Where a [`SqlWidget`] surfaces in the SPA. Mirrors the placement an
1398/// [`AggregateWidget`] expresses via `dashboard` + `pin_dashboard`, but as an
1399/// explicit block since a SQL widget lives on a standalone view.
1400#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1401pub struct Placement {
1402    /// The Analytics tab this widget groups under (the `AggregateWidget`
1403    /// `dashboard` analogue). Absent ⇒ not shown on the Analytics page.
1404    #[serde(default, skip_serializing_if = "Option::is_none")]
1405    pub analytics: Option<String>,
1406    /// Promote to the main Dashboard (reuses #900's pinned section). Absent ⇒
1407    /// not pinned.
1408    #[serde(default, skip_serializing_if = "Option::is_none")]
1409    pub dashboard: Option<DashboardPlacement>,
1410}
1411
1412impl Placement {
1413    /// True when the widget is pinned to the main Dashboard.
1414    pub fn is_pinned(&self) -> bool {
1415        self.dashboard.as_ref().is_some_and(|d| d.pin)
1416    }
1417    /// The Analytics tab name, or a fallback so a dashboard-only widget still
1418    /// carries a group label for the shared widget list.
1419    pub fn tab(&self) -> &str {
1420        self.analytics.as_deref().unwrap_or("Dashboard")
1421    }
1422}
1423
1424/// The `placement.dashboard` block — see [`Placement::dashboard`].
1425#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1426pub struct DashboardPlacement {
1427    /// Pin this widget to the main Dashboard's promoted section.
1428    #[serde(default)]
1429    pub pin: bool,
1430}
1431
1432/// Per-widget validation for a list of [`SqlWidget`]s — shared by the
1433/// [`View`] resource so authoring errors surface at `view create`. `field`
1434/// names the containing key for error messages. The read-only SQL check is
1435/// NOT here (it lives in the backend `api::query` sandbox, which kanade-shared
1436/// can't depend on) — this validates structure: non-empty title/query, a
1437/// known `kind`, the channels each `kind` needs, a real placement, and a
1438/// parseable `refresh`.
1439pub fn validate_sql_widgets(widgets: &[SqlWidget], field: &str) -> Result<(), String> {
1440    for (i, w) in widgets.iter().enumerate() {
1441        let at = format!("{field}[{i}]");
1442        if w.title.trim().is_empty() {
1443            return Err(format!("{at}.title must not be empty"));
1444        }
1445        if w.query.trim().is_empty() {
1446            return Err(format!("{at}.query must not be empty"));
1447        }
1448        if let Some(description) = &w.description {
1449            if description.trim().is_empty() {
1450                return Err(format!("{at}.description must not be empty when set"));
1451            }
1452        }
1453        if let Some(refresh) = &w.refresh {
1454            humantime::parse_duration(refresh)
1455                .map_err(|e| format!("{at}.refresh '{refresh}' is not a valid duration: {e}"))?;
1456        }
1457        // A widget that surfaces nowhere is an invisible no-op. A
1458        // `dashboard:` block with `pin: false` doesn't count — it pins
1459        // nowhere — so gate on the effective pin, not the block's presence
1460        // (Gemini / CodeRabbit).
1461        if w.placement.analytics.is_none() && !w.placement.is_pinned() {
1462            return Err(format!(
1463                "{at}.placement must set `analytics` and/or pin to `dashboard` (else the widget renders nowhere)"
1464            ));
1465        }
1466        if let Some(tab) = &w.placement.analytics {
1467            if tab.trim().is_empty() {
1468                return Err(format!(
1469                    "{at}.placement.analytics must not be empty when set"
1470                ));
1471            }
1472        }
1473        validate_render_spec(&w.render, &at)?;
1474    }
1475    Ok(())
1476}
1477
1478/// Validate a [`RenderSpec`]: reject the #492 `Unknown` catch-all (an operator
1479/// typo at create time) and require the channel columns each `kind` reads.
1480fn validate_render_spec(r: &RenderSpec, at: &str) -> Result<(), String> {
1481    // A channel column is "given" when present and non-blank.
1482    let given = |v: &Option<String>| v.as_deref().map(str::trim).is_some_and(|s| !s.is_empty());
1483    match r.kind {
1484        RenderKind::Unknown => {
1485            return Err(format!(
1486                "{at}.render.kind is not a known value (table | stat | bar | pie | gauge)"
1487            ));
1488        }
1489        RenderKind::Table => {
1490            // `columns` optional; if given, each name must be non-blank.
1491            if let Some(cols) = &r.columns {
1492                if cols.iter().any(|c| c.trim().is_empty()) {
1493                    return Err(format!("{at}.render.columns must not contain blank names"));
1494                }
1495            }
1496            if let Some(labels) = &r.labels {
1497                for (k, v) in labels {
1498                    if k.trim().is_empty() || v.trim().is_empty() {
1499                        return Err(format!(
1500                            "{at}.render.labels keys and values must be non-empty"
1501                        ));
1502                    }
1503                }
1504            }
1505        }
1506        RenderKind::Stat => {
1507            if !given(&r.value) {
1508                return Err(format!("{at}.render.value is required for kind=stat"));
1509            }
1510        }
1511        RenderKind::Bar | RenderKind::Pie => {
1512            let kind = if r.kind == RenderKind::Bar {
1513                "bar"
1514            } else {
1515                "pie"
1516            };
1517            if !given(&r.label) {
1518                return Err(format!("{at}.render.label is required for kind={kind}"));
1519            }
1520            if !given(&r.value) {
1521                return Err(format!("{at}.render.value is required for kind={kind}"));
1522            }
1523            // `limit: 0` truncates to no rows — an invisible widget, almost
1524            // certainly a typo. Omit `limit` for "all rows" (CodeRabbit).
1525            if r.limit == Some(0) {
1526                return Err(format!(
1527                    "{at}.render.limit must be >= 1 (omit it to keep all rows)"
1528                ));
1529            }
1530        }
1531        RenderKind::Gauge => {
1532            // Either a precomputed `value` ratio, or a `num`/`den` pair —
1533            // exactly one of the two forms.
1534            match (given(&r.value), given(&r.num), given(&r.den)) {
1535                (true, false, false) => {}
1536                (false, true, true) => {}
1537                _ => {
1538                    return Err(format!(
1539                        "{at}.render for kind=gauge needs either `value` (a ratio) or both `num` and `den`"
1540                    ));
1541                }
1542            }
1543        }
1544    }
1545    Ok(())
1546}
1547
1548/// A standalone declarative read/aggregation for the Analytics page (#743).
1549///
1550/// A **view** aggregates stored fleet data (`obs_events`, …) without an
1551/// `execute` or a schedule — unlike a [`Manifest`] it only declares
1552/// [`AggregateWidget`]s. (The first line is concise on purpose: `schemars`
1553/// uses it as the generated schema's `title`.) The backend reads views from
1554/// `BUCKET_VIEWS` at
1555/// query time and merges their widgets with the co-located `aggregate:`
1556/// hints on jobs, so a cross-cutting dashboard (one that charts events
1557/// emitted by several other jobs / the agent) has a home that doesn't need
1558/// a noop job carrier. Stored JSON in `BUCKET_VIEWS`, keyed by `id`.
1559#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1560pub struct View {
1561    /// Stable identifier (the KV key). Required, validated non-empty.
1562    pub id: String,
1563    /// Optional human description shown on the Views admin page.
1564    #[serde(default, skip_serializing_if = "Option::is_none")]
1565    pub description: Option<String>,
1566    /// The `obs_events` aggregate widgets this view contributes to the
1567    /// Analytics page. Optional since PR3 — a view may instead (or also)
1568    /// carry [`sql_widgets`](View::sql_widgets); a view must have at least one
1569    /// widget across the two lists.
1570    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1571    pub widgets: Vec<AggregateWidget>,
1572    /// #vuln-roadmap PR3: SQL-backed, materialized widgets — raw read-only SQL
1573    /// over the projector tables (inventory/feeds/…) mapped to a visual. This
1574    /// is how a correlation dashboard (vulnerability / EOL / license) is
1575    /// expressed as config. See [`SqlWidget`].
1576    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1577    pub sql_widgets: Vec<SqlWidget>,
1578    /// Free-form operator taxonomy (same role as [`Manifest::tags`]).
1579    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1580    pub tags: Vec<String>,
1581    /// GitOps provenance (#678), stamped by `kanade view create` from the
1582    /// source YAML's Git context — same as [`Manifest::origin`].
1583    #[serde(default, skip_serializing_if = "Option::is_none")]
1584    pub origin: Option<RepoOrigin>,
1585}
1586
1587/// True if `id` is a safe resource identifier — non-empty and only
1588/// `[A-Za-z0-9._-]`. A view `id` becomes a NATS KV key *and* a URL path
1589/// segment (`/api/views/{id}`), so this blocks `/`, `..`, whitespace and
1590/// other characters that would break the KV key or let a CLI arg wander
1591/// the URL space. (#743 / #744 follow-up — a deliberately small charset
1592/// rather than the looser set NATS technically allows.)
1593pub fn is_valid_resource_id(id: &str) -> bool {
1594    !id.is_empty()
1595        && id
1596            .chars()
1597            .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-')
1598}
1599
1600impl View {
1601    pub fn validate(&self) -> Result<(), String> {
1602        if !is_valid_resource_id(self.id.trim()) {
1603            return Err(
1604                "view.id must be non-empty and only [A-Za-z0-9._-] (it's a KV key + URL segment)"
1605                    .to_string(),
1606            );
1607        }
1608        // A view must contribute at least one widget across the two lists;
1609        // `validate_aggregate_widgets` rejects an empty `widgets` on its own,
1610        // so only call it when that list is non-empty (a pure-SQL view is
1611        // valid with an empty `widgets`).
1612        if self.widgets.is_empty() && self.sql_widgets.is_empty() {
1613            return Err(
1614                "view must declare at least one widget (`widgets:` and/or `sql_widgets:`)"
1615                    .to_string(),
1616            );
1617        }
1618        if !self.widgets.is_empty() {
1619            validate_aggregate_widgets(&self.widgets, "widgets")?;
1620        }
1621        validate_sql_widgets(&self.sql_widgets, "sql_widgets")?;
1622        for tag in &self.tags {
1623            if tag.trim().is_empty() {
1624                return Err("tags must not contain empty entries".to_string());
1625            }
1626        }
1627        Ok(())
1628    }
1629}
1630
1631/// Issue #246 — `emit:` manifest block for jobs whose stdout is
1632/// NDJSON observability events (one `ObsEvent` per line). Parallel
1633/// to `inventory:` but for the append-only timeline pipeline; see
1634/// `Manifest::emit` for the full contract.
1635#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1636pub struct EmitConfig {
1637    /// What kind of payload the agent should expect on stdout. Only
1638    /// `events` is defined today (parses each non-empty line as
1639    /// `ObsEvent` and publishes on `obs.<pc_id>`); future variants
1640    /// (e.g. metrics streams, structured trace events) plug in here.
1641    #[serde(rename = "type")]
1642    pub kind: EmitKind,
1643    /// Operator hint for where the script keeps its own state — the
1644    /// watermark file the PowerShell / sh body reads + writes
1645    /// between runs so it only emits NEW events since the last
1646    /// poll. The agent doesn't read this; it's documentation that
1647    /// the SPA (and `kanade job edit`) can surface to operators
1648    /// reviewing the manifest. Optional; the script is allowed to
1649    /// keep state anywhere (registry, env, etc.) — the field's
1650    /// presence makes the convention discoverable.
1651    #[serde(default, skip_serializing_if = "Option::is_none")]
1652    pub watermark_path: Option<String>,
1653}
1654
1655/// `emit.type` enum. Lowercase serde so manifests read
1656/// `type: events` rather than `Events`.
1657#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1658#[serde(rename_all = "lowercase")]
1659pub enum EmitKind {
1660    /// Per-line `ObsEvent` JSON. Agent parses + publishes on
1661    /// `obs.<pc_id>`, drops the stdout from the resulting
1662    /// `ExecResult`.
1663    Events,
1664}
1665
1666/// v0.31 / #40: declarative "flatten this JSON array into a real
1667/// SQLite table" spec on an inventory manifest. The projector
1668/// creates the table on first registration (CREATE TABLE IF NOT
1669/// EXISTS + indexes) and writes a row per element of
1670/// `payload[field]` on every result, scoped by (pc_id, job_id) so
1671/// each PC's rows replace cleanly without a per-PC schema.
1672#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1673pub struct ExplodeSpec {
1674    /// JSON array key under the payload to explode. E.g. `"apps"`
1675    /// for `payload: { apps: [{...}, {...}] }`.
1676    pub field: String,
1677    /// Derived SQLite table name. Operators choose this — pick
1678    /// something namespaced + stable (`inventory_sw_apps`, not
1679    /// `apps`) so multiple inventory manifests don't collide on a
1680    /// generic name.
1681    pub table: String,
1682    /// Element-level fields that uniquely identify a row inside one
1683    /// PC's payload. The full PK is `(pc_id, job_id) + these
1684    /// columns`. Required — operators must think about uniqueness
1685    /// (e.g. `["name", "source"]` for installed apps because the
1686    /// same name appears in multiple uninstall hives).
1687    ///
1688    /// v0.31 / #41: same tuple drives history identity. When
1689    /// `track_history` is on, the projector serialises these
1690    /// fields' values into `inventory_history.identity_json` for
1691    /// every change event, so queries like "every PC that ever
1692    /// installed Chrome (any source)" filter on identity_json
1693    /// content without a per-manifest schema.
1694    pub primary_key: Vec<String>,
1695    /// Per-element fields that become columns in the derived table.
1696    pub columns: Vec<ExplodeColumn>,
1697    /// v0.31 / #41: when true (default false), the projector
1698    /// diffs each PC's incoming payload against the prior rows
1699    /// for the same (pc_id, job_id) BEFORE the DELETE-then-INSERT
1700    /// replace, and writes added / removed / changed events into
1701    /// `inventory_history`. Lets operators answer time-dimension
1702    /// questions ("when did Chrome 120 first appear on PC X?",
1703    /// "what's the Win 11 23H2 rollout curve") without storing
1704    /// per-scan snapshots. Off by default so operators opt in
1705    /// per-spec — history has a real storage cost on long-lived
1706    /// deployments (mitigated by the 90-day default retention
1707    /// sweeper, see `cleanup` module).
1708    #[serde(default)]
1709    pub track_history: bool,
1710}
1711
1712/// One column in an [`ExplodeSpec`]'s derived table.
1713#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1714pub struct ExplodeColumn {
1715    /// JSON key under each array element. Becomes the column name
1716    /// in the derived SQLite table — we don't rename.
1717    pub field: String,
1718    /// SQLite affinity: `"text"` (default), `"integer"`, `"real"`.
1719    /// Storage maps directly via `sqlx::query.bind(...)`; type
1720    /// mismatches at INSERT-time fail loudly rather than silently
1721    /// dropping the row.
1722    #[serde(default, skip_serializing_if = "Option::is_none")]
1723    #[serde(rename = "type")]
1724    pub kind: Option<String>,
1725    /// When true, the projector creates a `CREATE INDEX` on this
1726    /// column at table-creation time. Boost for the common-filter
1727    /// columns (`name`, `version`) — operators mark them
1728    /// explicitly, the projector won't guess.
1729    #[serde(default)]
1730    pub index: bool,
1731}
1732
1733/// #vuln-roadmap: one declarative **external-data feed** on a `feed:`
1734/// manifest — see [`Manifest::feed`]. Unlike inventory [`ExplodeSpec`]
1735/// (keyed per `(pc_id, job_id)`), a feed is GLOBAL fleet-wide reference
1736/// data: the controller-tier job's script fetches + shapes it, prints the
1737/// array under [`field`](FeedSpec::field) inside a `#KANADE-FEED-BEGIN/END`
1738/// fence, and the projector REPLACES that feed's rows wholesale in the
1739/// shared `feeds` table keyed `(feed_id, item_id)`. The full element JSON
1740/// lands in a `data` column, so a `view:` SQL `json_extract`s whatever
1741/// shape the feed carries — no per-feed schema, no dynamic DDL. One
1742/// manifest may declare several feeds.
1743#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1744pub struct FeedSpec {
1745    /// Stable feed identifier — the `feed_id` partition in the shared
1746    /// `feeds` table. Operators choose this; namespace it (`cisa-kev`,
1747    /// `endoflife-windows`) so feeds don't collide. A new result for the
1748    /// same id replaces that partition wholesale.
1749    pub id: String,
1750    /// JSON array key under the (fenced) payload to ingest. E.g.
1751    /// `"vulnerabilities"` for `{ vulnerabilities: [{...}, {...}] }`.
1752    pub field: String,
1753    /// Element-level field(s) whose values uniquely identify an item
1754    /// within the feed — they form the `item_id` key (joined for a
1755    /// composite key). Required: operators must think about uniqueness
1756    /// (e.g. `["cveID"]` for CISA KEV). An element missing any of these is
1757    /// skipped (it has no stable identity).
1758    pub primary_key: Vec<String>,
1759}
1760
1761#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1762pub struct DisplayField {
1763    /// Top-level key in the stdout JSON.
1764    pub field: String,
1765    /// Human-readable column header.
1766    pub label: String,
1767    /// Optional render hint — `"number"`, `"bytes"`, `"timestamp"`,
1768    /// or `"table"` (#39). Defaults to plain text rendering on the
1769    /// SPA side. `"table"` expects the field's value to be a JSON
1770    /// array of objects and renders a nested sub-table on the
1771    /// per-PC detail page using `columns` as the schema; the fleet
1772    /// summary view falls back to showing the row count for
1773    /// `"table"` cells so the wide list stays compact.
1774    #[serde(default, skip_serializing_if = "Option::is_none")]
1775    #[serde(rename = "type")]
1776    pub kind: Option<String>,
1777    /// v0.30 / #39: when `kind == "table"`, the SPA renders the
1778    /// field's value (an array of objects like
1779    /// `disks: [{ device_id, size_bytes, ... }]`) as a nested
1780    /// sub-table using these columns. Each column is itself a
1781    /// `DisplayField`, so the nested cells reuse the same render
1782    /// hints (`bytes`, `number`, `timestamp`) — no parallel format
1783    /// pipeline. Ignored for any other `kind`.
1784    #[serde(default, skip_serializing_if = "Option::is_none")]
1785    pub columns: Option<Vec<DisplayField>>,
1786}
1787
1788#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1789pub struct Rollout {
1790    #[serde(default)]
1791    pub strategy: RolloutStrategy,
1792    pub waves: Vec<Wave>,
1793}
1794
1795#[derive(
1796    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
1797)]
1798#[serde(rename_all = "lowercase")]
1799pub enum RolloutStrategy {
1800    #[default]
1801    Wave,
1802}
1803
1804#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1805pub struct Wave {
1806    pub group: String,
1807    /// humantime delay measured from the deploy's publish time. wave[0]
1808    /// typically has "0s"; subsequent waves use minutes / hours.
1809    pub delay: String,
1810}
1811
1812#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default)]
1813pub struct Target {
1814    #[serde(default)]
1815    pub groups: Vec<String>,
1816    #[serde(default)]
1817    pub pcs: Vec<String>,
1818    #[serde(default)]
1819    pub all: bool,
1820}
1821
1822impl Target {
1823    /// At least one of all / groups / pcs is set.
1824    pub fn is_specified(&self) -> bool {
1825        self.all || !self.groups.is_empty() || !self.pcs.is_empty()
1826    }
1827
1828    /// Whether a PC (its `pc_id` + group membership) falls in this target:
1829    /// `all`, or the pc is listed, or it belongs to a listed group. Used
1830    /// by the agent to scope `client.visible_to` (#816). An unspecified
1831    /// target matches nobody (callers should treat "no target" as
1832    /// "visible to all" before calling this).
1833    pub fn matches(&self, pc_id: &str, groups: &[String]) -> bool {
1834        self.all
1835            || self.pcs.iter().any(|p| p == pc_id)
1836            || self.groups.iter().any(|g| groups.contains(g))
1837    }
1838}
1839
1840#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1841pub struct Execute {
1842    pub shell: ExecuteShell,
1843    /// Inline script body. Mutually exclusive with [`script_file`]
1844    /// and [`script_object`]; exactly one of the three must be set
1845    /// (enforced by [`Execute::validate_script_source`] at the
1846    /// write-side parse boundaries — `kanade job create` and
1847    /// `POST /api/jobs`).
1848    ///
1849    /// Empty string is treated as **unset** so operators can swap
1850    /// to a `script_file:` / `script_object:` alternative just by
1851    /// commenting out the body, without having to also drop the
1852    /// `script:` key entirely.
1853    ///
1854    /// [`script_file`]: Self::script_file
1855    /// [`script_object`]: Self::script_object
1856    #[serde(default, skip_serializing_if = "Option::is_none")]
1857    pub script: Option<String>,
1858    /// Repo-local file path resolved by the operator-side CLI at
1859    /// `kanade job create` time. The CLI reads the file, slots its
1860    /// contents into `script`, and clears this field before
1861    /// POSTing — so the backend / agents never see `script_file`
1862    /// in stored manifests. SPEC §2.4.1.
1863    ///
1864    /// Resolver lands in a follow-up PR
1865    /// (yukimemi/kanade#210); today this field passes parse-time
1866    /// validation but the operator-side CLI bails with "not yet
1867    /// implemented" until the resolver ships, so manifests that
1868    /// reach the backend with `script_file` set are treated as a
1869    /// schema-bug.
1870    #[serde(default, skip_serializing_if = "Option::is_none")]
1871    pub script_file: Option<String>,
1872    /// Object Store reference (`<name>/<version>`) into the
1873    /// `scripts` bucket (`OBJECT_SCRIPTS`). Agents fetch the body
1874    /// at Execute time via `/api/script-objects/{name}/{version}`
1875    /// and cache it locally. SPEC §2.4.1.
1876    ///
1877    /// Fully wired (#210/#211): the backend resolves the digest at
1878    /// exec submission (`api::exec::resolve_script_source`), the agent
1879    /// fetches + sha-verifies + caches the body (`script_cache`), and
1880    /// `kanade script` CRUDs the store. Unlike `script_file:` (inlined
1881    /// CLI-side, git-managed), this keeps the body in versioned,
1882    /// digest-pinned object storage — the ops-managed counterpart.
1883    #[serde(default, skip_serializing_if = "Option::is_none")]
1884    pub script_object: Option<String>,
1885    /// humantime duration string (e.g. "30s", "10m"). Script-intrinsic
1886    /// — represents how long this script reasonably takes to run.
1887    pub timeout: String,
1888    /// Token + session combination the agent uses to launch the
1889    /// script (v0.21). Default = [`RunAs::System`] (Session 0,
1890    /// LocalSystem privileges, no GUI) — matches pre-v0.21 behavior.
1891    #[serde(default)]
1892    pub run_as: RunAs,
1893    /// Working directory for the spawned child (v0.21.1). When
1894    /// unset, the child inherits the agent's cwd — on Windows that
1895    /// means `%SystemRoot%\System32` for the prod service, which is
1896    /// almost never what operators actually want. Use an absolute
1897    /// path; relative paths are passed through to the OS verbatim.
1898    /// `%PROGRAMDATA%` works for `run_as: system`; for `run_as: user`
1899    /// you'd want `%USERPROFILE%` (but expansion happens in the
1900    /// shell, so write `$env:USERPROFILE` for PowerShell, or set
1901    /// it via teravars before `kanade job create`).
1902    #[serde(default, skip_serializing_if = "Option::is_none")]
1903    pub cwd: Option<String>,
1904}
1905
1906impl Execute {
1907    /// Treat an empty `script:` body as "intentionally unset". Operators
1908    /// commenting out a block-scalar tend to leave the key behind, and
1909    /// failing the validator on `script: ""` would surprise them.
1910    fn has_inline_script(&self) -> bool {
1911        matches!(&self.script, Some(s) if !s.is_empty())
1912    }
1913
1914    /// Enforce that exactly one of `script` / `script_file` /
1915    /// `script_object` is set. Called at the write-side parse
1916    /// boundaries (CLI `kanade job create` + backend
1917    /// `POST /api/jobs`) so ambiguous YAML is rejected before it
1918    /// reaches the JOBS KV. Read paths (projector, agent
1919    /// scheduler, list endpoints) skip this check — they only ever
1920    /// see what the write path already validated.
1921    pub fn validate_script_source(&self) -> Result<(), String> {
1922        let inline = self.has_inline_script();
1923        let file = self.script_file.is_some();
1924        let obj = self.script_object.is_some();
1925        let set = [inline, file, obj].into_iter().filter(|b| *b).count();
1926        match set {
1927            1 => Ok(()),
1928            0 => Err("execute: one of `script`, `script_file`, `script_object` must be set".into()),
1929            _ => Err(format!(
1930                "execute: only one of `script` / `script_file` / `script_object` may be set \
1931                 (got script={inline}, script_file={file}, script_object={obj})"
1932            )),
1933        }
1934    }
1935}
1936
1937/// Job-generic post-step hook (see [`Manifest::finalize`]). Runs after
1938/// the main `execute:` script (and the collect upload) on a clean exit,
1939/// with the step's structured result injected via an environment
1940/// variable. P1 supports an inline `script:` only — `script_file:` /
1941/// `script_object:` are follow-ups.
1942#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1943pub struct FinalizeSpec {
1944    pub shell: ExecuteShell,
1945    /// Inline script body (required; inline-only in P1).
1946    pub script: String,
1947    /// humantime duration string (e.g. `"60s"`, `"5m"`). Defaults to
1948    /// `60s` when unset.
1949    #[serde(default = "default_finalize_timeout")]
1950    pub timeout: String,
1951    /// Token + session combination, like [`Execute::run_as`]. Defaults
1952    /// to [`RunAs::System`].
1953    #[serde(default)]
1954    pub run_as: RunAs,
1955    /// Working directory for the hook child, like [`Execute::cwd`].
1956    #[serde(default, skip_serializing_if = "Option::is_none")]
1957    pub cwd: Option<String>,
1958}
1959
1960/// Default `finalize.timeout` when the operator omits it.
1961fn default_finalize_timeout() -> String {
1962    "60s".to_string()
1963}
1964
1965impl FinalizeSpec {
1966    /// Lower to the wire form forwarded onto a [`Command`]. The timeout
1967    /// parse falls back to 60s — [`Manifest::validate`] already rejects
1968    /// an unparseable value at create time, so the fire path uses a safe
1969    /// default rather than failing (mirrors
1970    /// [`CollectHint::max_size_bytes`]). A sub-second timeout floors at
1971    /// 1s for the same reason `build_command` does.
1972    pub fn lower(&self) -> FinalizeCommand {
1973        let timeout_secs = humantime::parse_duration(&self.timeout)
1974            .map(|d| d.as_secs().max(1))
1975            .unwrap_or(60);
1976        FinalizeCommand {
1977            shell: self.shell.into(),
1978            script: self.script.clone(),
1979            timeout_secs,
1980            run_as: self.run_as,
1981            cwd: self.cwd.clone(),
1982        }
1983    }
1984}
1985
1986impl Manifest {
1987    /// Cross-field semantic checks that don't fit into pure serde
1988    /// derive. Currently delegates to
1989    /// [`Execute::validate_script_source`] — see that method's
1990    /// docs for the rationale on which call sites should run this.
1991    pub fn validate(&self) -> Result<(), String> {
1992        self.execute.validate_script_source()?;
1993        // Fail CLOSED on an unrecognised execution tier. `#[serde(other)]`
1994        // turns a typo (`tier: controler`) or a future tier into
1995        // `Tier::Unknown`; without this check the controller gate would
1996        // fall back to normal endpoint dispatch, so an operator who *meant*
1997        // to confine a job to the controller tier would silently get
1998        // fleet-wide dispatch (CodeRabbit #905). Rejecting it at the write
1999        // boundary surfaces the typo at `job create`, and — since
2000        // `exec_manifest` re-validates — a hand-poked KV manifest can't slip
2001        // a controller-tier job onto endpoints either.
2002        if matches!(self.tier, Some(Tier::Unknown)) {
2003            return Err(
2004                "tier: unrecognised execution tier — use `endpoint` or `controller` \
2005                 (this is a typo, or a tier a newer kanade supports that this backend does not)"
2006                    .to_string(),
2007            );
2008        }
2009        // #vuln-roadmap: a `feed:` spec drives the global `feeds`
2010        // projection. id / item_id are stored as *values* (the `feeds`
2011        // table is fixed-schema — no identifier splicing), but blank
2012        // values are silent projection bugs: a blank id collides every
2013        // feed under "", a blank field never matches the payload array,
2014        // and an empty primary_key yields no item_id (every row dropped).
2015        // Reject them at the write boundary so `kanade job create` surfaces
2016        // the typo instead of producing an empty/garbled feed at run time.
2017        let mut seen_feed_ids: Vec<&str> = Vec::new();
2018        for spec in &self.feed {
2019            let id = spec.id.trim();
2020            if id.is_empty() {
2021                return Err("feed.id must not be empty".to_string());
2022            }
2023            if spec.field.trim().is_empty() {
2024                return Err(format!("feed '{id}' field must not be empty"));
2025            }
2026            if spec.primary_key.is_empty() {
2027                return Err(format!("feed '{id}' needs at least one primary_key field"));
2028            }
2029            if spec.primary_key.iter().any(|k| k.trim().is_empty()) {
2030                return Err(format!(
2031                    "feed '{id}' primary_key must not contain blank entries"
2032                ));
2033            }
2034            // Two specs sharing an id both target the same `feeds`
2035            // partition and would clobber each other on every run —
2036            // reject the ambiguity rather than let last-write-wins.
2037            if seen_feed_ids.contains(&id) {
2038                return Err(format!("feed id '{id}' is declared more than once"));
2039            }
2040            seen_feed_ids.push(id);
2041        }
2042        // A `feed:` job fetches external data and MUST run on the trusted
2043        // controller tier — the dispatch guard (`requires_controller`) treats
2044        // a non-empty `feed:` as implying `controller`. An explicit
2045        // `tier: endpoint` contradicts that intent; reject it rather than
2046        // silently overriding, so the operator can't believe a feed runs on
2047        // endpoints. Omitting `tier:` (the default) is fine — the implication
2048        // confines it; `tier: controller` is the redundant-but-explicit form.
2049        if !self.feed.is_empty() && matches!(self.tier, Some(Tier::Endpoint)) {
2050            return Err(
2051                "feed: requires the controller tier — remove `tier: endpoint` (a feed: job \
2052                 fetches external data and is confined to the controller_group)"
2053                    .to_string(),
2054            );
2055        }
2056        // A present-but-empty finalize script is an invisible no-op
2057        // (the hook would run an empty body); reject it at the write
2058        // boundary. Inline-only in P1, so `script` is the sole source.
2059        if let Some(finalize) = &self.finalize {
2060            if finalize.script.trim().is_empty() {
2061                return Err("finalize.script must not be empty".to_string());
2062            }
2063            // Reject an unparseable timeout at the write boundary so the
2064            // operator sees the error at `job create` rather than getting
2065            // a silent fire-time fallback (`FinalizeSpec::lower` floors to
2066            // 60s, which would otherwise mask a typo).
2067            if humantime::parse_duration(&finalize.timeout).is_err() {
2068                return Err(format!(
2069                    "finalize.timeout '{}' is not a valid duration",
2070                    finalize.timeout
2071                ));
2072            }
2073            // Disallow cmd for finalize: the agent injects the result JSON
2074            // into the hook's environment, and cmd.exe quoting doesn't
2075            // nest — JSON's `"` plus shell metacharacters in a collected
2076            // path/key could break out into command injection at the
2077            // agent's (often LocalSystem) privilege. PowerShell's
2078            // single-quote escaping is safe, and finalize hooks are
2079            // PowerShell by convention anyway.
2080            if finalize.shell == ExecuteShell::Cmd {
2081                return Err(
2082                    "finalize.shell: cmd is not supported for finalize hooks (shell-injection \
2083                     risk when the result JSON is injected into the environment); use powershell"
2084                        .to_string(),
2085                );
2086            }
2087        }
2088        // Stdout-format compatibility (#821). `inventory:` / `check:` /
2089        // `collect:` now COMPOSE: each reads its own `#KANADE-<KIND>-
2090        // BEGIN/END`-fenced JSON block from stdout, so a single job can
2091        // project inventory facts, drive a Health-tab check, AND collect
2092        // files in one run. (A single-hint job may still skip the fence;
2093        // a multi-hint job must fence each block.)
2094        //
2095        // `emit:` remains the exception — its stdout is line-delimited
2096        // NDJSON consumed whole and then omitted from the result — so it
2097        // can't share stdout with any fenced hint. `feed:` is another fenced
2098        // stdout consumer (`#KANADE-FEED`), so it belongs in this exclusion
2099        // too: with `emit:` present the projector never sees the feed's fence
2100        // (CodeRabbit).
2101        if self.emit.is_some()
2102            && (self.inventory.is_some()
2103                || self.check.is_some()
2104                || self.collect.is_some()
2105                || !self.feed.is_empty())
2106        {
2107            return Err(
2108                "`emit:` is incompatible with `inventory:` / `check:` / `collect:` / `feed:` — \
2109                 emit's stdout is NDJSON timeline events (consumed whole and omitted from the \
2110                 result), while the others read fenced JSON blocks from stdout"
2111                    .to_string(),
2112            );
2113        }
2114        // A check's `name` is the Health-tab row id (React key); the
2115        // field names tell the agent where to read status/detail.
2116        // An empty value is an invisible runtime bug, and the serde
2117        // defaults don't guard an operator who writes `status_field:
2118        // ""` explicitly — reject all three here.
2119        if let Some(check) = &self.check {
2120            for (label, value) in [
2121                ("check.name", &check.name),
2122                ("check.status_field", &check.status_field),
2123                ("check.detail_field", &check.detail_field),
2124            ] {
2125                if value.trim().is_empty() {
2126                    return Err(format!("{label} must not be empty"));
2127                }
2128            }
2129            // A present-but-blank `troubleshoot` is a broken
2130            // remediation job id (the "修復する" button would target
2131            // an empty manifest id) — reject it too.
2132            if let Some(troubleshoot) = &check.troubleshoot {
2133                if troubleshoot.trim().is_empty() {
2134                    return Err("check.troubleshoot must not be empty when set".to_string());
2135                }
2136            }
2137            // A present-but-blank `label` would render an empty row
2138            // title on the Health tab / Compliance page — reject it so
2139            // the slug fallback only ever kicks in when label is absent.
2140            if let Some(label) = &check.label {
2141                if label.trim().is_empty() {
2142                    return Err("check.label must not be empty when set".to_string());
2143                }
2144            }
2145            if let Some(alert) = &check.alert {
2146                // An alert that names no recipient is a silent no-op.
2147                if !alert.notify_user && alert.notify_groups.is_empty() {
2148                    return Err("check.alert must set notify_user and/or notify_groups".to_string());
2149                }
2150                if alert.title.trim().is_empty() {
2151                    return Err("check.alert.title must not be empty".to_string());
2152                }
2153                // `on: []` would never fire; an empty group name resolves to
2154                // a malformed `notifications.group.` subject.
2155                if alert.on.is_empty() {
2156                    return Err("check.alert.on must list at least one status".to_string());
2157                }
2158                if alert.notify_groups.iter().any(|g| g.trim().is_empty()) {
2159                    return Err("check.alert.notify_groups must not contain blanks".to_string());
2160                }
2161                // Email is addressed via group_contacts (group → email), so
2162                // there must be a group to map. notify_user has no email.
2163                if alert.email && alert.notify_groups.is_empty() {
2164                    return Err(
2165                        "check.alert.email requires notify_groups (email is addressed per group, not per user)"
2166                            .to_string(),
2167                    );
2168                }
2169                // The alert rides the `check_status` projection, which only
2170                // runs for `fleet: true`.
2171                if !check.fleet {
2172                    return Err(
2173                        "check.alert requires fleet: true (the alert rides the compliance projection)"
2174                            .to_string(),
2175                    );
2176                }
2177            }
2178        }
2179        // #291: a `client:` job is rendered in the Client App's
2180        // catalog (`jobs.list` → `jobs.execute`). serde already makes
2181        // `name` + `category` required at parse time; the only gap is
2182        // a present-but-blank `name`, which would render an empty row
2183        // title — reject it like the other display-id fields.
2184        if let Some(client) = &self.client {
2185            if client.name.trim().is_empty() {
2186                return Err("client.name must not be empty".to_string());
2187            }
2188            // #792: category is a free-form key now, so a blank one would
2189            // group the job under an empty tab — reject it like `name`.
2190            if client.category.trim().is_empty() {
2191                return Err("client.category must not be empty".to_string());
2192            }
2193            // Optional display fields, when present, must be
2194            // meaningful: a blank `description` renders an empty
2195            // subtitle and a blank `icon` is a dangling lucide name.
2196            // Same present-but-blank guard the `check:` block applies
2197            // to its optional `troubleshoot` id.
2198            for (label, value) in [
2199                ("client.description", &client.description),
2200                ("client.icon", &client.icon),
2201                ("client.category_label", &client.category_label),
2202                ("client.category_icon", &client.category_icon),
2203            ] {
2204                if let Some(v) = value {
2205                    if v.trim().is_empty() {
2206                        return Err(format!("{label} must not be empty when set"));
2207                    }
2208                }
2209            }
2210            // #816: a present-but-empty `visible_to` (no all/groups/pcs)
2211            // would hide the job from everyone in the Client App — almost
2212            // certainly a mistake. Require at least one selector; omit the
2213            // whole block to mean "visible to all".
2214            if let Some(t) = &client.visible_to {
2215                if !t.is_specified() {
2216                    return Err(
2217                        "client.visible_to must set at least one of all / groups / pcs (omit it for all PCs)"
2218                            .to_string(),
2219                    );
2220                }
2221            }
2222            // show_when: a dynamic display gate keyed on a check result. A
2223            // malformed check slug matches nothing and an empty status list
2224            // matches nothing — both would silently hide the job forever,
2225            // so reject them at create time rather than at a confused
2226            // "why isn't my job showing?" later. The slug must be a clean
2227            // resource id (same charset checks/jobs use): a typo with spaces
2228            // or punctuation can never match a real check name, so catch it
2229            // here instead of failing closed at runtime. (Whether the slug
2230            // names a check that actually EXISTS can't be checked here —
2231            // checks are keyed by name across manifests — so a valid-but-
2232            // unknown slug stays a runtime miss = hidden, the documented
2233            // fail-closed behavior.)
2234            if let Some(sw) = &client.show_when {
2235                if !is_valid_resource_id(sw.check.trim()) {
2236                    return Err(
2237                        "client.show_when.check must be a non-empty check slug ([A-Za-z0-9._-])"
2238                            .to_string(),
2239                    );
2240                }
2241                if sw.is.is_empty() {
2242                    return Err(
2243                        "client.show_when.is must list at least one check status".to_string()
2244                    );
2245                }
2246            }
2247        }
2248        // #219: a `collect:` job's `name` heads the bundle on the SPA
2249        // Collect page (and the Client App row when paired with
2250        // `client:`), `files_field` tells the agent where to read the
2251        // path list, and `max_size` must be a parseable size so a typo
2252        // is caught at create time rather than silently capping the
2253        // bundle at the default on the fire path.
2254        if let Some(collect) = &self.collect {
2255            if collect.name.trim().is_empty() {
2256                return Err("collect.name must not be empty".to_string());
2257            }
2258            if collect.files_field.trim().is_empty() {
2259                return Err("collect.files_field must not be empty".to_string());
2260            }
2261            if let Some(description) = &collect.description {
2262                if description.trim().is_empty() {
2263                    return Err("collect.description must not be empty when set".to_string());
2264                }
2265            }
2266            if let Some(max_size) = &collect.max_size {
2267                parse_size_bytes(max_size).map_err(|e| format!("collect.max_size: {e}"))?;
2268            }
2269        }
2270        // #720/#743: `aggregate:` is a pure read-spec (it never touches
2271        // stdout and is never sent to an agent), so it composes with every
2272        // other hint. The per-widget rules are shared with the standalone
2273        // `view` resource — see [`validate_aggregate_widgets`].
2274        if let Some(widgets) = &self.aggregate {
2275            validate_aggregate_widgets(widgets, "aggregate")?;
2276        }
2277        // A blank / whitespace-only tag is an invisible operator typo
2278        // that would render an empty filter chip on the Jobs page —
2279        // reject it like the other present-but-blank display fields.
2280        for tag in &self.tags {
2281            if tag.trim().is_empty() {
2282                return Err("tags must not contain empty entries".to_string());
2283            }
2284        }
2285        Ok(())
2286    }
2287}
2288
2289#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
2290#[serde(rename_all = "lowercase")]
2291pub enum ExecuteShell {
2292    Powershell,
2293    Cmd,
2294}
2295
2296impl From<ExecuteShell> for Shell {
2297    fn from(s: ExecuteShell) -> Self {
2298        match s {
2299            ExecuteShell::Powershell => Shell::Powershell,
2300            ExecuteShell::Cmd => Shell::Cmd,
2301        }
2302    }
2303}
2304
2305#[cfg(test)]
2306mod tests {
2307    use super::*;
2308
2309    #[test]
2310    fn inventory_payload_extracts_fenced_block() {
2311        // Readable message + fenced JSON → only the JSON, trimmed.
2312        let stdout = "Wi-Fi 設定を適用しました。\n\
2313            #KANADE-INVENTORY-BEGIN\n\
2314            {\"applied\": true}\n\
2315            #KANADE-INVENTORY-END\n";
2316        assert_eq!(inventory_payload(stdout), "{\"applied\": true}");
2317    }
2318
2319    #[test]
2320    fn inventory_payload_falls_back_to_whole_stdout() {
2321        // No fence (a plain inventory job) → whole stdout, trimmed.
2322        assert_eq!(
2323            inventory_payload("  {\"ram_gb\": 16}\n"),
2324            "{\"ram_gb\": 16}"
2325        );
2326    }
2327
2328    #[test]
2329    fn inventory_payload_handles_unterminated_fence() {
2330        // Closing marker missing (e.g. truncated) → everything after the
2331        // opener, trimmed.
2332        let stdout = "msg\n#KANADE-INVENTORY-BEGIN\n{\"a\": 1}";
2333        assert_eq!(inventory_payload(stdout), "{\"a\": 1}");
2334    }
2335
2336    #[test]
2337    fn inventory_payload_ignores_mid_line_sentinel() {
2338        // The marker echoed mid-line (not at a line start) must NOT be
2339        // treated as a fence — fall back to the whole stdout.
2340        let stdout = "see #KANADE-INVENTORY-BEGIN in the docs\nnot json";
2341        assert_eq!(inventory_payload(stdout), stdout.trim());
2342    }
2343
2344    #[test]
2345    fn fenced_payload_extracts_each_hint_block_independently() {
2346        // #821: one stdout carrying a user message + all three fenced
2347        // blocks — every consumer pulls only its own.
2348        let stdout = "\
2349done!
2350#KANADE-INVENTORY-BEGIN
2351{\"os\":\"win\"}
2352#KANADE-INVENTORY-END
2353#KANADE-CHECK-BEGIN
2354{\"status\":\"ok\"}
2355#KANADE-CHECK-END
2356#KANADE-COLLECT-BEGIN
2357{\"files\":[\"a\"]}
2358#KANADE-COLLECT-END
2359";
2360        assert_eq!(
2361            fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
2362            "{\"os\":\"win\"}"
2363        );
2364        assert_eq!(
2365            fenced_payload(stdout, CHECK_BLOCK_BEGIN, CHECK_BLOCK_END),
2366            "{\"status\":\"ok\"}"
2367        );
2368        assert_eq!(
2369            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2370            "{\"files\":[\"a\"]}"
2371        );
2372    }
2373
2374    #[test]
2375    fn fenced_payload_falls_back_to_whole_stdout_without_fence() {
2376        // A single-hint job needs no fence — the whole (trimmed) stdout is
2377        // the payload.
2378        let stdout = "  {\"files\":[\"a\"]}  ";
2379        assert_eq!(
2380            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2381            "{\"files\":[\"a\"]}"
2382        );
2383    }
2384
2385    #[test]
2386    fn fenced_payload_returns_empty_when_other_fences_present_but_mine_missing() {
2387        // Multi-hint output (inventory + check fenced) but the COLLECT
2388        // fence is missing — collect must NOT fall back to the whole
2389        // stdout (which holds the inventory/check blocks) and cross-parse
2390        // a sibling block; it gets "" → its JSON parse fails → no data.
2391        let stdout = "\
2392#KANADE-INVENTORY-BEGIN
2393{\"os\":\"win\"}
2394#KANADE-INVENTORY-END
2395#KANADE-CHECK-BEGIN
2396{\"status\":\"ok\"}
2397#KANADE-CHECK-END
2398";
2399        assert_eq!(
2400            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2401            ""
2402        );
2403        // ...while the hints that DID fence still extract correctly.
2404        assert_eq!(
2405            fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
2406            "{\"os\":\"win\"}"
2407        );
2408    }
2409
2410    /// The example check-job + schedule YAMLs shipped under `configs/`
2411    /// must stay valid as the schema evolves (#290 PR-C). `include_str!`
2412    /// pins them at compile time so a breaking edit fails `cargo test`
2413    /// rather than only `kanade job create` at deploy time.
2414    #[test]
2415    fn example_check_job_yamls_parse_and_validate() {
2416        let jobs = [
2417            (
2418                "check-bitlocker",
2419                include_str!("../../../configs/jobs/check-bitlocker.yaml"),
2420            ),
2421            (
2422                "check-av-signature",
2423                include_str!("../../../configs/jobs/check-av-signature.yaml"),
2424            ),
2425            (
2426                "check-cert-expiry",
2427                include_str!("../../../configs/jobs/check-cert-expiry.yaml"),
2428            ),
2429            (
2430                "check-disk-space",
2431                include_str!("../../../configs/jobs/check-disk-space.yaml"),
2432            ),
2433            (
2434                "check-pending-reboot",
2435                include_str!("../../../configs/jobs/check-pending-reboot.yaml"),
2436            ),
2437            (
2438                "check-defender-rtp",
2439                include_str!("../../../configs/jobs/check-defender-rtp.yaml"),
2440            ),
2441            (
2442                "check-firewall",
2443                include_str!("../../../configs/jobs/check-firewall.yaml"),
2444            ),
2445        ];
2446        for (name, yaml) in jobs {
2447            let m: Manifest =
2448                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} parse: {e}"));
2449            m.validate()
2450                .unwrap_or_else(|e| panic!("{name} validate: {e}"));
2451            let check = m
2452                .check
2453                .as_ref()
2454                .unwrap_or_else(|| panic!("{name} must carry a check: hint"));
2455            assert!(!check.name.trim().is_empty(), "{name} check.name empty");
2456            // These examples all read admin-only WMI / registry / netsh
2457            // state, so they run_as system. NOTE: that's a property of
2458            // these particular checks, NOT of the `check:` contract — a
2459            // check probing user-session state could run_as user.
2460            assert_eq!(
2461                m.execute.run_as,
2462                RunAs::System,
2463                "{name} should run_as system"
2464            );
2465        }
2466    }
2467
2468    /// The example user-invokable job YAMLs (#291) shipped under
2469    /// `configs/jobs/` must stay valid as the `client:` schema
2470    /// evolves. `include_str!` pins them at compile time so a breaking
2471    /// edit fails `cargo test`, not `kanade job create` at deploy.
2472    #[test]
2473    fn example_client_job_yamls_parse_and_validate() {
2474        let jobs = [
2475            (
2476                "fix-teams-cache",
2477                "troubleshoot",
2478                include_str!("../../../configs/jobs/fix-teams-cache.yaml"),
2479            ),
2480            (
2481                "chrome-update",
2482                "software_update",
2483                include_str!("../../../configs/jobs/chrome-update.yaml"),
2484            ),
2485            (
2486                "install-slack",
2487                "catalog",
2488                include_str!("../../../configs/jobs/install-slack.yaml"),
2489            ),
2490            (
2491                "fix-defender-rtp",
2492                "troubleshoot",
2493                include_str!("../../../configs/jobs/fix-defender-rtp.yaml"),
2494            ),
2495            // #792 custom category ("settings") + #809 message/inventory.
2496            (
2497                "example-power-plan",
2498                "settings",
2499                include_str!("../../../configs/jobs/example-power-plan.yaml"),
2500            ),
2501            // #792: diagnostics moved to its own "support" tab.
2502            (
2503                "collect-diagnostics",
2504                "support",
2505                include_str!("../../../configs/jobs/collect-diagnostics.yaml"),
2506            ),
2507        ];
2508        for (id, category, yaml) in jobs {
2509            let m: Manifest =
2510                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
2511            m.validate()
2512                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
2513            assert_eq!(m.id, id, "{id} id mismatch");
2514            let client = m
2515                .client
2516                .as_ref()
2517                .unwrap_or_else(|| panic!("{id} must carry a client: block"));
2518            assert!(!client.name.trim().is_empty(), "{id} client.name empty");
2519            assert_eq!(client.category, category, "{id} category");
2520        }
2521    }
2522
2523    /// #219: the shipped `collect:` example must stay valid as the
2524    /// schema evolves. `include_str!` pins it at compile time so a
2525    /// breaking edit (or a YAML typo in the PowerShell block) fails
2526    /// `cargo test` rather than `kanade job create` at deploy. It carries
2527    /// both `collect:` and `client:` (end-user-triggerable), which must
2528    /// compose.
2529    #[test]
2530    fn example_collect_job_yaml_parses_and_validates() {
2531        let yaml = include_str!("../../../configs/jobs/collect-diagnostics.yaml");
2532        let m: Manifest = serde_yaml::from_str(yaml).expect("collect-diagnostics parse");
2533        m.validate().expect("collect-diagnostics validate");
2534        assert_eq!(m.id, "collect-diagnostics");
2535        let collect = m.collect.as_ref().expect("collect: block present");
2536        assert!(!collect.name.trim().is_empty());
2537        assert_eq!(collect.files_field, "files");
2538        assert_eq!(collect.max_size_bytes(), 50_000_000);
2539        // collect + client compose — the Client App can trigger it.
2540        assert!(
2541            m.client.is_some(),
2542            "collect-diagnostics also carries client:"
2543        );
2544    }
2545
2546    /// The `emit: { type: events }` collector jobs under
2547    /// `configs/jobs/` feed the obs_events timeline. `include_str!`
2548    /// pins them at compile time so a breaking edit (e.g. an `emit:`
2549    /// paired with `check:`/`inventory:`, a bad watermark field, or a
2550    /// YAML typo in the PowerShell block) fails `cargo test` rather
2551    /// than `kanade job create` at deploy. Every one must carry an
2552    /// `emit.type=events` block and NO check/inventory (validate()
2553    /// rejects the pairing).
2554    #[test]
2555    fn example_event_collector_job_yamls_parse_and_validate() {
2556        let jobs = [
2557            // collect-winlog-events was retired in #841 PR2 — the scheduled
2558            // human-session / power timeline is now read natively by the
2559            // agent (kanade-agent `winlog` module via EvtQuery), no
2560            // PowerShell job. collect-winlog-logons-all stays as the
2561            // on-demand forensic all-token-logons companion.
2562            (
2563                "collect-winlog-logons-all",
2564                include_str!("../../../configs/jobs/collect-winlog-logons-all.yaml"),
2565            ),
2566            (
2567                "collect-wlan-events",
2568                include_str!("../../../configs/jobs/collect-wlan-events.yaml"),
2569            ),
2570        ];
2571        for (id, yaml) in jobs {
2572            // Strict parse so an unknown-key typo in these fixtures fails
2573            // here (not silently at deploy) — the runtime Manifest is
2574            // unknown-key-tolerant, so the lenient serde_yaml::from_str
2575            // wouldn't catch fixture drift (CodeRabbit #689).
2576            let m: Manifest =
2577                crate::strict::from_yaml_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
2578            m.validate()
2579                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
2580            assert_eq!(m.id, id, "{id} id mismatch");
2581            let emit = m
2582                .emit
2583                .as_ref()
2584                .unwrap_or_else(|| panic!("{id} must carry an emit: block"));
2585            assert_eq!(emit.kind, EmitKind::Events, "{id} emit.type");
2586            assert!(
2587                m.check.is_none() && m.inventory.is_none(),
2588                "{id}: emit jobs must not pair with check/inventory"
2589            );
2590        }
2591    }
2592
2593    /// The `inventory:` snapshot jobs under `configs/jobs/` project
2594    /// facts into `inventory_facts` + exploded tables. `include_str!`
2595    /// pins them at compile time so a breaking edit (bad explode
2596    /// schema, a YAML typo in the PowerShell block, an `inventory:`
2597    /// accidentally paired with `emit:`) fails `cargo test` rather
2598    /// than the projector at deploy. Each must carry an `inventory:`
2599    /// block and NO emit (validate() rejects the pairing).
2600    #[test]
2601    fn example_inventory_job_yamls_parse_and_validate() {
2602        let jobs = [
2603            (
2604                "inventory-hw",
2605                include_str!("../../../configs/jobs/inventory-hw.yaml"),
2606            ),
2607            (
2608                "inventory-sw",
2609                include_str!("../../../configs/jobs/inventory-sw.yaml"),
2610            ),
2611            (
2612                "inventory-driver",
2613                include_str!("../../../configs/jobs/inventory-driver.yaml"),
2614            ),
2615        ];
2616        for (id, yaml) in jobs {
2617            let m: Manifest =
2618                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
2619            m.validate()
2620                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
2621            assert_eq!(m.id, id, "{id} id mismatch");
2622            assert!(m.inventory.is_some(), "{id} must carry an inventory: block");
2623            assert!(m.emit.is_none(), "{id}: inventory jobs must not set emit:");
2624        }
2625    }
2626
2627    #[test]
2628    fn example_check_schedule_yamls_parse_and_validate() {
2629        let schedules = [
2630            (
2631                "check-bitlocker",
2632                include_str!("../../../configs/schedules/check-bitlocker.yaml"),
2633            ),
2634            (
2635                "check-av-signature",
2636                include_str!("../../../configs/schedules/check-av-signature.yaml"),
2637            ),
2638            (
2639                "check-cert-expiry",
2640                include_str!("../../../configs/schedules/check-cert-expiry.yaml"),
2641            ),
2642            (
2643                "check-disk-space",
2644                include_str!("../../../configs/schedules/check-disk-space.yaml"),
2645            ),
2646            (
2647                "check-pending-reboot",
2648                include_str!("../../../configs/schedules/check-pending-reboot.yaml"),
2649            ),
2650            (
2651                "check-defender-rtp",
2652                include_str!("../../../configs/schedules/check-defender-rtp.yaml"),
2653            ),
2654            (
2655                "check-firewall",
2656                include_str!("../../../configs/schedules/check-firewall.yaml"),
2657            ),
2658        ];
2659        for (name, yaml) in schedules {
2660            let s: Schedule =
2661                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
2662            s.validate()
2663                .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
2664            assert_eq!(s.job_id, name, "{name} schedule must reference its job");
2665        }
2666    }
2667
2668    /// Inventory schedule wrappers (`per_pc` cadence) must stay valid
2669    /// alongside the schedule schema. `include_str!` pins them so a
2670    /// breaking edit fails `cargo test`, not `kanade schedule create`.
2671    #[test]
2672    fn example_inventory_schedule_yamls_parse_and_validate() {
2673        let schedules = [
2674            (
2675                "inventory-hw",
2676                include_str!("../../../configs/schedules/inventory-hw.yaml"),
2677            ),
2678            (
2679                "inventory-sw",
2680                include_str!("../../../configs/schedules/inventory-sw.yaml"),
2681            ),
2682            (
2683                "inventory-driver",
2684                include_str!("../../../configs/schedules/inventory-driver.yaml"),
2685            ),
2686        ];
2687        for (name, yaml) in schedules {
2688            let s: Schedule =
2689                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
2690            s.validate()
2691                .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
2692            assert_eq!(s.job_id, name, "{name} schedule must reference its job");
2693        }
2694    }
2695
2696    #[test]
2697    fn target_is_specified_requires_at_least_one_field() {
2698        let empty = Target::default();
2699        assert!(!empty.is_specified());
2700
2701        let with_all = Target {
2702            all: true,
2703            ..Target::default()
2704        };
2705        assert!(with_all.is_specified());
2706
2707        let with_groups = Target {
2708            groups: vec!["canary".into()],
2709            ..Target::default()
2710        };
2711        assert!(with_groups.is_specified());
2712
2713        let with_pcs = Target {
2714            pcs: vec!["pc-01".into()],
2715            ..Target::default()
2716        };
2717        assert!(with_pcs.is_specified());
2718    }
2719
2720    #[test]
2721    fn manifest_deserialises_minimal_yaml() {
2722        // Matches jobs/echo-test.yaml. v0.18: no target/rollout/jitter
2723        // — those live on the schedule / exec request now.
2724        let yaml = r#"
2725id: echo-test
2726version: 0.0.1
2727execute:
2728  shell: powershell
2729  script: "echo 'kanade'"
2730  timeout: 30s
2731"#;
2732        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2733        assert_eq!(m.id, "echo-test");
2734        assert_eq!(m.version, "0.0.1");
2735        assert!(matches!(m.execute.shell, ExecuteShell::Powershell));
2736        assert_eq!(
2737            m.execute.script.as_deref().map(str::trim),
2738            Some("echo 'kanade'")
2739        );
2740        assert!(m.execute.script_file.is_none());
2741        assert!(m.execute.script_object.is_none());
2742        assert_eq!(m.execute.timeout, "30s");
2743        assert!(!m.require_approval);
2744        m.validate()
2745            .expect("inline-script manifest passes validation");
2746    }
2747
2748    #[test]
2749    fn manifest_parses_check_job_and_validates() {
2750        // An operator-defined health check (#290): a `check:` hint +
2751        // a PowerShell script that prints {status, detail}.
2752        let yaml = r#"
2753id: check-bitlocker
2754version: 0.1.0
2755execute:
2756  shell: powershell
2757  run_as: system
2758  timeout: 15s
2759  script: |
2760    [pscustomobject]@{ status = 'ok'; detail = 'all volumes protected' } | ConvertTo-Json -Compress
2761check:
2762  name: bitlocker
2763  troubleshoot: fix-bitlocker
2764"#;
2765        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2766        let check = m.check.as_ref().expect("check hint present");
2767        assert_eq!(check.name, "bitlocker");
2768        assert_eq!(check.troubleshoot.as_deref(), Some("fix-bitlocker"));
2769        // Field names default to the conventional "status" / "detail".
2770        assert_eq!(check.status_field, "status");
2771        assert_eq!(check.detail_field, "detail");
2772        assert!(m.inventory.is_none() && m.emit.is_none());
2773        m.validate().expect("check-only manifest passes validation");
2774    }
2775
2776    #[test]
2777    fn manifest_check_defaults_and_custom_fields() {
2778        // Minimal: only `name`; status/detail fields default.
2779        let m: Manifest = serde_yaml::from_str(
2780            r#"
2781id: check-disk
2782version: 0.1.0
2783execute:
2784  shell: powershell
2785  script: "[pscustomobject]@{ status = 'ok' } | ConvertTo-Json -Compress"
2786  timeout: 10s
2787check:
2788  name: disk_free
2789"#,
2790        )
2791        .expect("parse");
2792        let c = m.check.as_ref().unwrap();
2793        assert_eq!(c.name, "disk_free");
2794        assert_eq!(c.status_field, "status");
2795        assert_eq!(c.detail_field, "detail");
2796        assert!(c.troubleshoot.is_none());
2797        m.validate().expect("validates");
2798
2799        // The operator can point status/detail at any field of their
2800        // free-form inventory object.
2801        let m2: Manifest = serde_yaml::from_str(
2802            r#"
2803id: check-custom
2804version: 0.1.0
2805execute:
2806  shell: powershell
2807  script: "echo x"
2808  timeout: 10s
2809check:
2810  name: patch_level
2811  status_field: compliance
2812  detail_field: summary
2813"#,
2814        )
2815        .expect("parse");
2816        let c2 = m2.check.as_ref().unwrap();
2817        assert_eq!(c2.status_field, "compliance");
2818        assert_eq!(c2.detail_field, "summary");
2819    }
2820
2821    #[test]
2822    fn manifest_allows_check_composed_with_inventory() {
2823        // `check:` + `inventory:` COMPOSE on the same stdout object:
2824        // status/detail → Health tab, the rest → SPA projection +
2825        // explode sub-tables. Must pass validation.
2826        let yaml = r#"
2827id: check-bitlocker-detailed
2828version: 0.1.0
2829execute:
2830  shell: powershell
2831  script: "echo x"
2832  timeout: 10s
2833check:
2834  name: bitlocker
2835inventory:
2836  display:
2837    - { field: status, label: Status }
2838"#;
2839        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2840        assert!(m.check.is_some() && m.inventory.is_some());
2841        m.validate().expect("check + inventory compose");
2842    }
2843
2844    #[test]
2845    fn manifest_parses_collect_job_and_validates() {
2846        // #219: a `collect:` hint + a script that lists files on stdout.
2847        let yaml = r#"
2848id: collect-diagnostics
2849version: 0.1.0
2850execute:
2851  shell: powershell
2852  run_as: system
2853  timeout: 120s
2854  script: |
2855    @{ files = @("$env:KANADE_COLLECT_DIR/system.csv") } | ConvertTo-Json
2856collect:
2857  name: "Full diagnostics"
2858  description: "Event logs + process"
2859  max_size: 50MB
2860"#;
2861        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2862        let c = m.collect.as_ref().expect("collect hint present");
2863        assert_eq!(c.name, "Full diagnostics");
2864        assert_eq!(c.files_field, "files"); // default
2865        assert_eq!(c.max_size_bytes(), 50_000_000);
2866        m.validate().expect("collect-only manifest validates");
2867    }
2868
2869    #[test]
2870    fn manifest_finalize_powershell_validates_and_lowers() {
2871        let yaml = r#"
2872id: collect-fin
2873version: 0.1.0
2874execute:
2875  shell: powershell
2876  timeout: 120s
2877  script: |
2878    @{ files = @() } | ConvertTo-Json
2879collect:
2880  name: "diag"
2881  max_size: 50MB
2882finalize:
2883  shell: powershell
2884  timeout: 30s
2885  run_as: system
2886  script: |
2887    Write-Output "cleanup"
2888"#;
2889        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2890        m.validate().expect("powershell finalize validates");
2891        let lowered = m.finalize.as_ref().expect("finalize present").lower();
2892        assert_eq!(lowered.timeout_secs, 30);
2893        assert!(matches!(lowered.shell, Shell::Powershell));
2894    }
2895
2896    #[test]
2897    fn manifest_finalize_rejects_cmd_shell() {
2898        // cmd finalize is an injection risk (the agent injects JSON into
2899        // the hook's env; cmd.exe quoting doesn't nest) — validate must
2900        // reject it.
2901        let yaml = r#"
2902id: collect-fin-cmd
2903version: 0.1.0
2904execute:
2905  shell: powershell
2906  timeout: 120s
2907  script: |
2908    @{ files = @() } | ConvertTo-Json
2909finalize:
2910  shell: cmd
2911  script: |
2912    echo hi
2913"#;
2914        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2915        let err = m.validate().expect_err("cmd finalize rejected");
2916        assert!(err.contains("finalize.shell"), "got: {err}");
2917    }
2918
2919    #[test]
2920    fn manifest_finalize_rejects_empty_script() {
2921        let yaml = r#"
2922id: collect-fin-empty
2923version: 0.1.0
2924execute:
2925  shell: powershell
2926  timeout: 120s
2927  script: |
2928    @{ files = @() } | ConvertTo-Json
2929finalize:
2930  shell: powershell
2931  script: "   "
2932"#;
2933        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2934        let err = m.validate().expect_err("empty finalize script rejected");
2935        assert!(err.contains("finalize.script"), "got: {err}");
2936    }
2937
2938    #[test]
2939    fn manifest_collect_max_size_defaults_when_unset() {
2940        let m: Manifest = serde_yaml::from_str(
2941            r#"
2942id: collect-min
2943version: 0.1.0
2944execute:
2945  shell: powershell
2946  script: "echo x"
2947  timeout: 10s
2948collect:
2949  name: minimal
2950"#,
2951        )
2952        .expect("parse");
2953        let c = m.collect.as_ref().unwrap();
2954        assert!(c.max_size.is_none());
2955        assert_eq!(c.max_size_bytes(), DEFAULT_COLLECT_MAX_SIZE);
2956        m.validate().expect("validates");
2957    }
2958
2959    #[test]
2960    fn manifest_allows_collect_with_client() {
2961        // collect composes with client (client doesn't touch stdout):
2962        // an end user can trigger a collection from the Client App.
2963        let yaml = r#"
2964id: collect-diag-client
2965version: 0.1.0
2966execute:
2967  shell: powershell
2968  script: "echo x"
2969  timeout: 10s
2970collect:
2971  name: diagnostics
2972client:
2973  name: "Send diagnostics"
2974  category: troubleshoot
2975"#;
2976        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2977        assert!(m.collect.is_some() && m.client.is_some());
2978        m.validate().expect("collect + client compose");
2979    }
2980
2981    #[test]
2982    fn manifest_allows_inventory_check_collect_coexistence() {
2983        // #821: the three fenced hints now COMPOSE — each reads its own
2984        // `#KANADE-<KIND>` stdout block, so one job can do all three.
2985        let yaml = r#"
2986id: multi-hint
2987version: 0.1.0
2988execute:
2989  shell: powershell
2990  script: "echo x"
2991  timeout: 10s
2992inventory:
2993  display:
2994    - { field: status, label: Status }
2995check:
2996  name: health
2997collect:
2998  name: diag
2999"#;
3000        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3001        m.validate()
3002            .expect("inventory + check + collect coexist after #821");
3003    }
3004
3005    #[test]
3006    fn manifest_rejects_emit_combined_with_fenced_hints() {
3007        // `emit:` consumes stdout as NDJSON (and blanks it), so it still
3008        // can't share with any fenced hint — inventory, check, OR collect.
3009        for extra in [
3010            "inventory:\n  display:\n    - { field: s, label: S }\n",
3011            "check:\n  name: health\n",
3012            "collect:\n  name: diag\n",
3013        ] {
3014            let yaml = format!(
3015                "id: bad-emit-mix\nversion: 0.1.0\nexecute:\n  shell: powershell\n  \
3016                 script: \"echo x\"\n  timeout: 10s\nemit:\n  type: events\n{extra}"
3017            );
3018            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
3019            let err = m
3020                .validate()
3021                .expect_err("emit + fenced hint must be rejected");
3022            assert!(err.contains("emit"), "error mentions emit: {err}");
3023        }
3024    }
3025
3026    #[test]
3027    fn manifest_rejects_collect_empty_name_and_bad_size() {
3028        let empty_name: Manifest = serde_yaml::from_str(
3029            r#"
3030id: c
3031version: 0.1.0
3032execute: { shell: powershell, script: "echo x", timeout: 10s }
3033collect: { name: "  " }
3034"#,
3035        )
3036        .expect("parse");
3037        assert!(
3038            empty_name.validate().is_err(),
3039            "blank collect.name rejected"
3040        );
3041
3042        let bad_size: Manifest = serde_yaml::from_str(
3043            r#"
3044id: c
3045version: 0.1.0
3046execute: { shell: powershell, script: "echo x", timeout: 10s }
3047collect: { name: diag, max_size: "50 quux" }
3048"#,
3049        )
3050        .expect("parse");
3051        let err = bad_size.validate().expect_err("bad max_size rejected");
3052        assert!(err.contains("max_size"), "error mentions max_size: {err}");
3053    }
3054
3055    #[test]
3056    fn parse_size_bytes_units() {
3057        assert_eq!(parse_size_bytes("1024").unwrap(), 1024);
3058        assert_eq!(parse_size_bytes("1B").unwrap(), 1);
3059        assert_eq!(parse_size_bytes("50MB").unwrap(), 50_000_000);
3060        assert_eq!(parse_size_bytes("500 KB").unwrap(), 500_000);
3061        assert_eq!(parse_size_bytes("1GiB").unwrap(), 1024 * 1024 * 1024);
3062        assert_eq!(parse_size_bytes("2mib").unwrap(), 2 * 1024 * 1024);
3063        assert!(parse_size_bytes("").is_err());
3064        assert!(parse_size_bytes("MB").is_err());
3065        assert!(parse_size_bytes("12 zonks").is_err());
3066    }
3067
3068    #[test]
3069    fn manifest_rejects_check_combined_with_emit() {
3070        // `emit:` stdout is NDJSON (and omitted from the result), so
3071        // it can't pair with `check:` (which needs a single JSON
3072        // object on stdout).
3073        let yaml = r#"
3074id: bad-mix
3075version: 0.1.0
3076execute:
3077  shell: powershell
3078  script: "echo x"
3079  timeout: 10s
3080check:
3081  name: bitlocker
3082emit:
3083  type: events
3084"#;
3085        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3086        let err = m.validate().expect_err("emit + check must fail");
3087        assert!(err.contains("incompatible"), "err: {err}");
3088    }
3089
3090    #[test]
3091    fn manifest_rejects_emit_combined_with_inventory() {
3092        // The other half of the emit-incompatibility condition.
3093        let yaml = r#"
3094id: bad-mix-2
3095version: 0.1.0
3096execute:
3097  shell: powershell
3098  script: "echo x"
3099  timeout: 10s
3100emit:
3101  type: events
3102inventory:
3103  display:
3104    - { field: status, label: Status }
3105"#;
3106        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3107        let err = m.validate().expect_err("emit + inventory must fail");
3108        assert!(err.contains("incompatible"), "err: {err}");
3109    }
3110
3111    #[test]
3112    fn manifest_rejects_empty_check_field_names() {
3113        // Empty name / status_field / detail_field are invisible
3114        // runtime bugs (empty React key, agent reads the wrong field)
3115        // — reject them even though serde supplies non-empty defaults.
3116        let base = |inner: &str| {
3117            format!(
3118                "id: c\nversion: 0.1.0\nexecute:\n  shell: powershell\n  script: \"echo x\"\n  timeout: 10s\ncheck:\n{inner}"
3119            )
3120        };
3121        for inner in [
3122            "  name: \"\"\n",
3123            "  name: ok\n  status_field: \"\"\n",
3124            "  name: ok\n  detail_field: \"   \"\n",
3125            // present-but-blank troubleshoot → broken remediation id.
3126            "  name: ok\n  troubleshoot: \"  \"\n",
3127        ] {
3128            let m: Manifest = serde_yaml::from_str(&base(inner)).expect("parse");
3129            let err = m.validate().expect_err("empty field must fail");
3130            assert!(err.contains("must not be empty"), "err: {err}");
3131        }
3132    }
3133
3134    #[test]
3135    fn check_alert_decodes_with_defaults_and_validates() {
3136        let yaml = r#"
3137id: c
3138version: 0.1.0
3139execute:
3140  shell: powershell
3141  script: "echo x"
3142  timeout: 10s
3143check:
3144  name: bitlocker
3145  alert:
3146    notify_user: true
3147    title: "BitLocker 未準拠"
3148"#;
3149        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3150        m.validate().expect("valid alert");
3151        let alert = m.check.unwrap().alert.unwrap();
3152        // Defaults: on = [fail], priority = warn, body = None.
3153        assert_eq!(alert.on, vec![CheckAlertStatus::Fail]);
3154        assert_eq!(
3155            alert.priority,
3156            crate::ipc::notifications::NotificationPriority::Warn
3157        );
3158        assert!(alert.body.is_none());
3159        assert!(alert.notify_user);
3160    }
3161
3162    #[test]
3163    fn check_alert_validation_rejects_bad_configs() {
3164        let base = |alert: &str| {
3165            format!(
3166                "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}"
3167            )
3168        };
3169        let cases = [
3170            // No recipient.
3171            ("    title: t\n", "notify_user and/or notify_groups"),
3172            // Empty title.
3173            (
3174                "    notify_user: true\n    title: \"  \"\n",
3175                "title must not be empty",
3176            ),
3177            // Empty `on`.
3178            (
3179                "    notify_user: true\n    title: t\n    on: []\n",
3180                "on must list at least one status",
3181            ),
3182            // Blank group name.
3183            (
3184                "    notify_groups: [\"  \"]\n    title: t\n",
3185                "notify_groups must not contain blanks",
3186            ),
3187            // alert requires fleet: true.
3188            (
3189                "    notify_user: true\n    title: t\n  fleet: false\n",
3190                "requires fleet: true",
3191            ),
3192            // email opt-in without a group to address.
3193            (
3194                "    notify_user: true\n    email: true\n    title: t\n",
3195                "email requires notify_groups",
3196            ),
3197        ];
3198        for (alert, want) in cases {
3199            let m: Manifest = serde_yaml::from_str(&base(alert)).expect("parse");
3200            let err = m.validate().expect_err("bad alert must fail");
3201            assert!(err.contains(want), "for {alert:?}: got {err}");
3202        }
3203    }
3204
3205    #[test]
3206    fn manifest_client_absent_by_default() {
3207        // A plain operator job (the overwhelming majority) carries no
3208        // `client:` block, so it never surfaces in the end-user
3209        // catalog.
3210        let yaml = r#"
3211id: echo-test
3212version: 0.0.1
3213execute:
3214  shell: powershell
3215  script: "echo 'kanade'"
3216  timeout: 30s
3217"#;
3218        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3219        assert!(m.client.is_none());
3220        m.validate().expect("operator-only job validates");
3221    }
3222
3223    #[test]
3224    fn manifest_client_parses_and_validates() {
3225        // The Client App "困ったとき" remediation job shape: a
3226        // user-invokable troubleshoot job with the end-user fields the
3227        // KLP `jobs.list` wire needs, grouped under `client:`.
3228        let yaml = r#"
3229id: fix-teams-cache
3230version: 1.0.0
3231execute:
3232  shell: powershell
3233  script: "echo clearing"
3234  timeout: 60s
3235client:
3236  name: "Teams のキャッシュをクリア"
3237  description: "Teams が重いときに試してください"
3238  category: troubleshoot
3239  icon: brush-cleaning
3240"#;
3241        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3242        let c = m.client.as_ref().expect("client block present");
3243        assert_eq!(c.name, "Teams のキャッシュをクリア");
3244        assert_eq!(
3245            c.description.as_deref(),
3246            Some("Teams が重いときに試してください")
3247        );
3248        assert_eq!(c.category, "troubleshoot");
3249        assert_eq!(c.icon.as_deref(), Some("brush-cleaning"));
3250        m.validate().expect("user-invokable job validates");
3251    }
3252
3253    #[test]
3254    fn manifest_client_minimal_only_name_and_category() {
3255        // description + icon are optional; name + category are the
3256        // serde-required minimum.
3257        let yaml = r#"
3258id: install-slack
3259version: 1.0.0
3260execute:
3261  shell: powershell
3262  script: "echo install"
3263  timeout: 600s
3264client:
3265  name: Slack
3266  category: catalog
3267"#;
3268        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3269        let c = m.client.as_ref().expect("client present");
3270        assert_eq!(c.category, "catalog");
3271        assert!(c.description.is_none() && c.icon.is_none());
3272        m.validate().expect("minimal client validates");
3273    }
3274
3275    #[test]
3276    fn manifest_client_rejects_blank_name() {
3277        // serde guarantees `name`/`category` are present; the one gap
3278        // is a present-but-blank name → empty catalog row title.
3279        let yaml = r#"
3280id: j
3281version: 1.0.0
3282execute:
3283  shell: powershell
3284  script: "echo x"
3285  timeout: 30s
3286client:
3287  name: "   "
3288  category: catalog
3289"#;
3290        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3291        let err = m.validate().expect_err("blank name must fail");
3292        assert!(err.contains("client.name"), "err: {err}");
3293    }
3294
3295    #[test]
3296    fn manifest_client_rejects_blank_optional_fields() {
3297        // description / icon are optional, but a present-but-blank
3298        // value is a bug (empty subtitle / dangling icon name) — reject
3299        // it, mirroring the check: block's troubleshoot guard.
3300        for (field, line) in [
3301            ("client.description", "  description: \"  \"\n"),
3302            ("client.icon", "  icon: \"\"\n"),
3303            // #792: the new category tab-metadata fields get the same
3304            // present-but-blank guard.
3305            ("client.category_label", "  category_label: \"  \"\n"),
3306            ("client.category_icon", "  category_icon: \"\"\n"),
3307        ] {
3308            let yaml = format!(
3309                "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}"
3310            );
3311            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
3312            let err = m.validate().expect_err("blank optional field must fail");
3313            assert!(err.contains(field), "expected {field} in err: {err}");
3314        }
3315    }
3316
3317    #[test]
3318    fn manifest_client_rejects_blank_category() {
3319        // #792: category is a free-form key now; serde keeps it required,
3320        // but a present-but-blank value would group the job under an empty
3321        // tab — validate() must reject it.
3322        let yaml = r#"
3323id: j
3324version: 1.0.0
3325execute:
3326  shell: powershell
3327  script: "echo x"
3328  timeout: 30s
3329client:
3330  name: "A job"
3331  category: "   "
3332"#;
3333        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3334        let err = m.validate().expect_err("blank category must fail");
3335        assert!(err.contains("client.category"), "err: {err}");
3336    }
3337
3338    #[test]
3339    fn target_matches_pc_group_and_all() {
3340        // #816: pc match, group match, all, and the no-match case.
3341        let by_pc = Target {
3342            pcs: vec!["PC1".into()],
3343            ..Default::default()
3344        };
3345        assert!(by_pc.matches("PC1", &[]));
3346        assert!(!by_pc.matches("PC2", &["g1".into()]));
3347
3348        let by_group = Target {
3349            groups: vec!["g1".into()],
3350            ..Default::default()
3351        };
3352        assert!(by_group.matches("PC2", &["g1".into()]));
3353        assert!(!by_group.matches("PC2", &["g2".into()]));
3354
3355        let all = Target {
3356            all: true,
3357            ..Default::default()
3358        };
3359        assert!(all.matches("anyPC", &[]));
3360    }
3361
3362    #[test]
3363    fn manifest_client_rejects_empty_visible_to() {
3364        // #816: a present-but-empty visible_to (no all/groups/pcs) would
3365        // hide the job from everyone — validate() must reject it.
3366        let yaml = r#"
3367id: j
3368version: 1.0.0
3369execute:
3370  shell: powershell
3371  script: "echo x"
3372  timeout: 30s
3373client:
3374  name: "A job"
3375  category: troubleshoot
3376  visible_to: {}
3377"#;
3378        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3379        let err = m.validate().expect_err("empty visible_to must fail");
3380        assert!(err.contains("client.visible_to"), "err: {err}");
3381    }
3382
3383    #[test]
3384    fn manifest_client_accepts_visible_to_groups() {
3385        let yaml = r#"
3386id: j
3387version: 1.0.0
3388execute:
3389  shell: powershell
3390  script: "echo x"
3391  timeout: 30s
3392client:
3393  name: "A job"
3394  category: settings
3395  visible_to:
3396    groups: [wifi-affected]
3397"#;
3398        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3399        m.validate().expect("visible_to with a group validates");
3400        let vt = m.client.unwrap().visible_to.unwrap();
3401        assert_eq!(vt.groups, vec!["wifi-affected".to_string()]);
3402    }
3403
3404    #[test]
3405    fn manifest_client_show_when_accepts_scalar_and_seq() {
3406        use crate::ipc::state::CheckStatus;
3407        // `is:` accepts a single status (author ergonomics) ...
3408        let scalar = r#"
3409id: office-update
3410version: 1.0.0
3411execute:
3412  shell: powershell
3413  script: "echo x"
3414  timeout: 30s
3415client:
3416  name: "Office を最新に更新"
3417  category: software_update
3418  show_when:
3419    check: office-up-to-date
3420    is: fail
3421"#;
3422        let m: Manifest = serde_yaml::from_str(scalar).expect("parse scalar");
3423        m.validate().expect("scalar show_when validates");
3424        let sw = m.client.unwrap().show_when.unwrap();
3425        assert_eq!(sw.check, "office-up-to-date");
3426        assert_eq!(sw.is, vec![CheckStatus::Fail]);
3427
3428        // ... and a list (e.g. fail-open on a not-yet-run check).
3429        let seq = scalar.replace("is: fail", "is: [fail, unknown]");
3430        let m: Manifest = serde_yaml::from_str(&seq).expect("parse seq");
3431        m.validate().expect("seq show_when validates");
3432        assert_eq!(
3433            m.client.unwrap().show_when.unwrap().is,
3434            vec![CheckStatus::Fail, CheckStatus::Unknown]
3435        );
3436    }
3437
3438    #[test]
3439    fn manifest_client_show_when_rejects_empty() {
3440        // A malformed check slug (here: internal spaces — a typo that could
3441        // never match a real check name) or an empty status list would
3442        // silently hide the job forever — validate() must reject both.
3443        let bad_check = r#"
3444id: j
3445version: 1.0.0
3446execute:
3447  shell: powershell
3448  script: "echo x"
3449  timeout: 30s
3450client:
3451  name: "A job"
3452  category: software_update
3453  show_when:
3454    check: "office up to date"
3455    is: fail
3456"#;
3457        let m: Manifest = serde_yaml::from_str(bad_check).expect("parse");
3458        let err = m.validate().expect_err("malformed check slug must fail");
3459        assert!(err.contains("client.show_when.check"), "err: {err}");
3460
3461        let empty_is = r#"
3462id: j
3463version: 1.0.0
3464execute:
3465  shell: powershell
3466  script: "echo x"
3467  timeout: 30s
3468client:
3469  name: "A job"
3470  category: software_update
3471  show_when:
3472    check: office-up-to-date
3473    is: []
3474"#;
3475        let m: Manifest = serde_yaml::from_str(empty_is).expect("parse");
3476        let err = m.validate().expect_err("empty is[] must fail");
3477        assert!(err.contains("client.show_when.is"), "err: {err}");
3478    }
3479
3480    #[test]
3481    fn manifest_client_requires_category_at_parse() {
3482        // A `client:` block missing `category` is a hard parse error
3483        // (serde required field) — no manual validate() needed.
3484        let yaml = r#"
3485id: j
3486version: 1.0.0
3487execute:
3488  shell: powershell
3489  script: "echo x"
3490  timeout: 30s
3491client:
3492  name: "A job"
3493"#;
3494        let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
3495        assert!(
3496            r.is_err(),
3497            "missing category must be a parse error, got {r:?}"
3498        );
3499    }
3500
3501    #[test]
3502    fn manifest_client_rejects_unknown_field() {
3503        // #492: the strict create boundary catches a fat-fingered
3504        // `displayname:` (with its path) instead of silently
3505        // dropping it; the tolerant read path accepts it.
3506        let yaml = r#"
3507id: j
3508version: 1.0.0
3509execute:
3510  shell: powershell
3511  script: "echo x"
3512  timeout: 30s
3513client:
3514  name: "A job"
3515  category: catalog
3516  displayname: oops
3517"#;
3518        let r = crate::strict::from_yaml_str::<Manifest>(yaml);
3519        let err = r.expect_err("unknown client field must be rejected at the write boundary");
3520        // serde_ignored renders the Option layer as `?`:
3521        // `client.?.displayname`. Assert on the leaf key.
3522        assert!(err.contains("displayname"), "{err}");
3523        // The READ path tolerates the same payload (gradual-upgrade
3524        // contract: an old agent must accept a newer writer's field).
3525        let m: Manifest = serde_yaml::from_str(yaml).expect("tolerant read");
3526        assert_eq!(m.client.as_ref().map(|c| c.name.as_str()), Some("A job"));
3527    }
3528
3529    #[test]
3530    fn manifest_tags_default_empty() {
3531        // The overwhelming majority of jobs carry no tags; the field
3532        // must default to an empty Vec (not fail to parse) and skip
3533        // serialisation so old readers never see the key.
3534        let yaml = r#"
3535id: echo-test
3536version: 0.0.1
3537execute:
3538  shell: powershell
3539  script: "echo 'kanade'"
3540  timeout: 30s
3541"#;
3542        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3543        assert!(m.tags.is_empty());
3544        m.validate().expect("tag-less job validates");
3545        // skip_serializing_if = empty ⇒ the key is absent from JSON.
3546        let json = serde_json::to_string(&m).expect("serialize");
3547        assert!(
3548            !json.contains("tags"),
3549            "empty tags must not serialise: {json}"
3550        );
3551    }
3552
3553    #[test]
3554    fn manifest_parses_and_validates_tags() {
3555        let yaml = r#"
3556id: check-bitlocker
3557version: 0.1.0
3558execute:
3559  shell: powershell
3560  script: "echo x"
3561  timeout: 30s
3562tags: [security, windows, health-check]
3563"#;
3564        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3565        assert_eq!(m.tags, vec!["security", "windows", "health-check"]);
3566        m.validate().expect("tagged job validates");
3567        // Round-trips through JSON (the wire format the SPA reads).
3568        let json = serde_json::to_string(&m).expect("serialize");
3569        assert!(json.contains("\"tags\""), "non-empty tags must serialise");
3570    }
3571
3572    #[test]
3573    fn manifest_rejects_blank_tag() {
3574        // A whitespace-only tag renders an empty filter chip — reject
3575        // it at the write boundary like the other blank display fields.
3576        let yaml = r#"
3577id: j
3578version: 0.1.0
3579execute:
3580  shell: powershell
3581  script: "echo x"
3582  timeout: 30s
3583tags: [ok, "   "]
3584"#;
3585        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3586        let err = m.validate().expect_err("blank tag must fail");
3587        assert!(err.contains("tags must not contain empty"), "err: {err}");
3588    }
3589
3590    #[test]
3591    fn validate_rejects_unknown_tier_and_accepts_known() {
3592        let base =
3593            "id: t\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: x\n  timeout: 30s\n";
3594        // A typo / future tier decodes to Tier::Unknown (#[serde(other)]) and
3595        // must FAIL CLOSED — never fall back to unrestricted endpoint dispatch.
3596        let bogus: Manifest =
3597            serde_yaml::from_str(&format!("{base}tier: controler\n")).expect("parse");
3598        let err = bogus.validate().expect_err("unknown tier must be rejected");
3599        assert!(err.contains("tier"), "err: {err}");
3600        // The two known tiers pass.
3601        serde_yaml::from_str::<Manifest>(&format!("{base}tier: controller\n"))
3602            .unwrap()
3603            .validate()
3604            .expect("controller tier is valid");
3605        serde_yaml::from_str::<Manifest>(&format!("{base}tier: endpoint\n"))
3606            .unwrap()
3607            .validate()
3608            .expect("endpoint tier is valid");
3609    }
3610
3611    #[test]
3612    fn feed_payload_extracts_fenced_block() {
3613        let stdout = "fetched 1500 KEV entries\n\
3614            #KANADE-FEED-BEGIN\n\
3615            {\"vulnerabilities\": []}\n\
3616            #KANADE-FEED-END\n";
3617        assert_eq!(feed_payload(stdout), "{\"vulnerabilities\": []}");
3618    }
3619
3620    #[test]
3621    fn validate_feed_rules() {
3622        let base =
3623            "id: f\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: x\n  timeout: 30s\n";
3624        // A well-formed feed (controller implied; no explicit tier) passes.
3625        serde_yaml::from_str::<Manifest>(&format!(
3626            "{base}feed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
3627        ))
3628        .unwrap()
3629        .validate()
3630        .expect("a well-formed feed is valid");
3631
3632        // Empty primary_key is rejected (no item_id → every row dropped).
3633        let err = serde_yaml::from_str::<Manifest>(&format!(
3634            "{base}feed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: []\n"
3635        ))
3636        .unwrap()
3637        .validate()
3638        .expect_err("empty primary_key must be rejected");
3639        assert!(err.contains("primary_key"), "err: {err}");
3640
3641        // A duplicate feed id clobbers a partition — rejected.
3642        let err = serde_yaml::from_str::<Manifest>(&format!(
3643            "{base}feed:\n  - id: dup\n    field: a\n    primary_key: [k]\n  - id: dup\n    field: b\n    primary_key: [k]\n"
3644        ))
3645        .unwrap()
3646        .validate()
3647        .expect_err("duplicate feed id must be rejected");
3648        assert!(err.contains("more than once"), "err: {err}");
3649
3650        // `feed:` + explicit `tier: endpoint` is contradictory — rejected.
3651        let err = serde_yaml::from_str::<Manifest>(&format!(
3652            "{base}tier: endpoint\nfeed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
3653        ))
3654        .unwrap()
3655        .validate()
3656        .expect_err("feed + tier: endpoint must be rejected");
3657        assert!(err.contains("controller tier"), "err: {err}");
3658
3659        // `feed:` + `emit:` is incompatible — emit consumes stdout whole, so
3660        // the feed's fence never reaches the projector.
3661        let err = serde_yaml::from_str::<Manifest>(&format!(
3662            "{base}emit:\n  type: events\nfeed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
3663        ))
3664        .unwrap()
3665        .validate()
3666        .expect_err("feed + emit must be rejected");
3667        assert!(err.contains("emit"), "err: {err}");
3668    }
3669
3670    // #720 — wrap an `aggregate:` YAML block (already indented as a
3671    // top-level key body) into an otherwise-minimal valid manifest.
3672    fn manifest_with_aggregate(aggregate_block: &str) -> Manifest {
3673        let yaml = format!(
3674            "id: t\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: echo hi\n  timeout: 30s\n{aggregate_block}"
3675        );
3676        serde_yaml::from_str(&yaml).expect("parse aggregate manifest")
3677    }
3678
3679    #[test]
3680    fn aggregate_accepts_full_valid_spec() {
3681        // count+group_by+exclude+sample_minutes, ratio+bool_path,
3682        // timeline+time_bucket, fleet ranking via group_by: pc_id, and a
3683        // bare total stat — alongside emit (composes with every hint).
3684        let m = manifest_with_aggregate(
3685            "emit:\n  type: events\naggregate:\n\
3686             - { dashboard: Utilization, title: Top apps, kind: app_sample, agg: count, group_by: foreground.app, sample_minutes: 2, exclude: [LockApp], render: bar }\n\
3687             - { dashboard: Utilization, title: Active ratio, kind: presence, agg: ratio, bool_path: active, sample_minutes: 5, render: gauge }\n\
3688             - { dashboard: Utilization, title: By hour, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: timeline }\n\
3689             - { dashboard: Reliability, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
3690             - { dashboard: Reliability, title: Total crashes, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
3691        );
3692        m.validate().expect("valid aggregate spec");
3693    }
3694
3695    #[test]
3696    fn aggregate_rejects_empty_list() {
3697        let m = manifest_with_aggregate("aggregate: []\n");
3698        let err = m.validate().expect_err("empty list must fail");
3699        assert!(err.contains("at least one widget"), "err: {err}");
3700    }
3701
3702    #[test]
3703    fn aggregate_rejects_ratio_without_bool_path() {
3704        let m = manifest_with_aggregate(
3705            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, render: gauge }\n",
3706        );
3707        let err = m.validate().expect_err("ratio needs bool_path");
3708        assert!(err.contains("agg=ratio requires `bool_path`"), "err: {err}");
3709    }
3710
3711    #[test]
3712    fn aggregate_rejects_sum_without_value_path() {
3713        let m = manifest_with_aggregate(
3714            "aggregate:\n- { dashboard: D, title: T, kind: io, agg: sum, render: bar }\n",
3715        );
3716        let err = m.validate().expect_err("sum needs value_path");
3717        assert!(err.contains("agg=sum requires `value_path`"), "err: {err}");
3718    }
3719
3720    #[test]
3721    fn aggregate_rejects_pc_id_group_without_fleet() {
3722        let m = manifest_with_aggregate(
3723            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: count, group_by: pc_id, render: bar }\n",
3724        );
3725        let err = m.validate().expect_err("pc_id grouping needs fleet");
3726        assert!(
3727            err.contains("pc_id is only valid with scope: fleet"),
3728            "err: {err}"
3729        );
3730    }
3731
3732    #[test]
3733    fn aggregate_rejects_transform_with_pc_id_group() {
3734        let m = manifest_with_aggregate(
3735            "aggregate:\n- { dashboard: D, title: T, scope: fleet, kind: web_visit, agg: count, group_by: pc_id, transform: host, render: bar }\n",
3736        );
3737        let err = m
3738            .validate()
3739            .expect_err("transform on pc_id grouping must fail");
3740        assert!(
3741            err.contains("transform is not valid with group_by: pc_id"),
3742            "err: {err}"
3743        );
3744    }
3745
3746    #[test]
3747    fn aggregate_rejects_timeline_without_bucket() {
3748        let m = manifest_with_aggregate(
3749            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, bool_path: active, render: timeline }\n",
3750        );
3751        let err = m.validate().expect_err("timeline needs a bucket");
3752        assert!(
3753            err.contains("render=timeline requires `time_bucket`"),
3754            "err: {err}"
3755        );
3756    }
3757
3758    #[test]
3759    fn aggregate_rejects_bucket_on_non_timeline() {
3760        let m = manifest_with_aggregate(
3761            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: gauge }\n",
3762        );
3763        let err = m.validate().expect_err("bucket only on timeline");
3764        assert!(
3765            err.contains("time_bucket is only valid with render: timeline"),
3766            "err: {err}"
3767        );
3768    }
3769
3770    #[test]
3771    fn aggregate_rejects_unsafe_json_path() {
3772        // A path with characters outside [A-Za-z0-9_.] could break out of
3773        // the `'$.' || ?` bind — reject at create time.
3774        let m = manifest_with_aggregate(
3775            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: \"foo'; DROP\", render: bar }\n",
3776        );
3777        let err = m.validate().expect_err("unsafe path must fail");
3778        assert!(err.contains("dotted JSON path"), "err: {err}");
3779    }
3780
3781    #[test]
3782    fn aggregate_rejects_blank_title() {
3783        let m = manifest_with_aggregate(
3784            "aggregate:\n- { dashboard: D, title: \"  \", kind: k, agg: count, render: stat }\n",
3785        );
3786        let err = m.validate().expect_err("blank title must fail");
3787        assert!(err.contains("title must not be empty"), "err: {err}");
3788    }
3789
3790    #[test]
3791    fn aggregate_rejects_blank_kind() {
3792        let m = manifest_with_aggregate(
3793            "aggregate:\n- { dashboard: D, title: T, kind: \" \", agg: count, render: stat }\n",
3794        );
3795        let err = m.validate().expect_err("blank kind must fail");
3796        assert!(err.contains("kind must not be empty"), "err: {err}");
3797    }
3798
3799    #[test]
3800    fn aggregate_rejects_blank_source_when_set() {
3801        let m = manifest_with_aggregate(
3802            "aggregate:\n- { dashboard: D, title: T, kind: k, source: \"\", agg: count, render: stat }\n",
3803        );
3804        let err = m.validate().expect_err("blank source must fail");
3805        assert!(
3806            err.contains("source must not be empty when set"),
3807            "err: {err}"
3808        );
3809    }
3810
3811    #[test]
3812    fn aggregate_accepts_description_and_rejects_blank() {
3813        let ok = manifest_with_aggregate(
3814            "aggregate:\n- { dashboard: D, title: T, description: \"samples x 2 min\", kind: k, agg: count, render: stat }\n",
3815        );
3816        ok.validate()
3817            .expect("description is a valid optional field");
3818        assert_eq!(
3819            ok.aggregate.as_ref().unwrap()[0].description.as_deref(),
3820            Some("samples x 2 min")
3821        );
3822        let bad = manifest_with_aggregate(
3823            "aggregate:\n- { dashboard: D, title: T, description: \"  \", kind: k, agg: count, render: stat }\n",
3824        );
3825        let err = bad.validate().expect_err("blank description must fail");
3826        assert!(
3827            err.contains("description must not be empty when set"),
3828            "err: {err}"
3829        );
3830    }
3831
3832    #[test]
3833    fn aggregate_rejects_count_with_value_path() {
3834        let m = manifest_with_aggregate(
3835            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, value_path: bytes, render: stat }\n",
3836        );
3837        let err = m.validate().expect_err("count must not use value_path");
3838        assert!(
3839            err.contains("agg=count does not use `value_path`"),
3840            "err: {err}"
3841        );
3842    }
3843
3844    #[test]
3845    fn aggregate_rejects_ratio_with_value_path() {
3846        let m = manifest_with_aggregate(
3847            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: ratio, bool_path: active, value_path: bytes, render: gauge }\n",
3848        );
3849        let err = m.validate().expect_err("ratio must not use value_path");
3850        assert!(
3851            err.contains("agg=ratio does not use `value_path`"),
3852            "err: {err}"
3853        );
3854    }
3855
3856    #[test]
3857    fn aggregate_rejects_gauge_without_ratio() {
3858        let m = manifest_with_aggregate(
3859            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, render: gauge }\n",
3860        );
3861        let err = m.validate().expect_err("gauge needs ratio");
3862        assert!(
3863            err.contains("render=gauge is only valid with agg: ratio"),
3864            "err: {err}"
3865        );
3866    }
3867
3868    #[test]
3869    fn aggregate_rejects_limit_without_group_by() {
3870        let m = manifest_with_aggregate(
3871            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, limit: 5, render: stat }\n",
3872        );
3873        let err = m.validate().expect_err("limit needs group_by");
3874        assert!(err.contains("limit requires `group_by`"), "err: {err}");
3875    }
3876
3877    #[test]
3878    fn aggregate_rejects_exclude_without_group_by() {
3879        let m = manifest_with_aggregate(
3880            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, exclude: [x], render: stat }\n",
3881        );
3882        let err = m.validate().expect_err("exclude needs group_by");
3883        assert!(err.contains("exclude requires `group_by`"), "err: {err}");
3884    }
3885
3886    #[test]
3887    fn aggregate_rejects_zero_limit_and_zero_sample_minutes() {
3888        let m = manifest_with_aggregate(
3889            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, limit: 0, render: bar }\n",
3890        );
3891        assert!(m.validate().unwrap_err().contains("limit must be > 0"));
3892        let m = manifest_with_aggregate(
3893            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, sample_minutes: 0, render: bar }\n",
3894        );
3895        assert!(
3896            m.validate()
3897                .unwrap_err()
3898                .contains("sample_minutes must be > 0")
3899        );
3900    }
3901
3902    #[test]
3903    fn aggregate_rejects_empty_exclude_entry() {
3904        let m = manifest_with_aggregate(
3905            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, exclude: [\"  \"], render: bar }\n",
3906        );
3907        let err = m.validate().expect_err("blank exclude entry must fail");
3908        assert!(
3909            err.contains("exclude must not contain empty entries"),
3910            "err: {err}"
3911        );
3912    }
3913
3914    #[test]
3915    fn aggregate_rejects_malformed_dotted_paths() {
3916        for bad in [".foo", "foo.", "foo..bar", "."] {
3917            let m = manifest_with_aggregate(&format!(
3918                "aggregate:\n- {{ dashboard: D, title: T, kind: k, agg: count, group_by: \"{bad}\", render: bar }}\n"
3919            ));
3920            let err = m.validate().expect_err("malformed path must fail");
3921            assert!(err.contains("dotted JSON path"), "path {bad}: {err}");
3922        }
3923    }
3924
3925    #[test]
3926    fn aggregate_rejects_unknown_enum_value() {
3927        // An unrecognised render string deserialises to the #492 Unknown
3928        // catch-all (so old readers don't choke); validate() rejects it as
3929        // a typo at create time.
3930        let m = manifest_with_aggregate(
3931            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, render: heatmap }\n",
3932        );
3933        let err = m.validate().expect_err("unknown render must fail");
3934        assert!(err.contains("render is not a known value"), "err: {err}");
3935    }
3936
3937    #[test]
3938    fn aggregate_accepts_order_field() {
3939        let m = manifest_with_aggregate(
3940            "aggregate:\n- { dashboard: D, title: T, order: -5, kind: k, agg: count, render: stat }\n",
3941        );
3942        m.validate().expect("order is a valid optional field");
3943        let w = &m.aggregate.as_ref().unwrap()[0];
3944        assert_eq!(w.order, Some(-5));
3945    }
3946
3947    #[test]
3948    fn aggregate_accepts_minimal_op_timeline() {
3949        // op_timeline needs no kind/agg — it reconstructs a fixed multi-kind
3950        // swimlane. A bare per-PC spec is valid, and `kind`/`agg` stay None.
3951        let m = manifest_with_aggregate(
3952            "aggregate:\n- { dashboard: Uptime, title: Operational state, scope: pc, render: op_timeline }\n",
3953        );
3954        m.validate().expect("minimal op_timeline is valid");
3955        let w = &m.aggregate.as_ref().unwrap()[0];
3956        assert_eq!(w.render, AggregateRender::OpTimeline);
3957        assert!(w.kind.is_none());
3958        assert!(w.agg.is_none());
3959    }
3960
3961    #[test]
3962    fn aggregate_rejects_op_timeline_with_fleet_scope() {
3963        let m = manifest_with_aggregate(
3964            "aggregate:\n- { dashboard: Uptime, title: T, scope: fleet, render: op_timeline }\n",
3965        );
3966        let err = m.validate().expect_err("op_timeline must be per-PC");
3967        assert!(
3968            err.contains("render=op_timeline requires scope: pc"),
3969            "err: {err}"
3970        );
3971    }
3972
3973    #[test]
3974    fn aggregate_rejects_op_timeline_with_aggregation_fields() {
3975        // Each aggregation knob the operator might paste in is rejected
3976        // (rather than silently ignored), pointing at the field to delete.
3977        for (block, field) in [
3978            ("kind: boot", "kind"),
3979            ("agg: count", "agg"),
3980            ("source: winlog:Security", "source"),
3981            ("group_by: pc_id", "group_by"),
3982            ("bool_path: active", "bool_path"),
3983            ("time_bucket: hour", "time_bucket"),
3984            ("limit: 5", "limit"),
3985        ] {
3986            let m = manifest_with_aggregate(&format!(
3987                "aggregate:\n- {{ dashboard: Uptime, title: T, scope: pc, {block}, render: op_timeline }}\n"
3988            ));
3989            let err = m
3990                .validate()
3991                .expect_err(&format!("op_timeline must reject {field}"));
3992            assert!(
3993                err.contains(&format!("render=op_timeline does not use `{field}`")),
3994                "field {field}: {err}"
3995            );
3996        }
3997    }
3998
3999    // ── #743 View resource ───────────────────────────────────────────
4000    fn view_from(yaml_body: &str) -> View {
4001        serde_yaml::from_str(&format!("id: v1\n{yaml_body}")).expect("parse view")
4002    }
4003
4004    #[test]
4005    fn view_accepts_valid_widgets() {
4006        let v = view_from(
4007            "widgets:\n\
4008             - { dashboard: Reliability, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
4009             - { dashboard: Reliability, title: Total, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
4010        );
4011        v.validate().expect("valid view");
4012    }
4013
4014    #[test]
4015    fn view_rejects_empty_widgets() {
4016        let v = view_from("widgets: []\n");
4017        let err = v.validate().expect_err("empty widgets must fail");
4018        assert!(err.contains("at least one widget"), "err: {err}");
4019    }
4020
4021    #[test]
4022    fn view_rejects_blank_id() {
4023        let v: View = serde_yaml::from_str(
4024            "id: \"  \"\nwidgets:\n- { dashboard: D, title: T, kind: k, agg: count, render: stat }\n",
4025        )
4026        .expect("parse");
4027        let err = v.validate().expect_err("blank id must fail");
4028        assert!(err.contains("view.id must"), "err: {err}");
4029    }
4030
4031    #[test]
4032    fn view_rejects_unsafe_id() {
4033        // A `/` or `..` in the id would break the KV key and the
4034        // `/api/views/{id}` URL segment — reject at create time.
4035        for bad in ["../etc", "a/b", "has space", "x;y"] {
4036            let v: View = serde_yaml::from_str(&format!(
4037                "id: \"{bad}\"\nwidgets:\n- {{ dashboard: D, title: T, kind: k, agg: count, render: stat }}\n",
4038            ))
4039            .expect("parse");
4040            let err = v.validate().expect_err("unsafe id must fail");
4041            assert!(err.contains("[A-Za-z0-9._-]"), "id {bad}: {err}");
4042        }
4043        assert!(is_valid_resource_id("dashboards-fleet.v1_2"));
4044    }
4045
4046    #[test]
4047    fn view_reuses_shared_widget_validation() {
4048        // The same per-widget rule the job hint enforces (ratio needs
4049        // bool_path), reported under the `widgets[..]` field.
4050        let v = view_from(
4051            "widgets:\n- { dashboard: D, title: T, kind: presence, agg: ratio, render: gauge }\n",
4052        );
4053        let err = v.validate().expect_err("ratio without bool_path must fail");
4054        assert!(
4055            err.contains("widgets[0].agg=ratio requires `bool_path`"),
4056            "err: {err}"
4057        );
4058    }
4059
4060    // ── #vuln-roadmap PR3 SQL-backed views ───────────────────────────
4061    #[test]
4062    fn view_accepts_pure_sql_widgets() {
4063        // A view with only sql_widgets (no obs_events aggregate widgets) is
4064        // valid — the vulnerability-dashboard shape.
4065        let v = view_from(
4066            "sql_widgets:
4067  - title: KEV-affected hosts
4068    query: \"SELECT pc_id, 1 AS cves FROM inventory_sw_apps\"
4069    refresh: 6h
4070    render: { kind: table, columns: [pc_id, cves], labels: { cves: CVE count } }
4071    placement: { analytics: Security, dashboard: { pin: true } }
4072",
4073        );
4074        v.validate().expect("valid sql view");
4075        // refresh parses; pin/tab helpers read the placement.
4076        let w = &v.sql_widgets[0];
4077        assert_eq!(
4078            w.refresh_interval(),
4079            std::time::Duration::from_secs(6 * 3600)
4080        );
4081        assert!(w.placement.is_pinned());
4082        assert_eq!(w.placement.tab(), "Security");
4083    }
4084
4085    #[test]
4086    fn sql_widget_defaults_and_mix() {
4087        // No refresh ⇒ default; a view can mix aggregate + sql widgets.
4088        let v = view_from(
4089            "widgets:
4090  - { dashboard: D, title: T, kind: k, agg: count, render: stat }
4091sql_widgets:
4092  - title: N affected
4093    query: \"SELECT count(*) AS n FROM feeds\"
4094    render: { kind: stat, value: n }
4095    placement: { dashboard: { pin: true } }
4096",
4097        );
4098        v.validate().expect("mixed view is valid");
4099        assert_eq!(v.sql_widgets[0].refresh_interval(), DEFAULT_VIEW_REFRESH);
4100        // dashboard-only placement (no analytics tab) falls back to a label.
4101        assert_eq!(v.sql_widgets[0].placement.tab(), "Dashboard");
4102    }
4103
4104    #[test]
4105    fn sql_widget_validation_rules() {
4106        // helper: build a view with one sql_widget from an inline render+placement
4107        let mk = |render: &str, placement: &str| -> Result<(), String> {
4108            view_from(&format!(
4109                "sql_widgets:
4110  - title: W
4111    query: \"SELECT 1 AS a\"
4112    render: {render}
4113    placement: {placement}
4114"
4115            ))
4116            .validate()
4117        };
4118        // bar needs label + value
4119        let err = mk("{ kind: bar, value: a }", "{ analytics: T }").unwrap_err();
4120        assert!(
4121            err.contains("render.label is required for kind=bar"),
4122            "err: {err}"
4123        );
4124        // pie needs value
4125        let err = mk("{ kind: pie, label: a }", "{ analytics: T }").unwrap_err();
4126        assert!(
4127            err.contains("render.value is required for kind=pie"),
4128            "err: {err}"
4129        );
4130        // stat needs value
4131        let err = mk("{ kind: stat }", "{ analytics: T }").unwrap_err();
4132        assert!(
4133            err.contains("render.value is required for kind=stat"),
4134            "err: {err}"
4135        );
4136        // gauge needs value XOR num+den
4137        let err = mk("{ kind: gauge, num: a }", "{ analytics: T }").unwrap_err();
4138        assert!(err.contains("needs either `value`"), "err: {err}");
4139        mk("{ kind: gauge, value: a }", "{ analytics: T }").expect("gauge value ok");
4140        mk("{ kind: gauge, num: a, den: a }", "{ analytics: T }").expect("gauge num/den ok");
4141        // unknown kind rejected
4142        let err = mk("{ kind: sunburst }", "{ analytics: T }").unwrap_err();
4143        assert!(
4144            err.contains("render.kind is not a known value"),
4145            "err: {err}"
4146        );
4147        // placement must surface somewhere
4148        let err = mk("{ kind: table }", "{}").unwrap_err();
4149        assert!(err.contains("placement must set"), "err: {err}");
4150        // a `dashboard: { pin: false }` block still surfaces nowhere.
4151        let err = mk("{ kind: table }", "{ dashboard: { pin: false } }").unwrap_err();
4152        assert!(err.contains("placement must set"), "err: {err}");
4153        mk("{ kind: table }", "{ dashboard: { pin: true } }").expect("pinned dashboard ok");
4154        // limit: 0 on a bar/pie is an invisible widget — rejected.
4155        let err = mk(
4156            "{ kind: bar, label: a, value: a, limit: 0 }",
4157            "{ analytics: T }",
4158        )
4159        .unwrap_err();
4160        assert!(err.contains("limit must be >= 1"), "err: {err}");
4161        // bad refresh duration rejected
4162        let err = view_from(
4163            "sql_widgets:
4164  - { title: W, query: \"SELECT 1\", refresh: \"6 sidereal days\", render: { kind: table }, placement: { analytics: T } }
4165",
4166        )
4167        .validate()
4168        .unwrap_err();
4169        assert!(
4170            err.contains("refresh") && err.contains("not a valid duration"),
4171            "err: {err}"
4172        );
4173        // table is fine with no channels
4174        mk("{ kind: table }", "{ analytics: T }").expect("bare table ok");
4175    }
4176
4177    fn execute_with(
4178        script: Option<&str>,
4179        script_file: Option<&str>,
4180        script_object: Option<&str>,
4181    ) -> Execute {
4182        Execute {
4183            shell: ExecuteShell::Powershell,
4184            script: script.map(str::to_owned),
4185            script_file: script_file.map(str::to_owned),
4186            script_object: script_object.map(str::to_owned),
4187            timeout: "30s".into(),
4188            run_as: RunAs::default(),
4189            cwd: None,
4190        }
4191    }
4192
4193    #[test]
4194    fn validate_accepts_inline_script() {
4195        let e = execute_with(Some("echo hi"), None, None);
4196        assert!(e.validate_script_source().is_ok());
4197    }
4198
4199    #[test]
4200    fn validate_accepts_script_file_alone() {
4201        let e = execute_with(None, Some("scripts/cleanup.ps1"), None);
4202        assert!(e.validate_script_source().is_ok());
4203    }
4204
4205    #[test]
4206    fn validate_accepts_script_object_alone() {
4207        let e = execute_with(None, None, Some("cleanup/1.0.0"));
4208        assert!(e.validate_script_source().is_ok());
4209    }
4210
4211    #[test]
4212    fn validate_treats_empty_inline_script_as_unset() {
4213        // `script: ""` + `script_object` set is the natural shape
4214        // when an operator comments out the YAML block-scalar body
4215        // but leaves the key. Should pass.
4216        let e = execute_with(Some(""), None, Some("cleanup/1.0.0"));
4217        assert!(e.validate_script_source().is_ok());
4218    }
4219
4220    #[test]
4221    fn validate_rejects_zero_sources() {
4222        let e = execute_with(None, None, None);
4223        let err = e.validate_script_source().unwrap_err();
4224        assert!(err.contains("must be set"), "got: {err}");
4225    }
4226
4227    #[test]
4228    fn validate_rejects_empty_inline_only() {
4229        let e = execute_with(Some(""), None, None);
4230        let err = e.validate_script_source().unwrap_err();
4231        assert!(err.contains("must be set"), "got: {err}");
4232    }
4233
4234    #[test]
4235    fn validate_rejects_inline_plus_file() {
4236        let e = execute_with(Some("echo hi"), Some("scripts/cleanup.ps1"), None);
4237        let err = e.validate_script_source().unwrap_err();
4238        assert!(err.contains("only one of"), "got: {err}");
4239    }
4240
4241    #[test]
4242    fn validate_rejects_inline_plus_object() {
4243        let e = execute_with(Some("echo hi"), None, Some("cleanup/1.0.0"));
4244        let err = e.validate_script_source().unwrap_err();
4245        assert!(err.contains("only one of"), "got: {err}");
4246    }
4247
4248    #[test]
4249    fn validate_rejects_file_plus_object() {
4250        let e = execute_with(None, Some("scripts/cleanup.ps1"), Some("cleanup/1.0.0"));
4251        let err = e.validate_script_source().unwrap_err();
4252        assert!(err.contains("only one of"), "got: {err}");
4253    }
4254
4255    #[test]
4256    fn validate_rejects_all_three() {
4257        let e = execute_with(
4258            Some("echo hi"),
4259            Some("scripts/cleanup.ps1"),
4260            Some("cleanup/1.0.0"),
4261        );
4262        let err = e.validate_script_source().unwrap_err();
4263        assert!(err.contains("only one of"), "got: {err}");
4264    }
4265
4266    #[test]
4267    fn manifest_deserialises_script_object_yaml() {
4268        // SPEC §2.4.1 example shape with the Object Store
4269        // reference picked over inline.
4270        let yaml = r#"
4271id: cleanup-disk-temp
4272version: 1.0.1
4273execute:
4274  shell: powershell
4275  script_object: cleanup-disk-temp/1.0.1
4276  timeout: 600s
4277"#;
4278        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4279        assert_eq!(
4280            m.execute.script_object.as_deref(),
4281            Some("cleanup-disk-temp/1.0.1")
4282        );
4283        assert!(m.execute.script.is_none());
4284        m.validate()
4285            .expect("script_object-only manifest passes validation");
4286    }
4287
4288    #[test]
4289    fn manifest_rejects_typo_in_script_field_name() {
4290        // #492: the strict create boundary catches `script_objectt`
4291        // and similar fat-fingers (with the full path) instead of
4292        // letting them silently fall through to "all three unset".
4293        let yaml = r#"
4294id: typo
4295version: 1.0.0
4296execute:
4297  shell: powershell
4298  script_objectt: oops
4299  timeout: 30s
4300"#;
4301        let err = crate::strict::from_yaml_str::<Manifest>(yaml)
4302            .expect_err("typo'd execute field must be rejected at the write boundary");
4303        assert!(err.contains("execute.script_objectt"), "{err}");
4304    }
4305
4306    #[test]
4307    fn schedule_carries_target_and_rollout() {
4308        let yaml = r#"
4309id: hourly-cleanup-canary
4310when:
4311  per_pc: { every: 1h }
4312job_id: cleanup
4313enabled: true
4314target:
4315  groups: [canary, wave1]
4316jitter: 30s
4317rollout:
4318  strategy: wave
4319  waves:
4320    - { group: canary, delay: 0s }
4321    - { group: wave1,  delay: 5s }
4322"#;
4323        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4324        assert_eq!(s.id, "hourly-cleanup-canary");
4325        assert_eq!(s.job_id, "cleanup");
4326        assert_eq!(s.plan.target.groups, vec!["canary", "wave1"]);
4327        assert_eq!(s.plan.jitter.as_deref(), Some("30s"));
4328        let rollout = s.plan.rollout.expect("rollout present");
4329        assert_eq!(rollout.waves.len(), 2);
4330        assert_eq!(rollout.waves[0].group, "canary");
4331        assert_eq!(rollout.waves[1].delay, "5s");
4332        assert_eq!(rollout.strategy, RolloutStrategy::Wave);
4333    }
4334
4335    #[test]
4336    fn schedule_minimal_target_all() {
4337        let yaml = r#"
4338id: kitting
4339when:
4340  per_pc: once
4341enabled: true
4342job_id: scheduled-echo
4343target: { all: true }
4344"#;
4345        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4346        assert_eq!(s.id, "kitting");
4347        assert_eq!(s.when, When::PerPc(PerPolicy::Once(OnceLiteral::Once)));
4348        assert!(s.enabled);
4349        assert_eq!(s.job_id, "scheduled-echo");
4350        assert!(s.plan.target.all);
4351        assert!(s.plan.rollout.is_none());
4352        assert!(s.plan.jitter.is_none());
4353        assert!(s.active.is_empty());
4354    }
4355
4356    #[test]
4357    fn schedule_enabled_defaults_to_true() {
4358        let yaml = r#"
4359id: x
4360when:
4361  per_pc: once
4362job_id: y
4363target: { all: true }
4364"#;
4365        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4366        assert!(s.enabled);
4367    }
4368
4369    #[test]
4370    fn schedule_tags_default_empty_and_skip_serialise() {
4371        let yaml = r#"
4372id: x
4373when:
4374  per_pc: once
4375job_id: y
4376target: { all: true }
4377"#;
4378        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4379        assert!(s.tags.is_empty());
4380        s.validate().expect("tag-less schedule validates");
4381        let json = serde_json::to_string(&s).expect("serialize");
4382        assert!(
4383            !json.contains("tags"),
4384            "empty tags must not serialise: {json}"
4385        );
4386    }
4387
4388    #[test]
4389    fn schedule_parses_and_validates_tags() {
4390        let yaml = r#"
4391id: weekly-cleanup
4392when:
4393  per_pc: { every: 1h }
4394job_id: cleanup
4395target: { all: true }
4396tags: [weekly, maintenance]
4397"#;
4398        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4399        assert_eq!(s.tags, vec!["weekly", "maintenance"]);
4400        s.validate().expect("tagged schedule validates");
4401    }
4402
4403    #[test]
4404    fn schedule_rejects_blank_tag() {
4405        let yaml = r#"
4406id: x
4407when:
4408  per_pc: once
4409job_id: y
4410target: { all: true }
4411tags: [ok, "  "]
4412"#;
4413        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4414        let err = s.validate().expect_err("blank tag must fail");
4415        assert!(err.contains("tags must not contain empty"), "err: {err}");
4416    }
4417
4418    // ---- `when` parsing (#418 Phase 1) ----
4419
4420    fn schedule_yaml_with(when_block: &str) -> String {
4421        format!(
4422            r#"
4423id: x
4424when:
4425{when_block}
4426job_id: y
4427target: {{ all: true }}
4428"#
4429        )
4430    }
4431
4432    #[test]
4433    fn when_per_pc_every_parses_unquoted_humantime() {
4434        // `6h` is digit-led but non-numeric → YAML string, same as
4435        // the old `cooldown: 6h` convention. No quotes needed.
4436        let s: Schedule =
4437            serde_yaml::from_str(&schedule_yaml_with("  per_pc: { every: 6h }")).expect("parse");
4438        assert_eq!(
4439            s.when,
4440            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() }))
4441        );
4442    }
4443
4444    #[test]
4445    fn when_per_target_every_parses() {
4446        let s: Schedule = serde_yaml::from_str(&schedule_yaml_with("  per_target: { every: 24h }"))
4447            .expect("parse");
4448        assert_eq!(
4449            s.when,
4450            When::PerTarget(PerPolicy::Every(EverySpec {
4451                every: "24h".into()
4452            }))
4453        );
4454    }
4455
4456    #[test]
4457    fn when_per_target_once_parses() {
4458        // Falls out of the shared PerPolicy shape and decide_fire
4459        // already implements it ("any one pc succeeds → skip the
4460        // target forever"), so it is allowed, not rejected.
4461        let s: Schedule =
4462            serde_yaml::from_str(&schedule_yaml_with("  per_target: once")).expect("parse");
4463        assert_eq!(s.when, When::PerTarget(PerPolicy::Once(OnceLiteral::Once)));
4464    }
4465
4466    #[test]
4467    fn when_calendar_time_parses() {
4468        let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(
4469            "  calendar:\n    at: \"09:00\"\n    days: [mon-fri]",
4470        ))
4471        .expect("parse");
4472        match &s.when {
4473            When::Calendar(c) => {
4474                assert_eq!(c.at, "09:00");
4475                assert_eq!(c.days, vec!["mon-fri"]);
4476            }
4477            other => panic!("expected calendar, got {other:?}"),
4478        }
4479    }
4480
4481    #[test]
4482    fn when_calendar_days_default_empty() {
4483        let s: Schedule =
4484            serde_yaml::from_str(&schedule_yaml_with("  calendar:\n    at: \"09:00\""))
4485                .expect("parse");
4486        match &s.when {
4487            When::Calendar(c) => assert!(c.days.is_empty(), "days defaults to empty (= daily)"),
4488            other => panic!("expected calendar, got {other:?}"),
4489        }
4490    }
4491
4492    #[test]
4493    fn when_calendar_datetime_parses_all_separators() {
4494        // one-shot: date+time in hyphen / ISO-T / slash forms
4495        for at in ["2026-06-10 09:00", "2026-06-10T09:00", "2026/06/10 09:00"] {
4496            let block = format!("  calendar:\n    at: \"{at}\"");
4497            let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(&block))
4498                .unwrap_or_else(|e| panic!("parse '{at}': {e}"));
4499            match &s.when {
4500                When::Calendar(c) => {
4501                    use chrono::Datelike;
4502                    let p = c.parse_at().expect("parse_at");
4503                    let d = p.date.expect("datetime at carries a date");
4504                    assert_eq!((d.year(), d.month(), d.day()), (2026, 6, 10), "for '{at}'");
4505                }
4506                other => panic!("expected calendar, got {other:?}"),
4507            }
4508        }
4509    }
4510
4511    #[test]
4512    fn when_rejects_bad_once_keyword() {
4513        // `onec` must be a parse error, not a silently-absorbed
4514        // string (OnceLiteral is a single-variant enum for exactly
4515        // this reason).
4516        let r: Result<Schedule, _> = serde_yaml::from_str(&schedule_yaml_with("  per_pc: onec"));
4517        assert!(r.is_err(), "expected parse error, got {r:?}");
4518    }
4519
4520    #[test]
4521    fn when_rejects_unknown_key_in_every() {
4522        // `{ evry: 6h }` still fails on the tolerant read path: the
4523        // required `every` key is missing, so no PerPolicy variant
4524        // matches (#492 removed deny_unknown_fields, but required
4525        // keys keep the untagged disambiguation honest).
4526        let r: Result<Schedule, _> =
4527            serde_yaml::from_str(&schedule_yaml_with("  per_pc: { evry: 6h }"));
4528        assert!(r.is_err(), "expected parse error, got {r:?}");
4529    }
4530
4531    #[test]
4532    fn when_rejects_unknown_variant() {
4533        let r: Result<Schedule, _> =
4534            serde_yaml::from_str(&schedule_yaml_with("  per_galaxy: once"));
4535        assert!(r.is_err(), "expected parse error, got {r:?}");
4536    }
4537
4538    #[test]
4539    fn when_rejects_old_top_level_cron_field() {
4540        // Pre-#418 shape: top-level `cron:` + no `when:`. Must fail
4541        // loudly (missing `when`), which is what turns stale KV
4542        // blobs into warn-skips after the upgrade.
4543        let yaml = r#"
4544id: x
4545cron: "* * * * * *"
4546job_id: y
4547target: { all: true }
4548"#;
4549        let r: Result<Schedule, _> = serde_yaml::from_str(yaml);
4550        assert!(r.is_err(), "expected parse error, got {r:?}");
4551    }
4552
4553    #[test]
4554    fn when_rejects_retired_cron_escape_hatch() {
4555        // #418 Phase 2 retired `when: { cron: "..." }`. A raw cron
4556        // is now an unknown variant → parse error (operators use the
4557        // calendar form instead).
4558        let r: Result<Schedule, _> =
4559            serde_yaml::from_str(&schedule_yaml_with("  cron: \"0 0 9 * * mon-fri\""));
4560        assert!(
4561            r.is_err(),
4562            "expected parse error for retired cron, got {r:?}"
4563        );
4564    }
4565
4566    #[test]
4567    fn when_round_trips_json_and_yaml() {
4568        // Round-trip through the full Schedule: that is the wire
4569        // unit for both stores (JSON catalog KV + YAML mirror), and
4570        // it exercises the singleton_map field attribute that keeps
4571        // serde_yaml on the map shape instead of `!per_pc` tags.
4572        for when in [
4573            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
4574            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
4575            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
4576            When::PerTarget(PerPolicy::Every(EverySpec {
4577                every: "24h".into(),
4578            })),
4579            calendar("09:00", &["mon-fri"]),
4580            calendar("2026-06-10 09:00", &[]),
4581            When::On(vec![OnTrigger::Startup]),
4582            When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
4583            When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
4584            When::On(vec![OnTrigger::NetworkChange]),
4585        ] {
4586            // Event triggers are agent-only; the rest validate on backend.
4587            let runs_on = if matches!(when, When::On(_)) {
4588                RunsOn::Agent
4589            } else {
4590                RunsOn::Backend
4591            };
4592            let s = schedule_with(when.clone(), runs_on);
4593
4594            let json = serde_json::to_string(&s).expect("json serialise");
4595            let back: Schedule = serde_json::from_str(&json).expect("json deserialise");
4596            assert_eq!(back.when, when, "json round-trip for {when}");
4597
4598            let yaml = serde_yaml::to_string(&s).expect("yaml serialise");
4599            assert!(
4600                !yaml.contains('!'),
4601                "yaml must use the map shape, not tags: {yaml}"
4602            );
4603            let back: Schedule = serde_yaml::from_str(&yaml).expect("yaml deserialise");
4604            assert_eq!(back.when, when, "yaml round-trip for {when}");
4605        }
4606    }
4607
4608    #[test]
4609    fn when_once_serialises_as_bare_keyword() {
4610        // The wire shape operators see in the YAML mirror must stay
4611        // the ergonomic `per_pc: once`, not a one-variant map.
4612        let json = serde_json::to_value(When::PerPc(PerPolicy::Once(OnceLiteral::Once)))
4613            .expect("serialise");
4614        assert_eq!(json, serde_json::json!({ "per_pc": "once" }));
4615    }
4616
4617    #[test]
4618    fn when_displays_operator_summary() {
4619        for (when, expected) in [
4620            (
4621                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
4622                "per_pc once",
4623            ),
4624            (
4625                When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
4626                "per_pc every 6h",
4627            ),
4628            (
4629                When::PerTarget(PerPolicy::Every(EverySpec {
4630                    every: "24h".into(),
4631                })),
4632                "per_target every 24h",
4633            ),
4634            (calendar("09:00", &["mon-fri"]), "at 09:00 [mon-fri]"),
4635            (calendar("2026-06-10 09:00", &[]), "at 2026-06-10 09:00"),
4636            (When::On(vec![OnTrigger::Startup]), "on [startup]"),
4637            (
4638                When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
4639                "on [startup,logon]",
4640            ),
4641            (
4642                When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
4643                "on [lock,unlock]",
4644            ),
4645            (
4646                When::On(vec![OnTrigger::NetworkChange]),
4647                "on [network_change]",
4648            ),
4649        ] {
4650            assert_eq!(when.to_string(), expected);
4651        }
4652    }
4653
4654    // ---- lowering (#418: when → engine vocabulary) ----
4655
4656    fn schedule_with(when: When, runs_on: RunsOn) -> Schedule {
4657        Schedule {
4658            id: "x".into(),
4659            when,
4660            job_id: "y".into(),
4661            // #917: validate() now rejects a target that dispatches
4662            // nothing, so the baseline helper carries the simplest
4663            // specified target.
4664            plan: FanoutPlan {
4665                target: Target {
4666                    all: true,
4667                    ..Target::default()
4668                },
4669                ..FanoutPlan::default()
4670            },
4671            active: Active::default(),
4672            constraints: Constraints::default(),
4673            on_failure: OnFailure::default(),
4674            tz: ScheduleTz::default(),
4675            starting_deadline: None,
4676            runs_on,
4677            enabled: true,
4678            tags: Vec::new(),
4679            origin: None,
4680        }
4681    }
4682
4683    fn calendar(at: &str, days: &[&str]) -> When {
4684        When::Calendar(CalendarSpec {
4685            at: at.into(),
4686            days: days.iter().map(|d| (*d).to_string()).collect(),
4687        })
4688    }
4689
4690    #[test]
4691    fn next_calendar_fire_returns_next_utc_occurrence() {
4692        use chrono::TimeZone;
4693        // Daily 09:00, evaluated in UTC. From 08:00 the same day, the
4694        // next strict occurrence is 09:00 that day.
4695        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
4696        s.tz = ScheduleTz::Utc;
4697        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 8, 0, 0).unwrap();
4698        let next = s.next_calendar_fire(now).expect("calendar has a next fire");
4699        assert_eq!(
4700            next,
4701            chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap()
4702        );
4703    }
4704
4705    #[test]
4706    fn next_calendar_fire_is_strictly_after_now() {
4707        use chrono::TimeZone;
4708        // Standing exactly on a fire instant must preview the *next*
4709        // one (inclusive = false), not the one firing right now.
4710        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
4711        s.tz = ScheduleTz::Utc;
4712        let on_fire = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap();
4713        let next = s
4714            .next_calendar_fire(on_fire)
4715            .expect("calendar has a next fire");
4716        assert_eq!(
4717            next,
4718            chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()
4719        );
4720    }
4721
4722    #[test]
4723    fn next_calendar_fire_none_for_reconcile_shapes() {
4724        // `per_pc` / `per_target` lower to the every-minute poll cron —
4725        // no discrete upcoming event to preview, so `None`.
4726        let now = chrono::Utc::now();
4727        for when in [
4728            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
4729            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
4730            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
4731            When::PerTarget(PerPolicy::Every(EverySpec {
4732                every: "24h".into(),
4733            })),
4734        ] {
4735            let s = schedule_with(when, RunsOn::Backend);
4736            assert!(
4737                s.next_calendar_fire(now).is_none(),
4738                "reconcile shapes have no calendar fire",
4739            );
4740        }
4741    }
4742
4743    // ---- preview_fires (#418 dry-run / preview) ----
4744
4745    fn cal_utc(at: &str, days: &[&str]) -> Schedule {
4746        let mut s = schedule_with(calendar(at, days), RunsOn::Backend);
4747        s.tz = ScheduleTz::Utc; // host-independent assertions
4748        s
4749    }
4750
4751    #[test]
4752    fn preview_lists_next_calendar_occurrences() {
4753        use chrono::TimeZone;
4754        // Weekday 09:00, from Wed 2026-06-10 00:00 UTC: the next five
4755        // fires skip the weekend (Sat 13 / Sun 14).
4756        let s = cal_utc("09:00", &["mon-fri"]);
4757        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
4758        let got = s.preview_fires(now, 5);
4759        let want: Vec<_> = [
4760            (2026, 6, 10), // Wed
4761            (2026, 6, 11), // Thu
4762            (2026, 6, 12), // Fri
4763            (2026, 6, 15), // Mon (skips Sat 13 / Sun 14)
4764            (2026, 6, 16), // Tue
4765        ]
4766        .iter()
4767        .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
4768        .collect();
4769        assert_eq!(got, want);
4770    }
4771
4772    #[test]
4773    fn preview_handles_nth_and_last_weekday() {
4774        use chrono::TimeZone;
4775        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
4776        // 2nd Tuesday (Patch Tuesday): Jun 9, Jul 14 2026.
4777        let nth = cal_utc("09:00", &["tue#2"]).preview_fires(now, 2);
4778        assert_eq!(
4779            nth,
4780            vec![
4781                chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap(),
4782                chrono::Utc.with_ymd_and_hms(2026, 7, 14, 9, 0, 0).unwrap(),
4783            ]
4784        );
4785        // Last Friday of the month: Jun 26, Jul 31 2026.
4786        let last = cal_utc("22:00", &["friL"]).preview_fires(now, 2);
4787        assert_eq!(
4788            last,
4789            vec![
4790                chrono::Utc.with_ymd_and_hms(2026, 6, 26, 22, 0, 0).unwrap(),
4791                chrono::Utc.with_ymd_and_hms(2026, 7, 31, 22, 0, 0).unwrap(),
4792            ]
4793        );
4794    }
4795
4796    #[test]
4797    fn preview_is_empty_for_reconcile_and_zero_count() {
4798        let now = chrono::Utc::now();
4799        // reconcile shapes have no discrete fire times
4800        let recon = schedule_with(
4801            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
4802            RunsOn::Backend,
4803        );
4804        assert!(recon.preview_fires(now, 5).is_empty());
4805        // count == 0 yields nothing even for a calendar
4806        assert!(cal_utc("09:00", &[]).preview_fires(now, 0).is_empty());
4807    }
4808
4809    #[test]
4810    fn preview_skips_outside_active_window() {
4811        use chrono::TimeZone;
4812        // Daily 09:00, active only [2026-06-15, 2026-06-17). Occurrences
4813        // before `from` are skipped; `until` is exclusive, so 06-17's
4814        // fire is out — leaving exactly the 15th and 16th.
4815        let mut s = cal_utc("09:00", &[]);
4816        s.active = Active {
4817            from: Some("2026-06-15".into()),
4818            until: Some("2026-06-17".into()),
4819        };
4820        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
4821        let got = s.preview_fires(now, 5);
4822        assert_eq!(
4823            got,
4824            vec![
4825                chrono::Utc.with_ymd_and_hms(2026, 6, 15, 9, 0, 0).unwrap(),
4826                chrono::Utc.with_ymd_and_hms(2026, 6, 16, 9, 0, 0).unwrap(),
4827            ]
4828        );
4829    }
4830
4831    #[test]
4832    fn preview_empty_when_calendar_time_outside_window() {
4833        use chrono::TimeZone;
4834        // Fires at 09:00 but the maintenance window is overnight — it can
4835        // never run, so the preview is empty (matches
4836        // `calendar_outside_window`), and the scan still terminates.
4837        let mut s = cal_utc("09:00", &[]);
4838        s.constraints = Constraints {
4839            window: Some("22:00-05:00".into()),
4840            ..Constraints::default()
4841        };
4842        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
4843        assert!(s.preview_fires(now, 5).is_empty());
4844        // Every candidate tick is rejected, so this also exercises the
4845        // SCAN_CAP bound: a large `count` must still terminate (and
4846        // return empty) rather than spin (claude #578 review).
4847        assert!(s.preview_fires(now, 50).is_empty());
4848    }
4849
4850    #[test]
4851    fn preview_past_one_shot_is_empty() {
4852        use chrono::TimeZone;
4853        // A dated one-shot whose instant has passed never fires again.
4854        let s = cal_utc("2026-06-10 09:00", &[]);
4855        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 0, 0, 0).unwrap();
4856        assert!(s.preview_fires(now, 5).is_empty());
4857        // …but from before it, the single future fire shows up.
4858        let before = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
4859        assert_eq!(
4860            s.preview_fires(before, 5),
4861            vec![chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()]
4862        );
4863    }
4864
4865    #[test]
4866    fn lowering_matches_the_418_table() {
4867        let cases = [
4868            (
4869                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
4870                (POLL_CRON, ExecMode::OncePerPc, None),
4871            ),
4872            (
4873                When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
4874                (POLL_CRON, ExecMode::OncePerPc, Some("6h")),
4875            ),
4876            (
4877                When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
4878                (POLL_CRON, ExecMode::OncePerTarget, None),
4879            ),
4880            (
4881                When::PerTarget(PerPolicy::Every(EverySpec {
4882                    every: "24h".into(),
4883                })),
4884                (POLL_CRON, ExecMode::OncePerTarget, Some("24h")),
4885            ),
4886            // calendar repeating → 6-field cron
4887            (
4888                calendar("09:00", &["mon-fri"]),
4889                ("0 0 9 * * mon-fri", ExecMode::EveryTick, None),
4890            ),
4891            // calendar daily (no days) → DOW *
4892            (
4893                calendar("18:30", &[]),
4894                ("0 30 18 * * *", ExecMode::EveryTick, None),
4895            ),
4896            // calendar one-shot → 7-field year cron
4897            (
4898                calendar("2026-06-10 09:00", &[]),
4899                ("0 0 9 10 6 * 2026", ExecMode::EveryTick, None),
4900            ),
4901        ];
4902        for (when, (cron, mode, cooldown)) in cases {
4903            let l = schedule_with(when.clone(), RunsOn::Backend).lowered();
4904            assert_eq!(l.cron, cron, "cron for {when}");
4905            assert_eq!(l.mode, mode, "mode for {when}");
4906            assert_eq!(l.cooldown.as_deref(), cooldown, "cooldown for {when}");
4907        }
4908    }
4909
4910    #[test]
4911    fn lowered_carries_schedule_tz() {
4912        for (tz, want) in [
4913            (ScheduleTz::Local, ScheduleTz::Local),
4914            (ScheduleTz::Utc, ScheduleTz::Utc),
4915        ] {
4916            let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
4917            s.tz = tz;
4918            assert_eq!(s.lowered().tz, want, "calendar carries tz");
4919            // reconcile shapes carry tz too (for the active-window check)
4920            let mut s = schedule_with(
4921                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
4922                RunsOn::Backend,
4923            );
4924            s.tz = tz;
4925            assert_eq!(s.lowered().tz, want, "reconcile carries tz");
4926        }
4927    }
4928
4929    #[test]
4930    fn poll_cron_is_accepted_by_the_engine_parser() {
4931        // POLL_CRON is system-generated — if the engine's parser
4932        // ever rejected it every reconcile schedule would die at
4933        // register time. Validate it with the same croner config
4934        // (Seconds::Required, dom_and_dow, year optional).
4935        croner::parser::CronParser::builder()
4936            .seconds(croner::parser::Seconds::Required)
4937            .dom_and_dow(true)
4938            .build()
4939            .parse(POLL_CRON)
4940            .expect("POLL_CRON must parse");
4941    }
4942
4943    // ---- Schedule::validate() (#418 decision F) ----
4944
4945    #[test]
4946    fn validate_accepts_reconcile_shapes() {
4947        for when in [
4948            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
4949            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
4950            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
4951            When::PerTarget(PerPolicy::Every(EverySpec {
4952                every: "24h".into(),
4953            })),
4954        ] {
4955            schedule_with(when.clone(), RunsOn::Backend)
4956                .validate()
4957                .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
4958        }
4959    }
4960
4961    #[test]
4962    fn validate_accepts_per_pc_on_agent() {
4963        schedule_with(
4964            When::PerPc(PerPolicy::Every(EverySpec { every: "1h".into() })),
4965            RunsOn::Agent,
4966        )
4967        .validate()
4968        .expect("per_pc + agent is the offline-inventory shape");
4969    }
4970
4971    // ---- #418 event triggers (when: { on }) ----
4972
4973    #[test]
4974    fn validate_accepts_event_on_agent() {
4975        for triggers in [
4976            vec![OnTrigger::Startup],
4977            vec![OnTrigger::Logon],
4978            vec![OnTrigger::Lock],
4979            vec![OnTrigger::Unlock],
4980            vec![OnTrigger::NetworkChange],
4981            vec![
4982                OnTrigger::Startup,
4983                OnTrigger::Logon,
4984                OnTrigger::Lock,
4985                OnTrigger::Unlock,
4986                OnTrigger::NetworkChange,
4987            ],
4988        ] {
4989            schedule_with(When::On(triggers), RunsOn::Agent)
4990                .validate()
4991                .expect("when.on is valid on runs_on: agent");
4992        }
4993    }
4994
4995    #[test]
4996    fn validate_rejects_event_on_backend() {
4997        let err = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Backend)
4998            .validate()
4999            .unwrap_err();
5000        assert!(err.contains("when.on"), "got: {err}");
5001        assert!(err.contains("runs_on: agent"), "got: {err}");
5002    }
5003
5004    #[test]
5005    fn validate_rejects_empty_event_list() {
5006        let err = schedule_with(When::On(vec![]), RunsOn::Agent)
5007            .validate()
5008            .unwrap_err();
5009        assert!(err.contains("when.on"), "got: {err}");
5010        assert!(err.contains("at least one"), "got: {err}");
5011    }
5012
5013    #[test]
5014    fn event_schedule_lowers_to_event_mode_and_is_event() {
5015        let s = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Agent);
5016        assert!(s.is_event());
5017        assert_eq!(s.lowered().mode, ExecMode::Event);
5018        assert_eq!(s.event_triggers(), &[OnTrigger::Startup]);
5019        // non-event schedules report no triggers.
5020        let cal = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5021        assert!(!cal.is_event());
5022        assert!(cal.event_triggers().is_empty());
5023    }
5024
5025    // ---- #418 constraints.require (env gates) ----
5026
5027    fn require_schedule(req: Require, runs_on: RunsOn) -> Schedule {
5028        let mut s = schedule_with(
5029            When::PerPc(PerPolicy::Every(EverySpec { every: "1m".into() })),
5030            runs_on,
5031        );
5032        s.constraints.require = Some(req);
5033        s
5034    }
5035
5036    #[test]
5037    fn require_met_combinations() {
5038        use std::time::Duration;
5039        let idle = |m: u64| Some(Duration::from_secs(m * 60));
5040        // Builder for the sensed state: (ac, idle, cpu, network).
5041        let env = |ac, idle, cpu, net| EnvState {
5042            ac_online: ac,
5043            idle,
5044            cpu_pct: cpu,
5045            network_up: net,
5046        };
5047        // Empty require — always met regardless of sensed state.
5048        assert!(require_met(
5049            &Require::default(),
5050            &env(false, None, None, false)
5051        ));
5052        // ac_power: only on AC.
5053        let ac = Require {
5054            ac_power: true,
5055            ..Default::default()
5056        };
5057        assert!(!require_met(&ac, &env(false, None, None, true)));
5058        assert!(require_met(&ac, &env(true, None, None, false)));
5059        // idle: needs >= the configured min; None idle never satisfies.
5060        let idle10 = Require {
5061            idle: Some("10m".into()),
5062            ..Default::default()
5063        };
5064        assert!(!require_met(&idle10, &env(true, None, None, true)));
5065        assert!(!require_met(&idle10, &env(true, idle(5), None, true)));
5066        assert!(require_met(&idle10, &env(true, idle(15), None, true)));
5067        assert!(require_met(&idle10, &env(true, idle(10), None, true))); // boundary inclusive
5068        // cpu_below: needs CPU strictly < threshold; None cpu never satisfies.
5069        let cpu20 = Require {
5070            cpu_below: Some(20.0),
5071            ..Default::default()
5072        };
5073        assert!(!require_met(&cpu20, &env(true, None, None, true))); // no sample → fail-closed
5074        assert!(!require_met(&cpu20, &env(true, None, Some(20.0), true))); // == threshold
5075        assert!(!require_met(&cpu20, &env(true, None, Some(55.0), true))); // busy
5076        assert!(require_met(&cpu20, &env(true, None, Some(5.0), true))); // quiet
5077        // network: only when online.
5078        let net = Require {
5079            network: true,
5080            ..Default::default()
5081        };
5082        assert!(!require_met(&net, &env(true, None, None, false))); // offline
5083        assert!(require_met(&net, &env(true, None, None, true))); // online
5084        // all four: AND.
5085        let all = Require {
5086            ac_power: true,
5087            idle: Some("10m".into()),
5088            cpu_below: Some(20.0),
5089            network: true,
5090        };
5091        assert!(!require_met(&all, &env(false, idle(20), Some(5.0), true))); // on battery
5092        assert!(!require_met(&all, &env(true, idle(1), Some(5.0), true))); // not idle enough
5093        assert!(!require_met(&all, &env(true, idle(20), Some(50.0), true))); // busy
5094        assert!(!require_met(&all, &env(true, idle(20), Some(5.0), false))); // offline
5095        assert!(require_met(&all, &env(true, idle(20), Some(5.0), true)));
5096        // An unparseable idle is treated as no-requirement by require_met
5097        // (validate rejects it at create time, so this only guards a
5098        // hand-edited blob): ac still gates.
5099        let bad = Require {
5100            ac_power: true,
5101            idle: Some("garbage".into()),
5102            ..Default::default()
5103        };
5104        assert!(require_met(&bad, &env(true, None, None, true)));
5105        assert!(!require_met(&bad, &env(false, None, None, true)));
5106    }
5107
5108    #[test]
5109    fn validate_accepts_and_rejects_cpu_below() {
5110        // In-range accepted.
5111        require_schedule(
5112            Require {
5113                cpu_below: Some(20.0),
5114                ..Default::default()
5115            },
5116            RunsOn::Agent,
5117        )
5118        .validate()
5119        .expect("cpu_below 20 is valid");
5120        // Upper boundary: 100.0 is accepted (fires unless CPU is exactly
5121        // 100%). Pins the inclusive upper bound against a future c < 100.0.
5122        require_schedule(
5123            Require {
5124                cpu_below: Some(100.0),
5125                ..Default::default()
5126            },
5127            RunsOn::Agent,
5128        )
5129        .validate()
5130        .expect("cpu_below 100 is valid");
5131        // Out of range rejected (0 and >100).
5132        for bad in [0.0, -5.0, 100.1] {
5133            let err = require_schedule(
5134                Require {
5135                    cpu_below: Some(bad),
5136                    ..Default::default()
5137                },
5138                RunsOn::Agent,
5139            )
5140            .validate()
5141            .unwrap_err();
5142            assert!(
5143                err.contains("constraints.require.cpu_below"),
5144                "cpu_below {bad}: {err}"
5145            );
5146        }
5147    }
5148
5149    #[test]
5150    fn validate_accepts_require_on_agent() {
5151        require_schedule(
5152            Require {
5153                ac_power: true,
5154                idle: Some("10m".into()),
5155                cpu_below: Some(20.0),
5156                network: true,
5157            },
5158            RunsOn::Agent,
5159        )
5160        .validate()
5161        .expect("constraints.require is valid on runs_on: agent");
5162    }
5163
5164    #[test]
5165    fn validate_rejects_require_on_backend() {
5166        let err = require_schedule(
5167            Require {
5168                ac_power: true,
5169                ..Default::default()
5170            },
5171            RunsOn::Backend,
5172        )
5173        .validate()
5174        .unwrap_err();
5175        assert!(err.contains("constraints.require"), "got: {err}");
5176        assert!(err.contains("runs_on: agent"), "got: {err}");
5177
5178        // An idle-only require (ac_power: false) is also non-empty
5179        // (is_empty folds the fields) and must reject on backend too —
5180        // guards against a regression in Require::is_empty.
5181        let err = require_schedule(
5182            Require {
5183                idle: Some("10m".into()),
5184                ..Default::default()
5185            },
5186            RunsOn::Backend,
5187        )
5188        .validate()
5189        .unwrap_err();
5190        assert!(
5191            err.contains("constraints.require"),
5192            "idle-only on backend: {err}"
5193        );
5194    }
5195
5196    #[test]
5197    fn validate_rejects_bad_require_idle() {
5198        let err = require_schedule(
5199            Require {
5200                idle: Some("not-a-duration".into()),
5201                ..Default::default()
5202            },
5203            RunsOn::Agent,
5204        )
5205        .validate()
5206        .unwrap_err();
5207        assert!(err.contains("constraints.require.idle"), "got: {err}");
5208    }
5209
5210    #[test]
5211    fn require_round_trips_and_skips_empty() {
5212        // ac_power: false is skipped; an all-default require nested in
5213        // constraints is omitted (is_empty folds it in).
5214        let yaml = "id: s\nwhen: { per_pc: { every: 1m } }\njob_id: j\nruns_on: agent\n\
5215                    constraints: { require: { ac_power: true, idle: 10m, cpu_below: 20, \
5216                    network: true } }\n";
5217        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5218        let req = s.constraints.require.as_ref().expect("require present");
5219        assert!(req.ac_power);
5220        assert_eq!(req.idle.as_deref(), Some("10m"));
5221        assert_eq!(req.cpu_below, Some(20.0));
5222        assert!(req.network);
5223        // Re-serialize: idle + cpu_below + network present, ac_power true.
5224        let back = serde_json::to_string(&s.constraints).unwrap();
5225        assert!(back.contains("\"idle\":\"10m\""), "got: {back}");
5226        assert!(back.contains("\"cpu_below\":20"), "got: {back}");
5227        assert!(back.contains("\"network\":true"), "got: {back}");
5228        // An empty require is omitted entirely by is_empty.
5229        let mut empty = s.clone();
5230        empty.constraints.require = Some(Require::default());
5231        assert!(empty.constraints.is_empty());
5232    }
5233
5234    #[test]
5235    fn validate_rejects_per_target_on_agent() {
5236        let err = schedule_with(
5237            When::PerTarget(PerPolicy::Every(EverySpec {
5238                every: "24h".into(),
5239            })),
5240            RunsOn::Agent,
5241        )
5242        .validate()
5243        .unwrap_err();
5244        assert!(err.contains("per_target"), "got: {err}");
5245        assert!(err.contains("runs_on: agent"), "got: {err}");
5246
5247        // per_target: once is also backend-only.
5248        let err = schedule_with(
5249            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5250            RunsOn::Agent,
5251        )
5252        .validate()
5253        .unwrap_err();
5254        assert!(err.contains("per_target"), "got (once): {err}");
5255        assert!(err.contains("runs_on: agent"), "got (once): {err}");
5256    }
5257
5258    #[test]
5259    fn validate_rejects_bad_every_duration() {
5260        let err = schedule_with(
5261            When::PerPc(PerPolicy::Every(EverySpec { every: "6x".into() })),
5262            RunsOn::Backend,
5263        )
5264        .validate()
5265        .unwrap_err();
5266        assert!(err.contains("when.every"), "got: {err}");
5267    }
5268
5269    #[test]
5270    fn validate_rejects_bad_jitter_and_starting_deadline() {
5271        let mut s = schedule_with(
5272            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5273            RunsOn::Backend,
5274        );
5275        s.plan.jitter = Some("5x".into());
5276        let err = s.validate().unwrap_err();
5277        assert!(err.contains("jitter"), "got: {err}");
5278
5279        let mut s = schedule_with(
5280            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5281            RunsOn::Backend,
5282        );
5283        s.starting_deadline = Some("soon".into());
5284        let err = s.validate().unwrap_err();
5285        assert!(err.contains("starting_deadline"), "got: {err}");
5286    }
5287
5288    #[test]
5289    fn validate_rejects_unspecified_target() {
5290        // #917 (1): an all-default target never dispatches anywhere —
5291        // runs_on: agent silently never fires, runs_on: backend
5292        // warn-fails every tick at the exec boundary. Both rejected.
5293        for runs_on in [RunsOn::Backend, RunsOn::Agent] {
5294            let mut s = schedule_with(When::PerPc(PerPolicy::Once(OnceLiteral::Once)), runs_on);
5295            s.plan.target = Target::default();
5296            let err = s.validate().unwrap_err();
5297            assert!(err.contains("target"), "for {runs_on:?}, got: {err}");
5298        }
5299    }
5300
5301    #[test]
5302    fn validate_accepts_waves_instead_of_target_on_backend() {
5303        // #917 (1): the exec boundary accepts rollout-only plans
5304        // (target then just labels the audit row) — so does validate.
5305        let mut s = schedule_with(
5306            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5307            RunsOn::Backend,
5308        );
5309        s.plan.target = Target::default();
5310        s.plan.rollout = Some(Rollout {
5311            strategy: RolloutStrategy::Wave,
5312            waves: vec![Wave {
5313                group: "canary".into(),
5314                delay: "0s".into(),
5315            }],
5316        });
5317        s.validate().expect("rollout-only plan should validate");
5318    }
5319
5320    #[test]
5321    fn validate_rejects_rollout_on_agent() {
5322        // #917 (1): rollout waves are backend-published; a runs_on:
5323        // agent schedule never reads them, so the combination is a
5324        // silent no-op — reject like max_concurrent-on-agent.
5325        let mut s = schedule_with(
5326            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5327            RunsOn::Agent,
5328        );
5329        s.plan.rollout = Some(Rollout {
5330            strategy: RolloutStrategy::Wave,
5331            waves: vec![Wave {
5332                group: "canary".into(),
5333                delay: "0s".into(),
5334            }],
5335        });
5336        let err = s.validate().unwrap_err();
5337        assert!(err.contains("rollout"), "got: {err}");
5338    }
5339
5340    #[test]
5341    fn validate_rejects_bad_waves() {
5342        // #917 (2): empty waves, blank group, unparseable delay — all
5343        // previously accepted and failed (or no-opped) at every fire.
5344        let base = || {
5345            schedule_with(
5346                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5347                RunsOn::Backend,
5348            )
5349        };
5350
5351        let mut s = base();
5352        s.plan.rollout = Some(Rollout {
5353            strategy: RolloutStrategy::Wave,
5354            waves: vec![],
5355        });
5356        let err = s.validate().unwrap_err();
5357        assert!(err.contains("at least one wave"), "got: {err}");
5358
5359        let mut s = base();
5360        s.plan.rollout = Some(Rollout {
5361            strategy: RolloutStrategy::Wave,
5362            waves: vec![Wave {
5363                group: "  ".into(),
5364                delay: "0s".into(),
5365            }],
5366        });
5367        let err = s.validate().unwrap_err();
5368        assert!(err.contains("waves[0].group"), "got: {err}");
5369
5370        let mut s = base();
5371        s.plan.rollout = Some(Rollout {
5372            strategy: RolloutStrategy::Wave,
5373            waves: vec![
5374                Wave {
5375                    group: "canary".into(),
5376                    delay: "0s".into(),
5377                },
5378                Wave {
5379                    group: "wave1".into(),
5380                    delay: "5 minuts".into(),
5381                },
5382            ],
5383        });
5384        let err = s.validate().unwrap_err();
5385        assert!(err.contains("waves[1].delay"), "got: {err}");
5386    }
5387
5388    #[test]
5389    fn validate_rejects_wave_delay_at_or_past_starting_deadline() {
5390        // #917 (3): the deadline is stamped once at tick time, so a
5391        // wave sleeping >= starting_deadline publishes already-expired
5392        // Commands — dead on arrival, every fire.
5393        let mut s = schedule_with(
5394            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5395            RunsOn::Backend,
5396        );
5397        s.starting_deadline = Some("30m".into());
5398        s.plan.rollout = Some(Rollout {
5399            strategy: RolloutStrategy::Wave,
5400            waves: vec![
5401                Wave {
5402                    group: "canary".into(),
5403                    delay: "0s".into(),
5404                },
5405                Wave {
5406                    group: "wave1".into(),
5407                    delay: "30m".into(),
5408                },
5409            ],
5410        });
5411        let err = s.validate().unwrap_err();
5412        assert!(
5413            err.contains("waves[1].delay") && err.contains("starting_deadline"),
5414            "got: {err}"
5415        );
5416
5417        // Strictly shorter is fine.
5418        s.plan.rollout.as_mut().unwrap().waves[1].delay = "29m".into();
5419        s.validate().expect("delay < deadline should validate");
5420    }
5421
5422    #[test]
5423    fn validate_rejects_operator_set_deadline_at() {
5424        // #917 (4): machine-stamped field — the scheduler overwrites it
5425        // on every fire, so a hand-set value is silently discarded.
5426        let mut s = schedule_with(
5427            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5428            RunsOn::Backend,
5429        );
5430        s.plan.deadline_at = Some(chrono::Utc::now());
5431        let err = s.validate().unwrap_err();
5432        assert!(
5433            err.contains("deadline_at") && err.contains("starting_deadline"),
5434            "got: {err}"
5435        );
5436    }
5437
5438    #[test]
5439    fn validate_accepts_calendar_shapes() {
5440        for when in [
5441            calendar("09:00", &["mon-fri"]),   // weekday morning
5442            calendar("00:00", &["sun"]),       // weekly
5443            calendar("18:30", &[]),            // daily
5444            calendar("2026-06-10 09:00", &[]), // one-shot
5445            calendar("2026/12/25 00:00", &[]), // one-shot, slash form
5446        ] {
5447            schedule_with(when.clone(), RunsOn::Backend)
5448                .validate()
5449                .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
5450        }
5451    }
5452
5453    #[test]
5454    fn validate_rejects_bad_at() {
5455        for bad in ["25:00", "09:60", "9", "noon", "2026-13-01 09:00"] {
5456            let err = schedule_with(calendar(bad, &[]), RunsOn::Backend)
5457                .validate()
5458                .unwrap_err();
5459            assert!(err.contains("when.at"), "for '{bad}', got: {err}");
5460        }
5461    }
5462
5463    #[test]
5464    fn validate_rejects_datetime_at_with_days() {
5465        // A dated `at` is a one-shot — pairing it with days is a
5466        // contradiction (the date already pins the day).
5467        let err = schedule_with(calendar("2026-06-10 09:00", &["mon"]), RunsOn::Backend)
5468            .validate()
5469            .unwrap_err();
5470        assert!(
5471            err.contains("one-shot") && err.contains("days"),
5472            "got: {err}"
5473        );
5474    }
5475
5476    #[test]
5477    fn validate_rejects_bad_day_name() {
5478        // A garbage DOW token is caught by the days pre-flight and
5479        // reported against `when.days`, not the confusing
5480        // "when.at lowered to invalid cron" (claude #432 review).
5481        let err = schedule_with(calendar("09:00", &["funday"]), RunsOn::Backend)
5482            .validate()
5483            .unwrap_err();
5484        assert!(err.contains("when.days"), "got: {err}");
5485        assert!(err.contains("funday"), "names the bad token: {err}");
5486        // a degenerate range like `mon-` reports the whole token, not
5487        // a cryptic empty part (claude #432 follow-up)
5488        let err = schedule_with(calendar("09:00", &["mon-"]), RunsOn::Backend)
5489            .validate()
5490            .unwrap_err();
5491        assert!(err.contains("'mon-'"), "names the whole token: {err}");
5492        // valid names / ranges / numeric / * all pass
5493        for ok in [
5494            calendar("09:00", &["mon-fri"]),
5495            calendar("09:00", &["mon", "wed", "sun"]),
5496            calendar("09:00", &["1-5"]),
5497        ] {
5498            schedule_with(ok.clone(), RunsOn::Backend)
5499                .validate()
5500                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
5501        }
5502    }
5503
5504    #[test]
5505    fn validate_accepts_nth_weekday() {
5506        // #418: nth-weekday (Patch Tuesday). validate() also lowers to
5507        // a cron and parses it with croner, so passing here proves the
5508        // whole chain — token → DOW field → engine-acceptable cron.
5509        for ok in [
5510            calendar("09:00", &["tue#2"]),          // 2nd Tuesday
5511            calendar("09:00", &["fri#1"]),          // 1st Friday
5512            calendar("03:00", &["sun#5"]),          // 5th Sunday
5513            calendar("09:00", &["tue#2", "thu#2"]), // a list of nths
5514            calendar("09:00", &["2#2"]),            // numeric DOW + ordinal
5515            // Case-insensitive both sides: validate lowercases, croner
5516            // upper-cases the whole pattern before aliasing (claude #547).
5517            calendar("09:00", &["TUE#2"]),
5518        ] {
5519            schedule_with(ok.clone(), RunsOn::Backend)
5520                .validate()
5521                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
5522        }
5523    }
5524
5525    #[test]
5526    fn validate_rejects_bad_nth_weekday() {
5527        // ordinal out of 1..5, a range with #, and a bad day before #.
5528        for bad in ["tue#0", "tue#6", "tue#x", "mon-fri#2", "funday#2"] {
5529            let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
5530                .validate()
5531                .unwrap_err();
5532            assert!(err.contains("when.days"), "for '{bad}', got: {err}");
5533        }
5534    }
5535
5536    #[test]
5537    fn validate_accepts_last_weekday() {
5538        // #418: last-weekday (`friL` = last Friday). Like the nth case,
5539        // validate() lowers to a cron and round-trips it through croner,
5540        // so passing proves token → DOW field → engine-acceptable cron
5541        // with the verified last-<dow>-of-month semantics.
5542        for ok in [
5543            calendar("09:00", &["friL"]),         // last Friday
5544            calendar("03:00", &["sunL"]),         // last Sunday
5545            calendar("22:00", &["5L"]),           // numeric DOW + last
5546            calendar("00:00", &["0L"]),           // numeric Sunday (0…
5547            calendar("00:00", &["7L"]),           // …and its 7 alias)
5548            calendar("09:00", &["monL", "friL"]), // a list of last-weekdays
5549            // Case-insensitive both the weekday and the `L` suffix:
5550            // validate lowercases the day, croner upper-cases the whole
5551            // pattern before aliasing (claude #547).
5552            calendar("09:00", &["FRIL"]),
5553            calendar("09:00", &["fril"]),
5554        ] {
5555            schedule_with(ok.clone(), RunsOn::Backend)
5556                .validate()
5557                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
5558        }
5559    }
5560
5561    #[test]
5562    fn validate_rejects_bad_last_weekday() {
5563        // bare `L` (no weekday — a footgun croner reads as Saturday), a
5564        // range with L, a bad day before L, and an internal space that
5565        // would otherwise leak a malformed cron downstream (gemini #560).
5566        for bad in ["L", "l", "mon-friL", "fundayL", "8L", "*L", "fri L"] {
5567            let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
5568                .validate()
5569                .unwrap_err();
5570            assert!(err.contains("when.days"), "for '{bad}', got: {err}");
5571        }
5572    }
5573
5574    #[test]
5575    fn calendar_oneshot_instant_detects_past() {
5576        use chrono::TimeZone;
5577        // a dated `at` resolves to an absolute instant…
5578        let c = CalendarSpec {
5579            at: "2024-01-01 09:00".into(),
5580            days: vec![],
5581        };
5582        let t = c
5583            .oneshot_instant(ScheduleTz::Utc)
5584            .expect("one-shot instant");
5585        assert_eq!(
5586            t,
5587            chrono::Utc.with_ymd_and_hms(2024, 1, 1, 9, 0, 0).unwrap()
5588        );
5589        assert!(t < chrono::Utc::now(), "2024 is in the past");
5590        // …while a repeating (time-only) calendar has no instant
5591        let rep = CalendarSpec {
5592            at: "09:00".into(),
5593            days: vec!["mon-fri".into()],
5594        };
5595        assert!(rep.oneshot_instant(ScheduleTz::Utc).is_none());
5596    }
5597
5598    fn schedule_with_active(from: Option<&str>, until: Option<&str>) -> Schedule {
5599        let mut s = schedule_with(
5600            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5601            RunsOn::Backend,
5602        );
5603        s.active = Active {
5604            from: from.map(str::to_owned),
5605            until: until.map(str::to_owned),
5606        };
5607        s
5608    }
5609
5610    #[test]
5611    fn validate_accepts_active_window() {
5612        schedule_with_active(Some("2026-07-01"), Some("2026-08-01T12:00:00+09:00"))
5613            .validate()
5614            .expect("date + rfc3339 bounds should validate");
5615    }
5616
5617    #[test]
5618    fn validate_rejects_unparseable_active_bound() {
5619        let err = schedule_with_active(Some("July 1st"), None)
5620            .validate()
5621            .unwrap_err();
5622        assert!(err.contains("active"), "got: {err}");
5623    }
5624
5625    #[test]
5626    fn validate_rejects_from_not_before_until() {
5627        let err = schedule_with_active(Some("2026-08-01"), Some("2026-07-01"))
5628            .validate()
5629            .unwrap_err();
5630        assert!(err.contains("strictly before"), "got: {err}");
5631
5632        let err = schedule_with_active(Some("2026-07-01"), Some("2026-07-01"))
5633            .validate()
5634            .unwrap_err();
5635        assert!(err.contains("strictly before"), "got: {err}");
5636    }
5637
5638    // ---- Active window semantics ----
5639
5640    #[test]
5641    fn active_window_is_half_open() {
5642        use chrono::TimeZone;
5643        let active = Active {
5644            from: Some("2026-07-01".into()),
5645            until: Some("2026-08-01".into()),
5646        };
5647        // UTC tz so the date bounds are UTC midnight.
5648        let at = |y, m, d, h| chrono::Utc.with_ymd_and_hms(y, m, d, h, 0, 0).unwrap();
5649        let c = |t| active.contains(t, ScheduleTz::Utc);
5650        assert!(!c(at(2026, 6, 30, 23)), "before from");
5651        assert!(c(at(2026, 7, 1, 0)), "at from (inclusive)");
5652        assert!(c(at(2026, 7, 15, 12)), "inside");
5653        assert!(!c(at(2026, 8, 1, 0)), "at until (exclusive)");
5654        assert!(!c(at(2026, 8, 2, 0)), "after until");
5655    }
5656
5657    #[test]
5658    fn active_empty_window_is_always_active() {
5659        assert!(Active::default().contains(chrono::Utc::now(), ScheduleTz::Local));
5660    }
5661
5662    #[test]
5663    fn active_rfc3339_bound_honours_offset_regardless_of_tz() {
5664        use chrono::TimeZone;
5665        let active = Active {
5666            from: Some("2026-07-01T09:00:00+09:00".into()),
5667            until: None,
5668        };
5669        // RFC3339 carries its own offset → tz arg is ignored.
5670        // 09:00 JST = 00:00 UTC.
5671        for tz in [ScheduleTz::Utc, ScheduleTz::Local] {
5672            assert!(
5673                !active.contains(
5674                    chrono::Utc
5675                        .with_ymd_and_hms(2026, 6, 30, 23, 59, 0)
5676                        .unwrap(),
5677                    tz
5678                )
5679            );
5680            assert!(active.contains(
5681                chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap(),
5682                tz
5683            ));
5684        }
5685    }
5686
5687    #[test]
5688    fn active_date_bound_respects_tz() {
5689        // A bare `YYYY-MM-DD` bound is midnight *in the schedule's
5690        // tz* (#418 Phase 2). The UTC interpretation is exact and
5691        // host-independent; assert that precisely.
5692        use chrono::TimeZone;
5693        let utc = Active::parse_bound("2026-07-01", ScheduleTz::Utc).expect("utc");
5694        assert_eq!(
5695            utc,
5696            chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap()
5697        );
5698
5699        // The local interpretation must equal what chrono::Local
5700        // computes for the same wall-clock midnight — proves the tz
5701        // path is wired to the host zone (the magnitude vs UTC is
5702        // host-dependent, so we compare against Local directly rather
5703        // than hard-coding the JST offset, keeping CI green on UTC
5704        // runners).
5705        let local = Active::parse_bound("2026-07-01", ScheduleTz::Local).expect("local");
5706        let want = chrono::Local
5707            .with_ymd_and_hms(2026, 7, 1, 0, 0, 0)
5708            .single()
5709            .expect("local midnight is unambiguous")
5710            .with_timezone(&chrono::Utc);
5711        assert_eq!(local, want, "date bound resolved in host-local tz");
5712    }
5713
5714    #[test]
5715    fn active_empty_is_skipped_when_serialising() {
5716        let s = schedule_with(
5717            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5718            RunsOn::Backend,
5719        );
5720        let json = serde_json::to_value(&s).expect("serialise");
5721        assert!(
5722            json.get("active").is_none(),
5723            "empty active must not appear on the wire: {json}"
5724        );
5725    }
5726
5727    // ---- constraints.window (#418 Phase 3) ----
5728
5729    fn with_window(win: &str) -> Schedule {
5730        let mut s = schedule_with(
5731            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5732            RunsOn::Backend,
5733        );
5734        s.constraints.window = Some(win.into());
5735        s
5736    }
5737
5738    #[test]
5739    fn constraints_window_parses_and_round_trips() {
5740        let yaml = r#"
5741id: x
5742when:
5743  per_pc: { every: 6h }
5744job_id: y
5745target: { all: true }
5746constraints:
5747  window: "22:00-05:00"
5748"#;
5749        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5750        assert_eq!(s.constraints.window.as_deref(), Some("22:00-05:00"));
5751        let back: Schedule =
5752            serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
5753        assert_eq!(back.constraints.window.as_deref(), Some("22:00-05:00"));
5754    }
5755
5756    #[test]
5757    fn constraints_empty_is_skipped_when_serialising() {
5758        let s = schedule_with(
5759            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5760            RunsOn::Backend,
5761        );
5762        let json = serde_json::to_value(&s).expect("serialise");
5763        assert!(
5764            json.get("constraints").is_none(),
5765            "empty constraints must not appear on the wire: {json}"
5766        );
5767    }
5768
5769    #[test]
5770    fn window_no_constraint_always_allows() {
5771        let c = Constraints::default();
5772        assert!(c.allows(chrono::Utc::now(), ScheduleTz::Local));
5773    }
5774
5775    #[test]
5776    fn window_same_day_is_half_open() {
5777        use chrono::TimeZone;
5778        let s = with_window("09:00-17:00");
5779        let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
5780        let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
5781        assert!(!a(at(8, 59)), "before start");
5782        assert!(a(at(9, 0)), "at start (inclusive)");
5783        assert!(a(at(16, 59)), "inside");
5784        assert!(!a(at(17, 0)), "at end (exclusive)");
5785        assert!(!a(at(23, 0)), "after end");
5786    }
5787
5788    #[test]
5789    fn window_crossing_midnight() {
5790        use chrono::TimeZone;
5791        let s = with_window("22:00-05:00");
5792        let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
5793        let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
5794        assert!(a(at(22, 0)), "at start tonight");
5795        assert!(a(at(23, 30)), "late tonight");
5796        assert!(a(at(3, 0)), "early tomorrow");
5797        assert!(!a(at(5, 0)), "at end (exclusive)");
5798        assert!(!a(at(12, 0)), "midday outside");
5799        assert!(!a(at(21, 59)), "just before start");
5800    }
5801
5802    #[test]
5803    fn window_respects_tz() {
5804        // The same instant is inside the window under one tz and may
5805        // be outside under another. Compare UTC vs Local via the
5806        // host's own offset (kept CI-green on UTC runners like the
5807        // active tz test does).
5808        use chrono::TimeZone;
5809        let s = with_window("09:00-17:00");
5810        let noon_utc = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 12, 0, 0).unwrap();
5811        // Under UTC, 12:00 is inside 09:00-17:00.
5812        assert!(s.constraints.allows(noon_utc, ScheduleTz::Utc));
5813        // Under Local, the verdict tracks the host wall-clock time;
5814        // assert it matches a direct wall_time membership check.
5815        let local_t = noon_utc.with_timezone(&chrono::Local).time();
5816        let in_local = local_t >= chrono::NaiveTime::from_hms_opt(9, 0, 0).unwrap()
5817            && local_t < chrono::NaiveTime::from_hms_opt(17, 0, 0).unwrap();
5818        assert_eq!(s.constraints.allows(noon_utc, ScheduleTz::Local), in_local);
5819    }
5820
5821    #[test]
5822    fn validate_accepts_good_window() {
5823        for w in ["09:00-17:00", "22:00-05:00", "00:00-23:59"] {
5824            with_window(w)
5825                .validate()
5826                .unwrap_or_else(|e| panic!("'{w}' should validate: {e}"));
5827        }
5828    }
5829
5830    #[test]
5831    fn validate_rejects_bad_window() {
5832        for bad in ["9-5", "22:00", "22:00-22:00", "25:00-05:00", "09:00_17:00"] {
5833            let err = with_window(bad).validate().unwrap_err();
5834            assert!(
5835                err.contains("constraints.window"),
5836                "for '{bad}', got: {err}"
5837            );
5838        }
5839    }
5840
5841    // ---- constraints.skip_dates (#418 holiday exclusion) ----
5842
5843    fn with_skip_dates(dates: &[&str]) -> Schedule {
5844        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5845        s.tz = ScheduleTz::Utc; // host-independent date assertions
5846        s.constraints.skip_dates = dates.iter().map(|d| (*d).to_string()).collect();
5847        s
5848    }
5849
5850    #[test]
5851    fn allows_blocks_listed_skip_date() {
5852        use chrono::TimeZone;
5853        let s = with_skip_dates(&["2026-06-10", "2026-12-25"]);
5854        // Any time on a listed date is blocked (whole day).
5855        let on = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap();
5856        assert!(!s.constraints.allows(on, ScheduleTz::Utc));
5857        let on_midnight = chrono::Utc.with_ymd_and_hms(2026, 12, 25, 0, 0, 0).unwrap();
5858        assert!(!s.constraints.allows(on_midnight, ScheduleTz::Utc));
5859        // A date not in the list fires normally.
5860        let off = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
5861        assert!(s.constraints.allows(off, ScheduleTz::Utc));
5862    }
5863
5864    #[test]
5865    fn allows_corrupt_skip_date_fails_closed() {
5866        use chrono::TimeZone;
5867        // A garbled entry (only reachable via hand-edited KV) blocks
5868        // rather than silently re-enabling fires — same posture as a
5869        // corrupt window.
5870        let s = with_skip_dates(&["not-a-date"]);
5871        let any = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
5872        assert!(!s.constraints.allows(any, ScheduleTz::Utc));
5873    }
5874
5875    #[test]
5876    fn validate_accepts_good_skip_dates() {
5877        with_skip_dates(&["2026-01-01", "2026-12-25", "2027-05-03"])
5878            .validate()
5879            .expect("well-formed skip dates should validate");
5880    }
5881
5882    #[test]
5883    fn validate_rejects_bad_skip_date() {
5884        for bad in ["2026-13-01", "01-01-2026", "nope", "2026/01/01"] {
5885            let err = with_skip_dates(&[bad]).validate().unwrap_err();
5886            assert!(
5887                err.contains("constraints.skip_dates"),
5888                "for '{bad}', got: {err}"
5889            );
5890        }
5891    }
5892
5893    #[test]
5894    fn preview_skips_holidays() {
5895        use chrono::TimeZone;
5896        // Daily 09:00 with two of the next five days marked as holidays
5897        // — preview drops exactly those, since it gates on `allows`.
5898        let mut s = cal_utc("09:00", &[]);
5899        s.constraints.skip_dates = vec!["2026-06-11".into(), "2026-06-13".into()];
5900        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5901        let got = s.preview_fires(now, 4);
5902        let want: Vec<_> = [
5903            (2026, 6, 10),
5904            (2026, 6, 12), // skips 06-11
5905            (2026, 6, 14), // skips 06-13
5906            (2026, 6, 15),
5907        ]
5908        .iter()
5909        .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
5910        .collect();
5911        assert_eq!(got, want);
5912    }
5913
5914    // ---- constraints.max_concurrent (#418) ----
5915
5916    fn with_max_concurrent(max: u32, runs_on: RunsOn) -> Schedule {
5917        let mut s = schedule_with(
5918            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5919            runs_on,
5920        );
5921        s.constraints.max_concurrent = Some(max);
5922        s
5923    }
5924
5925    #[test]
5926    fn validate_accepts_backend_max_concurrent() {
5927        with_max_concurrent(5, RunsOn::Backend)
5928            .validate()
5929            .expect("backend max_concurrent should validate");
5930    }
5931
5932    #[test]
5933    fn validate_rejects_max_concurrent_on_agent() {
5934        // Decision E: a central running-instance cap needs a central
5935        // counter, which agents don't have.
5936        let err = with_max_concurrent(5, RunsOn::Agent)
5937            .validate()
5938            .unwrap_err();
5939        assert!(err.contains("constraints.max_concurrent"), "got: {err}");
5940        assert!(err.contains("runs_on: agent"), "got: {err}");
5941    }
5942
5943    #[test]
5944    fn validate_rejects_zero_max_concurrent() {
5945        let err = with_max_concurrent(0, RunsOn::Backend)
5946            .validate()
5947            .unwrap_err();
5948        assert!(err.contains("max_concurrent must be >= 1"), "got: {err}");
5949    }
5950
5951    #[test]
5952    fn max_concurrent_round_trips_and_skips_when_absent() {
5953        let s = with_max_concurrent(3, RunsOn::Backend);
5954        let json = serde_json::to_value(&s.constraints).expect("ser");
5955        assert_eq!(json.get("max_concurrent").and_then(|v| v.as_u64()), Some(3));
5956        // A schedule with no constraints omits the whole block.
5957        let bare = schedule_with(
5958            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5959            RunsOn::Backend,
5960        );
5961        assert!(bare.constraints.is_empty());
5962    }
5963
5964    #[test]
5965    fn window_fail_closed_on_corrupt_blob() {
5966        // A malformed window (only reachable via a hand-edited KV
5967        // blob — validate() rejects it at create) must BLOCK, not
5968        // silently allow fires during a change-freeze (gemini #452).
5969        let s = with_window("22:00_05:00");
5970        assert!(
5971            !s.constraints.allows(chrono::Utc::now(), ScheduleTz::Utc),
5972            "corrupt window fails closed"
5973        );
5974        // …and the scheduler can surface why it's stuck.
5975        assert!(
5976            s.bad_window().is_some(),
5977            "bad_window reports the parse error"
5978        );
5979        assert!(with_window("22:00-05:00").bad_window().is_none());
5980    }
5981
5982    #[test]
5983    fn calendar_outside_window_is_flagged() {
5984        // at 09:00 can never fall in 22:00-05:00 → never fires.
5985        let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
5986        s.constraints.window = Some("22:00-05:00".into());
5987        assert!(s.calendar_outside_window(), "09:00 is not in 22:00-05:00");
5988
5989        // at 23:00 IS inside the overnight window → fine.
5990        let mut s = schedule_with(calendar("23:00", &[]), RunsOn::Backend);
5991        s.constraints.window = Some("22:00-05:00".into());
5992        assert!(!s.calendar_outside_window(), "23:00 is in 22:00-05:00");
5993
5994        // reconcile shapes are never flagged (they poll every minute).
5995        let mut s = schedule_with(
5996            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5997            RunsOn::Backend,
5998        );
5999        s.constraints.window = Some("22:00-05:00".into());
6000        assert!(!s.calendar_outside_window(), "reconcile is unaffected");
6001
6002        // no window → never flagged.
6003        let s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
6004        assert!(!s.calendar_outside_window());
6005    }
6006
6007    // ---- on_failure.retry (#418 Phase 4) ----
6008
6009    fn with_retry(max: u32, backoff: &str) -> Schedule {
6010        let mut s = schedule_with(
6011            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6012            RunsOn::Backend,
6013        );
6014        s.on_failure.retry = Some(Retry {
6015            max,
6016            backoff: backoff.into(),
6017        });
6018        s
6019    }
6020
6021    #[test]
6022    fn on_failure_parses_and_round_trips() {
6023        let yaml = r#"
6024id: x
6025when:
6026  per_pc: { every: 6h }
6027job_id: y
6028target: { all: true }
6029on_failure:
6030  retry: { max: 3, backoff: 10m }
6031"#;
6032        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6033        let r = s.on_failure.retry.as_ref().expect("retry present");
6034        assert_eq!(r.max, 3);
6035        assert_eq!(r.backoff, "10m");
6036        let back: Schedule =
6037            serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
6038        assert_eq!(back.on_failure, s.on_failure);
6039    }
6040
6041    #[test]
6042    fn on_failure_empty_is_skipped_when_serialising() {
6043        let s = schedule_with(
6044            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6045            RunsOn::Backend,
6046        );
6047        let json = serde_json::to_value(&s).expect("serialise");
6048        assert!(
6049            json.get("on_failure").is_none(),
6050            "empty on_failure must not appear on the wire: {json}"
6051        );
6052    }
6053
6054    #[test]
6055    fn validate_accepts_good_retry() {
6056        for (max, backoff) in [(1, "30s"), (3, "10m"), (10, "1h")] {
6057            with_retry(max, backoff)
6058                .validate()
6059                .unwrap_or_else(|e| panic!("retry {{max:{max}, backoff:{backoff}}}: {e}"));
6060        }
6061    }
6062
6063    #[test]
6064    fn validate_rejects_bad_backoff() {
6065        let err = with_retry(3, "soon").validate().unwrap_err();
6066        assert!(err.contains("on_failure.retry.backoff"), "got: {err}");
6067    }
6068
6069    #[test]
6070    fn validate_rejects_sub_second_backoff() {
6071        // "500ms" parses as humantime but lowers to 0s on the wire —
6072        // reject it so the operator doesn't get a silent no-wait
6073        // (coderabbit #466).
6074        for bad in ["500ms", "0s", "999ms"] {
6075            let err = with_retry(3, bad).validate().unwrap_err();
6076            assert!(
6077                err.contains("on_failure.retry.backoff must be >= 1s"),
6078                "for '{bad}', got: {err}"
6079            );
6080        }
6081    }
6082
6083    #[test]
6084    fn validate_rejects_out_of_range_max() {
6085        for bad in [0u32, 11, 1000] {
6086            let err = with_retry(bad, "10m").validate().unwrap_err();
6087            assert!(
6088                err.contains("on_failure.retry.max"),
6089                "for max={bad}, got: {err}"
6090            );
6091        }
6092    }
6093
6094    #[test]
6095    fn lowered_retry_reduces_backoff_to_seconds() {
6096        let s = with_retry(3, "10m");
6097        let spec = s.on_failure.lowered_retry().expect("a retry policy");
6098        assert_eq!(spec.max, 3);
6099        assert_eq!(spec.backoff_secs, 600);
6100    }
6101
6102    #[test]
6103    fn lowered_retry_is_none_without_policy() {
6104        let s = schedule_with(
6105            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6106            RunsOn::Backend,
6107        );
6108        assert!(s.on_failure.lowered_retry().is_none());
6109    }
6110
6111    // ---- global change-freeze (#418 Phase 5) ----
6112
6113    #[test]
6114    fn freeze_empty_window_is_always_active() {
6115        // The big-red-button shape: no bounds = frozen until cleared.
6116        let f = Freeze::default();
6117        assert!(f.is_active(chrono::Utc::now()));
6118    }
6119
6120    #[test]
6121    fn freeze_window_is_half_open() {
6122        use chrono::TimeZone;
6123        let f = Freeze {
6124            from: Some("2026-12-20T00:00:00+00:00".into()),
6125            until: Some("2027-01-05T00:00:00+00:00".into()),
6126            reason: Some("year-end".into()),
6127            tz: ScheduleTz::Utc,
6128        };
6129        let at = |y, mo, d| chrono::Utc.with_ymd_and_hms(y, mo, d, 0, 0, 0).unwrap();
6130        assert!(!f.is_active(at(2026, 12, 19)), "before from = not frozen");
6131        assert!(f.is_active(at(2026, 12, 20)), "from is inclusive");
6132        assert!(f.is_active(at(2026, 12, 31)), "inside window");
6133        assert!(!f.is_active(at(2027, 1, 5)), "until is exclusive");
6134        assert!(!f.is_active(at(2027, 1, 6)), "after until = not frozen");
6135    }
6136
6137    #[test]
6138    fn freeze_fails_closed_on_corrupt_bound() {
6139        // A freeze is a safety switch: an unparseable bound (only
6140        // reachable via a hand-edited KV blob) must read as FROZEN, not
6141        // "fire normally" (coderabbit #472) — the opposite of `active`,
6142        // which fail-opens.
6143        let f = Freeze {
6144            from: Some("not-a-date".into()),
6145            until: None,
6146            reason: None,
6147            tz: ScheduleTz::Utc,
6148        };
6149        assert!(f.is_active(chrono::Utc::now()), "corrupt bound → frozen");
6150    }
6151
6152    #[test]
6153    fn freeze_validate_accepts_good_bounds() {
6154        Freeze {
6155            from: Some("2026-12-20".into()),
6156            until: Some("2027-01-05T12:00:00+09:00".into()),
6157            reason: None,
6158            tz: ScheduleTz::Local,
6159        }
6160        .validate()
6161        .expect("date + rfc3339 bounds should validate");
6162        // Empty (indefinite) freeze is valid.
6163        Freeze::default().validate().expect("empty freeze is valid");
6164    }
6165
6166    #[test]
6167    fn freeze_validate_rejects_bad_bound_and_inverted_window() {
6168        let err = Freeze {
6169            from: Some("never".into()),
6170            ..Default::default()
6171        }
6172        .validate()
6173        .unwrap_err();
6174        assert!(err.contains("freeze:"), "got: {err}");
6175
6176        let inverted = Freeze {
6177            from: Some("2027-01-05".into()),
6178            until: Some("2026-12-20".into()),
6179            ..Default::default()
6180        }
6181        .validate()
6182        .unwrap_err();
6183        assert!(inverted.contains("freeze.from"), "got: {inverted}");
6184    }
6185
6186    #[test]
6187    fn freeze_round_trips_and_skips_empty_fields() {
6188        let f = Freeze {
6189            from: None,
6190            until: Some("2027-01-05".into()),
6191            reason: Some("INC-1234".into()),
6192            tz: ScheduleTz::Utc,
6193        };
6194        let json = serde_json::to_value(&f).expect("serialise");
6195        assert!(json.get("from").is_none(), "empty from omitted: {json}");
6196        let back: Freeze = serde_json::from_value(json).expect("round-trip");
6197        assert_eq!(back, f);
6198    }
6199
6200    #[test]
6201    fn shipped_schedule_configs_parse_and_validate() {
6202        // Every YAML under configs/schedules/ must parse with the
6203        // current Schedule serde AND pass validate() — keeps the
6204        // shipped examples from drifting out of sync with the model
6205        // (#418 removed back-compat, so drift = broken at create).
6206        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../configs/schedules");
6207        let mut seen = 0;
6208        for entry in std::fs::read_dir(&dir).expect("read configs/schedules") {
6209            let path = entry.expect("dir entry").path();
6210            if path.extension().and_then(|e| e.to_str()) != Some("yaml") {
6211                continue;
6212            }
6213            let body = std::fs::read_to_string(&path).expect("read yaml");
6214            let s: Schedule = serde_yaml::from_str(&body)
6215                .unwrap_or_else(|e| panic!("{} failed to parse: {e}", path.display()));
6216            s.validate()
6217                .unwrap_or_else(|e| panic!("{} failed validate(): {e}", path.display()));
6218            seen += 1;
6219        }
6220        assert!(seen > 0, "no schedule YAMLs found in {}", dir.display());
6221    }
6222
6223    // ---- pre-existing enum wire formats (unchanged by #418) ----
6224
6225    #[test]
6226    fn exec_mode_serialises_snake_case() {
6227        for (mode, expected) in [
6228            (ExecMode::EveryTick, "every_tick"),
6229            (ExecMode::OncePerPc, "once_per_pc"),
6230            (ExecMode::OncePerTarget, "once_per_target"),
6231        ] {
6232            let s = serde_json::to_value(mode).expect("serialise");
6233            assert_eq!(s, serde_json::Value::String(expected.into()));
6234            let back: ExecMode = serde_json::from_value(serde_json::Value::String(expected.into()))
6235                .expect("deserialise");
6236            assert_eq!(back, mode, "round-trip for {expected}");
6237        }
6238    }
6239
6240    #[test]
6241    fn schedule_runs_on_defaults_to_backend() {
6242        let yaml = r#"
6243id: x
6244when:
6245  per_pc: once
6246job_id: y
6247target: { all: true }
6248"#;
6249        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6250        assert_eq!(s.runs_on, RunsOn::Backend);
6251    }
6252
6253    #[test]
6254    fn schedule_runs_on_agent_parses() {
6255        let yaml = r#"
6256id: offline-inv
6257when:
6258  per_pc: { every: 1h }
6259job_id: inventory-hw
6260target: { all: true }
6261runs_on: agent
6262"#;
6263        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6264        assert_eq!(s.runs_on, RunsOn::Agent);
6265        assert_eq!(s.lowered().mode, ExecMode::OncePerPc);
6266    }
6267
6268    #[test]
6269    fn runs_on_serialises_snake_case() {
6270        for (mode, expected) in [(RunsOn::Backend, "backend"), (RunsOn::Agent, "agent")] {
6271            let s = serde_json::to_value(mode).expect("serialise");
6272            assert_eq!(s, serde_json::Value::String(expected.into()));
6273            let back: RunsOn = serde_json::from_value(serde_json::Value::String(expected.into()))
6274                .expect("deserialise");
6275            assert_eq!(back, mode);
6276        }
6277    }
6278
6279    #[test]
6280    fn execute_shell_into_wire_shell() {
6281        assert_eq!(Shell::from(ExecuteShell::Powershell), Shell::Powershell);
6282        assert_eq!(Shell::from(ExecuteShell::Cmd), Shell::Cmd);
6283    }
6284
6285    #[test]
6286    fn manifest_staleness_defaults_to_cached() {
6287        let yaml = r#"
6288id: x
6289version: 1.0.0
6290execute:
6291  shell: powershell
6292  script: "echo"
6293  timeout: 1s
6294"#;
6295        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
6296        assert_eq!(m.staleness, Staleness::Cached);
6297    }
6298
6299    #[test]
6300    fn manifest_strict_staleness_parses() {
6301        let yaml = r#"
6302id: urgent-patch
6303version: 2.5.1
6304execute:
6305  shell: powershell
6306  script: Install-Hotfix
6307  timeout: 5m
6308staleness:
6309  mode: strict
6310  max_cache_age: 0s
6311"#;
6312        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
6313        match m.staleness {
6314            Staleness::Strict { max_cache_age } => assert_eq!(max_cache_age, "0s"),
6315            other => panic!("expected strict, got {other:?}"),
6316        }
6317    }
6318
6319    #[test]
6320    fn manifest_unchecked_staleness_parses() {
6321        let yaml = r#"
6322id: legacy
6323version: 0.1.0
6324execute:
6325  shell: cmd
6326  script: "echo"
6327  timeout: 1s
6328staleness:
6329  mode: unchecked
6330"#;
6331        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
6332        assert_eq!(m.staleness, Staleness::Unchecked);
6333    }
6334
6335    #[test]
6336    fn missing_required_field_errors() {
6337        // `id` missing.
6338        let yaml = r#"
6339version: 1.0.0
6340target: { all: true }
6341execute:
6342  shell: powershell
6343  script: "echo"
6344  timeout: 1s
6345"#;
6346        let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
6347        assert!(r.is_err(), "expected error, got {:?}", r);
6348    }
6349
6350    #[test]
6351    fn display_field_table_kind_round_trips_with_nested_columns() {
6352        // #39: `type: table` + `columns:` on a DisplayField gets
6353        // round-tripped through serde so the SPA receives the
6354        // nested schema verbatim. Nested columns themselves are
6355        // DisplayFields so they can carry `type: bytes` /
6356        // `type: number` for cell formatting.
6357        let yaml = r#"
6358id: inv-hw
6359version: 1.0.0
6360execute:
6361  shell: powershell
6362  script: "echo"
6363  timeout: 60s
6364inventory:
6365  display:
6366    - field: hostname
6367      label: Hostname
6368    - field: disks
6369      label: Disks
6370      type: table
6371      columns:
6372        - field: device_id
6373          label: Drive
6374        - field: size_bytes
6375          label: Size
6376          type: bytes
6377        - field: free_bytes
6378          label: Free
6379          type: bytes
6380        - field: file_system
6381          label: FS
6382"#;
6383        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
6384        let inv = m.inventory.as_ref().expect("inventory hint");
6385        let disks = inv
6386            .display
6387            .iter()
6388            .find(|d| d.field == "disks")
6389            .expect("disks display row");
6390        assert_eq!(disks.kind.as_deref(), Some("table"));
6391        let cols = disks.columns.as_ref().expect("table needs columns");
6392        assert_eq!(cols.len(), 4);
6393        assert_eq!(cols[1].field, "size_bytes");
6394        assert_eq!(cols[1].kind.as_deref(), Some("bytes"));
6395    }
6396
6397    #[test]
6398    fn display_field_scalar_kind_keeps_columns_none() {
6399        // Defensive: when type is a scalar (`bytes` / `number` /
6400        // `timestamp`) the `columns` field stays None — the SPA
6401        // uses its presence as the "render nested table" signal,
6402        // so it must not leak in via serde defaults.
6403        let yaml = r#"
6404id: x
6405version: 1.0.0
6406execute:
6407  shell: powershell
6408  script: "echo"
6409  timeout: 5s
6410inventory:
6411  display:
6412    - { field: ram_bytes, label: RAM, type: bytes }
6413"#;
6414        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
6415        let inv = m.inventory.as_ref().unwrap();
6416        assert!(inv.display[0].columns.is_none());
6417    }
6418
6419    // ---- checked-in JSON Schema freshness (docs/schemas/) ----
6420
6421    /// The JSON Schemas under `docs/schemas/` must match what
6422    /// `schema_for!` produces today — a Cargo.lock-style freshness guard
6423    /// so a `Schedule` / `Manifest` field change can't silently drift
6424    /// the operator-facing schema. The SPA editor, the backend
6425    /// `/api/schemas/*` endpoints, and these files all read the same
6426    /// derived shape; this test fails CI if the checked-in copy lags.
6427    /// Regenerate with:
6428    ///   `UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current`
6429    #[test]
6430    fn schema_files_are_current() {
6431        assert_schema_file("schedule.schema.json", &schemars::schema_for!(Schedule));
6432        assert_schema_file("job.schema.json", &schemars::schema_for!(Manifest));
6433        assert_schema_file("view.schema.json", &schemars::schema_for!(View));
6434    }
6435
6436    fn assert_schema_file(name: &str, schema: &schemars::Schema) {
6437        let generated = serde_json::to_string_pretty(schema).expect("serialize schema") + "\n";
6438        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
6439            .join("../../docs/schemas")
6440            .join(name);
6441        if std::env::var_os("UPDATE_SCHEMAS").is_some() {
6442            std::fs::create_dir_all(path.parent().unwrap()).expect("mkdir docs/schemas");
6443            std::fs::write(&path, &generated).unwrap_or_else(|e| panic!("write {path:?}: {e}"));
6444            return;
6445        }
6446        // Normalize CRLF→LF before comparing: `.gitattributes` already
6447        // pins these files to `eol=lf`, but a stray CRLF working-tree
6448        // copy (autocrlf, a tool rewrite) shouldn't turn a *content*-
6449        // freshness check into a confusing line-ending failure — that's
6450        // .gitattributes' job, not this test's (gemini #588).
6451        let on_disk = std::fs::read_to_string(&path)
6452            .unwrap_or_else(|e| {
6453                panic!(
6454                    "read {path:?}: {e}\n\
6455                     generate it with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
6456                )
6457            })
6458            .replace("\r\n", "\n");
6459        assert_eq!(
6460            on_disk, generated,
6461            "{name} is stale — a Schedule/Manifest schema change isn't reflected in docs/schemas/. \
6462             Refresh with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
6463        );
6464    }
6465}
6466
6467/// Periodic schedule (spec §2.4.3). v0.18.0 carries the fanout plan
6468/// (target + optional rollout + optional jitter) inline; the
6469/// referenced job (`job_id` → [`BUCKET_JOBS`]) supplies only the
6470/// script body. Two schedules of the same job can target different
6471/// groups on different cadences without copying the manifest.
6472///
6473/// #418 Phase 1: the cadence is the single [`When`] field. The old
6474/// `cron` × `mode` × `cooldown` × `auto_disable_when_done` quartet
6475/// is gone (no back-compat — pre-Phase-1 KV blobs fail to parse and
6476/// are warn-skipped; re-`schedule create` to upgrade them). The
6477/// engine underneath is unchanged: [`Schedule::lowered`] maps `when`
6478/// onto the same (cron, ExecMode, cooldown) trio the scheduler and
6479/// `decide_fire` always ran on.
6480#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
6481pub struct Schedule {
6482    pub id: String,
6483    /// When to fire — a reconcile cadence (`per_pc` / `per_target`)
6484    /// or a calendar time trigger (`at` / `days`). See [`When`].
6485    ///
6486    /// `singleton_map`: serde_yaml 0.9 renders externally-tagged
6487    /// enums as `!per_pc` YAML tags by default; this keeps the
6488    /// operator-facing map shape (`when: { per_pc: once }`). JSON
6489    /// output is identical either way, and the schemars schema
6490    /// (external tagging = oneOf of single-key objects) already
6491    /// matches the singleton-map wire shape.
6492    #[serde(with = "serde_yaml::with::singleton_map")]
6493    #[schemars(with = "When")]
6494    pub when: When,
6495    /// Key into [`crate::kv::BUCKET_JOBS`]. Must equal a registered
6496    /// Manifest's `id`.
6497    pub job_id: String,
6498    /// Who + how-to-phase + when-to-stagger. The Manifest doesn't
6499    /// carry these any more — same job + different fanout = different
6500    /// schedule.
6501    #[serde(flatten)]
6502    pub plan: FanoutPlan,
6503    /// Optional validity window. Outside `[from, until)` the
6504    /// schedule is dormant — still registered, still visible, but
6505    /// every tick is skipped (deleted ≠ dormant: a campaign that
6506    /// ended stays inspectable and can be re-armed by editing the
6507    /// window). Checked at tick time on both the backend scheduler
6508    /// and the agent's local scheduler.
6509    #[serde(default, skip_serializing_if = "Active::is_empty")]
6510    pub active: Active,
6511    /// #418 operational constraints gating *when within an active
6512    /// period* a fire may happen: a maintenance `window`, a fleet
6513    /// `max_concurrent` cap, and `skip_dates` (holiday exclusion). The
6514    /// wall-clock ones are evaluated in the schedule's `tz`; future
6515    /// `require` (env gates) lands in the same namespace. Checked at
6516    /// tick time on both schedulers (and surfaced by `preview`).
6517    #[serde(default, skip_serializing_if = "Constraints::is_empty")]
6518    pub constraints: Constraints,
6519    /// #418 Phase 4: what to do after a fire's script comes back
6520    /// failed. Currently just `retry` (fixed-backoff in-process
6521    /// re-run); future `notify` / `disable` join the same namespace.
6522    /// Applied fire-side in `handle_command` (the retry policy is
6523    /// lowered onto every Command this schedule produces), so it
6524    /// covers both `runs_on` locations.
6525    #[serde(default, skip_serializing_if = "OnFailure::is_empty")]
6526    pub on_failure: OnFailure,
6527    /// #418 Phase 2: the timezone this schedule's wall-clock fields
6528    /// are evaluated in — both the calendar `at` firing time AND the
6529    /// `active.{from,until}` window bounds. `local` (default) = the
6530    /// running host's TZ (the agent's for `runs_on: agent`, the
6531    /// backend server's otherwise); `utc` for TZ-independent
6532    /// schedules. Reconcile shapes (`per_pc`/`per_target`) ignore it
6533    /// for firing (poll cron runs every minute regardless) but still
6534    /// honor it for the `active` window.
6535    #[serde(default)]
6536    pub tz: ScheduleTz,
6537    /// v0.22: optional humantime window after a cron tick during
6538    /// which the Command is still considered "live". The scheduler
6539    /// computes `tick_at + starting_deadline` and stamps it onto
6540    /// each Command as `deadline_at`; agents skip Commands they
6541    /// receive after that absolute time. `None` (default) = no
6542    /// deadline, meaning a Command queued in the broker / stream
6543    /// during agent downtime runs whenever the agent reconnects —
6544    /// good for kitting / inventory / cleanup. Set this for
6545    /// time-of-day notifications, lunch reminders, etc., where
6546    /// "fire 3 hours late" would be wrong.
6547    #[serde(default, skip_serializing_if = "Option::is_none")]
6548    pub starting_deadline: Option<String>,
6549    /// v0.23: where does the cron tick happen? `Backend` (default,
6550    /// historical) = backend's scheduler fires Commands via NATS;
6551    /// agents passively receive. `Agent` = each targeted agent runs
6552    /// its own internal cron and fires locally, so the schedule
6553    /// keeps ticking even when the broker is unreachable (laptop on
6554    /// the train, broker maintenance window, full WAN outage). The
6555    /// two locations are mutually exclusive — when `Agent`, the
6556    /// backend scheduler stays out and just keeps the definition in
6557    /// KV for agents to read.
6558    #[serde(default)]
6559    pub runs_on: RunsOn,
6560    #[serde(default = "default_true")]
6561    pub enabled: bool,
6562    /// Free-form operator taxonomy for the Schedules page — the
6563    /// schedule-side mirror of `Manifest.tags` (added in #640; a plain
6564    /// code ref rather than an intra-doc link, since that field isn't
6565    /// on this branch until #640 merges). Purely a SPA-side
6566    /// organisational aid (search / filter chips alongside the
6567    /// id-prefix grouping); the scheduler never reads it, so any
6568    /// string is allowed and it carries no firing semantics. A
6569    /// schedule's own tags are independent of its job's: the same job
6570    /// may back a `weekly` maintenance schedule and a `canary` rollout
6571    /// schedule. Empty by default and `skip_serializing_if`-elided per
6572    /// the #492 gradual-upgrade wire rule.
6573    #[serde(default, skip_serializing_if = "Vec::is_empty")]
6574    pub tags: Vec<String>,
6575    /// GitOps provenance (#695) — see [`RepoOrigin`]. Stamped by
6576    /// `kanade schedule create` when the source YAML lives inside a Git
6577    /// work tree, so the SPA renders the schedule read-only and points
6578    /// edits back at the repo (SPEC design principle #3: 設定駆動 YAML +
6579    /// Git), parity with a job's [`Manifest::origin`]. `None` for
6580    /// SPA-born schedules and ones applied from outside any repo. Purely
6581    /// informational — the scheduler never reads it. New field ⇒ #492
6582    /// wire rule (`default` + `skip_serializing_if`).
6583    #[serde(default, skip_serializing_if = "Option::is_none")]
6584    pub origin: Option<RepoOrigin>,
6585}
6586
6587/// v0.23 — where the cron tick fires from.
6588#[derive(
6589    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
6590)]
6591#[serde(rename_all = "snake_case")]
6592pub enum RunsOn {
6593    /// Backend's central scheduler ticks and publishes Commands to
6594    /// NATS. Historical default, what every pre-v0.23 schedule
6595    /// uses. Agent offline ⇒ Command queued in STREAM_EXEC; agent
6596    /// reconnects ⇒ catch-up via [`command_replay`](crate)
6597    /// (see kanade-agent's command_replay module).
6598    #[default]
6599    Backend,
6600    /// Each targeted agent runs the cron tick locally. Survives
6601    /// broker / WAN outages. Best for laptops / mobile devices that
6602    /// roam off the corporate network. Agent must be online for the
6603    /// initial schedule + job-catalog pull, but once cached the
6604    /// agent fires the script standalone.
6605    Agent,
6606}
6607
6608/// Per-pc/per-target dedup semantics for a [`Schedule`] (v0.19).
6609#[derive(
6610    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
6611)]
6612#[serde(rename_all = "snake_case")]
6613pub enum ExecMode {
6614    /// Fire on every cron tick at the whole target. Historical
6615    /// (pre-v0.19) behavior; no dedup.
6616    #[default]
6617    EveryTick,
6618    /// Fire at each pc until that pc succeeds; then skip it until
6619    /// the optional cooldown elapses (or forever if no cooldown).
6620    /// Use for kitting / first-boot / per-pc compliance checks.
6621    OncePerPc,
6622    /// Fire at the whole target until **any** pc succeeds; then
6623    /// skip the whole target until the optional cooldown elapses
6624    /// (or forever if no cooldown). Use for "one delegate is
6625    /// enough" tasks like license check-in.
6626    OncePerTarget,
6627    /// #418 OS-native event trigger (`when: { on: [...] }`). There is
6628    /// no cron — the agent fires it from an OS event source (boot /
6629    /// session-change), not a tick — so the scheduler skips
6630    /// `tokio-cron` registration for it. Each event occurrence fires
6631    /// once, gated by the standard freeze / active / window /
6632    /// skip_dates checks.
6633    Event,
6634}
6635
6636/// #418 Phase 1 — the single "when does this fire" axis.
6637///
6638/// Replaces the old `cron` + `mode` + `cooldown` trio whose
6639/// interactions were implicit (cron doubled as both a real
6640/// time-of-day trigger and a reconcile poll period; contradictory
6641/// combinations silently no-opped). Two shapes:
6642///
6643/// * **reconcile** (`per_pc` / `per_target`) — desired-state: "each
6644///   pc (or one delegate) should have run this within `every`".
6645///   The poll period is system-generated ([`POLL_CRON`], every
6646///   minute) and no longer the operator's concern.
6647/// * **calendar** (`{ at, days }`) — a wall-clock time trigger
6648///   (#418 Phase 2, replacing the old raw-cron escape hatch). Fires
6649///   the whole target at the given time, no dedup. `at: "09:00"` +
6650///   `days` repeats; `at: "2026-06-10 09:00"` (a date+time) fires
6651///   exactly once. Evaluated in the schedule's top-level `tz`.
6652#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
6653#[serde(rename_all = "snake_case")]
6654pub enum When {
6655    /// Fire at each targeted pc: `once` (kitting — succeed once,
6656    /// skip forever, forever catching brand-new / re-imaged pcs)
6657    /// or `{ every: <humantime> }` (patrol — re-arm per pc after
6658    /// the interval).
6659    PerPc(PerPolicy),
6660    /// Fire until **any** one pc of the target succeeds, then skip
6661    /// the whole target (`once`) or re-arm after `every`. Needs
6662    /// fleet-wide completion data, so it is backend-only —
6663    /// `runs_on: agent` + `per_target` is rejected by
6664    /// [`Schedule::validate`].
6665    PerTarget(PerPolicy),
6666    /// Calendar time trigger: `{ at: "09:00", days: [mon-fri] }`
6667    /// (repeating) or `{ at: "2026-06-10 09:00" }` (one-shot). Fires
6668    /// the whole target at that wall-clock time in the schedule's
6669    /// `tz` — no dedup, no cooldown.
6670    Calendar(CalendarSpec),
6671    /// #418 OS-native event trigger: `when: { on: [startup, logon] }`.
6672    /// Fires when the agent observes the listed OS event(s) rather than
6673    /// on a clock — there is no cron. `runs_on: agent` only (the agent
6674    /// owns the event source); [`Schedule::validate`] rejects it on
6675    /// `backend` and rejects an empty list. Each event occurrence fires
6676    /// once, gated by the same freeze / active / `constraints.window` /
6677    /// `skip_dates` checks as the cron path. `startup` fires once per OS
6678    /// boot (deduped via the host boot time); a `starting_deadline`, if
6679    /// set, limits it to "agent came up within that long after boot".
6680    On(Vec<OnTrigger>),
6681}
6682
6683/// An OS event the agent can fire a schedule on (#418 `when: { on }`).
6684#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash)]
6685#[serde(rename_all = "snake_case")]
6686pub enum OnTrigger {
6687    /// Once per OS boot (the agent's first run for that boot). Catches
6688    /// freshly-imaged / reinstalled hosts at their next startup.
6689    Startup,
6690    /// On an interactive-session user logon — console, RDP, or
6691    /// auto-logon (Windows `WTS_SESSION_LOGON`). Does not fire for
6692    /// service / network / batch logons (no interactive session).
6693    Logon,
6694    /// When the workstation is locked (Win+L / idle lock; Windows
6695    /// `WTS_SESSION_LOCK`). Use for step-away compliance / cleanup.
6696    Lock,
6697    /// When the workstation is unlocked — the user returns to a locked
6698    /// session (Windows `WTS_SESSION_UNLOCK`). Use to re-check
6699    /// compliance / refresh state when work resumes.
6700    Unlock,
6701    /// When the host's network changes — IP address table change on
6702    /// connect / disconnect / DHCP renew / VPN / Wi-Fi roam (Windows
6703    /// `NotifyAddrChange`). Debounced agent-side (a burst of changes
6704    /// from one transition fires once after the network settles), so
6705    /// use it for "re-check connectivity / re-register on network move"
6706    /// rather than expecting one fire per raw adapter event.
6707    ///
6708    /// IPv4 only: `NotifyAddrChange` watches the IPv4 address table, so a
6709    /// transition that touches only IPv6 addresses won't fire. In practice
6710    /// dual-stack networks change both tables together, but a pure-IPv6
6711    /// move (e.g. an IPv6-only Wi-Fi roam) is not detected.
6712    NetworkChange,
6713}
6714
6715/// Calendar time trigger (#418 Phase 2). `at` is either a time of
6716/// day (`"HH:MM"`, repeating — combine with `days`) or a full
6717/// date+time (`"YYYY-MM-DD HH:MM"`, a one-shot that fires once and
6718/// never again). Evaluated in the schedule's top-level `tz`.
6719#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
6720pub struct CalendarSpec {
6721    /// `"HH:MM"` (24h) for a repeating trigger, or
6722    /// `"YYYY-MM-DD HH:MM"` (hyphen / slash / `T` separators all
6723    /// accepted) for a one-shot. Parsed lazily —
6724    /// [`Schedule::validate`] rejects garbage at create time.
6725    pub at: String,
6726    /// Day-of-week filter for a time-of-day `at`: `["mon-fri"]`,
6727    /// `["mon","wed","fri"]`, … (passed verbatim to the cron DOW
6728    /// field, so ranges and names both work). An **nth-weekday**
6729    /// `["tue#2"]` fires only on the 2nd Tuesday of each month
6730    /// ("Patch Tuesday"); the ordinal is `1..5`. A **last-weekday**
6731    /// `["friL"]` fires only on the last Friday of each month (handy
6732    /// for monthly maintenance). Empty = every day. Must be empty
6733    /// when `at` carries a date (the date already pins the day).
6734    #[serde(default, skip_serializing_if = "Vec::is_empty")]
6735    pub days: Vec<String>,
6736}
6737
6738/// Parsed `CalendarSpec.at`: the wall-clock minute/hour, plus the
6739/// date for a one-shot (`None` = repeating time-of-day).
6740struct ParsedAt {
6741    minute: u32,
6742    hour: u32,
6743    date: Option<chrono::NaiveDate>,
6744}
6745
6746impl CalendarSpec {
6747    /// Parse `at`: a date+time (`YYYY-MM-DD HH:MM`, hyphen / slash /
6748    /// `T` separators) is a one-shot; a bare `HH:MM` is repeating.
6749    fn parse_at(&self) -> Result<ParsedAt, String> {
6750        use chrono::Timelike;
6751        let s = self.at.trim();
6752        for fmt in ["%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y/%m/%d %H:%M"] {
6753            if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, fmt) {
6754                return Ok(ParsedAt {
6755                    minute: dt.minute(),
6756                    hour: dt.hour(),
6757                    date: Some(dt.date()),
6758                });
6759            }
6760        }
6761        if let Ok(t) = chrono::NaiveTime::parse_from_str(s, "%H:%M") {
6762            return Ok(ParsedAt {
6763                minute: t.minute(),
6764                hour: t.hour(),
6765                date: None,
6766            });
6767        }
6768        Err(format!(
6769            "when.at: unparseable '{}' (want HH:MM or YYYY-MM-DD HH:MM)",
6770            self.at
6771        ))
6772    }
6773
6774    /// Pre-flight check on the `days` tokens so a bad day name gives
6775    /// a `when.days:`-scoped error instead of croner's confusing
6776    /// "when.at lowered to invalid cron" (claude #432 review). Each
6777    /// token is a day name (`mon`..`sun`), a numeric DOW (`0`..`7`),
6778    /// `*`, a `-` range of those, an **nth-weekday** like `tue#2`
6779    /// (2nd Tuesday of the month — "Patch Tuesday"), or a
6780    /// **last-weekday** like `friL` (last Friday of the month).
6781    fn validate_days(&self) -> Result<(), String> {
6782        const NAMES: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
6783        let is_day = |p: &str| NAMES.contains(&p) || p.parse::<u8>().is_ok_and(|n| n <= 7);
6784        for tok in &self.days {
6785            // Report the whole token on a malformed range like `mon-`
6786            // (which would otherwise split to a cryptic empty part —
6787            // claude #432 follow-up).
6788            let invalid = |reason: &str| {
6789                Err(format!(
6790                    "when.days: invalid day token '{tok}' ({reason}; \
6791                     want mon..sun, 0-7, a range like mon-fri, an nth-weekday \
6792                     like tue#2, a last-weekday like friL, or *)"
6793                ))
6794            };
6795            // #418: nth-weekday suffix (`tue#2` = 2nd Tuesday). Croner
6796            // accepts `<dow>#<n>` (n = 1..5) in the DOW field, and
6797            // `to_cron` passes the token through verbatim, so the
6798            // engine fires only on that occurrence. It's a single
6799            // weekday + ordinal — not combinable with a range.
6800            if let Some((day_part, nth_part)) = tok.split_once('#') {
6801                // Normalize once and use `d` consistently (gemini #547);
6802                // the outer `invalid` already echoes the raw `tok`.
6803                let d = day_part.trim().to_ascii_lowercase();
6804                if d.contains('-') || !is_day(&d) {
6805                    return invalid("the part before # must be a single weekday");
6806                }
6807                match nth_part.trim().parse::<u8>() {
6808                    Ok(n) if (1..=5).contains(&n) => {}
6809                    _ => return invalid("the # ordinal must be 1..5 (e.g. tue#2 = 2nd Tuesday)"),
6810                }
6811                continue;
6812            }
6813            // #418: last-weekday suffix (`friL` = last Friday of the
6814            // month — the monthly-maintenance sibling of Patch Tuesday).
6815            // Croner accepts `<dow>L` in the DOW field with verified
6816            // last-<dow>-of-month semantics, and `to_cron` passes it
6817            // through verbatim. A single weekday + `L` — bare `L` and
6818            // ranges are rejected (croner would read bare `L` as
6819            // Saturday, which is a confusing footgun).
6820            if let Some(day_part) = tok.strip_suffix(['L', 'l']) {
6821                // No `.trim()`: a cron DOW token can't carry internal
6822                // whitespace, so `"fri L"` must be *rejected* here (its
6823                // strip leaves `"fri "`, and `is_day` catches the space)
6824                // rather than trimmed into a clean `"fri"` that then
6825                // produces a malformed `fri L` cron downstream and a
6826                // confusing croner error (gemini #560).
6827                let d = day_part.to_ascii_lowercase();
6828                if d.is_empty() {
6829                    return invalid("`L` (last-weekday) needs a weekday before it, e.g. friL");
6830                }
6831                if d.contains('-') || !is_day(&d) {
6832                    return invalid(
6833                        "the part before L must be a single weekday (e.g. friL = last Friday)",
6834                    );
6835                }
6836                continue;
6837            }
6838            for part in tok.split('-') {
6839                let p = part.trim().to_ascii_lowercase();
6840                if p.is_empty() {
6841                    return invalid("empty range bound");
6842                }
6843                if p != "*" && !is_day(&p) {
6844                    return invalid(&format!("'{part}' is not a day"));
6845                }
6846            }
6847        }
6848        Ok(())
6849    }
6850
6851    /// For a one-shot (`at` carries a date), the absolute instant it
6852    /// fires in `tz`. `None` for a repeating calendar. Used to warn
6853    /// about a one-shot whose date is already in the past (it would
6854    /// never fire).
6855    pub fn oneshot_instant(&self, tz: ScheduleTz) -> Option<chrono::DateTime<chrono::Utc>> {
6856        let p = self.parse_at().ok()?;
6857        let date = p.date?;
6858        let naive = date.and_hms_opt(p.hour, p.minute, 0)?;
6859        tz.naive_to_utc(naive)
6860    }
6861
6862    /// The wall-clock time-of-day this calendar fires at (`None` if
6863    /// `at` is unparseable — validate() guards that). Used to detect
6864    /// a calendar whose fire time can never fall inside its
6865    /// `constraints.window` (claude #452 review).
6866    pub fn fire_time(&self) -> Option<chrono::NaiveTime> {
6867        let p = self.parse_at().ok()?;
6868        chrono::NaiveTime::from_hms_opt(p.hour, p.minute, 0)
6869    }
6870
6871    /// Lower to the cron string the scheduler engine runs. Repeating
6872    /// → 6-field `0 {min} {hour} * * {dow}`; one-shot → 7-field
6873    /// `0 {min} {hour} {day} {month} * {year}` (a past year never
6874    /// fires — that's what makes it one-shot).
6875    fn to_cron(&self) -> Result<String, String> {
6876        use chrono::Datelike;
6877        let ParsedAt { minute, hour, date } = self.parse_at()?;
6878        match date {
6879            Some(d) => {
6880                if !self.days.is_empty() {
6881                    return Err(
6882                        "when.at with a date is a one-shot and cannot be combined with days".into(),
6883                    );
6884                }
6885                Ok(format!(
6886                    "0 {minute} {hour} {} {} * {}",
6887                    d.day(),
6888                    d.month(),
6889                    d.year()
6890                ))
6891            }
6892            None => {
6893                let dow = if self.days.is_empty() {
6894                    "*".to_string()
6895                } else {
6896                    self.validate_days()?;
6897                    self.days.join(",")
6898                };
6899                Ok(format!("0 {minute} {hour} * * {dow}"))
6900            }
6901        }
6902    }
6903}
6904
6905/// The timezone a schedule's wall-clock fields (`when.at`,
6906/// `active.{from,until}`) are evaluated in (#418 Phase 2).
6907#[derive(
6908    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
6909)]
6910#[serde(rename_all = "snake_case")]
6911pub enum ScheduleTz {
6912    /// The running host's local timezone — the agent's for
6913    /// `runs_on: agent`, the backend server's otherwise. Default.
6914    #[default]
6915    Local,
6916    /// UTC — for timezone-independent schedules.
6917    Utc,
6918}
6919
6920impl ScheduleTz {
6921    /// Interpret a naive (zoneless) datetime as being in this tz and
6922    /// convert to UTC. On a DST *fold* (the local time occurs twice
6923    /// when clocks go back) we pick `.earliest()` rather than
6924    /// rejecting it; `None` is reserved for a true DST *gap* (a local
6925    /// time that never exists). `Utc` is fixed-offset so neither ever
6926    /// happens; `Local` is whatever timezone the running host is set
6927    /// to and *can* hit a gap/fold on any DST-observing host — not
6928    /// just the JST we run today (gemini + claude #432 review).
6929    fn naive_to_utc(self, naive: chrono::NaiveDateTime) -> Option<chrono::DateTime<chrono::Utc>> {
6930        use chrono::TimeZone;
6931        match self {
6932            ScheduleTz::Utc => Some(chrono::DateTime::from_naive_utc_and_offset(
6933                naive,
6934                chrono::Utc,
6935            )),
6936            ScheduleTz::Local => chrono::Local
6937                .from_local_datetime(&naive)
6938                .earliest()
6939                .map(|dt| dt.with_timezone(&chrono::Utc)),
6940        }
6941    }
6942
6943    /// The wall-clock time-of-day `now` reads as in this tz — used by
6944    /// [`Constraints::allows`] to test a maintenance window
6945    /// (#418 Phase 3). `Utc` is the naive UTC time; `Local` is the
6946    /// running host's local time.
6947    fn wall_time(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveTime {
6948        match self {
6949            ScheduleTz::Utc => now.time(),
6950            ScheduleTz::Local => now.with_timezone(&chrono::Local).time(),
6951        }
6952    }
6953
6954    /// The wall-clock *date* `now` reads as in this tz — used by
6955    /// [`Constraints::allows`] to test `skip_dates` (#418 holiday
6956    /// exclusion). Same tz semantics as [`Self::wall_time`].
6957    fn wall_date(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveDate {
6958        match self {
6959            ScheduleTz::Utc => now.date_naive(),
6960            ScheduleTz::Local => now.with_timezone(&chrono::Local).date_naive(),
6961        }
6962    }
6963
6964    /// Stable lowercase wire/display label (`local` / `utc`) — matches
6965    /// the serde `snake_case` representation. Used for the preview
6966    /// response's `tz` field so the JSON shape isn't coupled to the
6967    /// `Debug` repr (claude #578 review).
6968    pub fn as_str(self) -> &'static str {
6969        match self {
6970            ScheduleTz::Local => "local",
6971            ScheduleTz::Utc => "utc",
6972        }
6973    }
6974}
6975
6976impl std::fmt::Display for ScheduleTz {
6977    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6978        f.write_str(self.as_str())
6979    }
6980}
6981
6982/// `once` vs `{ every: <humantime> }` — shared by `per_pc` /
6983/// `per_target`. Untagged so the YAML stays the bare keyword or a
6984/// one-key map, nothing more ceremonial.
6985#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
6986#[serde(untagged)]
6987pub enum PerPolicy {
6988    /// The bare string `once`: succeed once, then skip permanently
6989    /// (cooldown = infinity).
6990    Once(OnceLiteral),
6991    /// Re-arm after the humantime interval, e.g. `{ every: 6h }`.
6992    Every(EverySpec),
6993}
6994
6995/// Single-variant enum so serde accepts exactly the string `once`
6996/// (a free-form `String` would swallow typos like `onec`).
6997#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
6998#[serde(rename_all = "snake_case")]
6999pub enum OnceLiteral {
7000    Once,
7001}
7002
7003/// `{ every: <humantime> }`. Standalone struct (not an inline
7004/// struct variant). `{ evry: 6h }` still fails to parse (the
7005/// required `every` key is missing), and the create boundaries
7006/// reject the unknown `evry` via [`crate::strict`] with its path —
7007/// while agents reading a future writer's extra fields tolerate
7008/// them (#492).
7009#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7010pub struct EverySpec {
7011    /// Humantime interval (`10m`, `6h`, `1d`...). Parsed lazily —
7012    /// [`Schedule::validate`] rejects garbage at create time.
7013    pub every: String,
7014}
7015
7016impl PerPolicy {
7017    /// The cooldown this policy lowers to: `once` = `None`
7018    /// (permanent skip), `every` = the interval.
7019    fn cooldown(&self) -> Option<String> {
7020        match self {
7021            PerPolicy::Once(_) => None,
7022            PerPolicy::Every(EverySpec { every }) => Some(every.clone()),
7023        }
7024    }
7025}
7026
7027impl std::fmt::Display for When {
7028    /// Operator-facing one-liner (`per_pc once` / `per_pc every 6h`
7029    /// / `at 09:00 [mon-fri]` / `at 2026-06-10 09:00`) for log
7030    /// lines, audit payloads and the API's `ScheduleSummary`.
7031    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7032        let policy = |p: &PerPolicy| match p {
7033            PerPolicy::Once(_) => "once".to_string(),
7034            PerPolicy::Every(EverySpec { every }) => format!("every {every}"),
7035        };
7036        match self {
7037            When::PerPc(p) => write!(f, "per_pc {}", policy(p)),
7038            When::PerTarget(p) => write!(f, "per_target {}", policy(p)),
7039            When::Calendar(c) if c.days.is_empty() => write!(f, "at {}", c.at),
7040            When::Calendar(c) => write!(f, "at {} [{}]", c.at, c.days.join(",")),
7041            When::On(triggers) => {
7042                let names: Vec<&str> = triggers.iter().map(|t| t.as_str()).collect();
7043                write!(f, "on [{}]", names.join(","))
7044            }
7045        }
7046    }
7047}
7048
7049impl OnTrigger {
7050    /// Lowercase wire/display label (matches the serde `snake_case`).
7051    pub fn as_str(self) -> &'static str {
7052        match self {
7053            OnTrigger::Startup => "startup",
7054            OnTrigger::Logon => "logon",
7055            OnTrigger::Lock => "lock",
7056            OnTrigger::Unlock => "unlock",
7057            OnTrigger::NetworkChange => "network_change",
7058        }
7059    }
7060}
7061
7062/// Optional validity window for a [`Schedule`] (#418 decision G).
7063/// Half-open `[from, until)`; either bound may be omitted. Bounds
7064/// are `YYYY-MM-DD` (= that day's 00:00 in the schedule's `tz`) or
7065/// full RFC3339 (offset is honored as-is, `tz` ignored). Kept as
7066/// strings so the JSON Schema the SPA editor consumes stays two
7067/// plain string fields, mirroring `jitter` / `starting_deadline`.
7068///
7069/// #418 Phase 2: bounds are evaluated in the schedule's top-level
7070/// `tz` (was UTC-only in Phase 1) so `tz: local` makes both the
7071/// calendar `at` AND the `active` window local — one consistent
7072/// timezone per schedule.
7073#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
7074pub struct Active {
7075    /// Dormant before this instant.
7076    #[serde(default, skip_serializing_if = "Option::is_none")]
7077    pub from: Option<String>,
7078    /// Dormant from this instant on (exclusive).
7079    #[serde(default, skip_serializing_if = "Option::is_none")]
7080    pub until: Option<String>,
7081}
7082
7083impl Active {
7084    /// `skip_serializing_if` helper — an empty window means "always
7085    /// active" and is omitted from the wire format entirely.
7086    pub fn is_empty(&self) -> bool {
7087        self.from.is_none() && self.until.is_none()
7088    }
7089
7090    /// Parse one bound: RFC3339 first (offset honored, `tz`
7091    /// ignored), then bare `YYYY-MM-DD` (00:00 in `tz`).
7092    pub fn parse_bound(s: &str, tz: ScheduleTz) -> Result<chrono::DateTime<chrono::Utc>, String> {
7093        if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
7094            return Ok(dt.with_timezone(&chrono::Utc));
7095        }
7096        if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
7097            let midnight = d.and_hms_opt(0, 0, 0).expect("00:00:00 is always valid");
7098            return tz.naive_to_utc(midnight).ok_or_else(|| {
7099                format!("active: bound '{s}' falls in a DST gap for the schedule's tz")
7100            });
7101        }
7102        Err(format!(
7103            "active: unparseable bound '{s}' (want YYYY-MM-DD or RFC3339)"
7104        ))
7105    }
7106
7107    /// Is `now` inside the window? Unparseable bounds are treated
7108    /// as absent here (fail-open) — [`Schedule::validate`] is the
7109    /// place that rejects them loudly; this runs on every tick and
7110    /// must never panic on a stale KV blob.
7111    pub fn contains(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
7112        let bound = |s: &Option<String>| s.as_deref().and_then(|s| Self::parse_bound(s, tz).ok());
7113        if bound(&self.from).is_some_and(|from| now < from) {
7114            return false;
7115        }
7116        if bound(&self.until).is_some_and(|until| now >= until) {
7117            return false;
7118        }
7119        true
7120    }
7121}
7122
7123/// Host-environment gate (#418 `constraints.require`). Fire only when
7124/// the target host is in the required state. Sensed **in-process by the
7125/// agent** (Win32), so it is `runs_on: agent` only — the backend cannot
7126/// read a target host's power/idle state ([`Schedule::validate`]
7127/// rejects it on `runs_on: backend`, symmetric with `when: { on }`).
7128///
7129/// Evaluated at fire time as a skip-this-tick gate (NOT in
7130/// [`Constraints::allows`], which stays pure for `preview`): a reconcile
7131/// cadence re-checks every minute (so it effectively defers until the
7132/// state is met — the intended pairing); a `calendar` fire that lands
7133/// while the state is unmet is simply missed, same as `window`. It is
7134/// therefore a *runtime* gate and does not appear in `preview`.
7135// No `Eq`: `cpu_below: Option<f64>` is only `PartialEq` (f64 is not Eq).
7136#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
7137pub struct Require {
7138    /// Fire only while on **AC power** (skip on battery). Reads
7139    /// `GetSystemPowerStatus`; an unknown/unreadable status is treated
7140    /// as not-on-AC (fail-closed — a restrictive gate must not fire
7141    /// when it can't confirm the condition). `false` (default) = no
7142    /// power requirement.
7143    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
7144    pub ac_power: bool,
7145    /// Fire only when the active console session has had **no keyboard /
7146    /// mouse input for at least this long** (humantime, e.g. `"10m"`) —
7147    /// "don't run while the user is actively working". Input-based
7148    /// (simpler than Task Scheduler's CPU/disk-aware idle). A
7149    /// headless / disconnected console (no interactive user) trivially
7150    /// satisfies it. `None` (default) = no idle requirement. Parsed
7151    /// lazily; [`Schedule::validate`] rejects garbage at create time.
7152    #[serde(default, skip_serializing_if = "Option::is_none")]
7153    pub idle: Option<String>,
7154    /// Fire only when the **whole-machine CPU usage is below this
7155    /// percent** (0–100; e.g. `20.0` = "system CPU < 20%") — "don't run
7156    /// while the box is busy". Reuses the agent's `host_perf` system CPU%
7157    /// sample (`sysinfo` mean over cores), so the reading is up to one
7158    /// `host_perf` cadence old (default 60s) — fine as a "generally
7159    /// busy?" proxy, and more accurate than a fresh one-shot read (CPU%
7160    /// needs two samples). An unavailable sample (host_perf not warmed
7161    /// up yet, or stale) is treated as "not below" (fail-closed — a
7162    /// restrictive gate must not fire when it can't confirm). `None`
7163    /// (default) = no CPU requirement. [`Schedule::validate`] rejects an
7164    /// out-of-range value at create time.
7165    #[serde(default, skip_serializing_if = "Option::is_none")]
7166    pub cpu_below: Option<f64>,
7167    /// Fire only when the host has **internet connectivity** (Windows
7168    /// `GetNetworkConnectivityHint` reports InternetAccess) — "don't run
7169    /// until online" for jobs that download / phone home. A captive
7170    /// portal (ConstrainedInternetAccess), LAN-only (LocalAccess), or
7171    /// unknown/unreadable state is treated as offline (fail-closed) — a
7172    /// portal would just fail a download, so we hold the run. For VPN /
7173    /// SASE / app-specific conditions, use a custom script gate (separate
7174    /// slice). `false` (default) = no network requirement.
7175    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
7176    pub network: bool,
7177}
7178
7179impl Require {
7180    /// `skip_serializing_if` helper for an embedded empty `require`.
7181    pub fn is_empty(&self) -> bool {
7182        !self.ac_power && self.idle.is_none() && self.cpu_below.is_none() && !self.network
7183    }
7184
7185    /// Parsed minimum-idle duration (`None` = no idle requirement, or an
7186    /// unparseable value — `validate` rejects the latter at create time).
7187    pub fn min_idle(&self) -> Option<std::time::Duration> {
7188        self.idle
7189            .as_deref()
7190            .and_then(|s| humantime::parse_duration(s.trim()).ok())
7191    }
7192
7193    /// First unparseable field for create-time rejection (mirrors
7194    /// [`Constraints::bad_skip_date`]).
7195    pub fn bad_idle(&self) -> Option<String> {
7196        self.idle.as_deref().and_then(|s| {
7197            humantime::parse_duration(s.trim())
7198                .err()
7199                .map(|e| format!("constraints.require.idle: invalid duration '{s}': {e}"))
7200        })
7201    }
7202}
7203
7204/// Host-environment state sensed by the agent, fed to [`require_met`].
7205/// A named struct (not positional args) so the growing set of sensed
7206/// signals — several of them `bool` — can't be transposed at a call
7207/// site. The Win32 sensing lives in `kanade-agent::env_gate`.
7208#[derive(Debug, Clone, Copy, Default)]
7209pub struct EnvState {
7210    /// Is the host on AC power (`false` if on battery or unreadable).
7211    pub ac_online: bool,
7212    /// How long the console has been idle (`None` = couldn't determine).
7213    pub idle: Option<std::time::Duration>,
7214    /// Whole-machine CPU usage 0–100 (`None` = no sample yet).
7215    pub cpu_pct: Option<f64>,
7216    /// Does the host have internet connectivity (`false` if offline /
7217    /// LAN-only / unreadable).
7218    pub network_up: bool,
7219}
7220
7221/// Pure env-gate decision (#418 `constraints.require`). The Win32
7222/// sensing lives in the agent (`kanade-agent::env_gate`); this is the
7223/// testable core, fed the already-sensed [`EnvState`]. Deliberately a
7224/// free fn (not folded into [`Constraints::allows`]) so `allows` stays
7225/// pure and `preview` never evaluates a runtime gate. Each set
7226/// requirement is a restrictive AND: any unmet (or unknown) gate skips.
7227pub fn require_met(req: &Require, env: &EnvState) -> bool {
7228    if req.ac_power && !env.ac_online {
7229        return false;
7230    }
7231    if let Some(min) = req.min_idle() {
7232        match env.idle {
7233            Some(d) if d >= min => {}
7234            _ => return false,
7235        }
7236    }
7237    if let Some(max) = req.cpu_below {
7238        match env.cpu_pct {
7239            Some(p) if p < max => {}
7240            _ => return false,
7241        }
7242    }
7243    if req.network && !env.network_up {
7244        return false;
7245    }
7246    true
7247}
7248
7249/// [`Active`] decides *over what date range* a schedule is live,
7250/// `Constraints` decides *when, within an active period,* a fire is
7251/// allowed: `window` (a maintenance time-of-day window),
7252/// `max_concurrent` (a fleet-wide running-instance cap), `skip_dates`
7253/// (holiday exclusion) and `require` (host-environment gates, agent-only
7254/// — see [`Require`]).
7255// No `Eq`: contains `require: Option<Require>` which holds an f64.
7256#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
7257pub struct Constraints {
7258    /// `"HH:MM-HH:MM"` wall-clock window (evaluated in the schedule's
7259    /// `tz`). Fires outside it are skipped — mainly for reconcile
7260    /// cadences ("patrol every 6h, but only fire overnight") and
7261    /// daytime change-freezes. `start > end` crosses midnight
7262    /// (`"22:00-05:00"` = 22:00 through 05:00 next morning). Parsed
7263    /// lazily; [`Schedule::validate`] rejects garbage at create time.
7264    #[serde(default, skip_serializing_if = "Option::is_none")]
7265    pub window: Option<String>,
7266    /// Fleet-wide cap on how many instances of this schedule's job may
7267    /// run **at the same time** (#418 "同時実行ハード上限"). The
7268    /// backend scheduler counts the job's still-in-flight runs
7269    /// (`execution_results.finished_at IS NULL`) each tick and only
7270    /// dispatches to as many remaining pcs as there are free slots —
7271    /// a rolling window that refills as runs complete. Useful for
7272    /// disk/CPU/network-heavy jobs you don't want hammering the whole
7273    /// fleet at once.
7274    ///
7275    /// **Backend-only** (it needs a central counter): combining it
7276    /// with `runs_on: agent` is rejected by [`Schedule::validate`]
7277    /// (#418 decision E — "中央上限には中央が要る"). Most meaningful
7278    /// for `per_pc` reconcile cadences, where the poll re-ticks and
7279    /// refills slots. `None` (default) = no cap.
7280    #[serde(default, skip_serializing_if = "Option::is_none")]
7281    pub max_concurrent: Option<u32>,
7282    /// Calendar dates the schedule must **not** fire on — holidays,
7283    /// blackout days, one-off freeze dates (#418 "祝日除外"). Each is
7284    /// `YYYY-MM-DD`, evaluated as a wall-clock date in the schedule's
7285    /// `tz`. Applies to every `when` shape (a reconcile cadence skips
7286    /// the whole day; a calendar fire landing on the date is
7287    /// suppressed) and is honored by both the live scheduler and
7288    /// `preview`, since both gate on [`Constraints::allows`]. Empty
7289    /// (default) = no skips. Operator-supplied: there is no built-in
7290    /// holiday calendar — list the dates you care about. Parsed lazily;
7291    /// [`Schedule::validate`] rejects a malformed date at create time.
7292    #[serde(default, skip_serializing_if = "Vec::is_empty")]
7293    pub skip_dates: Vec<String>,
7294    /// Host-environment gate (#418): fire only when the target host is
7295    /// in the required state (on AC power, idle). Agent-sensed at fire
7296    /// time, `runs_on: agent` only. See [`Require`]. `None` (default) =
7297    /// no environment requirement.
7298    #[serde(default, skip_serializing_if = "Option::is_none")]
7299    pub require: Option<Require>,
7300}
7301
7302impl Constraints {
7303    /// `skip_serializing_if` helper — empty constraints are omitted
7304    /// from the wire format entirely.
7305    pub fn is_empty(&self) -> bool {
7306        self.window.is_none()
7307            && self.max_concurrent.is_none()
7308            && self.skip_dates.is_empty()
7309            && self.require.as_ref().is_none_or(Require::is_empty)
7310    }
7311
7312    /// The first unparseable `skip_dates` entry, if any — the
7313    /// scheduler logs it at register time so a fail-closed
7314    /// (never-firing) schedule from a hand-edited KV blob is
7315    /// diagnosable, mirroring [`Schedule::bad_window`].
7316    pub fn bad_skip_date(&self) -> Option<String> {
7317        self.skip_dates.iter().find_map(|s| {
7318            chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d")
7319                .err()
7320                .map(|e| format!("constraints.skip_dates: invalid date '{s}': {e}"))
7321        })
7322    }
7323
7324    /// Parse `"HH:MM-HH:MM"` into `(start, end)`. Equal bounds are an
7325    /// error (a zero-width or all-day window is ambiguous — write no
7326    /// window for "always").
7327    pub fn parse_window(s: &str) -> Result<(chrono::NaiveTime, chrono::NaiveTime), String> {
7328        let (a, b) = s
7329            .split_once('-')
7330            .ok_or_else(|| format!("constraints.window: '{s}' must be 'HH:MM-HH:MM'"))?;
7331        let parse = |part: &str| {
7332            chrono::NaiveTime::parse_from_str(part.trim(), "%H:%M")
7333                .map_err(|e| format!("constraints.window: invalid time '{}': {e}", part.trim()))
7334        };
7335        let (start, end) = (parse(a)?, parse(b)?);
7336        if start == end {
7337            return Err(format!(
7338                "constraints.window: start and end are equal ('{s}'); omit window for 'always'"
7339            ));
7340        }
7341        Ok((start, end))
7342    }
7343
7344    /// Is a fire allowed at `now` (evaluated in `tz`)? No window =
7345    /// always allowed. Half-open `[start, end)`; `start > end`
7346    /// crosses midnight.
7347    ///
7348    /// **Fail-closed** on an unparseable window (returns `false`,
7349    /// gemini #452 review): a window is a *restrictive* constraint
7350    /// (change-freeze / overnight-only), so a corrupt one must NOT
7351    /// silently allow fires during the restricted hours. Bad windows
7352    /// are rejected at create time by [`Schedule::validate`]; this
7353    /// only bites a hand-edited KV blob, where blocking is the safe
7354    /// direction. The scheduler warns at register time
7355    /// ([`Schedule::bad_window`]) so a stuck schedule is diagnosable.
7356    /// The tick path never panics regardless.
7357    pub fn allows(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
7358        // #418 holiday / blackout dates: never fire on a listed wall
7359        // date (in `tz`). Checked before the window since a skipped day
7360        // overrides any within-window allowance. Fail-closed on a
7361        // corrupt entry (same posture as `window`): a skip date is a
7362        // *restrictive* constraint, so a garbled one must not silently
7363        // re-enable fires — it blocks until fixed (`validate` rejects it
7364        // at create time; `bad_skip_date` lets the scheduler warn).
7365        if !self.skip_dates.is_empty() {
7366            let today = tz.wall_date(now);
7367            let blocked = self.skip_dates.iter().any(|s| {
7368                match chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d") {
7369                    Ok(d) => d == today,
7370                    Err(_) => true, // corrupt entry → fail-closed (block)
7371                }
7372            });
7373            if blocked {
7374                return false;
7375            }
7376        }
7377        match self.window.as_deref() {
7378            // No window → always allowed.
7379            None => true,
7380            // Window set: membership, or fail-closed if unparseable
7381            // (`window_contains` returns None for a corrupt window).
7382            Some(_) => self.window_contains(tz.wall_time(now)).unwrap_or(false),
7383        }
7384    }
7385
7386    /// Membership of a wall-clock time-of-day in the window. `None`
7387    /// when there is no window or it's unparseable (callers decide
7388    /// the failure direction). `start > end` crosses midnight.
7389    fn window_contains(&self, t: chrono::NaiveTime) -> Option<bool> {
7390        let (start, end) = Self::parse_window(self.window.as_deref()?).ok()?;
7391        Some(if start <= end {
7392            start <= t && t < end
7393        } else {
7394            t >= start || t < end
7395        })
7396    }
7397}
7398
7399/// What to do when a fire's script fails (#418 Phase 4 — the "高"
7400/// retry/backoff gap). Where [`Constraints`] gates *whether* a fire
7401/// happens, `OnFailure` decides what happens *after* one ran and
7402/// came back bad. Only `retry` so far; future `notify` / `disable`
7403/// would join the same namespace.
7404#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
7405pub struct OnFailure {
7406    /// Re-run the script in-process when it exits non-zero (or times
7407    /// out), up to a cap, with a fixed backoff between attempts.
7408    /// `None` (default) = no retry: a failed run is published as-is
7409    /// and (for reconcile cadences) simply re-fires on the next poll
7410    /// tick. See [`Retry`].
7411    #[serde(default, skip_serializing_if = "Option::is_none")]
7412    pub retry: Option<Retry>,
7413}
7414
7415impl OnFailure {
7416    /// `skip_serializing_if` helper — an empty policy is omitted from
7417    /// the wire format entirely.
7418    pub fn is_empty(&self) -> bool {
7419        self.retry.is_none()
7420    }
7421
7422    /// Lower the operator-facing `retry` (humantime backoff) onto the
7423    /// engine vocabulary the agent's executor runs on (backoff in
7424    /// whole seconds). Single seam shared by the backend command
7425    /// builder and the agent's local scheduler so the two stamp the
7426    /// same [`crate::wire::RetrySpec`] onto every Command. Returns
7427    /// `None` when there is no retry policy or the backoff is
7428    /// unparseable (validate() rejects the latter at create time;
7429    /// this stays fail-safe = "no retry" for a hand-edited KV blob
7430    /// rather than panicking on the fire path).
7431    pub fn lowered_retry(&self) -> Option<crate::wire::RetrySpec> {
7432        let r = self.retry.as_ref()?;
7433        let backoff_secs = humantime::parse_duration(&r.backoff).ok()?.as_secs();
7434        Some(crate::wire::RetrySpec {
7435            max: r.max,
7436            backoff_secs,
7437        })
7438    }
7439}
7440
7441/// Fixed-backoff retry policy (#418 Phase 4). `max` is the number of
7442/// *additional* attempts after the first run (so `max: 3` = up to 4
7443/// total executions); `backoff` is the humantime delay slept between
7444/// attempts. The retry happens fire-side (inside `kanade fire` /
7445/// `handle_command`) on every OS for the PoC — the Windows-native
7446/// "restart on failure" Task Scheduler path is deferred to the
7447/// native-delegation phase (#418 decision H).
7448#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7449pub struct Retry {
7450    /// Max additional attempts after the first failure. Bounded
7451    /// `1..=10` by [`Schedule::validate`] — a typo'd `max: 1000`
7452    /// with a short backoff would otherwise pin a flapping script in
7453    /// a tight loop for the whole window.
7454    pub max: u32,
7455    /// Humantime delay slept between attempts (`"10m"`, `"30s"`).
7456    pub backoff: String,
7457}
7458
7459/// Fleet-wide change-freeze (#418 Phase 5 — the "メンテナンス窓 /
7460/// 変更凍結" gap's global half). Where [`Constraints::window`] is a
7461/// *per-schedule* time-of-day gate, a `Freeze` is a *single, fleet-
7462/// global* "stop all automated change" switch the operator flips
7463/// during an incident or a year-end change-freeze. It lives in its
7464/// own KV singleton ([`crate::kv::KEY_FREEZE`]); when present and
7465/// active, both the backend scheduler and every agent's local
7466/// scheduler skip *every* fire.
7467///
7468/// Shapes:
7469/// * `{}` (no bounds) — frozen indefinitely until the operator
7470///   clears it (incident "big red button").
7471/// * `{ from, until }` — frozen only within `[from, until)`,
7472///   evaluated in `tz` (planned change-freeze; auto-thaws).
7473///
7474/// The KV key being *absent* means "not frozen" — so clearing the
7475/// freeze is a KV delete, and `is_active` only ever runs on a freeze
7476/// the operator actually set.
7477#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
7478pub struct Freeze {
7479    /// Frozen from this instant (RFC3339 or bare `YYYY-MM-DD` in
7480    /// `tz`). `None` ⇒ frozen from the beginning of time.
7481    #[serde(default, skip_serializing_if = "Option::is_none")]
7482    pub from: Option<String>,
7483    /// Thawed from this instant on, exclusive. `None` ⇒ frozen with
7484    /// no scheduled end (manual clear required).
7485    #[serde(default, skip_serializing_if = "Option::is_none")]
7486    pub until: Option<String>,
7487    /// Operator-supplied note surfaced on the freeze-skip log and the
7488    /// SPA banner ("year-end change freeze", "INC-1234"). Advisory.
7489    #[serde(default, skip_serializing_if = "Option::is_none")]
7490    pub reason: Option<String>,
7491    /// Timezone the bare-date bounds are evaluated in (RFC3339 bounds
7492    /// carry their own offset). Defaults to host-local like a
7493    /// schedule's `tz`.
7494    #[serde(default)]
7495    pub tz: ScheduleTz,
7496}
7497
7498impl Freeze {
7499    /// Is the fleet frozen at `now`? An empty window (`from`/`until`
7500    /// both absent) is frozen unconditionally; otherwise membership of
7501    /// `[from, until)` in `tz`. Half-open like [`Active::contains`],
7502    /// but **fails CLOSED** on an unparseable bound — a freeze is a
7503    /// safety switch, so a corrupt window (only reachable via a
7504    /// hand-edited KV blob; `validate` rejects it at set time) must
7505    /// mean "frozen", not "fire normally" (coderabbit #472). This is
7506    /// the one deliberate divergence from `active`'s fail-OPEN
7507    /// behaviour, where an unparseable bound dormant-skips a schedule.
7508    pub fn is_active(&self, now: chrono::DateTime<chrono::Utc>) -> bool {
7509        // Parse a bound; an unparseable one short-circuits the whole
7510        // check to `true` (frozen) via the closure's `None` sentinel
7511        // handled below.
7512        let bound = |s: &Option<String>| -> Result<Option<chrono::DateTime<chrono::Utc>>, ()> {
7513            match s.as_deref() {
7514                None => Ok(None),
7515                Some(raw) => Active::parse_bound(raw, self.tz).map(Some).map_err(|_| ()),
7516            }
7517        };
7518        let (from, until) = match (bound(&self.from), bound(&self.until)) {
7519            (Ok(f), Ok(u)) => (f, u),
7520            // Any corrupt bound → fail closed (frozen).
7521            _ => return true,
7522        };
7523        if from.is_some_and(|f| now < f) {
7524            return false;
7525        }
7526        if until.is_some_and(|u| now >= u) {
7527            return false;
7528        }
7529        true
7530    }
7531
7532    /// Reject unparseable bounds / `from >= until` at set time (the
7533    /// API + CLI counterpart to [`Schedule::validate`]).
7534    pub fn validate(&self) -> Result<(), String> {
7535        let from = self
7536            .from
7537            .as_deref()
7538            .map(|s| Active::parse_bound(s, self.tz))
7539            .transpose()
7540            .map_err(|e| e.replace("active:", "freeze:"))?;
7541        let until = self
7542            .until
7543            .as_deref()
7544            .map(|s| Active::parse_bound(s, self.tz))
7545            .transpose()
7546            .map_err(|e| e.replace("active:", "freeze:"))?;
7547        if let (Some(f), Some(u)) = (from, until) {
7548            if f >= u {
7549                return Err(format!(
7550                    "freeze.from ({}) must be strictly before freeze.until ({})",
7551                    self.from.as_deref().unwrap_or_default(),
7552                    self.until.as_deref().unwrap_or_default(),
7553                ));
7554            }
7555        }
7556        Ok(())
7557    }
7558}
7559
7560/// The system-generated poll cadence every reconcile-shaped `when`
7561/// lowers to. Operators never write this: the real inter-run
7562/// spacing is the `every` cooldown; this only bounds "how soon do
7563/// we notice somebody is due" (#418 decision B took the poll
7564/// period away from the operator).
7565pub const POLL_CRON: &str = "0 * * * * *";
7566
7567/// What a [`When`] lowers to — the exact (cron, mode, cooldown)
7568/// trio the pre-#418 engine ran on. Keeping the engine vocabulary
7569/// unchanged is what lets Phase 1 swap the operator surface without
7570/// touching the tick / dedup machinery.
7571pub struct Lowered {
7572    /// Cron handed to `tokio-cron-scheduler` — [`POLL_CRON`] for
7573    /// reconcile shapes, a 6/7-field cron for calendar shapes.
7574    pub cron: String,
7575    /// Dedup semantics for `decide_fire`.
7576    pub mode: ExecMode,
7577    /// Humantime re-arm interval (`None` = succeed once, skip
7578    /// forever).
7579    pub cooldown: Option<String>,
7580    /// Timezone to evaluate `cron` in (#418 Phase 2). The scheduler
7581    /// passes this to `Job::new_async_tz`. Reconcile shapes carry
7582    /// the schedule's tz too even though POLL_CRON is tz-agnostic,
7583    /// so the same value drives the `active`-window check.
7584    pub tz: ScheduleTz,
7585}
7586
7587impl Schedule {
7588    /// The error message if this schedule's `constraints.window` is
7589    /// set but unparseable, else `None`. The scheduler logs this at
7590    /// register time so a fail-closed (never-firing) schedule from a
7591    /// hand-edited KV blob is diagnosable (gemini #452 review).
7592    pub fn bad_window(&self) -> Option<String> {
7593        let w = self.constraints.window.as_deref()?;
7594        Constraints::parse_window(w).err()
7595    }
7596
7597    /// True when this is a `calendar` schedule whose fire time can
7598    /// never fall inside its `constraints.window` — the cron fires,
7599    /// the window check rejects it, and (firing only at that
7600    /// time-of-day) it effectively never runs. An easy misconfig to
7601    /// set up by accident; the scheduler warns at register time
7602    /// (claude #452 review). Reconcile shapes poll every minute, so
7603    /// they always catch the window opening and aren't affected.
7604    pub fn calendar_outside_window(&self) -> bool {
7605        let When::Calendar(c) = &self.when else {
7606            return false;
7607        };
7608        let Some(t) = c.fire_time() else {
7609            return false;
7610        };
7611        matches!(self.constraints.window_contains(t), Some(false))
7612    }
7613
7614    /// Up to `count` future instants this schedule will fire, as
7615    /// absolute UTC, strictly after `now` — the dry-run / preview
7616    /// surface (#418 "ドライラン / プレビュー"). Only **calendar**
7617    /// schedules have discrete fire times; reconcile shapes
7618    /// (`per_pc`/`per_target`) poll every minute gated by cooldown, so
7619    /// they return an empty vec and the caller describes the cadence
7620    /// instead. Occurrences outside the `active.{from,until}` window or
7621    /// the `constraints.window` are **skipped**, so the list reflects
7622    /// when the schedule will ACTUALLY run, not the raw cron ticks.
7623    /// Evaluated in the schedule's `tz`, exactly like the scheduler's
7624    /// `Job::new_async_tz`, and with the same croner config the
7625    /// scheduler / [`Schedule::validate`] use, so a preview can never
7626    /// disagree with a real fire. A schedule that can never fire (a
7627    /// calendar time wholly outside its window, a past one-shot,
7628    /// `enabled: false` is *not* considered here — callers gate on
7629    /// `enabled` separately) yields an empty vec.
7630    pub fn preview_fires(
7631        &self,
7632        now: chrono::DateTime<chrono::Utc>,
7633        count: usize,
7634    ) -> Vec<chrono::DateTime<chrono::Utc>> {
7635        use croner::parser::{CronParser, Seconds};
7636        if !matches!(self.when, When::Calendar(_)) {
7637            return Vec::new();
7638        }
7639        // Same lowering + croner config as `next_calendar_fire` and the
7640        // live scheduler, so a preview can never disagree with a real
7641        // fire. `preview_fires` adds the N-occurrence walk and the
7642        // active / window filtering on top of that single seam.
7643        let lowered = self.lowered();
7644        let Ok(cron) = CronParser::builder()
7645            .seconds(Seconds::Required)
7646            .dom_and_dow(true)
7647            .build()
7648            .parse(&lowered.cron)
7649        else {
7650            return Vec::new();
7651        };
7652        let accept = |utc: chrono::DateTime<chrono::Utc>| {
7653            self.active.contains(utc, self.tz) && self.constraints.allows(utc, self.tz)
7654        };
7655        match self.tz {
7656            ScheduleTz::Utc => Self::next_occurrences(&cron, now, count, accept),
7657            ScheduleTz::Local => {
7658                Self::next_occurrences(&cron, now.with_timezone(&chrono::Local), count, accept)
7659            }
7660        }
7661    }
7662
7663    /// Walk croner forward from `after` collecting up to `count`
7664    /// accepted occurrences (converted to UTC). Generic over the tz the
7665    /// cron is evaluated in so `preview_fires` can run it in either
7666    /// `Utc` or `Local` without duplicating the loop.
7667    fn next_occurrences<Tz>(
7668        cron: &croner::Cron,
7669        after: chrono::DateTime<Tz>,
7670        count: usize,
7671        accept: impl Fn(chrono::DateTime<chrono::Utc>) -> bool,
7672    ) -> Vec<chrono::DateTime<chrono::Utc>>
7673    where
7674        Tz: chrono::TimeZone,
7675    {
7676        // Bound the scan so an `active`/window dead-end (every future
7677        // tick rejected) can't spin forever: ~4096 raw ticks covers
7678        // >10y of a daily calendar while staying instant for croner.
7679        const SCAN_CAP: usize = 4096;
7680        let mut out = Vec::with_capacity(count.min(SCAN_CAP));
7681        let mut cursor = after;
7682        let mut scanned = 0usize;
7683        while out.len() < count && scanned < SCAN_CAP {
7684            scanned += 1;
7685            let Ok(next) = cron.find_next_occurrence(&cursor, false) else {
7686                break;
7687            };
7688            let utc = next.with_timezone(&chrono::Utc);
7689            if accept(utc) {
7690                out.push(utc);
7691            }
7692            // `find_next_occurrence(.., inclusive = false)` already
7693            // advances strictly past `cursor`, so handing it `next`
7694            // verbatim gets the following occurrence — no manual +1s
7695            // nudge (and `DateTime<Tz>` is `Copy`, so no clone).
7696            cursor = next;
7697        }
7698        out
7699    }
7700
7701    /// Lower the operator-facing `when` onto the engine vocabulary.
7702    /// Single seam shared by the backend scheduler and the agent's
7703    /// local scheduler so the two can never drift.
7704    pub fn lowered(&self) -> Lowered {
7705        let tz = self.tz;
7706        match &self.when {
7707            When::PerPc(p) => Lowered {
7708                cron: POLL_CRON.into(),
7709                mode: ExecMode::OncePerPc,
7710                cooldown: p.cooldown(),
7711                tz,
7712            },
7713            When::PerTarget(p) => Lowered {
7714                cron: POLL_CRON.into(),
7715                mode: ExecMode::OncePerTarget,
7716                cooldown: p.cooldown(),
7717                tz,
7718            },
7719            // `to_cron` only fails on a malformed `at` (rejected by
7720            // validate() at create time). For a hand-edited KV blob
7721            // that slipped past, emit a deliberately-invalid cron so
7722            // register()'s Job::new_async_tz fails → warn+skip,
7723            // rather than firing at the wrong time.
7724            When::Calendar(c) => Lowered {
7725                cron: c
7726                    .to_cron()
7727                    .unwrap_or_else(|_| "# invalid calendar at".into()),
7728                mode: ExecMode::EveryTick,
7729                cooldown: None,
7730                tz,
7731            },
7732            // Event triggers have no cron — the agent fires them from an
7733            // OS event source. The `# event-trigger` cron is never
7734            // registered (the scheduler branches on `is_event()` first),
7735            // but keep it deliberately-invalid as a belt-and-suspenders
7736            // so a stray registration would fail rather than misfire.
7737            When::On(_) => Lowered {
7738                cron: "# event-trigger (no cron)".into(),
7739                mode: ExecMode::Event,
7740                cooldown: None,
7741                tz,
7742            },
7743        }
7744    }
7745
7746    /// True when this schedule fires from an OS event (`when: { on }`)
7747    /// rather than a clock — the agent skips `tokio-cron` registration
7748    /// for these and drives them from boot / session-change instead.
7749    pub fn is_event(&self) -> bool {
7750        matches!(self.when, When::On(_))
7751    }
7752
7753    /// The OS event triggers this schedule listens for, or `&[]` when it
7754    /// is not an event schedule.
7755    pub fn event_triggers(&self) -> &[OnTrigger] {
7756        match &self.when {
7757            When::On(t) => t,
7758            _ => &[],
7759        }
7760    }
7761
7762    /// The next absolute (UTC) time this schedule fires, or `None` when
7763    /// it has no discrete upcoming fire to preview.
7764    ///
7765    /// Used by the KLP `maintenance.list` preview ("what's about to
7766    /// happen on my PC", SPEC §2.1). Returns `None` for:
7767    ///
7768    /// - reconcile shapes (`per_pc` / `per_target`) — they lower to the
7769    ///   every-minute [`POLL_CRON`] and re-converge state continuously,
7770    ///   so "next fire" is always ~60s away and means nothing to a user
7771    ///   previewing upcoming maintenance;
7772    /// - a calendar schedule whose lowered cron won't parse (a
7773    ///   hand-edited KV blob that slipped past [`Schedule::validate`]);
7774    /// - a cron with no future occurrence.
7775    ///
7776    /// The wall-clock fire is evaluated in the schedule's own `tz`
7777    /// (matching the live tick's `Job::new_async_tz`) then normalised
7778    /// to UTC for the wire. `inclusive = false`: strictly the *next*
7779    /// fire after `now`, never one matching the current instant.
7780    pub fn next_calendar_fire(
7781        &self,
7782        now: chrono::DateTime<chrono::Utc>,
7783    ) -> Option<chrono::DateTime<chrono::Utc>> {
7784        if !matches!(self.when, When::Calendar(_)) {
7785            return None;
7786        }
7787        let lowered = self.lowered();
7788        // Same parser configuration tokio-cron-scheduler 0.15 uses
7789        // internally, so this can never compute a fire the live
7790        // scheduler wouldn't (seconds required, DOM-and-DOW honored).
7791        let cron = croner::parser::CronParser::builder()
7792            .seconds(croner::parser::Seconds::Required)
7793            .dom_and_dow(true)
7794            .build()
7795            .parse(&lowered.cron)
7796            .ok()?;
7797        match lowered.tz {
7798            ScheduleTz::Utc => cron.find_next_occurrence(&now, false).ok(),
7799            ScheduleTz::Local => {
7800                let now_local = now.with_timezone(&chrono::Local);
7801                cron.find_next_occurrence(&now_local, false)
7802                    .ok()
7803                    .map(|t| t.with_timezone(&chrono::Utc))
7804            }
7805        }
7806    }
7807
7808    /// Cross-field semantic checks that don't fit pure serde derive
7809    /// — the [`Manifest::validate`] counterpart (#418 decision F;
7810    /// pre-Phase-1 a broken schedule was accepted at create time
7811    /// and silently warn-skipped at tick time). Run at every create
7812    /// site: `kanade schedule create` (client-side) and
7813    /// `POST /api/schedules`. The job_id-exists check lives in the
7814    /// API handler instead — it needs the JOBS KV.
7815    pub fn validate(&self) -> Result<(), String> {
7816        if matches!(self.runs_on, RunsOn::Agent) && matches!(self.when, When::PerTarget(_)) {
7817            return Err(
7818                "when.per_target needs fleet-wide completion data and is backend-only; \
7819                 it cannot be combined with runs_on: agent (each agent self-schedules, \
7820                 so per-target dedup would be deduping across a target of 1)"
7821                    .into(),
7822            );
7823        }
7824        // #418 event triggers: the agent owns the OS event source
7825        // (boot / session-change), so `when: { on }` is agent-only and
7826        // needs at least one trigger.
7827        if let When::On(triggers) = &self.when {
7828            if !matches!(self.runs_on, RunsOn::Agent) {
7829                return Err(
7830                    "when.on (OS event trigger) is fired by the agent's own event \
7831                     source, so it requires runs_on: agent"
7832                        .into(),
7833                );
7834            }
7835            if triggers.is_empty() {
7836                return Err(
7837                    "when.on must list at least one trigger (e.g. [startup, logon])".into(),
7838                );
7839            }
7840        }
7841        if let Some(cd) = self.lowered().cooldown.as_deref() {
7842            humantime::parse_duration(cd)
7843                .map_err(|e| format!("when.every: invalid duration '{cd}': {e}"))?;
7844        }
7845        if let When::Calendar(c) = &self.when {
7846            // Lower the calendar form to its cron (catches a bad `at`
7847            // and the date+days conflict), then validate that cron
7848            // with the same parser configuration tokio-cron-scheduler
7849            // 0.15 uses internally (croner, seconds required,
7850            // DOM-and-DOW both honored, year optional) — create-time
7851            // validation can never accept what register() rejects.
7852            let cron = c.to_cron()?;
7853            croner::parser::CronParser::builder()
7854                .seconds(croner::parser::Seconds::Required)
7855                .dom_and_dow(true)
7856                .build()
7857                .parse(&cron)
7858                .map_err(|e| format!("when.at lowered to invalid cron '{cron}': {e}"))?;
7859        }
7860        // The other humantime strings on the schedule (claude #419
7861        // review): runtime degrades gracefully on both (bad jitter →
7862        // silent no-op, bad starting_deadline → warn + skipped tick),
7863        // but "rejected at create time" should cover every field the
7864        // operator can typo, not just `when`.
7865        if let Some(j) = &self.plan.jitter {
7866            humantime::parse_duration(j)
7867                .map_err(|e| format!("jitter: invalid duration '{j}': {e}"))?;
7868        }
7869        if let Some(sd) = &self.starting_deadline {
7870            humantime::parse_duration(sd)
7871                .map_err(|e| format!("starting_deadline: invalid duration '{sd}': {e}"))?;
7872        }
7873        // #917: the plan side got almost no create-time checks, so
7874        // several never-fires / fails-every-tick shapes were accepted
7875        // and only surfaced at dispatch time — or never:
7876        //
7877        // (1) a target that dispatches nothing. A runs_on: agent
7878        // schedule matches each agent against `target` (rollout waves
7879        // are backend-published and never reach that path), so an
7880        // unspecified target silently never fires; a runs_on: backend
7881        // one warn-fails every tick at the exec boundary, which
7882        // rejects the same shape with the same message.
7883        let has_waves = self
7884            .plan
7885            .rollout
7886            .as_ref()
7887            .is_some_and(|r| !r.waves.is_empty());
7888        if matches!(self.runs_on, RunsOn::Agent) {
7889            if !self.plan.target.is_specified() {
7890                return Err(
7891                    "target must specify at least one of `all` / `groups` / `pcs` — a \
7892                     runs_on: agent schedule matches each agent against `target`, so an \
7893                     unspecified target never fires anywhere"
7894                        .into(),
7895                );
7896            }
7897            if self.plan.rollout.is_some() {
7898                return Err(
7899                    "rollout waves are published by the backend and are ignored by \
7900                     runs_on: agent schedules (each agent self-schedules from `target`); \
7901                     drop `rollout:` or use runs_on: backend"
7902                        .into(),
7903                );
7904            }
7905        } else if !has_waves && !self.plan.target.is_specified() {
7906            return Err(
7907                "target must specify at least one of `all` / `groups` / `pcs` \
7908                 (or set `rollout.waves`) — the exec boundary rejects an \
7909                 unspecified target, so the schedule would fail every tick"
7910                    .into(),
7911            );
7912        }
7913        // (2) rollout waves were never validated: a blank group or an
7914        // unparseable delay failed at EVERY fire (the CLI doesn't even
7915        // expose waves, so the failure was always deferred to dispatch)
7916        // and an empty list dispatched nothing. (3) A wave delayed to
7917        // or past starting_deadline is dead on arrival: the deadline is
7918        // stamped once at tick time and the Command is serialised
7919        // before the wave sleep, so agents receive it already expired
7920        // (a synthetic exit-125 skip on every fire).
7921        if let Some(rollout) = &self.plan.rollout {
7922            if rollout.waves.is_empty() {
7923                return Err(
7924                    "rollout.waves must list at least one wave; omit `rollout:` for a \
7925                     one-shot fan-out of `target`"
7926                        .into(),
7927                );
7928            }
7929            let deadline = self
7930                .starting_deadline
7931                .as_deref()
7932                .and_then(|sd| humantime::parse_duration(sd).ok());
7933            for (i, wave) in rollout.waves.iter().enumerate() {
7934                if wave.group.trim().is_empty() {
7935                    return Err(format!("rollout.waves[{i}].group must not be blank"));
7936                }
7937                let delay = humantime::parse_duration(&wave.delay).map_err(|e| {
7938                    format!(
7939                        "rollout.waves[{i}].delay: invalid duration '{}': {e}",
7940                        wave.delay
7941                    )
7942                })?;
7943                if let Some(deadline) = deadline
7944                    && delay >= deadline
7945                {
7946                    return Err(format!(
7947                        "rollout.waves[{i}].delay ('{}') must be shorter than \
7948                         starting_deadline ('{}'): the deadline is stamped at tick time, \
7949                         so this wave's Commands would already be expired when published \
7950                         (skipped by every agent, every fire)",
7951                        wave.delay,
7952                        self.starting_deadline.as_deref().unwrap_or_default(),
7953                    ));
7954                }
7955            }
7956        }
7957        // (4) deadline_at is machine-stamped: the scheduler overwrites
7958        // it from `tick + starting_deadline` on every fire, so an
7959        // operator-set value is silently discarded — reject it and
7960        // point at the knob that does what they meant. (Ad-hoc POST
7961        // /api/exec bodies are a different write path and may still
7962        // carry it.)
7963        if self.plan.deadline_at.is_some() {
7964            return Err(
7965                "deadline_at is computed by the scheduler (tick time + starting_deadline) \
7966                 and overwritten on every fire — set `starting_deadline` instead"
7967                    .into(),
7968            );
7969        }
7970        let from = self
7971            .active
7972            .from
7973            .as_deref()
7974            .map(|s| Active::parse_bound(s, self.tz))
7975            .transpose()?;
7976        let until = self
7977            .active
7978            .until
7979            .as_deref()
7980            .map(|s| Active::parse_bound(s, self.tz))
7981            .transpose()?;
7982        if let (Some(f), Some(u)) = (from, until) {
7983            if f >= u {
7984                return Err(format!(
7985                    "active.from ({}) must be strictly before active.until ({})",
7986                    self.active.from.as_deref().unwrap_or_default(),
7987                    self.active.until.as_deref().unwrap_or_default(),
7988                ));
7989            }
7990        }
7991        // #418 Phase 3: a bad maintenance window is rejected at create
7992        // time (parse_window also catches equal bounds).
7993        if let Some(w) = self.constraints.window.as_deref() {
7994            Constraints::parse_window(w)?;
7995        }
7996        // #418 holiday exclusion: reject a malformed skip date at create
7997        // time so the fail-closed `allows` path only ever bites a
7998        // hand-edited KV blob, not a fresh `kanade schedule create`.
7999        if let Some(err) = self.constraints.bad_skip_date() {
8000            return Err(err);
8001        }
8002        // #418: constraints.max_concurrent is a central running-instance
8003        // cap, so it needs the backend's counter — reject it on
8004        // runs_on: agent (decision E), and reject a meaningless 0.
8005        if let Some(mc) = self.constraints.max_concurrent {
8006            // Check the structural incompatibility (agent has no central
8007            // counter) before the value range, so a `max_concurrent: 0`
8008            // + `runs_on: agent` combo reports the more fundamental
8009            // problem first (claude #542).
8010            if matches!(self.runs_on, RunsOn::Agent) {
8011                return Err(
8012                    "constraints.max_concurrent needs a central counter and is backend-only; \
8013                     it cannot be combined with runs_on: agent (each agent self-schedules, \
8014                     so there is no fleet-wide count to cap against)"
8015                        .into(),
8016                );
8017            }
8018            if mc == 0 {
8019                return Err(
8020                    "constraints.max_concurrent must be >= 1 (0 would never fire; \
8021                     omit it for no cap)"
8022                        .into(),
8023                );
8024            }
8025        }
8026        // #418: constraints.require (host-state env gates: ac_power /
8027        // idle / cpu_below / network) is sensed in-process by the agent,
8028        // so it needs runs_on: agent — the backend can't read a target
8029        // host's power / idle / cpu / connectivity state. Symmetric with
8030        // `when: { on }` (also agent-only); inverse of max_concurrent
8031        // (backend-only).
8032        if let Some(req) = &self.constraints.require {
8033            if !req.is_empty() && matches!(self.runs_on, RunsOn::Backend) {
8034                return Err(
8035                    "constraints.require (host-state env gates: ac_power / idle / cpu_below / \
8036                     network) is sensed in-process by the agent and needs runs_on: agent; the \
8037                     backend cannot read a target host's power / idle / cpu / connectivity state"
8038                        .into(),
8039                );
8040            }
8041            // Reject a malformed idle duration at create time so the
8042            // fail-closed runtime path only ever bites a hand-edited
8043            // KV blob (mirror skip_dates / on_failure.retry).
8044            if let Some(err) = req.bad_idle() {
8045                return Err(err);
8046            }
8047            // cpu_below is a percent — reject out-of-range so a typo
8048            // can't make a schedule that never (>=100 is always-busy?
8049            // no — <0 never matches) or trivially fires.
8050            if let Some(c) = req.cpu_below
8051                && !(c > 0.0 && c <= 100.0)
8052            {
8053                return Err(format!(
8054                    "constraints.require.cpu_below must be in (0, 100] percent (got {c}); \
8055                     omit it for no CPU requirement"
8056                ));
8057            }
8058        }
8059        // #418 Phase 4: a bad on_failure.retry is rejected at create
8060        // time — backoff must be valid humantime, and max is bounded
8061        // so a typo can't pin a flapping script in a tight loop.
8062        if let Some(r) = &self.on_failure.retry {
8063            let backoff = humantime::parse_duration(&r.backoff).map_err(|e| {
8064                format!(
8065                    "on_failure.retry.backoff: invalid duration '{}': {e}",
8066                    r.backoff
8067                )
8068            })?;
8069            // The wire form lowers backoff to whole seconds, so a
8070            // sub-second value would silently become a 0s no-wait
8071            // (coderabbit #466). Reject it rather than honour a backoff
8072            // the operator can't actually get.
8073            if backoff.as_secs() < 1 {
8074                return Err(format!(
8075                    "on_failure.retry.backoff must be >= 1s (got '{}'); sub-second backoffs \
8076                     round to 0 on the wire",
8077                    r.backoff
8078                ));
8079            }
8080            if !(1..=10).contains(&r.max) {
8081                return Err(format!(
8082                    "on_failure.retry.max must be 1..=10 (got {}); it counts additional \
8083                     attempts after the first run",
8084                    r.max
8085                ));
8086            }
8087        }
8088        // A blank / whitespace-only tag renders an empty filter chip on
8089        // the Schedules page — reject it at create time, mirroring the
8090        // Manifest::validate tag guard.
8091        for tag in &self.tags {
8092            if tag.trim().is_empty() {
8093                return Err("tags must not contain empty entries".to_string());
8094            }
8095        }
8096        Ok(())
8097    }
8098}
8099
8100/// Shared `serde(default)` for `bool` fields that default to `true`
8101/// (e.g. `CheckHint::fleet` / `CheckHint::health`). Generic name so it
8102/// doesn't read as "fleet" when reused for `health`.
8103fn default_true() -> bool {
8104    true
8105}