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