Skip to main content

kanade_shared/
manifest.rs

1use serde::{Deserialize, Serialize};
2
3use crate::wire::{FinalizeCommand, RunAs, Shell, Staleness};
4
5/// YAML job manifest (= registered "what to run", v0.18.0+).
6///
7/// Owns only script-intrinsic fields. **Who** (`target`), **how to
8/// phase fanout** (`rollout`), and **when to stagger start**
9/// (`jitter`) all moved to the Schedule / exec request side — same
10/// script can now be fired against different targets / rollouts
11/// without copying the script body.
12///
13/// #492: these types are READ fleet-wide (agents decode them from
14/// BUCKET_JOBS / BUCKET_SCHEDULES and inside live Commands), so they
15/// must tolerate unknown fields — `deny_unknown_fields` here made a
16/// gradually-upgrading fleet's OLD agents reject the whole object
17/// the moment a newer backend added any field. Operator typo
18/// protection (the old reason for the attribute) lives at the WRITE
19/// boundaries instead: `kanade job/schedule create` and the backend
20/// POST extractor parse via [`crate::strict`], which rejects unknown
21/// keys with their full paths. The wire rule: new fields always get
22/// `#[serde(default)]` (+ `skip_serializing_if` while old readers
23/// may still be strict).
24#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
25pub struct Manifest {
26    pub id: String,
27    pub version: String,
28    #[serde(default)]
29    pub description: Option<String>,
30    pub execute: Execute,
31    #[serde(default)]
32    pub require_approval: bool,
33    /// Opt-in marker that this job produces a JSON inventory fact
34    /// payload on stdout. When present, the backend's results
35    /// projector parses `ExecResult.stdout` as JSON and upserts an
36    /// `inventory_facts` row keyed by `(pc_id, manifest.id)`. The
37    /// `display` sub-config drives the SPA's Inventory page render.
38    #[serde(default)]
39    pub inventory: Option<InventoryHint>,
40    /// Issue #246: opt-in marker that this job emits per-line
41    /// observability events on stdout (one JSON `ObsEvent` per
42    /// newline). When present, the agent — after the script exits
43    /// successfully — parses each non-empty stdout line as an
44    /// `ObsEvent`, publishes it on `obs.<pc_id>` via the
45    /// `obs_outbox`, and (intentionally) **omits the stdout from
46    /// the `ExecResult`** so the timeline data doesn't double up
47    /// in `execution_results.stdout` (which would multiply rows
48    /// by ~50/day/PC of noise).
49    ///
50    /// Distinct from `inventory:` (single JSON object → projector
51    /// upsert) — events are append-only timeline points consumed
52    /// by the dedicated `obs_events` table.
53    #[serde(default)]
54    pub emit: Option<EmitConfig>,
55    /// #290: opt-in marker that this job is an operator-defined
56    /// **health check** whose result feeds the Client App's Health
57    /// tab over KLP (`StateSnapshot.checks`). The script prints a
58    /// free-form JSON object on stdout (like any inventory job); the
59    /// agent reads the [`CheckHint::status_field`] value dynamically
60    /// into a [`crate::ipc::state::Check`] named `check.name`.
61    /// Cadence / windows / conditions come from
62    /// the job's Schedule (exactly like inventory) — there is
63    /// deliberately no interval here. **Composes with `inventory:` and
64    /// `collect:`** (#821): each reads its own `#KANADE-<KIND>`-fenced
65    /// stdout block, so one job can drive a check, project inventory
66    /// facts, and collect files in a single run. Only `emit:` (NDJSON
67    /// stdout) is incompatible. A check-only job may skip the fence
68    /// (whole stdout is the JSON); a multi-hint job fences each block.
69    #[serde(default)]
70    pub check: Option<CheckHint>,
71    /// #219: opt-in marker that this job COLLECTS files into a bundle.
72    /// The script does the collection work and prints a single JSON
73    /// object on stdout carrying a `files` array of paths (the field
74    /// name is [`CollectHint::files_field`], default `"files"`); the
75    /// agent — after the script exits successfully — zips those files,
76    /// uploads the archive to the `OBJECT_COLLECTIONS` Object Store
77    /// bucket (key `<pc_id>/<job_id>/<timestamp>.zip`), and records the
78    /// key in [`crate::wire::ExecResult::collect_object`]. The operator
79    /// downloads bundles from the SPA Collect page.
80    ///
81    /// Like `inventory:` / `check:` this reads a JSON object from stdout.
82    /// #821: it reads its own `#KANADE-COLLECT-BEGIN/END`-fenced block,
83    /// so it **composes with `inventory:` / `check:`** (and a user
84    /// message) on one stdout — only `emit:` (NDJSON) is incompatible
85    /// (enforced in [`Manifest::validate`]). A collect-only job may skip
86    /// the fence. It also composes with `client:` — a `collect:` +
87    /// `client:` job lets an end user trigger a collection from the
88    /// Client App (the same-host agent runs it).
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub collect: Option<CollectHint>,
91    /// #720: opt-in declarative aggregation over `obs_events` that drives
92    /// the SPA **Analytics** page. Unlike the other hints this one never
93    /// touches stdout and is never delivered to the agent — it's a pure
94    /// *read spec* the backend reads from `BUCKET_JOBS` at query time and
95    /// turns into `json_extract` aggregation SQL. Each entry is one widget
96    /// (a `dashboard:` tab groups them); `scope:` selects per-PC vs
97    /// fleet-wide rollup. Because it consumes nothing at run time it
98    /// composes with every other hint (typically paired with `emit:`,
99    /// which produces the events it reads). See [`AggregateWidget`].
100    ///
101    /// New field ⇒ #492 wire rule (`default` + `skip_serializing_if`).
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub aggregate: Option<Vec<AggregateWidget>>,
104    /// v0.26: Layer 2 staleness policy (SPEC.md §2.6.2). Controls
105    /// what the agent does at fire time when it can't verify the
106    /// `script_current` / `script_status` KV values are fresh —
107    /// especially relevant for `runs_on: agent` schedules where
108    /// the agent may fire from cache while offline. Defaults to
109    /// `Staleness::Cached` (silently use cached values), which
110    /// matches every pre-v0.26 Manifest.
111    #[serde(default)]
112    pub staleness: Staleness,
113    /// #291: opt-in marker that this job is offered to **end users**
114    /// in the Client App's job tabs over KLP (`jobs.list` →
115    /// `jobs.execute`). Parallel to [`inventory`] / [`check`] /
116    /// [`emit`]: the block's mere presence is the opt-in, and it
117    /// groups the end-user presentation fields (name / category /
118    /// icon) that only make sense for a user-facing job. `None`
119    /// (the default) ⇒ an operator-only job — inventory, checks,
120    /// scheduled maintenance — that never surfaces in the catalog.
121    ///
122    /// The agent re-reads this at every `jobs.list` / `jobs.execute`
123    /// (SPEC §2.1), so removing the block takes a job out of a
124    /// running client on its next action.
125    ///
126    /// [`inventory`]: Manifest::inventory
127    /// [`check`]: Manifest::check
128    /// [`emit`]: Manifest::emit
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub client: Option<ClientHint>,
131    /// Free-form operator taxonomy for the Jobs catalog. Purely a
132    /// SPA-side organisational aid — agents / scheduler / projector
133    /// never read it — so it carries no runtime semantics and any
134    /// string is allowed (`security`, `weekly`, `windows`, …). Jobs
135    /// cross-cut (a `check-bitlocker` is at once a health-check, a
136    /// security control, and Windows-specific), which is why this is
137    /// a multi-valued list rather than the single closed-enum
138    /// [`ClientHint::category`] (whose values are the end-user Client
139    /// App's tabs, a different concern). The operator Jobs page groups
140    /// rows by id-prefix for free; tags add the orthogonal filter axis
141    /// prefixes can't express.
142    ///
143    /// Empty by default (the overwhelming majority of jobs), and a
144    /// new field, so it follows the #492 wire rule: `serde(default)`
145    /// plus `skip_serializing_if` keep gradually-upgrading old readers
146    /// from tripping over its absence / presence.
147    #[serde(default, skip_serializing_if = "Vec::is_empty")]
148    pub tags: Vec<String>,
149    /// GitOps provenance (#678) — see [`RepoOrigin`]. Stamped by
150    /// `kanade job create` when the source YAML lives inside a Git work
151    /// tree, so the SPA can render the job read-only and point edits
152    /// back at the repo instead of letting a ClickOps edit silently
153    /// diverge from Git (SPEC design principle #3: 設定駆動 YAML + Git).
154    /// `None` for SPA-born jobs and for manifests applied from outside
155    /// any Git repo. Purely informational: agents / scheduler /
156    /// projector never read it, and it survives `script_file:` inlining
157    /// (it's orthogonal to the exactly-one-of script-source rule). New
158    /// field ⇒ #492 wire rule (`default` + `skip_serializing_if`).
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub origin: Option<RepoOrigin>,
161    /// Job-generic post-step hook. When set, the agent runs this script
162    /// AFTER the main `execute:` script exits cleanly (and, for a
163    /// `collect:` job, after the bundle finishes uploading), so the
164    /// operator can delete / move / notify based on what the step
165    /// produced. Best-effort: a finalize failure is logged but never
166    /// fails the run — the upload (if any) already succeeded.
167    ///
168    /// For `collect:` jobs the agent injects the environment variable
169    /// `KANADE_COLLECT_RESULT` — a JSON object
170    /// `{ "ok": true, "bundles": [ { "key", "uploaded", "files": [...] } ] }`
171    /// — so the hook acts on exactly the files that were bundled and
172    /// uploaded (e.g. deletes only the `uploaded` ones). Composes with
173    /// every hint. New field ⇒ #492 wire rule (`default` +
174    /// `skip_serializing_if`).
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub finalize: Option<FinalizeSpec>,
177    /// #vuln-roadmap: declarative **external-data feeds**. Each entry fetches
178    /// global reference data (a vulnerability catalog, an EOL table, a license
179    /// roster) and projects it into the shared `feeds` table keyed
180    /// `(feed_id, item_id)` — fleet-wide, with no `pc_id`, unlike the per-PC
181    /// inventory [`ExplodeSpec`]. The job's script (run on the trusted
182    /// controller tier) fetches + shapes the data and prints the array under
183    /// each spec's [`field`](FeedSpec::field) inside a
184    /// `#KANADE-FEED-BEGIN/END` fence; the projector replaces that feed's rows
185    /// wholesale. A non-empty `feed:` **implies** `tier: controller` (the
186    /// dispatch guard treats it as such), so an external fetch never lands on
187    /// an employee endpoint. Composes with the other fenced hints. New field ⇒
188    /// #492 wire rule (`default` + `skip_serializing_if`). See [`FeedSpec`].
189    #[serde(default, skip_serializing_if = "Vec::is_empty")]
190    pub feed: Vec<FeedSpec>,
191    /// Execution tier (#vuln-roadmap). `None` / `endpoint` (default) ⇒ the
192    /// job dispatches to the targeted fleet agents like any job. `controller`
193    /// ⇒ it may run ONLY on trusted infra hosts — the backend constrains
194    /// dispatch to members of the operator-configured `controller_group`
195    /// (`server_settings` KV), and refuses to run anywhere if that group is
196    /// unset (fail-safe). This keeps `feed:` (external-fetch) and future
197    /// privileged hints off employee endpoints. The `feed:` hint implies
198    /// `controller`; it can also be set explicitly. New field ⇒ #492 wire
199    /// rule (`default` + `skip_serializing_if`).
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub tier: Option<Tier>,
202}
203
204/// Execution tier for a [`Manifest`] — see [`Manifest::tier`]. `endpoint`
205/// is the default (a normal fleet job); `controller` restricts dispatch to
206/// the trusted `controller_group`. `Unknown` is the #492 forward-compat
207/// catch-all: an older reader still *decodes* a job that names a future
208/// tier (so it doesn't fail the whole document), but `Manifest::validate()`
209/// **rejects** it — for a security field we fail closed rather than fall
210/// back to unrestricted `endpoint` dispatch (a future tier is presumably
211/// *more* restrictive, and a typo'd `controller` must not silently widen).
212#[derive(
213    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
214)]
215#[serde(rename_all = "snake_case")]
216#[non_exhaustive]
217pub enum Tier {
218    /// Dispatch to the targeted fleet agents (the default).
219    #[default]
220    Endpoint,
221    /// Dispatch only to members of the configured `controller_group`.
222    Controller,
223    /// #492 forward-compat catch-all (a future tier this build can't act on).
224    #[serde(other)]
225    Unknown,
226}
227
228/// GitOps provenance for a repo-managed YAML artifact — a [`Manifest`]
229/// (#678) or a [`Schedule`] (#695). Populated by `kanade job create` /
230/// `kanade schedule create` from the Git context of the source YAML;
231/// the SPA reads it to render Git-managed entries read-only and link
232/// the operator back at the repo. Never consulted by the runtime.
233#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
234pub struct RepoOrigin {
235    /// Repo-relative path of the source YAML — the primary edit target
236    /// the SPA surfaces (e.g. `configs/jobs/foo.yaml`). Forward slashes
237    /// regardless of the authoring OS.
238    pub path: String,
239    /// `origin` remote URL, when the repo has one. Lets the SPA turn
240    /// `path` into a clickable link; `None` for remote-less repos.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub repo: Option<String>,
243    /// Repo-relative path of the `script_file:` a job manifest inlined,
244    /// when it used one — a secondary pointer shown beneath `path`.
245    /// Always `None` for schedules (they carry no script).
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    pub script_file: Option<String>,
248}
249
250/// "Who + how + when-to-stagger" — the fanout-plan side of an exec.
251/// Used both as the POST `/api/exec/{job_id}` body and as the embedded
252/// `target` / `rollout` / `jitter` slot on [`Schedule`]. Centralising
253/// here keeps the validation + serialisation logic in one place.
254#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default)]
255pub struct FanoutPlan {
256    #[serde(default)]
257    pub target: Target,
258    /// Optional wave rollout — when present, the backend publishes
259    /// each wave's group subject on its own delay schedule instead
260    /// of fanning out the `target` block in one go. `target` then
261    /// only labels the deploy for the audit log.
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub rollout: Option<Rollout>,
264    /// Optional humantime jitter; agent uses it to randomise
265    /// execution start. Lives here (not on the script) so different
266    /// schedules / ad-hoc fires of the same job can pick different
267    /// stagger windows.
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub jitter: Option<String>,
270    /// Absolute time the scheduler stamps on each emitted Command
271    /// when this exec was driven by a [`Schedule`] with
272    /// `starting_deadline`. Agents receiving a Command after this
273    /// instant publish a synthetic skipped-result instead of
274    /// running the script. `None` (default) = no deadline / catch
275    /// up whenever delivered. Computed by the scheduler from
276    /// `tick_at + starting_deadline` and overwritten on every fire —
277    /// on a Schedule, setting it by hand is rejected at create time
278    /// (#917, use `starting_deadline`); it remains settable on an
279    /// ad-hoc POST /api/exec body.
280    #[serde(default, skip_serializing_if = "Option::is_none")]
281    pub deadline_at: Option<chrono::DateTime<chrono::Utc>>,
282}
283
284/// Sentinel lines that fence a hint's structured JSON payload inside an
285/// otherwise human-readable job stdout. Each stdout-reading hint
286/// (`inventory:` / `check:` / `collect:`) has its OWN `#KANADE-<KIND>-
287/// BEGIN`/`-END` pair, so one job can carry several of them at once
288/// (and/or a user-facing message) on its single stdout stream — every
289/// consumer extracts only its own block via [`fenced_payload`].
290///
291/// Originated for inventory (#793): a `client:` job couldn't put both a
292/// friendly message and a JSON object on one stdout (the Client App
293/// renders stdout verbatim, the projector needs JSON). #821 generalised
294/// it so inventory / check / collect can coexist. `emit:` is the
295/// exception — its stdout is line-delimited NDJSON consumed whole, so it
296/// never fences and never coexists with the others.
297///
298/// A job carrying a SINGLE hint may still skip the fence —
299/// [`fenced_payload`] falls back to the whole stdout — but a job
300/// COMBINING hints must fence each block (else every consumer would try
301/// to parse the same whole stdout).
302pub const INVENTORY_BLOCK_BEGIN: &str = "#KANADE-INVENTORY-BEGIN";
303/// Closing marker — see [`INVENTORY_BLOCK_BEGIN`].
304pub const INVENTORY_BLOCK_END: &str = "#KANADE-INVENTORY-END";
305/// Check-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
306pub const CHECK_BLOCK_BEGIN: &str = "#KANADE-CHECK-BEGIN";
307/// Check-payload closing marker.
308pub const CHECK_BLOCK_END: &str = "#KANADE-CHECK-END";
309/// Collect-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
310pub const COLLECT_BLOCK_BEGIN: &str = "#KANADE-COLLECT-BEGIN";
311/// Collect-payload closing marker.
312pub const COLLECT_BLOCK_END: &str = "#KANADE-COLLECT-END";
313/// Feed-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
314pub const FEED_BLOCK_BEGIN: &str = "#KANADE-FEED-BEGIN";
315/// Feed-payload closing marker.
316pub const FEED_BLOCK_END: &str = "#KANADE-FEED-END";
317
318/// Extract a hint's fenced block when the `begin` marker is present, else
319/// `None`. An unterminated fence (closing marker missing, e.g. truncated
320/// output) takes everything after the opener. Trimmed so surrounding
321/// message text / whitespace never reaches the JSON parser.
322pub fn fenced_payload_if_present<'a>(stdout: &'a str, begin: &str, end: &str) -> Option<&'a str> {
323    let b = find_line_marker(stdout, begin)?;
324    let after = &stdout[b + begin.len()..];
325    let inner = match find_line_marker(after, end) {
326        Some(e) => &after[..e],
327        None => after,
328    };
329    Some(inner.trim())
330}
331
332/// True if stdout carries ANY `#KANADE-<KIND>-BEGIN` fence at a line
333/// start — i.e. the script opted into fenced output. Used to decide
334/// whether a missing fence means "single-hint, use the whole stdout" or
335/// "multi-hint author error / truncation, this hint just has no block".
336pub fn has_any_hint_fence(stdout: &str) -> bool {
337    [
338        INVENTORY_BLOCK_BEGIN,
339        CHECK_BLOCK_BEGIN,
340        COLLECT_BLOCK_BEGIN,
341        FEED_BLOCK_BEGIN,
342    ]
343    .iter()
344    .any(|m| find_line_marker(stdout, m).is_some())
345}
346
347/// Extract one hint's JSON payload from a job's stdout. When the hint's
348/// own `#KANADE-<KIND>` fence is present, return that block. When it's
349/// absent, fall back to the WHOLE stdout only for an unfenced (single-
350/// hint) job; if any OTHER hint's fence is present (#821 multi-hint
351/// output) return `""` instead — the script opted into fences but this
352/// block is missing (author error or truncation), so this consumer must
353/// NOT grab a sibling hint's block. An empty payload fails the consumer's
354/// JSON parse and degrades to "no data for this hint", never cross-parse.
355pub fn fenced_payload<'a>(stdout: &'a str, begin: &str, end: &str) -> &'a str {
356    if let Some(p) = fenced_payload_if_present(stdout, begin, end) {
357        return p;
358    }
359    if has_any_hint_fence(stdout) {
360        ""
361    } else {
362        stdout.trim()
363    }
364}
365
366/// Inventory's fenced payload — [`fenced_payload`] with the inventory
367/// markers. Kept as a named helper for the projector call site.
368pub fn inventory_payload(stdout: &str) -> &str {
369    fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END)
370}
371
372/// Feed's fenced payload — [`fenced_payload`] with the feed markers. Kept as
373/// a named helper for the projector call site.
374pub fn feed_payload(stdout: &str) -> &str {
375    fenced_payload(stdout, FEED_BLOCK_BEGIN, FEED_BLOCK_END)
376}
377
378/// Find `needle` only where it begins a line (start of `hay` or right
379/// after a `\n`). Anchoring to line start means a script echoing the
380/// literal sentinel mid-message (e.g. printing a command name) can't
381/// false-trigger the fence (Claude #793).
382fn find_line_marker(hay: &str, needle: &str) -> Option<usize> {
383    if hay.starts_with(needle) {
384        return Some(0);
385    }
386    hay.find(&format!("\n{needle}")).map(|p| p + 1)
387}
388
389/// Manifest sub-section: how the SPA should render the inventory
390/// facts this job produces. Each field name (`field`) is a top-level
391/// key in the stdout JSON, e.g. `hostname`, `ram_gb`.
392///
393/// Two render modes:
394///   * `display` — vertical "field / value" per PC, used by the
395///     `/inventory?pc=<id>` detail view. ALL columns the operator
396///     wants visible on the detail page.
397///   * `summary` — horizontal table across the fleet (row = PC,
398///     column = field) on `/inventory`. Optional; when omitted the
399///     SPA falls back to `display`, but operators usually want a
400///     trimmer "hostname / OS / CPU / RAM" set for the fleet view.
401#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
402pub struct InventoryHint {
403    /// Detail-view columns, in order.
404    pub display: Vec<DisplayField>,
405    /// Optional fleet-list columns (row = PC). Defaults to `display`
406    /// when omitted, but operators usually pick a 3-5 column subset.
407    #[serde(default, skip_serializing_if = "Option::is_none")]
408    pub summary: Option<Vec<DisplayField>>,
409    /// v0.31 / #40: payload arrays that should be exploded into
410    /// per-element rows of a derived SQLite table. Lets operators
411    /// answer cross-PC questions ("which PCs still have Chrome <
412    /// 120?", "C: >90% full") with normal SQL filters + indexes
413    /// instead of grepping JSON. The projector creates the derived
414    /// table on register and replaces this PC's rows on each result
415    /// (DELETE WHERE pc_id=? AND job_id=? + bulk INSERT). See
416    /// [`ExplodeSpec`] for the per-spec schema.
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub explode: Option<Vec<ExplodeSpec>>,
419    /// v0.35 / #93: top-level scalar fields whose changes the
420    /// projector logs to `inventory_history` (one event per
421    /// changed field per scan). Pairs with `explode[].track_history`
422    /// — that covers array elements; this covers single-valued
423    /// fields like `ram_bytes` / `os_version` / `cpu_model` /
424    /// `os_build` that operators want to track for "did the RAM
425    /// get upgraded?" / "when did Win 11 land on this PC?" /
426    /// "BIOS / firmware bumped?" questions. Field name = `field_path`
427    /// in the history row, `identity_json` is NULL, `before_json`
428    /// / `after_json` each carry `{"value": <prior or new value>}`.
429    /// First-ever observation of a scalar (no prior facts row)
430    /// emits `added`; subsequent value changes emit `changed`. No
431    /// `removed` events — a scalar disappearing from the payload
432    /// is rare and the operator can still see the last value via
433    /// the `before_json` of the most recent change.
434    #[serde(default, skip_serializing_if = "Option::is_none")]
435    pub history_scalars: Option<Vec<String>>,
436}
437
438/// Manifest sub-section (#290): marks a job as an operator-defined
439/// **health check**. Parallel to [`InventoryHint`] / `EmitConfig`.
440/// The stdout contract is a free-form JSON object (same as any
441/// inventory job) from which the agent reads `status_field` /
442/// `detail_field` to build the KLP [`crate::ipc::state::Check`] shown
443/// on the Client App's Health tab.
444///
445/// There is deliberately **no timing field** — when / how often /
446/// in which window a check runs is driven by the job's Schedule,
447/// exactly like inventory jobs, so operators get the full `when:` /
448/// rollout / `runs_on` expressiveness for free.
449///
450/// A check's stdout is a **free-form inventory object** (arbitrary
451/// key/value pairs + arrays) — same as any inventory job — that also
452/// carries a status field. `check:` adds only the health semantics on
453/// top: which field is the ok/warn/fail/unknown status, an optional
454/// one-line summary field, and a remediation job. Everything else
455/// (rich per-PC detail, `explode` sub-tables like a software list) is
456/// driven by a co-present [`InventoryHint`] and rendered with the
457/// SAME display logic the SPA Inventory page uses — on the Client App
458/// too. This keeps checks maximally expressive without a bespoke
459/// payload type.
460#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
461pub struct CheckHint {
462    /// Stable check id → [`Check.name`](crate::ipc::state::Check),
463    /// the SPA/Client React key + analytics label. Unique within the
464    /// fleet's check set. Machine-friendly slug (`disk_space`,
465    /// `defender_rtp`); for the human-facing row title see [`label`].
466    ///
467    /// [`label`]: CheckHint::label
468    pub name: String,
469    /// Optional human-facing display title →
470    /// [`Check.label`](crate::ipc::state::Check). The Client App's
471    /// Health tab and the operator SPA's Compliance page render this
472    /// instead of the [`name`](CheckHint::name) slug when set
473    /// (`"ウイルス対策のリアルタイム保護"` reads better than
474    /// `defender_rtp`). Falls back to the slug when absent, so it's
475    /// purely additive. Author it in the check's language — there's no
476    /// per-locale variant; checks are operator-defined per fleet.
477    #[serde(default, skip_serializing_if = "Option::is_none")]
478    pub label: Option<String>,
479    /// Top-level stdout field whose string value
480    /// (`ok`/`warn`/`fail`/`unknown`) becomes the Health-tab light
481    /// ([`CheckStatus`](crate::ipc::state::CheckStatus)). Defaults to
482    /// `"status"`; a missing / unparseable value → `unknown`.
483    #[serde(default = "default_status_field")]
484    pub status_field: String,
485    /// Top-level stdout field used as the Health-tab row's one-line
486    /// summary. Defaults to `"detail"`; absent in the payload → no
487    /// detail line (the rich breakdown lives in the inventory view).
488    #[serde(default = "default_detail_field")]
489    pub detail_field: String,
490    /// Optional remediation job id →
491    /// [`Check.troubleshoot`](crate::ipc::state::Check). The Client
492    /// App shows a "修復する" button when present; that job must be
493    /// `user_invokable`.
494    #[serde(default, skip_serializing_if = "Option::is_none")]
495    pub troubleshoot: Option<String>,
496    /// #290 PR-E: when `true` (default), the backend also projects this
497    /// check's `status` / `detail` into the `check_status` table so the
498    /// operator SPA gets a fleet-wide compliance view for free — no
499    /// `inventory:` block needed. Set `fleet: false` for a client-only
500    /// check the operator doesn't want surfaced across the fleet.
501    #[serde(default = "default_true")]
502    pub fleet: bool,
503    /// When `true` (default), this check is shown on the Client App's
504    /// Health tab (the end user sees its ok/warn/fail row). Set
505    /// `health: false` for a **gate-only** check — one that exists purely
506    /// to drive a `client.show_when` display gate (e.g. `myapp-up-to-date`)
507    /// and would just be noise as a Health row. The agent still records it
508    /// into `StateSnapshot.checks` (so `show_when` can read it and the gate
509    /// keeps working); only the Client App's Health *rendering* skips it,
510    /// via the [`Check.health_hidden`](crate::ipc::state::Check::health_hidden)
511    /// wire flag. Orthogonal to [`fleet`](CheckHint::fleet): `fleet` gates
512    /// the operator SPA fleet view, `health` gates the end-user Health tab,
513    /// so a pure gate detector typically sets neither (`fleet: false` +
514    /// `health: false`) to stay invisible everywhere while still driving
515    /// the gate.
516    #[serde(default = "default_true")]
517    pub health: bool,
518    /// Optional auto-notification on a compliance transition. When set, the
519    /// backend publishes an end-user notification the moment this check
520    /// transitions *into* one of [`CheckAlert::on`] (e.g. ok → fail) — to
521    /// the failing PC's user and/or operator groups. Fired once per
522    /// transition (not on every poll). Requires `fleet: true` (the alert
523    /// rides the same projection that fills `check_status`).
524    #[serde(default, skip_serializing_if = "Option::is_none")]
525    pub alert: Option<CheckAlert>,
526}
527
528/// Auto-notification rule for a [`CheckHint`] (compliance alerting). When a
529/// check's status transitions into one of [`on`](Self::on), the backend
530/// publishes a notification to the failing PC's user
531/// ([`notify_user`](Self::notify_user)) and/or operator groups
532/// ([`notify_groups`](Self::notify_groups)). Deliberately config-driven:
533/// who gets told, how loud, and the wording all live in the manifest, not
534/// hardcoded in the backend.
535#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
536pub struct CheckAlert {
537    /// Statuses that fire the alert on *transition into* them (a check that
538    /// stays failing doesn't re-alert every poll). Defaults to `[fail]`.
539    /// `ok` is not representable — [`CheckAlertStatus`] has no `Ok` variant,
540    /// so a YAML `on: [ok]` fails to deserialize (before `validate()` is
541    /// even reached); "recovered" notifications are out of scope.
542    #[serde(default = "default_alert_on")]
543    pub on: Vec<CheckAlertStatus>,
544    /// Notify the user(s) on the failing PC (`notifications.pc.<pc_id>`).
545    #[serde(default)]
546    pub notify_user: bool,
547    /// Notify these operator groups (`notifications.group.<name>`).
548    #[serde(default, skip_serializing_if = "Vec::is_empty")]
549    pub notify_groups: Vec<String>,
550    /// Notification priority (colour/label only — toasting is the separate
551    /// `toast` flag). Defaults to `warn`.
552    #[serde(default = "default_alert_priority")]
553    pub priority: crate::ipc::notifications::NotificationPriority,
554    /// Require the recipient to click 確認 to dismiss.
555    #[serde(default)]
556    pub require_ack: bool,
557    /// Surface an OS toast (launches a closed Client App, Action Center
558    /// while locked). Recommended `true` for `notify_user` so a
559    /// non-emergency "your PC is non-compliant" nudge still reaches a user
560    /// whose app is closed.
561    #[serde(default)]
562    pub toast: bool,
563    /// Also send the alert by email, to every address mapped to the
564    /// `notify_groups` (via the `group_contacts` KV, edited on the SPA
565    /// Groups page). Opt-in: defaults to `false`, so an existing alert
566    /// never starts emailing on its own. Requires `notify_groups` to be
567    /// non-empty (there is no per-PC user email) and the backend's
568    /// `[mail]` config to be present; otherwise the email is a logged
569    /// no-op while the in-app/toast notification still fires.
570    #[serde(default)]
571    pub email: bool,
572    /// Notification title (required). May use the same `{…}` placeholders
573    /// as [`body`](Self::body).
574    pub title: String,
575    /// Notification body template. Placeholders: `{pc_id}`, `{name}` (check
576    /// slug), `{label}` (check label, falls back to slug), `{status}`,
577    /// `{detail}` (the check's one-line summary), `{last_logon}` (the PC's
578    /// last sign-in account). Absent → empty body.
579    #[serde(default, skip_serializing_if = "Option::is_none")]
580    pub body: Option<String>,
581}
582
583/// A check status that can trigger a [`CheckAlert`]. Mirrors the
584/// projected `check_status.status` values minus `ok` (alerting on `ok` is
585/// rejected at validation).
586#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash)]
587#[serde(rename_all = "snake_case")]
588pub enum CheckAlertStatus {
589    Warn,
590    Fail,
591    Unknown,
592}
593
594impl CheckAlertStatus {
595    /// The wire string, matching the projected `check_status.status`.
596    pub fn as_str(self) -> &'static str {
597        match self {
598            Self::Warn => "warn",
599            Self::Fail => "fail",
600            Self::Unknown => "unknown",
601        }
602    }
603}
604
605fn default_alert_on() -> Vec<CheckAlertStatus> {
606    vec![CheckAlertStatus::Fail]
607}
608
609fn default_alert_priority() -> crate::ipc::notifications::NotificationPriority {
610    crate::ipc::notifications::NotificationPriority::Warn
611}
612
613fn default_status_field() -> String {
614    "status".to_string()
615}
616
617fn default_detail_field() -> String {
618    "detail".to_string()
619}
620
621fn default_files_field() -> String {
622    "files".to_string()
623}
624
625/// Fallback cap on a collect bundle's total input size when the
626/// manifest's `collect.max_size` is unset. 50 MB (decimal).
627pub const DEFAULT_COLLECT_MAX_SIZE: u64 = 50 * 1_000_000;
628
629/// Manifest sub-section (#219): marks a job as a **file collector** and
630/// carries how the collected bundle presents in the SPA. Parallel to
631/// [`InventoryHint`] / [`CheckHint`] — the block's presence is the
632/// opt-in. The script prints a single JSON object on stdout whose
633/// [`files_field`](CollectHint::files_field) key holds an array of file
634/// paths to bundle (env vars are expanded); the agent zips them and
635/// uploads to `OBJECT_COLLECTIONS`. See [`Manifest::collect`].
636#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
637pub struct CollectHint {
638    /// Operator/end-user-facing title for the collection, shown as the
639    /// bundle's heading on the SPA Collect page (and the Client App row
640    /// when paired with `client:`). Required; validated non-empty.
641    pub name: String,
642    /// Optional one-line description of what the bundle contains.
643    #[serde(default, skip_serializing_if = "Option::is_none")]
644    pub description: Option<String>,
645    /// Human-readable cap on the bundle's total input size
646    /// (`"50MB"`, `"500KB"`, `"1GiB"`). The agent refuses to build a
647    /// bundle whose listed files exceed this. `None` ⇒
648    /// [`DEFAULT_COLLECT_MAX_SIZE`]. Parsed by [`parse_size_bytes`];
649    /// [`Manifest::validate`] rejects an unparseable value at create
650    /// time.
651    ///
652    /// Note: this bounds the **uncompressed** bytes the agent reads off
653    /// disk, not the resulting zip. Text logs compress well, so the
654    /// download is usually much smaller; many tiny files add a little
655    /// per-entry zip overhead. Read it as "how much the agent reads +
656    /// packs", not "the exact download size".
657    #[serde(default, skip_serializing_if = "Option::is_none")]
658    pub max_size: Option<String>,
659    /// Top-level stdout JSON key holding the array of file paths to
660    /// bundle. Defaults to `"files"`.
661    #[serde(default = "default_files_field")]
662    pub files_field: String,
663}
664
665impl CollectHint {
666    /// The effective size cap in bytes — the parsed `max_size` or
667    /// [`DEFAULT_COLLECT_MAX_SIZE`] when unset. Assumes `max_size` (if
668    /// present) already passed [`Manifest::validate`]; falls back to the
669    /// default on a parse error rather than panicking on the fire path.
670    pub fn max_size_bytes(&self) -> u64 {
671        match &self.max_size {
672            Some(s) => parse_size_bytes(s).unwrap_or(DEFAULT_COLLECT_MAX_SIZE),
673            None => DEFAULT_COLLECT_MAX_SIZE,
674        }
675    }
676}
677
678/// Parse a human-readable byte size (`"50MB"`, `"500 KB"`, `"1GiB"`,
679/// `"1024"`). Decimal units (KB/MB/GB) are 1000-based; binary units
680/// (KiB/MiB/GiB) are 1024-based; a bare number (or `B`) is bytes.
681/// Case-insensitive. Shared by `collect.max_size` validation and the
682/// agent's bundle-size enforcement.
683pub fn parse_size_bytes(s: &str) -> Result<u64, String> {
684    let t = s.trim();
685    if t.is_empty() {
686        return Err("size must not be empty".to_string());
687    }
688    let split = t.find(|c: char| !c.is_ascii_digit()).unwrap_or(t.len());
689    let (num_str, unit_raw) = t.split_at(split);
690    if num_str.is_empty() {
691        return Err(format!("size '{s}': missing leading number"));
692    }
693    let num: u64 = num_str
694        .parse()
695        .map_err(|_| format!("size '{s}': bad number '{num_str}'"))?;
696    let mult: u64 = match unit_raw.trim().to_ascii_lowercase().as_str() {
697        "" | "b" => 1,
698        "kb" => 1_000,
699        "mb" => 1_000_000,
700        "gb" => 1_000_000_000,
701        "kib" => 1024,
702        "mib" => 1024 * 1024,
703        "gib" => 1024 * 1024 * 1024,
704        other => {
705            return Err(format!(
706                "size '{s}': unknown unit '{other}' (use B/KB/MB/GB/KiB/MiB/GiB)"
707            ));
708        }
709    };
710    num.checked_mul(mult)
711        .ok_or_else(|| format!("size '{s}': overflow"))
712}
713
714/// Manifest sub-section (#291): marks a job as **user-invokable**
715/// from the Client App and carries how it presents to the end user.
716/// Parallel to [`InventoryHint`] / [`CheckHint`] / `EmitConfig` —
717/// the block's presence is the opt-in (no separate boolean), and its
718/// required fields (`name`, `category`) are enforced by serde at
719/// parse time, so a half-filled catalog entry fails
720/// `kanade job create` instead of rendering a nameless / tab-less row.
721///
722/// The agent maps this 1:1 into the KLP
723/// [`UserInvokableJob`](crate::ipc::jobs::UserInvokableJob) wire shape
724/// that `jobs.list` returns; the Client App renders one row per job in
725/// the tab named by `category`.
726#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
727pub struct ClientHint {
728    /// End-user-facing title for the job row. The operator-internal
729    /// `Manifest::id` slug is rarely what an end user should read, so
730    /// this is required (and validated non-empty by
731    /// [`Manifest::validate`]). Maps to `UserInvokableJob::display_name`.
732    pub name: String,
733    /// Optional one-line subtitle under `name` in the Client App.
734    /// Distinct from the operator-facing top-level
735    /// [`Manifest::description`] — this one is written for the end
736    /// user. Maps to `UserInvokableJob::display_description`.
737    #[serde(default, skip_serializing_if = "Option::is_none")]
738    pub description: Option<String>,
739    /// Which Client App tab the job lives in — a **free-form category
740    /// key** (#792). The Client App renders one tab per distinct key.
741    /// Well-known keys (`software_update`, `troubleshoot`, `catalog`)
742    /// carry built-in tab labels/icons; any other key defines a new tab
743    /// (style it with `category_label` / `category_icon`). Required and
744    /// validated non-empty — without it the agent can't place the job.
745    /// Note: the `software_update` key also drives the agent's
746    /// maintenance / auto-reboot grouping.
747    pub category: String,
748    /// Optional display name for the category's TAB. Set it on (at least
749    /// one of) a custom category's jobs to name the tab; `None` ⇒ a
750    /// built-in default for a well-known key, else the key itself.
751    #[serde(default, skip_serializing_if = "Option::is_none")]
752    pub category_label: Option<String>,
753    /// Optional icon for the category's TAB (lucide name or `data:` URL).
754    /// `None` ⇒ Client App default for the key.
755    #[serde(default, skip_serializing_if = "Option::is_none")]
756    pub category_icon: Option<String>,
757    /// Optional sort order for the TAB; lower sorts first. `None` ⇒
758    /// default (well-known keys keep their familiar order; custom keys
759    /// sort after, then by label).
760    #[serde(default, skip_serializing_if = "Option::is_none")]
761    pub category_order: Option<i64>,
762    /// Optional icon hint for the job ROW — a lucide-react icon name
763    /// or a `data:` URL. `None` ⇒ the Client App falls back to the
764    /// category's icon. Surfaced verbatim in `jobs.list[].icon`.
765    #[serde(default, skip_serializing_if = "Option::is_none")]
766    pub icon: Option<String>,
767    /// Optional visibility scope for the end-user Client App (#816).
768    ///
769    /// `None` ⇒ visible to every PC (current behavior). When set, only
770    /// agents whose `pc_id` / group membership match the [`Target`] list
771    /// the job in `jobs.list` and may run it via KLP `jobs.execute`.
772    ///
773    /// This gates the END-USER surface ONLY. Operators are unaffected:
774    /// `POST /api/exec/{job_id}` (SPA / `kanade exec`) is a separate path
775    /// that never consults `client:`, so an operator can still run the
776    /// job on any PC regardless of `visible_to`. Reuses the schedule
777    /// `Target` shape (`all` / `groups` / `pcs`); a present-but-empty
778    /// target is rejected by [`Manifest::validate`].
779    #[serde(default, skip_serializing_if = "Option::is_none")]
780    pub visible_to: Option<Target>,
781    /// Optional **dynamic display gate** keyed on a health check's result.
782    ///
783    /// `None` ⇒ always listed (current behavior). When set, the agent
784    /// lists the job in `jobs.list` ONLY while the named [`check:`] slug's
785    /// latest result is one of [`ShowWhen::is`]. The canonical use is an
786    /// update action that hides itself once the machine is already current:
787    /// pair the update job with a `check:` that reports `ok` when up to
788    /// date and gate on `is: [fail]`.
789    ///
790    /// Evaluated agent-side at `jobs.list` time against the live
791    /// `StateSnapshot.checks`, which is **keyed by check name** — so the
792    /// detector `check:` and this job may live in *different* manifests and
793    /// still share one slug. Distinct from [`visible_to`](ClientHint::visible_to):
794    /// that gates BOTH listing and `jobs.execute` (an authorization
795    /// boundary); `show_when` gates listing ONLY (a UX hint), so it can't
796    /// cause a list/execute race. New field ⇒ #492 wire rule.
797    ///
798    /// [`check:`]: crate::manifest::CheckHint
799    #[serde(default, skip_serializing_if = "Option::is_none")]
800    pub show_when: Option<ShowWhen>,
801    /// Optional **confirmation-dialog** config for the Client App's 実行
802    /// button.
803    ///
804    /// `None` ⇒ the historical default: the client shows a modal
805    /// confirmation with a built-in 「「{name}」を実行しますか?」 message
806    /// before firing the job (a mis-click guard for a possibly heavy /
807    /// destructive action). When set, the operator controls it:
808    /// - a bare bool — `confirm: false` runs immediately with **no** prompt;
809    ///   `confirm: true` is the same as omitting the block (default message);
810    /// - a struct — `confirm: { message: "…" }` shows the dialog with a
811    ///   custom message (and, redundantly with the scalar, `enabled: false`
812    ///   to suppress it).
813    ///
814    /// Gates the END-USER Client App surface only — the operator `POST
815    /// /api/exec` path never consults `client:`, so an operator-driven run
816    /// is unaffected. New field ⇒ #492 wire rule (`serde(default)` +
817    /// `skip_serializing_if`). Deserializes from bool-or-struct via
818    /// [`de_confirm`]; the JSON schema advertises the struct form (the
819    /// scalar is author ergonomics, like [`ShowWhen::is`]).
820    #[serde(
821        default,
822        deserialize_with = "de_confirm",
823        skip_serializing_if = "Option::is_none"
824    )]
825    pub confirm: Option<ConfirmHint>,
826    /// Optional **unlock scope** — the "裏コマンド" display gate. `None` (the
827    /// overwhelming default) ⇒ the job behaves as it always has. `Some(scope)`
828    /// ⇒ the job is **hidden from `jobs.list`** unless the calling OS user
829    /// currently holds an unlock grant for that scope, obtained by typing the
830    /// operator's secret code into the Client App (`support.unlock`).
831    ///
832    /// The intended use is helpdesk-only actions: a job that has no business
833    /// sitting in an end user's everyday catalog, but which the IT desk can
834    /// surface in seconds while walking that user through a problem — without
835    /// an operator-side exec, which needs SPA access and a correctly-cased
836    /// `pc_id`.
837    ///
838    /// The scope is a free-form slug (`support`, `admin`, …) matched against
839    /// the scopes configured in `ServerSettings::support_codes`, so one
840    /// deployment can run a first-line code and a stronger administrator code
841    /// side by side, each revealing a different set of jobs. A scope with no
842    /// configured code opens for nobody — a typo hides the job rather than
843    /// exposing it.
844    ///
845    /// **Listing only, like [`show_when`](ClientHint::show_when) and unlike
846    /// [`visible_to`](ClientHint::visible_to).** The agent does NOT re-check
847    /// it in `jobs.execute`, which has two consequences worth being explicit
848    /// about:
849    ///
850    /// - Anything the user can see, they can run — no race where the row is
851    ///   visible, the grant lapses, and pressing 実行 fails on a button they
852    ///   were just looking at.
853    /// - It is therefore **not a security boundary**: a standard user who
854    ///   speaks KLP to the agent's pipe directly and knows the job id can
855    ///   still run it. Approval controls for privileged work live on the
856    ///   operator (SPA) exec path; this hides a button, it does not guard a
857    ///   capability.
858    ///
859    /// The operator paths are unaffected in both directions: `POST
860    /// /api/exec/{job_id}` and `kanade exec` never consult `client:`, so an
861    /// operator can run the job on any PC whether or not anyone unlocked it.
862    /// New field ⇒ #492 wire rule (`serde(default)` + `skip_serializing_if`).
863    #[serde(default, skip_serializing_if = "Option::is_none")]
864    pub unlock: Option<String>,
865}
866
867/// Confirmation-dialog config for a [`ClientHint`] — see
868/// [`ClientHint::confirm`]. Controls the Client App's pre-run modal:
869/// whether it appears at all (`enabled`) and what it says (`message`).
870///
871/// Authored as either a bare bool (`confirm: false` / `true`) or a struct
872/// (`confirm: { message: "…" }`); both normalise here via [`de_confirm`].
873#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
874pub struct ConfirmHint {
875    /// Whether the Client App shows the confirmation dialog before running.
876    /// `false` fires the job immediately with no prompt. Defaults to `true`
877    /// (so an author who only sets `message` still gets the dialog, and the
878    /// struct form never accidentally suppresses it).
879    #[serde(default = "default_confirm_enabled")]
880    pub enabled: bool,
881    /// Custom dialog message. `None` ⇒ the client's built-in
882    /// 「「{name}」を実行しますか?」. Only meaningful while `enabled`;
883    /// rejected if present-but-blank by [`Manifest::validate`].
884    #[serde(default, skip_serializing_if = "Option::is_none")]
885    pub message: Option<String>,
886}
887
888/// `enabled` defaults to `true`: the historical behaviour is "always
889/// confirm", so a struct form that omits `enabled` (e.g. sets only
890/// `message`) still shows the dialog.
891fn default_confirm_enabled() -> bool {
892    true
893}
894
895/// Accept either a bare bool (`confirm: false` / `confirm: true`) or a
896/// struct (`confirm: { message: "…" }`) for [`ClientHint::confirm`],
897/// normalising to a [`ConfirmHint`]. The bool is pure author ergonomics —
898/// `false` ⇒ suppress the dialog, `true` ⇒ default message — while the
899/// struct carries a custom message. Called only when the key is present
900/// (absence is handled by `serde(default)` ⇒ `None`). An explicit
901/// `confirm: null` — which the generated schema permits (the field is
902/// `Option`) — maps to `None` too, so it can't produce a parse error;
903/// deserializing through `Option<BoolOrHint>` handles that cleanly (Gemini
904/// #960).
905fn de_confirm<'de, D>(d: D) -> Result<Option<ConfirmHint>, D::Error>
906where
907    D: serde::Deserializer<'de>,
908{
909    #[derive(Deserialize)]
910    #[serde(untagged)]
911    enum BoolOrHint {
912        Bool(bool),
913        Hint(ConfirmHint),
914    }
915    Ok(Option::<BoolOrHint>::deserialize(d)?.map(|b| match b {
916        BoolOrHint::Bool(enabled) => ConfirmHint {
917            enabled,
918            message: None,
919        },
920        BoolOrHint::Hint(h) => h,
921    }))
922}
923
924/// Dynamic display gate for a [`ClientHint`] — see
925/// [`ClientHint::show_when`]. Shows the job only while the named check's
926/// latest status is one of [`is`](ShowWhen::is).
927#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
928pub struct ShowWhen {
929    /// The `check:` slug (a [`CheckHint::name`](crate::manifest::CheckHint::name))
930    /// whose latest status gates this job. May be defined by a *different*
931    /// manifest: checks are keyed by name in the agent's snapshot, so a
932    /// standalone detector job and this one can share a slug. A check that
933    /// has never run (absent from the snapshot) does NOT match — the job
934    /// stays hidden until the detector first reports (fails closed, like
935    /// `visible_to`).
936    pub check: String,
937    /// The check status(es) in which the job is SHOWN. Accepts a single
938    /// status (`is: fail`) or a list (`is: [fail, unknown]`); both
939    /// deserialize to a `Vec`. The `length(min = 1)` schema constraint +
940    /// [`Manifest::validate`] both reject an empty set (it would match
941    /// nothing and silently hide the job) so schema-driven tooling and the
942    /// write path agree.
943    #[serde(deserialize_with = "de_one_or_many_check_status")]
944    #[schemars(length(min = 1))]
945    pub is: Vec<crate::ipc::state::CheckStatus>,
946}
947
948/// Accept either a single `CheckStatus` (`is: fail`) or a sequence
949/// (`is: [fail, unknown]`) for [`ShowWhen::is`], normalising to a `Vec`.
950/// The scalar form is purely author ergonomics; the JSON schema advertises
951/// the canonical array form (`#[schemars(with = ...)]`).
952fn de_one_or_many_check_status<'de, D>(
953    d: D,
954) -> Result<Vec<crate::ipc::state::CheckStatus>, D::Error>
955where
956    D: serde::Deserializer<'de>,
957{
958    use crate::ipc::state::CheckStatus;
959    #[derive(Deserialize)]
960    #[serde(untagged)]
961    enum OneOrMany {
962        One(CheckStatus),
963        Many(Vec<CheckStatus>),
964    }
965    Ok(match OneOrMany::deserialize(d)? {
966        OneOrMany::One(c) => vec![c],
967        OneOrMany::Many(v) => v,
968    })
969}
970
971/// #720 — one widget on the SPA **Analytics** page: a declarative
972/// aggregation over the `obs_events` table. The backend reads these off
973/// `Manifest::aggregate` (from `BUCKET_JOBS`) at query time and builds
974/// the `json_extract` GROUP BY / time-bucket SQL from these generic
975/// primitives, so an operator can chart any emitted event without a Rust
976/// change. The reference shapes are the attendance dashboards
977/// (presence / app_sample / web_visit), but the same DSL covers logon /
978/// reboot / agent-health trends, etc.
979#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
980pub struct AggregateWidget {
981    /// Tab this widget lives under on the Analytics page. Widgets from
982    /// every job are collected and grouped by this label, so the same
983    /// string across jobs builds one multi-source dashboard. Required.
984    pub dashboard: String,
985    /// Widget heading. Required, validated non-empty.
986    pub title: String,
987    /// Optional one-line subtitle shown muted under the `title` on the
988    /// Analytics page — room for a unit, a caveat, or what the number
989    /// means ("samples × 2 min", "Security 4624 only"). Rejected if
990    /// present-but-blank.
991    #[serde(default, skip_serializing_if = "Option::is_none")]
992    pub description: Option<String>,
993    /// Optional sort weight (#743). Once the order-aware sort lands (PR2)
994    /// widgets render in `(order, dashboard, title)` order, so a lower
995    /// `order` pulls a widget — and its tab — earlier; equal/absent `order`
996    /// falls back to the alphabetical `(dashboard, title)` ordering. Treated
997    /// as `0` when unset, so a fleet with no `order` anywhere stays purely
998    /// alphabetical (today's behaviour); negatives are allowed to pin
999    /// something first. (This field only carries the value; the backend
1000    /// applies it.)
1001    #[serde(default, skip_serializing_if = "Option::is_none")]
1002    pub order: Option<i32>,
1003    /// Promote this widget to the main Dashboard, not just the Analytics
1004    /// page (#vuln-roadmap PR3). The Dashboard fetches the pinned subset
1005    /// (`/api/analytics?pinned=true`, fleet scope) and renders it with the
1006    /// same widget components. Operator-controlled, so any config-driven
1007    /// view (e.g. a future vulnerability rollup) can surface up front
1008    /// without a bespoke card. Defaults to `false`. Pin a `scope: fleet`
1009    /// widget — a `pc`-scoped one needs a selected PC and won't render on
1010    /// the fleet Dashboard.
1011    // `Not::not` is `!self`, so this skips serializing the field when it's
1012    // `false` — keeps `pin_dashboard: false` out of the stored job/view JSON,
1013    // matching how the optional fields above omit their defaults.
1014    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1015    pub pin_dashboard: bool,
1016    /// `pc` rolls up a single selected PC; `fleet` rolls up all PCs
1017    /// (and unlocks `group_by: pc_id` to rank PCs against each other).
1018    /// Defaults to `pc`.
1019    #[serde(default)]
1020    pub scope: AggregateScope,
1021    /// `obs_events.kind` this widget reads (e.g. `app_sample`,
1022    /// `presence`, `unexpected_shutdown`). Required for every aggregation
1023    /// render (`bar`/`gauge`/`timeline`/`stat`); rejected for
1024    /// `op_timeline`, which reconstructs a fixed multi-kind operational
1025    /// swimlane (power/session/sleep) baked into the SPA and so reads no
1026    /// single `kind`.
1027    #[serde(default, skip_serializing_if = "Option::is_none")]
1028    pub kind: Option<String>,
1029    /// Optional `obs_events.source` filter, when one `kind` is emitted by
1030    /// more than one collector.
1031    #[serde(default, skip_serializing_if = "Option::is_none")]
1032    pub source: Option<String>,
1033    /// How to roll the matching events up. See [`AggregateAgg`]. Required
1034    /// for every aggregation render; rejected for `op_timeline` (which
1035    /// performs no rollup — it returns the raw operational events and the
1036    /// SPA folds them into lane spans).
1037    #[serde(default, skip_serializing_if = "Option::is_none")]
1038    pub agg: Option<AggregateAgg>,
1039    /// Dotted JSON path (no `$.` prefix) to group by for `agg: count` /
1040    /// `sum` — e.g. `foreground.app`. The literal `pc_id` is special:
1041    /// it groups by the `pc_id` column (fleet ranking), not a payload
1042    /// field. Omit for a single total. Required when `agg: sum` needs a
1043    /// breakdown; for `agg: count` omitting it yields the grand total.
1044    #[serde(default, skip_serializing_if = "Option::is_none")]
1045    pub group_by: Option<String>,
1046    /// Dotted JSON path to a boolean for `agg: ratio` (e.g. `active`):
1047    /// the widget reports `true_count / total`. Required when `agg: ratio`.
1048    #[serde(default, skip_serializing_if = "Option::is_none")]
1049    pub bool_path: Option<String>,
1050    /// Dotted JSON path to a number for `agg: sum`. Required when `agg: sum`.
1051    #[serde(default, skip_serializing_if = "Option::is_none")]
1052    pub value_path: Option<String>,
1053    /// Optional value transform applied before grouping. Currently only
1054    /// `host` (parse a URL down to its host) — used by the top-sites
1055    /// widget, where SQLite can't parse a URL so the backend does it in
1056    /// Rust. See [`AggregateTransform`].
1057    #[serde(default, skip_serializing_if = "Option::is_none")]
1058    pub transform: Option<AggregateTransform>,
1059    /// Optional sampling cadence in minutes. When set, a `count` is also
1060    /// reported as estimated time (`count × sample_minutes`) — e.g. a
1061    /// 2-minute app sampler turns 11 samples into ~22 minutes. Must be ≥ 1.
1062    #[serde(default, skip_serializing_if = "Option::is_none")]
1063    #[schemars(range(min = 1))]
1064    pub sample_minutes: Option<u32>,
1065    /// Grouped values to drop from the rollup (e.g. `["LockApp"]` so the
1066    /// lock screen doesn't top the app ranking). Empty by default.
1067    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1068    pub exclude: Vec<String>,
1069    /// Optional time bucketing — `hour` buckets events by local
1070    /// hour-of-day for a `timeline` render. See [`AggregateTimeBucket`].
1071    #[serde(default, skip_serializing_if = "Option::is_none")]
1072    pub time_bucket: Option<AggregateTimeBucket>,
1073    /// Top-N cap for grouped renders (`bar`). Defaults to 10 when unset.
1074    #[serde(default, skip_serializing_if = "Option::is_none")]
1075    #[schemars(range(min = 1))]
1076    pub limit: Option<u32>,
1077    /// Which widget the SPA draws. See [`AggregateRender`].
1078    pub render: AggregateRender,
1079}
1080
1081/// Per-PC vs fleet-wide rollup for an [`AggregateWidget`].
1082#[derive(
1083    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
1084)]
1085#[serde(rename_all = "lowercase")]
1086#[non_exhaustive]
1087pub enum AggregateScope {
1088    /// Roll up the single PC the operator selected. The default.
1089    #[default]
1090    Pc,
1091    /// Roll up across every PC. Unlocks `group_by: pc_id`.
1092    Fleet,
1093    /// #492 forward-compat catch-all — a Manifest is read fleet-wide, so
1094    /// an older reader must tolerate a future variant rather than failing
1095    /// to decode the whole job. The backend skips an `Unknown` widget.
1096    #[serde(other)]
1097    Unknown,
1098}
1099
1100/// The rollup function for an [`AggregateWidget`].
1101#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1102#[serde(rename_all = "lowercase")]
1103#[non_exhaustive]
1104pub enum AggregateAgg {
1105    /// Row count, optionally grouped (`group_by`) and time-estimated
1106    /// (`sample_minutes`).
1107    Count,
1108    /// `true_count / total` over `bool_path`.
1109    Ratio,
1110    /// Sum of `value_path`, optionally grouped.
1111    Sum,
1112    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1113    #[serde(other)]
1114    Unknown,
1115}
1116
1117/// Optional pre-grouping value transform for an [`AggregateWidget`].
1118#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1119#[serde(rename_all = "lowercase")]
1120#[non_exhaustive]
1121pub enum AggregateTransform {
1122    /// Parse the grouped value as a URL and keep only its host.
1123    Host,
1124    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1125    #[serde(other)]
1126    Unknown,
1127}
1128
1129/// Time bucketing for an [`AggregateWidget`] (drives a `timeline`).
1130#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1131#[serde(rename_all = "lowercase")]
1132#[non_exhaustive]
1133pub enum AggregateTimeBucket {
1134    /// Bucket by local hour-of-day (0–23), summed over the window.
1135    Hour,
1136    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1137    #[serde(other)]
1138    Unknown,
1139}
1140
1141/// Which visual the SPA renders an [`AggregateWidget`] as.
1142#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1143#[serde(rename_all = "lowercase")]
1144#[non_exhaustive]
1145pub enum AggregateRender {
1146    /// Ranked horizontal bars (a grouped `count` / `sum`).
1147    Bar,
1148    /// A single ratio dial (`agg: ratio`).
1149    Gauge,
1150    /// 24-hour activity strip (`time_bucket: hour`).
1151    Timeline,
1152    /// A single headline number (an ungrouped total).
1153    Stat,
1154    /// Per-PC operational swimlane (power / session / sleep) reconstructed
1155    /// from a fixed multi-kind event set. Unlike the aggregation renders it
1156    /// reads no single `kind`/`agg`: the backend returns the raw events in
1157    /// the window and the SPA folds them into lane spans (shared with the
1158    /// Events page strip). Per-PC only (`scope: pc`).
1159    #[serde(rename = "op_timeline")]
1160    OpTimeline,
1161    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1162    #[serde(other)]
1163    Unknown,
1164}
1165
1166/// True if `p` is a well-formed dotted JSON path of `[A-Za-z0-9_]`
1167/// segments joined by single dots — the shape safe to bind into
1168/// `json_extract(payload, '$.' || ?)`. The charset blocks injection; the
1169/// segment check additionally rejects `"."`, `".foo"`, `"foo."`,
1170/// `"foo..bar"`, which would pass the charset but produce a malformed
1171/// `$.` path that errors at query time. Accepts `pc_id`, `foreground.app`,
1172/// `active`, etc.
1173fn is_valid_json_path(p: &str) -> bool {
1174    !p.is_empty()
1175        && p.split('.').all(|seg| {
1176            !seg.is_empty() && seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
1177        })
1178}
1179
1180/// Per-widget validation for a list of [`AggregateWidget`]s — shared by
1181/// the `aggregate:` job hint ([`Manifest::validate`]) and the standalone
1182/// [`View`] resource (#743) so the two can't diverge. `field` names the
1183/// containing key for error messages (`"aggregate"` or `"widgets"`).
1184///
1185/// Enforces: non-empty list; non-empty dashboard/title (and `kind`/`agg`
1186/// for every aggregation render); a blank-when-set `source`; rejection of
1187/// any #492 `Unknown` enum (an operator typo at create time); safe dotted
1188/// JSON paths; the value path each `agg` needs (and rejection of mis-paired
1189/// ones); `pc_id` grouping only in `fleet` scope; `transform`/`limit`/
1190/// `exclude` only with a `group_by`; positive `limit`/`sample_minutes`;
1191/// `gauge`⇔`ratio`; and `timeline`⇔`time_bucket`. A `render: op_timeline`
1192/// widget is validated separately (per-PC, no aggregation knobs) — see
1193/// [`validate_op_timeline_widget`].
1194pub fn validate_aggregate_widgets(widgets: &[AggregateWidget], field: &str) -> Result<(), String> {
1195    if widgets.is_empty() {
1196        return Err(format!(
1197            "`{field}:` must list at least one widget when present"
1198        ));
1199    }
1200    for (i, w) in widgets.iter().enumerate() {
1201        let at = format!("{field}[{i}]");
1202        for (label, value) in [("dashboard", &w.dashboard), ("title", &w.title)] {
1203            if value.trim().is_empty() {
1204                return Err(format!("{at}.{label} must not be empty"));
1205            }
1206        }
1207        // A present-but-blank `description` renders an empty muted line —
1208        // reject it so the subtitle only shows when it says something.
1209        if let Some(description) = &w.description {
1210            if description.trim().is_empty() {
1211                return Err(format!("{at}.description must not be empty when set"));
1212            }
1213        }
1214        // Reject values that fell through to the #492 `Unknown` catch-all:
1215        // at create time on the current version that's an operator typo. (A
1216        // genuinely-future variant only reaches an older reader via a stored
1217        // resource, which is never re-validated, so forward-compat holds.)
1218        if w.scope == AggregateScope::Unknown {
1219            return Err(format!("{at}.scope is not a known value (pc | fleet)"));
1220        }
1221        if w.render == AggregateRender::Unknown {
1222            return Err(format!(
1223                "{at}.render is not a known value (bar | gauge | timeline | stat | op_timeline)"
1224            ));
1225        }
1226        // `op_timeline` reconstructs a fixed per-PC operational swimlane
1227        // (power/session/sleep) from a baked-in multi-kind set — it uses none
1228        // of the aggregation knobs, so validate it on its own terms (per-PC,
1229        // no `kind`/`agg`/grouping) and skip the rollup rules below.
1230        if w.render == AggregateRender::OpTimeline {
1231            validate_op_timeline_widget(w, &at)?;
1232            continue;
1233        }
1234        // Every other render is an aggregation over a single `kind`.
1235        if w.kind.as_deref().map(str::trim).unwrap_or("").is_empty() {
1236            return Err(format!("{at}.kind must not be empty"));
1237        }
1238        let agg = match w.agg {
1239            Some(AggregateAgg::Unknown) => {
1240                return Err(format!(
1241                    "{at}.agg is not a known value (count | ratio | sum)"
1242                ));
1243            }
1244            Some(agg) => agg,
1245            None => return Err(format!("{at}.agg is required")),
1246        };
1247        // A present-but-blank `source` is a no-op filter — reject like the
1248        // other blank-when-set guards.
1249        if let Some(source) = &w.source {
1250            if source.trim().is_empty() {
1251                return Err(format!("{at}.source must not be empty when set"));
1252            }
1253        }
1254        if w.transform == Some(AggregateTransform::Unknown) {
1255            return Err(format!("{at}.transform is not a known value (host)"));
1256        }
1257        if w.time_bucket == Some(AggregateTimeBucket::Unknown) {
1258            return Err(format!("{at}.time_bucket is not a known value (hour)"));
1259        }
1260        for (label, path) in [
1261            ("group_by", &w.group_by),
1262            ("bool_path", &w.bool_path),
1263            ("value_path", &w.value_path),
1264        ] {
1265            if let Some(p) = path {
1266                if !is_valid_json_path(p) {
1267                    return Err(format!(
1268                        "{at}.{label} '{p}' must be a dotted JSON path of [A-Za-z0-9_] segments"
1269                    ));
1270                }
1271            }
1272        }
1273        // Each agg uses exactly one value path; reject a mis-paired path so
1274        // a typo fails at create rather than being ignored.
1275        match agg {
1276            // count: grouped → ranking, ungrouped → grand total.
1277            AggregateAgg::Count => {
1278                for (label, path) in [("bool_path", &w.bool_path), ("value_path", &w.value_path)] {
1279                    if path.is_some() {
1280                        return Err(format!("{at}.agg=count does not use `{label}`"));
1281                    }
1282                }
1283            }
1284            AggregateAgg::Ratio => {
1285                if w.bool_path.is_none() {
1286                    return Err(format!("{at}.agg=ratio requires `bool_path`"));
1287                }
1288                if w.value_path.is_some() {
1289                    return Err(format!("{at}.agg=ratio does not use `value_path`"));
1290                }
1291            }
1292            AggregateAgg::Sum => {
1293                if w.value_path.is_none() {
1294                    return Err(format!("{at}.agg=sum requires `value_path`"));
1295                }
1296                if w.bool_path.is_some() {
1297                    return Err(format!("{at}.agg=sum does not use `bool_path`"));
1298                }
1299            }
1300            // Rejected above; arm exists only for exhaustiveness.
1301            AggregateAgg::Unknown => {}
1302        }
1303        // Ranking PCs against each other only means something across the
1304        // fleet — within one PC it's a single bar.
1305        if w.group_by.as_deref() == Some("pc_id") && w.scope != AggregateScope::Fleet {
1306            return Err(format!(
1307                "{at}.group_by: pc_id is only valid with scope: fleet"
1308            ));
1309        }
1310        // `transform` rewrites the grouped PAYLOAD value (URL→host); it's
1311        // meaningless on a `pc_id` grouping (the pc_id column, not a payload
1312        // field), so reject the combo at create time.
1313        if w.transform.is_some() && w.group_by.as_deref() == Some("pc_id") {
1314            return Err(format!("{at}.transform is not valid with group_by: pc_id"));
1315        }
1316        // limit / transform / exclude all operate on grouped values, so
1317        // without a `group_by` they're silent no-ops — reject.
1318        if w.group_by.is_none() {
1319            if w.limit.is_some() {
1320                return Err(format!("{at}.limit requires `group_by`"));
1321            }
1322            if w.transform.is_some() {
1323                return Err(format!("{at}.transform requires `group_by`"));
1324            }
1325            if !w.exclude.is_empty() {
1326                return Err(format!("{at}.exclude requires `group_by`"));
1327            }
1328        }
1329        if w.limit == Some(0) {
1330            return Err(format!("{at}.limit must be > 0"));
1331        }
1332        if w.sample_minutes == Some(0) {
1333            return Err(format!("{at}.sample_minutes must be > 0"));
1334        }
1335        for ex in &w.exclude {
1336            if ex.trim().is_empty() {
1337                return Err(format!("{at}.exclude must not contain empty entries"));
1338            }
1339        }
1340        // A gauge draws a single ratio dial — only meaningful for agg: ratio.
1341        if w.render == AggregateRender::Gauge && agg != AggregateAgg::Ratio {
1342            return Err(format!("{at}.render=gauge is only valid with agg: ratio"));
1343        }
1344        // A timeline needs a bucket; a bucket on any other render is a no-op
1345        // that signals operator confusion — reject both.
1346        match (w.render, &w.time_bucket) {
1347            (AggregateRender::Timeline, None) => {
1348                return Err(format!("{at}.render=timeline requires `time_bucket`"));
1349            }
1350            (r, Some(_)) if r != AggregateRender::Timeline => {
1351                return Err(format!(
1352                    "{at}.time_bucket is only valid with render: timeline"
1353                ));
1354            }
1355            _ => {}
1356        }
1357    }
1358    Ok(())
1359}
1360
1361/// Validate a `render: op_timeline` widget. It draws a fixed per-PC
1362/// operational swimlane (power / session / sleep) reconstructed by the SPA
1363/// from a baked-in multi-kind event set, so it uses none of the aggregation
1364/// knobs: require `scope: pc` and reject every field that only makes sense
1365/// for a rollup (`kind`/`source`/`agg`/`group_by`/`bool_path`/`value_path`/
1366/// `transform`/`sample_minutes`/`exclude`/`time_bucket`/`limit`). Rejecting
1367/// the unused fields (rather than ignoring them) keeps an operator typo from
1368/// silently doing nothing, matching the rest of this validator.
1369fn validate_op_timeline_widget(w: &AggregateWidget, at: &str) -> Result<(), String> {
1370    // Per-PC only: a fleet-wide swimlane of every PC's spans is unbounded
1371    // and unreadable, and the backend only computes it in per-PC scope.
1372    if w.scope != AggregateScope::Pc {
1373        return Err(format!("{at}.render=op_timeline requires scope: pc"));
1374    }
1375    // Each unused field, with the name the operator wrote, so the error
1376    // points at exactly what to delete.
1377    if w.kind.is_some() {
1378        return Err(format!("{at}.render=op_timeline does not use `kind`"));
1379    }
1380    if w.source.is_some() {
1381        return Err(format!("{at}.render=op_timeline does not use `source`"));
1382    }
1383    if w.agg.is_some() {
1384        return Err(format!("{at}.render=op_timeline does not use `agg`"));
1385    }
1386    for (label, set) in [
1387        ("group_by", w.group_by.is_some()),
1388        ("bool_path", w.bool_path.is_some()),
1389        ("value_path", w.value_path.is_some()),
1390        ("transform", w.transform.is_some()),
1391        ("sample_minutes", w.sample_minutes.is_some()),
1392        ("time_bucket", w.time_bucket.is_some()),
1393        ("limit", w.limit.is_some()),
1394        ("exclude", !w.exclude.is_empty()),
1395    ] {
1396        if set {
1397            return Err(format!("{at}.render=op_timeline does not use `{label}`"));
1398        }
1399    }
1400    Ok(())
1401}
1402
1403/// Default materialization cadence for a [`SqlWidget`] whose `refresh` is
1404/// unset — 1 hour. A view over feed/inventory tables changes only as fast as
1405/// its underlying feed refresh (often daily), so an hour is fresh enough while
1406/// keeping an expensive correlation join off the ~30s Dashboard poll path.
1407pub const DEFAULT_VIEW_REFRESH: std::time::Duration = std::time::Duration::from_secs(3600);
1408
1409/// #vuln-roadmap PR3: a **SQL-backed, materialized** widget on a [`View`].
1410///
1411/// Where an [`AggregateWidget`] encodes an `obs_events` rollup in structured
1412/// YAML fields, a `SqlWidget` carries a raw read-only `SELECT`/`WITH` over the
1413/// projector's tables (inventory `explode:` tables, `feeds`, `check_status`,
1414/// …) — the correlation that powers a vulnerability / EOL / license dashboard
1415/// is just a `JOIN`, far more expressive than a YAML DSL. The backend runs the
1416/// query in the read-only sandbox (`api::query`), caches the result on the
1417/// `refresh` cadence, and maps it to the same render-ready shape the existing
1418/// widget components consume, via [`RenderSpec`]. See [`View::sql_widgets`].
1419#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1420pub struct SqlWidget {
1421    /// Widget heading. Required, validated non-empty.
1422    pub title: String,
1423    /// Optional muted subtitle (a unit, a caveat). Rejected if present-blank.
1424    #[serde(default, skip_serializing_if = "Option::is_none")]
1425    pub description: Option<String>,
1426    /// The read-only SQL. Executed in the `api::query` sandbox: a single
1427    /// `SELECT`/`WITH` on a `SQLITE_OPEN_READONLY` connection, row-capped and
1428    /// time-bounded. The backend validates it read-only at `view create` and
1429    /// again at run time; a write verb / stacked statement is rejected.
1430    pub query: String,
1431    /// How the query's result columns map to a visual — see [`RenderSpec`].
1432    pub render: RenderSpec,
1433    /// Materialization cadence as a humantime duration (`"6h"`, `"30m"`).
1434    /// Absent ⇒ [`DEFAULT_VIEW_REFRESH`]. The backend re-runs the query at
1435    /// most this often; reads in between hit the cache.
1436    #[serde(default, skip_serializing_if = "Option::is_none")]
1437    pub refresh: Option<String>,
1438    /// Where the widget surfaces — an Analytics tab and/or a pinned Dashboard
1439    /// card. At least one must be set (else it renders nowhere).
1440    pub placement: Placement,
1441}
1442
1443impl SqlWidget {
1444    /// The effective refresh cadence — the parsed `refresh` or
1445    /// [`DEFAULT_VIEW_REFRESH`]. Falls back to the default on an unparseable
1446    /// value rather than panicking on the read path (validation already
1447    /// rejected a bad value at `view create`).
1448    pub fn refresh_interval(&self) -> std::time::Duration {
1449        self.refresh
1450            .as_deref()
1451            .and_then(|s| humantime::parse_duration(s).ok())
1452            .unwrap_or(DEFAULT_VIEW_REFRESH)
1453    }
1454}
1455
1456/// How a [`SqlWidget`]'s SQL result columns map onto a visual. A `kind` names
1457/// the chart; the channel fields (`value`, `label`, `columns`, …) name which
1458/// result columns feed it. Only the channels a `kind` uses are read; the
1459/// backend validates the named columns exist in the result. New chart types
1460/// are "one renderer + the same mapping", so this stays a flat, additive shape.
1461#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Hash)]
1462pub struct RenderSpec {
1463    /// Which visual to render the result as.
1464    pub kind: RenderKind,
1465    /// `table` only: the columns to show, in order. Absent ⇒ every result
1466    /// column (the universal default).
1467    #[serde(default, skip_serializing_if = "Option::is_none")]
1468    pub columns: Option<Vec<String>>,
1469    /// `table` only: optional per-column header relabelling (result column →
1470    /// display name). Columns not listed keep their SQL name.
1471    #[serde(default, skip_serializing_if = "Option::is_none")]
1472    pub labels: Option<std::collections::BTreeMap<String, String>>,
1473    /// `stat` / `bar` / `pie` / `gauge`: the result column holding the numeric
1474    /// value (`stat`/`gauge` read the first row; `bar`/`pie` read every row).
1475    #[serde(default, skip_serializing_if = "Option::is_none")]
1476    pub value: Option<String>,
1477    /// `bar` / `pie`: the result column holding each row's category label.
1478    #[serde(default, skip_serializing_if = "Option::is_none")]
1479    pub label: Option<String>,
1480    /// `bar` / `pie`: keep only the top-N rows (by value). Absent ⇒ all rows.
1481    #[serde(default, skip_serializing_if = "Option::is_none")]
1482    pub limit: Option<u32>,
1483    /// `pie` only: render as a donut (a hole with the total in the centre).
1484    #[serde(default, skip_serializing_if = "Option::is_none")]
1485    pub donut: Option<bool>,
1486    /// `gauge` only: the numerator column (paired with `den`). Alternative to
1487    /// a precomputed `value` ratio.
1488    #[serde(default, skip_serializing_if = "Option::is_none")]
1489    pub num: Option<String>,
1490    /// `gauge` only: the denominator column (paired with `num`).
1491    #[serde(default, skip_serializing_if = "Option::is_none")]
1492    pub den: Option<String>,
1493}
1494
1495/// The chart kind for a [`RenderSpec`]. `table` and `pie` are new in PR3; the
1496/// rest reuse the existing `obs_events` widget renderers.
1497#[derive(
1498    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash, Default,
1499)]
1500#[serde(rename_all = "lowercase")]
1501pub enum RenderKind {
1502    /// The full result grid (new renderer). The universal default.
1503    #[default]
1504    Table,
1505    /// A single headline number from the first row's `value` cell.
1506    Stat,
1507    /// Ranked horizontal bars — `label` + `value` per row, optional top-N.
1508    Bar,
1509    /// Parts-of-a-whole (new renderer) — `label` + `value` per row.
1510    Pie,
1511    /// A ratio dial — a `value` ratio, or a `num`/`den` pair.
1512    Gauge,
1513    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1514    #[serde(other)]
1515    Unknown,
1516}
1517
1518/// Where a [`SqlWidget`] surfaces in the SPA. Mirrors the placement an
1519/// [`AggregateWidget`] expresses via `dashboard` + `pin_dashboard`, but as an
1520/// explicit block since a SQL widget lives on a standalone view.
1521#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1522pub struct Placement {
1523    /// The Analytics tab this widget groups under (the `AggregateWidget`
1524    /// `dashboard` analogue). Absent ⇒ not shown on the Analytics page.
1525    #[serde(default, skip_serializing_if = "Option::is_none")]
1526    pub analytics: Option<String>,
1527    /// Promote to the main Dashboard (reuses #900's pinned section). Absent ⇒
1528    /// not pinned.
1529    #[serde(default, skip_serializing_if = "Option::is_none")]
1530    pub dashboard: Option<DashboardPlacement>,
1531}
1532
1533impl Placement {
1534    /// True when the widget is pinned to the main Dashboard.
1535    pub fn is_pinned(&self) -> bool {
1536        self.dashboard.as_ref().is_some_and(|d| d.pin)
1537    }
1538    /// The Analytics tab name, or a fallback so a dashboard-only widget still
1539    /// carries a group label for the shared widget list.
1540    pub fn tab(&self) -> &str {
1541        self.analytics.as_deref().unwrap_or("Dashboard")
1542    }
1543}
1544
1545/// The `placement.dashboard` block — see [`Placement::dashboard`].
1546#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1547pub struct DashboardPlacement {
1548    /// Pin this widget to the main Dashboard's promoted section.
1549    #[serde(default)]
1550    pub pin: bool,
1551}
1552
1553/// Per-widget validation for a list of [`SqlWidget`]s — shared by the
1554/// [`View`] resource so authoring errors surface at `view create`. `field`
1555/// names the containing key for error messages. The read-only SQL check is
1556/// NOT here (it lives in the backend `api::query` sandbox, which kanade-shared
1557/// can't depend on) — this validates structure: non-empty title/query, a
1558/// known `kind`, the channels each `kind` needs, a real placement, and a
1559/// parseable `refresh`.
1560pub fn validate_sql_widgets(widgets: &[SqlWidget], field: &str) -> Result<(), String> {
1561    for (i, w) in widgets.iter().enumerate() {
1562        let at = format!("{field}[{i}]");
1563        if w.title.trim().is_empty() {
1564            return Err(format!("{at}.title must not be empty"));
1565        }
1566        if w.query.trim().is_empty() {
1567            return Err(format!("{at}.query must not be empty"));
1568        }
1569        if let Some(description) = &w.description {
1570            if description.trim().is_empty() {
1571                return Err(format!("{at}.description must not be empty when set"));
1572            }
1573        }
1574        if let Some(refresh) = &w.refresh {
1575            humantime::parse_duration(refresh)
1576                .map_err(|e| format!("{at}.refresh '{refresh}' is not a valid duration: {e}"))?;
1577        }
1578        // A widget that surfaces nowhere is an invisible no-op. A
1579        // `dashboard:` block with `pin: false` doesn't count — it pins
1580        // nowhere — so gate on the effective pin, not the block's presence
1581        // (Gemini / CodeRabbit).
1582        if w.placement.analytics.is_none() && !w.placement.is_pinned() {
1583            return Err(format!(
1584                "{at}.placement must set `analytics` and/or pin to `dashboard` (else the widget renders nowhere)"
1585            ));
1586        }
1587        if let Some(tab) = &w.placement.analytics {
1588            if tab.trim().is_empty() {
1589                return Err(format!(
1590                    "{at}.placement.analytics must not be empty when set"
1591                ));
1592            }
1593        }
1594        // A per-PC widget (its query binds `:pc_id`) renders only in the
1595        // per-PC Analytics scope, bound to the selected PC. The Dashboard's
1596        // pinned section is fleet-scope and never sends a PC, so a pinned
1597        // per-PC widget would be silently dropped on every request — reject
1598        // the contradiction at create time rather than let it vanish (claude
1599        // review). Literal-aware so a `:pc_id` inside a string literal doesn't
1600        // trip it (see [`rewrite_pc_id_param`]).
1601        if w.placement.is_pinned() && rewrite_pc_id_param(&w.query).1 > 0 {
1602            return Err(format!(
1603                "{at}: a per-PC widget (its query binds `:pc_id`) cannot pin to the Dashboard \
1604                 (the Dashboard is fleet-scope, it never selects a PC) — use `analytics` placement only"
1605            ));
1606        }
1607        validate_render_spec(&w.render, &at)?;
1608    }
1609    Ok(())
1610}
1611
1612/// The named parameter a per-PC [`SqlWidget`] binds to the selected PC. Its
1613/// presence in a widget's query is what makes the widget per-PC.
1614pub const PC_ID_PARAM: &str = ":pc_id";
1615
1616/// Rewrite every *real* `:pc_id` parameter in a widget query to a positional
1617/// `?`, returning `(rewritten_sql, count)`. "Real" = OUTSIDE string literals,
1618/// quoted identifiers and comments, and a whole token (the char after `:pc_id`
1619/// isn't a word char, so `:pc_idx` is left alone). One scanner shared by three
1620/// call sites so they can't disagree on how many `?` SQLite will actually see:
1621///   * per-PC scope detection (`count > 0` ⇒ the widget is per-PC),
1622///   * the backend's bind path (sqlx-sqlite binds POSITIONAL `?` only, not
1623///     `:name`, so the token must be rewritten and bound once per occurrence),
1624///   * and `validate_sql_widgets`' pinned-per-PC rejection above.
1625///
1626/// The literal/comment skipping mirrors the read-only sandbox's
1627/// `strip_sql_noise`, so a `:pc_id` inside `SELECT 'see :pc_id docs'` is copied
1628/// verbatim and NOT counted — it would otherwise be miscounted (a bind-count
1629/// mismatch → `SQLITE_RANGE`) and misclassify the widget's scope (Gemini /
1630/// claude review).
1631pub fn rewrite_pc_id_param(sql: &str) -> (String, usize) {
1632    let mut out = String::with_capacity(sql.len());
1633    let mut count = 0usize;
1634    let mut chars = sql.char_indices().peekable();
1635    while let Some((idx, c)) = chars.next() {
1636        match c {
1637            // String literal / quoted identifier — copy verbatim, honouring the
1638            // doubled-quote escape (`''` / `""` stays inside).
1639            '\'' | '"' => {
1640                out.push(c);
1641                let quote = c;
1642                while let Some((_, d)) = chars.next() {
1643                    out.push(d);
1644                    if d == quote {
1645                        if chars.peek().map(|&(_, e)| e) == Some(quote) {
1646                            let (_, e) = chars.next().unwrap();
1647                            out.push(e);
1648                        } else {
1649                            break;
1650                        }
1651                    }
1652                }
1653            }
1654            // Line comment — copy to end of line.
1655            '-' if chars.peek().map(|&(_, e)| e) == Some('-') => {
1656                out.push(c);
1657                for (_, d) in chars.by_ref() {
1658                    out.push(d);
1659                    if d == '\n' {
1660                        break;
1661                    }
1662                }
1663            }
1664            // Block comment — copy to `*/`.
1665            '/' if chars.peek().map(|&(_, e)| e) == Some('*') => {
1666                out.push(c);
1667                let (_, star) = chars.next().unwrap();
1668                out.push(star);
1669                let mut prev = ' ';
1670                for (_, d) in chars.by_ref() {
1671                    out.push(d);
1672                    if prev == '*' && d == '/' {
1673                        break;
1674                    }
1675                    prev = d;
1676                }
1677            }
1678            // A `:pc_id` token outside any literal/comment — rewrite if it's a
1679            // whole token (not the prefix of `:pc_idx`).
1680            ':' if sql[idx..].starts_with(PC_ID_PARAM) => {
1681                let after = idx + PC_ID_PARAM.len();
1682                let next_is_word = sql[after..]
1683                    .chars()
1684                    .next()
1685                    .is_some_and(|w| w.is_alphanumeric() || w == '_');
1686                if next_is_word {
1687                    out.push(c);
1688                } else {
1689                    out.push('?');
1690                    count += 1;
1691                    for _ in 0..PC_ID_PARAM.chars().count() - 1 {
1692                        chars.next();
1693                    }
1694                }
1695            }
1696            _ => out.push(c),
1697        }
1698    }
1699    (out, count)
1700}
1701
1702/// Validate a [`RenderSpec`]: reject the #492 `Unknown` catch-all (an operator
1703/// typo at create time) and require the channel columns each `kind` reads.
1704fn validate_render_spec(r: &RenderSpec, at: &str) -> Result<(), String> {
1705    // A channel column is "given" when present and non-blank.
1706    let given = |v: &Option<String>| v.as_deref().map(str::trim).is_some_and(|s| !s.is_empty());
1707    match r.kind {
1708        RenderKind::Unknown => {
1709            return Err(format!(
1710                "{at}.render.kind is not a known value (table | stat | bar | pie | gauge)"
1711            ));
1712        }
1713        RenderKind::Table => {
1714            // `columns` optional; if given, each name must be non-blank.
1715            if let Some(cols) = &r.columns {
1716                if cols.iter().any(|c| c.trim().is_empty()) {
1717                    return Err(format!("{at}.render.columns must not contain blank names"));
1718                }
1719            }
1720            if let Some(labels) = &r.labels {
1721                for (k, v) in labels {
1722                    if k.trim().is_empty() || v.trim().is_empty() {
1723                        return Err(format!(
1724                            "{at}.render.labels keys and values must be non-empty"
1725                        ));
1726                    }
1727                }
1728            }
1729        }
1730        RenderKind::Stat => {
1731            if !given(&r.value) {
1732                return Err(format!("{at}.render.value is required for kind=stat"));
1733            }
1734        }
1735        RenderKind::Bar | RenderKind::Pie => {
1736            let kind = if r.kind == RenderKind::Bar {
1737                "bar"
1738            } else {
1739                "pie"
1740            };
1741            if !given(&r.label) {
1742                return Err(format!("{at}.render.label is required for kind={kind}"));
1743            }
1744            if !given(&r.value) {
1745                return Err(format!("{at}.render.value is required for kind={kind}"));
1746            }
1747            // `limit: 0` truncates to no rows — an invisible widget, almost
1748            // certainly a typo. Omit `limit` for "all rows" (CodeRabbit).
1749            if r.limit == Some(0) {
1750                return Err(format!(
1751                    "{at}.render.limit must be >= 1 (omit it to keep all rows)"
1752                ));
1753            }
1754        }
1755        RenderKind::Gauge => {
1756            // Either a precomputed `value` ratio, or a `num`/`den` pair —
1757            // exactly one of the two forms.
1758            match (given(&r.value), given(&r.num), given(&r.den)) {
1759                (true, false, false) => {}
1760                (false, true, true) => {}
1761                _ => {
1762                    return Err(format!(
1763                        "{at}.render for kind=gauge needs either `value` (a ratio) or both `num` and `den`"
1764                    ));
1765                }
1766            }
1767        }
1768    }
1769    Ok(())
1770}
1771
1772/// A standalone declarative read/aggregation for the Analytics page (#743).
1773///
1774/// A **view** aggregates stored fleet data (`obs_events`, …) without an
1775/// `execute` or a schedule — unlike a [`Manifest`] it only declares
1776/// [`AggregateWidget`]s. (The first line is concise on purpose: `schemars`
1777/// uses it as the generated schema's `title`.) The backend reads views from
1778/// `BUCKET_VIEWS` at
1779/// query time and merges their widgets with the co-located `aggregate:`
1780/// hints on jobs, so a cross-cutting dashboard (one that charts events
1781/// emitted by several other jobs / the agent) has a home that doesn't need
1782/// a noop job carrier. Stored JSON in `BUCKET_VIEWS`, keyed by `id`.
1783#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1784pub struct View {
1785    /// Stable identifier (the KV key). Required, validated non-empty.
1786    pub id: String,
1787    /// Optional human description shown on the Views admin page.
1788    #[serde(default, skip_serializing_if = "Option::is_none")]
1789    pub description: Option<String>,
1790    /// The `obs_events` aggregate widgets this view contributes to the
1791    /// Analytics page. Optional since PR3 — a view may instead (or also)
1792    /// carry [`sql_widgets`](View::sql_widgets); a view must have at least one
1793    /// widget across the two lists.
1794    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1795    pub widgets: Vec<AggregateWidget>,
1796    /// #vuln-roadmap PR3: SQL-backed, materialized widgets — raw read-only SQL
1797    /// over the projector tables (inventory/feeds/…) mapped to a visual. This
1798    /// is how a correlation dashboard (vulnerability / EOL / license) is
1799    /// expressed as config. See [`SqlWidget`].
1800    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1801    pub sql_widgets: Vec<SqlWidget>,
1802    /// Free-form operator taxonomy (same role as [`Manifest::tags`]).
1803    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1804    pub tags: Vec<String>,
1805    /// GitOps provenance (#678), stamped by `kanade view create` from the
1806    /// source YAML's Git context — same as [`Manifest::origin`].
1807    #[serde(default, skip_serializing_if = "Option::is_none")]
1808    pub origin: Option<RepoOrigin>,
1809}
1810
1811/// True if `id` is a safe resource identifier — non-empty and only
1812/// `[A-Za-z0-9._-]`. A view `id` becomes a NATS KV key *and* a URL path
1813/// segment (`/api/views/{id}`), so this blocks `/`, `..`, whitespace and
1814/// other characters that would break the KV key or let a CLI arg wander
1815/// the URL space. (#743 / #744 follow-up — a deliberately small charset
1816/// rather than the looser set NATS technically allows.)
1817pub fn is_valid_resource_id(id: &str) -> bool {
1818    !id.is_empty()
1819        && id
1820            .chars()
1821            .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-')
1822}
1823
1824impl View {
1825    pub fn validate(&self) -> Result<(), String> {
1826        // Validate the id exactly as stored — no `.trim()`. `views::create`
1827        // uses `self.id` verbatim as the KV key and it's the `/api/views/{id}`
1828        // URL segment a lookup matches, so a padded id like `" my-view "` that
1829        // validated as its trimmed form but was stored raw would silently never
1830        // match. The charset excludes whitespace, so checking the untrimmed id
1831        // rejects such an id outright.
1832        if !is_valid_resource_id(&self.id) {
1833            return Err(
1834                "view.id must be non-empty and only [A-Za-z0-9._-] (it's a KV key + URL segment; \
1835                 no surrounding whitespace)"
1836                    .to_string(),
1837            );
1838        }
1839        // A view must contribute at least one widget across the two lists;
1840        // `validate_aggregate_widgets` rejects an empty `widgets` on its own,
1841        // so only call it when that list is non-empty (a pure-SQL view is
1842        // valid with an empty `widgets`).
1843        if self.widgets.is_empty() && self.sql_widgets.is_empty() {
1844            return Err(
1845                "view must declare at least one widget (`widgets:` and/or `sql_widgets:`)"
1846                    .to_string(),
1847            );
1848        }
1849        if !self.widgets.is_empty() {
1850            validate_aggregate_widgets(&self.widgets, "widgets")?;
1851        }
1852        validate_sql_widgets(&self.sql_widgets, "sql_widgets")?;
1853        for tag in &self.tags {
1854            if tag.trim().is_empty() {
1855                return Err("tags must not contain empty entries".to_string());
1856            }
1857        }
1858        Ok(())
1859    }
1860}
1861
1862/// Default membership-recompute cadence for a dynamic [`GroupDef`] whose
1863/// `refresh` is unset — 10 minutes. A group's SQL is evaluated lazily (only
1864/// when a schedule targeting it fires, or the members preview is requested)
1865/// and the result cached for this long, so fleet facts (inventory updates, a
1866/// newly-registered PC) reach the group within at most one cadence while an
1867/// expensive correlation query stays off the hot scheduler-tick path. A
1868/// static `members:` group ignores this (its membership is literal).
1869pub const DEFAULT_GROUP_REFRESH: std::time::Duration = std::time::Duration::from_secs(600);
1870
1871/// A **declared fleet group** (#1032): the third manifest kind alongside
1872/// [`Manifest`] (jobs) and [`Schedule`] (schedules), stored in
1873/// `BUCKET_GROUP_DEFS` keyed by [`id`](GroupDef::id).
1874///
1875/// (The first doc line deliberately does not start with `#NNN` — schemars
1876/// treats a leading `#` as a Markdown heading and would extract it as the
1877/// schema `title`, garbling it. Same reason [`View`]'s doc leads with prose.)
1878///
1879/// A group definition names a set of PCs in one of two mutually-exclusive
1880/// ways:
1881///   * **static** — a literal [`members`](GroupDef::members) list. Declared,
1882///     git-reviewable membership (the auditability win over hand-editing the
1883///     imperative `agent_groups` KV).
1884///   * **dynamic** — a read-only SQL [`query`](GroupDef::query) that returns a
1885///     `pc_id` column. Membership is *derived from the fleet's own facts*
1886///     (`agents`, `inventory_facts` + `json_extract(facts_json, …)`, `feeds`,
1887///     `check_status`, `explode:` tables — anything in the projector DB), so
1888///     "every client OS", "the servers sharing a hostname prefix", "machines
1889///     still on build 26100" are all just a `SELECT`. The query runs in the
1890///     backend read-only sandbox (`api::query`), never on the endpoint.
1891///
1892/// A schedule's `target.groups` resolves a defined group (static or dynamic)
1893/// **in addition to** the imperative `agent_groups` membership, so declared
1894/// groups and manually-assigned ones coexist and this never mutates
1895/// `agent_groups`.
1896#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1897pub struct GroupDef {
1898    /// Stable identifier (the KV key + URL segment + the name a schedule's
1899    /// `target.groups` references). Required; same `[A-Za-z0-9._-]` charset
1900    /// as a [`View`] id via [`is_valid_resource_id`].
1901    pub id: String,
1902    /// Optional human description shown on the groups admin page.
1903    #[serde(default, skip_serializing_if = "Option::is_none")]
1904    pub description: Option<String>,
1905    /// Static membership — a literal list of `pc_id`s. Mutually exclusive with
1906    /// [`query`](GroupDef::query); exactly one of the two must be set
1907    /// (enforced by [`GroupDef::validate`]).
1908    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1909    pub members: Vec<String>,
1910    /// Dynamic membership — a read-only `SELECT`/`WITH` returning a `pc_id`
1911    /// column. Mutually exclusive with [`members`](GroupDef::members). The
1912    /// backend validates it read-only at `group create` and again at run time;
1913    /// a write verb / stacked statement is rejected. Empty string is treated
1914    /// as unset so an operator can comment the body out to switch to
1915    /// `members:` without dropping the key.
1916    #[serde(default, skip_serializing_if = "Option::is_none")]
1917    pub query: Option<String>,
1918    /// Membership-recompute cadence for a dynamic group as a humantime
1919    /// duration (`"30m"`, `"6h"`). Absent ⇒ [`DEFAULT_GROUP_REFRESH`]. Ignored
1920    /// for a static group.
1921    #[serde(default, skip_serializing_if = "Option::is_none")]
1922    pub refresh: Option<String>,
1923    /// Free-form operator taxonomy (same role as [`Manifest::tags`]).
1924    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1925    pub tags: Vec<String>,
1926    /// GitOps provenance (#678), stamped by `kanade group def create` from the
1927    /// source YAML's Git context — same as [`View::origin`].
1928    #[serde(default, skip_serializing_if = "Option::is_none")]
1929    pub origin: Option<RepoOrigin>,
1930}
1931
1932impl GroupDef {
1933    /// The dynamic SQL body if this is a dynamic group — a non-blank `query`.
1934    /// (An empty-string `query` reads as unset, mirroring [`Execute::script`].)
1935    pub fn dynamic_query(&self) -> Option<&str> {
1936        self.query
1937            .as_deref()
1938            .map(str::trim)
1939            .filter(|q| !q.is_empty())
1940    }
1941
1942    /// The effective recompute cadence for a dynamic group — the parsed
1943    /// `refresh` or [`DEFAULT_GROUP_REFRESH`]. Falls back to the default on an
1944    /// unparseable value rather than panicking on the read path (validation
1945    /// already rejected a bad value at create time).
1946    pub fn refresh_interval(&self) -> std::time::Duration {
1947        self.refresh
1948            .as_deref()
1949            .and_then(|s| humantime::parse_duration(s).ok())
1950            .unwrap_or(DEFAULT_GROUP_REFRESH)
1951    }
1952
1953    pub fn validate(&self) -> Result<(), String> {
1954        // Validate the id EXACTLY as stored — no `.trim()`. The id is used
1955        // verbatim as the KV key (`group_defs::create` does `kv.put(&group.id,
1956        // …)`) and as the name a schedule's `target.groups` matches, so a
1957        // padded id like `" clients "` that validated as its trimmed form but
1958        // was stored raw would silently never match. The charset excludes
1959        // whitespace, so checking the untrimmed id rejects such an id outright.
1960        if !is_valid_resource_id(&self.id) {
1961            return Err(
1962                "group.id must be non-empty and only [A-Za-z0-9._-] (it's a KV key + URL segment; \
1963                 no surrounding whitespace)"
1964                    .to_string(),
1965            );
1966        }
1967        // Exactly one of members / query. A blank `query` counts as unset so
1968        // the "comment the body out" workflow lands on the members branch
1969        // rather than a confusing "both set" error.
1970        let has_members = !self.members.is_empty();
1971        let has_query = self.dynamic_query().is_some();
1972        match (has_members, has_query) {
1973            (false, false) => {
1974                return Err(
1975                    "group must declare either a static `members:` list or a dynamic `query:`"
1976                        .to_string(),
1977                );
1978            }
1979            (true, true) => {
1980                return Err(
1981                    "`members:` and `query:` are mutually exclusive — a group is either static or dynamic"
1982                        .to_string(),
1983                );
1984            }
1985            _ => {}
1986        }
1987        for m in &self.members {
1988            if m.trim().is_empty() {
1989                return Err("members must not contain empty entries".to_string());
1990            }
1991        }
1992        // A dynamic group's refresh must parse (a static group ignores it, but
1993        // reject a bad value either way so a later members→query switch can't
1994        // surprise the operator).
1995        if let Some(r) = &self.refresh
1996            && humantime::parse_duration(r).is_err()
1997        {
1998            return Err(format!(
1999                "group.refresh '{r}' is not a valid duration (e.g. '30m', '6h')"
2000            ));
2001        }
2002        for tag in &self.tags {
2003            if tag.trim().is_empty() {
2004                return Err("tags must not contain empty entries".to_string());
2005            }
2006        }
2007        Ok(())
2008    }
2009}
2010
2011/// Issue #246 — `emit:` manifest block for jobs whose stdout is
2012/// NDJSON observability events (one `ObsEvent` per line). Parallel
2013/// to `inventory:` but for the append-only timeline pipeline; see
2014/// `Manifest::emit` for the full contract.
2015#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2016pub struct EmitConfig {
2017    /// What kind of payload the agent should expect on stdout. Only
2018    /// `events` is defined today (parses each non-empty line as
2019    /// `ObsEvent` and publishes on `obs.<pc_id>`); future variants
2020    /// (e.g. metrics streams, structured trace events) plug in here.
2021    #[serde(rename = "type")]
2022    pub kind: EmitKind,
2023    /// Operator hint for where the script keeps its own state — the
2024    /// watermark file the PowerShell / sh body reads + writes
2025    /// between runs so it only emits NEW events since the last
2026    /// poll. The agent doesn't read this; it's documentation that
2027    /// the SPA (and `kanade job edit`) can surface to operators
2028    /// reviewing the manifest. Optional; the script is allowed to
2029    /// keep state anywhere (registry, env, etc.) — the field's
2030    /// presence makes the convention discoverable.
2031    #[serde(default, skip_serializing_if = "Option::is_none")]
2032    pub watermark_path: Option<String>,
2033}
2034
2035/// `emit.type` enum. Lowercase serde so manifests read
2036/// `type: events` rather than `Events`.
2037#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
2038#[serde(rename_all = "lowercase")]
2039pub enum EmitKind {
2040    /// Per-line `ObsEvent` JSON. Agent parses + publishes on
2041    /// `obs.<pc_id>`, drops the stdout from the resulting
2042    /// `ExecResult`.
2043    Events,
2044}
2045
2046/// v0.31 / #40: declarative "flatten this JSON array into a real
2047/// SQLite table" spec on an inventory manifest. The projector
2048/// creates the table on first registration (CREATE TABLE IF NOT
2049/// EXISTS + indexes) and writes a row per element of
2050/// `payload[field]` on every result, scoped by (pc_id, job_id) so
2051/// each PC's rows replace cleanly without a per-PC schema.
2052#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2053pub struct ExplodeSpec {
2054    /// JSON array key under the payload to explode. E.g. `"apps"`
2055    /// for `payload: { apps: [{...}, {...}] }`.
2056    pub field: String,
2057    /// Derived SQLite table name. Operators choose this — pick
2058    /// something namespaced + stable (`inventory_sw_apps`, not
2059    /// `apps`) so multiple inventory manifests don't collide on a
2060    /// generic name.
2061    pub table: String,
2062    /// Element-level fields that uniquely identify a row inside one
2063    /// PC's payload. The full PK is `(pc_id, job_id) + these
2064    /// columns`. Required — operators must think about uniqueness
2065    /// (e.g. `["name", "source"]` for installed apps because the
2066    /// same name appears in multiple uninstall hives).
2067    ///
2068    /// v0.31 / #41: same tuple drives history identity. When
2069    /// `track_history` is on, the projector serialises these
2070    /// fields' values into `inventory_history.identity_json` for
2071    /// every change event, so queries like "every PC that ever
2072    /// installed Chrome (any source)" filter on identity_json
2073    /// content without a per-manifest schema.
2074    pub primary_key: Vec<String>,
2075    /// Per-element fields that become columns in the derived table.
2076    pub columns: Vec<ExplodeColumn>,
2077    /// v0.31 / #41: when true (default false), the projector
2078    /// diffs each PC's incoming payload against the prior rows
2079    /// for the same (pc_id, job_id) BEFORE the DELETE-then-INSERT
2080    /// replace, and writes added / removed / changed events into
2081    /// `inventory_history`. Lets operators answer time-dimension
2082    /// questions ("when did Chrome 120 first appear on PC X?",
2083    /// "what's the Win 11 23H2 rollout curve") without storing
2084    /// per-scan snapshots. Off by default so operators opt in
2085    /// per-spec — history has a real storage cost on long-lived
2086    /// deployments (mitigated by the 90-day default retention
2087    /// sweeper, see `cleanup` module).
2088    #[serde(default)]
2089    pub track_history: bool,
2090}
2091
2092/// One column in an [`ExplodeSpec`]'s derived table.
2093#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2094pub struct ExplodeColumn {
2095    /// JSON key under each array element. Becomes the column name
2096    /// in the derived SQLite table — we don't rename.
2097    pub field: String,
2098    /// SQLite affinity: `"text"` (default), `"integer"`, `"real"`.
2099    /// Storage maps directly via `sqlx::query.bind(...)`; type
2100    /// mismatches at INSERT-time fail loudly rather than silently
2101    /// dropping the row.
2102    #[serde(default, skip_serializing_if = "Option::is_none")]
2103    #[serde(rename = "type")]
2104    pub kind: Option<String>,
2105    /// When true, the projector creates a `CREATE INDEX` on this
2106    /// column at table-creation time. Boost for the common-filter
2107    /// columns (`name`, `version`) — operators mark them
2108    /// explicitly, the projector won't guess.
2109    #[serde(default)]
2110    pub index: bool,
2111}
2112
2113/// #vuln-roadmap: one declarative **external-data feed** on a `feed:`
2114/// manifest — see [`Manifest::feed`]. Unlike inventory [`ExplodeSpec`]
2115/// (keyed per `(pc_id, job_id)`), a feed is GLOBAL fleet-wide reference
2116/// data: the controller-tier job's script fetches + shapes it, prints the
2117/// array under [`field`](FeedSpec::field) inside a `#KANADE-FEED-BEGIN/END`
2118/// fence, and the projector REPLACES that feed's rows wholesale in the
2119/// shared `feeds` table keyed `(feed_id, item_id)`. The full element JSON
2120/// lands in a `data` column, so a `view:` SQL `json_extract`s whatever
2121/// shape the feed carries — no per-feed schema, no dynamic DDL. One
2122/// manifest may declare several feeds.
2123#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2124pub struct FeedSpec {
2125    /// Stable feed identifier — the `feed_id` partition in the shared
2126    /// `feeds` table. Operators choose this; namespace it (`cisa-kev`,
2127    /// `endoflife-windows`) so feeds don't collide. A new result for the
2128    /// same id replaces that partition wholesale.
2129    pub id: String,
2130    /// JSON array key under the (fenced) payload to ingest. E.g.
2131    /// `"vulnerabilities"` for `{ vulnerabilities: [{...}, {...}] }`.
2132    pub field: String,
2133    /// Element-level field(s) whose values uniquely identify an item
2134    /// within the feed — they form the `item_id` key (joined for a
2135    /// composite key). Required: operators must think about uniqueness
2136    /// (e.g. `["cveID"]` for CISA KEV). An element missing any of these is
2137    /// skipped (it has no stable identity).
2138    pub primary_key: Vec<String>,
2139}
2140
2141#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2142pub struct DisplayField {
2143    /// Top-level key in the stdout JSON.
2144    pub field: String,
2145    /// Human-readable column header.
2146    pub label: String,
2147    /// Optional render hint — `"number"`, `"bytes"`, `"timestamp"`,
2148    /// or `"table"` (#39). Defaults to plain text rendering on the
2149    /// SPA side. `"table"` expects the field's value to be a JSON
2150    /// array of objects and renders a nested sub-table on the
2151    /// per-PC detail page using `columns` as the schema; the fleet
2152    /// summary view falls back to showing the row count for
2153    /// `"table"` cells so the wide list stays compact.
2154    #[serde(default, skip_serializing_if = "Option::is_none")]
2155    #[serde(rename = "type")]
2156    pub kind: Option<String>,
2157    /// v0.30 / #39: when `kind == "table"`, the SPA renders the
2158    /// field's value (an array of objects like
2159    /// `disks: [{ device_id, size_bytes, ... }]`) as a nested
2160    /// sub-table using these columns. Each column is itself a
2161    /// `DisplayField`, so the nested cells reuse the same render
2162    /// hints (`bytes`, `number`, `timestamp`) — no parallel format
2163    /// pipeline. Ignored for any other `kind`.
2164    #[serde(default, skip_serializing_if = "Option::is_none")]
2165    pub columns: Option<Vec<DisplayField>>,
2166}
2167
2168#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2169pub struct Rollout {
2170    #[serde(default)]
2171    pub strategy: RolloutStrategy,
2172    pub waves: Vec<Wave>,
2173}
2174
2175#[derive(
2176    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
2177)]
2178#[serde(rename_all = "lowercase")]
2179pub enum RolloutStrategy {
2180    #[default]
2181    Wave,
2182}
2183
2184#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2185pub struct Wave {
2186    pub group: String,
2187    /// humantime delay measured from the deploy's publish time. wave[0]
2188    /// typically has "0s"; subsequent waves use minutes / hours.
2189    pub delay: String,
2190}
2191
2192#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default)]
2193pub struct Target {
2194    #[serde(default)]
2195    pub groups: Vec<String>,
2196    #[serde(default)]
2197    pub pcs: Vec<String>,
2198    #[serde(default)]
2199    pub all: bool,
2200}
2201
2202impl Target {
2203    /// At least one of all / groups / pcs is set.
2204    pub fn is_specified(&self) -> bool {
2205        self.all || !self.groups.is_empty() || !self.pcs.is_empty()
2206    }
2207
2208    /// Whether a PC (its `pc_id` + group membership) falls in this target:
2209    /// `all`, or the pc is listed, or it belongs to a listed group. Used
2210    /// by the agent to scope `client.visible_to` (#816). An unspecified
2211    /// target matches nobody (callers should treat "no target" as
2212    /// "visible to all" before calling this).
2213    pub fn matches(&self, pc_id: &str, groups: &[String]) -> bool {
2214        self.all
2215            || self.pcs.iter().any(|p| p == pc_id)
2216            || self.groups.iter().any(|g| groups.contains(g))
2217    }
2218}
2219
2220#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2221pub struct Execute {
2222    pub shell: ExecuteShell,
2223    /// Inline script body. Mutually exclusive with [`script_file`]
2224    /// and [`script_object`]; exactly one of the three must be set
2225    /// (enforced by [`Execute::validate_script_source`] at the
2226    /// write-side parse boundaries — `kanade job create` and
2227    /// `POST /api/jobs`).
2228    ///
2229    /// Empty string is treated as **unset** so operators can swap
2230    /// to a `script_file:` / `script_object:` alternative just by
2231    /// commenting out the body, without having to also drop the
2232    /// `script:` key entirely.
2233    ///
2234    /// [`script_file`]: Self::script_file
2235    /// [`script_object`]: Self::script_object
2236    #[serde(default, skip_serializing_if = "Option::is_none")]
2237    pub script: Option<String>,
2238    /// Repo-local file path resolved by the operator-side CLI at
2239    /// `kanade job create` time. The CLI reads the file, slots its
2240    /// contents into `script`, and clears this field before
2241    /// POSTing — so the backend / agents never see `script_file`
2242    /// in stored manifests. SPEC §2.4.1.
2243    ///
2244    /// The resolver shipped with #210: `kanade job create` /
2245    /// `kanade job validate` inline this field end-to-end. Because
2246    /// resolution is CLI-side (it needs the operator's filesystem),
2247    /// `POST /api/jobs` rejects a manifest that still carries it
2248    /// (#918) — a stored `script_file` job would 400 at every exec.
2249    /// Inline the script or use `script_object` when writing through
2250    /// the API / SPA editor.
2251    #[serde(default, skip_serializing_if = "Option::is_none")]
2252    pub script_file: Option<String>,
2253    /// Object Store reference (`<name>/<version>`) into the
2254    /// `scripts` bucket (`OBJECT_SCRIPTS`). Agents fetch the body
2255    /// at Execute time via `/api/script-objects/{name}/{version}`
2256    /// and cache it locally. SPEC §2.4.1.
2257    ///
2258    /// Fully wired (#210/#211): the backend resolves the digest at
2259    /// exec submission (`api::exec::resolve_script_source`), the agent
2260    /// fetches + sha-verifies + caches the body (`script_cache`), and
2261    /// `kanade script` CRUDs the store. Unlike `script_file:` (inlined
2262    /// CLI-side, git-managed), this keeps the body in versioned,
2263    /// digest-pinned object storage — the ops-managed counterpart.
2264    #[serde(default, skip_serializing_if = "Option::is_none")]
2265    pub script_object: Option<String>,
2266    /// humantime duration string (e.g. "30s", "10m"). Script-intrinsic
2267    /// — represents how long this script reasonably takes to run.
2268    pub timeout: String,
2269    /// Token + session combination the agent uses to launch the
2270    /// script (v0.21). Default = [`RunAs::System`] (Session 0,
2271    /// LocalSystem privileges, no GUI) — matches pre-v0.21 behavior.
2272    #[serde(default)]
2273    pub run_as: RunAs,
2274    /// Working directory for the spawned child (v0.21.1). When
2275    /// unset, the child inherits the agent's cwd — on Windows that
2276    /// means `%SystemRoot%\System32` for the prod service, which is
2277    /// almost never what operators actually want. Use an absolute
2278    /// path; relative paths are passed through to the OS verbatim.
2279    /// `%PROGRAMDATA%` works for `run_as: system`; for `run_as: user`
2280    /// you'd want `%USERPROFILE%` (but expansion happens in the
2281    /// shell, so write `$env:USERPROFILE` for PowerShell, or set
2282    /// it via teravars before `kanade job create`).
2283    #[serde(default, skip_serializing_if = "Option::is_none")]
2284    pub cwd: Option<String>,
2285}
2286
2287impl Execute {
2288    /// Treat an empty — or whitespace-only (#918) — `script:` body as
2289    /// "intentionally unset". Operators commenting out a block-scalar
2290    /// tend to leave the key behind, and failing the validator on
2291    /// `script: ""` would surprise them; a body of blank lines can't
2292    /// be a real script either, only a commented-out one, and letting
2293    /// it count as "set" shipped a validated do-nothing job.
2294    fn has_inline_script(&self) -> bool {
2295        matches!(&self.script, Some(s) if !s.trim().is_empty())
2296    }
2297
2298    /// Enforce that exactly one of `script` / `script_file` /
2299    /// `script_object` is set. Called at the write-side parse
2300    /// boundaries (CLI `kanade job create` + backend
2301    /// `POST /api/jobs`) so ambiguous YAML is rejected before it
2302    /// reaches the JOBS KV. Read paths (projector, agent
2303    /// scheduler, list endpoints) skip this check — they only ever
2304    /// see what the write path already validated.
2305    pub fn validate_script_source(&self) -> Result<(), String> {
2306        // #918: a blank-but-present alternate source is a typo, not a
2307        // choice — `script_file: ""` used to count as "set", pass the
2308        // exactly-one check, and only fail at use time (the CLI reads
2309        // a file named ""; a stored blank script_object 404s on every
2310        // exec). Reject it with the field named. Inline `script` keeps
2311        // its documented empty-means-unset semantics instead — see
2312        // `has_inline_script`.
2313        if matches!(&self.script_file, Some(s) if s.trim().is_empty()) {
2314            return Err(
2315                "execute.script_file must not be blank when set (drop the key to use \
2316                 another source)"
2317                    .into(),
2318            );
2319        }
2320        if matches!(&self.script_object, Some(s) if s.trim().is_empty()) {
2321            return Err(
2322                "execute.script_object must not be blank when set (drop the key to use \
2323                 another source)"
2324                    .into(),
2325            );
2326        }
2327        let inline = self.has_inline_script();
2328        let file = self.script_file.is_some();
2329        let obj = self.script_object.is_some();
2330        let set = [inline, file, obj].into_iter().filter(|b| *b).count();
2331        match set {
2332            1 => {}
2333            0 => {
2334                return Err(
2335                    "execute: one of `script`, `script_file`, `script_object` must be set".into(),
2336                );
2337            }
2338            _ => {
2339                return Err(format!(
2340                    "execute: only one of `script` / `script_file` / `script_object` may be set \
2341                     (got script={inline}, script_file={file}, script_object={obj})"
2342                ));
2343            }
2344        }
2345        // #918: a script_object ref is `<name>/<version>` — the agent
2346        // fetches the body via `/api/script-objects/{name}/{version}`
2347        // and the backend uses the ref *verbatim* as the Object Store
2348        // key (`resolve_script_source`), so each half must be a
2349        // well-formed resource id: exactly one slash, and both halves
2350        // [A-Za-z0-9._-]. `is_valid_resource_id` also rejects a half
2351        // that's blank OR merely whitespace-padded (`"foo/bar "`) —
2352        // padding survives a JSON POST body (unlike a YAML plain
2353        // scalar) and would 404 on every exec (gemini/claude #943).
2354        if let Some(obj_ref) = self.script_object.as_deref() {
2355            let parts: Vec<&str> = obj_ref.split('/').collect();
2356            if parts.len() != 2 || parts.iter().any(|p| !is_valid_resource_id(p)) {
2357                return Err(format!(
2358                    "execute.script_object must be `<name>/<version>` with each half \
2359                     [A-Za-z0-9._-] (got '{obj_ref}'); publish bodies with \
2360                     `kanade script publish <name> <version>`"
2361                ));
2362            }
2363        }
2364        Ok(())
2365    }
2366}
2367
2368/// Job-generic post-step hook (see [`Manifest::finalize`]). Runs after
2369/// the main `execute:` script (and the collect upload) on a clean exit,
2370/// with the step's structured result injected via an environment
2371/// variable. P1 supports an inline `script:` only — `script_file:` /
2372/// `script_object:` are follow-ups.
2373#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2374pub struct FinalizeSpec {
2375    pub shell: ExecuteShell,
2376    /// Inline script body (required; inline-only in P1).
2377    pub script: String,
2378    /// humantime duration string (e.g. `"60s"`, `"5m"`). Defaults to
2379    /// `60s` when unset.
2380    #[serde(default = "default_finalize_timeout")]
2381    pub timeout: String,
2382    /// Token + session combination, like [`Execute::run_as`]. Defaults
2383    /// to [`RunAs::System`].
2384    #[serde(default)]
2385    pub run_as: RunAs,
2386    /// Working directory for the hook child, like [`Execute::cwd`].
2387    #[serde(default, skip_serializing_if = "Option::is_none")]
2388    pub cwd: Option<String>,
2389    /// #965: for a `collect:` job, run this hook once per uploaded
2390    /// bundle (with a single-bundle `KANADE_COLLECT_RESULT`) as each
2391    /// bundle uploads, instead of once after the whole set. Lets an
2392    /// interrupted collect still clean up the days it managed to
2393    /// upload (partial progress sticks), breaking the
2394    /// offline-before-finalize backlog spiral.
2395    ///
2396    /// **Opt-in** (default `false` = one call after all bundles, the
2397    /// established contract) because per-bundle changes the hook's
2398    /// payload (all → one) and invocation count (1 → N), which would
2399    /// break a hook written for the all-at-once assumption (cross-bundle
2400    /// aggregation, once-only side effects, all-or-nothing). Only valid
2401    /// with a `collect:` hint — [`Manifest::validate`] rejects it
2402    /// otherwise, since a non-collect finalize has no bundles to iterate.
2403    #[serde(default)]
2404    pub on_each_bundle: bool,
2405}
2406
2407/// Default `finalize.timeout` when the operator omits it.
2408fn default_finalize_timeout() -> String {
2409    "60s".to_string()
2410}
2411
2412impl FinalizeSpec {
2413    /// Lower to the wire form forwarded onto a [`Command`]. The timeout
2414    /// parse falls back to 60s — [`Manifest::validate`] already rejects
2415    /// an unparseable value at create time, so the fire path uses a safe
2416    /// default rather than failing (mirrors
2417    /// [`CollectHint::max_size_bytes`]). A sub-second timeout floors at
2418    /// 1s for the same reason `build_command` does.
2419    pub fn lower(&self) -> FinalizeCommand {
2420        let timeout_secs = humantime::parse_duration(&self.timeout)
2421            .map(|d| d.as_secs().max(1))
2422            .unwrap_or(60);
2423        FinalizeCommand {
2424            shell: self.shell.into(),
2425            script: self.script.clone(),
2426            timeout_secs,
2427            run_as: self.run_as,
2428            cwd: self.cwd.clone(),
2429            on_each_bundle: self.on_each_bundle,
2430        }
2431    }
2432}
2433
2434impl Manifest {
2435    /// Cross-field semantic checks that don't fit into pure serde
2436    /// derive. Currently delegates to
2437    /// [`Execute::validate_script_source`] — see that method's
2438    /// docs for the rationale on which call sites should run this.
2439    pub fn validate(&self) -> Result<(), String> {
2440        self.execute.validate_script_source()?;
2441        // Fail CLOSED on an unrecognised execution tier. `#[serde(other)]`
2442        // turns a typo (`tier: controler`) or a future tier into
2443        // `Tier::Unknown`; without this check the controller gate would
2444        // fall back to normal endpoint dispatch, so an operator who *meant*
2445        // to confine a job to the controller tier would silently get
2446        // fleet-wide dispatch (CodeRabbit #905). Rejecting it at the write
2447        // boundary surfaces the typo at `job create`, and — since
2448        // `exec_manifest` re-validates — a hand-poked KV manifest can't slip
2449        // a controller-tier job onto endpoints either.
2450        if matches!(self.tier, Some(Tier::Unknown)) {
2451            return Err(
2452                "tier: unrecognised execution tier — use `endpoint` or `controller` \
2453                 (this is a typo, or a tier a newer kanade supports that this backend does not)"
2454                    .to_string(),
2455            );
2456        }
2457        // #vuln-roadmap: a `feed:` spec drives the global `feeds`
2458        // projection. id / item_id are stored as *values* (the `feeds`
2459        // table is fixed-schema — no identifier splicing), but blank
2460        // values are silent projection bugs: a blank id collides every
2461        // feed under "", a blank field never matches the payload array,
2462        // and an empty primary_key yields no item_id (every row dropped).
2463        // Reject them at the write boundary so `kanade job create` surfaces
2464        // the typo instead of producing an empty/garbled feed at run time.
2465        let mut seen_feed_ids: Vec<&str> = Vec::new();
2466        for spec in &self.feed {
2467            let id = spec.id.trim();
2468            if id.is_empty() {
2469                return Err("feed.id must not be empty".to_string());
2470            }
2471            if spec.field.trim().is_empty() {
2472                return Err(format!("feed '{id}' field must not be empty"));
2473            }
2474            if spec.primary_key.is_empty() {
2475                return Err(format!("feed '{id}' needs at least one primary_key field"));
2476            }
2477            if spec.primary_key.iter().any(|k| k.trim().is_empty()) {
2478                return Err(format!(
2479                    "feed '{id}' primary_key must not contain blank entries"
2480                ));
2481            }
2482            // Two specs sharing an id both target the same `feeds`
2483            // partition and would clobber each other on every run —
2484            // reject the ambiguity rather than let last-write-wins.
2485            if seen_feed_ids.contains(&id) {
2486                return Err(format!("feed id '{id}' is declared more than once"));
2487            }
2488            seen_feed_ids.push(id);
2489        }
2490        // A `feed:` job fetches external data and MUST run on the trusted
2491        // controller tier — the dispatch guard (`requires_controller`) treats
2492        // a non-empty `feed:` as implying `controller`. An explicit
2493        // `tier: endpoint` contradicts that intent; reject it rather than
2494        // silently overriding, so the operator can't believe a feed runs on
2495        // endpoints. Omitting `tier:` (the default) is fine — the implication
2496        // confines it; `tier: controller` is the redundant-but-explicit form.
2497        if !self.feed.is_empty() && matches!(self.tier, Some(Tier::Endpoint)) {
2498            return Err(
2499                "feed: requires the controller tier — remove `tier: endpoint` (a feed: job \
2500                 fetches external data and is confined to the controller_group)"
2501                    .to_string(),
2502            );
2503        }
2504        // A present-but-empty finalize script is an invisible no-op
2505        // (the hook would run an empty body); reject it at the write
2506        // boundary. Inline-only in P1, so `script` is the sole source.
2507        if let Some(finalize) = &self.finalize {
2508            if finalize.script.trim().is_empty() {
2509                return Err("finalize.script must not be empty".to_string());
2510            }
2511            // Reject an unparseable timeout at the write boundary so the
2512            // operator sees the error at `job create` rather than getting
2513            // a silent fire-time fallback (`FinalizeSpec::lower` floors to
2514            // 60s, which would otherwise mask a typo).
2515            if humantime::parse_duration(&finalize.timeout).is_err() {
2516                return Err(format!(
2517                    "finalize.timeout '{}' is not a valid duration",
2518                    finalize.timeout
2519                ));
2520            }
2521            // Disallow cmd for finalize: the agent injects the result JSON
2522            // into the hook's environment, and cmd.exe quoting doesn't
2523            // nest — JSON's `"` plus shell metacharacters in a collected
2524            // path/key could break out into command injection at the
2525            // agent's (often LocalSystem) privilege. PowerShell's
2526            // single-quote escaping is safe, and finalize hooks are
2527            // PowerShell by convention anyway.
2528            // `sh` is rejected for the same injection reason (its
2529            // single-word quoting doesn't nest around the JSON result
2530            // either), and additionally because the injected prelude is
2531            // PowerShell syntax (`$env:KANADE_COLLECT_RESULT = '...'`) —
2532            // it would be malformed in a POSIX shell. `pwsh` IS allowed:
2533            // it's PowerShell, so the prelude + single-quote escaping are
2534            // valid and safe.
2535            if matches!(finalize.shell, ExecuteShell::Cmd | ExecuteShell::Sh) {
2536                return Err(
2537                    "finalize.shell: cmd and sh are not supported for finalize hooks \
2538                     (shell-injection risk when the result JSON is injected, and the injected \
2539                     prelude is PowerShell syntax); use powershell or pwsh"
2540                        .to_string(),
2541                );
2542            }
2543            // #965: per-bundle finalize only means anything for a
2544            // collect: job — a non-collect finalize has no bundles to
2545            // iterate (it runs once after the script). Reject the
2546            // combination at the write boundary so a confused operator
2547            // is told rather than silently getting a no-op.
2548            if finalize.on_each_bundle && self.collect.is_none() {
2549                return Err(
2550                    "finalize.on_each_bundle: true requires a collect: hint — a non-collect \
2551                     finalize has no bundles to iterate (it runs once after the script)"
2552                        .to_string(),
2553                );
2554            }
2555        }
2556        // Stdout-format compatibility (#821). `inventory:` / `check:` /
2557        // `collect:` now COMPOSE: each reads its own `#KANADE-<KIND>-
2558        // BEGIN/END`-fenced JSON block from stdout, so a single job can
2559        // project inventory facts, drive a Health-tab check, AND collect
2560        // files in one run. (A single-hint job may still skip the fence;
2561        // a multi-hint job must fence each block.)
2562        //
2563        // `emit:` remains the exception — its stdout is line-delimited
2564        // NDJSON consumed whole and then omitted from the result — so it
2565        // can't share stdout with any fenced hint. `feed:` is another fenced
2566        // stdout consumer (`#KANADE-FEED`), so it belongs in this exclusion
2567        // too: with `emit:` present the projector never sees the feed's fence
2568        // (CodeRabbit).
2569        if self.emit.is_some()
2570            && (self.inventory.is_some()
2571                || self.check.is_some()
2572                || self.collect.is_some()
2573                || !self.feed.is_empty())
2574        {
2575            return Err(
2576                "`emit:` is incompatible with `inventory:` / `check:` / `collect:` / `feed:` — \
2577                 emit's stdout is NDJSON timeline events (consumed whole and omitted from the \
2578                 result), while the others read fenced JSON blocks from stdout"
2579                    .to_string(),
2580            );
2581        }
2582        // A check's `name` is the Health-tab row id (React key); the
2583        // field names tell the agent where to read status/detail.
2584        // An empty value is an invisible runtime bug, and the serde
2585        // defaults don't guard an operator who writes `status_field:
2586        // ""` explicitly — reject all three here.
2587        if let Some(check) = &self.check {
2588            for (label, value) in [
2589                ("check.name", &check.name),
2590                ("check.status_field", &check.status_field),
2591                ("check.detail_field", &check.detail_field),
2592            ] {
2593                if value.trim().is_empty() {
2594                    return Err(format!("{label} must not be empty"));
2595                }
2596            }
2597            // A present-but-blank `troubleshoot` is a broken
2598            // remediation job id (the "修復する" button would target
2599            // an empty manifest id) — reject it too.
2600            if let Some(troubleshoot) = &check.troubleshoot {
2601                if troubleshoot.trim().is_empty() {
2602                    return Err("check.troubleshoot must not be empty when set".to_string());
2603                }
2604            }
2605            // A present-but-blank `label` would render an empty row
2606            // title on the Health tab / Compliance page — reject it so
2607            // the slug fallback only ever kicks in when label is absent.
2608            if let Some(label) = &check.label {
2609                if label.trim().is_empty() {
2610                    return Err("check.label must not be empty when set".to_string());
2611                }
2612            }
2613            if let Some(alert) = &check.alert {
2614                // An alert that names no recipient is a silent no-op.
2615                if !alert.notify_user && alert.notify_groups.is_empty() {
2616                    return Err("check.alert must set notify_user and/or notify_groups".to_string());
2617                }
2618                if alert.title.trim().is_empty() {
2619                    return Err("check.alert.title must not be empty".to_string());
2620                }
2621                // `on: []` would never fire; an empty group name resolves to
2622                // a malformed `notifications.group.` subject.
2623                if alert.on.is_empty() {
2624                    return Err("check.alert.on must list at least one status".to_string());
2625                }
2626                if alert.notify_groups.iter().any(|g| g.trim().is_empty()) {
2627                    return Err("check.alert.notify_groups must not contain blanks".to_string());
2628                }
2629                // Email is addressed via group_contacts (group → email), so
2630                // there must be a group to map. notify_user has no email.
2631                if alert.email && alert.notify_groups.is_empty() {
2632                    return Err(
2633                        "check.alert.email requires notify_groups (email is addressed per group, not per user)"
2634                            .to_string(),
2635                    );
2636                }
2637                // The alert rides the `check_status` projection, which only
2638                // runs for `fleet: true`.
2639                if !check.fleet {
2640                    return Err(
2641                        "check.alert requires fleet: true (the alert rides the compliance projection)"
2642                            .to_string(),
2643                    );
2644                }
2645            }
2646        }
2647        // #291: a `client:` job is rendered in the Client App's
2648        // catalog (`jobs.list` → `jobs.execute`). serde already makes
2649        // `name` + `category` required at parse time; the only gap is
2650        // a present-but-blank `name`, which would render an empty row
2651        // title — reject it like the other display-id fields.
2652        if let Some(client) = &self.client {
2653            if client.name.trim().is_empty() {
2654                return Err("client.name must not be empty".to_string());
2655            }
2656            // #792: category is a free-form key now, so a blank one would
2657            // group the job under an empty tab — reject it like `name`.
2658            if client.category.trim().is_empty() {
2659                return Err("client.category must not be empty".to_string());
2660            }
2661            // Optional display fields, when present, must be
2662            // meaningful: a blank `description` renders an empty
2663            // subtitle and a blank `icon` is a dangling lucide name.
2664            // Same present-but-blank guard the `check:` block applies
2665            // to its optional `troubleshoot` id.
2666            for (label, value) in [
2667                ("client.description", &client.description),
2668                ("client.icon", &client.icon),
2669                ("client.category_label", &client.category_label),
2670                ("client.category_icon", &client.category_icon),
2671            ] {
2672                if let Some(v) = value {
2673                    if v.trim().is_empty() {
2674                        return Err(format!("{label} must not be empty when set"));
2675                    }
2676                }
2677            }
2678            // #816: a present-but-empty `visible_to` (no all/groups/pcs)
2679            // would hide the job from everyone in the Client App — almost
2680            // certainly a mistake. Require at least one selector; omit the
2681            // whole block to mean "visible to all".
2682            if let Some(t) = &client.visible_to {
2683                if !t.is_specified() {
2684                    return Err(
2685                        "client.visible_to must set at least one of all / groups / pcs (omit it for all PCs)"
2686                            .to_string(),
2687                    );
2688                }
2689            }
2690            // show_when: a dynamic display gate keyed on a check result. A
2691            // malformed check slug matches nothing and an empty status list
2692            // matches nothing — both would silently hide the job forever,
2693            // so reject them at create time rather than at a confused
2694            // "why isn't my job showing?" later. The slug must be a clean
2695            // resource id (same charset checks/jobs use): a typo with spaces
2696            // or punctuation can never match a real check name, so catch it
2697            // here instead of failing closed at runtime. (Whether the slug
2698            // names a check that actually EXISTS can't be checked here —
2699            // checks are keyed by name across manifests — so a valid-but-
2700            // unknown slug stays a runtime miss = hidden, the documented
2701            // fail-closed behavior.)
2702            if let Some(sw) = &client.show_when {
2703                if !is_valid_resource_id(sw.check.trim()) {
2704                    return Err(
2705                        "client.show_when.check must be a non-empty check slug ([A-Za-z0-9._-])"
2706                            .to_string(),
2707                    );
2708                }
2709                if sw.is.is_empty() {
2710                    return Err(
2711                        "client.show_when.is must list at least one check status".to_string()
2712                    );
2713                }
2714            }
2715            // confirm: a present-but-blank custom message would render an
2716            // empty dialog title — reject it like the other display fields.
2717            // (A `confirm: false` / `enabled: false` with no message is fine:
2718            // the dialog is suppressed, so there's nothing to render.)
2719            if let Some(c) = &client.confirm {
2720                if let Some(msg) = &c.message {
2721                    if msg.trim().is_empty() {
2722                        return Err("client.confirm.message must not be empty when set".to_string());
2723                    }
2724                }
2725            }
2726            // unlock: the scope slug is matched byte-for-byte against the
2727            // operator's configured `support_codes[].scope`, so a slug with
2728            // stray whitespace / punctuation can never match one — and
2729            // because the gate fails closed, the job would simply be
2730            // invisible forever with no error anywhere. Reject it at create
2731            // time. (Whether a code is actually CONFIGURED for the scope
2732            // can't be checked here — that lives in server settings, not the
2733            // manifest — so an unconfigured scope stays a runtime miss =
2734            // hidden.)
2735            //
2736            // Validated EXACTLY AS STORED — no `.trim()`, the same no-trim
2737            // rule `View::validate` / `AgentGroup::validate` spell out. The
2738            // backend trims a support code's scope before storing it, so a
2739            // padded manifest scope that validated as its trimmed form but
2740            // was stored raw would pass this check and then never match a
2741            // code — precisely the silent-forever-hidden failure this guard
2742            // exists to prevent.
2743            if let Some(scope) = &client.unlock {
2744                if !is_valid_resource_id(scope) {
2745                    return Err(
2746                        "client.unlock must be a non-empty unlock scope slug ([A-Za-z0-9._-]) \
2747                         with no surrounding whitespace"
2748                            .to_string(),
2749                    );
2750                }
2751            }
2752        }
2753        // #219: a `collect:` job's `name` heads the bundle on the SPA
2754        // Collect page (and the Client App row when paired with
2755        // `client:`), `files_field` tells the agent where to read the
2756        // path list, and `max_size` must be a parseable size so a typo
2757        // is caught at create time rather than silently capping the
2758        // bundle at the default on the fire path.
2759        if let Some(collect) = &self.collect {
2760            if collect.name.trim().is_empty() {
2761                return Err("collect.name must not be empty".to_string());
2762            }
2763            if collect.files_field.trim().is_empty() {
2764                return Err("collect.files_field must not be empty".to_string());
2765            }
2766            if let Some(description) = &collect.description {
2767                if description.trim().is_empty() {
2768                    return Err("collect.description must not be empty when set".to_string());
2769                }
2770            }
2771            if let Some(max_size) = &collect.max_size {
2772                parse_size_bytes(max_size).map_err(|e| format!("collect.max_size: {e}"))?;
2773            }
2774        }
2775        // #720/#743: `aggregate:` is a pure read-spec (it never touches
2776        // stdout and is never sent to an agent), so it composes with every
2777        // other hint. The per-widget rules are shared with the standalone
2778        // `view` resource — see [`validate_aggregate_widgets`].
2779        if let Some(widgets) = &self.aggregate {
2780            validate_aggregate_widgets(widgets, "aggregate")?;
2781        }
2782        // A blank / whitespace-only tag is an invisible operator typo
2783        // that would render an empty filter chip on the Jobs page —
2784        // reject it like the other present-but-blank display fields.
2785        for tag in &self.tags {
2786            if tag.trim().is_empty() {
2787                return Err("tags must not contain empty entries".to_string());
2788            }
2789        }
2790        Ok(())
2791    }
2792}
2793
2794#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
2795#[serde(rename_all = "lowercase")]
2796pub enum ExecuteShell {
2797    /// Windows PowerShell 5.1 (`powershell`).
2798    Powershell,
2799    /// `cmd.exe` (`cmd /C`). Windows only.
2800    Cmd,
2801    /// POSIX shell (`sh -c`). Linux/macOS.
2802    Sh,
2803    /// PowerShell 7, cross-platform (`pwsh`).
2804    Pwsh,
2805}
2806
2807impl From<ExecuteShell> for Shell {
2808    fn from(s: ExecuteShell) -> Self {
2809        match s {
2810            ExecuteShell::Powershell => Shell::Powershell,
2811            ExecuteShell::Cmd => Shell::Cmd,
2812            ExecuteShell::Sh => Shell::Sh,
2813            ExecuteShell::Pwsh => Shell::Pwsh,
2814        }
2815    }
2816}
2817
2818#[cfg(test)]
2819mod tests {
2820    use super::*;
2821
2822    #[test]
2823    fn inventory_payload_extracts_fenced_block() {
2824        // Readable message + fenced JSON → only the JSON, trimmed.
2825        let stdout = "Wi-Fi 設定を適用しました。\n\
2826            #KANADE-INVENTORY-BEGIN\n\
2827            {\"applied\": true}\n\
2828            #KANADE-INVENTORY-END\n";
2829        assert_eq!(inventory_payload(stdout), "{\"applied\": true}");
2830    }
2831
2832    #[test]
2833    fn inventory_payload_falls_back_to_whole_stdout() {
2834        // No fence (a plain inventory job) → whole stdout, trimmed.
2835        assert_eq!(
2836            inventory_payload("  {\"ram_gb\": 16}\n"),
2837            "{\"ram_gb\": 16}"
2838        );
2839    }
2840
2841    #[test]
2842    fn inventory_payload_handles_unterminated_fence() {
2843        // Closing marker missing (e.g. truncated) → everything after the
2844        // opener, trimmed.
2845        let stdout = "msg\n#KANADE-INVENTORY-BEGIN\n{\"a\": 1}";
2846        assert_eq!(inventory_payload(stdout), "{\"a\": 1}");
2847    }
2848
2849    #[test]
2850    fn inventory_payload_ignores_mid_line_sentinel() {
2851        // The marker echoed mid-line (not at a line start) must NOT be
2852        // treated as a fence — fall back to the whole stdout.
2853        let stdout = "see #KANADE-INVENTORY-BEGIN in the docs\nnot json";
2854        assert_eq!(inventory_payload(stdout), stdout.trim());
2855    }
2856
2857    #[test]
2858    fn fenced_payload_extracts_each_hint_block_independently() {
2859        // #821: one stdout carrying a user message + all three fenced
2860        // blocks — every consumer pulls only its own.
2861        let stdout = "\
2862done!
2863#KANADE-INVENTORY-BEGIN
2864{\"os\":\"win\"}
2865#KANADE-INVENTORY-END
2866#KANADE-CHECK-BEGIN
2867{\"status\":\"ok\"}
2868#KANADE-CHECK-END
2869#KANADE-COLLECT-BEGIN
2870{\"files\":[\"a\"]}
2871#KANADE-COLLECT-END
2872";
2873        assert_eq!(
2874            fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
2875            "{\"os\":\"win\"}"
2876        );
2877        assert_eq!(
2878            fenced_payload(stdout, CHECK_BLOCK_BEGIN, CHECK_BLOCK_END),
2879            "{\"status\":\"ok\"}"
2880        );
2881        assert_eq!(
2882            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2883            "{\"files\":[\"a\"]}"
2884        );
2885    }
2886
2887    #[test]
2888    fn fenced_payload_falls_back_to_whole_stdout_without_fence() {
2889        // A single-hint job needs no fence — the whole (trimmed) stdout is
2890        // the payload.
2891        let stdout = "  {\"files\":[\"a\"]}  ";
2892        assert_eq!(
2893            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2894            "{\"files\":[\"a\"]}"
2895        );
2896    }
2897
2898    #[test]
2899    fn fenced_payload_returns_empty_when_other_fences_present_but_mine_missing() {
2900        // Multi-hint output (inventory + check fenced) but the COLLECT
2901        // fence is missing — collect must NOT fall back to the whole
2902        // stdout (which holds the inventory/check blocks) and cross-parse
2903        // a sibling block; it gets "" → its JSON parse fails → no data.
2904        let stdout = "\
2905#KANADE-INVENTORY-BEGIN
2906{\"os\":\"win\"}
2907#KANADE-INVENTORY-END
2908#KANADE-CHECK-BEGIN
2909{\"status\":\"ok\"}
2910#KANADE-CHECK-END
2911";
2912        assert_eq!(
2913            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2914            ""
2915        );
2916        // ...while the hints that DID fence still extract correctly.
2917        assert_eq!(
2918            fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
2919            "{\"os\":\"win\"}"
2920        );
2921    }
2922
2923    /// The example check-job + schedule YAMLs shipped under `configs/`
2924    /// must stay valid as the schema evolves (#290 PR-C). `include_str!`
2925    /// pins them at compile time so a breaking edit fails `cargo test`
2926    /// rather than only `kanade job create` at deploy time.
2927    #[test]
2928    fn example_check_job_yamls_parse_and_validate() {
2929        let jobs = [
2930            (
2931                "check-bitlocker",
2932                include_str!("../../../configs/jobs/check-bitlocker.yaml"),
2933            ),
2934            (
2935                "check-av-signature",
2936                include_str!("../../../configs/jobs/check-av-signature.yaml"),
2937            ),
2938            (
2939                "check-cert-expiry",
2940                include_str!("../../../configs/jobs/check-cert-expiry.yaml"),
2941            ),
2942            (
2943                "check-disk-space",
2944                include_str!("../../../configs/jobs/check-disk-space.yaml"),
2945            ),
2946            (
2947                "check-pending-reboot",
2948                include_str!("../../../configs/jobs/check-pending-reboot.yaml"),
2949            ),
2950            (
2951                "check-defender-rtp",
2952                include_str!("../../../configs/jobs/check-defender-rtp.yaml"),
2953            ),
2954            (
2955                "check-firewall",
2956                include_str!("../../../configs/jobs/check-firewall.yaml"),
2957            ),
2958        ];
2959        for (name, yaml) in jobs {
2960            let m: Manifest =
2961                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} parse: {e}"));
2962            m.validate()
2963                .unwrap_or_else(|e| panic!("{name} validate: {e}"));
2964            let check = m
2965                .check
2966                .as_ref()
2967                .unwrap_or_else(|| panic!("{name} must carry a check: hint"));
2968            assert!(!check.name.trim().is_empty(), "{name} check.name empty");
2969            // These examples all read admin-only WMI / registry / netsh
2970            // state, so they run_as system. NOTE: that's a property of
2971            // these particular checks, NOT of the `check:` contract — a
2972            // check probing user-session state could run_as user.
2973            assert_eq!(
2974                m.execute.run_as,
2975                RunAs::System,
2976                "{name} should run_as system"
2977            );
2978        }
2979    }
2980
2981    /// The example user-invokable job YAMLs (#291) shipped under
2982    /// `configs/jobs/` must stay valid as the `client:` schema
2983    /// evolves. `include_str!` pins them at compile time so a breaking
2984    /// edit fails `cargo test`, not `kanade job create` at deploy.
2985    #[test]
2986    fn example_client_job_yamls_parse_and_validate() {
2987        let jobs = [
2988            (
2989                "fix-teams-cache",
2990                "troubleshoot",
2991                include_str!("../../../configs/jobs/fix-teams-cache.yaml"),
2992            ),
2993            (
2994                "chrome-update",
2995                "software_update",
2996                include_str!("../../../configs/jobs/chrome-update.yaml"),
2997            ),
2998            (
2999                "install-slack",
3000                "catalog",
3001                include_str!("../../../configs/jobs/install-slack.yaml"),
3002            ),
3003            (
3004                "fix-defender-rtp",
3005                "troubleshoot",
3006                include_str!("../../../configs/jobs/fix-defender-rtp.yaml"),
3007            ),
3008            // #792 custom category ("settings") + #809 message/inventory.
3009            (
3010                "example-power-plan",
3011                "settings",
3012                include_str!("../../../configs/jobs/example-power-plan.yaml"),
3013            ),
3014            // #792: diagnostics moved to its own "support" tab.
3015            (
3016                "collect-diagnostics",
3017                "support",
3018                include_str!("../../../configs/jobs/collect-diagnostics.yaml"),
3019            ),
3020        ];
3021        for (id, category, yaml) in jobs {
3022            let m: Manifest =
3023                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
3024            m.validate()
3025                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
3026            assert_eq!(m.id, id, "{id} id mismatch");
3027            let client = m
3028                .client
3029                .as_ref()
3030                .unwrap_or_else(|| panic!("{id} must carry a client: block"));
3031            assert!(!client.name.trim().is_empty(), "{id} client.name empty");
3032            assert_eq!(client.category, category, "{id} category");
3033        }
3034    }
3035
3036    /// #219: the shipped `collect:` example must stay valid as the
3037    /// schema evolves. `include_str!` pins it at compile time so a
3038    /// breaking edit (or a YAML typo in the PowerShell block) fails
3039    /// `cargo test` rather than `kanade job create` at deploy. It carries
3040    /// both `collect:` and `client:` (end-user-triggerable), which must
3041    /// compose.
3042    #[test]
3043    fn example_collect_job_yaml_parses_and_validates() {
3044        let yaml = include_str!("../../../configs/jobs/collect-diagnostics.yaml");
3045        let m: Manifest = serde_yaml::from_str(yaml).expect("collect-diagnostics parse");
3046        m.validate().expect("collect-diagnostics validate");
3047        assert_eq!(m.id, "collect-diagnostics");
3048        let collect = m.collect.as_ref().expect("collect: block present");
3049        assert!(!collect.name.trim().is_empty());
3050        assert_eq!(collect.files_field, "files");
3051        assert_eq!(collect.max_size_bytes(), 50_000_000);
3052        // collect + client compose — the Client App can trigger it.
3053        assert!(
3054            m.client.is_some(),
3055            "collect-diagnostics also carries client:"
3056        );
3057    }
3058
3059    /// The `emit: { type: events }` collector jobs under
3060    /// `configs/jobs/` feed the obs_events timeline. `include_str!`
3061    /// pins them at compile time so a breaking edit (e.g. an `emit:`
3062    /// paired with `check:`/`inventory:`, a bad watermark field, or a
3063    /// YAML typo in the PowerShell block) fails `cargo test` rather
3064    /// than `kanade job create` at deploy. Every one must carry an
3065    /// `emit.type=events` block and NO check/inventory (validate()
3066    /// rejects the pairing).
3067    #[test]
3068    fn example_event_collector_job_yamls_parse_and_validate() {
3069        let jobs = [
3070            // collect-winlog-events was retired in #841 PR2 — the scheduled
3071            // human-session / power timeline is now read natively by the
3072            // agent (kanade-agent `winlog` module via EvtQuery), no
3073            // PowerShell job. collect-winlog-logons-all stays as the
3074            // on-demand forensic all-token-logons companion.
3075            (
3076                "collect-winlog-logons-all",
3077                include_str!("../../../configs/jobs/collect-winlog-logons-all.yaml"),
3078            ),
3079            (
3080                "collect-wlan-events",
3081                include_str!("../../../configs/jobs/collect-wlan-events.yaml"),
3082            ),
3083        ];
3084        for (id, yaml) in jobs {
3085            // Strict parse so an unknown-key typo in these fixtures fails
3086            // here (not silently at deploy) — the runtime Manifest is
3087            // unknown-key-tolerant, so the lenient serde_yaml::from_str
3088            // wouldn't catch fixture drift (CodeRabbit #689).
3089            let m: Manifest =
3090                crate::strict::from_yaml_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
3091            m.validate()
3092                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
3093            assert_eq!(m.id, id, "{id} id mismatch");
3094            let emit = m
3095                .emit
3096                .as_ref()
3097                .unwrap_or_else(|| panic!("{id} must carry an emit: block"));
3098            assert_eq!(emit.kind, EmitKind::Events, "{id} emit.type");
3099            assert!(
3100                m.check.is_none() && m.inventory.is_none(),
3101                "{id}: emit jobs must not pair with check/inventory"
3102            );
3103        }
3104    }
3105
3106    /// The `inventory:` snapshot jobs under `configs/jobs/` project
3107    /// facts into `inventory_facts` + exploded tables. `include_str!`
3108    /// pins them at compile time so a breaking edit (bad explode
3109    /// schema, a YAML typo in the PowerShell block, an `inventory:`
3110    /// accidentally paired with `emit:`) fails `cargo test` rather
3111    /// than the projector at deploy. Each must carry an `inventory:`
3112    /// block and NO emit (validate() rejects the pairing).
3113    #[test]
3114    fn example_inventory_job_yamls_parse_and_validate() {
3115        let jobs = [
3116            (
3117                "inventory-hw",
3118                include_str!("../../../configs/jobs/inventory-hw.yaml"),
3119            ),
3120            (
3121                "inventory-sw",
3122                include_str!("../../../configs/jobs/inventory-sw.yaml"),
3123            ),
3124            (
3125                "inventory-driver",
3126                include_str!("../../../configs/jobs/inventory-driver.yaml"),
3127            ),
3128        ];
3129        for (id, yaml) in jobs {
3130            let m: Manifest =
3131                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
3132            m.validate()
3133                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
3134            assert_eq!(m.id, id, "{id} id mismatch");
3135            assert!(m.inventory.is_some(), "{id} must carry an inventory: block");
3136            assert!(m.emit.is_none(), "{id}: inventory jobs must not set emit:");
3137        }
3138    }
3139
3140    #[test]
3141    fn example_check_schedule_yamls_parse_and_validate() {
3142        let schedules = [
3143            (
3144                "check-bitlocker",
3145                include_str!("../../../configs/schedules/check-bitlocker.yaml"),
3146            ),
3147            (
3148                "check-av-signature",
3149                include_str!("../../../configs/schedules/check-av-signature.yaml"),
3150            ),
3151            (
3152                "check-cert-expiry",
3153                include_str!("../../../configs/schedules/check-cert-expiry.yaml"),
3154            ),
3155            (
3156                "check-disk-space",
3157                include_str!("../../../configs/schedules/check-disk-space.yaml"),
3158            ),
3159            (
3160                "check-pending-reboot",
3161                include_str!("../../../configs/schedules/check-pending-reboot.yaml"),
3162            ),
3163            (
3164                "check-defender-rtp",
3165                include_str!("../../../configs/schedules/check-defender-rtp.yaml"),
3166            ),
3167            (
3168                "check-firewall",
3169                include_str!("../../../configs/schedules/check-firewall.yaml"),
3170            ),
3171        ];
3172        for (name, yaml) in schedules {
3173            let s: Schedule =
3174                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
3175            s.validate()
3176                .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
3177            assert_eq!(s.job_id, name, "{name} schedule must reference its job");
3178        }
3179    }
3180
3181    /// Inventory schedule wrappers (`per_pc` cadence) must stay valid
3182    /// alongside the schedule schema. `include_str!` pins them so a
3183    /// breaking edit fails `cargo test`, not `kanade schedule create`.
3184    #[test]
3185    fn example_inventory_schedule_yamls_parse_and_validate() {
3186        let schedules = [
3187            (
3188                "inventory-hw",
3189                include_str!("../../../configs/schedules/inventory-hw.yaml"),
3190            ),
3191            (
3192                "inventory-sw",
3193                include_str!("../../../configs/schedules/inventory-sw.yaml"),
3194            ),
3195            (
3196                "inventory-driver",
3197                include_str!("../../../configs/schedules/inventory-driver.yaml"),
3198            ),
3199        ];
3200        for (name, yaml) in schedules {
3201            let s: Schedule =
3202                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
3203            s.validate()
3204                .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
3205            assert_eq!(s.job_id, name, "{name} schedule must reference its job");
3206        }
3207    }
3208
3209    #[test]
3210    fn target_is_specified_requires_at_least_one_field() {
3211        let empty = Target::default();
3212        assert!(!empty.is_specified());
3213
3214        let with_all = Target {
3215            all: true,
3216            ..Target::default()
3217        };
3218        assert!(with_all.is_specified());
3219
3220        let with_groups = Target {
3221            groups: vec!["canary".into()],
3222            ..Target::default()
3223        };
3224        assert!(with_groups.is_specified());
3225
3226        let with_pcs = Target {
3227            pcs: vec!["pc-01".into()],
3228            ..Target::default()
3229        };
3230        assert!(with_pcs.is_specified());
3231    }
3232
3233    #[test]
3234    fn manifest_deserialises_minimal_yaml() {
3235        // Matches jobs/echo-test.yaml. v0.18: no target/rollout/jitter
3236        // — those live on the schedule / exec request now.
3237        let yaml = r#"
3238id: echo-test
3239version: 0.0.1
3240execute:
3241  shell: powershell
3242  script: "echo 'kanade'"
3243  timeout: 30s
3244"#;
3245        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3246        assert_eq!(m.id, "echo-test");
3247        assert_eq!(m.version, "0.0.1");
3248        assert!(matches!(m.execute.shell, ExecuteShell::Powershell));
3249        assert_eq!(
3250            m.execute.script.as_deref().map(str::trim),
3251            Some("echo 'kanade'")
3252        );
3253        assert!(m.execute.script_file.is_none());
3254        assert!(m.execute.script_object.is_none());
3255        assert_eq!(m.execute.timeout, "30s");
3256        assert!(!m.require_approval);
3257        m.validate()
3258            .expect("inline-script manifest passes validation");
3259    }
3260
3261    #[test]
3262    fn manifest_parses_check_job_and_validates() {
3263        // An operator-defined health check (#290): a `check:` hint +
3264        // a PowerShell script that prints {status, detail}.
3265        let yaml = r#"
3266id: check-bitlocker
3267version: 0.1.0
3268execute:
3269  shell: powershell
3270  run_as: system
3271  timeout: 15s
3272  script: |
3273    [pscustomobject]@{ status = 'ok'; detail = 'all volumes protected' } | ConvertTo-Json -Compress
3274check:
3275  name: bitlocker
3276  troubleshoot: fix-bitlocker
3277"#;
3278        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3279        let check = m.check.as_ref().expect("check hint present");
3280        assert_eq!(check.name, "bitlocker");
3281        assert_eq!(check.troubleshoot.as_deref(), Some("fix-bitlocker"));
3282        // Field names default to the conventional "status" / "detail".
3283        assert_eq!(check.status_field, "status");
3284        assert_eq!(check.detail_field, "detail");
3285        assert!(m.inventory.is_none() && m.emit.is_none());
3286        m.validate().expect("check-only manifest passes validation");
3287    }
3288
3289    #[test]
3290    fn manifest_check_defaults_and_custom_fields() {
3291        // Minimal: only `name`; status/detail fields default.
3292        let m: Manifest = serde_yaml::from_str(
3293            r#"
3294id: check-disk
3295version: 0.1.0
3296execute:
3297  shell: powershell
3298  script: "[pscustomobject]@{ status = 'ok' } | ConvertTo-Json -Compress"
3299  timeout: 10s
3300check:
3301  name: disk_free
3302"#,
3303        )
3304        .expect("parse");
3305        let c = m.check.as_ref().unwrap();
3306        assert_eq!(c.name, "disk_free");
3307        assert_eq!(c.status_field, "status");
3308        assert_eq!(c.detail_field, "detail");
3309        assert!(c.troubleshoot.is_none());
3310        m.validate().expect("validates");
3311
3312        // The operator can point status/detail at any field of their
3313        // free-form inventory object.
3314        let m2: Manifest = serde_yaml::from_str(
3315            r#"
3316id: check-custom
3317version: 0.1.0
3318execute:
3319  shell: powershell
3320  script: "echo x"
3321  timeout: 10s
3322check:
3323  name: patch_level
3324  status_field: compliance
3325  detail_field: summary
3326"#,
3327        )
3328        .expect("parse");
3329        let c2 = m2.check.as_ref().unwrap();
3330        assert_eq!(c2.status_field, "compliance");
3331        assert_eq!(c2.detail_field, "summary");
3332    }
3333
3334    #[test]
3335    fn manifest_allows_check_composed_with_inventory() {
3336        // `check:` + `inventory:` COMPOSE on the same stdout object:
3337        // status/detail → Health tab, the rest → SPA projection +
3338        // explode sub-tables. Must pass validation.
3339        let yaml = r#"
3340id: check-bitlocker-detailed
3341version: 0.1.0
3342execute:
3343  shell: powershell
3344  script: "echo x"
3345  timeout: 10s
3346check:
3347  name: bitlocker
3348inventory:
3349  display:
3350    - { field: status, label: Status }
3351"#;
3352        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3353        assert!(m.check.is_some() && m.inventory.is_some());
3354        m.validate().expect("check + inventory compose");
3355    }
3356
3357    #[test]
3358    fn manifest_parses_collect_job_and_validates() {
3359        // #219: a `collect:` hint + a script that lists files on stdout.
3360        let yaml = r#"
3361id: collect-diagnostics
3362version: 0.1.0
3363execute:
3364  shell: powershell
3365  run_as: system
3366  timeout: 120s
3367  script: |
3368    @{ files = @("$env:KANADE_COLLECT_DIR/system.csv") } | ConvertTo-Json
3369collect:
3370  name: "Full diagnostics"
3371  description: "Event logs + process"
3372  max_size: 50MB
3373"#;
3374        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3375        let c = m.collect.as_ref().expect("collect hint present");
3376        assert_eq!(c.name, "Full diagnostics");
3377        assert_eq!(c.files_field, "files"); // default
3378        assert_eq!(c.max_size_bytes(), 50_000_000);
3379        m.validate().expect("collect-only manifest validates");
3380    }
3381
3382    #[test]
3383    fn manifest_finalize_powershell_validates_and_lowers() {
3384        let yaml = r#"
3385id: collect-fin
3386version: 0.1.0
3387execute:
3388  shell: powershell
3389  timeout: 120s
3390  script: |
3391    @{ files = @() } | ConvertTo-Json
3392collect:
3393  name: "diag"
3394  max_size: 50MB
3395finalize:
3396  shell: powershell
3397  timeout: 30s
3398  run_as: system
3399  script: |
3400    Write-Output "cleanup"
3401"#;
3402        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3403        m.validate().expect("powershell finalize validates");
3404        let lowered = m.finalize.as_ref().expect("finalize present").lower();
3405        assert_eq!(lowered.timeout_secs, 30);
3406        assert!(matches!(lowered.shell, Shell::Powershell));
3407        // #965: default is the one-call-after-all contract.
3408        assert!(!lowered.on_each_bundle);
3409    }
3410
3411    #[test]
3412    fn manifest_finalize_on_each_bundle_validates_with_collect_and_lowers() {
3413        // #965: on_each_bundle + a collect hint is the intended
3414        // combination — validates, and the flag survives lowering.
3415        let yaml = r#"
3416id: collect-fin-each
3417version: 0.1.0
3418execute:
3419  shell: powershell
3420  timeout: 120s
3421  script: |
3422    @{ files = @() } | ConvertTo-Json
3423collect:
3424  name: "diag"
3425  max_size: 50MB
3426finalize:
3427  shell: powershell
3428  on_each_bundle: true
3429  script: |
3430    Write-Output "cleanup"
3431"#;
3432        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3433        m.validate().expect("on_each_bundle + collect validates");
3434        let lowered = m.finalize.as_ref().expect("finalize present").lower();
3435        assert!(lowered.on_each_bundle, "flag survives lowering");
3436    }
3437
3438    #[test]
3439    fn manifest_finalize_on_each_bundle_without_collect_rejected() {
3440        // #965: a non-collect finalize has no bundles to iterate, so
3441        // on_each_bundle is a no-op — reject it at the write boundary so
3442        // the operator is told rather than silently getting nothing.
3443        let yaml = r#"
3444id: fin-each-no-collect
3445version: 0.1.0
3446execute:
3447  shell: powershell
3448  timeout: 120s
3449  script: |
3450    Write-Output "hi"
3451finalize:
3452  shell: powershell
3453  on_each_bundle: true
3454  script: |
3455    Write-Output "cleanup"
3456"#;
3457        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3458        let err = m
3459            .validate()
3460            .expect_err("on_each_bundle without collect rejected");
3461        assert!(err.contains("on_each_bundle"), "got: {err}");
3462        assert!(err.contains("collect"), "got: {err}");
3463    }
3464
3465    #[test]
3466    fn manifest_finalize_rejects_cmd_shell() {
3467        // cmd finalize is an injection risk (the agent injects JSON into
3468        // the hook's env; cmd.exe quoting doesn't nest) — validate must
3469        // reject it.
3470        let yaml = r#"
3471id: collect-fin-cmd
3472version: 0.1.0
3473execute:
3474  shell: powershell
3475  timeout: 120s
3476  script: |
3477    @{ files = @() } | ConvertTo-Json
3478finalize:
3479  shell: cmd
3480  script: |
3481    echo hi
3482"#;
3483        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3484        let err = m.validate().expect_err("cmd finalize rejected");
3485        assert!(err.contains("finalize.shell"), "got: {err}");
3486    }
3487
3488    #[test]
3489    fn manifest_finalize_rejects_sh_shell() {
3490        // sh finalize is rejected for the same reason as cmd: the agent
3491        // injects the result JSON, and the injected prelude is PowerShell
3492        // syntax that a POSIX shell can't run.
3493        let yaml = r#"
3494id: collect-fin-sh
3495version: 0.1.0
3496execute:
3497  shell: powershell
3498  timeout: 120s
3499  script: |
3500    @{ files = @() } | ConvertTo-Json
3501finalize:
3502  shell: sh
3503  script: |
3504    echo hi
3505"#;
3506        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3507        let err = m.validate().expect_err("sh finalize rejected");
3508        assert!(err.contains("finalize.shell"), "got: {err}");
3509    }
3510
3511    #[test]
3512    fn manifest_finalize_accepts_pwsh_shell() {
3513        // pwsh IS PowerShell, so the injected prelude + single-quote
3514        // escaping are valid and safe — a pwsh finalize must validate.
3515        let yaml = r#"
3516id: collect-fin-pwsh
3517version: 0.1.0
3518execute:
3519  shell: pwsh
3520  timeout: 120s
3521  script: |
3522    @{ files = @() } | ConvertTo-Json
3523finalize:
3524  shell: pwsh
3525  script: |
3526    Write-Output hi
3527"#;
3528        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3529        m.validate().expect("pwsh finalize accepted");
3530    }
3531
3532    #[test]
3533    fn manifest_finalize_rejects_empty_script() {
3534        let yaml = r#"
3535id: collect-fin-empty
3536version: 0.1.0
3537execute:
3538  shell: powershell
3539  timeout: 120s
3540  script: |
3541    @{ files = @() } | ConvertTo-Json
3542finalize:
3543  shell: powershell
3544  script: "   "
3545"#;
3546        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3547        let err = m.validate().expect_err("empty finalize script rejected");
3548        assert!(err.contains("finalize.script"), "got: {err}");
3549    }
3550
3551    #[test]
3552    fn manifest_collect_max_size_defaults_when_unset() {
3553        let m: Manifest = serde_yaml::from_str(
3554            r#"
3555id: collect-min
3556version: 0.1.0
3557execute:
3558  shell: powershell
3559  script: "echo x"
3560  timeout: 10s
3561collect:
3562  name: minimal
3563"#,
3564        )
3565        .expect("parse");
3566        let c = m.collect.as_ref().unwrap();
3567        assert!(c.max_size.is_none());
3568        assert_eq!(c.max_size_bytes(), DEFAULT_COLLECT_MAX_SIZE);
3569        m.validate().expect("validates");
3570    }
3571
3572    #[test]
3573    fn manifest_allows_collect_with_client() {
3574        // collect composes with client (client doesn't touch stdout):
3575        // an end user can trigger a collection from the Client App.
3576        let yaml = r#"
3577id: collect-diag-client
3578version: 0.1.0
3579execute:
3580  shell: powershell
3581  script: "echo x"
3582  timeout: 10s
3583collect:
3584  name: diagnostics
3585client:
3586  name: "Send diagnostics"
3587  category: troubleshoot
3588"#;
3589        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3590        assert!(m.collect.is_some() && m.client.is_some());
3591        m.validate().expect("collect + client compose");
3592    }
3593
3594    #[test]
3595    fn manifest_allows_inventory_check_collect_coexistence() {
3596        // #821: the three fenced hints now COMPOSE — each reads its own
3597        // `#KANADE-<KIND>` stdout block, so one job can do all three.
3598        let yaml = r#"
3599id: multi-hint
3600version: 0.1.0
3601execute:
3602  shell: powershell
3603  script: "echo x"
3604  timeout: 10s
3605inventory:
3606  display:
3607    - { field: status, label: Status }
3608check:
3609  name: health
3610collect:
3611  name: diag
3612"#;
3613        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3614        m.validate()
3615            .expect("inventory + check + collect coexist after #821");
3616    }
3617
3618    #[test]
3619    fn manifest_rejects_emit_combined_with_fenced_hints() {
3620        // `emit:` consumes stdout as NDJSON (and blanks it), so it still
3621        // can't share with any fenced hint — inventory, check, OR collect.
3622        for extra in [
3623            "inventory:\n  display:\n    - { field: s, label: S }\n",
3624            "check:\n  name: health\n",
3625            "collect:\n  name: diag\n",
3626        ] {
3627            let yaml = format!(
3628                "id: bad-emit-mix\nversion: 0.1.0\nexecute:\n  shell: powershell\n  \
3629                 script: \"echo x\"\n  timeout: 10s\nemit:\n  type: events\n{extra}"
3630            );
3631            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
3632            let err = m
3633                .validate()
3634                .expect_err("emit + fenced hint must be rejected");
3635            assert!(err.contains("emit"), "error mentions emit: {err}");
3636        }
3637    }
3638
3639    #[test]
3640    fn manifest_rejects_collect_empty_name_and_bad_size() {
3641        let empty_name: Manifest = serde_yaml::from_str(
3642            r#"
3643id: c
3644version: 0.1.0
3645execute: { shell: powershell, script: "echo x", timeout: 10s }
3646collect: { name: "  " }
3647"#,
3648        )
3649        .expect("parse");
3650        assert!(
3651            empty_name.validate().is_err(),
3652            "blank collect.name rejected"
3653        );
3654
3655        let bad_size: Manifest = serde_yaml::from_str(
3656            r#"
3657id: c
3658version: 0.1.0
3659execute: { shell: powershell, script: "echo x", timeout: 10s }
3660collect: { name: diag, max_size: "50 quux" }
3661"#,
3662        )
3663        .expect("parse");
3664        let err = bad_size.validate().expect_err("bad max_size rejected");
3665        assert!(err.contains("max_size"), "error mentions max_size: {err}");
3666    }
3667
3668    #[test]
3669    fn parse_size_bytes_units() {
3670        assert_eq!(parse_size_bytes("1024").unwrap(), 1024);
3671        assert_eq!(parse_size_bytes("1B").unwrap(), 1);
3672        assert_eq!(parse_size_bytes("50MB").unwrap(), 50_000_000);
3673        assert_eq!(parse_size_bytes("500 KB").unwrap(), 500_000);
3674        assert_eq!(parse_size_bytes("1GiB").unwrap(), 1024 * 1024 * 1024);
3675        assert_eq!(parse_size_bytes("2mib").unwrap(), 2 * 1024 * 1024);
3676        assert!(parse_size_bytes("").is_err());
3677        assert!(parse_size_bytes("MB").is_err());
3678        assert!(parse_size_bytes("12 zonks").is_err());
3679    }
3680
3681    #[test]
3682    fn manifest_rejects_check_combined_with_emit() {
3683        // `emit:` stdout is NDJSON (and omitted from the result), so
3684        // it can't pair with `check:` (which needs a single JSON
3685        // object on stdout).
3686        let yaml = r#"
3687id: bad-mix
3688version: 0.1.0
3689execute:
3690  shell: powershell
3691  script: "echo x"
3692  timeout: 10s
3693check:
3694  name: bitlocker
3695emit:
3696  type: events
3697"#;
3698        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3699        let err = m.validate().expect_err("emit + check must fail");
3700        assert!(err.contains("incompatible"), "err: {err}");
3701    }
3702
3703    #[test]
3704    fn manifest_rejects_emit_combined_with_inventory() {
3705        // The other half of the emit-incompatibility condition.
3706        let yaml = r#"
3707id: bad-mix-2
3708version: 0.1.0
3709execute:
3710  shell: powershell
3711  script: "echo x"
3712  timeout: 10s
3713emit:
3714  type: events
3715inventory:
3716  display:
3717    - { field: status, label: Status }
3718"#;
3719        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3720        let err = m.validate().expect_err("emit + inventory must fail");
3721        assert!(err.contains("incompatible"), "err: {err}");
3722    }
3723
3724    #[test]
3725    fn manifest_rejects_empty_check_field_names() {
3726        // Empty name / status_field / detail_field are invisible
3727        // runtime bugs (empty React key, agent reads the wrong field)
3728        // — reject them even though serde supplies non-empty defaults.
3729        let base = |inner: &str| {
3730            format!(
3731                "id: c\nversion: 0.1.0\nexecute:\n  shell: powershell\n  script: \"echo x\"\n  timeout: 10s\ncheck:\n{inner}"
3732            )
3733        };
3734        for inner in [
3735            "  name: \"\"\n",
3736            "  name: ok\n  status_field: \"\"\n",
3737            "  name: ok\n  detail_field: \"   \"\n",
3738            // present-but-blank troubleshoot → broken remediation id.
3739            "  name: ok\n  troubleshoot: \"  \"\n",
3740        ] {
3741            let m: Manifest = serde_yaml::from_str(&base(inner)).expect("parse");
3742            let err = m.validate().expect_err("empty field must fail");
3743            assert!(err.contains("must not be empty"), "err: {err}");
3744        }
3745    }
3746
3747    #[test]
3748    fn check_alert_decodes_with_defaults_and_validates() {
3749        let yaml = r#"
3750id: c
3751version: 0.1.0
3752execute:
3753  shell: powershell
3754  script: "echo x"
3755  timeout: 10s
3756check:
3757  name: bitlocker
3758  alert:
3759    notify_user: true
3760    title: "BitLocker 未準拠"
3761"#;
3762        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3763        m.validate().expect("valid alert");
3764        let alert = m.check.unwrap().alert.unwrap();
3765        // Defaults: on = [fail], priority = warn, body = None.
3766        assert_eq!(alert.on, vec![CheckAlertStatus::Fail]);
3767        assert_eq!(
3768            alert.priority,
3769            crate::ipc::notifications::NotificationPriority::Warn
3770        );
3771        assert!(alert.body.is_none());
3772        assert!(alert.notify_user);
3773    }
3774
3775    #[test]
3776    fn check_alert_validation_rejects_bad_configs() {
3777        let base = |alert: &str| {
3778            format!(
3779                "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}"
3780            )
3781        };
3782        let cases = [
3783            // No recipient.
3784            ("    title: t\n", "notify_user and/or notify_groups"),
3785            // Empty title.
3786            (
3787                "    notify_user: true\n    title: \"  \"\n",
3788                "title must not be empty",
3789            ),
3790            // Empty `on`.
3791            (
3792                "    notify_user: true\n    title: t\n    on: []\n",
3793                "on must list at least one status",
3794            ),
3795            // Blank group name.
3796            (
3797                "    notify_groups: [\"  \"]\n    title: t\n",
3798                "notify_groups must not contain blanks",
3799            ),
3800            // alert requires fleet: true.
3801            (
3802                "    notify_user: true\n    title: t\n  fleet: false\n",
3803                "requires fleet: true",
3804            ),
3805            // email opt-in without a group to address.
3806            (
3807                "    notify_user: true\n    email: true\n    title: t\n",
3808                "email requires notify_groups",
3809            ),
3810        ];
3811        for (alert, want) in cases {
3812            let m: Manifest = serde_yaml::from_str(&base(alert)).expect("parse");
3813            let err = m.validate().expect_err("bad alert must fail");
3814            assert!(err.contains(want), "for {alert:?}: got {err}");
3815        }
3816    }
3817
3818    #[test]
3819    fn manifest_client_absent_by_default() {
3820        // A plain operator job (the overwhelming majority) carries no
3821        // `client:` block, so it never surfaces in the end-user
3822        // catalog.
3823        let yaml = r#"
3824id: echo-test
3825version: 0.0.1
3826execute:
3827  shell: powershell
3828  script: "echo 'kanade'"
3829  timeout: 30s
3830"#;
3831        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3832        assert!(m.client.is_none());
3833        m.validate().expect("operator-only job validates");
3834    }
3835
3836    #[test]
3837    fn manifest_client_parses_and_validates() {
3838        // The Client App "困ったとき" remediation job shape: a
3839        // user-invokable troubleshoot job with the end-user fields the
3840        // KLP `jobs.list` wire needs, grouped under `client:`.
3841        let yaml = r#"
3842id: fix-teams-cache
3843version: 1.0.0
3844execute:
3845  shell: powershell
3846  script: "echo clearing"
3847  timeout: 60s
3848client:
3849  name: "Teams のキャッシュをクリア"
3850  description: "Teams が重いときに試してください"
3851  category: troubleshoot
3852  icon: brush-cleaning
3853"#;
3854        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3855        let c = m.client.as_ref().expect("client block present");
3856        assert_eq!(c.name, "Teams のキャッシュをクリア");
3857        assert_eq!(
3858            c.description.as_deref(),
3859            Some("Teams が重いときに試してください")
3860        );
3861        assert_eq!(c.category, "troubleshoot");
3862        assert_eq!(c.icon.as_deref(), Some("brush-cleaning"));
3863        m.validate().expect("user-invokable job validates");
3864    }
3865
3866    #[test]
3867    fn manifest_client_minimal_only_name_and_category() {
3868        // description + icon are optional; name + category are the
3869        // serde-required minimum.
3870        let yaml = r#"
3871id: install-slack
3872version: 1.0.0
3873execute:
3874  shell: powershell
3875  script: "echo install"
3876  timeout: 600s
3877client:
3878  name: Slack
3879  category: catalog
3880"#;
3881        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3882        let c = m.client.as_ref().expect("client present");
3883        assert_eq!(c.category, "catalog");
3884        assert!(c.description.is_none() && c.icon.is_none());
3885        m.validate().expect("minimal client validates");
3886    }
3887
3888    #[test]
3889    fn manifest_client_rejects_blank_name() {
3890        // serde guarantees `name`/`category` are present; the one gap
3891        // is a present-but-blank name → empty catalog row title.
3892        let yaml = r#"
3893id: j
3894version: 1.0.0
3895execute:
3896  shell: powershell
3897  script: "echo x"
3898  timeout: 30s
3899client:
3900  name: "   "
3901  category: catalog
3902"#;
3903        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3904        let err = m.validate().expect_err("blank name must fail");
3905        assert!(err.contains("client.name"), "err: {err}");
3906    }
3907
3908    #[test]
3909    fn manifest_client_rejects_blank_optional_fields() {
3910        // description / icon are optional, but a present-but-blank
3911        // value is a bug (empty subtitle / dangling icon name) — reject
3912        // it, mirroring the check: block's troubleshoot guard.
3913        for (field, line) in [
3914            ("client.description", "  description: \"  \"\n"),
3915            ("client.icon", "  icon: \"\"\n"),
3916            // #792: the new category tab-metadata fields get the same
3917            // present-but-blank guard.
3918            ("client.category_label", "  category_label: \"  \"\n"),
3919            ("client.category_icon", "  category_icon: \"\"\n"),
3920        ] {
3921            let yaml = format!(
3922                "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}"
3923            );
3924            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
3925            let err = m.validate().expect_err("blank optional field must fail");
3926            assert!(err.contains(field), "expected {field} in err: {err}");
3927        }
3928    }
3929
3930    #[test]
3931    fn manifest_client_rejects_blank_category() {
3932        // #792: category is a free-form key now; serde keeps it required,
3933        // but a present-but-blank value would group the job under an empty
3934        // tab — validate() must reject it.
3935        let yaml = r#"
3936id: j
3937version: 1.0.0
3938execute:
3939  shell: powershell
3940  script: "echo x"
3941  timeout: 30s
3942client:
3943  name: "A job"
3944  category: "   "
3945"#;
3946        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3947        let err = m.validate().expect_err("blank category must fail");
3948        assert!(err.contains("client.category"), "err: {err}");
3949    }
3950
3951    #[test]
3952    fn target_matches_pc_group_and_all() {
3953        // #816: pc match, group match, all, and the no-match case.
3954        let by_pc = Target {
3955            pcs: vec!["PC1".into()],
3956            ..Default::default()
3957        };
3958        assert!(by_pc.matches("PC1", &[]));
3959        assert!(!by_pc.matches("PC2", &["g1".into()]));
3960
3961        let by_group = Target {
3962            groups: vec!["g1".into()],
3963            ..Default::default()
3964        };
3965        assert!(by_group.matches("PC2", &["g1".into()]));
3966        assert!(!by_group.matches("PC2", &["g2".into()]));
3967
3968        let all = Target {
3969            all: true,
3970            ..Default::default()
3971        };
3972        assert!(all.matches("anyPC", &[]));
3973    }
3974
3975    #[test]
3976    fn manifest_client_rejects_empty_visible_to() {
3977        // #816: a present-but-empty visible_to (no all/groups/pcs) would
3978        // hide the job from everyone — validate() must reject it.
3979        let yaml = r#"
3980id: j
3981version: 1.0.0
3982execute:
3983  shell: powershell
3984  script: "echo x"
3985  timeout: 30s
3986client:
3987  name: "A job"
3988  category: troubleshoot
3989  visible_to: {}
3990"#;
3991        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3992        let err = m.validate().expect_err("empty visible_to must fail");
3993        assert!(err.contains("client.visible_to"), "err: {err}");
3994    }
3995
3996    #[test]
3997    fn manifest_client_accepts_visible_to_groups() {
3998        let yaml = r#"
3999id: j
4000version: 1.0.0
4001execute:
4002  shell: powershell
4003  script: "echo x"
4004  timeout: 30s
4005client:
4006  name: "A job"
4007  category: settings
4008  visible_to:
4009    groups: [wifi-affected]
4010"#;
4011        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4012        m.validate().expect("visible_to with a group validates");
4013        let vt = m.client.unwrap().visible_to.unwrap();
4014        assert_eq!(vt.groups, vec!["wifi-affected".to_string()]);
4015    }
4016
4017    #[test]
4018    fn manifest_client_show_when_accepts_scalar_and_seq() {
4019        use crate::ipc::state::CheckStatus;
4020        // `is:` accepts a single status (author ergonomics) ...
4021        let scalar = r#"
4022id: office-update
4023version: 1.0.0
4024execute:
4025  shell: powershell
4026  script: "echo x"
4027  timeout: 30s
4028client:
4029  name: "Office を最新に更新"
4030  category: software_update
4031  show_when:
4032    check: office-up-to-date
4033    is: fail
4034"#;
4035        let m: Manifest = serde_yaml::from_str(scalar).expect("parse scalar");
4036        m.validate().expect("scalar show_when validates");
4037        let sw = m.client.unwrap().show_when.unwrap();
4038        assert_eq!(sw.check, "office-up-to-date");
4039        assert_eq!(sw.is, vec![CheckStatus::Fail]);
4040
4041        // ... and a list (e.g. fail-open on a not-yet-run check).
4042        let seq = scalar.replace("is: fail", "is: [fail, unknown]");
4043        let m: Manifest = serde_yaml::from_str(&seq).expect("parse seq");
4044        m.validate().expect("seq show_when validates");
4045        assert_eq!(
4046            m.client.unwrap().show_when.unwrap().is,
4047            vec![CheckStatus::Fail, CheckStatus::Unknown]
4048        );
4049    }
4050
4051    #[test]
4052    fn manifest_client_unlock_round_trips_and_defaults_absent() {
4053        let yaml = r#"
4054id: j
4055version: 1.0.0
4056execute:
4057  shell: powershell
4058  script: "echo x"
4059  timeout: 30s
4060client:
4061  name: "A job"
4062  category: troubleshoot
4063  unlock: support
4064"#;
4065        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4066        m.validate().expect("valid");
4067        assert_eq!(
4068            m.client.as_ref().unwrap().unlock.as_deref(),
4069            Some("support")
4070        );
4071
4072        // Absent ⇒ an ordinary job, and absent from the encoded form too, so
4073        // an older reader sees byte-for-byte what it saw before the field.
4074        let plain = yaml.replace("  unlock: support\n", "");
4075        let m: Manifest = serde_yaml::from_str(&plain).expect("parse");
4076        assert!(m.client.as_ref().unwrap().unlock.is_none());
4077        let v = serde_json::to_value(&m).unwrap();
4078        assert!(v["client"].get("unlock").is_none(), "wire: {v:?}");
4079    }
4080
4081    #[test]
4082    fn manifest_client_unlock_rejects_a_malformed_scope() {
4083        // The scope is compared byte-for-byte with a configured support
4084        // code's scope, and the gate fails closed — so a typo with spaces
4085        // would hide the job forever with no error anywhere. Catch it at
4086        // create time instead.
4087        let yaml = r#"
4088id: j
4089version: 1.0.0
4090execute:
4091  shell: powershell
4092  script: "echo x"
4093  timeout: 30s
4094client:
4095  name: "A job"
4096  category: troubleshoot
4097  unlock: "help desk"
4098"#;
4099        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4100        let err = m.validate().expect_err("malformed unlock scope must fail");
4101        assert!(err.contains("client.unlock"), "err: {err}");
4102
4103        let blank = yaml.replace(r#"unlock: "help desk""#, r#"unlock: "  ""#);
4104        let m: Manifest = serde_yaml::from_str(&blank).expect("parse");
4105        let err = m.validate().expect_err("blank unlock scope must fail");
4106        assert!(err.contains("client.unlock"), "err: {err}");
4107
4108        // The padded-but-otherwise-valid case (Claude review on #1166): the
4109        // charset check runs on the scope EXACTLY AS STORED, so these must
4110        // fail here rather than pass validation and then silently never
4111        // match a support code (whose scope the backend trims before
4112        // storing) — leaving the job hidden forever with no error anywhere.
4113        for padded in [r#"unlock: " support""#, r#"unlock: "support ""#] {
4114            let m: Manifest = serde_yaml::from_str(&yaml.replace(r#"unlock: "help desk""#, padded))
4115                .expect("parse");
4116            let err = m
4117                .validate()
4118                .expect_err("padded unlock scope must fail: {padded}");
4119            assert!(err.contains("client.unlock"), "{padded} err: {err}");
4120        }
4121    }
4122
4123    #[test]
4124    fn manifest_client_show_when_rejects_empty() {
4125        // A malformed check slug (here: internal spaces — a typo that could
4126        // never match a real check name) or an empty status list would
4127        // silently hide the job forever — validate() must reject both.
4128        let bad_check = r#"
4129id: j
4130version: 1.0.0
4131execute:
4132  shell: powershell
4133  script: "echo x"
4134  timeout: 30s
4135client:
4136  name: "A job"
4137  category: software_update
4138  show_when:
4139    check: "office up to date"
4140    is: fail
4141"#;
4142        let m: Manifest = serde_yaml::from_str(bad_check).expect("parse");
4143        let err = m.validate().expect_err("malformed check slug must fail");
4144        assert!(err.contains("client.show_when.check"), "err: {err}");
4145
4146        let empty_is = r#"
4147id: j
4148version: 1.0.0
4149execute:
4150  shell: powershell
4151  script: "echo x"
4152  timeout: 30s
4153client:
4154  name: "A job"
4155  category: software_update
4156  show_when:
4157    check: office-up-to-date
4158    is: []
4159"#;
4160        let m: Manifest = serde_yaml::from_str(empty_is).expect("parse");
4161        let err = m.validate().expect_err("empty is[] must fail");
4162        assert!(err.contains("client.show_when.is"), "err: {err}");
4163    }
4164
4165    #[test]
4166    fn manifest_client_confirm_accepts_bool_and_struct() {
4167        // `confirm:` deserializes from a bare bool or a struct. A bool
4168        // sets `enabled` (message stays default); a struct carries a custom
4169        // message and defaults `enabled` to true.
4170        let base = r#"
4171id: j
4172version: 1.0.0
4173execute:
4174  shell: powershell
4175  script: "echo x"
4176  timeout: 30s
4177client:
4178  name: "Wi-Fi 省電力を切る"
4179  category: settings
4180"#;
4181        // `confirm: false` ⇒ dialog suppressed.
4182        let off: Manifest =
4183            serde_yaml::from_str(&format!("{base}  confirm: false\n")).expect("parse false");
4184        off.validate().expect("confirm: false validates");
4185        let c = off.client.unwrap().confirm.unwrap();
4186        assert!(!c.enabled);
4187        assert!(c.message.is_none());
4188
4189        // `confirm: true` ⇒ same as omitting (dialog shown, default message).
4190        let on: Manifest =
4191            serde_yaml::from_str(&format!("{base}  confirm: true\n")).expect("parse true");
4192        let c = on.client.unwrap().confirm.unwrap();
4193        assert!(c.enabled);
4194        assert!(c.message.is_none());
4195
4196        // Struct with only a message ⇒ enabled defaults true, custom text.
4197        let msg: Manifest = serde_yaml::from_str(&format!(
4198            "{base}  confirm:\n    message: \"再インストールには数分かかります。よろしいですか?\"\n"
4199        ))
4200        .expect("parse struct");
4201        msg.validate().expect("confirm message validates");
4202        let c = msg.client.unwrap().confirm.unwrap();
4203        assert!(c.enabled);
4204        assert_eq!(
4205            c.message.as_deref(),
4206            Some("再インストールには数分かかります。よろしいですか?")
4207        );
4208
4209        // Absent ⇒ None (historical default handled by the client).
4210        let none: Manifest = serde_yaml::from_str(base).expect("parse none");
4211        assert!(none.client.unwrap().confirm.is_none());
4212
4213        // Explicit `confirm: null` is schema-valid (the field is Option) and
4214        // must map to None, not a parse error (Gemini #960).
4215        let null: Manifest =
4216            serde_yaml::from_str(&format!("{base}  confirm: null\n")).expect("parse null");
4217        assert!(null.client.unwrap().confirm.is_none());
4218    }
4219
4220    #[test]
4221    fn manifest_client_confirm_rejects_blank_message() {
4222        // A present-but-blank custom message would render an empty dialog
4223        // title — validate() must reject it, like the other display fields.
4224        let yaml = r#"
4225id: j
4226version: 1.0.0
4227execute:
4228  shell: powershell
4229  script: "echo x"
4230  timeout: 30s
4231client:
4232  name: "A job"
4233  category: settings
4234  confirm:
4235    message: "   "
4236"#;
4237        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4238        let err = m.validate().expect_err("blank confirm.message must fail");
4239        assert!(err.contains("client.confirm.message"), "err: {err}");
4240    }
4241
4242    #[test]
4243    fn manifest_client_requires_category_at_parse() {
4244        // A `client:` block missing `category` is a hard parse error
4245        // (serde required field) — no manual validate() needed.
4246        let yaml = r#"
4247id: j
4248version: 1.0.0
4249execute:
4250  shell: powershell
4251  script: "echo x"
4252  timeout: 30s
4253client:
4254  name: "A job"
4255"#;
4256        let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
4257        assert!(
4258            r.is_err(),
4259            "missing category must be a parse error, got {r:?}"
4260        );
4261    }
4262
4263    #[test]
4264    fn manifest_client_rejects_unknown_field() {
4265        // #492: the strict create boundary catches a fat-fingered
4266        // `displayname:` (with its path) instead of silently
4267        // dropping it; the tolerant read path accepts it.
4268        let yaml = r#"
4269id: j
4270version: 1.0.0
4271execute:
4272  shell: powershell
4273  script: "echo x"
4274  timeout: 30s
4275client:
4276  name: "A job"
4277  category: catalog
4278  displayname: oops
4279"#;
4280        let r = crate::strict::from_yaml_str::<Manifest>(yaml);
4281        let err = r.expect_err("unknown client field must be rejected at the write boundary");
4282        // serde_ignored renders the Option layer as `?`:
4283        // `client.?.displayname`. Assert on the leaf key.
4284        assert!(err.contains("displayname"), "{err}");
4285        // The READ path tolerates the same payload (gradual-upgrade
4286        // contract: an old agent must accept a newer writer's field).
4287        let m: Manifest = serde_yaml::from_str(yaml).expect("tolerant read");
4288        assert_eq!(m.client.as_ref().map(|c| c.name.as_str()), Some("A job"));
4289    }
4290
4291    #[test]
4292    fn manifest_tags_default_empty() {
4293        // The overwhelming majority of jobs carry no tags; the field
4294        // must default to an empty Vec (not fail to parse) and skip
4295        // serialisation so old readers never see the key.
4296        let yaml = r#"
4297id: echo-test
4298version: 0.0.1
4299execute:
4300  shell: powershell
4301  script: "echo 'kanade'"
4302  timeout: 30s
4303"#;
4304        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4305        assert!(m.tags.is_empty());
4306        m.validate().expect("tag-less job validates");
4307        // skip_serializing_if = empty ⇒ the key is absent from JSON.
4308        let json = serde_json::to_string(&m).expect("serialize");
4309        assert!(
4310            !json.contains("tags"),
4311            "empty tags must not serialise: {json}"
4312        );
4313    }
4314
4315    #[test]
4316    fn manifest_parses_and_validates_tags() {
4317        let yaml = r#"
4318id: check-bitlocker
4319version: 0.1.0
4320execute:
4321  shell: powershell
4322  script: "echo x"
4323  timeout: 30s
4324tags: [security, windows, health-check]
4325"#;
4326        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4327        assert_eq!(m.tags, vec!["security", "windows", "health-check"]);
4328        m.validate().expect("tagged job validates");
4329        // Round-trips through JSON (the wire format the SPA reads).
4330        let json = serde_json::to_string(&m).expect("serialize");
4331        assert!(json.contains("\"tags\""), "non-empty tags must serialise");
4332    }
4333
4334    #[test]
4335    fn manifest_rejects_blank_tag() {
4336        // A whitespace-only tag renders an empty filter chip — reject
4337        // it at the write boundary like the other blank display fields.
4338        let yaml = r#"
4339id: j
4340version: 0.1.0
4341execute:
4342  shell: powershell
4343  script: "echo x"
4344  timeout: 30s
4345tags: [ok, "   "]
4346"#;
4347        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4348        let err = m.validate().expect_err("blank tag must fail");
4349        assert!(err.contains("tags must not contain empty"), "err: {err}");
4350    }
4351
4352    #[test]
4353    fn validate_rejects_unknown_tier_and_accepts_known() {
4354        let base =
4355            "id: t\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: x\n  timeout: 30s\n";
4356        // A typo / future tier decodes to Tier::Unknown (#[serde(other)]) and
4357        // must FAIL CLOSED — never fall back to unrestricted endpoint dispatch.
4358        let bogus: Manifest =
4359            serde_yaml::from_str(&format!("{base}tier: controler\n")).expect("parse");
4360        let err = bogus.validate().expect_err("unknown tier must be rejected");
4361        assert!(err.contains("tier"), "err: {err}");
4362        // The two known tiers pass.
4363        serde_yaml::from_str::<Manifest>(&format!("{base}tier: controller\n"))
4364            .unwrap()
4365            .validate()
4366            .expect("controller tier is valid");
4367        serde_yaml::from_str::<Manifest>(&format!("{base}tier: endpoint\n"))
4368            .unwrap()
4369            .validate()
4370            .expect("endpoint tier is valid");
4371    }
4372
4373    #[test]
4374    fn feed_payload_extracts_fenced_block() {
4375        let stdout = "fetched 1500 KEV entries\n\
4376            #KANADE-FEED-BEGIN\n\
4377            {\"vulnerabilities\": []}\n\
4378            #KANADE-FEED-END\n";
4379        assert_eq!(feed_payload(stdout), "{\"vulnerabilities\": []}");
4380    }
4381
4382    #[test]
4383    fn validate_feed_rules() {
4384        let base =
4385            "id: f\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: x\n  timeout: 30s\n";
4386        // A well-formed feed (controller implied; no explicit tier) passes.
4387        serde_yaml::from_str::<Manifest>(&format!(
4388            "{base}feed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4389        ))
4390        .unwrap()
4391        .validate()
4392        .expect("a well-formed feed is valid");
4393
4394        // Empty primary_key is rejected (no item_id → every row dropped).
4395        let err = serde_yaml::from_str::<Manifest>(&format!(
4396            "{base}feed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: []\n"
4397        ))
4398        .unwrap()
4399        .validate()
4400        .expect_err("empty primary_key must be rejected");
4401        assert!(err.contains("primary_key"), "err: {err}");
4402
4403        // A duplicate feed id clobbers a partition — rejected.
4404        let err = serde_yaml::from_str::<Manifest>(&format!(
4405            "{base}feed:\n  - id: dup\n    field: a\n    primary_key: [k]\n  - id: dup\n    field: b\n    primary_key: [k]\n"
4406        ))
4407        .unwrap()
4408        .validate()
4409        .expect_err("duplicate feed id must be rejected");
4410        assert!(err.contains("more than once"), "err: {err}");
4411
4412        // `feed:` + explicit `tier: endpoint` is contradictory — rejected.
4413        let err = serde_yaml::from_str::<Manifest>(&format!(
4414            "{base}tier: endpoint\nfeed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4415        ))
4416        .unwrap()
4417        .validate()
4418        .expect_err("feed + tier: endpoint must be rejected");
4419        assert!(err.contains("controller tier"), "err: {err}");
4420
4421        // `feed:` + `emit:` is incompatible — emit consumes stdout whole, so
4422        // the feed's fence never reaches the projector.
4423        let err = serde_yaml::from_str::<Manifest>(&format!(
4424            "{base}emit:\n  type: events\nfeed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4425        ))
4426        .unwrap()
4427        .validate()
4428        .expect_err("feed + emit must be rejected");
4429        assert!(err.contains("emit"), "err: {err}");
4430    }
4431
4432    // #720 — wrap an `aggregate:` YAML block (already indented as a
4433    // top-level key body) into an otherwise-minimal valid manifest.
4434    fn manifest_with_aggregate(aggregate_block: &str) -> Manifest {
4435        let yaml = format!(
4436            "id: t\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: echo hi\n  timeout: 30s\n{aggregate_block}"
4437        );
4438        serde_yaml::from_str(&yaml).expect("parse aggregate manifest")
4439    }
4440
4441    #[test]
4442    fn aggregate_accepts_full_valid_spec() {
4443        // count+group_by+exclude+sample_minutes, ratio+bool_path,
4444        // timeline+time_bucket, fleet ranking via group_by: pc_id, and a
4445        // bare total stat — alongside emit (composes with every hint).
4446        let m = manifest_with_aggregate(
4447            "emit:\n  type: events\naggregate:\n\
4448             - { dashboard: Utilization, title: Top apps, kind: app_sample, agg: count, group_by: foreground.app, sample_minutes: 2, exclude: [LockApp], render: bar }\n\
4449             - { dashboard: Utilization, title: Active ratio, kind: presence, agg: ratio, bool_path: active, sample_minutes: 5, render: gauge }\n\
4450             - { dashboard: Utilization, title: By hour, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: timeline }\n\
4451             - { dashboard: Reliability, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
4452             - { dashboard: Reliability, title: Total crashes, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
4453        );
4454        m.validate().expect("valid aggregate spec");
4455    }
4456
4457    #[test]
4458    fn aggregate_rejects_empty_list() {
4459        let m = manifest_with_aggregate("aggregate: []\n");
4460        let err = m.validate().expect_err("empty list must fail");
4461        assert!(err.contains("at least one widget"), "err: {err}");
4462    }
4463
4464    #[test]
4465    fn aggregate_rejects_ratio_without_bool_path() {
4466        let m = manifest_with_aggregate(
4467            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, render: gauge }\n",
4468        );
4469        let err = m.validate().expect_err("ratio needs bool_path");
4470        assert!(err.contains("agg=ratio requires `bool_path`"), "err: {err}");
4471    }
4472
4473    #[test]
4474    fn aggregate_rejects_sum_without_value_path() {
4475        let m = manifest_with_aggregate(
4476            "aggregate:\n- { dashboard: D, title: T, kind: io, agg: sum, render: bar }\n",
4477        );
4478        let err = m.validate().expect_err("sum needs value_path");
4479        assert!(err.contains("agg=sum requires `value_path`"), "err: {err}");
4480    }
4481
4482    #[test]
4483    fn aggregate_rejects_pc_id_group_without_fleet() {
4484        let m = manifest_with_aggregate(
4485            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: count, group_by: pc_id, render: bar }\n",
4486        );
4487        let err = m.validate().expect_err("pc_id grouping needs fleet");
4488        assert!(
4489            err.contains("pc_id is only valid with scope: fleet"),
4490            "err: {err}"
4491        );
4492    }
4493
4494    #[test]
4495    fn aggregate_rejects_transform_with_pc_id_group() {
4496        let m = manifest_with_aggregate(
4497            "aggregate:\n- { dashboard: D, title: T, scope: fleet, kind: web_visit, agg: count, group_by: pc_id, transform: host, render: bar }\n",
4498        );
4499        let err = m
4500            .validate()
4501            .expect_err("transform on pc_id grouping must fail");
4502        assert!(
4503            err.contains("transform is not valid with group_by: pc_id"),
4504            "err: {err}"
4505        );
4506    }
4507
4508    #[test]
4509    fn aggregate_rejects_timeline_without_bucket() {
4510        let m = manifest_with_aggregate(
4511            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, bool_path: active, render: timeline }\n",
4512        );
4513        let err = m.validate().expect_err("timeline needs a bucket");
4514        assert!(
4515            err.contains("render=timeline requires `time_bucket`"),
4516            "err: {err}"
4517        );
4518    }
4519
4520    #[test]
4521    fn aggregate_rejects_bucket_on_non_timeline() {
4522        let m = manifest_with_aggregate(
4523            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: gauge }\n",
4524        );
4525        let err = m.validate().expect_err("bucket only on timeline");
4526        assert!(
4527            err.contains("time_bucket is only valid with render: timeline"),
4528            "err: {err}"
4529        );
4530    }
4531
4532    #[test]
4533    fn aggregate_rejects_unsafe_json_path() {
4534        // A path with characters outside [A-Za-z0-9_.] could break out of
4535        // the `'$.' || ?` bind — reject at create time.
4536        let m = manifest_with_aggregate(
4537            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: \"foo'; DROP\", render: bar }\n",
4538        );
4539        let err = m.validate().expect_err("unsafe path must fail");
4540        assert!(err.contains("dotted JSON path"), "err: {err}");
4541    }
4542
4543    #[test]
4544    fn aggregate_rejects_blank_title() {
4545        let m = manifest_with_aggregate(
4546            "aggregate:\n- { dashboard: D, title: \"  \", kind: k, agg: count, render: stat }\n",
4547        );
4548        let err = m.validate().expect_err("blank title must fail");
4549        assert!(err.contains("title must not be empty"), "err: {err}");
4550    }
4551
4552    #[test]
4553    fn aggregate_rejects_blank_kind() {
4554        let m = manifest_with_aggregate(
4555            "aggregate:\n- { dashboard: D, title: T, kind: \" \", agg: count, render: stat }\n",
4556        );
4557        let err = m.validate().expect_err("blank kind must fail");
4558        assert!(err.contains("kind must not be empty"), "err: {err}");
4559    }
4560
4561    #[test]
4562    fn aggregate_rejects_blank_source_when_set() {
4563        let m = manifest_with_aggregate(
4564            "aggregate:\n- { dashboard: D, title: T, kind: k, source: \"\", agg: count, render: stat }\n",
4565        );
4566        let err = m.validate().expect_err("blank source must fail");
4567        assert!(
4568            err.contains("source must not be empty when set"),
4569            "err: {err}"
4570        );
4571    }
4572
4573    #[test]
4574    fn aggregate_accepts_description_and_rejects_blank() {
4575        let ok = manifest_with_aggregate(
4576            "aggregate:\n- { dashboard: D, title: T, description: \"samples x 2 min\", kind: k, agg: count, render: stat }\n",
4577        );
4578        ok.validate()
4579            .expect("description is a valid optional field");
4580        assert_eq!(
4581            ok.aggregate.as_ref().unwrap()[0].description.as_deref(),
4582            Some("samples x 2 min")
4583        );
4584        let bad = manifest_with_aggregate(
4585            "aggregate:\n- { dashboard: D, title: T, description: \"  \", kind: k, agg: count, render: stat }\n",
4586        );
4587        let err = bad.validate().expect_err("blank description must fail");
4588        assert!(
4589            err.contains("description must not be empty when set"),
4590            "err: {err}"
4591        );
4592    }
4593
4594    #[test]
4595    fn aggregate_rejects_count_with_value_path() {
4596        let m = manifest_with_aggregate(
4597            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, value_path: bytes, render: stat }\n",
4598        );
4599        let err = m.validate().expect_err("count must not use value_path");
4600        assert!(
4601            err.contains("agg=count does not use `value_path`"),
4602            "err: {err}"
4603        );
4604    }
4605
4606    #[test]
4607    fn aggregate_rejects_ratio_with_value_path() {
4608        let m = manifest_with_aggregate(
4609            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: ratio, bool_path: active, value_path: bytes, render: gauge }\n",
4610        );
4611        let err = m.validate().expect_err("ratio must not use value_path");
4612        assert!(
4613            err.contains("agg=ratio does not use `value_path`"),
4614            "err: {err}"
4615        );
4616    }
4617
4618    #[test]
4619    fn aggregate_rejects_gauge_without_ratio() {
4620        let m = manifest_with_aggregate(
4621            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, render: gauge }\n",
4622        );
4623        let err = m.validate().expect_err("gauge needs ratio");
4624        assert!(
4625            err.contains("render=gauge is only valid with agg: ratio"),
4626            "err: {err}"
4627        );
4628    }
4629
4630    #[test]
4631    fn aggregate_rejects_limit_without_group_by() {
4632        let m = manifest_with_aggregate(
4633            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, limit: 5, render: stat }\n",
4634        );
4635        let err = m.validate().expect_err("limit needs group_by");
4636        assert!(err.contains("limit requires `group_by`"), "err: {err}");
4637    }
4638
4639    #[test]
4640    fn aggregate_rejects_exclude_without_group_by() {
4641        let m = manifest_with_aggregate(
4642            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, exclude: [x], render: stat }\n",
4643        );
4644        let err = m.validate().expect_err("exclude needs group_by");
4645        assert!(err.contains("exclude requires `group_by`"), "err: {err}");
4646    }
4647
4648    #[test]
4649    fn aggregate_rejects_zero_limit_and_zero_sample_minutes() {
4650        let m = manifest_with_aggregate(
4651            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, limit: 0, render: bar }\n",
4652        );
4653        assert!(m.validate().unwrap_err().contains("limit must be > 0"));
4654        let m = manifest_with_aggregate(
4655            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, sample_minutes: 0, render: bar }\n",
4656        );
4657        assert!(
4658            m.validate()
4659                .unwrap_err()
4660                .contains("sample_minutes must be > 0")
4661        );
4662    }
4663
4664    #[test]
4665    fn aggregate_rejects_empty_exclude_entry() {
4666        let m = manifest_with_aggregate(
4667            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, exclude: [\"  \"], render: bar }\n",
4668        );
4669        let err = m.validate().expect_err("blank exclude entry must fail");
4670        assert!(
4671            err.contains("exclude must not contain empty entries"),
4672            "err: {err}"
4673        );
4674    }
4675
4676    #[test]
4677    fn aggregate_rejects_malformed_dotted_paths() {
4678        for bad in [".foo", "foo.", "foo..bar", "."] {
4679            let m = manifest_with_aggregate(&format!(
4680                "aggregate:\n- {{ dashboard: D, title: T, kind: k, agg: count, group_by: \"{bad}\", render: bar }}\n"
4681            ));
4682            let err = m.validate().expect_err("malformed path must fail");
4683            assert!(err.contains("dotted JSON path"), "path {bad}: {err}");
4684        }
4685    }
4686
4687    #[test]
4688    fn aggregate_rejects_unknown_enum_value() {
4689        // An unrecognised render string deserialises to the #492 Unknown
4690        // catch-all (so old readers don't choke); validate() rejects it as
4691        // a typo at create time.
4692        let m = manifest_with_aggregate(
4693            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, render: heatmap }\n",
4694        );
4695        let err = m.validate().expect_err("unknown render must fail");
4696        assert!(err.contains("render is not a known value"), "err: {err}");
4697    }
4698
4699    #[test]
4700    fn aggregate_accepts_order_field() {
4701        let m = manifest_with_aggregate(
4702            "aggregate:\n- { dashboard: D, title: T, order: -5, kind: k, agg: count, render: stat }\n",
4703        );
4704        m.validate().expect("order is a valid optional field");
4705        let w = &m.aggregate.as_ref().unwrap()[0];
4706        assert_eq!(w.order, Some(-5));
4707    }
4708
4709    #[test]
4710    fn aggregate_accepts_minimal_op_timeline() {
4711        // op_timeline needs no kind/agg — it reconstructs a fixed multi-kind
4712        // swimlane. A bare per-PC spec is valid, and `kind`/`agg` stay None.
4713        let m = manifest_with_aggregate(
4714            "aggregate:\n- { dashboard: Uptime, title: Operational state, scope: pc, render: op_timeline }\n",
4715        );
4716        m.validate().expect("minimal op_timeline is valid");
4717        let w = &m.aggregate.as_ref().unwrap()[0];
4718        assert_eq!(w.render, AggregateRender::OpTimeline);
4719        assert!(w.kind.is_none());
4720        assert!(w.agg.is_none());
4721    }
4722
4723    #[test]
4724    fn aggregate_rejects_op_timeline_with_fleet_scope() {
4725        let m = manifest_with_aggregate(
4726            "aggregate:\n- { dashboard: Uptime, title: T, scope: fleet, render: op_timeline }\n",
4727        );
4728        let err = m.validate().expect_err("op_timeline must be per-PC");
4729        assert!(
4730            err.contains("render=op_timeline requires scope: pc"),
4731            "err: {err}"
4732        );
4733    }
4734
4735    #[test]
4736    fn aggregate_rejects_op_timeline_with_aggregation_fields() {
4737        // Each aggregation knob the operator might paste in is rejected
4738        // (rather than silently ignored), pointing at the field to delete.
4739        for (block, field) in [
4740            ("kind: boot", "kind"),
4741            ("agg: count", "agg"),
4742            ("source: winlog:Security", "source"),
4743            ("group_by: pc_id", "group_by"),
4744            ("bool_path: active", "bool_path"),
4745            ("time_bucket: hour", "time_bucket"),
4746            ("limit: 5", "limit"),
4747        ] {
4748            let m = manifest_with_aggregate(&format!(
4749                "aggregate:\n- {{ dashboard: Uptime, title: T, scope: pc, {block}, render: op_timeline }}\n"
4750            ));
4751            let err = m
4752                .validate()
4753                .expect_err(&format!("op_timeline must reject {field}"));
4754            assert!(
4755                err.contains(&format!("render=op_timeline does not use `{field}`")),
4756                "field {field}: {err}"
4757            );
4758        }
4759    }
4760
4761    // ── #743 View resource ───────────────────────────────────────────
4762    fn view_from(yaml_body: &str) -> View {
4763        serde_yaml::from_str(&format!("id: v1\n{yaml_body}")).expect("parse view")
4764    }
4765
4766    #[test]
4767    fn view_accepts_valid_widgets() {
4768        let v = view_from(
4769            "widgets:\n\
4770             - { dashboard: Reliability, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
4771             - { dashboard: Reliability, title: Total, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
4772        );
4773        v.validate().expect("valid view");
4774    }
4775
4776    #[test]
4777    fn view_rejects_empty_widgets() {
4778        let v = view_from("widgets: []\n");
4779        let err = v.validate().expect_err("empty widgets must fail");
4780        assert!(err.contains("at least one widget"), "err: {err}");
4781    }
4782
4783    #[test]
4784    fn view_rejects_blank_id() {
4785        let v: View = serde_yaml::from_str(
4786            "id: \"  \"\nwidgets:\n- { dashboard: D, title: T, kind: k, agg: count, render: stat }\n",
4787        )
4788        .expect("parse");
4789        let err = v.validate().expect_err("blank id must fail");
4790        assert!(err.contains("view.id must"), "err: {err}");
4791    }
4792
4793    #[test]
4794    fn view_rejects_unsafe_id() {
4795        // A `/` or `..` in the id would break the KV key and the
4796        // `/api/views/{id}` URL segment — reject at create time.
4797        for bad in ["../etc", "a/b", "has space", "x;y"] {
4798            let v: View = serde_yaml::from_str(&format!(
4799                "id: \"{bad}\"\nwidgets:\n- {{ dashboard: D, title: T, kind: k, agg: count, render: stat }}\n",
4800            ))
4801            .expect("parse");
4802            let err = v.validate().expect_err("unsafe id must fail");
4803            assert!(err.contains("[A-Za-z0-9._-]"), "id {bad}: {err}");
4804        }
4805        assert!(is_valid_resource_id("dashboards-fleet.v1_2"));
4806    }
4807
4808    #[test]
4809    fn view_rejects_untrimmed_id() {
4810        // A padded id validated-as-trimmed but stored-raw would be a KV key
4811        // (and `/api/views/{id}` segment) nothing matches — reject it outright
4812        // (the id is used verbatim).
4813        let v: View = serde_yaml::from_str(
4814            "id: \" my-view \"\nwidgets:\n- { dashboard: D, title: T, kind: k, agg: count, render: stat }\n",
4815        )
4816        .expect("parse");
4817        let err = v.validate().expect_err("padded id must fail");
4818        assert!(err.contains("view.id must"), "err: {err}");
4819    }
4820
4821    #[test]
4822    fn view_reuses_shared_widget_validation() {
4823        // The same per-widget rule the job hint enforces (ratio needs
4824        // bool_path), reported under the `widgets[..]` field.
4825        let v = view_from(
4826            "widgets:\n- { dashboard: D, title: T, kind: presence, agg: ratio, render: gauge }\n",
4827        );
4828        let err = v.validate().expect_err("ratio without bool_path must fail");
4829        assert!(
4830            err.contains("widgets[0].agg=ratio requires `bool_path`"),
4831            "err: {err}"
4832        );
4833    }
4834
4835    // ── #vuln-roadmap PR3 SQL-backed views ───────────────────────────
4836    #[test]
4837    fn view_accepts_pure_sql_widgets() {
4838        // A view with only sql_widgets (no obs_events aggregate widgets) is
4839        // valid — the vulnerability-dashboard shape.
4840        let v = view_from(
4841            "sql_widgets:
4842  - title: KEV-affected hosts
4843    query: \"SELECT pc_id, 1 AS cves FROM inventory_sw_apps\"
4844    refresh: 6h
4845    render: { kind: table, columns: [pc_id, cves], labels: { cves: CVE count } }
4846    placement: { analytics: Security, dashboard: { pin: true } }
4847",
4848        );
4849        v.validate().expect("valid sql view");
4850        // refresh parses; pin/tab helpers read the placement.
4851        let w = &v.sql_widgets[0];
4852        assert_eq!(
4853            w.refresh_interval(),
4854            std::time::Duration::from_secs(6 * 3600)
4855        );
4856        assert!(w.placement.is_pinned());
4857        assert_eq!(w.placement.tab(), "Security");
4858    }
4859
4860    #[test]
4861    fn sql_widget_defaults_and_mix() {
4862        // No refresh ⇒ default; a view can mix aggregate + sql widgets.
4863        let v = view_from(
4864            "widgets:
4865  - { dashboard: D, title: T, kind: k, agg: count, render: stat }
4866sql_widgets:
4867  - title: N affected
4868    query: \"SELECT count(*) AS n FROM feeds\"
4869    render: { kind: stat, value: n }
4870    placement: { dashboard: { pin: true } }
4871",
4872        );
4873        v.validate().expect("mixed view is valid");
4874        assert_eq!(v.sql_widgets[0].refresh_interval(), DEFAULT_VIEW_REFRESH);
4875        // dashboard-only placement (no analytics tab) falls back to a label.
4876        assert_eq!(v.sql_widgets[0].placement.tab(), "Dashboard");
4877    }
4878
4879    #[test]
4880    fn sql_widget_validation_rules() {
4881        // helper: build a view with one sql_widget from an inline render+placement
4882        let mk = |render: &str, placement: &str| -> Result<(), String> {
4883            view_from(&format!(
4884                "sql_widgets:
4885  - title: W
4886    query: \"SELECT 1 AS a\"
4887    render: {render}
4888    placement: {placement}
4889"
4890            ))
4891            .validate()
4892        };
4893        // bar needs label + value
4894        let err = mk("{ kind: bar, value: a }", "{ analytics: T }").unwrap_err();
4895        assert!(
4896            err.contains("render.label is required for kind=bar"),
4897            "err: {err}"
4898        );
4899        // pie needs value
4900        let err = mk("{ kind: pie, label: a }", "{ analytics: T }").unwrap_err();
4901        assert!(
4902            err.contains("render.value is required for kind=pie"),
4903            "err: {err}"
4904        );
4905        // stat needs value
4906        let err = mk("{ kind: stat }", "{ analytics: T }").unwrap_err();
4907        assert!(
4908            err.contains("render.value is required for kind=stat"),
4909            "err: {err}"
4910        );
4911        // gauge needs value XOR num+den
4912        let err = mk("{ kind: gauge, num: a }", "{ analytics: T }").unwrap_err();
4913        assert!(err.contains("needs either `value`"), "err: {err}");
4914        mk("{ kind: gauge, value: a }", "{ analytics: T }").expect("gauge value ok");
4915        mk("{ kind: gauge, num: a, den: a }", "{ analytics: T }").expect("gauge num/den ok");
4916        // unknown kind rejected
4917        let err = mk("{ kind: sunburst }", "{ analytics: T }").unwrap_err();
4918        assert!(
4919            err.contains("render.kind is not a known value"),
4920            "err: {err}"
4921        );
4922        // placement must surface somewhere
4923        let err = mk("{ kind: table }", "{}").unwrap_err();
4924        assert!(err.contains("placement must set"), "err: {err}");
4925        // a `dashboard: { pin: false }` block still surfaces nowhere.
4926        let err = mk("{ kind: table }", "{ dashboard: { pin: false } }").unwrap_err();
4927        assert!(err.contains("placement must set"), "err: {err}");
4928        mk("{ kind: table }", "{ dashboard: { pin: true } }").expect("pinned dashboard ok");
4929        // limit: 0 on a bar/pie is an invisible widget — rejected.
4930        let err = mk(
4931            "{ kind: bar, label: a, value: a, limit: 0 }",
4932            "{ analytics: T }",
4933        )
4934        .unwrap_err();
4935        assert!(err.contains("limit must be >= 1"), "err: {err}");
4936        // bad refresh duration rejected
4937        let err = view_from(
4938            "sql_widgets:
4939  - { title: W, query: \"SELECT 1\", refresh: \"6 sidereal days\", render: { kind: table }, placement: { analytics: T } }
4940",
4941        )
4942        .validate()
4943        .unwrap_err();
4944        assert!(
4945            err.contains("refresh") && err.contains("not a valid duration"),
4946            "err: {err}"
4947        );
4948        // table is fine with no channels
4949        mk("{ kind: table }", "{ analytics: T }").expect("bare table ok");
4950    }
4951
4952    #[test]
4953    fn rewrite_pc_id_param_is_literal_and_boundary_aware() {
4954        // A real param outside any literal is rewritten + counted.
4955        let (sql, n) = rewrite_pc_id_param("SELECT * FROM t WHERE pc_id = :pc_id");
4956        assert_eq!(n, 1);
4957        assert!(sql.ends_with("pc_id = ?"), "sql: {sql}");
4958        // Appearing twice → two `?`, count 2 (one bind each — the caller binds
4959        // pc_id per occurrence since sqlx-sqlite has no named params).
4960        let (sql, n) = rewrite_pc_id_param("WHERE a = :pc_id AND (:pc_id IS NOT NULL)");
4961        assert_eq!(n, 2);
4962        assert_eq!(sql, "WHERE a = ? AND (? IS NOT NULL)");
4963        // Inside a string literal → copied verbatim, NOT counted (would else be
4964        // a bind-count mismatch → SQLITE_RANGE, and misclassify scope).
4965        let (sql, n) = rewrite_pc_id_param("SELECT 'see :pc_id docs' AS hint");
4966        assert_eq!(n, 0);
4967        assert_eq!(sql, "SELECT 'see :pc_id docs' AS hint");
4968        // Inside a comment → left alone.
4969        let (_, n) = rewrite_pc_id_param("SELECT 1 -- filter by :pc_id\n");
4970        assert_eq!(n, 0);
4971        // A longer identifier prefix (`:pc_idx`) is not our token.
4972        let (sql, n) = rewrite_pc_id_param("WHERE x = :pc_idx");
4973        assert_eq!(n, 0);
4974        assert_eq!(sql, "WHERE x = :pc_idx");
4975    }
4976
4977    #[test]
4978    fn validate_rejects_pinned_per_pc_widget() {
4979        // A per-PC widget (binds :pc_id) that also pins to the Dashboard is a
4980        // create-time contradiction (Dashboard is fleet-scope) — rejected.
4981        let err = view_from(
4982            "sql_widgets:
4983  - title: W
4984    query: \"SELECT count(*) AS n FROM inventory_sw_apps WHERE pc_id = :pc_id\"
4985    render: { kind: stat, value: n }
4986    placement: { analytics: Security, dashboard: { pin: true } }
4987",
4988        )
4989        .validate()
4990        .unwrap_err();
4991        assert!(err.contains("per-PC widget"), "err: {err}");
4992        // The same widget WITHOUT the pin is fine (per-PC, analytics only).
4993        view_from(
4994            "sql_widgets:
4995  - title: W
4996    query: \"SELECT count(*) AS n FROM inventory_sw_apps WHERE pc_id = :pc_id\"
4997    render: { kind: stat, value: n }
4998    placement: { analytics: Security }
4999",
5000        )
5001        .validate()
5002        .expect("per-PC analytics-only widget is valid");
5003    }
5004
5005    fn execute_with(
5006        script: Option<&str>,
5007        script_file: Option<&str>,
5008        script_object: Option<&str>,
5009    ) -> Execute {
5010        Execute {
5011            shell: ExecuteShell::Powershell,
5012            script: script.map(str::to_owned),
5013            script_file: script_file.map(str::to_owned),
5014            script_object: script_object.map(str::to_owned),
5015            timeout: "30s".into(),
5016            run_as: RunAs::default(),
5017            cwd: None,
5018        }
5019    }
5020
5021    #[test]
5022    fn validate_accepts_inline_script() {
5023        let e = execute_with(Some("echo hi"), None, None);
5024        assert!(e.validate_script_source().is_ok());
5025    }
5026
5027    #[test]
5028    fn validate_accepts_script_file_alone() {
5029        let e = execute_with(None, Some("scripts/cleanup.ps1"), None);
5030        assert!(e.validate_script_source().is_ok());
5031    }
5032
5033    #[test]
5034    fn validate_accepts_script_object_alone() {
5035        let e = execute_with(None, None, Some("cleanup/1.0.0"));
5036        assert!(e.validate_script_source().is_ok());
5037    }
5038
5039    #[test]
5040    fn validate_treats_empty_inline_script_as_unset() {
5041        // `script: ""` + `script_object` set is the natural shape
5042        // when an operator comments out the YAML block-scalar body
5043        // but leaves the key. Should pass.
5044        let e = execute_with(Some(""), None, Some("cleanup/1.0.0"));
5045        assert!(e.validate_script_source().is_ok());
5046    }
5047
5048    #[test]
5049    fn validate_rejects_zero_sources() {
5050        let e = execute_with(None, None, None);
5051        let err = e.validate_script_source().unwrap_err();
5052        assert!(err.contains("must be set"), "got: {err}");
5053    }
5054
5055    #[test]
5056    fn validate_rejects_empty_inline_only() {
5057        let e = execute_with(Some(""), None, None);
5058        let err = e.validate_script_source().unwrap_err();
5059        assert!(err.contains("must be set"), "got: {err}");
5060    }
5061
5062    #[test]
5063    fn validate_rejects_inline_plus_file() {
5064        let e = execute_with(Some("echo hi"), Some("scripts/cleanup.ps1"), None);
5065        let err = e.validate_script_source().unwrap_err();
5066        assert!(err.contains("only one of"), "got: {err}");
5067    }
5068
5069    #[test]
5070    fn validate_rejects_inline_plus_object() {
5071        let e = execute_with(Some("echo hi"), None, Some("cleanup/1.0.0"));
5072        let err = e.validate_script_source().unwrap_err();
5073        assert!(err.contains("only one of"), "got: {err}");
5074    }
5075
5076    #[test]
5077    fn validate_rejects_file_plus_object() {
5078        let e = execute_with(None, Some("scripts/cleanup.ps1"), Some("cleanup/1.0.0"));
5079        let err = e.validate_script_source().unwrap_err();
5080        assert!(err.contains("only one of"), "got: {err}");
5081    }
5082
5083    #[test]
5084    fn validate_rejects_all_three() {
5085        let e = execute_with(
5086            Some("echo hi"),
5087            Some("scripts/cleanup.ps1"),
5088            Some("cleanup/1.0.0"),
5089        );
5090        let err = e.validate_script_source().unwrap_err();
5091        assert!(err.contains("only one of"), "got: {err}");
5092    }
5093
5094    #[test]
5095    fn validate_rejects_blank_script_file() {
5096        // #918: a blank `script_file` used to count as "set" and pass
5097        // the exactly-one check, then fail at use time (the CLI reads
5098        // a file named "").
5099        for blank in ["", "   "] {
5100            let e = execute_with(None, Some(blank), None);
5101            let err = e.validate_script_source().unwrap_err();
5102            assert!(err.contains("script_file must not be blank"), "got: {err}");
5103        }
5104    }
5105
5106    #[test]
5107    fn validate_rejects_blank_script_object() {
5108        // #918: same for a blank `script_object` (would 404 every exec).
5109        for blank in ["", "   "] {
5110            let e = execute_with(None, None, Some(blank));
5111            let err = e.validate_script_source().unwrap_err();
5112            assert!(
5113                err.contains("script_object must not be blank"),
5114                "got: {err}"
5115            );
5116        }
5117    }
5118
5119    #[test]
5120    fn validate_treats_whitespace_inline_script_as_unset() {
5121        // #918: a whitespace-only inline body is a commented-out block,
5122        // not a real script — with no other source it's "zero sources".
5123        let e = execute_with(Some("   \n  "), None, None);
5124        let err = e.validate_script_source().unwrap_err();
5125        assert!(err.contains("must be set"), "got: {err}");
5126    }
5127
5128    #[test]
5129    fn validate_rejects_malformed_script_object_ref() {
5130        // #918: the ref must be `<name>/<version>`; a missing slash,
5131        // extra slash, blank half, or whitespace-padded half (the last
5132        // survives a JSON POST body and 404s at exec — gemini/claude
5133        // #943) can never resolve.
5134        for bad in [
5135            "no-slash", "a/b/c", "/1.0.0", "cleanup/", " / ", "foo/bar ", " foo/bar", "foo /bar",
5136        ] {
5137            let e = execute_with(None, None, Some(bad));
5138            let err = e.validate_script_source().unwrap_err();
5139            assert!(
5140                err.contains("must be `<name>/<version>`"),
5141                "for '{bad}', got: {err}"
5142            );
5143        }
5144    }
5145
5146    #[test]
5147    fn manifest_deserialises_script_object_yaml() {
5148        // SPEC §2.4.1 example shape with the Object Store
5149        // reference picked over inline.
5150        let yaml = r#"
5151id: cleanup-disk-temp
5152version: 1.0.1
5153execute:
5154  shell: powershell
5155  script_object: cleanup-disk-temp/1.0.1
5156  timeout: 600s
5157"#;
5158        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
5159        assert_eq!(
5160            m.execute.script_object.as_deref(),
5161            Some("cleanup-disk-temp/1.0.1")
5162        );
5163        assert!(m.execute.script.is_none());
5164        m.validate()
5165            .expect("script_object-only manifest passes validation");
5166    }
5167
5168    #[test]
5169    fn manifest_rejects_typo_in_script_field_name() {
5170        // #492: the strict create boundary catches `script_objectt`
5171        // and similar fat-fingers (with the full path) instead of
5172        // letting them silently fall through to "all three unset".
5173        let yaml = r#"
5174id: typo
5175version: 1.0.0
5176execute:
5177  shell: powershell
5178  script_objectt: oops
5179  timeout: 30s
5180"#;
5181        let err = crate::strict::from_yaml_str::<Manifest>(yaml)
5182            .expect_err("typo'd execute field must be rejected at the write boundary");
5183        assert!(err.contains("execute.script_objectt"), "{err}");
5184    }
5185
5186    #[test]
5187    fn schedule_carries_target_and_rollout() {
5188        let yaml = r#"
5189id: hourly-cleanup-canary
5190when:
5191  per_pc: { every: 1h }
5192job_id: cleanup
5193enabled: true
5194target:
5195  groups: [canary, wave1]
5196jitter: 30s
5197rollout:
5198  strategy: wave
5199  waves:
5200    - { group: canary, delay: 0s }
5201    - { group: wave1,  delay: 5s }
5202"#;
5203        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5204        assert_eq!(s.id, "hourly-cleanup-canary");
5205        assert_eq!(s.job_id, "cleanup");
5206        assert_eq!(s.plan.target.groups, vec!["canary", "wave1"]);
5207        assert_eq!(s.plan.jitter.as_deref(), Some("30s"));
5208        let rollout = s.plan.rollout.expect("rollout present");
5209        assert_eq!(rollout.waves.len(), 2);
5210        assert_eq!(rollout.waves[0].group, "canary");
5211        assert_eq!(rollout.waves[1].delay, "5s");
5212        assert_eq!(rollout.strategy, RolloutStrategy::Wave);
5213    }
5214
5215    #[test]
5216    fn schedule_minimal_target_all() {
5217        let yaml = r#"
5218id: kitting
5219when:
5220  per_pc: once
5221enabled: true
5222job_id: scheduled-echo
5223target: { all: true }
5224"#;
5225        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5226        assert_eq!(s.id, "kitting");
5227        assert_eq!(s.when, When::PerPc(PerPolicy::Once(OnceLiteral::Once)));
5228        assert!(s.enabled);
5229        assert_eq!(s.job_id, "scheduled-echo");
5230        assert!(s.plan.target.all);
5231        assert!(s.plan.rollout.is_none());
5232        assert!(s.plan.jitter.is_none());
5233        assert!(s.active.is_empty());
5234    }
5235
5236    #[test]
5237    fn schedule_enabled_defaults_to_true() {
5238        let yaml = r#"
5239id: x
5240when:
5241  per_pc: once
5242job_id: y
5243target: { all: true }
5244"#;
5245        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5246        assert!(s.enabled);
5247    }
5248
5249    fn once_per_version_yaml(runs_on: &str, per: &str) -> String {
5250        format!(
5251            "id: x\nwhen:\n  {per}\njob_id: install-kanade-client\n\
5252             target: {{ groups: [dejisen] }}\nruns_on: {runs_on}\n"
5253        )
5254    }
5255
5256    #[test]
5257    fn per_pc_once_per_version_parses() {
5258        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5259            "backend",
5260            "per_pc: once_per_version",
5261        ))
5262        .expect("parse");
5263        assert_eq!(
5264            s.when,
5265            When::PerPc(PerPolicy::OncePerVersion(
5266                OncePerVersionLiteral::OncePerVersion
5267            ))
5268        );
5269    }
5270
5271    #[test]
5272    fn per_pc_once_per_version_lowers_to_version_mode_no_cooldown() {
5273        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5274            "backend",
5275            "per_pc: once_per_version",
5276        ))
5277        .expect("parse");
5278        let l = s.lowered();
5279        assert_eq!(l.mode, ExecMode::OncePerPcVersion);
5280        assert_eq!(l.cooldown, None, "version re-arm is not a cooldown");
5281    }
5282
5283    #[test]
5284    fn once_per_version_displays_and_serialises() {
5285        let w = When::PerPc(PerPolicy::OncePerVersion(
5286            OncePerVersionLiteral::OncePerVersion,
5287        ));
5288        assert_eq!(w.to_string(), "per_pc once_per_version");
5289        // serde round-trips through the ergonomic bare string.
5290        let json = serde_json::to_value(&w).unwrap();
5291        assert_eq!(json, serde_json::json!({ "per_pc": "once_per_version" }));
5292    }
5293
5294    #[test]
5295    fn once_per_version_rejects_typo() {
5296        // The distinct literal still catches typos (no free-form String).
5297        let r: Result<Schedule, _> = serde_yaml::from_str(&once_per_version_yaml(
5298            "backend",
5299            "per_pc: once_per_verison",
5300        ));
5301        assert!(r.is_err(), "typo should not parse");
5302    }
5303
5304    #[test]
5305    fn validate_accepts_once_per_version_on_backend() {
5306        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5307            "backend",
5308            "per_pc: once_per_version",
5309        ))
5310        .expect("parse");
5311        assert!(s.validate().is_ok(), "got: {:?}", s.validate());
5312    }
5313
5314    #[test]
5315    fn validate_rejects_once_per_version_on_agent() {
5316        let s: Schedule =
5317            serde_yaml::from_str(&once_per_version_yaml("agent", "per_pc: once_per_version"))
5318                .expect("parse");
5319        let err = s
5320            .validate()
5321            .expect_err("agent + once_per_version must be rejected");
5322        assert!(err.contains("once_per_version"), "got: {err}");
5323        assert!(err.contains("backend"), "got: {err}");
5324    }
5325
5326    #[test]
5327    fn validate_rejects_once_per_version_on_per_target() {
5328        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5329            "backend",
5330            "per_target: once_per_version",
5331        ))
5332        .expect("parse");
5333        let err = s
5334            .validate()
5335            .expect_err("per_target + once_per_version must be rejected");
5336        assert!(err.contains("once_per_version"), "got: {err}");
5337        assert!(err.contains("per_pc"), "got: {err}");
5338    }
5339
5340    #[test]
5341    fn schedule_tags_default_empty_and_skip_serialise() {
5342        let yaml = r#"
5343id: x
5344when:
5345  per_pc: once
5346job_id: y
5347target: { all: true }
5348"#;
5349        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5350        assert!(s.tags.is_empty());
5351        s.validate().expect("tag-less schedule validates");
5352        let json = serde_json::to_string(&s).expect("serialize");
5353        assert!(
5354            !json.contains("tags"),
5355            "empty tags must not serialise: {json}"
5356        );
5357    }
5358
5359    #[test]
5360    fn schedule_parses_and_validates_tags() {
5361        let yaml = r#"
5362id: weekly-cleanup
5363when:
5364  per_pc: { every: 1h }
5365job_id: cleanup
5366target: { all: true }
5367tags: [weekly, maintenance]
5368"#;
5369        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5370        assert_eq!(s.tags, vec!["weekly", "maintenance"]);
5371        s.validate().expect("tagged schedule validates");
5372    }
5373
5374    #[test]
5375    fn schedule_rejects_blank_tag() {
5376        let yaml = r#"
5377id: x
5378when:
5379  per_pc: once
5380job_id: y
5381target: { all: true }
5382tags: [ok, "  "]
5383"#;
5384        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5385        let err = s.validate().expect_err("blank tag must fail");
5386        assert!(err.contains("tags must not contain empty"), "err: {err}");
5387    }
5388
5389    // ---- `when` parsing (#418 Phase 1) ----
5390
5391    fn schedule_yaml_with(when_block: &str) -> String {
5392        format!(
5393            r#"
5394id: x
5395when:
5396{when_block}
5397job_id: y
5398target: {{ all: true }}
5399"#
5400        )
5401    }
5402
5403    #[test]
5404    fn when_per_pc_every_parses_unquoted_humantime() {
5405        // `6h` is digit-led but non-numeric → YAML string, same as
5406        // the old `cooldown: 6h` convention. No quotes needed.
5407        let s: Schedule =
5408            serde_yaml::from_str(&schedule_yaml_with("  per_pc: { every: 6h }")).expect("parse");
5409        assert_eq!(
5410            s.when,
5411            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() }))
5412        );
5413    }
5414
5415    #[test]
5416    fn when_per_target_every_parses() {
5417        let s: Schedule = serde_yaml::from_str(&schedule_yaml_with("  per_target: { every: 24h }"))
5418            .expect("parse");
5419        assert_eq!(
5420            s.when,
5421            When::PerTarget(PerPolicy::Every(EverySpec {
5422                every: "24h".into()
5423            }))
5424        );
5425    }
5426
5427    #[test]
5428    fn when_per_target_once_parses() {
5429        // Falls out of the shared PerPolicy shape and decide_fire
5430        // already implements it ("any one pc succeeds → skip the
5431        // target forever"), so it is allowed, not rejected.
5432        let s: Schedule =
5433            serde_yaml::from_str(&schedule_yaml_with("  per_target: once")).expect("parse");
5434        assert_eq!(s.when, When::PerTarget(PerPolicy::Once(OnceLiteral::Once)));
5435    }
5436
5437    #[test]
5438    fn when_calendar_time_parses() {
5439        let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(
5440            "  calendar:\n    at: \"09:00\"\n    days: [mon-fri]",
5441        ))
5442        .expect("parse");
5443        match &s.when {
5444            When::Calendar(c) => {
5445                assert_eq!(c.at, "09:00");
5446                assert_eq!(c.days, vec!["mon-fri"]);
5447            }
5448            other => panic!("expected calendar, got {other:?}"),
5449        }
5450    }
5451
5452    #[test]
5453    fn when_calendar_days_default_empty() {
5454        let s: Schedule =
5455            serde_yaml::from_str(&schedule_yaml_with("  calendar:\n    at: \"09:00\""))
5456                .expect("parse");
5457        match &s.when {
5458            When::Calendar(c) => assert!(c.days.is_empty(), "days defaults to empty (= daily)"),
5459            other => panic!("expected calendar, got {other:?}"),
5460        }
5461    }
5462
5463    #[test]
5464    fn when_calendar_datetime_parses_all_separators() {
5465        // one-shot: date+time in hyphen / ISO-T / slash forms
5466        for at in ["2026-06-10 09:00", "2026-06-10T09:00", "2026/06/10 09:00"] {
5467            let block = format!("  calendar:\n    at: \"{at}\"");
5468            let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(&block))
5469                .unwrap_or_else(|e| panic!("parse '{at}': {e}"));
5470            match &s.when {
5471                When::Calendar(c) => {
5472                    use chrono::Datelike;
5473                    let p = c.parse_at().expect("parse_at");
5474                    let d = p.date.expect("datetime at carries a date");
5475                    assert_eq!((d.year(), d.month(), d.day()), (2026, 6, 10), "for '{at}'");
5476                }
5477                other => panic!("expected calendar, got {other:?}"),
5478            }
5479        }
5480    }
5481
5482    #[test]
5483    fn when_rejects_bad_once_keyword() {
5484        // `onec` must be a parse error, not a silently-absorbed
5485        // string (OnceLiteral is a single-variant enum for exactly
5486        // this reason).
5487        let r: Result<Schedule, _> = serde_yaml::from_str(&schedule_yaml_with("  per_pc: onec"));
5488        assert!(r.is_err(), "expected parse error, got {r:?}");
5489    }
5490
5491    #[test]
5492    fn when_rejects_unknown_key_in_every() {
5493        // `{ evry: 6h }` still fails on the tolerant read path: the
5494        // required `every` key is missing, so no PerPolicy variant
5495        // matches (#492 removed deny_unknown_fields, but required
5496        // keys keep the untagged disambiguation honest).
5497        let r: Result<Schedule, _> =
5498            serde_yaml::from_str(&schedule_yaml_with("  per_pc: { evry: 6h }"));
5499        assert!(r.is_err(), "expected parse error, got {r:?}");
5500    }
5501
5502    #[test]
5503    fn when_rejects_unknown_variant() {
5504        let r: Result<Schedule, _> =
5505            serde_yaml::from_str(&schedule_yaml_with("  per_galaxy: once"));
5506        assert!(r.is_err(), "expected parse error, got {r:?}");
5507    }
5508
5509    #[test]
5510    fn when_rejects_old_top_level_cron_field() {
5511        // Pre-#418 shape: top-level `cron:` + no `when:`. Must fail
5512        // loudly (missing `when`), which is what turns stale KV
5513        // blobs into warn-skips after the upgrade.
5514        let yaml = r#"
5515id: x
5516cron: "* * * * * *"
5517job_id: y
5518target: { all: true }
5519"#;
5520        let r: Result<Schedule, _> = serde_yaml::from_str(yaml);
5521        assert!(r.is_err(), "expected parse error, got {r:?}");
5522    }
5523
5524    #[test]
5525    fn when_rejects_retired_cron_escape_hatch() {
5526        // #418 Phase 2 retired `when: { cron: "..." }`. A raw cron
5527        // is now an unknown variant → parse error (operators use the
5528        // calendar form instead).
5529        let r: Result<Schedule, _> =
5530            serde_yaml::from_str(&schedule_yaml_with("  cron: \"0 0 9 * * mon-fri\""));
5531        assert!(
5532            r.is_err(),
5533            "expected parse error for retired cron, got {r:?}"
5534        );
5535    }
5536
5537    #[test]
5538    fn when_round_trips_json_and_yaml() {
5539        // Round-trip through the full Schedule: that is the wire
5540        // unit for both stores (JSON catalog KV + YAML mirror), and
5541        // it exercises the singleton_map field attribute that keeps
5542        // serde_yaml on the map shape instead of `!per_pc` tags.
5543        for when in [
5544            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5545            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5546            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5547            When::PerTarget(PerPolicy::Every(EverySpec {
5548                every: "24h".into(),
5549            })),
5550            calendar("09:00", &["mon-fri"]),
5551            calendar("2026-06-10 09:00", &[]),
5552            When::On(vec![OnTrigger::Startup]),
5553            When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
5554            When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
5555            When::On(vec![OnTrigger::NetworkChange]),
5556        ] {
5557            // Event triggers are agent-only; the rest validate on backend.
5558            let runs_on = if matches!(when, When::On(_)) {
5559                RunsOn::Agent
5560            } else {
5561                RunsOn::Backend
5562            };
5563            let s = schedule_with(when.clone(), runs_on);
5564
5565            let json = serde_json::to_string(&s).expect("json serialise");
5566            let back: Schedule = serde_json::from_str(&json).expect("json deserialise");
5567            assert_eq!(back.when, when, "json round-trip for {when}");
5568
5569            let yaml = serde_yaml::to_string(&s).expect("yaml serialise");
5570            assert!(
5571                !yaml.contains('!'),
5572                "yaml must use the map shape, not tags: {yaml}"
5573            );
5574            let back: Schedule = serde_yaml::from_str(&yaml).expect("yaml deserialise");
5575            assert_eq!(back.when, when, "yaml round-trip for {when}");
5576        }
5577    }
5578
5579    #[test]
5580    fn when_once_serialises_as_bare_keyword() {
5581        // The wire shape operators see in the YAML mirror must stay
5582        // the ergonomic `per_pc: once`, not a one-variant map.
5583        let json = serde_json::to_value(When::PerPc(PerPolicy::Once(OnceLiteral::Once)))
5584            .expect("serialise");
5585        assert_eq!(json, serde_json::json!({ "per_pc": "once" }));
5586    }
5587
5588    #[test]
5589    fn when_displays_operator_summary() {
5590        for (when, expected) in [
5591            (
5592                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5593                "per_pc once",
5594            ),
5595            (
5596                When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5597                "per_pc every 6h",
5598            ),
5599            (
5600                When::PerTarget(PerPolicy::Every(EverySpec {
5601                    every: "24h".into(),
5602                })),
5603                "per_target every 24h",
5604            ),
5605            (calendar("09:00", &["mon-fri"]), "at 09:00 [mon-fri]"),
5606            (calendar("2026-06-10 09:00", &[]), "at 2026-06-10 09:00"),
5607            (When::On(vec![OnTrigger::Startup]), "on [startup]"),
5608            (
5609                When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
5610                "on [startup,logon]",
5611            ),
5612            (
5613                When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
5614                "on [lock,unlock]",
5615            ),
5616            (
5617                When::On(vec![OnTrigger::NetworkChange]),
5618                "on [network_change]",
5619            ),
5620        ] {
5621            assert_eq!(when.to_string(), expected);
5622        }
5623    }
5624
5625    // ---- lowering (#418: when → engine vocabulary) ----
5626
5627    fn schedule_with(when: When, runs_on: RunsOn) -> Schedule {
5628        Schedule {
5629            id: "x".into(),
5630            when,
5631            job_id: "y".into(),
5632            // #917: validate() now rejects a target that dispatches
5633            // nothing, so the baseline helper carries the simplest
5634            // specified target.
5635            plan: FanoutPlan {
5636                target: Target {
5637                    all: true,
5638                    ..Target::default()
5639                },
5640                ..FanoutPlan::default()
5641            },
5642            active: Active::default(),
5643            constraints: Constraints::default(),
5644            on_failure: OnFailure::default(),
5645            tz: ScheduleTz::default(),
5646            starting_deadline: None,
5647            runs_on,
5648            enabled: true,
5649            tags: Vec::new(),
5650            origin: None,
5651        }
5652    }
5653
5654    fn calendar(at: &str, days: &[&str]) -> When {
5655        When::Calendar(CalendarSpec {
5656            at: at.into(),
5657            days: days.iter().map(|d| (*d).to_string()).collect(),
5658        })
5659    }
5660
5661    #[test]
5662    fn next_calendar_fire_returns_next_utc_occurrence() {
5663        use chrono::TimeZone;
5664        // Daily 09:00, evaluated in UTC. From 08:00 the same day, the
5665        // next strict occurrence is 09:00 that day.
5666        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5667        s.tz = ScheduleTz::Utc;
5668        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 8, 0, 0).unwrap();
5669        let next = s.next_calendar_fire(now).expect("calendar has a next fire");
5670        assert_eq!(
5671            next,
5672            chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap()
5673        );
5674    }
5675
5676    #[test]
5677    fn next_calendar_fire_is_strictly_after_now() {
5678        use chrono::TimeZone;
5679        // Standing exactly on a fire instant must preview the *next*
5680        // one (inclusive = false), not the one firing right now.
5681        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5682        s.tz = ScheduleTz::Utc;
5683        let on_fire = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap();
5684        let next = s
5685            .next_calendar_fire(on_fire)
5686            .expect("calendar has a next fire");
5687        assert_eq!(
5688            next,
5689            chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()
5690        );
5691    }
5692
5693    #[test]
5694    fn next_calendar_fire_none_for_reconcile_shapes() {
5695        // `per_pc` / `per_target` lower to the every-minute poll cron —
5696        // no discrete upcoming event to preview, so `None`.
5697        let now = chrono::Utc::now();
5698        for when in [
5699            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5700            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5701            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5702            When::PerTarget(PerPolicy::Every(EverySpec {
5703                every: "24h".into(),
5704            })),
5705        ] {
5706            let s = schedule_with(when, RunsOn::Backend);
5707            assert!(
5708                s.next_calendar_fire(now).is_none(),
5709                "reconcile shapes have no calendar fire",
5710            );
5711        }
5712    }
5713
5714    // ---- preview_fires (#418 dry-run / preview) ----
5715
5716    fn cal_utc(at: &str, days: &[&str]) -> Schedule {
5717        let mut s = schedule_with(calendar(at, days), RunsOn::Backend);
5718        s.tz = ScheduleTz::Utc; // host-independent assertions
5719        s
5720    }
5721
5722    #[test]
5723    fn preview_lists_next_calendar_occurrences() {
5724        use chrono::TimeZone;
5725        // Weekday 09:00, from Wed 2026-06-10 00:00 UTC: the next five
5726        // fires skip the weekend (Sat 13 / Sun 14).
5727        let s = cal_utc("09:00", &["mon-fri"]);
5728        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5729        let got = s.preview_fires(now, 5);
5730        let want: Vec<_> = [
5731            (2026, 6, 10), // Wed
5732            (2026, 6, 11), // Thu
5733            (2026, 6, 12), // Fri
5734            (2026, 6, 15), // Mon (skips Sat 13 / Sun 14)
5735            (2026, 6, 16), // Tue
5736        ]
5737        .iter()
5738        .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
5739        .collect();
5740        assert_eq!(got, want);
5741    }
5742
5743    #[test]
5744    fn preview_handles_nth_and_last_weekday() {
5745        use chrono::TimeZone;
5746        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
5747        // 2nd Tuesday (Patch Tuesday): Jun 9, Jul 14 2026.
5748        let nth = cal_utc("09:00", &["tue#2"]).preview_fires(now, 2);
5749        assert_eq!(
5750            nth,
5751            vec![
5752                chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap(),
5753                chrono::Utc.with_ymd_and_hms(2026, 7, 14, 9, 0, 0).unwrap(),
5754            ]
5755        );
5756        // Last Friday of the month: Jun 26, Jul 31 2026.
5757        let last = cal_utc("22:00", &["friL"]).preview_fires(now, 2);
5758        assert_eq!(
5759            last,
5760            vec![
5761                chrono::Utc.with_ymd_and_hms(2026, 6, 26, 22, 0, 0).unwrap(),
5762                chrono::Utc.with_ymd_and_hms(2026, 7, 31, 22, 0, 0).unwrap(),
5763            ]
5764        );
5765    }
5766
5767    #[test]
5768    fn preview_is_empty_for_reconcile_and_zero_count() {
5769        let now = chrono::Utc::now();
5770        // reconcile shapes have no discrete fire times
5771        let recon = schedule_with(
5772            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5773            RunsOn::Backend,
5774        );
5775        assert!(recon.preview_fires(now, 5).is_empty());
5776        // count == 0 yields nothing even for a calendar
5777        assert!(cal_utc("09:00", &[]).preview_fires(now, 0).is_empty());
5778    }
5779
5780    #[test]
5781    fn preview_skips_outside_active_window() {
5782        use chrono::TimeZone;
5783        // Daily 09:00, active only [2026-06-15, 2026-06-17). Occurrences
5784        // before `from` are skipped; `until` is exclusive, so 06-17's
5785        // fire is out — leaving exactly the 15th and 16th.
5786        let mut s = cal_utc("09:00", &[]);
5787        s.active = Active {
5788            from: Some("2026-06-15".into()),
5789            until: Some("2026-06-17".into()),
5790        };
5791        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5792        let got = s.preview_fires(now, 5);
5793        assert_eq!(
5794            got,
5795            vec![
5796                chrono::Utc.with_ymd_and_hms(2026, 6, 15, 9, 0, 0).unwrap(),
5797                chrono::Utc.with_ymd_and_hms(2026, 6, 16, 9, 0, 0).unwrap(),
5798            ]
5799        );
5800    }
5801
5802    #[test]
5803    fn preview_empty_when_calendar_time_outside_window() {
5804        use chrono::TimeZone;
5805        // Fires at 09:00 but the maintenance window is overnight — it can
5806        // never run, so the preview is empty (matches
5807        // `calendar_outside_window`), and the scan still terminates.
5808        let mut s = cal_utc("09:00", &[]);
5809        s.constraints = Constraints {
5810            window: Some("22:00-05:00".into()),
5811            ..Constraints::default()
5812        };
5813        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5814        assert!(s.preview_fires(now, 5).is_empty());
5815        // Every candidate tick is rejected, so this also exercises the
5816        // SCAN_CAP bound: a large `count` must still terminate (and
5817        // return empty) rather than spin (claude #578 review).
5818        assert!(s.preview_fires(now, 50).is_empty());
5819    }
5820
5821    #[test]
5822    fn preview_past_one_shot_is_empty() {
5823        use chrono::TimeZone;
5824        // A dated one-shot whose instant has passed never fires again.
5825        let s = cal_utc("2026-06-10 09:00", &[]);
5826        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 0, 0, 0).unwrap();
5827        assert!(s.preview_fires(now, 5).is_empty());
5828        // …but from before it, the single future fire shows up.
5829        let before = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
5830        assert_eq!(
5831            s.preview_fires(before, 5),
5832            vec![chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()]
5833        );
5834    }
5835
5836    #[test]
5837    fn lowering_matches_the_418_table() {
5838        let cases = [
5839            (
5840                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5841                (POLL_CRON, ExecMode::OncePerPc, None),
5842            ),
5843            (
5844                When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5845                (POLL_CRON, ExecMode::OncePerPc, Some("6h")),
5846            ),
5847            (
5848                When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5849                (POLL_CRON, ExecMode::OncePerTarget, None),
5850            ),
5851            (
5852                When::PerTarget(PerPolicy::Every(EverySpec {
5853                    every: "24h".into(),
5854                })),
5855                (POLL_CRON, ExecMode::OncePerTarget, Some("24h")),
5856            ),
5857            // calendar repeating → 6-field cron
5858            (
5859                calendar("09:00", &["mon-fri"]),
5860                ("0 0 9 * * mon-fri", ExecMode::EveryTick, None),
5861            ),
5862            // calendar daily (no days) → DOW *
5863            (
5864                calendar("18:30", &[]),
5865                ("0 30 18 * * *", ExecMode::EveryTick, None),
5866            ),
5867            // calendar one-shot → 7-field year cron
5868            (
5869                calendar("2026-06-10 09:00", &[]),
5870                ("0 0 9 10 6 * 2026", ExecMode::EveryTick, None),
5871            ),
5872        ];
5873        for (when, (cron, mode, cooldown)) in cases {
5874            let l = schedule_with(when.clone(), RunsOn::Backend).lowered();
5875            assert_eq!(l.cron, cron, "cron for {when}");
5876            assert_eq!(l.mode, mode, "mode for {when}");
5877            assert_eq!(l.cooldown.as_deref(), cooldown, "cooldown for {when}");
5878        }
5879    }
5880
5881    #[test]
5882    fn lowered_carries_schedule_tz() {
5883        for (tz, want) in [
5884            (ScheduleTz::Local, ScheduleTz::Local),
5885            (ScheduleTz::Utc, ScheduleTz::Utc),
5886        ] {
5887            let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
5888            s.tz = tz;
5889            assert_eq!(s.lowered().tz, want, "calendar carries tz");
5890            // reconcile shapes carry tz too (for the active-window check)
5891            let mut s = schedule_with(
5892                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5893                RunsOn::Backend,
5894            );
5895            s.tz = tz;
5896            assert_eq!(s.lowered().tz, want, "reconcile carries tz");
5897        }
5898    }
5899
5900    #[test]
5901    fn poll_cron_is_accepted_by_the_engine_parser() {
5902        // POLL_CRON is system-generated — if the engine's parser
5903        // ever rejected it every reconcile schedule would die at
5904        // register time. Validate it with the same croner config
5905        // (Seconds::Required, dom_and_dow, year optional).
5906        croner::parser::CronParser::builder()
5907            .seconds(croner::parser::Seconds::Required)
5908            .dom_and_dow(true)
5909            .build()
5910            .parse(POLL_CRON)
5911            .expect("POLL_CRON must parse");
5912    }
5913
5914    // ---- Schedule::validate() (#418 decision F) ----
5915
5916    #[test]
5917    fn validate_accepts_reconcile_shapes() {
5918        for when in [
5919            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5920            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5921            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5922            When::PerTarget(PerPolicy::Every(EverySpec {
5923                every: "24h".into(),
5924            })),
5925        ] {
5926            schedule_with(when.clone(), RunsOn::Backend)
5927                .validate()
5928                .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
5929        }
5930    }
5931
5932    #[test]
5933    fn validate_accepts_per_pc_on_agent() {
5934        schedule_with(
5935            When::PerPc(PerPolicy::Every(EverySpec { every: "1h".into() })),
5936            RunsOn::Agent,
5937        )
5938        .validate()
5939        .expect("per_pc + agent is the offline-inventory shape");
5940    }
5941
5942    // ---- #418 event triggers (when: { on }) ----
5943
5944    #[test]
5945    fn validate_accepts_event_on_agent() {
5946        for triggers in [
5947            vec![OnTrigger::Startup],
5948            vec![OnTrigger::Logon],
5949            vec![OnTrigger::Lock],
5950            vec![OnTrigger::Unlock],
5951            vec![OnTrigger::NetworkChange],
5952            vec![
5953                OnTrigger::Startup,
5954                OnTrigger::Logon,
5955                OnTrigger::Lock,
5956                OnTrigger::Unlock,
5957                OnTrigger::NetworkChange,
5958            ],
5959        ] {
5960            schedule_with(When::On(triggers), RunsOn::Agent)
5961                .validate()
5962                .expect("when.on is valid on runs_on: agent");
5963        }
5964    }
5965
5966    #[test]
5967    fn validate_rejects_event_on_backend() {
5968        let err = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Backend)
5969            .validate()
5970            .unwrap_err();
5971        assert!(err.contains("when.on"), "got: {err}");
5972        assert!(err.contains("runs_on: agent"), "got: {err}");
5973    }
5974
5975    #[test]
5976    fn validate_rejects_empty_event_list() {
5977        let err = schedule_with(When::On(vec![]), RunsOn::Agent)
5978            .validate()
5979            .unwrap_err();
5980        assert!(err.contains("when.on"), "got: {err}");
5981        assert!(err.contains("at least one"), "got: {err}");
5982    }
5983
5984    #[test]
5985    fn event_schedule_lowers_to_event_mode_and_is_event() {
5986        let s = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Agent);
5987        assert!(s.is_event());
5988        assert_eq!(s.lowered().mode, ExecMode::Event);
5989        assert_eq!(s.event_triggers(), &[OnTrigger::Startup]);
5990        // non-event schedules report no triggers.
5991        let cal = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5992        assert!(!cal.is_event());
5993        assert!(cal.event_triggers().is_empty());
5994    }
5995
5996    // ---- #418 constraints.require (env gates) ----
5997
5998    fn require_schedule(req: Require, runs_on: RunsOn) -> Schedule {
5999        let mut s = schedule_with(
6000            When::PerPc(PerPolicy::Every(EverySpec { every: "1m".into() })),
6001            runs_on,
6002        );
6003        s.constraints.require = Some(req);
6004        s
6005    }
6006
6007    #[test]
6008    fn require_met_combinations() {
6009        use std::time::Duration;
6010        let idle = |m: u64| Some(Duration::from_secs(m * 60));
6011        // Builder for the sensed state: (ac, idle, cpu, network).
6012        let env = |ac, idle, cpu, net| EnvState {
6013            ac_online: ac,
6014            idle,
6015            cpu_pct: cpu,
6016            network_up: net,
6017        };
6018        // Empty require — always met regardless of sensed state.
6019        assert!(require_met(
6020            &Require::default(),
6021            &env(false, None, None, false)
6022        ));
6023        // ac_power: only on AC.
6024        let ac = Require {
6025            ac_power: true,
6026            ..Default::default()
6027        };
6028        assert!(!require_met(&ac, &env(false, None, None, true)));
6029        assert!(require_met(&ac, &env(true, None, None, false)));
6030        // idle: needs >= the configured min; None idle never satisfies.
6031        let idle10 = Require {
6032            idle: Some("10m".into()),
6033            ..Default::default()
6034        };
6035        assert!(!require_met(&idle10, &env(true, None, None, true)));
6036        assert!(!require_met(&idle10, &env(true, idle(5), None, true)));
6037        assert!(require_met(&idle10, &env(true, idle(15), None, true)));
6038        assert!(require_met(&idle10, &env(true, idle(10), None, true))); // boundary inclusive
6039        // cpu_below: needs CPU strictly < threshold; None cpu never satisfies.
6040        let cpu20 = Require {
6041            cpu_below: Some(20.0),
6042            ..Default::default()
6043        };
6044        assert!(!require_met(&cpu20, &env(true, None, None, true))); // no sample → fail-closed
6045        assert!(!require_met(&cpu20, &env(true, None, Some(20.0), true))); // == threshold
6046        assert!(!require_met(&cpu20, &env(true, None, Some(55.0), true))); // busy
6047        assert!(require_met(&cpu20, &env(true, None, Some(5.0), true))); // quiet
6048        // network: only when online.
6049        let net = Require {
6050            network: true,
6051            ..Default::default()
6052        };
6053        assert!(!require_met(&net, &env(true, None, None, false))); // offline
6054        assert!(require_met(&net, &env(true, None, None, true))); // online
6055        // all four: AND.
6056        let all = Require {
6057            ac_power: true,
6058            idle: Some("10m".into()),
6059            cpu_below: Some(20.0),
6060            network: true,
6061        };
6062        assert!(!require_met(&all, &env(false, idle(20), Some(5.0), true))); // on battery
6063        assert!(!require_met(&all, &env(true, idle(1), Some(5.0), true))); // not idle enough
6064        assert!(!require_met(&all, &env(true, idle(20), Some(50.0), true))); // busy
6065        assert!(!require_met(&all, &env(true, idle(20), Some(5.0), false))); // offline
6066        assert!(require_met(&all, &env(true, idle(20), Some(5.0), true)));
6067        // An unparseable idle is treated as no-requirement by require_met
6068        // (validate rejects it at create time, so this only guards a
6069        // hand-edited blob): ac still gates.
6070        let bad = Require {
6071            ac_power: true,
6072            idle: Some("garbage".into()),
6073            ..Default::default()
6074        };
6075        assert!(require_met(&bad, &env(true, None, None, true)));
6076        assert!(!require_met(&bad, &env(false, None, None, true)));
6077    }
6078
6079    #[test]
6080    fn validate_accepts_and_rejects_cpu_below() {
6081        // In-range accepted.
6082        require_schedule(
6083            Require {
6084                cpu_below: Some(20.0),
6085                ..Default::default()
6086            },
6087            RunsOn::Agent,
6088        )
6089        .validate()
6090        .expect("cpu_below 20 is valid");
6091        // Upper boundary: 100.0 is accepted (fires unless CPU is exactly
6092        // 100%). Pins the inclusive upper bound against a future c < 100.0.
6093        require_schedule(
6094            Require {
6095                cpu_below: Some(100.0),
6096                ..Default::default()
6097            },
6098            RunsOn::Agent,
6099        )
6100        .validate()
6101        .expect("cpu_below 100 is valid");
6102        // Out of range rejected (0 and >100).
6103        for bad in [0.0, -5.0, 100.1] {
6104            let err = require_schedule(
6105                Require {
6106                    cpu_below: Some(bad),
6107                    ..Default::default()
6108                },
6109                RunsOn::Agent,
6110            )
6111            .validate()
6112            .unwrap_err();
6113            assert!(
6114                err.contains("constraints.require.cpu_below"),
6115                "cpu_below {bad}: {err}"
6116            );
6117        }
6118    }
6119
6120    #[test]
6121    fn validate_accepts_require_on_agent() {
6122        require_schedule(
6123            Require {
6124                ac_power: true,
6125                idle: Some("10m".into()),
6126                cpu_below: Some(20.0),
6127                network: true,
6128            },
6129            RunsOn::Agent,
6130        )
6131        .validate()
6132        .expect("constraints.require is valid on runs_on: agent");
6133    }
6134
6135    #[test]
6136    fn validate_rejects_require_on_backend() {
6137        let err = require_schedule(
6138            Require {
6139                ac_power: true,
6140                ..Default::default()
6141            },
6142            RunsOn::Backend,
6143        )
6144        .validate()
6145        .unwrap_err();
6146        assert!(err.contains("constraints.require"), "got: {err}");
6147        assert!(err.contains("runs_on: agent"), "got: {err}");
6148
6149        // An idle-only require (ac_power: false) is also non-empty
6150        // (is_empty folds the fields) and must reject on backend too —
6151        // guards against a regression in Require::is_empty.
6152        let err = require_schedule(
6153            Require {
6154                idle: Some("10m".into()),
6155                ..Default::default()
6156            },
6157            RunsOn::Backend,
6158        )
6159        .validate()
6160        .unwrap_err();
6161        assert!(
6162            err.contains("constraints.require"),
6163            "idle-only on backend: {err}"
6164        );
6165    }
6166
6167    #[test]
6168    fn validate_rejects_bad_require_idle() {
6169        let err = require_schedule(
6170            Require {
6171                idle: Some("not-a-duration".into()),
6172                ..Default::default()
6173            },
6174            RunsOn::Agent,
6175        )
6176        .validate()
6177        .unwrap_err();
6178        assert!(err.contains("constraints.require.idle"), "got: {err}");
6179    }
6180
6181    #[test]
6182    fn require_round_trips_and_skips_empty() {
6183        // ac_power: false is skipped; an all-default require nested in
6184        // constraints is omitted (is_empty folds it in).
6185        let yaml = "id: s\nwhen: { per_pc: { every: 1m } }\njob_id: j\nruns_on: agent\n\
6186                    constraints: { require: { ac_power: true, idle: 10m, cpu_below: 20, \
6187                    network: true } }\n";
6188        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6189        let req = s.constraints.require.as_ref().expect("require present");
6190        assert!(req.ac_power);
6191        assert_eq!(req.idle.as_deref(), Some("10m"));
6192        assert_eq!(req.cpu_below, Some(20.0));
6193        assert!(req.network);
6194        // Re-serialize: idle + cpu_below + network present, ac_power true.
6195        let back = serde_json::to_string(&s.constraints).unwrap();
6196        assert!(back.contains("\"idle\":\"10m\""), "got: {back}");
6197        assert!(back.contains("\"cpu_below\":20"), "got: {back}");
6198        assert!(back.contains("\"network\":true"), "got: {back}");
6199        // An empty require is omitted entirely by is_empty.
6200        let mut empty = s.clone();
6201        empty.constraints.require = Some(Require::default());
6202        assert!(empty.constraints.is_empty());
6203    }
6204
6205    #[test]
6206    fn validate_rejects_per_target_on_agent() {
6207        let err = schedule_with(
6208            When::PerTarget(PerPolicy::Every(EverySpec {
6209                every: "24h".into(),
6210            })),
6211            RunsOn::Agent,
6212        )
6213        .validate()
6214        .unwrap_err();
6215        assert!(err.contains("per_target"), "got: {err}");
6216        assert!(err.contains("runs_on: agent"), "got: {err}");
6217
6218        // per_target: once is also backend-only.
6219        let err = schedule_with(
6220            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
6221            RunsOn::Agent,
6222        )
6223        .validate()
6224        .unwrap_err();
6225        assert!(err.contains("per_target"), "got (once): {err}");
6226        assert!(err.contains("runs_on: agent"), "got (once): {err}");
6227    }
6228
6229    #[test]
6230    fn validate_rejects_bad_every_duration() {
6231        let err = schedule_with(
6232            When::PerPc(PerPolicy::Every(EverySpec { every: "6x".into() })),
6233            RunsOn::Backend,
6234        )
6235        .validate()
6236        .unwrap_err();
6237        assert!(err.contains("when.every"), "got: {err}");
6238    }
6239
6240    #[test]
6241    fn validate_rejects_bad_jitter_and_starting_deadline() {
6242        let mut s = schedule_with(
6243            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6244            RunsOn::Backend,
6245        );
6246        s.plan.jitter = Some("5x".into());
6247        let err = s.validate().unwrap_err();
6248        assert!(err.contains("jitter"), "got: {err}");
6249
6250        let mut s = schedule_with(
6251            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6252            RunsOn::Backend,
6253        );
6254        s.starting_deadline = Some("soon".into());
6255        let err = s.validate().unwrap_err();
6256        assert!(err.contains("starting_deadline"), "got: {err}");
6257    }
6258
6259    #[test]
6260    fn validate_rejects_unspecified_target() {
6261        // #917 (1): an all-default target never dispatches anywhere —
6262        // runs_on: agent silently never fires, runs_on: backend
6263        // warn-fails every tick at the exec boundary. Both rejected.
6264        for runs_on in [RunsOn::Backend, RunsOn::Agent] {
6265            let mut s = schedule_with(When::PerPc(PerPolicy::Once(OnceLiteral::Once)), runs_on);
6266            s.plan.target = Target::default();
6267            let err = s.validate().unwrap_err();
6268            assert!(err.contains("target"), "for {runs_on:?}, got: {err}");
6269        }
6270    }
6271
6272    /// A Schedule with every top-level field populated so each one
6273    /// actually serialises (the optional ones are `skip_serializing_if`).
6274    fn fully_populated_schedule() -> Schedule {
6275        let mut s = schedule_with(
6276            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6277            RunsOn::Backend,
6278        );
6279        s.plan.rollout = Some(Rollout {
6280            strategy: RolloutStrategy::Wave,
6281            waves: vec![Wave {
6282                group: "canary".into(),
6283                delay: "0s".into(),
6284            }],
6285        });
6286        s.plan.jitter = Some("5m".into());
6287        s.plan.deadline_at = Some(chrono::Utc::now());
6288        s.active = Active {
6289            from: Some("2026-01-01 00:00".into()),
6290            until: Some("2026-12-31 00:00".into()),
6291        };
6292        s.constraints = Constraints {
6293            window: Some("09:00-17:00".into()),
6294            ..Constraints::default()
6295        };
6296        s.on_failure = OnFailure {
6297            retry: Some(Retry {
6298                max: 1,
6299                backoff: "10s".into(),
6300            }),
6301        };
6302        s.starting_deadline = Some("30m".into());
6303        s.tags = vec!["health".into()];
6304        s.origin = Some(RepoOrigin {
6305            path: "configs/schedules/x.yaml".into(),
6306            repo: None,
6307            script_file: None,
6308        });
6309        s
6310    }
6311
6312    #[test]
6313    fn schedule_top_level_keys_cover_serialized_fields() {
6314        // #924 drift guard: the hand-maintained TOP_LEVEL_KEYS list must
6315        // match exactly what a fully-populated Schedule serialises — so a
6316        // future field added to Schedule or FanoutPlan can't slip past
6317        // the flatten-aware strict guard by being forgotten here.
6318        let s = fully_populated_schedule();
6319        let value = serde_json::to_value(&s).expect("serialize schedule");
6320        let serialized: std::collections::BTreeSet<String> = value
6321            .as_object()
6322            .expect("schedule serialises to an object")
6323            .keys()
6324            .cloned()
6325            .collect();
6326        let listed: std::collections::BTreeSet<String> = Schedule::TOP_LEVEL_KEYS
6327            .iter()
6328            .map(|s| s.to_string())
6329            .collect();
6330        assert_eq!(
6331            serialized, listed,
6332            "TOP_LEVEL_KEYS is out of sync with Schedule's serialized fields \
6333             (flatten-aware strict guard would miss a real field or reject a valid one)"
6334        );
6335    }
6336
6337    #[test]
6338    fn strict_rejects_flatten_hidden_top_level_typo() {
6339        // #924: a top-level typo on a flattening type (jiter / enabledd)
6340        // is buffered into the flatten target by serde and hidden from
6341        // serde_ignored — the top-level guard must catch it. Verified on
6342        // both the YAML and JSON strict boundaries.
6343        let yaml = "\
6344id: s1
6345job_id: j1
6346when:
6347  per_pc: once
6348target:
6349  all: true
6350jiter: 5m
6351";
6352        let err = crate::strict::from_yaml_str::<Schedule>(yaml).unwrap_err();
6353        assert!(err.contains("jiter"), "got: {err}");
6354
6355        let json = serde_json::json!({
6356            "id": "s1",
6357            "job_id": "j1",
6358            "when": { "per_pc": "once" },
6359            "target": { "all": true },
6360            "enabledd": false,
6361        });
6362        let err = crate::strict::from_json_slice::<Schedule>(&serde_json::to_vec(&json).unwrap())
6363            .unwrap_err();
6364        assert!(err.contains("enabledd"), "got: {err}");
6365    }
6366
6367    #[test]
6368    fn strict_accepts_all_valid_schedule_top_level_keys() {
6369        // The guard must not reject any legitimate key — round-trip a
6370        // fully-populated schedule through the strict YAML boundary.
6371        let s = fully_populated_schedule();
6372        let yaml = serde_yaml::to_string(&s).expect("serialize");
6373        crate::strict::from_yaml_str::<Schedule>(&yaml)
6374            .expect("every serialized key must be accepted by the strict guard");
6375    }
6376
6377    #[test]
6378    fn strict_rejects_non_string_top_level_yaml_key() {
6379        // #924 (gemini #945): a YAML key isn't always a string — an
6380        // unquoted `true:` parses as a boolean, `123:` as a number. A
6381        // `filter_map` on `as_str()` would drop these and let them slip
6382        // past the flatten guard; `yaml_key_label` renders them so they
6383        // are still rejected. (serde_yaml is YAML 1.2, so `on:` stays a
6384        // *string* "on" — also rejected, just via the string path.)
6385        let base = "\
6386id: s1
6387job_id: j1
6388when:
6389  per_pc: once
6390target:
6391  all: true
6392";
6393        for (extra, needle) in [
6394            ("true: x\n", "true"),
6395            ("123: x\n", "123"),
6396            ("on: y\n", "on"),
6397        ] {
6398            let yaml = format!("{base}{extra}");
6399            let err = crate::strict::from_yaml_str::<Schedule>(&yaml).unwrap_err();
6400            assert!(err.contains(needle), "for '{extra}', got: {err}");
6401        }
6402    }
6403
6404    #[test]
6405    fn validate_accepts_waves_instead_of_target_on_backend() {
6406        // #917 (1): the exec boundary accepts rollout-only plans
6407        // (target then just labels the audit row) — so does validate.
6408        let mut s = schedule_with(
6409            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6410            RunsOn::Backend,
6411        );
6412        s.plan.target = Target::default();
6413        s.plan.rollout = Some(Rollout {
6414            strategy: RolloutStrategy::Wave,
6415            waves: vec![Wave {
6416                group: "canary".into(),
6417                delay: "0s".into(),
6418            }],
6419        });
6420        s.validate().expect("rollout-only plan should validate");
6421    }
6422
6423    #[test]
6424    fn validate_rejects_rollout_on_agent() {
6425        // #917 (1): rollout waves are backend-published; a runs_on:
6426        // agent schedule never reads them, so the combination is a
6427        // silent no-op — reject like max_concurrent-on-agent.
6428        let mut s = schedule_with(
6429            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6430            RunsOn::Agent,
6431        );
6432        s.plan.rollout = Some(Rollout {
6433            strategy: RolloutStrategy::Wave,
6434            waves: vec![Wave {
6435                group: "canary".into(),
6436                delay: "0s".into(),
6437            }],
6438        });
6439        let err = s.validate().unwrap_err();
6440        assert!(err.contains("rollout"), "got: {err}");
6441    }
6442
6443    #[test]
6444    fn validate_rejects_bad_waves() {
6445        // #917 (2): empty waves, blank group, unparseable delay — all
6446        // previously accepted and failed (or no-opped) at every fire.
6447        let base = || {
6448            schedule_with(
6449                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6450                RunsOn::Backend,
6451            )
6452        };
6453
6454        let mut s = base();
6455        s.plan.rollout = Some(Rollout {
6456            strategy: RolloutStrategy::Wave,
6457            waves: vec![],
6458        });
6459        let err = s.validate().unwrap_err();
6460        assert!(err.contains("at least one wave"), "got: {err}");
6461
6462        let mut s = base();
6463        s.plan.rollout = Some(Rollout {
6464            strategy: RolloutStrategy::Wave,
6465            waves: vec![Wave {
6466                group: "  ".into(),
6467                delay: "0s".into(),
6468            }],
6469        });
6470        let err = s.validate().unwrap_err();
6471        assert!(err.contains("waves[0].group"), "got: {err}");
6472
6473        let mut s = base();
6474        s.plan.rollout = Some(Rollout {
6475            strategy: RolloutStrategy::Wave,
6476            waves: vec![
6477                Wave {
6478                    group: "canary".into(),
6479                    delay: "0s".into(),
6480                },
6481                Wave {
6482                    group: "wave1".into(),
6483                    delay: "5 minuts".into(),
6484                },
6485            ],
6486        });
6487        let err = s.validate().unwrap_err();
6488        assert!(err.contains("waves[1].delay"), "got: {err}");
6489    }
6490
6491    #[test]
6492    fn validate_rejects_wave_delay_at_or_past_starting_deadline() {
6493        // #917 (3): the deadline is stamped once at tick time, so a
6494        // wave sleeping >= starting_deadline publishes already-expired
6495        // Commands — dead on arrival, every fire.
6496        let mut s = schedule_with(
6497            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6498            RunsOn::Backend,
6499        );
6500        s.starting_deadline = Some("30m".into());
6501        s.plan.rollout = Some(Rollout {
6502            strategy: RolloutStrategy::Wave,
6503            waves: vec![
6504                Wave {
6505                    group: "canary".into(),
6506                    delay: "0s".into(),
6507                },
6508                Wave {
6509                    group: "wave1".into(),
6510                    delay: "30m".into(),
6511                },
6512            ],
6513        });
6514        let err = s.validate().unwrap_err();
6515        assert!(
6516            err.contains("waves[1].delay") && err.contains("starting_deadline"),
6517            "got: {err}"
6518        );
6519
6520        // Strictly shorter is fine.
6521        s.plan.rollout.as_mut().unwrap().waves[1].delay = "29m".into();
6522        s.validate().expect("delay < deadline should validate");
6523    }
6524
6525    #[test]
6526    fn validate_rejects_operator_set_deadline_at() {
6527        // #917 (4): machine-stamped field — the scheduler overwrites it
6528        // on every fire, so a hand-set value is silently discarded.
6529        let mut s = schedule_with(
6530            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6531            RunsOn::Backend,
6532        );
6533        s.plan.deadline_at = Some(chrono::Utc::now());
6534        let err = s.validate().unwrap_err();
6535        assert!(
6536            err.contains("deadline_at") && err.contains("starting_deadline"),
6537            "got: {err}"
6538        );
6539    }
6540
6541    #[test]
6542    fn validate_accepts_calendar_shapes() {
6543        for when in [
6544            calendar("09:00", &["mon-fri"]),   // weekday morning
6545            calendar("00:00", &["sun"]),       // weekly
6546            calendar("18:30", &[]),            // daily
6547            calendar("2026-06-10 09:00", &[]), // one-shot
6548            calendar("2026/12/25 00:00", &[]), // one-shot, slash form
6549        ] {
6550            schedule_with(when.clone(), RunsOn::Backend)
6551                .validate()
6552                .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
6553        }
6554    }
6555
6556    #[test]
6557    fn validate_rejects_bad_at() {
6558        for bad in ["25:00", "09:60", "9", "noon", "2026-13-01 09:00"] {
6559            let err = schedule_with(calendar(bad, &[]), RunsOn::Backend)
6560                .validate()
6561                .unwrap_err();
6562            assert!(err.contains("when.at"), "for '{bad}', got: {err}");
6563        }
6564    }
6565
6566    #[test]
6567    fn validate_rejects_datetime_at_with_days() {
6568        // A dated `at` is a one-shot — pairing it with days is a
6569        // contradiction (the date already pins the day).
6570        let err = schedule_with(calendar("2026-06-10 09:00", &["mon"]), RunsOn::Backend)
6571            .validate()
6572            .unwrap_err();
6573        assert!(
6574            err.contains("one-shot") && err.contains("days"),
6575            "got: {err}"
6576        );
6577    }
6578
6579    #[test]
6580    fn validate_rejects_bad_day_name() {
6581        // A garbage DOW token is caught by the days pre-flight and
6582        // reported against `when.days`, not the confusing
6583        // "when.at lowered to invalid cron" (claude #432 review).
6584        let err = schedule_with(calendar("09:00", &["funday"]), RunsOn::Backend)
6585            .validate()
6586            .unwrap_err();
6587        assert!(err.contains("when.days"), "got: {err}");
6588        assert!(err.contains("funday"), "names the bad token: {err}");
6589        // a degenerate range like `mon-` reports the whole token, not
6590        // a cryptic empty part (claude #432 follow-up)
6591        let err = schedule_with(calendar("09:00", &["mon-"]), RunsOn::Backend)
6592            .validate()
6593            .unwrap_err();
6594        assert!(err.contains("'mon-'"), "names the whole token: {err}");
6595        // valid names / ranges / numeric / * all pass
6596        for ok in [
6597            calendar("09:00", &["mon-fri"]),
6598            calendar("09:00", &["mon", "wed", "sun"]),
6599            calendar("09:00", &["1-5"]),
6600        ] {
6601            schedule_with(ok.clone(), RunsOn::Backend)
6602                .validate()
6603                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6604        }
6605    }
6606
6607    #[test]
6608    fn validate_accepts_nth_weekday() {
6609        // #418: nth-weekday (Patch Tuesday). validate() also lowers to
6610        // a cron and parses it with croner, so passing here proves the
6611        // whole chain — token → DOW field → engine-acceptable cron.
6612        for ok in [
6613            calendar("09:00", &["tue#2"]),          // 2nd Tuesday
6614            calendar("09:00", &["fri#1"]),          // 1st Friday
6615            calendar("03:00", &["sun#5"]),          // 5th Sunday
6616            calendar("09:00", &["tue#2", "thu#2"]), // a list of nths
6617            calendar("09:00", &["2#2"]),            // numeric DOW + ordinal
6618            // Case-insensitive both sides: validate lowercases, croner
6619            // upper-cases the whole pattern before aliasing (claude #547).
6620            calendar("09:00", &["TUE#2"]),
6621        ] {
6622            schedule_with(ok.clone(), RunsOn::Backend)
6623                .validate()
6624                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6625        }
6626    }
6627
6628    #[test]
6629    fn validate_rejects_bad_nth_weekday() {
6630        // ordinal out of 1..5, a range with #, and a bad day before #.
6631        for bad in ["tue#0", "tue#6", "tue#x", "mon-fri#2", "funday#2"] {
6632            let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
6633                .validate()
6634                .unwrap_err();
6635            assert!(err.contains("when.days"), "for '{bad}', got: {err}");
6636        }
6637    }
6638
6639    #[test]
6640    fn validate_accepts_last_weekday() {
6641        // #418: last-weekday (`friL` = last Friday). Like the nth case,
6642        // validate() lowers to a cron and round-trips it through croner,
6643        // so passing proves token → DOW field → engine-acceptable cron
6644        // with the verified last-<dow>-of-month semantics.
6645        for ok in [
6646            calendar("09:00", &["friL"]),         // last Friday
6647            calendar("03:00", &["sunL"]),         // last Sunday
6648            calendar("22:00", &["5L"]),           // numeric DOW + last
6649            calendar("00:00", &["0L"]),           // numeric Sunday (0…
6650            calendar("00:00", &["7L"]),           // …and its 7 alias)
6651            calendar("09:00", &["monL", "friL"]), // a list of last-weekdays
6652            // Case-insensitive both the weekday and the `L` suffix:
6653            // validate lowercases the day, croner upper-cases the whole
6654            // pattern before aliasing (claude #547).
6655            calendar("09:00", &["FRIL"]),
6656            calendar("09:00", &["fril"]),
6657        ] {
6658            schedule_with(ok.clone(), RunsOn::Backend)
6659                .validate()
6660                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6661        }
6662    }
6663
6664    #[test]
6665    fn validate_rejects_bad_last_weekday() {
6666        // bare `L` (no weekday — a footgun croner reads as Saturday), a
6667        // range with L, a bad day before L, and an internal space that
6668        // would otherwise leak a malformed cron downstream (gemini #560).
6669        for bad in ["L", "l", "mon-friL", "fundayL", "8L", "*L", "fri L"] {
6670            let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
6671                .validate()
6672                .unwrap_err();
6673            assert!(err.contains("when.days"), "for '{bad}', got: {err}");
6674        }
6675    }
6676
6677    #[test]
6678    fn calendar_oneshot_instant_detects_past() {
6679        use chrono::TimeZone;
6680        // a dated `at` resolves to an absolute instant…
6681        let c = CalendarSpec {
6682            at: "2024-01-01 09:00".into(),
6683            days: vec![],
6684        };
6685        let t = c
6686            .oneshot_instant(ScheduleTz::Utc)
6687            .expect("one-shot instant");
6688        assert_eq!(
6689            t,
6690            chrono::Utc.with_ymd_and_hms(2024, 1, 1, 9, 0, 0).unwrap()
6691        );
6692        assert!(t < chrono::Utc::now(), "2024 is in the past");
6693        // …while a repeating (time-only) calendar has no instant
6694        let rep = CalendarSpec {
6695            at: "09:00".into(),
6696            days: vec!["mon-fri".into()],
6697        };
6698        assert!(rep.oneshot_instant(ScheduleTz::Utc).is_none());
6699    }
6700
6701    fn schedule_with_active(from: Option<&str>, until: Option<&str>) -> Schedule {
6702        let mut s = schedule_with(
6703            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6704            RunsOn::Backend,
6705        );
6706        s.active = Active {
6707            from: from.map(str::to_owned),
6708            until: until.map(str::to_owned),
6709        };
6710        s
6711    }
6712
6713    #[test]
6714    fn validate_accepts_active_window() {
6715        schedule_with_active(Some("2026-07-01"), Some("2026-08-01T12:00:00+09:00"))
6716            .validate()
6717            .expect("date + rfc3339 bounds should validate");
6718    }
6719
6720    #[test]
6721    fn validate_rejects_unparseable_active_bound() {
6722        let err = schedule_with_active(Some("July 1st"), None)
6723            .validate()
6724            .unwrap_err();
6725        assert!(err.contains("active"), "got: {err}");
6726    }
6727
6728    #[test]
6729    fn validate_rejects_from_not_before_until() {
6730        let err = schedule_with_active(Some("2026-08-01"), Some("2026-07-01"))
6731            .validate()
6732            .unwrap_err();
6733        assert!(err.contains("strictly before"), "got: {err}");
6734
6735        let err = schedule_with_active(Some("2026-07-01"), Some("2026-07-01"))
6736            .validate()
6737            .unwrap_err();
6738        assert!(err.contains("strictly before"), "got: {err}");
6739    }
6740
6741    // ---- Active window semantics ----
6742
6743    #[test]
6744    fn active_window_is_half_open() {
6745        use chrono::TimeZone;
6746        let active = Active {
6747            from: Some("2026-07-01".into()),
6748            until: Some("2026-08-01".into()),
6749        };
6750        // UTC tz so the date bounds are UTC midnight.
6751        let at = |y, m, d, h| chrono::Utc.with_ymd_and_hms(y, m, d, h, 0, 0).unwrap();
6752        let c = |t| active.contains(t, ScheduleTz::Utc);
6753        assert!(!c(at(2026, 6, 30, 23)), "before from");
6754        assert!(c(at(2026, 7, 1, 0)), "at from (inclusive)");
6755        assert!(c(at(2026, 7, 15, 12)), "inside");
6756        assert!(!c(at(2026, 8, 1, 0)), "at until (exclusive)");
6757        assert!(!c(at(2026, 8, 2, 0)), "after until");
6758    }
6759
6760    #[test]
6761    fn active_empty_window_is_always_active() {
6762        assert!(Active::default().contains(chrono::Utc::now(), ScheduleTz::Local));
6763    }
6764
6765    #[test]
6766    fn active_rfc3339_bound_honours_offset_regardless_of_tz() {
6767        use chrono::TimeZone;
6768        let active = Active {
6769            from: Some("2026-07-01T09:00:00+09:00".into()),
6770            until: None,
6771        };
6772        // RFC3339 carries its own offset → tz arg is ignored.
6773        // 09:00 JST = 00:00 UTC.
6774        for tz in [ScheduleTz::Utc, ScheduleTz::Local] {
6775            assert!(
6776                !active.contains(
6777                    chrono::Utc
6778                        .with_ymd_and_hms(2026, 6, 30, 23, 59, 0)
6779                        .unwrap(),
6780                    tz
6781                )
6782            );
6783            assert!(active.contains(
6784                chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap(),
6785                tz
6786            ));
6787        }
6788    }
6789
6790    #[test]
6791    fn active_date_bound_respects_tz() {
6792        // A bare `YYYY-MM-DD` bound is midnight *in the schedule's
6793        // tz* (#418 Phase 2). The UTC interpretation is exact and
6794        // host-independent; assert that precisely.
6795        use chrono::TimeZone;
6796        let utc = Active::parse_bound("2026-07-01", ScheduleTz::Utc).expect("utc");
6797        assert_eq!(
6798            utc,
6799            chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap()
6800        );
6801
6802        // The local interpretation must equal what chrono::Local
6803        // computes for the same wall-clock midnight — proves the tz
6804        // path is wired to the host zone (the magnitude vs UTC is
6805        // host-dependent, so we compare against Local directly rather
6806        // than hard-coding the JST offset, keeping CI green on UTC
6807        // runners).
6808        let local = Active::parse_bound("2026-07-01", ScheduleTz::Local).expect("local");
6809        let want = chrono::Local
6810            .with_ymd_and_hms(2026, 7, 1, 0, 0, 0)
6811            .single()
6812            .expect("local midnight is unambiguous")
6813            .with_timezone(&chrono::Utc);
6814        assert_eq!(local, want, "date bound resolved in host-local tz");
6815    }
6816
6817    #[test]
6818    fn active_empty_is_skipped_when_serialising() {
6819        let s = schedule_with(
6820            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6821            RunsOn::Backend,
6822        );
6823        let json = serde_json::to_value(&s).expect("serialise");
6824        assert!(
6825            json.get("active").is_none(),
6826            "empty active must not appear on the wire: {json}"
6827        );
6828    }
6829
6830    // ---- constraints.window (#418 Phase 3) ----
6831
6832    fn with_window(win: &str) -> Schedule {
6833        let mut s = schedule_with(
6834            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6835            RunsOn::Backend,
6836        );
6837        s.constraints.window = Some(win.into());
6838        s
6839    }
6840
6841    #[test]
6842    fn constraints_window_parses_and_round_trips() {
6843        let yaml = r#"
6844id: x
6845when:
6846  per_pc: { every: 6h }
6847job_id: y
6848target: { all: true }
6849constraints:
6850  window: "22:00-05:00"
6851"#;
6852        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6853        assert_eq!(s.constraints.window.as_deref(), Some("22:00-05:00"));
6854        let back: Schedule =
6855            serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
6856        assert_eq!(back.constraints.window.as_deref(), Some("22:00-05:00"));
6857    }
6858
6859    #[test]
6860    fn constraints_empty_is_skipped_when_serialising() {
6861        let s = schedule_with(
6862            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6863            RunsOn::Backend,
6864        );
6865        let json = serde_json::to_value(&s).expect("serialise");
6866        assert!(
6867            json.get("constraints").is_none(),
6868            "empty constraints must not appear on the wire: {json}"
6869        );
6870    }
6871
6872    #[test]
6873    fn window_no_constraint_always_allows() {
6874        let c = Constraints::default();
6875        assert!(c.allows(chrono::Utc::now(), ScheduleTz::Local));
6876    }
6877
6878    #[test]
6879    fn window_same_day_is_half_open() {
6880        use chrono::TimeZone;
6881        let s = with_window("09:00-17:00");
6882        let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
6883        let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
6884        assert!(!a(at(8, 59)), "before start");
6885        assert!(a(at(9, 0)), "at start (inclusive)");
6886        assert!(a(at(16, 59)), "inside");
6887        assert!(!a(at(17, 0)), "at end (exclusive)");
6888        assert!(!a(at(23, 0)), "after end");
6889    }
6890
6891    #[test]
6892    fn window_crossing_midnight() {
6893        use chrono::TimeZone;
6894        let s = with_window("22:00-05:00");
6895        let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
6896        let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
6897        assert!(a(at(22, 0)), "at start tonight");
6898        assert!(a(at(23, 30)), "late tonight");
6899        assert!(a(at(3, 0)), "early tomorrow");
6900        assert!(!a(at(5, 0)), "at end (exclusive)");
6901        assert!(!a(at(12, 0)), "midday outside");
6902        assert!(!a(at(21, 59)), "just before start");
6903    }
6904
6905    #[test]
6906    fn window_respects_tz() {
6907        // The same instant is inside the window under one tz and may
6908        // be outside under another. Compare UTC vs Local via the
6909        // host's own offset (kept CI-green on UTC runners like the
6910        // active tz test does).
6911        use chrono::TimeZone;
6912        let s = with_window("09:00-17:00");
6913        let noon_utc = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 12, 0, 0).unwrap();
6914        // Under UTC, 12:00 is inside 09:00-17:00.
6915        assert!(s.constraints.allows(noon_utc, ScheduleTz::Utc));
6916        // Under Local, the verdict tracks the host wall-clock time;
6917        // assert it matches a direct wall_time membership check.
6918        let local_t = noon_utc.with_timezone(&chrono::Local).time();
6919        let in_local = local_t >= chrono::NaiveTime::from_hms_opt(9, 0, 0).unwrap()
6920            && local_t < chrono::NaiveTime::from_hms_opt(17, 0, 0).unwrap();
6921        assert_eq!(s.constraints.allows(noon_utc, ScheduleTz::Local), in_local);
6922    }
6923
6924    #[test]
6925    fn validate_accepts_good_window() {
6926        for w in ["09:00-17:00", "22:00-05:00", "00:00-23:59"] {
6927            with_window(w)
6928                .validate()
6929                .unwrap_or_else(|e| panic!("'{w}' should validate: {e}"));
6930        }
6931    }
6932
6933    #[test]
6934    fn validate_rejects_bad_window() {
6935        for bad in ["9-5", "22:00", "22:00-22:00", "25:00-05:00", "09:00_17:00"] {
6936            let err = with_window(bad).validate().unwrap_err();
6937            assert!(
6938                err.contains("constraints.window"),
6939                "for '{bad}', got: {err}"
6940            );
6941        }
6942    }
6943
6944    // ---- constraints.skip_dates (#418 holiday exclusion) ----
6945
6946    fn with_skip_dates(dates: &[&str]) -> Schedule {
6947        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
6948        s.tz = ScheduleTz::Utc; // host-independent date assertions
6949        s.constraints.skip_dates = dates.iter().map(|d| (*d).to_string()).collect();
6950        s
6951    }
6952
6953    #[test]
6954    fn allows_blocks_listed_skip_date() {
6955        use chrono::TimeZone;
6956        let s = with_skip_dates(&["2026-06-10", "2026-12-25"]);
6957        // Any time on a listed date is blocked (whole day).
6958        let on = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap();
6959        assert!(!s.constraints.allows(on, ScheduleTz::Utc));
6960        let on_midnight = chrono::Utc.with_ymd_and_hms(2026, 12, 25, 0, 0, 0).unwrap();
6961        assert!(!s.constraints.allows(on_midnight, ScheduleTz::Utc));
6962        // A date not in the list fires normally.
6963        let off = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
6964        assert!(s.constraints.allows(off, ScheduleTz::Utc));
6965    }
6966
6967    #[test]
6968    fn allows_corrupt_skip_date_fails_closed() {
6969        use chrono::TimeZone;
6970        // A garbled entry (only reachable via hand-edited KV) blocks
6971        // rather than silently re-enabling fires — same posture as a
6972        // corrupt window.
6973        let s = with_skip_dates(&["not-a-date"]);
6974        let any = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
6975        assert!(!s.constraints.allows(any, ScheduleTz::Utc));
6976    }
6977
6978    #[test]
6979    fn validate_accepts_good_skip_dates() {
6980        with_skip_dates(&["2026-01-01", "2026-12-25", "2027-05-03"])
6981            .validate()
6982            .expect("well-formed skip dates should validate");
6983    }
6984
6985    #[test]
6986    fn validate_rejects_bad_skip_date() {
6987        for bad in ["2026-13-01", "01-01-2026", "nope", "2026/01/01"] {
6988            let err = with_skip_dates(&[bad]).validate().unwrap_err();
6989            assert!(
6990                err.contains("constraints.skip_dates"),
6991                "for '{bad}', got: {err}"
6992            );
6993        }
6994    }
6995
6996    #[test]
6997    fn preview_skips_holidays() {
6998        use chrono::TimeZone;
6999        // Daily 09:00 with two of the next five days marked as holidays
7000        // — preview drops exactly those, since it gates on `allows`.
7001        let mut s = cal_utc("09:00", &[]);
7002        s.constraints.skip_dates = vec!["2026-06-11".into(), "2026-06-13".into()];
7003        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
7004        let got = s.preview_fires(now, 4);
7005        let want: Vec<_> = [
7006            (2026, 6, 10),
7007            (2026, 6, 12), // skips 06-11
7008            (2026, 6, 14), // skips 06-13
7009            (2026, 6, 15),
7010        ]
7011        .iter()
7012        .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
7013        .collect();
7014        assert_eq!(got, want);
7015    }
7016
7017    // ---- constraints.max_concurrent (#418) ----
7018
7019    fn with_max_concurrent(max: u32, runs_on: RunsOn) -> Schedule {
7020        let mut s = schedule_with(
7021            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
7022            runs_on,
7023        );
7024        s.constraints.max_concurrent = Some(max);
7025        s
7026    }
7027
7028    #[test]
7029    fn validate_accepts_backend_max_concurrent() {
7030        with_max_concurrent(5, RunsOn::Backend)
7031            .validate()
7032            .expect("backend max_concurrent should validate");
7033    }
7034
7035    #[test]
7036    fn validate_rejects_max_concurrent_on_agent() {
7037        // Decision E: a central running-instance cap needs a central
7038        // counter, which agents don't have.
7039        let err = with_max_concurrent(5, RunsOn::Agent)
7040            .validate()
7041            .unwrap_err();
7042        assert!(err.contains("constraints.max_concurrent"), "got: {err}");
7043        assert!(err.contains("runs_on: agent"), "got: {err}");
7044    }
7045
7046    #[test]
7047    fn validate_rejects_zero_max_concurrent() {
7048        let err = with_max_concurrent(0, RunsOn::Backend)
7049            .validate()
7050            .unwrap_err();
7051        assert!(err.contains("max_concurrent must be >= 1"), "got: {err}");
7052    }
7053
7054    #[test]
7055    fn max_concurrent_round_trips_and_skips_when_absent() {
7056        let s = with_max_concurrent(3, RunsOn::Backend);
7057        let json = serde_json::to_value(&s.constraints).expect("ser");
7058        assert_eq!(json.get("max_concurrent").and_then(|v| v.as_u64()), Some(3));
7059        // A schedule with no constraints omits the whole block.
7060        let bare = schedule_with(
7061            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7062            RunsOn::Backend,
7063        );
7064        assert!(bare.constraints.is_empty());
7065    }
7066
7067    #[test]
7068    fn window_fail_closed_on_corrupt_blob() {
7069        // A malformed window (only reachable via a hand-edited KV
7070        // blob — validate() rejects it at create) must BLOCK, not
7071        // silently allow fires during a change-freeze (gemini #452).
7072        let s = with_window("22:00_05:00");
7073        assert!(
7074            !s.constraints.allows(chrono::Utc::now(), ScheduleTz::Utc),
7075            "corrupt window fails closed"
7076        );
7077        // …and the scheduler can surface why it's stuck.
7078        assert!(
7079            s.bad_window().is_some(),
7080            "bad_window reports the parse error"
7081        );
7082        assert!(with_window("22:00-05:00").bad_window().is_none());
7083    }
7084
7085    #[test]
7086    fn calendar_outside_window_is_flagged() {
7087        // at 09:00 can never fall in 22:00-05:00 → never fires.
7088        let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
7089        s.constraints.window = Some("22:00-05:00".into());
7090        assert!(s.calendar_outside_window(), "09:00 is not in 22:00-05:00");
7091
7092        // at 23:00 IS inside the overnight window → fine.
7093        let mut s = schedule_with(calendar("23:00", &[]), RunsOn::Backend);
7094        s.constraints.window = Some("22:00-05:00".into());
7095        assert!(!s.calendar_outside_window(), "23:00 is in 22:00-05:00");
7096
7097        // reconcile shapes are never flagged (they poll every minute).
7098        let mut s = schedule_with(
7099            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
7100            RunsOn::Backend,
7101        );
7102        s.constraints.window = Some("22:00-05:00".into());
7103        assert!(!s.calendar_outside_window(), "reconcile is unaffected");
7104
7105        // no window → never flagged.
7106        let s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
7107        assert!(!s.calendar_outside_window());
7108    }
7109
7110    // ---- on_failure.retry (#418 Phase 4) ----
7111
7112    fn with_retry(max: u32, backoff: &str) -> Schedule {
7113        let mut s = schedule_with(
7114            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
7115            RunsOn::Backend,
7116        );
7117        s.on_failure.retry = Some(Retry {
7118            max,
7119            backoff: backoff.into(),
7120        });
7121        s
7122    }
7123
7124    #[test]
7125    fn on_failure_parses_and_round_trips() {
7126        let yaml = r#"
7127id: x
7128when:
7129  per_pc: { every: 6h }
7130job_id: y
7131target: { all: true }
7132on_failure:
7133  retry: { max: 3, backoff: 10m }
7134"#;
7135        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7136        let r = s.on_failure.retry.as_ref().expect("retry present");
7137        assert_eq!(r.max, 3);
7138        assert_eq!(r.backoff, "10m");
7139        let back: Schedule =
7140            serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
7141        assert_eq!(back.on_failure, s.on_failure);
7142    }
7143
7144    #[test]
7145    fn on_failure_empty_is_skipped_when_serialising() {
7146        let s = schedule_with(
7147            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7148            RunsOn::Backend,
7149        );
7150        let json = serde_json::to_value(&s).expect("serialise");
7151        assert!(
7152            json.get("on_failure").is_none(),
7153            "empty on_failure must not appear on the wire: {json}"
7154        );
7155    }
7156
7157    #[test]
7158    fn validate_accepts_good_retry() {
7159        for (max, backoff) in [(1, "30s"), (3, "10m"), (10, "1h")] {
7160            with_retry(max, backoff)
7161                .validate()
7162                .unwrap_or_else(|e| panic!("retry {{max:{max}, backoff:{backoff}}}: {e}"));
7163        }
7164    }
7165
7166    #[test]
7167    fn validate_rejects_bad_backoff() {
7168        let err = with_retry(3, "soon").validate().unwrap_err();
7169        assert!(err.contains("on_failure.retry.backoff"), "got: {err}");
7170    }
7171
7172    #[test]
7173    fn validate_rejects_sub_second_backoff() {
7174        // "500ms" parses as humantime but lowers to 0s on the wire —
7175        // reject it so the operator doesn't get a silent no-wait
7176        // (coderabbit #466).
7177        for bad in ["500ms", "0s", "999ms"] {
7178            let err = with_retry(3, bad).validate().unwrap_err();
7179            assert!(
7180                err.contains("on_failure.retry.backoff must be >= 1s"),
7181                "for '{bad}', got: {err}"
7182            );
7183        }
7184    }
7185
7186    #[test]
7187    fn validate_rejects_out_of_range_max() {
7188        for bad in [0u32, 11, 1000] {
7189            let err = with_retry(bad, "10m").validate().unwrap_err();
7190            assert!(
7191                err.contains("on_failure.retry.max"),
7192                "for max={bad}, got: {err}"
7193            );
7194        }
7195    }
7196
7197    #[test]
7198    fn lowered_retry_reduces_backoff_to_seconds() {
7199        let s = with_retry(3, "10m");
7200        let spec = s.on_failure.lowered_retry().expect("a retry policy");
7201        assert_eq!(spec.max, 3);
7202        assert_eq!(spec.backoff_secs, 600);
7203    }
7204
7205    #[test]
7206    fn lowered_retry_is_none_without_policy() {
7207        let s = schedule_with(
7208            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7209            RunsOn::Backend,
7210        );
7211        assert!(s.on_failure.lowered_retry().is_none());
7212    }
7213
7214    // ---- global change-freeze (#418 Phase 5) ----
7215
7216    #[test]
7217    fn freeze_empty_window_is_always_active() {
7218        // The big-red-button shape: no bounds = frozen until cleared.
7219        let f = Freeze::default();
7220        assert!(f.is_active(chrono::Utc::now()));
7221    }
7222
7223    #[test]
7224    fn freeze_window_is_half_open() {
7225        use chrono::TimeZone;
7226        let f = Freeze {
7227            from: Some("2026-12-20T00:00:00+00:00".into()),
7228            until: Some("2027-01-05T00:00:00+00:00".into()),
7229            reason: Some("year-end".into()),
7230            tz: ScheduleTz::Utc,
7231        };
7232        let at = |y, mo, d| chrono::Utc.with_ymd_and_hms(y, mo, d, 0, 0, 0).unwrap();
7233        assert!(!f.is_active(at(2026, 12, 19)), "before from = not frozen");
7234        assert!(f.is_active(at(2026, 12, 20)), "from is inclusive");
7235        assert!(f.is_active(at(2026, 12, 31)), "inside window");
7236        assert!(!f.is_active(at(2027, 1, 5)), "until is exclusive");
7237        assert!(!f.is_active(at(2027, 1, 6)), "after until = not frozen");
7238    }
7239
7240    #[test]
7241    fn freeze_fails_closed_on_corrupt_bound() {
7242        // A freeze is a safety switch: an unparseable bound (only
7243        // reachable via a hand-edited KV blob) must read as FROZEN, not
7244        // "fire normally" (coderabbit #472) — the opposite of `active`,
7245        // which fail-opens.
7246        let f = Freeze {
7247            from: Some("not-a-date".into()),
7248            until: None,
7249            reason: None,
7250            tz: ScheduleTz::Utc,
7251        };
7252        assert!(f.is_active(chrono::Utc::now()), "corrupt bound → frozen");
7253    }
7254
7255    #[test]
7256    fn freeze_validate_accepts_good_bounds() {
7257        Freeze {
7258            from: Some("2026-12-20".into()),
7259            until: Some("2027-01-05T12:00:00+09:00".into()),
7260            reason: None,
7261            tz: ScheduleTz::Local,
7262        }
7263        .validate()
7264        .expect("date + rfc3339 bounds should validate");
7265        // Empty (indefinite) freeze is valid.
7266        Freeze::default().validate().expect("empty freeze is valid");
7267    }
7268
7269    #[test]
7270    fn freeze_validate_rejects_bad_bound_and_inverted_window() {
7271        let err = Freeze {
7272            from: Some("never".into()),
7273            ..Default::default()
7274        }
7275        .validate()
7276        .unwrap_err();
7277        assert!(err.contains("freeze:"), "got: {err}");
7278
7279        let inverted = Freeze {
7280            from: Some("2027-01-05".into()),
7281            until: Some("2026-12-20".into()),
7282            ..Default::default()
7283        }
7284        .validate()
7285        .unwrap_err();
7286        assert!(inverted.contains("freeze.from"), "got: {inverted}");
7287    }
7288
7289    #[test]
7290    fn freeze_round_trips_and_skips_empty_fields() {
7291        let f = Freeze {
7292            from: None,
7293            until: Some("2027-01-05".into()),
7294            reason: Some("INC-1234".into()),
7295            tz: ScheduleTz::Utc,
7296        };
7297        let json = serde_json::to_value(&f).expect("serialise");
7298        assert!(json.get("from").is_none(), "empty from omitted: {json}");
7299        let back: Freeze = serde_json::from_value(json).expect("round-trip");
7300        assert_eq!(back, f);
7301    }
7302
7303    #[test]
7304    fn shipped_schedule_configs_parse_and_validate() {
7305        // Every YAML under configs/schedules/ must parse with the
7306        // current Schedule serde AND pass validate() — keeps the
7307        // shipped examples from drifting out of sync with the model
7308        // (#418 removed back-compat, so drift = broken at create).
7309        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../configs/schedules");
7310        let mut seen = 0;
7311        for entry in std::fs::read_dir(&dir).expect("read configs/schedules") {
7312            let path = entry.expect("dir entry").path();
7313            if path.extension().and_then(|e| e.to_str()) != Some("yaml") {
7314                continue;
7315            }
7316            let body = std::fs::read_to_string(&path).expect("read yaml");
7317            let s: Schedule = serde_yaml::from_str(&body)
7318                .unwrap_or_else(|e| panic!("{} failed to parse: {e}", path.display()));
7319            s.validate()
7320                .unwrap_or_else(|e| panic!("{} failed validate(): {e}", path.display()));
7321            seen += 1;
7322        }
7323        assert!(seen > 0, "no schedule YAMLs found in {}", dir.display());
7324    }
7325
7326    // ---- pre-existing enum wire formats (unchanged by #418) ----
7327
7328    #[test]
7329    fn exec_mode_serialises_snake_case() {
7330        for (mode, expected) in [
7331            (ExecMode::EveryTick, "every_tick"),
7332            (ExecMode::OncePerPc, "once_per_pc"),
7333            (ExecMode::OncePerTarget, "once_per_target"),
7334        ] {
7335            let s = serde_json::to_value(mode).expect("serialise");
7336            assert_eq!(s, serde_json::Value::String(expected.into()));
7337            let back: ExecMode = serde_json::from_value(serde_json::Value::String(expected.into()))
7338                .expect("deserialise");
7339            assert_eq!(back, mode, "round-trip for {expected}");
7340        }
7341    }
7342
7343    #[test]
7344    fn schedule_runs_on_defaults_to_backend() {
7345        let yaml = r#"
7346id: x
7347when:
7348  per_pc: once
7349job_id: y
7350target: { all: true }
7351"#;
7352        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7353        assert_eq!(s.runs_on, RunsOn::Backend);
7354    }
7355
7356    #[test]
7357    fn schedule_runs_on_agent_parses() {
7358        let yaml = r#"
7359id: offline-inv
7360when:
7361  per_pc: { every: 1h }
7362job_id: inventory-hw
7363target: { all: true }
7364runs_on: agent
7365"#;
7366        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7367        assert_eq!(s.runs_on, RunsOn::Agent);
7368        assert_eq!(s.lowered().mode, ExecMode::OncePerPc);
7369    }
7370
7371    #[test]
7372    fn runs_on_serialises_snake_case() {
7373        for (mode, expected) in [(RunsOn::Backend, "backend"), (RunsOn::Agent, "agent")] {
7374            let s = serde_json::to_value(mode).expect("serialise");
7375            assert_eq!(s, serde_json::Value::String(expected.into()));
7376            let back: RunsOn = serde_json::from_value(serde_json::Value::String(expected.into()))
7377                .expect("deserialise");
7378            assert_eq!(back, mode);
7379        }
7380    }
7381
7382    #[test]
7383    fn execute_shell_into_wire_shell() {
7384        assert_eq!(Shell::from(ExecuteShell::Powershell), Shell::Powershell);
7385        assert_eq!(Shell::from(ExecuteShell::Cmd), Shell::Cmd);
7386        assert_eq!(Shell::from(ExecuteShell::Sh), Shell::Sh);
7387        assert_eq!(Shell::from(ExecuteShell::Pwsh), Shell::Pwsh);
7388    }
7389
7390    #[test]
7391    fn execute_shell_parses_sh_and_pwsh() {
7392        // The manifest `execute.shell` accepts the two new lowercase
7393        // tokens end-to-end (serde), so an operator can author a Linux
7394        // job.
7395        for (yaml_shell, want) in [("sh", ExecuteShell::Sh), ("pwsh", ExecuteShell::Pwsh)] {
7396            let yaml = format!(
7397                "id: x\nversion: 1.0.0\nexecute:\n  shell: {yaml_shell}\n  script: \"echo\"\n  timeout: 1s\n"
7398            );
7399            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
7400            assert_eq!(m.execute.shell, want, "shell {yaml_shell}");
7401        }
7402    }
7403
7404    #[test]
7405    fn manifest_staleness_defaults_to_cached() {
7406        let yaml = r#"
7407id: x
7408version: 1.0.0
7409execute:
7410  shell: powershell
7411  script: "echo"
7412  timeout: 1s
7413"#;
7414        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7415        assert_eq!(m.staleness, Staleness::Cached);
7416    }
7417
7418    #[test]
7419    fn manifest_strict_staleness_parses() {
7420        let yaml = r#"
7421id: urgent-patch
7422version: 2.5.1
7423execute:
7424  shell: powershell
7425  script: Install-Hotfix
7426  timeout: 5m
7427staleness:
7428  mode: strict
7429  max_cache_age: 0s
7430"#;
7431        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7432        match m.staleness {
7433            Staleness::Strict { max_cache_age } => assert_eq!(max_cache_age, "0s"),
7434            other => panic!("expected strict, got {other:?}"),
7435        }
7436    }
7437
7438    #[test]
7439    fn manifest_unchecked_staleness_parses() {
7440        let yaml = r#"
7441id: legacy
7442version: 0.1.0
7443execute:
7444  shell: cmd
7445  script: "echo"
7446  timeout: 1s
7447staleness:
7448  mode: unchecked
7449"#;
7450        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7451        assert_eq!(m.staleness, Staleness::Unchecked);
7452    }
7453
7454    #[test]
7455    fn missing_required_field_errors() {
7456        // `id` missing.
7457        let yaml = r#"
7458version: 1.0.0
7459target: { all: true }
7460execute:
7461  shell: powershell
7462  script: "echo"
7463  timeout: 1s
7464"#;
7465        let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
7466        assert!(r.is_err(), "expected error, got {:?}", r);
7467    }
7468
7469    #[test]
7470    fn display_field_table_kind_round_trips_with_nested_columns() {
7471        // #39: `type: table` + `columns:` on a DisplayField gets
7472        // round-tripped through serde so the SPA receives the
7473        // nested schema verbatim. Nested columns themselves are
7474        // DisplayFields so they can carry `type: bytes` /
7475        // `type: number` for cell formatting.
7476        let yaml = r#"
7477id: inv-hw
7478version: 1.0.0
7479execute:
7480  shell: powershell
7481  script: "echo"
7482  timeout: 60s
7483inventory:
7484  display:
7485    - field: hostname
7486      label: Hostname
7487    - field: disks
7488      label: Disks
7489      type: table
7490      columns:
7491        - field: device_id
7492          label: Drive
7493        - field: size_bytes
7494          label: Size
7495          type: bytes
7496        - field: free_bytes
7497          label: Free
7498          type: bytes
7499        - field: file_system
7500          label: FS
7501"#;
7502        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7503        let inv = m.inventory.as_ref().expect("inventory hint");
7504        let disks = inv
7505            .display
7506            .iter()
7507            .find(|d| d.field == "disks")
7508            .expect("disks display row");
7509        assert_eq!(disks.kind.as_deref(), Some("table"));
7510        let cols = disks.columns.as_ref().expect("table needs columns");
7511        assert_eq!(cols.len(), 4);
7512        assert_eq!(cols[1].field, "size_bytes");
7513        assert_eq!(cols[1].kind.as_deref(), Some("bytes"));
7514    }
7515
7516    #[test]
7517    fn display_field_scalar_kind_keeps_columns_none() {
7518        // Defensive: when type is a scalar (`bytes` / `number` /
7519        // `timestamp`) the `columns` field stays None — the SPA
7520        // uses its presence as the "render nested table" signal,
7521        // so it must not leak in via serde defaults.
7522        let yaml = r#"
7523id: x
7524version: 1.0.0
7525execute:
7526  shell: powershell
7527  script: "echo"
7528  timeout: 5s
7529inventory:
7530  display:
7531    - { field: ram_bytes, label: RAM, type: bytes }
7532"#;
7533        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7534        let inv = m.inventory.as_ref().unwrap();
7535        assert!(inv.display[0].columns.is_none());
7536    }
7537
7538    // ---- GroupDef (#1032 dynamic groups) ----
7539
7540    fn group_def(yaml: &str) -> Result<GroupDef, String> {
7541        let g: GroupDef = crate::strict::from_yaml_str(yaml).map_err(|e| e.to_string())?;
7542        g.validate().map(|()| g)
7543    }
7544
7545    #[test]
7546    fn group_def_static_members_valid() {
7547        let g = group_def("id: pilot\nmembers: [PC-A, PC-B]\n").expect("valid static group");
7548        assert_eq!(g.members, vec!["PC-A", "PC-B"]);
7549        assert!(g.dynamic_query().is_none());
7550    }
7551
7552    #[test]
7553    fn group_def_dynamic_query_valid() {
7554        let g = group_def(
7555            "id: clients\nquery: \"SELECT pc_id FROM agents WHERE hostname LIKE 'X%'\"\nrefresh: 30m\n",
7556        )
7557        .expect("valid dynamic group");
7558        assert_eq!(
7559            g.dynamic_query(),
7560            Some("SELECT pc_id FROM agents WHERE hostname LIKE 'X%'")
7561        );
7562        assert_eq!(g.refresh_interval(), std::time::Duration::from_secs(1800));
7563    }
7564
7565    #[test]
7566    fn group_def_refresh_defaults_when_absent() {
7567        let g = group_def("id: c\nquery: \"SELECT pc_id FROM agents\"\n").unwrap();
7568        assert_eq!(g.refresh_interval(), DEFAULT_GROUP_REFRESH);
7569    }
7570
7571    #[test]
7572    fn group_def_rejects_neither_members_nor_query() {
7573        let err = group_def("id: empty\n").unwrap_err();
7574        assert!(err.contains("either"), "err: {err}");
7575    }
7576
7577    #[test]
7578    fn group_def_rejects_both_members_and_query() {
7579        let err = group_def("id: both\nmembers: [PC-A]\nquery: \"SELECT pc_id FROM agents\"\n")
7580            .unwrap_err();
7581        assert!(err.contains("mutually exclusive"), "err: {err}");
7582    }
7583
7584    #[test]
7585    fn group_def_blank_query_is_unset_not_both() {
7586        // An empty-string query reads as unset, so a members group with a
7587        // commented-out (emptied) query is still valid, not a "both set" error.
7588        let g =
7589            group_def("id: pilot\nmembers: [PC-A]\nquery: \"\"\n").expect("blank query = unset");
7590        assert!(g.dynamic_query().is_none());
7591    }
7592
7593    #[test]
7594    fn group_def_rejects_bad_id_charset() {
7595        let err = group_def("id: bad/id\nmembers: [PC-A]\n").unwrap_err();
7596        assert!(err.contains("group.id"), "err: {err}");
7597    }
7598
7599    #[test]
7600    fn group_def_rejects_untrimmed_id() {
7601        // A padded id validated-as-trimmed but stored-raw would be a KV key
7602        // nothing matches — reject it outright (the id is used verbatim).
7603        let err = group_def("id: \" clients \"\nmembers: [PC-A]\n").unwrap_err();
7604        assert!(err.contains("group.id"), "err: {err}");
7605    }
7606
7607    #[test]
7608    fn group_def_rejects_bad_refresh() {
7609        let err =
7610            group_def("id: c\nquery: \"SELECT pc_id FROM agents\"\nrefresh: soon\n").unwrap_err();
7611        assert!(err.contains("refresh"), "err: {err}");
7612    }
7613
7614    #[test]
7615    fn group_def_rejects_unknown_key() {
7616        // Strict parse (#492) — a typo'd key is an operator error, not silently
7617        // dropped.
7618        let err = group_def("id: c\nmembers: [PC-A]\nrlue: x\n").unwrap_err();
7619        assert!(err.to_lowercase().contains("unknown"), "err: {err}");
7620    }
7621
7622    // ---- checked-in JSON Schema freshness (docs/schemas/) ----
7623
7624    /// The JSON Schemas under `docs/schemas/` must match what
7625    /// `schema_for!` produces today — a Cargo.lock-style freshness guard
7626    /// so a `Schedule` / `Manifest` field change can't silently drift
7627    /// the operator-facing schema. The SPA editor, the backend
7628    /// `/api/schemas/*` endpoints, and these files all read the same
7629    /// derived shape; this test fails CI if the checked-in copy lags.
7630    /// Regenerate with:
7631    ///   `UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current`
7632    #[test]
7633    fn schema_files_are_current() {
7634        assert_schema_file("schedule.schema.json", &schemars::schema_for!(Schedule));
7635        assert_schema_file("job.schema.json", &schemars::schema_for!(Manifest));
7636        assert_schema_file("view.schema.json", &schemars::schema_for!(View));
7637        assert_schema_file("group-def.schema.json", &schemars::schema_for!(GroupDef));
7638    }
7639
7640    fn assert_schema_file(name: &str, schema: &schemars::Schema) {
7641        let generated = serde_json::to_string_pretty(schema).expect("serialize schema") + "\n";
7642        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7643            .join("../../docs/schemas")
7644            .join(name);
7645        if std::env::var_os("UPDATE_SCHEMAS").is_some() {
7646            std::fs::create_dir_all(path.parent().unwrap()).expect("mkdir docs/schemas");
7647            std::fs::write(&path, &generated).unwrap_or_else(|e| panic!("write {path:?}: {e}"));
7648            return;
7649        }
7650        // Normalize CRLF→LF before comparing: `.gitattributes` already
7651        // pins these files to `eol=lf`, but a stray CRLF working-tree
7652        // copy (autocrlf, a tool rewrite) shouldn't turn a *content*-
7653        // freshness check into a confusing line-ending failure — that's
7654        // .gitattributes' job, not this test's (gemini #588).
7655        let on_disk = std::fs::read_to_string(&path)
7656            .unwrap_or_else(|e| {
7657                panic!(
7658                    "read {path:?}: {e}\n\
7659                     generate it with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
7660                )
7661            })
7662            .replace("\r\n", "\n");
7663        assert_eq!(
7664            on_disk, generated,
7665            "{name} is stale — a Schedule/Manifest schema change isn't reflected in docs/schemas/. \
7666             Refresh with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
7667        );
7668    }
7669}
7670
7671/// Periodic schedule (spec §2.4.3). v0.18.0 carries the fanout plan
7672/// (target + optional rollout + optional jitter) inline; the
7673/// referenced job (`job_id` → [`BUCKET_JOBS`]) supplies only the
7674/// script body. Two schedules of the same job can target different
7675/// groups on different cadences without copying the manifest.
7676///
7677/// #418 Phase 1: the cadence is the single [`When`] field. The old
7678/// `cron` × `mode` × `cooldown` × `auto_disable_when_done` quartet
7679/// is gone (no back-compat — pre-Phase-1 KV blobs fail to parse and
7680/// are warn-skipped; re-`schedule create` to upgrade them). The
7681/// engine underneath is unchanged: [`Schedule::lowered`] maps `when`
7682/// onto the same (cron, ExecMode, cooldown) trio the scheduler and
7683/// `decide_fire` always ran on.
7684#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
7685pub struct Schedule {
7686    pub id: String,
7687    /// When to fire — a reconcile cadence (`per_pc` / `per_target`)
7688    /// or a calendar time trigger (`at` / `days`). See [`When`].
7689    ///
7690    /// `singleton_map`: serde_yaml 0.9 renders externally-tagged
7691    /// enums as `!per_pc` YAML tags by default; this keeps the
7692    /// operator-facing map shape (`when: { per_pc: once }`). JSON
7693    /// output is identical either way, and the schemars schema
7694    /// (external tagging = oneOf of single-key objects) already
7695    /// matches the singleton-map wire shape.
7696    #[serde(with = "serde_yaml::with::singleton_map")]
7697    #[schemars(with = "When")]
7698    pub when: When,
7699    /// Key into [`crate::kv::BUCKET_JOBS`]. Must equal a registered
7700    /// Manifest's `id`.
7701    pub job_id: String,
7702    /// Who + how-to-phase + when-to-stagger. The Manifest doesn't
7703    /// carry these any more — same job + different fanout = different
7704    /// schedule.
7705    #[serde(flatten)]
7706    pub plan: FanoutPlan,
7707    /// Optional validity window. Outside `[from, until)` the
7708    /// schedule is dormant — still registered, still visible, but
7709    /// every tick is skipped (deleted ≠ dormant: a campaign that
7710    /// ended stays inspectable and can be re-armed by editing the
7711    /// window). Checked at tick time on both the backend scheduler
7712    /// and the agent's local scheduler.
7713    #[serde(default, skip_serializing_if = "Active::is_empty")]
7714    pub active: Active,
7715    /// #418 operational constraints gating *when within an active
7716    /// period* a fire may happen: a maintenance `window`, a fleet
7717    /// `max_concurrent` cap, and `skip_dates` (holiday exclusion). The
7718    /// wall-clock ones are evaluated in the schedule's `tz`; future
7719    /// `require` (env gates) lands in the same namespace. Checked at
7720    /// tick time on both schedulers (and surfaced by `preview`).
7721    #[serde(default, skip_serializing_if = "Constraints::is_empty")]
7722    pub constraints: Constraints,
7723    /// #418 Phase 4: what to do after a fire's script comes back
7724    /// failed. Currently just `retry` (fixed-backoff in-process
7725    /// re-run); future `notify` / `disable` join the same namespace.
7726    /// Applied fire-side in `handle_command` (the retry policy is
7727    /// lowered onto every Command this schedule produces), so it
7728    /// covers both `runs_on` locations.
7729    #[serde(default, skip_serializing_if = "OnFailure::is_empty")]
7730    pub on_failure: OnFailure,
7731    /// #418 Phase 2: the timezone this schedule's wall-clock fields
7732    /// are evaluated in — both the calendar `at` firing time AND the
7733    /// `active.{from,until}` window bounds. `local` (default) = the
7734    /// running host's TZ (the agent's for `runs_on: agent`, the
7735    /// backend server's otherwise); `utc` for TZ-independent
7736    /// schedules. Reconcile shapes (`per_pc`/`per_target`) ignore it
7737    /// for firing (poll cron runs every minute regardless) but still
7738    /// honor it for the `active` window.
7739    #[serde(default)]
7740    pub tz: ScheduleTz,
7741    /// v0.22: optional humantime window after a cron tick during
7742    /// which the Command is still considered "live". The scheduler
7743    /// computes `tick_at + starting_deadline` and stamps it onto
7744    /// each Command as `deadline_at`; agents skip Commands they
7745    /// receive after that absolute time. `None` (default) = no
7746    /// deadline, meaning a Command queued in the broker / stream
7747    /// during agent downtime runs whenever the agent reconnects —
7748    /// good for kitting / inventory / cleanup. Set this for
7749    /// time-of-day notifications, lunch reminders, etc., where
7750    /// "fire 3 hours late" would be wrong.
7751    #[serde(default, skip_serializing_if = "Option::is_none")]
7752    pub starting_deadline: Option<String>,
7753    /// v0.23: where does the cron tick happen? `Backend` (default,
7754    /// historical) = backend's scheduler fires Commands via NATS;
7755    /// agents passively receive. `Agent` = each targeted agent runs
7756    /// its own internal cron and fires locally, so the schedule
7757    /// keeps ticking even when the broker is unreachable (laptop on
7758    /// the train, broker maintenance window, full WAN outage). The
7759    /// two locations are mutually exclusive — when `Agent`, the
7760    /// backend scheduler stays out and just keeps the definition in
7761    /// KV for agents to read.
7762    #[serde(default)]
7763    pub runs_on: RunsOn,
7764    #[serde(default = "default_true")]
7765    pub enabled: bool,
7766    /// Free-form operator taxonomy for the Schedules page — the
7767    /// schedule-side mirror of `Manifest.tags` (added in #640; a plain
7768    /// code ref rather than an intra-doc link, since that field isn't
7769    /// on this branch until #640 merges). Purely a SPA-side
7770    /// organisational aid (search / filter chips alongside the
7771    /// id-prefix grouping); the scheduler never reads it, so any
7772    /// string is allowed and it carries no firing semantics. A
7773    /// schedule's own tags are independent of its job's: the same job
7774    /// may back a `weekly` maintenance schedule and a `canary` rollout
7775    /// schedule. Empty by default and `skip_serializing_if`-elided per
7776    /// the #492 gradual-upgrade wire rule.
7777    #[serde(default, skip_serializing_if = "Vec::is_empty")]
7778    pub tags: Vec<String>,
7779    /// GitOps provenance (#695) — see [`RepoOrigin`]. Stamped by
7780    /// `kanade schedule create` when the source YAML lives inside a Git
7781    /// work tree, so the SPA renders the schedule read-only and points
7782    /// edits back at the repo (SPEC design principle #3: 設定駆動 YAML +
7783    /// Git), parity with a job's [`Manifest::origin`]. `None` for
7784    /// SPA-born schedules and ones applied from outside any repo. Purely
7785    /// informational — the scheduler never reads it. New field ⇒ #492
7786    /// wire rule (`default` + `skip_serializing_if`).
7787    #[serde(default, skip_serializing_if = "Option::is_none")]
7788    pub origin: Option<RepoOrigin>,
7789}
7790
7791impl Schedule {
7792    /// Every valid top-level key on a Schedule YAML/JSON document —
7793    /// this struct's own fields PLUS the fields of the
7794    /// `#[serde(flatten)] plan: FanoutPlan`. The strict create
7795    /// boundary needs this because serde's flatten buffering hides
7796    /// unknown top-level keys from `serde_ignored`, so a typo like
7797    /// `jiter:` or `enabledd:` would otherwise be silently dropped
7798    /// (#924). Kept in sync with the field list by
7799    /// `schedule_top_level_keys_cover_serialized_fields`.
7800    pub const TOP_LEVEL_KEYS: &'static [&'static str] = &[
7801        // Schedule's own fields:
7802        "id",
7803        "when",
7804        "job_id",
7805        "active",
7806        "constraints",
7807        "on_failure",
7808        "tz",
7809        "starting_deadline",
7810        "runs_on",
7811        "enabled",
7812        "tags",
7813        "origin",
7814        // flattened FanoutPlan:
7815        "target",
7816        "rollout",
7817        "jitter",
7818        "deadline_at",
7819    ];
7820}
7821
7822impl crate::strict::StrictSchema for Schedule {
7823    fn strict_top_level_keys() -> Option<&'static [&'static str]> {
7824        Some(Self::TOP_LEVEL_KEYS)
7825    }
7826}
7827
7828/// Manifest has no `#[serde(flatten)]` field, so `serde_ignored`
7829/// already catches every top-level typo — the default (`None`) is
7830/// correct.
7831impl crate::strict::StrictSchema for Manifest {}
7832
7833/// View likewise has no flattened field.
7834impl crate::strict::StrictSchema for View {}
7835
7836/// GroupDef likewise has no flattened field.
7837impl crate::strict::StrictSchema for GroupDef {}
7838
7839/// v0.23 — where the cron tick fires from.
7840#[derive(
7841    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
7842)]
7843#[serde(rename_all = "snake_case")]
7844pub enum RunsOn {
7845    /// Backend's central scheduler ticks and publishes Commands to
7846    /// NATS. Historical default, what every pre-v0.23 schedule
7847    /// uses. Agent offline ⇒ Command queued in STREAM_EXEC; agent
7848    /// reconnects ⇒ catch-up via [`command_replay`](crate)
7849    /// (see kanade-agent's command_replay module).
7850    #[default]
7851    Backend,
7852    /// Each targeted agent runs the cron tick locally. Survives
7853    /// broker / WAN outages. Best for laptops / mobile devices that
7854    /// roam off the corporate network. Agent must be online for the
7855    /// initial schedule + job-catalog pull, but once cached the
7856    /// agent fires the script standalone.
7857    Agent,
7858}
7859
7860/// Per-pc/per-target dedup semantics for a [`Schedule`] (v0.19).
7861#[derive(
7862    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
7863)]
7864#[serde(rename_all = "snake_case")]
7865pub enum ExecMode {
7866    /// Fire on every cron tick at the whole target. Historical
7867    /// (pre-v0.19) behavior; no dedup.
7868    #[default]
7869    EveryTick,
7870    /// Fire at each pc until that pc succeeds; then skip it until
7871    /// the optional cooldown elapses (or forever if no cooldown).
7872    /// Use for kitting / first-boot / per-pc compliance checks.
7873    OncePerPc,
7874    /// Fire at the whole target until **any** pc succeeds; then
7875    /// skip the whole target until the optional cooldown elapses
7876    /// (or forever if no cooldown). Use for "one delegate is
7877    /// enough" tasks like license check-in.
7878    OncePerTarget,
7879    /// Like [`OncePerPc`](ExecMode::OncePerPc), but the "already
7880    /// succeeded ⇒ skip" check is scoped to the CURRENT manifest
7881    /// version: a pc whose only successful run recorded an OLDER
7882    /// manifest version re-fires so the new version reaches it. Bumping
7883    /// the job's YAML `version` is the redistribution trigger. Plain
7884    /// `OncePerPc` (kitting) is version-blind — a pc that ever succeeded
7885    /// is skipped forever; this mode re-arms per version. per_pc only —
7886    /// `Schedule::validate` rejects `per_target: once_per_version`.
7887    OncePerPcVersion,
7888    /// #418 OS-native event trigger (`when: { on: [...] }`). There is
7889    /// no cron — the agent fires it from an OS event source (boot /
7890    /// session-change), not a tick — so the scheduler skips
7891    /// `tokio-cron` registration for it. Each event occurrence fires
7892    /// once, gated by the standard freeze / active / window /
7893    /// skip_dates checks.
7894    Event,
7895}
7896
7897/// #418 Phase 1 — the single "when does this fire" axis.
7898///
7899/// Replaces the old `cron` + `mode` + `cooldown` trio whose
7900/// interactions were implicit (cron doubled as both a real
7901/// time-of-day trigger and a reconcile poll period; contradictory
7902/// combinations silently no-opped). Two shapes:
7903///
7904/// * **reconcile** (`per_pc` / `per_target`) — desired-state: "each
7905///   pc (or one delegate) should have run this within `every`".
7906///   The poll period is system-generated ([`POLL_CRON`], every
7907///   minute) and no longer the operator's concern.
7908/// * **calendar** (`{ at, days }`) — a wall-clock time trigger
7909///   (#418 Phase 2, replacing the old raw-cron escape hatch). Fires
7910///   the whole target at the given time, no dedup. `at: "09:00"` +
7911///   `days` repeats; `at: "2026-06-10 09:00"` (a date+time) fires
7912///   exactly once. Evaluated in the schedule's top-level `tz`.
7913#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7914#[serde(rename_all = "snake_case")]
7915pub enum When {
7916    /// Fire at each targeted pc: `once` (kitting — succeed once,
7917    /// skip forever, forever catching brand-new / re-imaged pcs)
7918    /// or `{ every: <humantime> }` (patrol — re-arm per pc after
7919    /// the interval).
7920    PerPc(PerPolicy),
7921    /// Fire until **any** one pc of the target succeeds, then skip
7922    /// the whole target (`once`) or re-arm after `every`. Needs
7923    /// fleet-wide completion data, so it is backend-only —
7924    /// `runs_on: agent` + `per_target` is rejected by
7925    /// [`Schedule::validate`].
7926    PerTarget(PerPolicy),
7927    /// Calendar time trigger: `{ at: "09:00", days: [mon-fri] }`
7928    /// (repeating) or `{ at: "2026-06-10 09:00" }` (one-shot). Fires
7929    /// the whole target at that wall-clock time in the schedule's
7930    /// `tz` — no dedup, no cooldown.
7931    Calendar(CalendarSpec),
7932    /// #418 OS-native event trigger: `when: { on: [startup, logon] }`.
7933    /// Fires when the agent observes the listed OS event(s) rather than
7934    /// on a clock — there is no cron. `runs_on: agent` only (the agent
7935    /// owns the event source); [`Schedule::validate`] rejects it on
7936    /// `backend` and rejects an empty list. Each event occurrence fires
7937    /// once, gated by the same freeze / active / `constraints.window` /
7938    /// `skip_dates` checks as the cron path. `startup` fires once per OS
7939    /// boot (deduped via the host boot time); a `starting_deadline`, if
7940    /// set, limits it to "agent came up within that long after boot".
7941    On(Vec<OnTrigger>),
7942}
7943
7944/// An OS event the agent can fire a schedule on (#418 `when: { on }`).
7945#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash)]
7946#[serde(rename_all = "snake_case")]
7947pub enum OnTrigger {
7948    /// Once per OS boot (the agent's first run for that boot). Catches
7949    /// freshly-imaged / reinstalled hosts at their next startup.
7950    Startup,
7951    /// On an interactive-session user logon — console, RDP, or
7952    /// auto-logon (Windows `WTS_SESSION_LOGON`). Does not fire for
7953    /// service / network / batch logons (no interactive session).
7954    Logon,
7955    /// When the workstation is locked (Win+L / idle lock; Windows
7956    /// `WTS_SESSION_LOCK`). Use for step-away compliance / cleanup.
7957    Lock,
7958    /// When the workstation is unlocked — the user returns to a locked
7959    /// session (Windows `WTS_SESSION_UNLOCK`). Use to re-check
7960    /// compliance / refresh state when work resumes.
7961    Unlock,
7962    /// When the host's network changes — IP address table change on
7963    /// connect / disconnect / DHCP renew / VPN / Wi-Fi roam (Windows
7964    /// `NotifyAddrChange`). Debounced agent-side (a burst of changes
7965    /// from one transition fires once after the network settles), so
7966    /// use it for "re-check connectivity / re-register on network move"
7967    /// rather than expecting one fire per raw adapter event.
7968    ///
7969    /// IPv4 only: `NotifyAddrChange` watches the IPv4 address table, so a
7970    /// transition that touches only IPv6 addresses won't fire. In practice
7971    /// dual-stack networks change both tables together, but a pure-IPv6
7972    /// move (e.g. an IPv6-only Wi-Fi roam) is not detected.
7973    NetworkChange,
7974}
7975
7976/// Calendar time trigger (#418 Phase 2). `at` is either a time of
7977/// day (`"HH:MM"`, repeating — combine with `days`) or a full
7978/// date+time (`"YYYY-MM-DD HH:MM"`, a one-shot that fires once and
7979/// never again). Evaluated in the schedule's top-level `tz`.
7980#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7981pub struct CalendarSpec {
7982    /// `"HH:MM"` (24h) for a repeating trigger, or
7983    /// `"YYYY-MM-DD HH:MM"` (hyphen / slash / `T` separators all
7984    /// accepted) for a one-shot. Parsed lazily —
7985    /// [`Schedule::validate`] rejects garbage at create time.
7986    pub at: String,
7987    /// Day-of-week filter for a time-of-day `at`: `["mon-fri"]`,
7988    /// `["mon","wed","fri"]`, … (passed verbatim to the cron DOW
7989    /// field, so ranges and names both work). An **nth-weekday**
7990    /// `["tue#2"]` fires only on the 2nd Tuesday of each month
7991    /// ("Patch Tuesday"); the ordinal is `1..5`. A **last-weekday**
7992    /// `["friL"]` fires only on the last Friday of each month (handy
7993    /// for monthly maintenance). Empty = every day. Must be empty
7994    /// when `at` carries a date (the date already pins the day).
7995    #[serde(default, skip_serializing_if = "Vec::is_empty")]
7996    pub days: Vec<String>,
7997}
7998
7999/// Parsed `CalendarSpec.at`: the wall-clock minute/hour, plus the
8000/// date for a one-shot (`None` = repeating time-of-day).
8001struct ParsedAt {
8002    minute: u32,
8003    hour: u32,
8004    date: Option<chrono::NaiveDate>,
8005}
8006
8007impl CalendarSpec {
8008    /// Parse `at`: a date+time (`YYYY-MM-DD HH:MM`, hyphen / slash /
8009    /// `T` separators) is a one-shot; a bare `HH:MM` is repeating.
8010    fn parse_at(&self) -> Result<ParsedAt, String> {
8011        use chrono::Timelike;
8012        let s = self.at.trim();
8013        for fmt in ["%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y/%m/%d %H:%M"] {
8014            if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, fmt) {
8015                return Ok(ParsedAt {
8016                    minute: dt.minute(),
8017                    hour: dt.hour(),
8018                    date: Some(dt.date()),
8019                });
8020            }
8021        }
8022        if let Ok(t) = chrono::NaiveTime::parse_from_str(s, "%H:%M") {
8023            return Ok(ParsedAt {
8024                minute: t.minute(),
8025                hour: t.hour(),
8026                date: None,
8027            });
8028        }
8029        Err(format!(
8030            "when.at: unparseable '{}' (want HH:MM or YYYY-MM-DD HH:MM)",
8031            self.at
8032        ))
8033    }
8034
8035    /// Pre-flight check on the `days` tokens so a bad day name gives
8036    /// a `when.days:`-scoped error instead of croner's confusing
8037    /// "when.at lowered to invalid cron" (claude #432 review). Each
8038    /// token is a day name (`mon`..`sun`), a numeric DOW (`0`..`7`),
8039    /// `*`, a `-` range of those, an **nth-weekday** like `tue#2`
8040    /// (2nd Tuesday of the month — "Patch Tuesday"), or a
8041    /// **last-weekday** like `friL` (last Friday of the month).
8042    fn validate_days(&self) -> Result<(), String> {
8043        const NAMES: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
8044        let is_day = |p: &str| NAMES.contains(&p) || p.parse::<u8>().is_ok_and(|n| n <= 7);
8045        for tok in &self.days {
8046            // Report the whole token on a malformed range like `mon-`
8047            // (which would otherwise split to a cryptic empty part —
8048            // claude #432 follow-up).
8049            let invalid = |reason: &str| {
8050                Err(format!(
8051                    "when.days: invalid day token '{tok}' ({reason}; \
8052                     want mon..sun, 0-7, a range like mon-fri, an nth-weekday \
8053                     like tue#2, a last-weekday like friL, or *)"
8054                ))
8055            };
8056            // #418: nth-weekday suffix (`tue#2` = 2nd Tuesday). Croner
8057            // accepts `<dow>#<n>` (n = 1..5) in the DOW field, and
8058            // `to_cron` passes the token through verbatim, so the
8059            // engine fires only on that occurrence. It's a single
8060            // weekday + ordinal — not combinable with a range.
8061            if let Some((day_part, nth_part)) = tok.split_once('#') {
8062                // Normalize once and use `d` consistently (gemini #547);
8063                // the outer `invalid` already echoes the raw `tok`.
8064                let d = day_part.trim().to_ascii_lowercase();
8065                if d.contains('-') || !is_day(&d) {
8066                    return invalid("the part before # must be a single weekday");
8067                }
8068                match nth_part.trim().parse::<u8>() {
8069                    Ok(n) if (1..=5).contains(&n) => {}
8070                    _ => return invalid("the # ordinal must be 1..5 (e.g. tue#2 = 2nd Tuesday)"),
8071                }
8072                continue;
8073            }
8074            // #418: last-weekday suffix (`friL` = last Friday of the
8075            // month — the monthly-maintenance sibling of Patch Tuesday).
8076            // Croner accepts `<dow>L` in the DOW field with verified
8077            // last-<dow>-of-month semantics, and `to_cron` passes it
8078            // through verbatim. A single weekday + `L` — bare `L` and
8079            // ranges are rejected (croner would read bare `L` as
8080            // Saturday, which is a confusing footgun).
8081            if let Some(day_part) = tok.strip_suffix(['L', 'l']) {
8082                // No `.trim()`: a cron DOW token can't carry internal
8083                // whitespace, so `"fri L"` must be *rejected* here (its
8084                // strip leaves `"fri "`, and `is_day` catches the space)
8085                // rather than trimmed into a clean `"fri"` that then
8086                // produces a malformed `fri L` cron downstream and a
8087                // confusing croner error (gemini #560).
8088                let d = day_part.to_ascii_lowercase();
8089                if d.is_empty() {
8090                    return invalid("`L` (last-weekday) needs a weekday before it, e.g. friL");
8091                }
8092                if d.contains('-') || !is_day(&d) {
8093                    return invalid(
8094                        "the part before L must be a single weekday (e.g. friL = last Friday)",
8095                    );
8096                }
8097                continue;
8098            }
8099            for part in tok.split('-') {
8100                let p = part.trim().to_ascii_lowercase();
8101                if p.is_empty() {
8102                    return invalid("empty range bound");
8103                }
8104                if p != "*" && !is_day(&p) {
8105                    return invalid(&format!("'{part}' is not a day"));
8106                }
8107            }
8108        }
8109        Ok(())
8110    }
8111
8112    /// For a one-shot (`at` carries a date), the absolute instant it
8113    /// fires in `tz`. `None` for a repeating calendar. Used to warn
8114    /// about a one-shot whose date is already in the past (it would
8115    /// never fire).
8116    pub fn oneshot_instant(&self, tz: ScheduleTz) -> Option<chrono::DateTime<chrono::Utc>> {
8117        let p = self.parse_at().ok()?;
8118        let date = p.date?;
8119        let naive = date.and_hms_opt(p.hour, p.minute, 0)?;
8120        tz.naive_to_utc(naive)
8121    }
8122
8123    /// The wall-clock time-of-day this calendar fires at (`None` if
8124    /// `at` is unparseable — validate() guards that). Used to detect
8125    /// a calendar whose fire time can never fall inside its
8126    /// `constraints.window` (claude #452 review).
8127    pub fn fire_time(&self) -> Option<chrono::NaiveTime> {
8128        let p = self.parse_at().ok()?;
8129        chrono::NaiveTime::from_hms_opt(p.hour, p.minute, 0)
8130    }
8131
8132    /// Lower to the cron string the scheduler engine runs. Repeating
8133    /// → 6-field `0 {min} {hour} * * {dow}`; one-shot → 7-field
8134    /// `0 {min} {hour} {day} {month} * {year}` (a past year never
8135    /// fires — that's what makes it one-shot).
8136    fn to_cron(&self) -> Result<String, String> {
8137        use chrono::Datelike;
8138        let ParsedAt { minute, hour, date } = self.parse_at()?;
8139        match date {
8140            Some(d) => {
8141                if !self.days.is_empty() {
8142                    return Err(
8143                        "when.at with a date is a one-shot and cannot be combined with days".into(),
8144                    );
8145                }
8146                Ok(format!(
8147                    "0 {minute} {hour} {} {} * {}",
8148                    d.day(),
8149                    d.month(),
8150                    d.year()
8151                ))
8152            }
8153            None => {
8154                let dow = if self.days.is_empty() {
8155                    "*".to_string()
8156                } else {
8157                    self.validate_days()?;
8158                    self.days.join(",")
8159                };
8160                Ok(format!("0 {minute} {hour} * * {dow}"))
8161            }
8162        }
8163    }
8164}
8165
8166/// The timezone a schedule's wall-clock fields (`when.at`,
8167/// `active.{from,until}`) are evaluated in (#418 Phase 2).
8168#[derive(
8169    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
8170)]
8171#[serde(rename_all = "snake_case")]
8172pub enum ScheduleTz {
8173    /// The running host's local timezone — the agent's for
8174    /// `runs_on: agent`, the backend server's otherwise. Default.
8175    #[default]
8176    Local,
8177    /// UTC — for timezone-independent schedules.
8178    Utc,
8179}
8180
8181impl ScheduleTz {
8182    /// Interpret a naive (zoneless) datetime as being in this tz and
8183    /// convert to UTC. On a DST *fold* (the local time occurs twice
8184    /// when clocks go back) we pick `.earliest()` rather than
8185    /// rejecting it; `None` is reserved for a true DST *gap* (a local
8186    /// time that never exists). `Utc` is fixed-offset so neither ever
8187    /// happens; `Local` is whatever timezone the running host is set
8188    /// to and *can* hit a gap/fold on any DST-observing host — not
8189    /// just the JST we run today (gemini + claude #432 review).
8190    fn naive_to_utc(self, naive: chrono::NaiveDateTime) -> Option<chrono::DateTime<chrono::Utc>> {
8191        use chrono::TimeZone;
8192        match self {
8193            ScheduleTz::Utc => Some(chrono::DateTime::from_naive_utc_and_offset(
8194                naive,
8195                chrono::Utc,
8196            )),
8197            ScheduleTz::Local => chrono::Local
8198                .from_local_datetime(&naive)
8199                .earliest()
8200                .map(|dt| dt.with_timezone(&chrono::Utc)),
8201        }
8202    }
8203
8204    /// The wall-clock time-of-day `now` reads as in this tz — used by
8205    /// [`Constraints::allows`] to test a maintenance window
8206    /// (#418 Phase 3). `Utc` is the naive UTC time; `Local` is the
8207    /// running host's local time.
8208    fn wall_time(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveTime {
8209        match self {
8210            ScheduleTz::Utc => now.time(),
8211            ScheduleTz::Local => now.with_timezone(&chrono::Local).time(),
8212        }
8213    }
8214
8215    /// The wall-clock *date* `now` reads as in this tz — used by
8216    /// [`Constraints::allows`] to test `skip_dates` (#418 holiday
8217    /// exclusion). Same tz semantics as [`Self::wall_time`].
8218    fn wall_date(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveDate {
8219        match self {
8220            ScheduleTz::Utc => now.date_naive(),
8221            ScheduleTz::Local => now.with_timezone(&chrono::Local).date_naive(),
8222        }
8223    }
8224
8225    /// Stable lowercase wire/display label (`local` / `utc`) — matches
8226    /// the serde `snake_case` representation. Used for the preview
8227    /// response's `tz` field so the JSON shape isn't coupled to the
8228    /// `Debug` repr (claude #578 review).
8229    pub fn as_str(self) -> &'static str {
8230        match self {
8231            ScheduleTz::Local => "local",
8232            ScheduleTz::Utc => "utc",
8233        }
8234    }
8235}
8236
8237impl std::fmt::Display for ScheduleTz {
8238    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8239        f.write_str(self.as_str())
8240    }
8241}
8242
8243/// `once` / `once_per_version` / `{ every: <humantime> }` — shared by
8244/// `per_pc` / `per_target`. Untagged so the YAML stays the bare keyword
8245/// or a one-key map, nothing more ceremonial. `once_per_version` is
8246/// per_pc + backend only (see the variant doc and `Schedule::validate`).
8247#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8248#[serde(untagged)]
8249pub enum PerPolicy {
8250    /// The bare string `once`: succeed once, then skip permanently
8251    /// (cooldown = infinity), version-blind.
8252    Once(OnceLiteral),
8253    /// The bare string `once_per_version`: succeed once *per manifest
8254    /// version*, then skip until the job's YAML `version` changes. Like
8255    /// `once` but re-arms each pc when the version it succeeded at is no
8256    /// longer current — the version-aware redistribution shape. per_pc
8257    /// only (`Schedule::validate` rejects it on `per_target`).
8258    OncePerVersion(OncePerVersionLiteral),
8259    /// Re-arm after the humantime interval, e.g. `{ every: 6h }`.
8260    Every(EverySpec),
8261}
8262
8263/// Single-variant enum so serde accepts exactly the string `once`
8264/// (a free-form `String` would swallow typos like `onec`).
8265#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
8266#[serde(rename_all = "snake_case")]
8267pub enum OnceLiteral {
8268    Once,
8269}
8270
8271/// Single-variant enum so serde accepts exactly the string
8272/// `once_per_version` (mirrors [`OnceLiteral`]'s typo-catching). The
8273/// distinct literal — rather than a bool field on `once` — keeps the
8274/// ergonomic bare-string surface (`per_pc: once_per_version`).
8275#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
8276#[serde(rename_all = "snake_case")]
8277pub enum OncePerVersionLiteral {
8278    OncePerVersion,
8279}
8280
8281/// `{ every: <humantime> }`. Standalone struct (not an inline
8282/// struct variant). `{ evry: 6h }` still fails to parse (the
8283/// required `every` key is missing), and the create boundaries
8284/// reject the unknown `evry` via [`crate::strict`] with its path —
8285/// while agents reading a future writer's extra fields tolerate
8286/// them (#492).
8287#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8288pub struct EverySpec {
8289    /// Humantime interval (`10m`, `6h`, `1d`...). Parsed lazily —
8290    /// [`Schedule::validate`] rejects garbage at create time.
8291    pub every: String,
8292}
8293
8294impl PerPolicy {
8295    /// The cooldown this policy lowers to: `once` = `None`
8296    /// (permanent skip), `every` = the interval.
8297    fn cooldown(&self) -> Option<String> {
8298        match self {
8299            // Both `once` shapes lower to "no time-based re-arm". The
8300            // version-aware re-arm for `once_per_version` is not a
8301            // cooldown — it is the version filter the scheduler applies
8302            // to the completion set, so the cooldown stays None here.
8303            PerPolicy::Once(_) | PerPolicy::OncePerVersion(_) => None,
8304            PerPolicy::Every(EverySpec { every }) => Some(every.clone()),
8305        }
8306    }
8307}
8308
8309impl std::fmt::Display for When {
8310    /// Operator-facing one-liner (`per_pc once` / `per_pc every 6h`
8311    /// / `at 09:00 [mon-fri]` / `at 2026-06-10 09:00`) for log
8312    /// lines, audit payloads and the API's `ScheduleSummary`.
8313    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8314        let policy = |p: &PerPolicy| match p {
8315            PerPolicy::Once(_) => "once".to_string(),
8316            PerPolicy::OncePerVersion(_) => "once_per_version".to_string(),
8317            PerPolicy::Every(EverySpec { every }) => format!("every {every}"),
8318        };
8319        match self {
8320            When::PerPc(p) => write!(f, "per_pc {}", policy(p)),
8321            When::PerTarget(p) => write!(f, "per_target {}", policy(p)),
8322            When::Calendar(c) if c.days.is_empty() => write!(f, "at {}", c.at),
8323            When::Calendar(c) => write!(f, "at {} [{}]", c.at, c.days.join(",")),
8324            When::On(triggers) => {
8325                let names: Vec<&str> = triggers.iter().map(|t| t.as_str()).collect();
8326                write!(f, "on [{}]", names.join(","))
8327            }
8328        }
8329    }
8330}
8331
8332impl OnTrigger {
8333    /// Lowercase wire/display label (matches the serde `snake_case`).
8334    pub fn as_str(self) -> &'static str {
8335        match self {
8336            OnTrigger::Startup => "startup",
8337            OnTrigger::Logon => "logon",
8338            OnTrigger::Lock => "lock",
8339            OnTrigger::Unlock => "unlock",
8340            OnTrigger::NetworkChange => "network_change",
8341        }
8342    }
8343}
8344
8345/// Optional validity window for a [`Schedule`] (#418 decision G).
8346/// Half-open `[from, until)`; either bound may be omitted. Bounds
8347/// are `YYYY-MM-DD` (= that day's 00:00 in the schedule's `tz`) or
8348/// full RFC3339 (offset is honored as-is, `tz` ignored). Kept as
8349/// strings so the JSON Schema the SPA editor consumes stays two
8350/// plain string fields, mirroring `jitter` / `starting_deadline`.
8351///
8352/// #418 Phase 2: bounds are evaluated in the schedule's top-level
8353/// `tz` (was UTC-only in Phase 1) so `tz: local` makes both the
8354/// calendar `at` AND the `active` window local — one consistent
8355/// timezone per schedule.
8356#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
8357pub struct Active {
8358    /// Dormant before this instant.
8359    #[serde(default, skip_serializing_if = "Option::is_none")]
8360    pub from: Option<String>,
8361    /// Dormant from this instant on (exclusive).
8362    #[serde(default, skip_serializing_if = "Option::is_none")]
8363    pub until: Option<String>,
8364}
8365
8366impl Active {
8367    /// `skip_serializing_if` helper — an empty window means "always
8368    /// active" and is omitted from the wire format entirely.
8369    pub fn is_empty(&self) -> bool {
8370        self.from.is_none() && self.until.is_none()
8371    }
8372
8373    /// Parse one bound: RFC3339 first (offset honored, `tz`
8374    /// ignored), then bare `YYYY-MM-DD` (00:00 in `tz`).
8375    pub fn parse_bound(s: &str, tz: ScheduleTz) -> Result<chrono::DateTime<chrono::Utc>, String> {
8376        if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
8377            return Ok(dt.with_timezone(&chrono::Utc));
8378        }
8379        if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
8380            let midnight = d.and_hms_opt(0, 0, 0).expect("00:00:00 is always valid");
8381            return tz.naive_to_utc(midnight).ok_or_else(|| {
8382                format!("active: bound '{s}' falls in a DST gap for the schedule's tz")
8383            });
8384        }
8385        Err(format!(
8386            "active: unparseable bound '{s}' (want YYYY-MM-DD or RFC3339)"
8387        ))
8388    }
8389
8390    /// Is `now` inside the window? Unparseable bounds are treated
8391    /// as absent here (fail-open) — [`Schedule::validate`] is the
8392    /// place that rejects them loudly; this runs on every tick and
8393    /// must never panic on a stale KV blob.
8394    pub fn contains(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
8395        let bound = |s: &Option<String>| s.as_deref().and_then(|s| Self::parse_bound(s, tz).ok());
8396        if bound(&self.from).is_some_and(|from| now < from) {
8397            return false;
8398        }
8399        if bound(&self.until).is_some_and(|until| now >= until) {
8400            return false;
8401        }
8402        true
8403    }
8404}
8405
8406/// Host-environment gate (#418 `constraints.require`). Fire only when
8407/// the target host is in the required state. Sensed **in-process by the
8408/// agent** (Win32), so it is `runs_on: agent` only — the backend cannot
8409/// read a target host's power/idle state ([`Schedule::validate`]
8410/// rejects it on `runs_on: backend`, symmetric with `when: { on }`).
8411///
8412/// Evaluated at fire time as a skip-this-tick gate (NOT in
8413/// [`Constraints::allows`], which stays pure for `preview`): a reconcile
8414/// cadence re-checks every minute (so it effectively defers until the
8415/// state is met — the intended pairing); a `calendar` fire that lands
8416/// while the state is unmet is simply missed, same as `window`. It is
8417/// therefore a *runtime* gate and does not appear in `preview`.
8418// No `Eq`: `cpu_below: Option<f64>` is only `PartialEq` (f64 is not Eq).
8419#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
8420pub struct Require {
8421    /// Fire only while on **AC power** (skip on battery). Reads
8422    /// `GetSystemPowerStatus`; an unknown/unreadable status is treated
8423    /// as not-on-AC (fail-closed — a restrictive gate must not fire
8424    /// when it can't confirm the condition). `false` (default) = no
8425    /// power requirement.
8426    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
8427    pub ac_power: bool,
8428    /// Fire only when the active console session has had **no keyboard /
8429    /// mouse input for at least this long** (humantime, e.g. `"10m"`) —
8430    /// "don't run while the user is actively working". Input-based
8431    /// (simpler than Task Scheduler's CPU/disk-aware idle). A
8432    /// headless / disconnected console (no interactive user) trivially
8433    /// satisfies it. `None` (default) = no idle requirement. Parsed
8434    /// lazily; [`Schedule::validate`] rejects garbage at create time.
8435    #[serde(default, skip_serializing_if = "Option::is_none")]
8436    pub idle: Option<String>,
8437    /// Fire only when the **whole-machine CPU usage is below this
8438    /// percent** (0–100; e.g. `20.0` = "system CPU < 20%") — "don't run
8439    /// while the box is busy". Reuses the agent's `host_perf` system CPU%
8440    /// sample (`sysinfo` mean over cores), so the reading is up to one
8441    /// `host_perf` cadence old (default 60s) — fine as a "generally
8442    /// busy?" proxy, and more accurate than a fresh one-shot read (CPU%
8443    /// needs two samples). An unavailable sample (host_perf not warmed
8444    /// up yet, or stale) is treated as "not below" (fail-closed — a
8445    /// restrictive gate must not fire when it can't confirm). `None`
8446    /// (default) = no CPU requirement. [`Schedule::validate`] rejects an
8447    /// out-of-range value at create time.
8448    #[serde(default, skip_serializing_if = "Option::is_none")]
8449    pub cpu_below: Option<f64>,
8450    /// Fire only when the host has **internet connectivity** (Windows
8451    /// `GetNetworkConnectivityHint` reports InternetAccess) — "don't run
8452    /// until online" for jobs that download / phone home. A captive
8453    /// portal (ConstrainedInternetAccess), LAN-only (LocalAccess), or
8454    /// unknown/unreadable state is treated as offline (fail-closed) — a
8455    /// portal would just fail a download, so we hold the run. For VPN /
8456    /// SASE / app-specific conditions, use a custom script gate (separate
8457    /// slice). `false` (default) = no network requirement.
8458    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
8459    pub network: bool,
8460}
8461
8462impl Require {
8463    /// `skip_serializing_if` helper for an embedded empty `require`.
8464    pub fn is_empty(&self) -> bool {
8465        !self.ac_power && self.idle.is_none() && self.cpu_below.is_none() && !self.network
8466    }
8467
8468    /// Parsed minimum-idle duration (`None` = no idle requirement, or an
8469    /// unparseable value — `validate` rejects the latter at create time).
8470    pub fn min_idle(&self) -> Option<std::time::Duration> {
8471        self.idle
8472            .as_deref()
8473            .and_then(|s| humantime::parse_duration(s.trim()).ok())
8474    }
8475
8476    /// First unparseable field for create-time rejection (mirrors
8477    /// [`Constraints::bad_skip_date`]).
8478    pub fn bad_idle(&self) -> Option<String> {
8479        self.idle.as_deref().and_then(|s| {
8480            humantime::parse_duration(s.trim())
8481                .err()
8482                .map(|e| format!("constraints.require.idle: invalid duration '{s}': {e}"))
8483        })
8484    }
8485}
8486
8487/// Host-environment state sensed by the agent, fed to [`require_met`].
8488/// A named struct (not positional args) so the growing set of sensed
8489/// signals — several of them `bool` — can't be transposed at a call
8490/// site. The Win32 sensing lives in `kanade-agent::env_gate`.
8491#[derive(Debug, Clone, Copy, Default)]
8492pub struct EnvState {
8493    /// Is the host on AC power (`false` if on battery or unreadable).
8494    pub ac_online: bool,
8495    /// How long the console has been idle (`None` = couldn't determine).
8496    pub idle: Option<std::time::Duration>,
8497    /// Whole-machine CPU usage 0–100 (`None` = no sample yet).
8498    pub cpu_pct: Option<f64>,
8499    /// Does the host have internet connectivity (`false` if offline /
8500    /// LAN-only / unreadable).
8501    pub network_up: bool,
8502}
8503
8504/// Pure env-gate decision (#418 `constraints.require`). The Win32
8505/// sensing lives in the agent (`kanade-agent::env_gate`); this is the
8506/// testable core, fed the already-sensed [`EnvState`]. Deliberately a
8507/// free fn (not folded into [`Constraints::allows`]) so `allows` stays
8508/// pure and `preview` never evaluates a runtime gate. Each set
8509/// requirement is a restrictive AND: any unmet (or unknown) gate skips.
8510pub fn require_met(req: &Require, env: &EnvState) -> bool {
8511    if req.ac_power && !env.ac_online {
8512        return false;
8513    }
8514    if let Some(min) = req.min_idle() {
8515        match env.idle {
8516            Some(d) if d >= min => {}
8517            _ => return false,
8518        }
8519    }
8520    if let Some(max) = req.cpu_below {
8521        match env.cpu_pct {
8522            Some(p) if p < max => {}
8523            _ => return false,
8524        }
8525    }
8526    if req.network && !env.network_up {
8527        return false;
8528    }
8529    true
8530}
8531
8532/// [`Active`] decides *over what date range* a schedule is live,
8533/// `Constraints` decides *when, within an active period,* a fire is
8534/// allowed: `window` (a maintenance time-of-day window),
8535/// `max_concurrent` (a fleet-wide running-instance cap), `skip_dates`
8536/// (holiday exclusion) and `require` (host-environment gates, agent-only
8537/// — see [`Require`]).
8538// No `Eq`: contains `require: Option<Require>` which holds an f64.
8539#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
8540pub struct Constraints {
8541    /// `"HH:MM-HH:MM"` wall-clock window (evaluated in the schedule's
8542    /// `tz`). Fires outside it are skipped — mainly for reconcile
8543    /// cadences ("patrol every 6h, but only fire overnight") and
8544    /// daytime change-freezes. `start > end` crosses midnight
8545    /// (`"22:00-05:00"` = 22:00 through 05:00 next morning). Parsed
8546    /// lazily; [`Schedule::validate`] rejects garbage at create time.
8547    #[serde(default, skip_serializing_if = "Option::is_none")]
8548    pub window: Option<String>,
8549    /// Fleet-wide cap on how many instances of this schedule's job may
8550    /// run **at the same time** (#418 "同時実行ハード上限"). The
8551    /// backend scheduler counts the job's still-in-flight runs
8552    /// (`execution_results.finished_at IS NULL`) each tick and only
8553    /// dispatches to as many remaining pcs as there are free slots —
8554    /// a rolling window that refills as runs complete. Useful for
8555    /// disk/CPU/network-heavy jobs you don't want hammering the whole
8556    /// fleet at once.
8557    ///
8558    /// **Backend-only** (it needs a central counter): combining it
8559    /// with `runs_on: agent` is rejected by [`Schedule::validate`]
8560    /// (#418 decision E — "中央上限には中央が要る"). Most meaningful
8561    /// for `per_pc` reconcile cadences, where the poll re-ticks and
8562    /// refills slots. `None` (default) = no cap.
8563    #[serde(default, skip_serializing_if = "Option::is_none")]
8564    pub max_concurrent: Option<u32>,
8565    /// Calendar dates the schedule must **not** fire on — holidays,
8566    /// blackout days, one-off freeze dates (#418 "祝日除外"). Each is
8567    /// `YYYY-MM-DD`, evaluated as a wall-clock date in the schedule's
8568    /// `tz`. Applies to every `when` shape (a reconcile cadence skips
8569    /// the whole day; a calendar fire landing on the date is
8570    /// suppressed) and is honored by both the live scheduler and
8571    /// `preview`, since both gate on [`Constraints::allows`]. Empty
8572    /// (default) = no skips. Operator-supplied: there is no built-in
8573    /// holiday calendar — list the dates you care about. Parsed lazily;
8574    /// [`Schedule::validate`] rejects a malformed date at create time.
8575    #[serde(default, skip_serializing_if = "Vec::is_empty")]
8576    pub skip_dates: Vec<String>,
8577    /// Host-environment gate (#418): fire only when the target host is
8578    /// in the required state (on AC power, idle). Agent-sensed at fire
8579    /// time, `runs_on: agent` only. See [`Require`]. `None` (default) =
8580    /// no environment requirement.
8581    #[serde(default, skip_serializing_if = "Option::is_none")]
8582    pub require: Option<Require>,
8583}
8584
8585impl Constraints {
8586    /// `skip_serializing_if` helper — empty constraints are omitted
8587    /// from the wire format entirely.
8588    pub fn is_empty(&self) -> bool {
8589        self.window.is_none()
8590            && self.max_concurrent.is_none()
8591            && self.skip_dates.is_empty()
8592            && self.require.as_ref().is_none_or(Require::is_empty)
8593    }
8594
8595    /// The first unparseable `skip_dates` entry, if any — the
8596    /// scheduler logs it at register time so a fail-closed
8597    /// (never-firing) schedule from a hand-edited KV blob is
8598    /// diagnosable, mirroring [`Schedule::bad_window`].
8599    pub fn bad_skip_date(&self) -> Option<String> {
8600        self.skip_dates.iter().find_map(|s| {
8601            chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d")
8602                .err()
8603                .map(|e| format!("constraints.skip_dates: invalid date '{s}': {e}"))
8604        })
8605    }
8606
8607    /// Parse `"HH:MM-HH:MM"` into `(start, end)`. Equal bounds are an
8608    /// error (a zero-width or all-day window is ambiguous — write no
8609    /// window for "always").
8610    pub fn parse_window(s: &str) -> Result<(chrono::NaiveTime, chrono::NaiveTime), String> {
8611        let (a, b) = s
8612            .split_once('-')
8613            .ok_or_else(|| format!("constraints.window: '{s}' must be 'HH:MM-HH:MM'"))?;
8614        let parse = |part: &str| {
8615            chrono::NaiveTime::parse_from_str(part.trim(), "%H:%M")
8616                .map_err(|e| format!("constraints.window: invalid time '{}': {e}", part.trim()))
8617        };
8618        let (start, end) = (parse(a)?, parse(b)?);
8619        if start == end {
8620            return Err(format!(
8621                "constraints.window: start and end are equal ('{s}'); omit window for 'always'"
8622            ));
8623        }
8624        Ok((start, end))
8625    }
8626
8627    /// Is a fire allowed at `now` (evaluated in `tz`)? No window =
8628    /// always allowed. Half-open `[start, end)`; `start > end`
8629    /// crosses midnight.
8630    ///
8631    /// **Fail-closed** on an unparseable window (returns `false`,
8632    /// gemini #452 review): a window is a *restrictive* constraint
8633    /// (change-freeze / overnight-only), so a corrupt one must NOT
8634    /// silently allow fires during the restricted hours. Bad windows
8635    /// are rejected at create time by [`Schedule::validate`]; this
8636    /// only bites a hand-edited KV blob, where blocking is the safe
8637    /// direction. The scheduler warns at register time
8638    /// ([`Schedule::bad_window`]) so a stuck schedule is diagnosable.
8639    /// The tick path never panics regardless.
8640    pub fn allows(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
8641        // #418 holiday / blackout dates: never fire on a listed wall
8642        // date (in `tz`). Checked before the window since a skipped day
8643        // overrides any within-window allowance. Fail-closed on a
8644        // corrupt entry (same posture as `window`): a skip date is a
8645        // *restrictive* constraint, so a garbled one must not silently
8646        // re-enable fires — it blocks until fixed (`validate` rejects it
8647        // at create time; `bad_skip_date` lets the scheduler warn).
8648        if !self.skip_dates.is_empty() {
8649            let today = tz.wall_date(now);
8650            let blocked = self.skip_dates.iter().any(|s| {
8651                match chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d") {
8652                    Ok(d) => d == today,
8653                    Err(_) => true, // corrupt entry → fail-closed (block)
8654                }
8655            });
8656            if blocked {
8657                return false;
8658            }
8659        }
8660        match self.window.as_deref() {
8661            // No window → always allowed.
8662            None => true,
8663            // Window set: membership, or fail-closed if unparseable
8664            // (`window_contains` returns None for a corrupt window).
8665            Some(_) => self.window_contains(tz.wall_time(now)).unwrap_or(false),
8666        }
8667    }
8668
8669    /// Membership of a wall-clock time-of-day in the window. `None`
8670    /// when there is no window or it's unparseable (callers decide
8671    /// the failure direction). `start > end` crosses midnight.
8672    fn window_contains(&self, t: chrono::NaiveTime) -> Option<bool> {
8673        let (start, end) = Self::parse_window(self.window.as_deref()?).ok()?;
8674        Some(if start <= end {
8675            start <= t && t < end
8676        } else {
8677            t >= start || t < end
8678        })
8679    }
8680}
8681
8682/// What to do when a fire's script fails (#418 Phase 4 — the "高"
8683/// retry/backoff gap). Where [`Constraints`] gates *whether* a fire
8684/// happens, `OnFailure` decides what happens *after* one ran and
8685/// came back bad. Only `retry` so far; future `notify` / `disable`
8686/// would join the same namespace.
8687#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
8688pub struct OnFailure {
8689    /// Re-run the script in-process when it exits non-zero (or times
8690    /// out), up to a cap, with a fixed backoff between attempts.
8691    /// `None` (default) = no retry: a failed run is published as-is
8692    /// and (for reconcile cadences) simply re-fires on the next poll
8693    /// tick. See [`Retry`].
8694    #[serde(default, skip_serializing_if = "Option::is_none")]
8695    pub retry: Option<Retry>,
8696}
8697
8698impl OnFailure {
8699    /// `skip_serializing_if` helper — an empty policy is omitted from
8700    /// the wire format entirely.
8701    pub fn is_empty(&self) -> bool {
8702        self.retry.is_none()
8703    }
8704
8705    /// Lower the operator-facing `retry` (humantime backoff) onto the
8706    /// engine vocabulary the agent's executor runs on (backoff in
8707    /// whole seconds). Single seam shared by the backend command
8708    /// builder and the agent's local scheduler so the two stamp the
8709    /// same [`crate::wire::RetrySpec`] onto every Command. Returns
8710    /// `None` when there is no retry policy or the backoff is
8711    /// unparseable (validate() rejects the latter at create time;
8712    /// this stays fail-safe = "no retry" for a hand-edited KV blob
8713    /// rather than panicking on the fire path).
8714    pub fn lowered_retry(&self) -> Option<crate::wire::RetrySpec> {
8715        let r = self.retry.as_ref()?;
8716        let backoff_secs = humantime::parse_duration(&r.backoff).ok()?.as_secs();
8717        Some(crate::wire::RetrySpec {
8718            max: r.max,
8719            backoff_secs,
8720        })
8721    }
8722}
8723
8724/// Fixed-backoff retry policy (#418 Phase 4). `max` is the number of
8725/// *additional* attempts after the first run (so `max: 3` = up to 4
8726/// total executions); `backoff` is the humantime delay slept between
8727/// attempts. The retry happens fire-side (inside `kanade fire` /
8728/// `handle_command`) on every OS for the PoC — the Windows-native
8729/// "restart on failure" Task Scheduler path is deferred to the
8730/// native-delegation phase (#418 decision H).
8731#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8732pub struct Retry {
8733    /// Max additional attempts after the first failure. Bounded
8734    /// `1..=10` by [`Schedule::validate`] — a typo'd `max: 1000`
8735    /// with a short backoff would otherwise pin a flapping script in
8736    /// a tight loop for the whole window.
8737    pub max: u32,
8738    /// Humantime delay slept between attempts (`"10m"`, `"30s"`).
8739    pub backoff: String,
8740}
8741
8742/// Fleet-wide change-freeze (#418 Phase 5 — the "メンテナンス窓 /
8743/// 変更凍結" gap's global half). Where [`Constraints::window`] is a
8744/// *per-schedule* time-of-day gate, a `Freeze` is a *single, fleet-
8745/// global* "stop all automated change" switch the operator flips
8746/// during an incident or a year-end change-freeze. It lives in its
8747/// own KV singleton ([`crate::kv::KEY_FREEZE`]); when present and
8748/// active, both the backend scheduler and every agent's local
8749/// scheduler skip *every* fire.
8750///
8751/// Shapes:
8752/// * `{}` (no bounds) — frozen indefinitely until the operator
8753///   clears it (incident "big red button").
8754/// * `{ from, until }` — frozen only within `[from, until)`,
8755///   evaluated in `tz` (planned change-freeze; auto-thaws).
8756///
8757/// The KV key being *absent* means "not frozen" — so clearing the
8758/// freeze is a KV delete, and `is_active` only ever runs on a freeze
8759/// the operator actually set.
8760#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
8761pub struct Freeze {
8762    /// Frozen from this instant (RFC3339 or bare `YYYY-MM-DD` in
8763    /// `tz`). `None` ⇒ frozen from the beginning of time.
8764    #[serde(default, skip_serializing_if = "Option::is_none")]
8765    pub from: Option<String>,
8766    /// Thawed from this instant on, exclusive. `None` ⇒ frozen with
8767    /// no scheduled end (manual clear required).
8768    #[serde(default, skip_serializing_if = "Option::is_none")]
8769    pub until: Option<String>,
8770    /// Operator-supplied note surfaced on the freeze-skip log and the
8771    /// SPA banner ("year-end change freeze", "INC-1234"). Advisory.
8772    #[serde(default, skip_serializing_if = "Option::is_none")]
8773    pub reason: Option<String>,
8774    /// Timezone the bare-date bounds are evaluated in (RFC3339 bounds
8775    /// carry their own offset). Defaults to host-local like a
8776    /// schedule's `tz`.
8777    #[serde(default)]
8778    pub tz: ScheduleTz,
8779}
8780
8781impl Freeze {
8782    /// Is the fleet frozen at `now`? An empty window (`from`/`until`
8783    /// both absent) is frozen unconditionally; otherwise membership of
8784    /// `[from, until)` in `tz`. Half-open like [`Active::contains`],
8785    /// but **fails CLOSED** on an unparseable bound — a freeze is a
8786    /// safety switch, so a corrupt window (only reachable via a
8787    /// hand-edited KV blob; `validate` rejects it at set time) must
8788    /// mean "frozen", not "fire normally" (coderabbit #472). This is
8789    /// the one deliberate divergence from `active`'s fail-OPEN
8790    /// behaviour, where an unparseable bound dormant-skips a schedule.
8791    pub fn is_active(&self, now: chrono::DateTime<chrono::Utc>) -> bool {
8792        // Parse a bound; an unparseable one short-circuits the whole
8793        // check to `true` (frozen) via the closure's `None` sentinel
8794        // handled below.
8795        let bound = |s: &Option<String>| -> Result<Option<chrono::DateTime<chrono::Utc>>, ()> {
8796            match s.as_deref() {
8797                None => Ok(None),
8798                Some(raw) => Active::parse_bound(raw, self.tz).map(Some).map_err(|_| ()),
8799            }
8800        };
8801        let (from, until) = match (bound(&self.from), bound(&self.until)) {
8802            (Ok(f), Ok(u)) => (f, u),
8803            // Any corrupt bound → fail closed (frozen).
8804            _ => return true,
8805        };
8806        if from.is_some_and(|f| now < f) {
8807            return false;
8808        }
8809        if until.is_some_and(|u| now >= u) {
8810            return false;
8811        }
8812        true
8813    }
8814
8815    /// Reject unparseable bounds / `from >= until` at set time (the
8816    /// API + CLI counterpart to [`Schedule::validate`]).
8817    pub fn validate(&self) -> Result<(), String> {
8818        let from = self
8819            .from
8820            .as_deref()
8821            .map(|s| Active::parse_bound(s, self.tz))
8822            .transpose()
8823            .map_err(|e| e.replace("active:", "freeze:"))?;
8824        let until = self
8825            .until
8826            .as_deref()
8827            .map(|s| Active::parse_bound(s, self.tz))
8828            .transpose()
8829            .map_err(|e| e.replace("active:", "freeze:"))?;
8830        if let (Some(f), Some(u)) = (from, until) {
8831            if f >= u {
8832                return Err(format!(
8833                    "freeze.from ({}) must be strictly before freeze.until ({})",
8834                    self.from.as_deref().unwrap_or_default(),
8835                    self.until.as_deref().unwrap_or_default(),
8836                ));
8837            }
8838        }
8839        Ok(())
8840    }
8841}
8842
8843/// The system-generated poll cadence every reconcile-shaped `when`
8844/// lowers to. Operators never write this: the real inter-run
8845/// spacing is the `every` cooldown; this only bounds "how soon do
8846/// we notice somebody is due" (#418 decision B took the poll
8847/// period away from the operator).
8848pub const POLL_CRON: &str = "0 * * * * *";
8849
8850/// What a [`When`] lowers to — the exact (cron, mode, cooldown)
8851/// trio the pre-#418 engine ran on. Keeping the engine vocabulary
8852/// unchanged is what lets Phase 1 swap the operator surface without
8853/// touching the tick / dedup machinery.
8854pub struct Lowered {
8855    /// Cron handed to `tokio-cron-scheduler` — [`POLL_CRON`] for
8856    /// reconcile shapes, a 6/7-field cron for calendar shapes.
8857    pub cron: String,
8858    /// Dedup semantics for `decide_fire`.
8859    pub mode: ExecMode,
8860    /// Humantime re-arm interval (`None` = succeed once, skip
8861    /// forever).
8862    pub cooldown: Option<String>,
8863    /// Timezone to evaluate `cron` in (#418 Phase 2). The scheduler
8864    /// passes this to `Job::new_async_tz`. Reconcile shapes carry
8865    /// the schedule's tz too even though POLL_CRON is tz-agnostic,
8866    /// so the same value drives the `active`-window check.
8867    pub tz: ScheduleTz,
8868}
8869
8870impl Schedule {
8871    /// The error message if this schedule's `constraints.window` is
8872    /// set but unparseable, else `None`. The scheduler logs this at
8873    /// register time so a fail-closed (never-firing) schedule from a
8874    /// hand-edited KV blob is diagnosable (gemini #452 review).
8875    pub fn bad_window(&self) -> Option<String> {
8876        let w = self.constraints.window.as_deref()?;
8877        Constraints::parse_window(w).err()
8878    }
8879
8880    /// True when this is a `calendar` schedule whose fire time can
8881    /// never fall inside its `constraints.window` — the cron fires,
8882    /// the window check rejects it, and (firing only at that
8883    /// time-of-day) it effectively never runs. An easy misconfig to
8884    /// set up by accident; the scheduler warns at register time
8885    /// (claude #452 review). Reconcile shapes poll every minute, so
8886    /// they always catch the window opening and aren't affected.
8887    pub fn calendar_outside_window(&self) -> bool {
8888        let When::Calendar(c) = &self.when else {
8889            return false;
8890        };
8891        let Some(t) = c.fire_time() else {
8892            return false;
8893        };
8894        matches!(self.constraints.window_contains(t), Some(false))
8895    }
8896
8897    /// Up to `count` future instants this schedule will fire, as
8898    /// absolute UTC, strictly after `now` — the dry-run / preview
8899    /// surface (#418 "ドライラン / プレビュー"). Only **calendar**
8900    /// schedules have discrete fire times; reconcile shapes
8901    /// (`per_pc`/`per_target`) poll every minute gated by cooldown, so
8902    /// they return an empty vec and the caller describes the cadence
8903    /// instead. Occurrences outside the `active.{from,until}` window or
8904    /// the `constraints.window` are **skipped**, so the list reflects
8905    /// when the schedule will ACTUALLY run, not the raw cron ticks.
8906    /// Evaluated in the schedule's `tz`, exactly like the scheduler's
8907    /// `Job::new_async_tz`, and with the same croner config the
8908    /// scheduler / [`Schedule::validate`] use, so a preview can never
8909    /// disagree with a real fire. A schedule that can never fire (a
8910    /// calendar time wholly outside its window, a past one-shot,
8911    /// `enabled: false` is *not* considered here — callers gate on
8912    /// `enabled` separately) yields an empty vec.
8913    pub fn preview_fires(
8914        &self,
8915        now: chrono::DateTime<chrono::Utc>,
8916        count: usize,
8917    ) -> Vec<chrono::DateTime<chrono::Utc>> {
8918        use croner::parser::{CronParser, Seconds};
8919        if !matches!(self.when, When::Calendar(_)) {
8920            return Vec::new();
8921        }
8922        // Same lowering + croner config as `next_calendar_fire` and the
8923        // live scheduler, so a preview can never disagree with a real
8924        // fire. `preview_fires` adds the N-occurrence walk and the
8925        // active / window filtering on top of that single seam.
8926        let lowered = self.lowered();
8927        let Ok(cron) = CronParser::builder()
8928            .seconds(Seconds::Required)
8929            .dom_and_dow(true)
8930            .build()
8931            .parse(&lowered.cron)
8932        else {
8933            return Vec::new();
8934        };
8935        let accept = |utc: chrono::DateTime<chrono::Utc>| {
8936            self.active.contains(utc, self.tz) && self.constraints.allows(utc, self.tz)
8937        };
8938        match self.tz {
8939            ScheduleTz::Utc => Self::next_occurrences(&cron, now, count, accept),
8940            ScheduleTz::Local => {
8941                Self::next_occurrences(&cron, now.with_timezone(&chrono::Local), count, accept)
8942            }
8943        }
8944    }
8945
8946    /// Walk croner forward from `after` collecting up to `count`
8947    /// accepted occurrences (converted to UTC). Generic over the tz the
8948    /// cron is evaluated in so `preview_fires` can run it in either
8949    /// `Utc` or `Local` without duplicating the loop.
8950    fn next_occurrences<Tz>(
8951        cron: &croner::Cron,
8952        after: chrono::DateTime<Tz>,
8953        count: usize,
8954        accept: impl Fn(chrono::DateTime<chrono::Utc>) -> bool,
8955    ) -> Vec<chrono::DateTime<chrono::Utc>>
8956    where
8957        Tz: chrono::TimeZone,
8958    {
8959        // Bound the scan so an `active`/window dead-end (every future
8960        // tick rejected) can't spin forever: ~4096 raw ticks covers
8961        // >10y of a daily calendar while staying instant for croner.
8962        const SCAN_CAP: usize = 4096;
8963        let mut out = Vec::with_capacity(count.min(SCAN_CAP));
8964        let mut cursor = after;
8965        let mut scanned = 0usize;
8966        while out.len() < count && scanned < SCAN_CAP {
8967            scanned += 1;
8968            let Ok(next) = cron.find_next_occurrence(&cursor, false) else {
8969                break;
8970            };
8971            let utc = next.with_timezone(&chrono::Utc);
8972            if accept(utc) {
8973                out.push(utc);
8974            }
8975            // `find_next_occurrence(.., inclusive = false)` already
8976            // advances strictly past `cursor`, so handing it `next`
8977            // verbatim gets the following occurrence — no manual +1s
8978            // nudge (and `DateTime<Tz>` is `Copy`, so no clone).
8979            cursor = next;
8980        }
8981        out
8982    }
8983
8984    /// Lower the operator-facing `when` onto the engine vocabulary.
8985    /// Single seam shared by the backend scheduler and the agent's
8986    /// local scheduler so the two can never drift.
8987    pub fn lowered(&self) -> Lowered {
8988        let tz = self.tz;
8989        match &self.when {
8990            When::PerPc(p) => Lowered {
8991                cron: POLL_CRON.into(),
8992                // `once_per_version` re-arms each pc when the manifest
8993                // version changes; the scheduler keys that dedup on
8994                // `execution_results.version`. Plain `once` / `every`
8995                // stay version-blind.
8996                mode: match p {
8997                    PerPolicy::OncePerVersion(_) => ExecMode::OncePerPcVersion,
8998                    PerPolicy::Once(_) | PerPolicy::Every(_) => ExecMode::OncePerPc,
8999                },
9000                cooldown: p.cooldown(),
9001                tz,
9002            },
9003            When::PerTarget(p) => Lowered {
9004                cron: POLL_CRON.into(),
9005                mode: ExecMode::OncePerTarget,
9006                cooldown: p.cooldown(),
9007                tz,
9008            },
9009            // `to_cron` only fails on a malformed `at` (rejected by
9010            // validate() at create time). For a hand-edited KV blob
9011            // that slipped past, emit a deliberately-invalid cron so
9012            // register()'s Job::new_async_tz fails → warn+skip,
9013            // rather than firing at the wrong time.
9014            When::Calendar(c) => Lowered {
9015                cron: c
9016                    .to_cron()
9017                    .unwrap_or_else(|_| "# invalid calendar at".into()),
9018                mode: ExecMode::EveryTick,
9019                cooldown: None,
9020                tz,
9021            },
9022            // Event triggers have no cron — the agent fires them from an
9023            // OS event source. The `# event-trigger` cron is never
9024            // registered (the scheduler branches on `is_event()` first),
9025            // but keep it deliberately-invalid as a belt-and-suspenders
9026            // so a stray registration would fail rather than misfire.
9027            When::On(_) => Lowered {
9028                cron: "# event-trigger (no cron)".into(),
9029                mode: ExecMode::Event,
9030                cooldown: None,
9031                tz,
9032            },
9033        }
9034    }
9035
9036    /// True when this schedule fires from an OS event (`when: { on }`)
9037    /// rather than a clock — the agent skips `tokio-cron` registration
9038    /// for these and drives them from boot / session-change instead.
9039    pub fn is_event(&self) -> bool {
9040        matches!(self.when, When::On(_))
9041    }
9042
9043    /// The OS event triggers this schedule listens for, or `&[]` when it
9044    /// is not an event schedule.
9045    pub fn event_triggers(&self) -> &[OnTrigger] {
9046        match &self.when {
9047            When::On(t) => t,
9048            _ => &[],
9049        }
9050    }
9051
9052    /// The next absolute (UTC) time this schedule fires, or `None` when
9053    /// it has no discrete upcoming fire to preview.
9054    ///
9055    /// Used by the KLP `maintenance.list` preview ("what's about to
9056    /// happen on my PC", SPEC §2.1). Returns `None` for:
9057    ///
9058    /// - reconcile shapes (`per_pc` / `per_target`) — they lower to the
9059    ///   every-minute [`POLL_CRON`] and re-converge state continuously,
9060    ///   so "next fire" is always ~60s away and means nothing to a user
9061    ///   previewing upcoming maintenance;
9062    /// - a calendar schedule whose lowered cron won't parse (a
9063    ///   hand-edited KV blob that slipped past [`Schedule::validate`]);
9064    /// - a cron with no future occurrence.
9065    ///
9066    /// The wall-clock fire is evaluated in the schedule's own `tz`
9067    /// (matching the live tick's `Job::new_async_tz`) then normalised
9068    /// to UTC for the wire. `inclusive = false`: strictly the *next*
9069    /// fire after `now`, never one matching the current instant.
9070    pub fn next_calendar_fire(
9071        &self,
9072        now: chrono::DateTime<chrono::Utc>,
9073    ) -> Option<chrono::DateTime<chrono::Utc>> {
9074        if !matches!(self.when, When::Calendar(_)) {
9075            return None;
9076        }
9077        let lowered = self.lowered();
9078        // Same parser configuration tokio-cron-scheduler 0.15 uses
9079        // internally, so this can never compute a fire the live
9080        // scheduler wouldn't (seconds required, DOM-and-DOW honored).
9081        let cron = croner::parser::CronParser::builder()
9082            .seconds(croner::parser::Seconds::Required)
9083            .dom_and_dow(true)
9084            .build()
9085            .parse(&lowered.cron)
9086            .ok()?;
9087        match lowered.tz {
9088            ScheduleTz::Utc => cron.find_next_occurrence(&now, false).ok(),
9089            ScheduleTz::Local => {
9090                let now_local = now.with_timezone(&chrono::Local);
9091                cron.find_next_occurrence(&now_local, false)
9092                    .ok()
9093                    .map(|t| t.with_timezone(&chrono::Utc))
9094            }
9095        }
9096    }
9097
9098    /// Cross-field semantic checks that don't fit pure serde derive
9099    /// — the [`Manifest::validate`] counterpart (#418 decision F;
9100    /// pre-Phase-1 a broken schedule was accepted at create time
9101    /// and silently warn-skipped at tick time). Run at every create
9102    /// site: `kanade schedule create` (client-side) and
9103    /// `POST /api/schedules`. The job_id-exists check lives in the
9104    /// API handler instead — it needs the JOBS KV.
9105    pub fn validate(&self) -> Result<(), String> {
9106        if matches!(self.runs_on, RunsOn::Agent) && matches!(self.when, When::PerTarget(_)) {
9107            return Err(
9108                "when.per_target needs fleet-wide completion data and is backend-only; \
9109                 it cannot be combined with runs_on: agent (each agent self-schedules, \
9110                 so per-target dedup would be deduping across a target of 1)"
9111                    .into(),
9112            );
9113        }
9114        // `once_per_version` is a per_pc-only shape: it re-arms an
9115        // individual pc when the manifest version it succeeded at is no
9116        // longer current. "One delegate per version" for a whole target
9117        // has no clear meaning, so reject it rather than silently
9118        // lowering to plain per_target (version-blind).
9119        if matches!(self.when, When::PerTarget(PerPolicy::OncePerVersion(_))) {
9120            return Err(
9121                "when.per_target: once_per_version is not supported — once_per_version \
9122                 re-arms per pc per manifest version, which only makes sense for per_pc. \
9123                 Use `per_pc: once_per_version`."
9124                    .into(),
9125            );
9126        }
9127        // `once_per_version` keys its dedup on the backend's
9128        // `execution_results.version` history. A runs_on: agent schedule
9129        // self-schedules from the agent's local completion map, which has
9130        // no per-version record, so it is backend-only (symmetric with
9131        // per_target). Reject it rather than silently degrade to
9132        // version-blind kitting-once on the agent.
9133        if matches!(self.runs_on, RunsOn::Agent)
9134            && matches!(self.when, When::PerPc(PerPolicy::OncePerVersion(_)))
9135        {
9136            return Err(
9137                "when.per_pc: once_per_version keys its dedup on the backend's per-version \
9138                 completion history and is backend-only; it cannot be combined with \
9139                 runs_on: agent (the agent self-schedules with no per-version record). \
9140                 Use runs_on: backend."
9141                    .into(),
9142            );
9143        }
9144        // #418 event triggers: the agent owns the OS event source
9145        // (boot / session-change), so `when: { on }` is agent-only and
9146        // needs at least one trigger.
9147        if let When::On(triggers) = &self.when {
9148            if !matches!(self.runs_on, RunsOn::Agent) {
9149                return Err(
9150                    "when.on (OS event trigger) is fired by the agent's own event \
9151                     source, so it requires runs_on: agent"
9152                        .into(),
9153                );
9154            }
9155            if triggers.is_empty() {
9156                return Err(
9157                    "when.on must list at least one trigger (e.g. [startup, logon])".into(),
9158                );
9159            }
9160        }
9161        if let Some(cd) = self.lowered().cooldown.as_deref() {
9162            humantime::parse_duration(cd)
9163                .map_err(|e| format!("when.every: invalid duration '{cd}': {e}"))?;
9164        }
9165        if let When::Calendar(c) = &self.when {
9166            // Lower the calendar form to its cron (catches a bad `at`
9167            // and the date+days conflict), then validate that cron
9168            // with the same parser configuration tokio-cron-scheduler
9169            // 0.15 uses internally (croner, seconds required,
9170            // DOM-and-DOW both honored, year optional) — create-time
9171            // validation can never accept what register() rejects.
9172            let cron = c.to_cron()?;
9173            croner::parser::CronParser::builder()
9174                .seconds(croner::parser::Seconds::Required)
9175                .dom_and_dow(true)
9176                .build()
9177                .parse(&cron)
9178                .map_err(|e| format!("when.at lowered to invalid cron '{cron}': {e}"))?;
9179        }
9180        // The other humantime strings on the schedule (claude #419
9181        // review): runtime degrades gracefully on both (bad jitter →
9182        // silent no-op, bad starting_deadline → warn + skipped tick),
9183        // but "rejected at create time" should cover every field the
9184        // operator can typo, not just `when`.
9185        if let Some(j) = &self.plan.jitter {
9186            humantime::parse_duration(j)
9187                .map_err(|e| format!("jitter: invalid duration '{j}': {e}"))?;
9188        }
9189        if let Some(sd) = &self.starting_deadline {
9190            humantime::parse_duration(sd)
9191                .map_err(|e| format!("starting_deadline: invalid duration '{sd}': {e}"))?;
9192        }
9193        // #917: the plan side got almost no create-time checks, so
9194        // several never-fires / fails-every-tick shapes were accepted
9195        // and only surfaced at dispatch time — or never:
9196        //
9197        // (1) a target that dispatches nothing. A runs_on: agent
9198        // schedule matches each agent against `target` (rollout waves
9199        // are backend-published and never reach that path), so an
9200        // unspecified target silently never fires; a runs_on: backend
9201        // one warn-fails every tick at the exec boundary, which
9202        // rejects the same shape with the same message.
9203        let has_waves = self
9204            .plan
9205            .rollout
9206            .as_ref()
9207            .is_some_and(|r| !r.waves.is_empty());
9208        if matches!(self.runs_on, RunsOn::Agent) {
9209            if !self.plan.target.is_specified() {
9210                return Err(
9211                    "target must specify at least one of `all` / `groups` / `pcs` — a \
9212                     runs_on: agent schedule matches each agent against `target`, so an \
9213                     unspecified target never fires anywhere"
9214                        .into(),
9215                );
9216            }
9217            if self.plan.rollout.is_some() {
9218                return Err(
9219                    "rollout waves are published by the backend and are ignored by \
9220                     runs_on: agent schedules (each agent self-schedules from `target`); \
9221                     drop `rollout:` or use runs_on: backend"
9222                        .into(),
9223                );
9224            }
9225        } else if !has_waves && !self.plan.target.is_specified() {
9226            return Err(
9227                "target must specify at least one of `all` / `groups` / `pcs` \
9228                 (or set `rollout.waves`) — the exec boundary rejects an \
9229                 unspecified target, so the schedule would fail every tick"
9230                    .into(),
9231            );
9232        }
9233        // (2) rollout waves were never validated: a blank group or an
9234        // unparseable delay failed at EVERY fire (the CLI doesn't even
9235        // expose waves, so the failure was always deferred to dispatch)
9236        // and an empty list dispatched nothing. (3) A wave delayed to
9237        // or past starting_deadline is dead on arrival: the deadline is
9238        // stamped once at tick time and the Command is serialised
9239        // before the wave sleep, so agents receive it already expired
9240        // (a synthetic exit-125 skip on every fire).
9241        if let Some(rollout) = &self.plan.rollout {
9242            if rollout.waves.is_empty() {
9243                return Err(
9244                    "rollout.waves must list at least one wave; omit `rollout:` for a \
9245                     one-shot fan-out of `target`"
9246                        .into(),
9247                );
9248            }
9249            let deadline = self
9250                .starting_deadline
9251                .as_deref()
9252                .and_then(|sd| humantime::parse_duration(sd).ok());
9253            for (i, wave) in rollout.waves.iter().enumerate() {
9254                if wave.group.trim().is_empty() {
9255                    return Err(format!("rollout.waves[{i}].group must not be blank"));
9256                }
9257                let delay = humantime::parse_duration(&wave.delay).map_err(|e| {
9258                    format!(
9259                        "rollout.waves[{i}].delay: invalid duration '{}': {e}",
9260                        wave.delay
9261                    )
9262                })?;
9263                if let Some(deadline) = deadline
9264                    && delay >= deadline
9265                {
9266                    return Err(format!(
9267                        "rollout.waves[{i}].delay ('{}') must be shorter than \
9268                         starting_deadline ('{}'): the deadline is stamped at tick time, \
9269                         so this wave's Commands would already be expired when published \
9270                         (skipped by every agent, every fire)",
9271                        wave.delay,
9272                        self.starting_deadline.as_deref().unwrap_or_default(),
9273                    ));
9274                }
9275            }
9276        }
9277        // (4) deadline_at is machine-stamped: the scheduler overwrites
9278        // it from `tick + starting_deadline` on every fire, so an
9279        // operator-set value is silently discarded — reject it and
9280        // point at the knob that does what they meant. (Ad-hoc POST
9281        // /api/exec bodies are a different write path and may still
9282        // carry it.)
9283        if self.plan.deadline_at.is_some() {
9284            return Err(
9285                "deadline_at is computed by the scheduler (tick time + starting_deadline) \
9286                 and overwritten on every fire — set `starting_deadline` instead"
9287                    .into(),
9288            );
9289        }
9290        let from = self
9291            .active
9292            .from
9293            .as_deref()
9294            .map(|s| Active::parse_bound(s, self.tz))
9295            .transpose()?;
9296        let until = self
9297            .active
9298            .until
9299            .as_deref()
9300            .map(|s| Active::parse_bound(s, self.tz))
9301            .transpose()?;
9302        if let (Some(f), Some(u)) = (from, until) {
9303            if f >= u {
9304                return Err(format!(
9305                    "active.from ({}) must be strictly before active.until ({})",
9306                    self.active.from.as_deref().unwrap_or_default(),
9307                    self.active.until.as_deref().unwrap_or_default(),
9308                ));
9309            }
9310        }
9311        // #418 Phase 3: a bad maintenance window is rejected at create
9312        // time (parse_window also catches equal bounds).
9313        if let Some(w) = self.constraints.window.as_deref() {
9314            Constraints::parse_window(w)?;
9315        }
9316        // #418 holiday exclusion: reject a malformed skip date at create
9317        // time so the fail-closed `allows` path only ever bites a
9318        // hand-edited KV blob, not a fresh `kanade schedule create`.
9319        if let Some(err) = self.constraints.bad_skip_date() {
9320            return Err(err);
9321        }
9322        // #418: constraints.max_concurrent is a central running-instance
9323        // cap, so it needs the backend's counter — reject it on
9324        // runs_on: agent (decision E), and reject a meaningless 0.
9325        if let Some(mc) = self.constraints.max_concurrent {
9326            // Check the structural incompatibility (agent has no central
9327            // counter) before the value range, so a `max_concurrent: 0`
9328            // + `runs_on: agent` combo reports the more fundamental
9329            // problem first (claude #542).
9330            if matches!(self.runs_on, RunsOn::Agent) {
9331                return Err(
9332                    "constraints.max_concurrent needs a central counter and is backend-only; \
9333                     it cannot be combined with runs_on: agent (each agent self-schedules, \
9334                     so there is no fleet-wide count to cap against)"
9335                        .into(),
9336                );
9337            }
9338            if mc == 0 {
9339                return Err(
9340                    "constraints.max_concurrent must be >= 1 (0 would never fire; \
9341                     omit it for no cap)"
9342                        .into(),
9343                );
9344            }
9345        }
9346        // #418: constraints.require (host-state env gates: ac_power /
9347        // idle / cpu_below / network) is sensed in-process by the agent,
9348        // so it needs runs_on: agent — the backend can't read a target
9349        // host's power / idle / cpu / connectivity state. Symmetric with
9350        // `when: { on }` (also agent-only); inverse of max_concurrent
9351        // (backend-only).
9352        if let Some(req) = &self.constraints.require {
9353            if !req.is_empty() && matches!(self.runs_on, RunsOn::Backend) {
9354                return Err(
9355                    "constraints.require (host-state env gates: ac_power / idle / cpu_below / \
9356                     network) is sensed in-process by the agent and needs runs_on: agent; the \
9357                     backend cannot read a target host's power / idle / cpu / connectivity state"
9358                        .into(),
9359                );
9360            }
9361            // Reject a malformed idle duration at create time so the
9362            // fail-closed runtime path only ever bites a hand-edited
9363            // KV blob (mirror skip_dates / on_failure.retry).
9364            if let Some(err) = req.bad_idle() {
9365                return Err(err);
9366            }
9367            // cpu_below is a percent — reject out-of-range so a typo
9368            // can't make a schedule that never (>=100 is always-busy?
9369            // no — <0 never matches) or trivially fires.
9370            if let Some(c) = req.cpu_below
9371                && !(c > 0.0 && c <= 100.0)
9372            {
9373                return Err(format!(
9374                    "constraints.require.cpu_below must be in (0, 100] percent (got {c}); \
9375                     omit it for no CPU requirement"
9376                ));
9377            }
9378        }
9379        // #418 Phase 4: a bad on_failure.retry is rejected at create
9380        // time — backoff must be valid humantime, and max is bounded
9381        // so a typo can't pin a flapping script in a tight loop.
9382        if let Some(r) = &self.on_failure.retry {
9383            let backoff = humantime::parse_duration(&r.backoff).map_err(|e| {
9384                format!(
9385                    "on_failure.retry.backoff: invalid duration '{}': {e}",
9386                    r.backoff
9387                )
9388            })?;
9389            // The wire form lowers backoff to whole seconds, so a
9390            // sub-second value would silently become a 0s no-wait
9391            // (coderabbit #466). Reject it rather than honour a backoff
9392            // the operator can't actually get.
9393            if backoff.as_secs() < 1 {
9394                return Err(format!(
9395                    "on_failure.retry.backoff must be >= 1s (got '{}'); sub-second backoffs \
9396                     round to 0 on the wire",
9397                    r.backoff
9398                ));
9399            }
9400            if !(1..=10).contains(&r.max) {
9401                return Err(format!(
9402                    "on_failure.retry.max must be 1..=10 (got {}); it counts additional \
9403                     attempts after the first run",
9404                    r.max
9405                ));
9406            }
9407        }
9408        // A blank / whitespace-only tag renders an empty filter chip on
9409        // the Schedules page — reject it at create time, mirroring the
9410        // Manifest::validate tag guard.
9411        for tag in &self.tags {
9412            if tag.trim().is_empty() {
9413                return Err("tags must not contain empty entries".to_string());
9414            }
9415        }
9416        Ok(())
9417    }
9418}
9419
9420/// Shared `serde(default)` for `bool` fields that default to `true`
9421/// (e.g. `CheckHint::fleet` / `CheckHint::health`). Generic name so it
9422/// doesn't read as "fleet" when reused for `health`.
9423fn default_true() -> bool {
9424    true
9425}