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