Skip to main content

kanade_shared/
manifest.rs

1use serde::{Deserialize, Serialize};
2
3use crate::wire::{FinalizeCommand, RunAs, Shell, Staleness};
4
5/// YAML job manifest (= registered "what to run", v0.18.0+).
6///
7/// Owns only script-intrinsic fields. **Who** (`target`), **how to
8/// phase fanout** (`rollout`), and **when to stagger start**
9/// (`jitter`) all moved to the Schedule / exec request side — same
10/// script can now be fired against different targets / rollouts
11/// without copying the script body.
12///
13/// #492: these types are READ fleet-wide (agents decode them from
14/// BUCKET_JOBS / BUCKET_SCHEDULES and inside live Commands), so they
15/// must tolerate unknown fields — `deny_unknown_fields` here made a
16/// gradually-upgrading fleet's OLD agents reject the whole object
17/// the moment a newer backend added any field. Operator typo
18/// protection (the old reason for the attribute) lives at the WRITE
19/// boundaries instead: `kanade job/schedule create` and the backend
20/// POST extractor parse via [`crate::strict`], which rejects unknown
21/// keys with their full paths. The wire rule: new fields always get
22/// `#[serde(default)]` (+ `skip_serializing_if` while old readers
23/// may still be strict).
24#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
25pub struct Manifest {
26    pub id: String,
27    pub version: String,
28    #[serde(default)]
29    pub description: Option<String>,
30    pub execute: Execute,
31    #[serde(default)]
32    pub require_approval: bool,
33    /// Opt-in marker that this job produces a JSON inventory fact
34    /// payload on stdout. When present, the backend's results
35    /// projector parses `ExecResult.stdout` as JSON and upserts an
36    /// `inventory_facts` row keyed by `(pc_id, manifest.id)`. The
37    /// `display` sub-config drives the SPA's Inventory page render.
38    #[serde(default)]
39    pub inventory: Option<InventoryHint>,
40    /// Issue #246: opt-in marker that this job emits per-line
41    /// observability events on stdout (one JSON `ObsEvent` per
42    /// newline). When present, the agent — after the script exits
43    /// successfully — parses each non-empty stdout line as an
44    /// `ObsEvent`, publishes it on `obs.<pc_id>` via the
45    /// `obs_outbox`, and (intentionally) **omits the stdout from
46    /// the `ExecResult`** so the timeline data doesn't double up
47    /// in `execution_results.stdout` (which would multiply rows
48    /// by ~50/day/PC of noise).
49    ///
50    /// Distinct from `inventory:` (single JSON object → projector
51    /// upsert) — events are append-only timeline points consumed
52    /// by the dedicated `obs_events` table.
53    #[serde(default)]
54    pub emit: Option<EmitConfig>,
55    /// #290: opt-in marker that this job is an operator-defined
56    /// **health check** whose result feeds the Client App's Health
57    /// tab over KLP (`StateSnapshot.checks`). The script prints a
58    /// free-form JSON object on stdout (like any inventory job); the
59    /// agent reads the [`CheckHint::status_field`] value dynamically
60    /// into a [`crate::ipc::state::Check`] named `check.name`.
61    /// Cadence / windows / conditions come from
62    /// the job's Schedule (exactly like inventory) — there is
63    /// deliberately no interval here. **Composes with `inventory:` and
64    /// `collect:`** (#821): each reads its own `#KANADE-<KIND>`-fenced
65    /// stdout block, so one job can drive a check, project inventory
66    /// facts, and collect files in a single run. Only `emit:` (NDJSON
67    /// stdout) is incompatible. A check-only job may skip the fence
68    /// (whole stdout is the JSON); a multi-hint job fences each block.
69    #[serde(default)]
70    pub check: Option<CheckHint>,
71    /// #219: opt-in marker that this job COLLECTS files into a bundle.
72    /// The script does the collection work and prints a single JSON
73    /// object on stdout carrying a `files` array of paths (the field
74    /// name is [`CollectHint::files_field`], default `"files"`); the
75    /// agent — after the script exits successfully — zips those files,
76    /// uploads the archive to the `OBJECT_COLLECTIONS` Object Store
77    /// bucket (key `<pc_id>/<job_id>/<timestamp>.zip`), and records the
78    /// key in [`crate::wire::ExecResult::collect_object`]. The operator
79    /// downloads bundles from the SPA Collect page.
80    ///
81    /// Like `inventory:` / `check:` this reads a JSON object from stdout.
82    /// #821: it reads its own `#KANADE-COLLECT-BEGIN/END`-fenced block,
83    /// so it **composes with `inventory:` / `check:`** (and a user
84    /// message) on one stdout — only `emit:` (NDJSON) is incompatible
85    /// (enforced in [`Manifest::validate`]). A collect-only job may skip
86    /// the fence. It also composes with `client:` — a `collect:` +
87    /// `client:` job lets an end user trigger a collection from the
88    /// Client App (the same-host agent runs it).
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub collect: Option<CollectHint>,
91    /// #720: opt-in declarative aggregation over `obs_events` that drives
92    /// the SPA **Analytics** page. Unlike the other hints this one never
93    /// touches stdout and is never delivered to the agent — it's a pure
94    /// *read spec* the backend reads from `BUCKET_JOBS` at query time and
95    /// turns into `json_extract` aggregation SQL. Each entry is one widget
96    /// (a `dashboard:` tab groups them); `scope:` selects per-PC vs
97    /// fleet-wide rollup. Because it consumes nothing at run time it
98    /// composes with every other hint (typically paired with `emit:`,
99    /// which produces the events it reads). See [`AggregateWidget`].
100    ///
101    /// New field ⇒ #492 wire rule (`default` + `skip_serializing_if`).
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub aggregate: Option<Vec<AggregateWidget>>,
104    /// v0.26: Layer 2 staleness policy (SPEC.md §2.6.2). Controls
105    /// what the agent does at fire time when it can't verify the
106    /// `script_current` / `script_status` KV values are fresh —
107    /// especially relevant for `runs_on: agent` schedules where
108    /// the agent may fire from cache while offline. Defaults to
109    /// `Staleness::Cached` (silently use cached values), which
110    /// matches every pre-v0.26 Manifest.
111    #[serde(default)]
112    pub staleness: Staleness,
113    /// #291: opt-in marker that this job is offered to **end users**
114    /// in the Client App's job tabs over KLP (`jobs.list` →
115    /// `jobs.execute`). Parallel to [`inventory`] / [`check`] /
116    /// [`emit`]: the block's mere presence is the opt-in, and it
117    /// groups the end-user presentation fields (name / category /
118    /// icon) that only make sense for a user-facing job. `None`
119    /// (the default) ⇒ an operator-only job — inventory, checks,
120    /// scheduled maintenance — that never surfaces in the catalog.
121    ///
122    /// The agent re-reads this at every `jobs.list` / `jobs.execute`
123    /// (SPEC §2.1), so removing the block takes a job out of a
124    /// running client on its next action.
125    ///
126    /// [`inventory`]: Manifest::inventory
127    /// [`check`]: Manifest::check
128    /// [`emit`]: Manifest::emit
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub client: Option<ClientHint>,
131    /// Free-form operator taxonomy for the Jobs catalog. Purely a
132    /// SPA-side organisational aid — agents / scheduler / projector
133    /// never read it — so it carries no runtime semantics and any
134    /// string is allowed (`security`, `weekly`, `windows`, …). Jobs
135    /// cross-cut (a `check-bitlocker` is at once a health-check, a
136    /// security control, and Windows-specific), which is why this is
137    /// a multi-valued list rather than the single closed-enum
138    /// [`ClientHint::category`] (whose values are the end-user Client
139    /// App's tabs, a different concern). The operator Jobs page groups
140    /// rows by id-prefix for free; tags add the orthogonal filter axis
141    /// prefixes can't express.
142    ///
143    /// Empty by default (the overwhelming majority of jobs), and a
144    /// new field, so it follows the #492 wire rule: `serde(default)`
145    /// plus `skip_serializing_if` keep gradually-upgrading old readers
146    /// from tripping over its absence / presence.
147    #[serde(default, skip_serializing_if = "Vec::is_empty")]
148    pub tags: Vec<String>,
149    /// GitOps provenance (#678) — see [`RepoOrigin`]. Stamped by
150    /// `kanade job create` when the source YAML lives inside a Git work
151    /// tree, so the SPA can render the job read-only and point edits
152    /// back at the repo instead of letting a ClickOps edit silently
153    /// diverge from Git (SPEC design principle #3: 設定駆動 YAML + Git).
154    /// `None` for SPA-born jobs and for manifests applied from outside
155    /// any Git repo. Purely informational: agents / scheduler /
156    /// projector never read it, and it survives `script_file:` inlining
157    /// (it's orthogonal to the exactly-one-of script-source rule). New
158    /// field ⇒ #492 wire rule (`default` + `skip_serializing_if`).
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub origin: Option<RepoOrigin>,
161    /// Job-generic post-step hook. When set, the agent runs this script
162    /// AFTER the main `execute:` script exits cleanly (and, for a
163    /// `collect:` job, after the bundle finishes uploading), so the
164    /// operator can delete / move / notify based on what the step
165    /// produced. Best-effort: a finalize failure is logged but never
166    /// fails the run — the upload (if any) already succeeded.
167    ///
168    /// For `collect:` jobs the agent injects the environment variable
169    /// `KANADE_COLLECT_RESULT` — a JSON object
170    /// `{ "ok": true, "bundles": [ { "key", "uploaded", "files": [...] } ] }`
171    /// — so the hook acts on exactly the files that were bundled and
172    /// uploaded (e.g. deletes only the `uploaded` ones). Composes with
173    /// every hint. New field ⇒ #492 wire rule (`default` +
174    /// `skip_serializing_if`).
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub finalize: Option<FinalizeSpec>,
177    /// #vuln-roadmap: declarative **external-data feeds**. Each entry fetches
178    /// global reference data (a vulnerability catalog, an EOL table, a license
179    /// roster) and projects it into the shared `feeds` table keyed
180    /// `(feed_id, item_id)` — fleet-wide, with no `pc_id`, unlike the per-PC
181    /// inventory [`ExplodeSpec`]. The job's script (run on the trusted
182    /// controller tier) fetches + shapes the data and prints the array under
183    /// each spec's [`field`](FeedSpec::field) inside a
184    /// `#KANADE-FEED-BEGIN/END` fence; the projector replaces that feed's rows
185    /// wholesale. A non-empty `feed:` **implies** `tier: controller` (the
186    /// dispatch guard treats it as such), so an external fetch never lands on
187    /// an employee endpoint. Composes with the other fenced hints. New field ⇒
188    /// #492 wire rule (`default` + `skip_serializing_if`). See [`FeedSpec`].
189    #[serde(default, skip_serializing_if = "Vec::is_empty")]
190    pub feed: Vec<FeedSpec>,
191    /// Execution tier (#vuln-roadmap). `None` / `endpoint` (default) ⇒ the
192    /// job dispatches to the targeted fleet agents like any job. `controller`
193    /// ⇒ it may run ONLY on trusted infra hosts — the backend constrains
194    /// dispatch to members of the operator-configured `controller_group`
195    /// (`server_settings` KV), and refuses to run anywhere if that group is
196    /// unset (fail-safe). This keeps `feed:` (external-fetch) and future
197    /// privileged hints off employee endpoints. The `feed:` hint implies
198    /// `controller`; it can also be set explicitly. New field ⇒ #492 wire
199    /// rule (`default` + `skip_serializing_if`).
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub tier: Option<Tier>,
202}
203
204/// Execution tier for a [`Manifest`] — see [`Manifest::tier`]. `endpoint`
205/// is the default (a normal fleet job); `controller` restricts dispatch to
206/// the trusted `controller_group`. `Unknown` is the #492 forward-compat
207/// catch-all: an older reader still *decodes* a job that names a future
208/// tier (so it doesn't fail the whole document), but `Manifest::validate()`
209/// **rejects** it — for a security field we fail closed rather than fall
210/// back to unrestricted `endpoint` dispatch (a future tier is presumably
211/// *more* restrictive, and a typo'd `controller` must not silently widen).
212#[derive(
213    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
214)]
215#[serde(rename_all = "snake_case")]
216#[non_exhaustive]
217pub enum Tier {
218    /// Dispatch to the targeted fleet agents (the default).
219    #[default]
220    Endpoint,
221    /// Dispatch only to members of the configured `controller_group`.
222    Controller,
223    /// #492 forward-compat catch-all (a future tier this build can't act on).
224    #[serde(other)]
225    Unknown,
226}
227
228/// GitOps provenance for a repo-managed YAML artifact — a [`Manifest`]
229/// (#678) or a [`Schedule`] (#695). Populated by `kanade job create` /
230/// `kanade schedule create` from the Git context of the source YAML;
231/// the SPA reads it to render Git-managed entries read-only and link
232/// the operator back at the repo. Never consulted by the runtime.
233#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
234pub struct RepoOrigin {
235    /// Repo-relative path of the source YAML — the primary edit target
236    /// the SPA surfaces (e.g. `configs/jobs/foo.yaml`). Forward slashes
237    /// regardless of the authoring OS.
238    pub path: String,
239    /// `origin` remote URL, when the repo has one. Lets the SPA turn
240    /// `path` into a clickable link; `None` for remote-less repos.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub repo: Option<String>,
243    /// Repo-relative path of the `script_file:` a job manifest inlined,
244    /// when it used one — a secondary pointer shown beneath `path`.
245    /// Always `None` for schedules (they carry no script).
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    pub script_file: Option<String>,
248}
249
250/// "Who + how + when-to-stagger" — the fanout-plan side of an exec.
251/// Used both as the POST `/api/exec/{job_id}` body and as the embedded
252/// `target` / `rollout` / `jitter` slot on [`Schedule`]. Centralising
253/// here keeps the validation + serialisation logic in one place.
254#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default)]
255pub struct FanoutPlan {
256    #[serde(default)]
257    pub target: Target,
258    /// Optional wave rollout — when present, the backend publishes
259    /// each wave's group subject on its own delay schedule instead
260    /// of fanning out the `target` block in one go. `target` then
261    /// only labels the deploy for the audit log.
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub rollout: Option<Rollout>,
264    /// Optional humantime jitter; agent uses it to randomise
265    /// execution start. Lives here (not on the script) so different
266    /// schedules / ad-hoc fires of the same job can pick different
267    /// stagger windows.
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub jitter: Option<String>,
270    /// Absolute time the scheduler stamps on each emitted Command
271    /// when this exec was driven by a [`Schedule`] with
272    /// `starting_deadline`. Agents receiving a Command after this
273    /// instant publish a synthetic skipped-result instead of
274    /// running the script. `None` (default) = no deadline / catch
275    /// up whenever delivered. Computed by the scheduler from
276    /// `tick_at + starting_deadline` and overwritten on every fire —
277    /// on a Schedule, setting it by hand is rejected at create time
278    /// (#917, use `starting_deadline`); it remains settable on an
279    /// ad-hoc POST /api/exec body.
280    #[serde(default, skip_serializing_if = "Option::is_none")]
281    pub deadline_at: Option<chrono::DateTime<chrono::Utc>>,
282}
283
284/// Sentinel lines that fence a hint's structured JSON payload inside an
285/// otherwise human-readable job stdout. Each stdout-reading hint
286/// (`inventory:` / `check:` / `collect:`) has its OWN `#KANADE-<KIND>-
287/// BEGIN`/`-END` pair, so one job can carry several of them at once
288/// (and/or a user-facing message) on its single stdout stream — every
289/// consumer extracts only its own block via [`fenced_payload`].
290///
291/// Originated for inventory (#793): a `client:` job couldn't put both a
292/// friendly message and a JSON object on one stdout (the Client App
293/// renders stdout verbatim, the projector needs JSON). #821 generalised
294/// it so inventory / check / collect can coexist. `emit:` is the
295/// exception — its stdout is line-delimited NDJSON consumed whole, so it
296/// never fences and never coexists with the others.
297///
298/// A job carrying a SINGLE hint may still skip the fence —
299/// [`fenced_payload`] falls back to the whole stdout — but a job
300/// COMBINING hints must fence each block (else every consumer would try
301/// to parse the same whole stdout).
302pub const INVENTORY_BLOCK_BEGIN: &str = "#KANADE-INVENTORY-BEGIN";
303/// Closing marker — see [`INVENTORY_BLOCK_BEGIN`].
304pub const INVENTORY_BLOCK_END: &str = "#KANADE-INVENTORY-END";
305/// Check-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
306pub const CHECK_BLOCK_BEGIN: &str = "#KANADE-CHECK-BEGIN";
307/// Check-payload closing marker.
308pub const CHECK_BLOCK_END: &str = "#KANADE-CHECK-END";
309/// Collect-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
310pub const COLLECT_BLOCK_BEGIN: &str = "#KANADE-COLLECT-BEGIN";
311/// Collect-payload closing marker.
312pub const COLLECT_BLOCK_END: &str = "#KANADE-COLLECT-END";
313/// Feed-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
314pub const FEED_BLOCK_BEGIN: &str = "#KANADE-FEED-BEGIN";
315/// Feed-payload closing marker.
316pub const FEED_BLOCK_END: &str = "#KANADE-FEED-END";
317
318/// Extract a hint's fenced block when the `begin` marker is present, else
319/// `None`. An unterminated fence (closing marker missing, e.g. truncated
320/// output) takes everything after the opener. Trimmed so surrounding
321/// message text / whitespace never reaches the JSON parser.
322pub fn fenced_payload_if_present<'a>(stdout: &'a str, begin: &str, end: &str) -> Option<&'a str> {
323    let b = find_line_marker(stdout, begin)?;
324    let after = &stdout[b + begin.len()..];
325    let inner = match find_line_marker(after, end) {
326        Some(e) => &after[..e],
327        None => after,
328    };
329    Some(inner.trim())
330}
331
332/// True if stdout carries ANY `#KANADE-<KIND>-BEGIN` fence at a line
333/// start — i.e. the script opted into fenced output. Used to decide
334/// whether a missing fence means "single-hint, use the whole stdout" or
335/// "multi-hint author error / truncation, this hint just has no block".
336pub fn has_any_hint_fence(stdout: &str) -> bool {
337    [
338        INVENTORY_BLOCK_BEGIN,
339        CHECK_BLOCK_BEGIN,
340        COLLECT_BLOCK_BEGIN,
341        FEED_BLOCK_BEGIN,
342    ]
343    .iter()
344    .any(|m| find_line_marker(stdout, m).is_some())
345}
346
347/// Extract one hint's JSON payload from a job's stdout. When the hint's
348/// own `#KANADE-<KIND>` fence is present, return that block. When it's
349/// absent, fall back to the WHOLE stdout only for an unfenced (single-
350/// hint) job; if any OTHER hint's fence is present (#821 multi-hint
351/// output) return `""` instead — the script opted into fences but this
352/// block is missing (author error or truncation), so this consumer must
353/// NOT grab a sibling hint's block. An empty payload fails the consumer's
354/// JSON parse and degrades to "no data for this hint", never cross-parse.
355pub fn fenced_payload<'a>(stdout: &'a str, begin: &str, end: &str) -> &'a str {
356    if let Some(p) = fenced_payload_if_present(stdout, begin, end) {
357        return p;
358    }
359    if has_any_hint_fence(stdout) {
360        ""
361    } else {
362        stdout.trim()
363    }
364}
365
366/// Inventory's fenced payload — [`fenced_payload`] with the inventory
367/// markers. Kept as a named helper for the projector call site.
368pub fn inventory_payload(stdout: &str) -> &str {
369    fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END)
370}
371
372/// Feed's fenced payload — [`fenced_payload`] with the feed markers. Kept as
373/// a named helper for the projector call site.
374pub fn feed_payload(stdout: &str) -> &str {
375    fenced_payload(stdout, FEED_BLOCK_BEGIN, FEED_BLOCK_END)
376}
377
378/// Find `needle` only where it begins a line (start of `hay` or right
379/// after a `\n`). Anchoring to line start means a script echoing the
380/// literal sentinel mid-message (e.g. printing a command name) can't
381/// false-trigger the fence (Claude #793).
382fn find_line_marker(hay: &str, needle: &str) -> Option<usize> {
383    if hay.starts_with(needle) {
384        return Some(0);
385    }
386    hay.find(&format!("\n{needle}")).map(|p| p + 1)
387}
388
389/// Manifest sub-section: how the SPA should render the inventory
390/// facts this job produces. Each field name (`field`) is a top-level
391/// key in the stdout JSON, e.g. `hostname`, `ram_gb`.
392///
393/// Two render modes:
394///   * `display` — vertical "field / value" per PC, used by the
395///     `/inventory?pc=<id>` detail view. ALL columns the operator
396///     wants visible on the detail page.
397///   * `summary` — horizontal table across the fleet (row = PC,
398///     column = field) on `/inventory`. Optional; when omitted the
399///     SPA falls back to `display`, but operators usually want a
400///     trimmer "hostname / OS / CPU / RAM" set for the fleet view.
401#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
402pub struct InventoryHint {
403    /// Detail-view columns, in order.
404    pub display: Vec<DisplayField>,
405    /// Optional fleet-list columns (row = PC). Defaults to `display`
406    /// when omitted, but operators usually pick a 3-5 column subset.
407    #[serde(default, skip_serializing_if = "Option::is_none")]
408    pub summary: Option<Vec<DisplayField>>,
409    /// v0.31 / #40: payload arrays that should be exploded into
410    /// per-element rows of a derived SQLite table. Lets operators
411    /// answer cross-PC questions ("which PCs still have Chrome <
412    /// 120?", "C: >90% full") with normal SQL filters + indexes
413    /// instead of grepping JSON. The projector creates the derived
414    /// table on register and replaces this PC's rows on each result
415    /// (DELETE WHERE pc_id=? AND job_id=? + bulk INSERT). See
416    /// [`ExplodeSpec`] for the per-spec schema.
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub explode: Option<Vec<ExplodeSpec>>,
419    /// v0.35 / #93: top-level scalar fields whose changes the
420    /// projector logs to `inventory_history` (one event per
421    /// changed field per scan). Pairs with `explode[].track_history`
422    /// — that covers array elements; this covers single-valued
423    /// fields like `ram_bytes` / `os_version` / `cpu_model` /
424    /// `os_build` that operators want to track for "did the RAM
425    /// get upgraded?" / "when did Win 11 land on this PC?" /
426    /// "BIOS / firmware bumped?" questions. Field name = `field_path`
427    /// in the history row, `identity_json` is NULL, `before_json`
428    /// / `after_json` each carry `{"value": <prior or new value>}`.
429    /// First-ever observation of a scalar (no prior facts row)
430    /// emits `added`; subsequent value changes emit `changed`. No
431    /// `removed` events — a scalar disappearing from the payload
432    /// is rare and the operator can still see the last value via
433    /// the `before_json` of the most recent change.
434    #[serde(default, skip_serializing_if = "Option::is_none")]
435    pub history_scalars: Option<Vec<String>>,
436}
437
438/// Manifest sub-section (#290): marks a job as an operator-defined
439/// **health check**. Parallel to [`InventoryHint`] / `EmitConfig`.
440/// The stdout contract is a free-form JSON object (same as any
441/// inventory job) from which the agent reads `status_field` /
442/// `detail_field` to build the KLP [`crate::ipc::state::Check`] shown
443/// on the Client App's Health tab.
444///
445/// There is deliberately **no timing field** — when / how often /
446/// in which window a check runs is driven by the job's Schedule,
447/// exactly like inventory jobs, so operators get the full `when:` /
448/// rollout / `runs_on` expressiveness for free.
449///
450/// A check's stdout is a **free-form inventory object** (arbitrary
451/// key/value pairs + arrays) — same as any inventory job — that also
452/// carries a status field. `check:` adds only the health semantics on
453/// top: which field is the ok/warn/fail/unknown status, an optional
454/// one-line summary field, and a remediation job. Everything else
455/// (rich per-PC detail, `explode` sub-tables like a software list) is
456/// driven by a co-present [`InventoryHint`] and rendered with the
457/// SAME display logic the SPA Inventory page uses — on the Client App
458/// too. This keeps checks maximally expressive without a bespoke
459/// payload type.
460#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
461pub struct CheckHint {
462    /// Stable check id → [`Check.name`](crate::ipc::state::Check),
463    /// the SPA/Client React key + analytics label. Unique within the
464    /// fleet's check set. Machine-friendly slug (`disk_space`,
465    /// `defender_rtp`); for the human-facing row title see [`label`].
466    ///
467    /// [`label`]: CheckHint::label
468    pub name: String,
469    /// Optional human-facing display title →
470    /// [`Check.label`](crate::ipc::state::Check). The Client App's
471    /// Health tab and the operator SPA's Compliance page render this
472    /// instead of the [`name`](CheckHint::name) slug when set
473    /// (`"ウイルス対策のリアルタイム保護"` reads better than
474    /// `defender_rtp`). Falls back to the slug when absent, so it's
475    /// purely additive. Author it in the check's language — there's no
476    /// per-locale variant; checks are operator-defined per fleet.
477    #[serde(default, skip_serializing_if = "Option::is_none")]
478    pub label: Option<String>,
479    /// Top-level stdout field whose string value
480    /// (`ok`/`warn`/`fail`/`unknown`) becomes the Health-tab light
481    /// ([`CheckStatus`](crate::ipc::state::CheckStatus)). Defaults to
482    /// `"status"`; a missing / unparseable value → `unknown`.
483    #[serde(default = "default_status_field")]
484    pub status_field: String,
485    /// Top-level stdout field used as the Health-tab row's one-line
486    /// summary. Defaults to `"detail"`; absent in the payload → no
487    /// detail line (the rich breakdown lives in the inventory view).
488    #[serde(default = "default_detail_field")]
489    pub detail_field: String,
490    /// Optional remediation job id →
491    /// [`Check.troubleshoot`](crate::ipc::state::Check). The Client
492    /// App shows a "修復する" button when present; that job must be
493    /// `user_invokable`.
494    #[serde(default, skip_serializing_if = "Option::is_none")]
495    pub troubleshoot: Option<String>,
496    /// #290 PR-E: when `true` (default), the backend also projects this
497    /// check's `status` / `detail` into the `check_status` table so the
498    /// operator SPA gets a fleet-wide compliance view for free — no
499    /// `inventory:` block needed. Set `fleet: false` for a client-only
500    /// check the operator doesn't want surfaced across the fleet.
501    #[serde(default = "default_true")]
502    pub fleet: bool,
503    /// When `true` (default), this check is shown on the Client App's
504    /// Health tab (the end user sees its ok/warn/fail row). Set
505    /// `health: false` for a **gate-only** check — one that exists purely
506    /// to drive a `client.show_when` display gate (e.g. `myapp-up-to-date`)
507    /// and would just be noise as a Health row. The agent still records it
508    /// into `StateSnapshot.checks` (so `show_when` can read it and the gate
509    /// keeps working); only the Client App's Health *rendering* skips it,
510    /// via the [`Check.health_hidden`](crate::ipc::state::Check::health_hidden)
511    /// wire flag. Orthogonal to [`fleet`](CheckHint::fleet): `fleet` gates
512    /// the operator SPA fleet view, `health` gates the end-user Health tab,
513    /// so a pure gate detector typically sets neither (`fleet: false` +
514    /// `health: false`) to stay invisible everywhere while still driving
515    /// the gate.
516    #[serde(default = "default_true")]
517    pub health: bool,
518    /// Optional auto-notification on a compliance transition. When set, the
519    /// backend publishes an end-user notification the moment this check
520    /// transitions *into* one of [`CheckAlert::on`] (e.g. ok → fail) — to
521    /// the failing PC's user and/or operator groups. Fired once per
522    /// transition (not on every poll). Requires `fleet: true` (the alert
523    /// rides the same projection that fills `check_status`).
524    #[serde(default, skip_serializing_if = "Option::is_none")]
525    pub alert: Option<CheckAlert>,
526}
527
528/// Auto-notification rule for a [`CheckHint`] (compliance alerting). When a
529/// check's status transitions into one of [`on`](Self::on), the backend
530/// publishes a notification to the failing PC's user
531/// ([`notify_user`](Self::notify_user)) and/or operator groups
532/// ([`notify_groups`](Self::notify_groups)). Deliberately config-driven:
533/// who gets told, how loud, and the wording all live in the manifest, not
534/// hardcoded in the backend.
535#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
536pub struct CheckAlert {
537    /// Statuses that fire the alert on *transition into* them (a check that
538    /// stays failing doesn't re-alert every poll). Defaults to `[fail]`.
539    /// `ok` is not representable — [`CheckAlertStatus`] has no `Ok` variant,
540    /// so a YAML `on: [ok]` fails to deserialize (before `validate()` is
541    /// even reached); "recovered" notifications are out of scope.
542    #[serde(default = "default_alert_on")]
543    pub on: Vec<CheckAlertStatus>,
544    /// Notify the user(s) on the failing PC (`notifications.pc.<pc_id>`).
545    #[serde(default)]
546    pub notify_user: bool,
547    /// Notify these operator groups (`notifications.group.<name>`).
548    #[serde(default, skip_serializing_if = "Vec::is_empty")]
549    pub notify_groups: Vec<String>,
550    /// Notification priority (colour/label only — toasting is the separate
551    /// `toast` flag). Defaults to `warn`.
552    #[serde(default = "default_alert_priority")]
553    pub priority: crate::ipc::notifications::NotificationPriority,
554    /// Require the recipient to click 確認 to dismiss.
555    #[serde(default)]
556    pub require_ack: bool,
557    /// Surface an OS toast (launches a closed Client App, Action Center
558    /// while locked). Recommended `true` for `notify_user` so a
559    /// non-emergency "your PC is non-compliant" nudge still reaches a user
560    /// whose app is closed.
561    #[serde(default)]
562    pub toast: bool,
563    /// Also send the alert by email, to every address mapped to the
564    /// `notify_groups` (via the `group_contacts` KV, edited on the SPA
565    /// Groups page). Opt-in: defaults to `false`, so an existing alert
566    /// never starts emailing on its own. Requires `notify_groups` to be
567    /// non-empty (there is no per-PC user email) and the backend's
568    /// `[mail]` config to be present; otherwise the email is a logged
569    /// no-op while the in-app/toast notification still fires.
570    #[serde(default)]
571    pub email: bool,
572    /// Notification title (required). May use the same `{…}` placeholders
573    /// as [`body`](Self::body).
574    pub title: String,
575    /// Notification body template. Placeholders: `{pc_id}`, `{name}` (check
576    /// slug), `{label}` (check label, falls back to slug), `{status}`,
577    /// `{detail}` (the check's one-line summary), `{last_logon}` (the PC's
578    /// last sign-in account). Absent → empty body.
579    #[serde(default, skip_serializing_if = "Option::is_none")]
580    pub body: Option<String>,
581}
582
583/// A check status that can trigger a [`CheckAlert`]. Mirrors the
584/// projected `check_status.status` values minus `ok` (alerting on `ok` is
585/// rejected at validation).
586#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash)]
587#[serde(rename_all = "snake_case")]
588pub enum CheckAlertStatus {
589    Warn,
590    Fail,
591    Unknown,
592}
593
594impl CheckAlertStatus {
595    /// The wire string, matching the projected `check_status.status`.
596    pub fn as_str(self) -> &'static str {
597        match self {
598            Self::Warn => "warn",
599            Self::Fail => "fail",
600            Self::Unknown => "unknown",
601        }
602    }
603}
604
605fn default_alert_on() -> Vec<CheckAlertStatus> {
606    vec![CheckAlertStatus::Fail]
607}
608
609fn default_alert_priority() -> crate::ipc::notifications::NotificationPriority {
610    crate::ipc::notifications::NotificationPriority::Warn
611}
612
613fn default_status_field() -> String {
614    "status".to_string()
615}
616
617fn default_detail_field() -> String {
618    "detail".to_string()
619}
620
621fn default_files_field() -> String {
622    "files".to_string()
623}
624
625/// Fallback cap on a collect bundle's total input size when the
626/// manifest's `collect.max_size` is unset. 50 MB (decimal).
627pub const DEFAULT_COLLECT_MAX_SIZE: u64 = 50 * 1_000_000;
628
629/// Manifest sub-section (#219): marks a job as a **file collector** and
630/// carries how the collected bundle presents in the SPA. Parallel to
631/// [`InventoryHint`] / [`CheckHint`] — the block's presence is the
632/// opt-in. The script prints a single JSON object on stdout whose
633/// [`files_field`](CollectHint::files_field) key holds an array of file
634/// paths to bundle (env vars are expanded); the agent zips them and
635/// uploads to `OBJECT_COLLECTIONS`. See [`Manifest::collect`].
636#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
637pub struct CollectHint {
638    /// Operator/end-user-facing title for the collection, shown as the
639    /// bundle's heading on the SPA Collect page (and the Client App row
640    /// when paired with `client:`). Required; validated non-empty.
641    pub name: String,
642    /// Optional one-line description of what the bundle contains.
643    #[serde(default, skip_serializing_if = "Option::is_none")]
644    pub description: Option<String>,
645    /// Human-readable cap on the bundle's total input size
646    /// (`"50MB"`, `"500KB"`, `"1GiB"`). The agent refuses to build a
647    /// bundle whose listed files exceed this. `None` ⇒
648    /// [`DEFAULT_COLLECT_MAX_SIZE`]. Parsed by [`parse_size_bytes`];
649    /// [`Manifest::validate`] rejects an unparseable value at create
650    /// time.
651    ///
652    /// Note: this bounds the **uncompressed** bytes the agent reads off
653    /// disk, not the resulting zip. Text logs compress well, so the
654    /// download is usually much smaller; many tiny files add a little
655    /// per-entry zip overhead. Read it as "how much the agent reads +
656    /// packs", not "the exact download size".
657    #[serde(default, skip_serializing_if = "Option::is_none")]
658    pub max_size: Option<String>,
659    /// Top-level stdout JSON key holding the array of file paths to
660    /// bundle. Defaults to `"files"`.
661    #[serde(default = "default_files_field")]
662    pub files_field: String,
663}
664
665impl CollectHint {
666    /// The effective size cap in bytes — the parsed `max_size` or
667    /// [`DEFAULT_COLLECT_MAX_SIZE`] when unset. Assumes `max_size` (if
668    /// present) already passed [`Manifest::validate`]; falls back to the
669    /// default on a parse error rather than panicking on the fire path.
670    pub fn max_size_bytes(&self) -> u64 {
671        match &self.max_size {
672            Some(s) => parse_size_bytes(s).unwrap_or(DEFAULT_COLLECT_MAX_SIZE),
673            None => DEFAULT_COLLECT_MAX_SIZE,
674        }
675    }
676}
677
678/// Parse a human-readable byte size (`"50MB"`, `"500 KB"`, `"1GiB"`,
679/// `"1024"`). Decimal units (KB/MB/GB) are 1000-based; binary units
680/// (KiB/MiB/GiB) are 1024-based; a bare number (or `B`) is bytes.
681/// Case-insensitive. Shared by `collect.max_size` validation and the
682/// agent's bundle-size enforcement.
683pub fn parse_size_bytes(s: &str) -> Result<u64, String> {
684    let t = s.trim();
685    if t.is_empty() {
686        return Err("size must not be empty".to_string());
687    }
688    let split = t.find(|c: char| !c.is_ascii_digit()).unwrap_or(t.len());
689    let (num_str, unit_raw) = t.split_at(split);
690    if num_str.is_empty() {
691        return Err(format!("size '{s}': missing leading number"));
692    }
693    let num: u64 = num_str
694        .parse()
695        .map_err(|_| format!("size '{s}': bad number '{num_str}'"))?;
696    let mult: u64 = match unit_raw.trim().to_ascii_lowercase().as_str() {
697        "" | "b" => 1,
698        "kb" => 1_000,
699        "mb" => 1_000_000,
700        "gb" => 1_000_000_000,
701        "kib" => 1024,
702        "mib" => 1024 * 1024,
703        "gib" => 1024 * 1024 * 1024,
704        other => {
705            return Err(format!(
706                "size '{s}': unknown unit '{other}' (use B/KB/MB/GB/KiB/MiB/GiB)"
707            ));
708        }
709    };
710    num.checked_mul(mult)
711        .ok_or_else(|| format!("size '{s}': overflow"))
712}
713
714/// Manifest sub-section (#291): marks a job as **user-invokable**
715/// from the Client App and carries how it presents to the end user.
716/// Parallel to [`InventoryHint`] / [`CheckHint`] / `EmitConfig` —
717/// the block's presence is the opt-in (no separate boolean), and its
718/// required fields (`name`, `category`) are enforced by serde at
719/// parse time, so a half-filled catalog entry fails
720/// `kanade job create` instead of rendering a nameless / tab-less row.
721///
722/// The agent maps this 1:1 into the KLP
723/// [`UserInvokableJob`](crate::ipc::jobs::UserInvokableJob) wire shape
724/// that `jobs.list` returns; the Client App renders one row per job in
725/// the tab named by `category`.
726#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
727pub struct ClientHint {
728    /// End-user-facing title for the job row. The operator-internal
729    /// `Manifest::id` slug is rarely what an end user should read, so
730    /// this is required (and validated non-empty by
731    /// [`Manifest::validate`]). Maps to `UserInvokableJob::display_name`.
732    pub name: String,
733    /// Optional one-line subtitle under `name` in the Client App.
734    /// Distinct from the operator-facing top-level
735    /// [`Manifest::description`] — this one is written for the end
736    /// user. Maps to `UserInvokableJob::display_description`.
737    #[serde(default, skip_serializing_if = "Option::is_none")]
738    pub description: Option<String>,
739    /// Which Client App tab the job lives in — a **free-form category
740    /// key** (#792). The Client App renders one tab per distinct key.
741    /// Well-known keys (`software_update`, `troubleshoot`, `catalog`)
742    /// carry built-in tab labels/icons; any other key defines a new tab
743    /// (style it with `category_label` / `category_icon`). Required and
744    /// validated non-empty — without it the agent can't place the job.
745    /// Note: the `software_update` key also drives the agent's
746    /// maintenance / auto-reboot grouping.
747    pub category: String,
748    /// Optional display name for the category's TAB. Set it on (at least
749    /// one of) a custom category's jobs to name the tab; `None` ⇒ a
750    /// built-in default for a well-known key, else the key itself.
751    #[serde(default, skip_serializing_if = "Option::is_none")]
752    pub category_label: Option<String>,
753    /// Optional icon for the category's TAB (lucide name or `data:` URL).
754    /// `None` ⇒ Client App default for the key.
755    #[serde(default, skip_serializing_if = "Option::is_none")]
756    pub category_icon: Option<String>,
757    /// Optional sort order for the TAB; lower sorts first. `None` ⇒
758    /// default (well-known keys keep their familiar order; custom keys
759    /// sort after, then by label).
760    #[serde(default, skip_serializing_if = "Option::is_none")]
761    pub category_order: Option<i64>,
762    /// Optional icon hint for the job ROW — a lucide-react icon name
763    /// or a `data:` URL. `None` ⇒ the Client App falls back to the
764    /// category's icon. Surfaced verbatim in `jobs.list[].icon`.
765    #[serde(default, skip_serializing_if = "Option::is_none")]
766    pub icon: Option<String>,
767    /// Optional visibility scope for the end-user Client App (#816).
768    ///
769    /// `None` ⇒ visible to every PC (current behavior). When set, only
770    /// agents whose `pc_id` / group membership match the [`Target`] list
771    /// the job in `jobs.list` and may run it via KLP `jobs.execute`.
772    ///
773    /// This gates the END-USER surface ONLY. Operators are unaffected:
774    /// `POST /api/exec/{job_id}` (SPA / `kanade exec`) is a separate path
775    /// that never consults `client:`, so an operator can still run the
776    /// job on any PC regardless of `visible_to`. Reuses the schedule
777    /// `Target` shape (`all` / `groups` / `pcs`); a present-but-empty
778    /// target is rejected by [`Manifest::validate`].
779    #[serde(default, skip_serializing_if = "Option::is_none")]
780    pub visible_to: Option<Target>,
781    /// Optional **dynamic display gate** keyed on a health check's result.
782    ///
783    /// `None` ⇒ always listed (current behavior). When set, the agent
784    /// lists the job in `jobs.list` ONLY while the named [`check:`] slug's
785    /// latest result is one of [`ShowWhen::is`]. The canonical use is an
786    /// update action that hides itself once the machine is already current:
787    /// pair the update job with a `check:` that reports `ok` when up to
788    /// date and gate on `is: [fail]`.
789    ///
790    /// Evaluated agent-side at `jobs.list` time against the live
791    /// `StateSnapshot.checks`, which is **keyed by check name** — so the
792    /// detector `check:` and this job may live in *different* manifests and
793    /// still share one slug. Distinct from [`visible_to`](ClientHint::visible_to):
794    /// that gates BOTH listing and `jobs.execute` (an authorization
795    /// boundary); `show_when` gates listing ONLY (a UX hint), so it can't
796    /// cause a list/execute race. New field ⇒ #492 wire rule.
797    ///
798    /// [`check:`]: crate::manifest::CheckHint
799    #[serde(default, skip_serializing_if = "Option::is_none")]
800    pub show_when: Option<ShowWhen>,
801    /// Optional **confirmation-dialog** config for the Client App's 実行
802    /// button.
803    ///
804    /// `None` ⇒ the historical default: the client shows a modal
805    /// confirmation with a built-in 「「{name}」を実行しますか?」 message
806    /// before firing the job (a mis-click guard for a possibly heavy /
807    /// destructive action). When set, the operator controls it:
808    /// - a bare bool — `confirm: false` runs immediately with **no** prompt;
809    ///   `confirm: true` is the same as omitting the block (default message);
810    /// - a struct — `confirm: { message: "…" }` shows the dialog with a
811    ///   custom message (and, redundantly with the scalar, `enabled: false`
812    ///   to suppress it).
813    ///
814    /// Gates the END-USER Client App surface only — the operator `POST
815    /// /api/exec` path never consults `client:`, so an operator-driven run
816    /// is unaffected. New field ⇒ #492 wire rule (`serde(default)` +
817    /// `skip_serializing_if`). Deserializes from bool-or-struct via
818    /// [`de_confirm`]; the JSON schema advertises the struct form (the
819    /// scalar is author ergonomics, like [`ShowWhen::is`]).
820    #[serde(
821        default,
822        deserialize_with = "de_confirm",
823        skip_serializing_if = "Option::is_none"
824    )]
825    pub confirm: Option<ConfirmHint>,
826}
827
828/// Confirmation-dialog config for a [`ClientHint`] — see
829/// [`ClientHint::confirm`]. Controls the Client App's pre-run modal:
830/// whether it appears at all (`enabled`) and what it says (`message`).
831///
832/// Authored as either a bare bool (`confirm: false` / `true`) or a struct
833/// (`confirm: { message: "…" }`); both normalise here via [`de_confirm`].
834#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
835pub struct ConfirmHint {
836    /// Whether the Client App shows the confirmation dialog before running.
837    /// `false` fires the job immediately with no prompt. Defaults to `true`
838    /// (so an author who only sets `message` still gets the dialog, and the
839    /// struct form never accidentally suppresses it).
840    #[serde(default = "default_confirm_enabled")]
841    pub enabled: bool,
842    /// Custom dialog message. `None` ⇒ the client's built-in
843    /// 「「{name}」を実行しますか?」. Only meaningful while `enabled`;
844    /// rejected if present-but-blank by [`Manifest::validate`].
845    #[serde(default, skip_serializing_if = "Option::is_none")]
846    pub message: Option<String>,
847}
848
849/// `enabled` defaults to `true`: the historical behaviour is "always
850/// confirm", so a struct form that omits `enabled` (e.g. sets only
851/// `message`) still shows the dialog.
852fn default_confirm_enabled() -> bool {
853    true
854}
855
856/// Accept either a bare bool (`confirm: false` / `confirm: true`) or a
857/// struct (`confirm: { message: "…" }`) for [`ClientHint::confirm`],
858/// normalising to a [`ConfirmHint`]. The bool is pure author ergonomics —
859/// `false` ⇒ suppress the dialog, `true` ⇒ default message — while the
860/// struct carries a custom message. Called only when the key is present
861/// (absence is handled by `serde(default)` ⇒ `None`). An explicit
862/// `confirm: null` — which the generated schema permits (the field is
863/// `Option`) — maps to `None` too, so it can't produce a parse error;
864/// deserializing through `Option<BoolOrHint>` handles that cleanly (Gemini
865/// #960).
866fn de_confirm<'de, D>(d: D) -> Result<Option<ConfirmHint>, D::Error>
867where
868    D: serde::Deserializer<'de>,
869{
870    #[derive(Deserialize)]
871    #[serde(untagged)]
872    enum BoolOrHint {
873        Bool(bool),
874        Hint(ConfirmHint),
875    }
876    Ok(Option::<BoolOrHint>::deserialize(d)?.map(|b| match b {
877        BoolOrHint::Bool(enabled) => ConfirmHint {
878            enabled,
879            message: None,
880        },
881        BoolOrHint::Hint(h) => h,
882    }))
883}
884
885/// Dynamic display gate for a [`ClientHint`] — see
886/// [`ClientHint::show_when`]. Shows the job only while the named check's
887/// latest status is one of [`is`](ShowWhen::is).
888#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
889pub struct ShowWhen {
890    /// The `check:` slug (a [`CheckHint::name`](crate::manifest::CheckHint::name))
891    /// whose latest status gates this job. May be defined by a *different*
892    /// manifest: checks are keyed by name in the agent's snapshot, so a
893    /// standalone detector job and this one can share a slug. A check that
894    /// has never run (absent from the snapshot) does NOT match — the job
895    /// stays hidden until the detector first reports (fails closed, like
896    /// `visible_to`).
897    pub check: String,
898    /// The check status(es) in which the job is SHOWN. Accepts a single
899    /// status (`is: fail`) or a list (`is: [fail, unknown]`); both
900    /// deserialize to a `Vec`. The `length(min = 1)` schema constraint +
901    /// [`Manifest::validate`] both reject an empty set (it would match
902    /// nothing and silently hide the job) so schema-driven tooling and the
903    /// write path agree.
904    #[serde(deserialize_with = "de_one_or_many_check_status")]
905    #[schemars(length(min = 1))]
906    pub is: Vec<crate::ipc::state::CheckStatus>,
907}
908
909/// Accept either a single `CheckStatus` (`is: fail`) or a sequence
910/// (`is: [fail, unknown]`) for [`ShowWhen::is`], normalising to a `Vec`.
911/// The scalar form is purely author ergonomics; the JSON schema advertises
912/// the canonical array form (`#[schemars(with = ...)]`).
913fn de_one_or_many_check_status<'de, D>(
914    d: D,
915) -> Result<Vec<crate::ipc::state::CheckStatus>, D::Error>
916where
917    D: serde::Deserializer<'de>,
918{
919    use crate::ipc::state::CheckStatus;
920    #[derive(Deserialize)]
921    #[serde(untagged)]
922    enum OneOrMany {
923        One(CheckStatus),
924        Many(Vec<CheckStatus>),
925    }
926    Ok(match OneOrMany::deserialize(d)? {
927        OneOrMany::One(c) => vec![c],
928        OneOrMany::Many(v) => v,
929    })
930}
931
932/// #720 — one widget on the SPA **Analytics** page: a declarative
933/// aggregation over the `obs_events` table. The backend reads these off
934/// `Manifest::aggregate` (from `BUCKET_JOBS`) at query time and builds
935/// the `json_extract` GROUP BY / time-bucket SQL from these generic
936/// primitives, so an operator can chart any emitted event without a Rust
937/// change. The reference shapes are the attendance dashboards
938/// (presence / app_sample / web_visit), but the same DSL covers logon /
939/// reboot / agent-health trends, etc.
940#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
941pub struct AggregateWidget {
942    /// Tab this widget lives under on the Analytics page. Widgets from
943    /// every job are collected and grouped by this label, so the same
944    /// string across jobs builds one multi-source dashboard. Required.
945    pub dashboard: String,
946    /// Widget heading. Required, validated non-empty.
947    pub title: String,
948    /// Optional one-line subtitle shown muted under the `title` on the
949    /// Analytics page — room for a unit, a caveat, or what the number
950    /// means ("samples × 2 min", "Security 4624 only"). Rejected if
951    /// present-but-blank.
952    #[serde(default, skip_serializing_if = "Option::is_none")]
953    pub description: Option<String>,
954    /// Optional sort weight (#743). Once the order-aware sort lands (PR2)
955    /// widgets render in `(order, dashboard, title)` order, so a lower
956    /// `order` pulls a widget — and its tab — earlier; equal/absent `order`
957    /// falls back to the alphabetical `(dashboard, title)` ordering. Treated
958    /// as `0` when unset, so a fleet with no `order` anywhere stays purely
959    /// alphabetical (today's behaviour); negatives are allowed to pin
960    /// something first. (This field only carries the value; the backend
961    /// applies it.)
962    #[serde(default, skip_serializing_if = "Option::is_none")]
963    pub order: Option<i32>,
964    /// Promote this widget to the main Dashboard, not just the Analytics
965    /// page (#vuln-roadmap PR3). The Dashboard fetches the pinned subset
966    /// (`/api/analytics?pinned=true`, fleet scope) and renders it with the
967    /// same widget components. Operator-controlled, so any config-driven
968    /// view (e.g. a future vulnerability rollup) can surface up front
969    /// without a bespoke card. Defaults to `false`. Pin a `scope: fleet`
970    /// widget — a `pc`-scoped one needs a selected PC and won't render on
971    /// the fleet Dashboard.
972    // `Not::not` is `!self`, so this skips serializing the field when it's
973    // `false` — keeps `pin_dashboard: false` out of the stored job/view JSON,
974    // matching how the optional fields above omit their defaults.
975    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
976    pub pin_dashboard: bool,
977    /// `pc` rolls up a single selected PC; `fleet` rolls up all PCs
978    /// (and unlocks `group_by: pc_id` to rank PCs against each other).
979    /// Defaults to `pc`.
980    #[serde(default)]
981    pub scope: AggregateScope,
982    /// `obs_events.kind` this widget reads (e.g. `app_sample`,
983    /// `presence`, `unexpected_shutdown`). Required for every aggregation
984    /// render (`bar`/`gauge`/`timeline`/`stat`); rejected for
985    /// `op_timeline`, which reconstructs a fixed multi-kind operational
986    /// swimlane (power/session/sleep) baked into the SPA and so reads no
987    /// single `kind`.
988    #[serde(default, skip_serializing_if = "Option::is_none")]
989    pub kind: Option<String>,
990    /// Optional `obs_events.source` filter, when one `kind` is emitted by
991    /// more than one collector.
992    #[serde(default, skip_serializing_if = "Option::is_none")]
993    pub source: Option<String>,
994    /// How to roll the matching events up. See [`AggregateAgg`]. Required
995    /// for every aggregation render; rejected for `op_timeline` (which
996    /// performs no rollup — it returns the raw operational events and the
997    /// SPA folds them into lane spans).
998    #[serde(default, skip_serializing_if = "Option::is_none")]
999    pub agg: Option<AggregateAgg>,
1000    /// Dotted JSON path (no `$.` prefix) to group by for `agg: count` /
1001    /// `sum` — e.g. `foreground.app`. The literal `pc_id` is special:
1002    /// it groups by the `pc_id` column (fleet ranking), not a payload
1003    /// field. Omit for a single total. Required when `agg: sum` needs a
1004    /// breakdown; for `agg: count` omitting it yields the grand total.
1005    #[serde(default, skip_serializing_if = "Option::is_none")]
1006    pub group_by: Option<String>,
1007    /// Dotted JSON path to a boolean for `agg: ratio` (e.g. `active`):
1008    /// the widget reports `true_count / total`. Required when `agg: ratio`.
1009    #[serde(default, skip_serializing_if = "Option::is_none")]
1010    pub bool_path: Option<String>,
1011    /// Dotted JSON path to a number for `agg: sum`. Required when `agg: sum`.
1012    #[serde(default, skip_serializing_if = "Option::is_none")]
1013    pub value_path: Option<String>,
1014    /// Optional value transform applied before grouping. Currently only
1015    /// `host` (parse a URL down to its host) — used by the top-sites
1016    /// widget, where SQLite can't parse a URL so the backend does it in
1017    /// Rust. See [`AggregateTransform`].
1018    #[serde(default, skip_serializing_if = "Option::is_none")]
1019    pub transform: Option<AggregateTransform>,
1020    /// Optional sampling cadence in minutes. When set, a `count` is also
1021    /// reported as estimated time (`count × sample_minutes`) — e.g. a
1022    /// 2-minute app sampler turns 11 samples into ~22 minutes. Must be ≥ 1.
1023    #[serde(default, skip_serializing_if = "Option::is_none")]
1024    #[schemars(range(min = 1))]
1025    pub sample_minutes: Option<u32>,
1026    /// Grouped values to drop from the rollup (e.g. `["LockApp"]` so the
1027    /// lock screen doesn't top the app ranking). Empty by default.
1028    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1029    pub exclude: Vec<String>,
1030    /// Optional time bucketing — `hour` buckets events by local
1031    /// hour-of-day for a `timeline` render. See [`AggregateTimeBucket`].
1032    #[serde(default, skip_serializing_if = "Option::is_none")]
1033    pub time_bucket: Option<AggregateTimeBucket>,
1034    /// Top-N cap for grouped renders (`bar`). Defaults to 10 when unset.
1035    #[serde(default, skip_serializing_if = "Option::is_none")]
1036    #[schemars(range(min = 1))]
1037    pub limit: Option<u32>,
1038    /// Which widget the SPA draws. See [`AggregateRender`].
1039    pub render: AggregateRender,
1040}
1041
1042/// Per-PC vs fleet-wide rollup for an [`AggregateWidget`].
1043#[derive(
1044    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
1045)]
1046#[serde(rename_all = "lowercase")]
1047#[non_exhaustive]
1048pub enum AggregateScope {
1049    /// Roll up the single PC the operator selected. The default.
1050    #[default]
1051    Pc,
1052    /// Roll up across every PC. Unlocks `group_by: pc_id`.
1053    Fleet,
1054    /// #492 forward-compat catch-all — a Manifest is read fleet-wide, so
1055    /// an older reader must tolerate a future variant rather than failing
1056    /// to decode the whole job. The backend skips an `Unknown` widget.
1057    #[serde(other)]
1058    Unknown,
1059}
1060
1061/// The rollup function for an [`AggregateWidget`].
1062#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1063#[serde(rename_all = "lowercase")]
1064#[non_exhaustive]
1065pub enum AggregateAgg {
1066    /// Row count, optionally grouped (`group_by`) and time-estimated
1067    /// (`sample_minutes`).
1068    Count,
1069    /// `true_count / total` over `bool_path`.
1070    Ratio,
1071    /// Sum of `value_path`, optionally grouped.
1072    Sum,
1073    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1074    #[serde(other)]
1075    Unknown,
1076}
1077
1078/// Optional pre-grouping value transform for an [`AggregateWidget`].
1079#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1080#[serde(rename_all = "lowercase")]
1081#[non_exhaustive]
1082pub enum AggregateTransform {
1083    /// Parse the grouped value as a URL and keep only its host.
1084    Host,
1085    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1086    #[serde(other)]
1087    Unknown,
1088}
1089
1090/// Time bucketing for an [`AggregateWidget`] (drives a `timeline`).
1091#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1092#[serde(rename_all = "lowercase")]
1093#[non_exhaustive]
1094pub enum AggregateTimeBucket {
1095    /// Bucket by local hour-of-day (0–23), summed over the window.
1096    Hour,
1097    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1098    #[serde(other)]
1099    Unknown,
1100}
1101
1102/// Which visual the SPA renders an [`AggregateWidget`] as.
1103#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1104#[serde(rename_all = "lowercase")]
1105#[non_exhaustive]
1106pub enum AggregateRender {
1107    /// Ranked horizontal bars (a grouped `count` / `sum`).
1108    Bar,
1109    /// A single ratio dial (`agg: ratio`).
1110    Gauge,
1111    /// 24-hour activity strip (`time_bucket: hour`).
1112    Timeline,
1113    /// A single headline number (an ungrouped total).
1114    Stat,
1115    /// Per-PC operational swimlane (power / session / sleep) reconstructed
1116    /// from a fixed multi-kind event set. Unlike the aggregation renders it
1117    /// reads no single `kind`/`agg`: the backend returns the raw events in
1118    /// the window and the SPA folds them into lane spans (shared with the
1119    /// Events page strip). Per-PC only (`scope: pc`).
1120    #[serde(rename = "op_timeline")]
1121    OpTimeline,
1122    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1123    #[serde(other)]
1124    Unknown,
1125}
1126
1127/// True if `p` is a well-formed dotted JSON path of `[A-Za-z0-9_]`
1128/// segments joined by single dots — the shape safe to bind into
1129/// `json_extract(payload, '$.' || ?)`. The charset blocks injection; the
1130/// segment check additionally rejects `"."`, `".foo"`, `"foo."`,
1131/// `"foo..bar"`, which would pass the charset but produce a malformed
1132/// `$.` path that errors at query time. Accepts `pc_id`, `foreground.app`,
1133/// `active`, etc.
1134fn is_valid_json_path(p: &str) -> bool {
1135    !p.is_empty()
1136        && p.split('.').all(|seg| {
1137            !seg.is_empty() && seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
1138        })
1139}
1140
1141/// Per-widget validation for a list of [`AggregateWidget`]s — shared by
1142/// the `aggregate:` job hint ([`Manifest::validate`]) and the standalone
1143/// [`View`] resource (#743) so the two can't diverge. `field` names the
1144/// containing key for error messages (`"aggregate"` or `"widgets"`).
1145///
1146/// Enforces: non-empty list; non-empty dashboard/title (and `kind`/`agg`
1147/// for every aggregation render); a blank-when-set `source`; rejection of
1148/// any #492 `Unknown` enum (an operator typo at create time); safe dotted
1149/// JSON paths; the value path each `agg` needs (and rejection of mis-paired
1150/// ones); `pc_id` grouping only in `fleet` scope; `transform`/`limit`/
1151/// `exclude` only with a `group_by`; positive `limit`/`sample_minutes`;
1152/// `gauge`⇔`ratio`; and `timeline`⇔`time_bucket`. A `render: op_timeline`
1153/// widget is validated separately (per-PC, no aggregation knobs) — see
1154/// [`validate_op_timeline_widget`].
1155pub fn validate_aggregate_widgets(widgets: &[AggregateWidget], field: &str) -> Result<(), String> {
1156    if widgets.is_empty() {
1157        return Err(format!(
1158            "`{field}:` must list at least one widget when present"
1159        ));
1160    }
1161    for (i, w) in widgets.iter().enumerate() {
1162        let at = format!("{field}[{i}]");
1163        for (label, value) in [("dashboard", &w.dashboard), ("title", &w.title)] {
1164            if value.trim().is_empty() {
1165                return Err(format!("{at}.{label} must not be empty"));
1166            }
1167        }
1168        // A present-but-blank `description` renders an empty muted line —
1169        // reject it so the subtitle only shows when it says something.
1170        if let Some(description) = &w.description {
1171            if description.trim().is_empty() {
1172                return Err(format!("{at}.description must not be empty when set"));
1173            }
1174        }
1175        // Reject values that fell through to the #492 `Unknown` catch-all:
1176        // at create time on the current version that's an operator typo. (A
1177        // genuinely-future variant only reaches an older reader via a stored
1178        // resource, which is never re-validated, so forward-compat holds.)
1179        if w.scope == AggregateScope::Unknown {
1180            return Err(format!("{at}.scope is not a known value (pc | fleet)"));
1181        }
1182        if w.render == AggregateRender::Unknown {
1183            return Err(format!(
1184                "{at}.render is not a known value (bar | gauge | timeline | stat | op_timeline)"
1185            ));
1186        }
1187        // `op_timeline` reconstructs a fixed per-PC operational swimlane
1188        // (power/session/sleep) from a baked-in multi-kind set — it uses none
1189        // of the aggregation knobs, so validate it on its own terms (per-PC,
1190        // no `kind`/`agg`/grouping) and skip the rollup rules below.
1191        if w.render == AggregateRender::OpTimeline {
1192            validate_op_timeline_widget(w, &at)?;
1193            continue;
1194        }
1195        // Every other render is an aggregation over a single `kind`.
1196        if w.kind.as_deref().map(str::trim).unwrap_or("").is_empty() {
1197            return Err(format!("{at}.kind must not be empty"));
1198        }
1199        let agg = match w.agg {
1200            Some(AggregateAgg::Unknown) => {
1201                return Err(format!(
1202                    "{at}.agg is not a known value (count | ratio | sum)"
1203                ));
1204            }
1205            Some(agg) => agg,
1206            None => return Err(format!("{at}.agg is required")),
1207        };
1208        // A present-but-blank `source` is a no-op filter — reject like the
1209        // other blank-when-set guards.
1210        if let Some(source) = &w.source {
1211            if source.trim().is_empty() {
1212                return Err(format!("{at}.source must not be empty when set"));
1213            }
1214        }
1215        if w.transform == Some(AggregateTransform::Unknown) {
1216            return Err(format!("{at}.transform is not a known value (host)"));
1217        }
1218        if w.time_bucket == Some(AggregateTimeBucket::Unknown) {
1219            return Err(format!("{at}.time_bucket is not a known value (hour)"));
1220        }
1221        for (label, path) in [
1222            ("group_by", &w.group_by),
1223            ("bool_path", &w.bool_path),
1224            ("value_path", &w.value_path),
1225        ] {
1226            if let Some(p) = path {
1227                if !is_valid_json_path(p) {
1228                    return Err(format!(
1229                        "{at}.{label} '{p}' must be a dotted JSON path of [A-Za-z0-9_] segments"
1230                    ));
1231                }
1232            }
1233        }
1234        // Each agg uses exactly one value path; reject a mis-paired path so
1235        // a typo fails at create rather than being ignored.
1236        match agg {
1237            // count: grouped → ranking, ungrouped → grand total.
1238            AggregateAgg::Count => {
1239                for (label, path) in [("bool_path", &w.bool_path), ("value_path", &w.value_path)] {
1240                    if path.is_some() {
1241                        return Err(format!("{at}.agg=count does not use `{label}`"));
1242                    }
1243                }
1244            }
1245            AggregateAgg::Ratio => {
1246                if w.bool_path.is_none() {
1247                    return Err(format!("{at}.agg=ratio requires `bool_path`"));
1248                }
1249                if w.value_path.is_some() {
1250                    return Err(format!("{at}.agg=ratio does not use `value_path`"));
1251                }
1252            }
1253            AggregateAgg::Sum => {
1254                if w.value_path.is_none() {
1255                    return Err(format!("{at}.agg=sum requires `value_path`"));
1256                }
1257                if w.bool_path.is_some() {
1258                    return Err(format!("{at}.agg=sum does not use `bool_path`"));
1259                }
1260            }
1261            // Rejected above; arm exists only for exhaustiveness.
1262            AggregateAgg::Unknown => {}
1263        }
1264        // Ranking PCs against each other only means something across the
1265        // fleet — within one PC it's a single bar.
1266        if w.group_by.as_deref() == Some("pc_id") && w.scope != AggregateScope::Fleet {
1267            return Err(format!(
1268                "{at}.group_by: pc_id is only valid with scope: fleet"
1269            ));
1270        }
1271        // `transform` rewrites the grouped PAYLOAD value (URL→host); it's
1272        // meaningless on a `pc_id` grouping (the pc_id column, not a payload
1273        // field), so reject the combo at create time.
1274        if w.transform.is_some() && w.group_by.as_deref() == Some("pc_id") {
1275            return Err(format!("{at}.transform is not valid with group_by: pc_id"));
1276        }
1277        // limit / transform / exclude all operate on grouped values, so
1278        // without a `group_by` they're silent no-ops — reject.
1279        if w.group_by.is_none() {
1280            if w.limit.is_some() {
1281                return Err(format!("{at}.limit requires `group_by`"));
1282            }
1283            if w.transform.is_some() {
1284                return Err(format!("{at}.transform requires `group_by`"));
1285            }
1286            if !w.exclude.is_empty() {
1287                return Err(format!("{at}.exclude requires `group_by`"));
1288            }
1289        }
1290        if w.limit == Some(0) {
1291            return Err(format!("{at}.limit must be > 0"));
1292        }
1293        if w.sample_minutes == Some(0) {
1294            return Err(format!("{at}.sample_minutes must be > 0"));
1295        }
1296        for ex in &w.exclude {
1297            if ex.trim().is_empty() {
1298                return Err(format!("{at}.exclude must not contain empty entries"));
1299            }
1300        }
1301        // A gauge draws a single ratio dial — only meaningful for agg: ratio.
1302        if w.render == AggregateRender::Gauge && agg != AggregateAgg::Ratio {
1303            return Err(format!("{at}.render=gauge is only valid with agg: ratio"));
1304        }
1305        // A timeline needs a bucket; a bucket on any other render is a no-op
1306        // that signals operator confusion — reject both.
1307        match (w.render, &w.time_bucket) {
1308            (AggregateRender::Timeline, None) => {
1309                return Err(format!("{at}.render=timeline requires `time_bucket`"));
1310            }
1311            (r, Some(_)) if r != AggregateRender::Timeline => {
1312                return Err(format!(
1313                    "{at}.time_bucket is only valid with render: timeline"
1314                ));
1315            }
1316            _ => {}
1317        }
1318    }
1319    Ok(())
1320}
1321
1322/// Validate a `render: op_timeline` widget. It draws a fixed per-PC
1323/// operational swimlane (power / session / sleep) reconstructed by the SPA
1324/// from a baked-in multi-kind event set, so it uses none of the aggregation
1325/// knobs: require `scope: pc` and reject every field that only makes sense
1326/// for a rollup (`kind`/`source`/`agg`/`group_by`/`bool_path`/`value_path`/
1327/// `transform`/`sample_minutes`/`exclude`/`time_bucket`/`limit`). Rejecting
1328/// the unused fields (rather than ignoring them) keeps an operator typo from
1329/// silently doing nothing, matching the rest of this validator.
1330fn validate_op_timeline_widget(w: &AggregateWidget, at: &str) -> Result<(), String> {
1331    // Per-PC only: a fleet-wide swimlane of every PC's spans is unbounded
1332    // and unreadable, and the backend only computes it in per-PC scope.
1333    if w.scope != AggregateScope::Pc {
1334        return Err(format!("{at}.render=op_timeline requires scope: pc"));
1335    }
1336    // Each unused field, with the name the operator wrote, so the error
1337    // points at exactly what to delete.
1338    if w.kind.is_some() {
1339        return Err(format!("{at}.render=op_timeline does not use `kind`"));
1340    }
1341    if w.source.is_some() {
1342        return Err(format!("{at}.render=op_timeline does not use `source`"));
1343    }
1344    if w.agg.is_some() {
1345        return Err(format!("{at}.render=op_timeline does not use `agg`"));
1346    }
1347    for (label, set) in [
1348        ("group_by", w.group_by.is_some()),
1349        ("bool_path", w.bool_path.is_some()),
1350        ("value_path", w.value_path.is_some()),
1351        ("transform", w.transform.is_some()),
1352        ("sample_minutes", w.sample_minutes.is_some()),
1353        ("time_bucket", w.time_bucket.is_some()),
1354        ("limit", w.limit.is_some()),
1355        ("exclude", !w.exclude.is_empty()),
1356    ] {
1357        if set {
1358            return Err(format!("{at}.render=op_timeline does not use `{label}`"));
1359        }
1360    }
1361    Ok(())
1362}
1363
1364/// Default materialization cadence for a [`SqlWidget`] whose `refresh` is
1365/// unset — 1 hour. A view over feed/inventory tables changes only as fast as
1366/// its underlying feed refresh (often daily), so an hour is fresh enough while
1367/// keeping an expensive correlation join off the ~30s Dashboard poll path.
1368pub const DEFAULT_VIEW_REFRESH: std::time::Duration = std::time::Duration::from_secs(3600);
1369
1370/// #vuln-roadmap PR3: a **SQL-backed, materialized** widget on a [`View`].
1371///
1372/// Where an [`AggregateWidget`] encodes an `obs_events` rollup in structured
1373/// YAML fields, a `SqlWidget` carries a raw read-only `SELECT`/`WITH` over the
1374/// projector's tables (inventory `explode:` tables, `feeds`, `check_status`,
1375/// …) — the correlation that powers a vulnerability / EOL / license dashboard
1376/// is just a `JOIN`, far more expressive than a YAML DSL. The backend runs the
1377/// query in the read-only sandbox (`api::query`), caches the result on the
1378/// `refresh` cadence, and maps it to the same render-ready shape the existing
1379/// widget components consume, via [`RenderSpec`]. See [`View::sql_widgets`].
1380#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1381pub struct SqlWidget {
1382    /// Widget heading. Required, validated non-empty.
1383    pub title: String,
1384    /// Optional muted subtitle (a unit, a caveat). Rejected if present-blank.
1385    #[serde(default, skip_serializing_if = "Option::is_none")]
1386    pub description: Option<String>,
1387    /// The read-only SQL. Executed in the `api::query` sandbox: a single
1388    /// `SELECT`/`WITH` on a `SQLITE_OPEN_READONLY` connection, row-capped and
1389    /// time-bounded. The backend validates it read-only at `view create` and
1390    /// again at run time; a write verb / stacked statement is rejected.
1391    pub query: String,
1392    /// How the query's result columns map to a visual — see [`RenderSpec`].
1393    pub render: RenderSpec,
1394    /// Materialization cadence as a humantime duration (`"6h"`, `"30m"`).
1395    /// Absent ⇒ [`DEFAULT_VIEW_REFRESH`]. The backend re-runs the query at
1396    /// most this often; reads in between hit the cache.
1397    #[serde(default, skip_serializing_if = "Option::is_none")]
1398    pub refresh: Option<String>,
1399    /// Where the widget surfaces — an Analytics tab and/or a pinned Dashboard
1400    /// card. At least one must be set (else it renders nowhere).
1401    pub placement: Placement,
1402}
1403
1404impl SqlWidget {
1405    /// The effective refresh cadence — the parsed `refresh` or
1406    /// [`DEFAULT_VIEW_REFRESH`]. Falls back to the default on an unparseable
1407    /// value rather than panicking on the read path (validation already
1408    /// rejected a bad value at `view create`).
1409    pub fn refresh_interval(&self) -> std::time::Duration {
1410        self.refresh
1411            .as_deref()
1412            .and_then(|s| humantime::parse_duration(s).ok())
1413            .unwrap_or(DEFAULT_VIEW_REFRESH)
1414    }
1415}
1416
1417/// How a [`SqlWidget`]'s SQL result columns map onto a visual. A `kind` names
1418/// the chart; the channel fields (`value`, `label`, `columns`, …) name which
1419/// result columns feed it. Only the channels a `kind` uses are read; the
1420/// backend validates the named columns exist in the result. New chart types
1421/// are "one renderer + the same mapping", so this stays a flat, additive shape.
1422#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Hash)]
1423pub struct RenderSpec {
1424    /// Which visual to render the result as.
1425    pub kind: RenderKind,
1426    /// `table` only: the columns to show, in order. Absent ⇒ every result
1427    /// column (the universal default).
1428    #[serde(default, skip_serializing_if = "Option::is_none")]
1429    pub columns: Option<Vec<String>>,
1430    /// `table` only: optional per-column header relabelling (result column →
1431    /// display name). Columns not listed keep their SQL name.
1432    #[serde(default, skip_serializing_if = "Option::is_none")]
1433    pub labels: Option<std::collections::BTreeMap<String, String>>,
1434    /// `stat` / `bar` / `pie` / `gauge`: the result column holding the numeric
1435    /// value (`stat`/`gauge` read the first row; `bar`/`pie` read every row).
1436    #[serde(default, skip_serializing_if = "Option::is_none")]
1437    pub value: Option<String>,
1438    /// `bar` / `pie`: the result column holding each row's category label.
1439    #[serde(default, skip_serializing_if = "Option::is_none")]
1440    pub label: Option<String>,
1441    /// `bar` / `pie`: keep only the top-N rows (by value). Absent ⇒ all rows.
1442    #[serde(default, skip_serializing_if = "Option::is_none")]
1443    pub limit: Option<u32>,
1444    /// `pie` only: render as a donut (a hole with the total in the centre).
1445    #[serde(default, skip_serializing_if = "Option::is_none")]
1446    pub donut: Option<bool>,
1447    /// `gauge` only: the numerator column (paired with `den`). Alternative to
1448    /// a precomputed `value` ratio.
1449    #[serde(default, skip_serializing_if = "Option::is_none")]
1450    pub num: Option<String>,
1451    /// `gauge` only: the denominator column (paired with `num`).
1452    #[serde(default, skip_serializing_if = "Option::is_none")]
1453    pub den: Option<String>,
1454}
1455
1456/// The chart kind for a [`RenderSpec`]. `table` and `pie` are new in PR3; the
1457/// rest reuse the existing `obs_events` widget renderers.
1458#[derive(
1459    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash, Default,
1460)]
1461#[serde(rename_all = "lowercase")]
1462pub enum RenderKind {
1463    /// The full result grid (new renderer). The universal default.
1464    #[default]
1465    Table,
1466    /// A single headline number from the first row's `value` cell.
1467    Stat,
1468    /// Ranked horizontal bars — `label` + `value` per row, optional top-N.
1469    Bar,
1470    /// Parts-of-a-whole (new renderer) — `label` + `value` per row.
1471    Pie,
1472    /// A ratio dial — a `value` ratio, or a `num`/`den` pair.
1473    Gauge,
1474    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1475    #[serde(other)]
1476    Unknown,
1477}
1478
1479/// Where a [`SqlWidget`] surfaces in the SPA. Mirrors the placement an
1480/// [`AggregateWidget`] expresses via `dashboard` + `pin_dashboard`, but as an
1481/// explicit block since a SQL widget lives on a standalone view.
1482#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1483pub struct Placement {
1484    /// The Analytics tab this widget groups under (the `AggregateWidget`
1485    /// `dashboard` analogue). Absent ⇒ not shown on the Analytics page.
1486    #[serde(default, skip_serializing_if = "Option::is_none")]
1487    pub analytics: Option<String>,
1488    /// Promote to the main Dashboard (reuses #900's pinned section). Absent ⇒
1489    /// not pinned.
1490    #[serde(default, skip_serializing_if = "Option::is_none")]
1491    pub dashboard: Option<DashboardPlacement>,
1492}
1493
1494impl Placement {
1495    /// True when the widget is pinned to the main Dashboard.
1496    pub fn is_pinned(&self) -> bool {
1497        self.dashboard.as_ref().is_some_and(|d| d.pin)
1498    }
1499    /// The Analytics tab name, or a fallback so a dashboard-only widget still
1500    /// carries a group label for the shared widget list.
1501    pub fn tab(&self) -> &str {
1502        self.analytics.as_deref().unwrap_or("Dashboard")
1503    }
1504}
1505
1506/// The `placement.dashboard` block — see [`Placement::dashboard`].
1507#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1508pub struct DashboardPlacement {
1509    /// Pin this widget to the main Dashboard's promoted section.
1510    #[serde(default)]
1511    pub pin: bool,
1512}
1513
1514/// Per-widget validation for a list of [`SqlWidget`]s — shared by the
1515/// [`View`] resource so authoring errors surface at `view create`. `field`
1516/// names the containing key for error messages. The read-only SQL check is
1517/// NOT here (it lives in the backend `api::query` sandbox, which kanade-shared
1518/// can't depend on) — this validates structure: non-empty title/query, a
1519/// known `kind`, the channels each `kind` needs, a real placement, and a
1520/// parseable `refresh`.
1521pub fn validate_sql_widgets(widgets: &[SqlWidget], field: &str) -> Result<(), String> {
1522    for (i, w) in widgets.iter().enumerate() {
1523        let at = format!("{field}[{i}]");
1524        if w.title.trim().is_empty() {
1525            return Err(format!("{at}.title must not be empty"));
1526        }
1527        if w.query.trim().is_empty() {
1528            return Err(format!("{at}.query must not be empty"));
1529        }
1530        if let Some(description) = &w.description {
1531            if description.trim().is_empty() {
1532                return Err(format!("{at}.description must not be empty when set"));
1533            }
1534        }
1535        if let Some(refresh) = &w.refresh {
1536            humantime::parse_duration(refresh)
1537                .map_err(|e| format!("{at}.refresh '{refresh}' is not a valid duration: {e}"))?;
1538        }
1539        // A widget that surfaces nowhere is an invisible no-op. A
1540        // `dashboard:` block with `pin: false` doesn't count — it pins
1541        // nowhere — so gate on the effective pin, not the block's presence
1542        // (Gemini / CodeRabbit).
1543        if w.placement.analytics.is_none() && !w.placement.is_pinned() {
1544            return Err(format!(
1545                "{at}.placement must set `analytics` and/or pin to `dashboard` (else the widget renders nowhere)"
1546            ));
1547        }
1548        if let Some(tab) = &w.placement.analytics {
1549            if tab.trim().is_empty() {
1550                return Err(format!(
1551                    "{at}.placement.analytics must not be empty when set"
1552                ));
1553            }
1554        }
1555        // A per-PC widget (its query binds `:pc_id`) renders only in the
1556        // per-PC Analytics scope, bound to the selected PC. The Dashboard's
1557        // pinned section is fleet-scope and never sends a PC, so a pinned
1558        // per-PC widget would be silently dropped on every request — reject
1559        // the contradiction at create time rather than let it vanish (claude
1560        // review). Literal-aware so a `:pc_id` inside a string literal doesn't
1561        // trip it (see [`rewrite_pc_id_param`]).
1562        if w.placement.is_pinned() && rewrite_pc_id_param(&w.query).1 > 0 {
1563            return Err(format!(
1564                "{at}: a per-PC widget (its query binds `:pc_id`) cannot pin to the Dashboard \
1565                 (the Dashboard is fleet-scope, it never selects a PC) — use `analytics` placement only"
1566            ));
1567        }
1568        validate_render_spec(&w.render, &at)?;
1569    }
1570    Ok(())
1571}
1572
1573/// The named parameter a per-PC [`SqlWidget`] binds to the selected PC. Its
1574/// presence in a widget's query is what makes the widget per-PC.
1575pub const PC_ID_PARAM: &str = ":pc_id";
1576
1577/// Rewrite every *real* `:pc_id` parameter in a widget query to a positional
1578/// `?`, returning `(rewritten_sql, count)`. "Real" = OUTSIDE string literals,
1579/// quoted identifiers and comments, and a whole token (the char after `:pc_id`
1580/// isn't a word char, so `:pc_idx` is left alone). One scanner shared by three
1581/// call sites so they can't disagree on how many `?` SQLite will actually see:
1582///   * per-PC scope detection (`count > 0` ⇒ the widget is per-PC),
1583///   * the backend's bind path (sqlx-sqlite binds POSITIONAL `?` only, not
1584///     `:name`, so the token must be rewritten and bound once per occurrence),
1585///   * and `validate_sql_widgets`' pinned-per-PC rejection above.
1586///
1587/// The literal/comment skipping mirrors the read-only sandbox's
1588/// `strip_sql_noise`, so a `:pc_id` inside `SELECT 'see :pc_id docs'` is copied
1589/// verbatim and NOT counted — it would otherwise be miscounted (a bind-count
1590/// mismatch → `SQLITE_RANGE`) and misclassify the widget's scope (Gemini /
1591/// claude review).
1592pub fn rewrite_pc_id_param(sql: &str) -> (String, usize) {
1593    let mut out = String::with_capacity(sql.len());
1594    let mut count = 0usize;
1595    let mut chars = sql.char_indices().peekable();
1596    while let Some((idx, c)) = chars.next() {
1597        match c {
1598            // String literal / quoted identifier — copy verbatim, honouring the
1599            // doubled-quote escape (`''` / `""` stays inside).
1600            '\'' | '"' => {
1601                out.push(c);
1602                let quote = c;
1603                while let Some((_, d)) = chars.next() {
1604                    out.push(d);
1605                    if d == quote {
1606                        if chars.peek().map(|&(_, e)| e) == Some(quote) {
1607                            let (_, e) = chars.next().unwrap();
1608                            out.push(e);
1609                        } else {
1610                            break;
1611                        }
1612                    }
1613                }
1614            }
1615            // Line comment — copy to end of line.
1616            '-' if chars.peek().map(|&(_, e)| e) == Some('-') => {
1617                out.push(c);
1618                for (_, d) in chars.by_ref() {
1619                    out.push(d);
1620                    if d == '\n' {
1621                        break;
1622                    }
1623                }
1624            }
1625            // Block comment — copy to `*/`.
1626            '/' if chars.peek().map(|&(_, e)| e) == Some('*') => {
1627                out.push(c);
1628                let (_, star) = chars.next().unwrap();
1629                out.push(star);
1630                let mut prev = ' ';
1631                for (_, d) in chars.by_ref() {
1632                    out.push(d);
1633                    if prev == '*' && d == '/' {
1634                        break;
1635                    }
1636                    prev = d;
1637                }
1638            }
1639            // A `:pc_id` token outside any literal/comment — rewrite if it's a
1640            // whole token (not the prefix of `:pc_idx`).
1641            ':' if sql[idx..].starts_with(PC_ID_PARAM) => {
1642                let after = idx + PC_ID_PARAM.len();
1643                let next_is_word = sql[after..]
1644                    .chars()
1645                    .next()
1646                    .is_some_and(|w| w.is_alphanumeric() || w == '_');
1647                if next_is_word {
1648                    out.push(c);
1649                } else {
1650                    out.push('?');
1651                    count += 1;
1652                    for _ in 0..PC_ID_PARAM.chars().count() - 1 {
1653                        chars.next();
1654                    }
1655                }
1656            }
1657            _ => out.push(c),
1658        }
1659    }
1660    (out, count)
1661}
1662
1663/// Validate a [`RenderSpec`]: reject the #492 `Unknown` catch-all (an operator
1664/// typo at create time) and require the channel columns each `kind` reads.
1665fn validate_render_spec(r: &RenderSpec, at: &str) -> Result<(), String> {
1666    // A channel column is "given" when present and non-blank.
1667    let given = |v: &Option<String>| v.as_deref().map(str::trim).is_some_and(|s| !s.is_empty());
1668    match r.kind {
1669        RenderKind::Unknown => {
1670            return Err(format!(
1671                "{at}.render.kind is not a known value (table | stat | bar | pie | gauge)"
1672            ));
1673        }
1674        RenderKind::Table => {
1675            // `columns` optional; if given, each name must be non-blank.
1676            if let Some(cols) = &r.columns {
1677                if cols.iter().any(|c| c.trim().is_empty()) {
1678                    return Err(format!("{at}.render.columns must not contain blank names"));
1679                }
1680            }
1681            if let Some(labels) = &r.labels {
1682                for (k, v) in labels {
1683                    if k.trim().is_empty() || v.trim().is_empty() {
1684                        return Err(format!(
1685                            "{at}.render.labels keys and values must be non-empty"
1686                        ));
1687                    }
1688                }
1689            }
1690        }
1691        RenderKind::Stat => {
1692            if !given(&r.value) {
1693                return Err(format!("{at}.render.value is required for kind=stat"));
1694            }
1695        }
1696        RenderKind::Bar | RenderKind::Pie => {
1697            let kind = if r.kind == RenderKind::Bar {
1698                "bar"
1699            } else {
1700                "pie"
1701            };
1702            if !given(&r.label) {
1703                return Err(format!("{at}.render.label is required for kind={kind}"));
1704            }
1705            if !given(&r.value) {
1706                return Err(format!("{at}.render.value is required for kind={kind}"));
1707            }
1708            // `limit: 0` truncates to no rows — an invisible widget, almost
1709            // certainly a typo. Omit `limit` for "all rows" (CodeRabbit).
1710            if r.limit == Some(0) {
1711                return Err(format!(
1712                    "{at}.render.limit must be >= 1 (omit it to keep all rows)"
1713                ));
1714            }
1715        }
1716        RenderKind::Gauge => {
1717            // Either a precomputed `value` ratio, or a `num`/`den` pair —
1718            // exactly one of the two forms.
1719            match (given(&r.value), given(&r.num), given(&r.den)) {
1720                (true, false, false) => {}
1721                (false, true, true) => {}
1722                _ => {
1723                    return Err(format!(
1724                        "{at}.render for kind=gauge needs either `value` (a ratio) or both `num` and `den`"
1725                    ));
1726                }
1727            }
1728        }
1729    }
1730    Ok(())
1731}
1732
1733/// A standalone declarative read/aggregation for the Analytics page (#743).
1734///
1735/// A **view** aggregates stored fleet data (`obs_events`, …) without an
1736/// `execute` or a schedule — unlike a [`Manifest`] it only declares
1737/// [`AggregateWidget`]s. (The first line is concise on purpose: `schemars`
1738/// uses it as the generated schema's `title`.) The backend reads views from
1739/// `BUCKET_VIEWS` at
1740/// query time and merges their widgets with the co-located `aggregate:`
1741/// hints on jobs, so a cross-cutting dashboard (one that charts events
1742/// emitted by several other jobs / the agent) has a home that doesn't need
1743/// a noop job carrier. Stored JSON in `BUCKET_VIEWS`, keyed by `id`.
1744#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1745pub struct View {
1746    /// Stable identifier (the KV key). Required, validated non-empty.
1747    pub id: String,
1748    /// Optional human description shown on the Views admin page.
1749    #[serde(default, skip_serializing_if = "Option::is_none")]
1750    pub description: Option<String>,
1751    /// The `obs_events` aggregate widgets this view contributes to the
1752    /// Analytics page. Optional since PR3 — a view may instead (or also)
1753    /// carry [`sql_widgets`](View::sql_widgets); a view must have at least one
1754    /// widget across the two lists.
1755    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1756    pub widgets: Vec<AggregateWidget>,
1757    /// #vuln-roadmap PR3: SQL-backed, materialized widgets — raw read-only SQL
1758    /// over the projector tables (inventory/feeds/…) mapped to a visual. This
1759    /// is how a correlation dashboard (vulnerability / EOL / license) is
1760    /// expressed as config. See [`SqlWidget`].
1761    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1762    pub sql_widgets: Vec<SqlWidget>,
1763    /// Free-form operator taxonomy (same role as [`Manifest::tags`]).
1764    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1765    pub tags: Vec<String>,
1766    /// GitOps provenance (#678), stamped by `kanade view create` from the
1767    /// source YAML's Git context — same as [`Manifest::origin`].
1768    #[serde(default, skip_serializing_if = "Option::is_none")]
1769    pub origin: Option<RepoOrigin>,
1770}
1771
1772/// True if `id` is a safe resource identifier — non-empty and only
1773/// `[A-Za-z0-9._-]`. A view `id` becomes a NATS KV key *and* a URL path
1774/// segment (`/api/views/{id}`), so this blocks `/`, `..`, whitespace and
1775/// other characters that would break the KV key or let a CLI arg wander
1776/// the URL space. (#743 / #744 follow-up — a deliberately small charset
1777/// rather than the looser set NATS technically allows.)
1778pub fn is_valid_resource_id(id: &str) -> bool {
1779    !id.is_empty()
1780        && id
1781            .chars()
1782            .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-')
1783}
1784
1785impl View {
1786    pub fn validate(&self) -> Result<(), String> {
1787        // Validate the id exactly as stored — no `.trim()`. `views::create`
1788        // uses `self.id` verbatim as the KV key and it's the `/api/views/{id}`
1789        // URL segment a lookup matches, so a padded id like `" my-view "` that
1790        // validated as its trimmed form but was stored raw would silently never
1791        // match. The charset excludes whitespace, so checking the untrimmed id
1792        // rejects such an id outright.
1793        if !is_valid_resource_id(&self.id) {
1794            return Err(
1795                "view.id must be non-empty and only [A-Za-z0-9._-] (it's a KV key + URL segment; \
1796                 no surrounding whitespace)"
1797                    .to_string(),
1798            );
1799        }
1800        // A view must contribute at least one widget across the two lists;
1801        // `validate_aggregate_widgets` rejects an empty `widgets` on its own,
1802        // so only call it when that list is non-empty (a pure-SQL view is
1803        // valid with an empty `widgets`).
1804        if self.widgets.is_empty() && self.sql_widgets.is_empty() {
1805            return Err(
1806                "view must declare at least one widget (`widgets:` and/or `sql_widgets:`)"
1807                    .to_string(),
1808            );
1809        }
1810        if !self.widgets.is_empty() {
1811            validate_aggregate_widgets(&self.widgets, "widgets")?;
1812        }
1813        validate_sql_widgets(&self.sql_widgets, "sql_widgets")?;
1814        for tag in &self.tags {
1815            if tag.trim().is_empty() {
1816                return Err("tags must not contain empty entries".to_string());
1817            }
1818        }
1819        Ok(())
1820    }
1821}
1822
1823/// Default membership-recompute cadence for a dynamic [`GroupDef`] whose
1824/// `refresh` is unset — 10 minutes. A group's SQL is evaluated lazily (only
1825/// when a schedule targeting it fires, or the members preview is requested)
1826/// and the result cached for this long, so fleet facts (inventory updates, a
1827/// newly-registered PC) reach the group within at most one cadence while an
1828/// expensive correlation query stays off the hot scheduler-tick path. A
1829/// static `members:` group ignores this (its membership is literal).
1830pub const DEFAULT_GROUP_REFRESH: std::time::Duration = std::time::Duration::from_secs(600);
1831
1832/// A **declared fleet group** (#1032): the third manifest kind alongside
1833/// [`Manifest`] (jobs) and [`Schedule`] (schedules), stored in
1834/// `BUCKET_GROUP_DEFS` keyed by [`id`](GroupDef::id).
1835///
1836/// (The first doc line deliberately does not start with `#NNN` — schemars
1837/// treats a leading `#` as a Markdown heading and would extract it as the
1838/// schema `title`, garbling it. Same reason [`View`]'s doc leads with prose.)
1839///
1840/// A group definition names a set of PCs in one of two mutually-exclusive
1841/// ways:
1842///   * **static** — a literal [`members`](GroupDef::members) list. Declared,
1843///     git-reviewable membership (the auditability win over hand-editing the
1844///     imperative `agent_groups` KV).
1845///   * **dynamic** — a read-only SQL [`query`](GroupDef::query) that returns a
1846///     `pc_id` column. Membership is *derived from the fleet's own facts*
1847///     (`agents`, `inventory_facts` + `json_extract(facts_json, …)`, `feeds`,
1848///     `check_status`, `explode:` tables — anything in the projector DB), so
1849///     "every client OS", "the servers sharing a hostname prefix", "machines
1850///     still on build 26100" are all just a `SELECT`. The query runs in the
1851///     backend read-only sandbox (`api::query`), never on the endpoint.
1852///
1853/// A schedule's `target.groups` resolves a defined group (static or dynamic)
1854/// **in addition to** the imperative `agent_groups` membership, so declared
1855/// groups and manually-assigned ones coexist and this never mutates
1856/// `agent_groups`.
1857#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1858pub struct GroupDef {
1859    /// Stable identifier (the KV key + URL segment + the name a schedule's
1860    /// `target.groups` references). Required; same `[A-Za-z0-9._-]` charset
1861    /// as a [`View`] id via [`is_valid_resource_id`].
1862    pub id: String,
1863    /// Optional human description shown on the groups admin page.
1864    #[serde(default, skip_serializing_if = "Option::is_none")]
1865    pub description: Option<String>,
1866    /// Static membership — a literal list of `pc_id`s. Mutually exclusive with
1867    /// [`query`](GroupDef::query); exactly one of the two must be set
1868    /// (enforced by [`GroupDef::validate`]).
1869    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1870    pub members: Vec<String>,
1871    /// Dynamic membership — a read-only `SELECT`/`WITH` returning a `pc_id`
1872    /// column. Mutually exclusive with [`members`](GroupDef::members). The
1873    /// backend validates it read-only at `group create` and again at run time;
1874    /// a write verb / stacked statement is rejected. Empty string is treated
1875    /// as unset so an operator can comment the body out to switch to
1876    /// `members:` without dropping the key.
1877    #[serde(default, skip_serializing_if = "Option::is_none")]
1878    pub query: Option<String>,
1879    /// Membership-recompute cadence for a dynamic group as a humantime
1880    /// duration (`"30m"`, `"6h"`). Absent ⇒ [`DEFAULT_GROUP_REFRESH`]. Ignored
1881    /// for a static group.
1882    #[serde(default, skip_serializing_if = "Option::is_none")]
1883    pub refresh: Option<String>,
1884    /// Free-form operator taxonomy (same role as [`Manifest::tags`]).
1885    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1886    pub tags: Vec<String>,
1887    /// GitOps provenance (#678), stamped by `kanade group def create` from the
1888    /// source YAML's Git context — same as [`View::origin`].
1889    #[serde(default, skip_serializing_if = "Option::is_none")]
1890    pub origin: Option<RepoOrigin>,
1891}
1892
1893impl GroupDef {
1894    /// The dynamic SQL body if this is a dynamic group — a non-blank `query`.
1895    /// (An empty-string `query` reads as unset, mirroring [`Execute::script`].)
1896    pub fn dynamic_query(&self) -> Option<&str> {
1897        self.query
1898            .as_deref()
1899            .map(str::trim)
1900            .filter(|q| !q.is_empty())
1901    }
1902
1903    /// The effective recompute cadence for a dynamic group — the parsed
1904    /// `refresh` or [`DEFAULT_GROUP_REFRESH`]. Falls back to the default on an
1905    /// unparseable value rather than panicking on the read path (validation
1906    /// already rejected a bad value at create time).
1907    pub fn refresh_interval(&self) -> std::time::Duration {
1908        self.refresh
1909            .as_deref()
1910            .and_then(|s| humantime::parse_duration(s).ok())
1911            .unwrap_or(DEFAULT_GROUP_REFRESH)
1912    }
1913
1914    pub fn validate(&self) -> Result<(), String> {
1915        // Validate the id EXACTLY as stored — no `.trim()`. The id is used
1916        // verbatim as the KV key (`group_defs::create` does `kv.put(&group.id,
1917        // …)`) and as the name a schedule's `target.groups` matches, so a
1918        // padded id like `" clients "` that validated as its trimmed form but
1919        // was stored raw would silently never match. The charset excludes
1920        // whitespace, so checking the untrimmed id rejects such an id outright.
1921        if !is_valid_resource_id(&self.id) {
1922            return Err(
1923                "group.id must be non-empty and only [A-Za-z0-9._-] (it's a KV key + URL segment; \
1924                 no surrounding whitespace)"
1925                    .to_string(),
1926            );
1927        }
1928        // Exactly one of members / query. A blank `query` counts as unset so
1929        // the "comment the body out" workflow lands on the members branch
1930        // rather than a confusing "both set" error.
1931        let has_members = !self.members.is_empty();
1932        let has_query = self.dynamic_query().is_some();
1933        match (has_members, has_query) {
1934            (false, false) => {
1935                return Err(
1936                    "group must declare either a static `members:` list or a dynamic `query:`"
1937                        .to_string(),
1938                );
1939            }
1940            (true, true) => {
1941                return Err(
1942                    "`members:` and `query:` are mutually exclusive — a group is either static or dynamic"
1943                        .to_string(),
1944                );
1945            }
1946            _ => {}
1947        }
1948        for m in &self.members {
1949            if m.trim().is_empty() {
1950                return Err("members must not contain empty entries".to_string());
1951            }
1952        }
1953        // A dynamic group's refresh must parse (a static group ignores it, but
1954        // reject a bad value either way so a later members→query switch can't
1955        // surprise the operator).
1956        if let Some(r) = &self.refresh
1957            && humantime::parse_duration(r).is_err()
1958        {
1959            return Err(format!(
1960                "group.refresh '{r}' is not a valid duration (e.g. '30m', '6h')"
1961            ));
1962        }
1963        for tag in &self.tags {
1964            if tag.trim().is_empty() {
1965                return Err("tags must not contain empty entries".to_string());
1966            }
1967        }
1968        Ok(())
1969    }
1970}
1971
1972/// Issue #246 — `emit:` manifest block for jobs whose stdout is
1973/// NDJSON observability events (one `ObsEvent` per line). Parallel
1974/// to `inventory:` but for the append-only timeline pipeline; see
1975/// `Manifest::emit` for the full contract.
1976#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1977pub struct EmitConfig {
1978    /// What kind of payload the agent should expect on stdout. Only
1979    /// `events` is defined today (parses each non-empty line as
1980    /// `ObsEvent` and publishes on `obs.<pc_id>`); future variants
1981    /// (e.g. metrics streams, structured trace events) plug in here.
1982    #[serde(rename = "type")]
1983    pub kind: EmitKind,
1984    /// Operator hint for where the script keeps its own state — the
1985    /// watermark file the PowerShell / sh body reads + writes
1986    /// between runs so it only emits NEW events since the last
1987    /// poll. The agent doesn't read this; it's documentation that
1988    /// the SPA (and `kanade job edit`) can surface to operators
1989    /// reviewing the manifest. Optional; the script is allowed to
1990    /// keep state anywhere (registry, env, etc.) — the field's
1991    /// presence makes the convention discoverable.
1992    #[serde(default, skip_serializing_if = "Option::is_none")]
1993    pub watermark_path: Option<String>,
1994}
1995
1996/// `emit.type` enum. Lowercase serde so manifests read
1997/// `type: events` rather than `Events`.
1998#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1999#[serde(rename_all = "lowercase")]
2000pub enum EmitKind {
2001    /// Per-line `ObsEvent` JSON. Agent parses + publishes on
2002    /// `obs.<pc_id>`, drops the stdout from the resulting
2003    /// `ExecResult`.
2004    Events,
2005}
2006
2007/// v0.31 / #40: declarative "flatten this JSON array into a real
2008/// SQLite table" spec on an inventory manifest. The projector
2009/// creates the table on first registration (CREATE TABLE IF NOT
2010/// EXISTS + indexes) and writes a row per element of
2011/// `payload[field]` on every result, scoped by (pc_id, job_id) so
2012/// each PC's rows replace cleanly without a per-PC schema.
2013#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2014pub struct ExplodeSpec {
2015    /// JSON array key under the payload to explode. E.g. `"apps"`
2016    /// for `payload: { apps: [{...}, {...}] }`.
2017    pub field: String,
2018    /// Derived SQLite table name. Operators choose this — pick
2019    /// something namespaced + stable (`inventory_sw_apps`, not
2020    /// `apps`) so multiple inventory manifests don't collide on a
2021    /// generic name.
2022    pub table: String,
2023    /// Element-level fields that uniquely identify a row inside one
2024    /// PC's payload. The full PK is `(pc_id, job_id) + these
2025    /// columns`. Required — operators must think about uniqueness
2026    /// (e.g. `["name", "source"]` for installed apps because the
2027    /// same name appears in multiple uninstall hives).
2028    ///
2029    /// v0.31 / #41: same tuple drives history identity. When
2030    /// `track_history` is on, the projector serialises these
2031    /// fields' values into `inventory_history.identity_json` for
2032    /// every change event, so queries like "every PC that ever
2033    /// installed Chrome (any source)" filter on identity_json
2034    /// content without a per-manifest schema.
2035    pub primary_key: Vec<String>,
2036    /// Per-element fields that become columns in the derived table.
2037    pub columns: Vec<ExplodeColumn>,
2038    /// v0.31 / #41: when true (default false), the projector
2039    /// diffs each PC's incoming payload against the prior rows
2040    /// for the same (pc_id, job_id) BEFORE the DELETE-then-INSERT
2041    /// replace, and writes added / removed / changed events into
2042    /// `inventory_history`. Lets operators answer time-dimension
2043    /// questions ("when did Chrome 120 first appear on PC X?",
2044    /// "what's the Win 11 23H2 rollout curve") without storing
2045    /// per-scan snapshots. Off by default so operators opt in
2046    /// per-spec — history has a real storage cost on long-lived
2047    /// deployments (mitigated by the 90-day default retention
2048    /// sweeper, see `cleanup` module).
2049    #[serde(default)]
2050    pub track_history: bool,
2051}
2052
2053/// One column in an [`ExplodeSpec`]'s derived table.
2054#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2055pub struct ExplodeColumn {
2056    /// JSON key under each array element. Becomes the column name
2057    /// in the derived SQLite table — we don't rename.
2058    pub field: String,
2059    /// SQLite affinity: `"text"` (default), `"integer"`, `"real"`.
2060    /// Storage maps directly via `sqlx::query.bind(...)`; type
2061    /// mismatches at INSERT-time fail loudly rather than silently
2062    /// dropping the row.
2063    #[serde(default, skip_serializing_if = "Option::is_none")]
2064    #[serde(rename = "type")]
2065    pub kind: Option<String>,
2066    /// When true, the projector creates a `CREATE INDEX` on this
2067    /// column at table-creation time. Boost for the common-filter
2068    /// columns (`name`, `version`) — operators mark them
2069    /// explicitly, the projector won't guess.
2070    #[serde(default)]
2071    pub index: bool,
2072}
2073
2074/// #vuln-roadmap: one declarative **external-data feed** on a `feed:`
2075/// manifest — see [`Manifest::feed`]. Unlike inventory [`ExplodeSpec`]
2076/// (keyed per `(pc_id, job_id)`), a feed is GLOBAL fleet-wide reference
2077/// data: the controller-tier job's script fetches + shapes it, prints the
2078/// array under [`field`](FeedSpec::field) inside a `#KANADE-FEED-BEGIN/END`
2079/// fence, and the projector REPLACES that feed's rows wholesale in the
2080/// shared `feeds` table keyed `(feed_id, item_id)`. The full element JSON
2081/// lands in a `data` column, so a `view:` SQL `json_extract`s whatever
2082/// shape the feed carries — no per-feed schema, no dynamic DDL. One
2083/// manifest may declare several feeds.
2084#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2085pub struct FeedSpec {
2086    /// Stable feed identifier — the `feed_id` partition in the shared
2087    /// `feeds` table. Operators choose this; namespace it (`cisa-kev`,
2088    /// `endoflife-windows`) so feeds don't collide. A new result for the
2089    /// same id replaces that partition wholesale.
2090    pub id: String,
2091    /// JSON array key under the (fenced) payload to ingest. E.g.
2092    /// `"vulnerabilities"` for `{ vulnerabilities: [{...}, {...}] }`.
2093    pub field: String,
2094    /// Element-level field(s) whose values uniquely identify an item
2095    /// within the feed — they form the `item_id` key (joined for a
2096    /// composite key). Required: operators must think about uniqueness
2097    /// (e.g. `["cveID"]` for CISA KEV). An element missing any of these is
2098    /// skipped (it has no stable identity).
2099    pub primary_key: Vec<String>,
2100}
2101
2102#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2103pub struct DisplayField {
2104    /// Top-level key in the stdout JSON.
2105    pub field: String,
2106    /// Human-readable column header.
2107    pub label: String,
2108    /// Optional render hint — `"number"`, `"bytes"`, `"timestamp"`,
2109    /// or `"table"` (#39). Defaults to plain text rendering on the
2110    /// SPA side. `"table"` expects the field's value to be a JSON
2111    /// array of objects and renders a nested sub-table on the
2112    /// per-PC detail page using `columns` as the schema; the fleet
2113    /// summary view falls back to showing the row count for
2114    /// `"table"` cells so the wide list stays compact.
2115    #[serde(default, skip_serializing_if = "Option::is_none")]
2116    #[serde(rename = "type")]
2117    pub kind: Option<String>,
2118    /// v0.30 / #39: when `kind == "table"`, the SPA renders the
2119    /// field's value (an array of objects like
2120    /// `disks: [{ device_id, size_bytes, ... }]`) as a nested
2121    /// sub-table using these columns. Each column is itself a
2122    /// `DisplayField`, so the nested cells reuse the same render
2123    /// hints (`bytes`, `number`, `timestamp`) — no parallel format
2124    /// pipeline. Ignored for any other `kind`.
2125    #[serde(default, skip_serializing_if = "Option::is_none")]
2126    pub columns: Option<Vec<DisplayField>>,
2127}
2128
2129#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2130pub struct Rollout {
2131    #[serde(default)]
2132    pub strategy: RolloutStrategy,
2133    pub waves: Vec<Wave>,
2134}
2135
2136#[derive(
2137    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
2138)]
2139#[serde(rename_all = "lowercase")]
2140pub enum RolloutStrategy {
2141    #[default]
2142    Wave,
2143}
2144
2145#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2146pub struct Wave {
2147    pub group: String,
2148    /// humantime delay measured from the deploy's publish time. wave[0]
2149    /// typically has "0s"; subsequent waves use minutes / hours.
2150    pub delay: String,
2151}
2152
2153#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default)]
2154pub struct Target {
2155    #[serde(default)]
2156    pub groups: Vec<String>,
2157    #[serde(default)]
2158    pub pcs: Vec<String>,
2159    #[serde(default)]
2160    pub all: bool,
2161}
2162
2163impl Target {
2164    /// At least one of all / groups / pcs is set.
2165    pub fn is_specified(&self) -> bool {
2166        self.all || !self.groups.is_empty() || !self.pcs.is_empty()
2167    }
2168
2169    /// Whether a PC (its `pc_id` + group membership) falls in this target:
2170    /// `all`, or the pc is listed, or it belongs to a listed group. Used
2171    /// by the agent to scope `client.visible_to` (#816). An unspecified
2172    /// target matches nobody (callers should treat "no target" as
2173    /// "visible to all" before calling this).
2174    pub fn matches(&self, pc_id: &str, groups: &[String]) -> bool {
2175        self.all
2176            || self.pcs.iter().any(|p| p == pc_id)
2177            || self.groups.iter().any(|g| groups.contains(g))
2178    }
2179}
2180
2181#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2182pub struct Execute {
2183    pub shell: ExecuteShell,
2184    /// Inline script body. Mutually exclusive with [`script_file`]
2185    /// and [`script_object`]; exactly one of the three must be set
2186    /// (enforced by [`Execute::validate_script_source`] at the
2187    /// write-side parse boundaries — `kanade job create` and
2188    /// `POST /api/jobs`).
2189    ///
2190    /// Empty string is treated as **unset** so operators can swap
2191    /// to a `script_file:` / `script_object:` alternative just by
2192    /// commenting out the body, without having to also drop the
2193    /// `script:` key entirely.
2194    ///
2195    /// [`script_file`]: Self::script_file
2196    /// [`script_object`]: Self::script_object
2197    #[serde(default, skip_serializing_if = "Option::is_none")]
2198    pub script: Option<String>,
2199    /// Repo-local file path resolved by the operator-side CLI at
2200    /// `kanade job create` time. The CLI reads the file, slots its
2201    /// contents into `script`, and clears this field before
2202    /// POSTing — so the backend / agents never see `script_file`
2203    /// in stored manifests. SPEC §2.4.1.
2204    ///
2205    /// The resolver shipped with #210: `kanade job create` /
2206    /// `kanade job validate` inline this field end-to-end. Because
2207    /// resolution is CLI-side (it needs the operator's filesystem),
2208    /// `POST /api/jobs` rejects a manifest that still carries it
2209    /// (#918) — a stored `script_file` job would 400 at every exec.
2210    /// Inline the script or use `script_object` when writing through
2211    /// the API / SPA editor.
2212    #[serde(default, skip_serializing_if = "Option::is_none")]
2213    pub script_file: Option<String>,
2214    /// Object Store reference (`<name>/<version>`) into the
2215    /// `scripts` bucket (`OBJECT_SCRIPTS`). Agents fetch the body
2216    /// at Execute time via `/api/script-objects/{name}/{version}`
2217    /// and cache it locally. SPEC §2.4.1.
2218    ///
2219    /// Fully wired (#210/#211): the backend resolves the digest at
2220    /// exec submission (`api::exec::resolve_script_source`), the agent
2221    /// fetches + sha-verifies + caches the body (`script_cache`), and
2222    /// `kanade script` CRUDs the store. Unlike `script_file:` (inlined
2223    /// CLI-side, git-managed), this keeps the body in versioned,
2224    /// digest-pinned object storage — the ops-managed counterpart.
2225    #[serde(default, skip_serializing_if = "Option::is_none")]
2226    pub script_object: Option<String>,
2227    /// humantime duration string (e.g. "30s", "10m"). Script-intrinsic
2228    /// — represents how long this script reasonably takes to run.
2229    pub timeout: String,
2230    /// Token + session combination the agent uses to launch the
2231    /// script (v0.21). Default = [`RunAs::System`] (Session 0,
2232    /// LocalSystem privileges, no GUI) — matches pre-v0.21 behavior.
2233    #[serde(default)]
2234    pub run_as: RunAs,
2235    /// Working directory for the spawned child (v0.21.1). When
2236    /// unset, the child inherits the agent's cwd — on Windows that
2237    /// means `%SystemRoot%\System32` for the prod service, which is
2238    /// almost never what operators actually want. Use an absolute
2239    /// path; relative paths are passed through to the OS verbatim.
2240    /// `%PROGRAMDATA%` works for `run_as: system`; for `run_as: user`
2241    /// you'd want `%USERPROFILE%` (but expansion happens in the
2242    /// shell, so write `$env:USERPROFILE` for PowerShell, or set
2243    /// it via teravars before `kanade job create`).
2244    #[serde(default, skip_serializing_if = "Option::is_none")]
2245    pub cwd: Option<String>,
2246}
2247
2248impl Execute {
2249    /// Treat an empty — or whitespace-only (#918) — `script:` body as
2250    /// "intentionally unset". Operators commenting out a block-scalar
2251    /// tend to leave the key behind, and failing the validator on
2252    /// `script: ""` would surprise them; a body of blank lines can't
2253    /// be a real script either, only a commented-out one, and letting
2254    /// it count as "set" shipped a validated do-nothing job.
2255    fn has_inline_script(&self) -> bool {
2256        matches!(&self.script, Some(s) if !s.trim().is_empty())
2257    }
2258
2259    /// Enforce that exactly one of `script` / `script_file` /
2260    /// `script_object` is set. Called at the write-side parse
2261    /// boundaries (CLI `kanade job create` + backend
2262    /// `POST /api/jobs`) so ambiguous YAML is rejected before it
2263    /// reaches the JOBS KV. Read paths (projector, agent
2264    /// scheduler, list endpoints) skip this check — they only ever
2265    /// see what the write path already validated.
2266    pub fn validate_script_source(&self) -> Result<(), String> {
2267        // #918: a blank-but-present alternate source is a typo, not a
2268        // choice — `script_file: ""` used to count as "set", pass the
2269        // exactly-one check, and only fail at use time (the CLI reads
2270        // a file named ""; a stored blank script_object 404s on every
2271        // exec). Reject it with the field named. Inline `script` keeps
2272        // its documented empty-means-unset semantics instead — see
2273        // `has_inline_script`.
2274        if matches!(&self.script_file, Some(s) if s.trim().is_empty()) {
2275            return Err(
2276                "execute.script_file must not be blank when set (drop the key to use \
2277                 another source)"
2278                    .into(),
2279            );
2280        }
2281        if matches!(&self.script_object, Some(s) if s.trim().is_empty()) {
2282            return Err(
2283                "execute.script_object must not be blank when set (drop the key to use \
2284                 another source)"
2285                    .into(),
2286            );
2287        }
2288        let inline = self.has_inline_script();
2289        let file = self.script_file.is_some();
2290        let obj = self.script_object.is_some();
2291        let set = [inline, file, obj].into_iter().filter(|b| *b).count();
2292        match set {
2293            1 => {}
2294            0 => {
2295                return Err(
2296                    "execute: one of `script`, `script_file`, `script_object` must be set".into(),
2297                );
2298            }
2299            _ => {
2300                return Err(format!(
2301                    "execute: only one of `script` / `script_file` / `script_object` may be set \
2302                     (got script={inline}, script_file={file}, script_object={obj})"
2303                ));
2304            }
2305        }
2306        // #918: a script_object ref is `<name>/<version>` — the agent
2307        // fetches the body via `/api/script-objects/{name}/{version}`
2308        // and the backend uses the ref *verbatim* as the Object Store
2309        // key (`resolve_script_source`), so each half must be a
2310        // well-formed resource id: exactly one slash, and both halves
2311        // [A-Za-z0-9._-]. `is_valid_resource_id` also rejects a half
2312        // that's blank OR merely whitespace-padded (`"foo/bar "`) —
2313        // padding survives a JSON POST body (unlike a YAML plain
2314        // scalar) and would 404 on every exec (gemini/claude #943).
2315        if let Some(obj_ref) = self.script_object.as_deref() {
2316            let parts: Vec<&str> = obj_ref.split('/').collect();
2317            if parts.len() != 2 || parts.iter().any(|p| !is_valid_resource_id(p)) {
2318                return Err(format!(
2319                    "execute.script_object must be `<name>/<version>` with each half \
2320                     [A-Za-z0-9._-] (got '{obj_ref}'); publish bodies with \
2321                     `kanade script publish <name> <version>`"
2322                ));
2323            }
2324        }
2325        Ok(())
2326    }
2327}
2328
2329/// Job-generic post-step hook (see [`Manifest::finalize`]). Runs after
2330/// the main `execute:` script (and the collect upload) on a clean exit,
2331/// with the step's structured result injected via an environment
2332/// variable. P1 supports an inline `script:` only — `script_file:` /
2333/// `script_object:` are follow-ups.
2334#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2335pub struct FinalizeSpec {
2336    pub shell: ExecuteShell,
2337    /// Inline script body (required; inline-only in P1).
2338    pub script: String,
2339    /// humantime duration string (e.g. `"60s"`, `"5m"`). Defaults to
2340    /// `60s` when unset.
2341    #[serde(default = "default_finalize_timeout")]
2342    pub timeout: String,
2343    /// Token + session combination, like [`Execute::run_as`]. Defaults
2344    /// to [`RunAs::System`].
2345    #[serde(default)]
2346    pub run_as: RunAs,
2347    /// Working directory for the hook child, like [`Execute::cwd`].
2348    #[serde(default, skip_serializing_if = "Option::is_none")]
2349    pub cwd: Option<String>,
2350    /// #965: for a `collect:` job, run this hook once per uploaded
2351    /// bundle (with a single-bundle `KANADE_COLLECT_RESULT`) as each
2352    /// bundle uploads, instead of once after the whole set. Lets an
2353    /// interrupted collect still clean up the days it managed to
2354    /// upload (partial progress sticks), breaking the
2355    /// offline-before-finalize backlog spiral.
2356    ///
2357    /// **Opt-in** (default `false` = one call after all bundles, the
2358    /// established contract) because per-bundle changes the hook's
2359    /// payload (all → one) and invocation count (1 → N), which would
2360    /// break a hook written for the all-at-once assumption (cross-bundle
2361    /// aggregation, once-only side effects, all-or-nothing). Only valid
2362    /// with a `collect:` hint — [`Manifest::validate`] rejects it
2363    /// otherwise, since a non-collect finalize has no bundles to iterate.
2364    #[serde(default)]
2365    pub on_each_bundle: bool,
2366}
2367
2368/// Default `finalize.timeout` when the operator omits it.
2369fn default_finalize_timeout() -> String {
2370    "60s".to_string()
2371}
2372
2373impl FinalizeSpec {
2374    /// Lower to the wire form forwarded onto a [`Command`]. The timeout
2375    /// parse falls back to 60s — [`Manifest::validate`] already rejects
2376    /// an unparseable value at create time, so the fire path uses a safe
2377    /// default rather than failing (mirrors
2378    /// [`CollectHint::max_size_bytes`]). A sub-second timeout floors at
2379    /// 1s for the same reason `build_command` does.
2380    pub fn lower(&self) -> FinalizeCommand {
2381        let timeout_secs = humantime::parse_duration(&self.timeout)
2382            .map(|d| d.as_secs().max(1))
2383            .unwrap_or(60);
2384        FinalizeCommand {
2385            shell: self.shell.into(),
2386            script: self.script.clone(),
2387            timeout_secs,
2388            run_as: self.run_as,
2389            cwd: self.cwd.clone(),
2390            on_each_bundle: self.on_each_bundle,
2391        }
2392    }
2393}
2394
2395impl Manifest {
2396    /// Cross-field semantic checks that don't fit into pure serde
2397    /// derive. Currently delegates to
2398    /// [`Execute::validate_script_source`] — see that method's
2399    /// docs for the rationale on which call sites should run this.
2400    pub fn validate(&self) -> Result<(), String> {
2401        self.execute.validate_script_source()?;
2402        // Fail CLOSED on an unrecognised execution tier. `#[serde(other)]`
2403        // turns a typo (`tier: controler`) or a future tier into
2404        // `Tier::Unknown`; without this check the controller gate would
2405        // fall back to normal endpoint dispatch, so an operator who *meant*
2406        // to confine a job to the controller tier would silently get
2407        // fleet-wide dispatch (CodeRabbit #905). Rejecting it at the write
2408        // boundary surfaces the typo at `job create`, and — since
2409        // `exec_manifest` re-validates — a hand-poked KV manifest can't slip
2410        // a controller-tier job onto endpoints either.
2411        if matches!(self.tier, Some(Tier::Unknown)) {
2412            return Err(
2413                "tier: unrecognised execution tier — use `endpoint` or `controller` \
2414                 (this is a typo, or a tier a newer kanade supports that this backend does not)"
2415                    .to_string(),
2416            );
2417        }
2418        // #vuln-roadmap: a `feed:` spec drives the global `feeds`
2419        // projection. id / item_id are stored as *values* (the `feeds`
2420        // table is fixed-schema — no identifier splicing), but blank
2421        // values are silent projection bugs: a blank id collides every
2422        // feed under "", a blank field never matches the payload array,
2423        // and an empty primary_key yields no item_id (every row dropped).
2424        // Reject them at the write boundary so `kanade job create` surfaces
2425        // the typo instead of producing an empty/garbled feed at run time.
2426        let mut seen_feed_ids: Vec<&str> = Vec::new();
2427        for spec in &self.feed {
2428            let id = spec.id.trim();
2429            if id.is_empty() {
2430                return Err("feed.id must not be empty".to_string());
2431            }
2432            if spec.field.trim().is_empty() {
2433                return Err(format!("feed '{id}' field must not be empty"));
2434            }
2435            if spec.primary_key.is_empty() {
2436                return Err(format!("feed '{id}' needs at least one primary_key field"));
2437            }
2438            if spec.primary_key.iter().any(|k| k.trim().is_empty()) {
2439                return Err(format!(
2440                    "feed '{id}' primary_key must not contain blank entries"
2441                ));
2442            }
2443            // Two specs sharing an id both target the same `feeds`
2444            // partition and would clobber each other on every run —
2445            // reject the ambiguity rather than let last-write-wins.
2446            if seen_feed_ids.contains(&id) {
2447                return Err(format!("feed id '{id}' is declared more than once"));
2448            }
2449            seen_feed_ids.push(id);
2450        }
2451        // A `feed:` job fetches external data and MUST run on the trusted
2452        // controller tier — the dispatch guard (`requires_controller`) treats
2453        // a non-empty `feed:` as implying `controller`. An explicit
2454        // `tier: endpoint` contradicts that intent; reject it rather than
2455        // silently overriding, so the operator can't believe a feed runs on
2456        // endpoints. Omitting `tier:` (the default) is fine — the implication
2457        // confines it; `tier: controller` is the redundant-but-explicit form.
2458        if !self.feed.is_empty() && matches!(self.tier, Some(Tier::Endpoint)) {
2459            return Err(
2460                "feed: requires the controller tier — remove `tier: endpoint` (a feed: job \
2461                 fetches external data and is confined to the controller_group)"
2462                    .to_string(),
2463            );
2464        }
2465        // A present-but-empty finalize script is an invisible no-op
2466        // (the hook would run an empty body); reject it at the write
2467        // boundary. Inline-only in P1, so `script` is the sole source.
2468        if let Some(finalize) = &self.finalize {
2469            if finalize.script.trim().is_empty() {
2470                return Err("finalize.script must not be empty".to_string());
2471            }
2472            // Reject an unparseable timeout at the write boundary so the
2473            // operator sees the error at `job create` rather than getting
2474            // a silent fire-time fallback (`FinalizeSpec::lower` floors to
2475            // 60s, which would otherwise mask a typo).
2476            if humantime::parse_duration(&finalize.timeout).is_err() {
2477                return Err(format!(
2478                    "finalize.timeout '{}' is not a valid duration",
2479                    finalize.timeout
2480                ));
2481            }
2482            // Disallow cmd for finalize: the agent injects the result JSON
2483            // into the hook's environment, and cmd.exe quoting doesn't
2484            // nest — JSON's `"` plus shell metacharacters in a collected
2485            // path/key could break out into command injection at the
2486            // agent's (often LocalSystem) privilege. PowerShell's
2487            // single-quote escaping is safe, and finalize hooks are
2488            // PowerShell by convention anyway.
2489            if finalize.shell == ExecuteShell::Cmd {
2490                return Err(
2491                    "finalize.shell: cmd is not supported for finalize hooks (shell-injection \
2492                     risk when the result JSON is injected into the environment); use powershell"
2493                        .to_string(),
2494                );
2495            }
2496            // #965: per-bundle finalize only means anything for a
2497            // collect: job — a non-collect finalize has no bundles to
2498            // iterate (it runs once after the script). Reject the
2499            // combination at the write boundary so a confused operator
2500            // is told rather than silently getting a no-op.
2501            if finalize.on_each_bundle && self.collect.is_none() {
2502                return Err(
2503                    "finalize.on_each_bundle: true requires a collect: hint — a non-collect \
2504                     finalize has no bundles to iterate (it runs once after the script)"
2505                        .to_string(),
2506                );
2507            }
2508        }
2509        // Stdout-format compatibility (#821). `inventory:` / `check:` /
2510        // `collect:` now COMPOSE: each reads its own `#KANADE-<KIND>-
2511        // BEGIN/END`-fenced JSON block from stdout, so a single job can
2512        // project inventory facts, drive a Health-tab check, AND collect
2513        // files in one run. (A single-hint job may still skip the fence;
2514        // a multi-hint job must fence each block.)
2515        //
2516        // `emit:` remains the exception — its stdout is line-delimited
2517        // NDJSON consumed whole and then omitted from the result — so it
2518        // can't share stdout with any fenced hint. `feed:` is another fenced
2519        // stdout consumer (`#KANADE-FEED`), so it belongs in this exclusion
2520        // too: with `emit:` present the projector never sees the feed's fence
2521        // (CodeRabbit).
2522        if self.emit.is_some()
2523            && (self.inventory.is_some()
2524                || self.check.is_some()
2525                || self.collect.is_some()
2526                || !self.feed.is_empty())
2527        {
2528            return Err(
2529                "`emit:` is incompatible with `inventory:` / `check:` / `collect:` / `feed:` — \
2530                 emit's stdout is NDJSON timeline events (consumed whole and omitted from the \
2531                 result), while the others read fenced JSON blocks from stdout"
2532                    .to_string(),
2533            );
2534        }
2535        // A check's `name` is the Health-tab row id (React key); the
2536        // field names tell the agent where to read status/detail.
2537        // An empty value is an invisible runtime bug, and the serde
2538        // defaults don't guard an operator who writes `status_field:
2539        // ""` explicitly — reject all three here.
2540        if let Some(check) = &self.check {
2541            for (label, value) in [
2542                ("check.name", &check.name),
2543                ("check.status_field", &check.status_field),
2544                ("check.detail_field", &check.detail_field),
2545            ] {
2546                if value.trim().is_empty() {
2547                    return Err(format!("{label} must not be empty"));
2548                }
2549            }
2550            // A present-but-blank `troubleshoot` is a broken
2551            // remediation job id (the "修復する" button would target
2552            // an empty manifest id) — reject it too.
2553            if let Some(troubleshoot) = &check.troubleshoot {
2554                if troubleshoot.trim().is_empty() {
2555                    return Err("check.troubleshoot must not be empty when set".to_string());
2556                }
2557            }
2558            // A present-but-blank `label` would render an empty row
2559            // title on the Health tab / Compliance page — reject it so
2560            // the slug fallback only ever kicks in when label is absent.
2561            if let Some(label) = &check.label {
2562                if label.trim().is_empty() {
2563                    return Err("check.label must not be empty when set".to_string());
2564                }
2565            }
2566            if let Some(alert) = &check.alert {
2567                // An alert that names no recipient is a silent no-op.
2568                if !alert.notify_user && alert.notify_groups.is_empty() {
2569                    return Err("check.alert must set notify_user and/or notify_groups".to_string());
2570                }
2571                if alert.title.trim().is_empty() {
2572                    return Err("check.alert.title must not be empty".to_string());
2573                }
2574                // `on: []` would never fire; an empty group name resolves to
2575                // a malformed `notifications.group.` subject.
2576                if alert.on.is_empty() {
2577                    return Err("check.alert.on must list at least one status".to_string());
2578                }
2579                if alert.notify_groups.iter().any(|g| g.trim().is_empty()) {
2580                    return Err("check.alert.notify_groups must not contain blanks".to_string());
2581                }
2582                // Email is addressed via group_contacts (group → email), so
2583                // there must be a group to map. notify_user has no email.
2584                if alert.email && alert.notify_groups.is_empty() {
2585                    return Err(
2586                        "check.alert.email requires notify_groups (email is addressed per group, not per user)"
2587                            .to_string(),
2588                    );
2589                }
2590                // The alert rides the `check_status` projection, which only
2591                // runs for `fleet: true`.
2592                if !check.fleet {
2593                    return Err(
2594                        "check.alert requires fleet: true (the alert rides the compliance projection)"
2595                            .to_string(),
2596                    );
2597                }
2598            }
2599        }
2600        // #291: a `client:` job is rendered in the Client App's
2601        // catalog (`jobs.list` → `jobs.execute`). serde already makes
2602        // `name` + `category` required at parse time; the only gap is
2603        // a present-but-blank `name`, which would render an empty row
2604        // title — reject it like the other display-id fields.
2605        if let Some(client) = &self.client {
2606            if client.name.trim().is_empty() {
2607                return Err("client.name must not be empty".to_string());
2608            }
2609            // #792: category is a free-form key now, so a blank one would
2610            // group the job under an empty tab — reject it like `name`.
2611            if client.category.trim().is_empty() {
2612                return Err("client.category must not be empty".to_string());
2613            }
2614            // Optional display fields, when present, must be
2615            // meaningful: a blank `description` renders an empty
2616            // subtitle and a blank `icon` is a dangling lucide name.
2617            // Same present-but-blank guard the `check:` block applies
2618            // to its optional `troubleshoot` id.
2619            for (label, value) in [
2620                ("client.description", &client.description),
2621                ("client.icon", &client.icon),
2622                ("client.category_label", &client.category_label),
2623                ("client.category_icon", &client.category_icon),
2624            ] {
2625                if let Some(v) = value {
2626                    if v.trim().is_empty() {
2627                        return Err(format!("{label} must not be empty when set"));
2628                    }
2629                }
2630            }
2631            // #816: a present-but-empty `visible_to` (no all/groups/pcs)
2632            // would hide the job from everyone in the Client App — almost
2633            // certainly a mistake. Require at least one selector; omit the
2634            // whole block to mean "visible to all".
2635            if let Some(t) = &client.visible_to {
2636                if !t.is_specified() {
2637                    return Err(
2638                        "client.visible_to must set at least one of all / groups / pcs (omit it for all PCs)"
2639                            .to_string(),
2640                    );
2641                }
2642            }
2643            // show_when: a dynamic display gate keyed on a check result. A
2644            // malformed check slug matches nothing and an empty status list
2645            // matches nothing — both would silently hide the job forever,
2646            // so reject them at create time rather than at a confused
2647            // "why isn't my job showing?" later. The slug must be a clean
2648            // resource id (same charset checks/jobs use): a typo with spaces
2649            // or punctuation can never match a real check name, so catch it
2650            // here instead of failing closed at runtime. (Whether the slug
2651            // names a check that actually EXISTS can't be checked here —
2652            // checks are keyed by name across manifests — so a valid-but-
2653            // unknown slug stays a runtime miss = hidden, the documented
2654            // fail-closed behavior.)
2655            if let Some(sw) = &client.show_when {
2656                if !is_valid_resource_id(sw.check.trim()) {
2657                    return Err(
2658                        "client.show_when.check must be a non-empty check slug ([A-Za-z0-9._-])"
2659                            .to_string(),
2660                    );
2661                }
2662                if sw.is.is_empty() {
2663                    return Err(
2664                        "client.show_when.is must list at least one check status".to_string()
2665                    );
2666                }
2667            }
2668            // confirm: a present-but-blank custom message would render an
2669            // empty dialog title — reject it like the other display fields.
2670            // (A `confirm: false` / `enabled: false` with no message is fine:
2671            // the dialog is suppressed, so there's nothing to render.)
2672            if let Some(c) = &client.confirm {
2673                if let Some(msg) = &c.message {
2674                    if msg.trim().is_empty() {
2675                        return Err("client.confirm.message must not be empty when set".to_string());
2676                    }
2677                }
2678            }
2679        }
2680        // #219: a `collect:` job's `name` heads the bundle on the SPA
2681        // Collect page (and the Client App row when paired with
2682        // `client:`), `files_field` tells the agent where to read the
2683        // path list, and `max_size` must be a parseable size so a typo
2684        // is caught at create time rather than silently capping the
2685        // bundle at the default on the fire path.
2686        if let Some(collect) = &self.collect {
2687            if collect.name.trim().is_empty() {
2688                return Err("collect.name must not be empty".to_string());
2689            }
2690            if collect.files_field.trim().is_empty() {
2691                return Err("collect.files_field must not be empty".to_string());
2692            }
2693            if let Some(description) = &collect.description {
2694                if description.trim().is_empty() {
2695                    return Err("collect.description must not be empty when set".to_string());
2696                }
2697            }
2698            if let Some(max_size) = &collect.max_size {
2699                parse_size_bytes(max_size).map_err(|e| format!("collect.max_size: {e}"))?;
2700            }
2701        }
2702        // #720/#743: `aggregate:` is a pure read-spec (it never touches
2703        // stdout and is never sent to an agent), so it composes with every
2704        // other hint. The per-widget rules are shared with the standalone
2705        // `view` resource — see [`validate_aggregate_widgets`].
2706        if let Some(widgets) = &self.aggregate {
2707            validate_aggregate_widgets(widgets, "aggregate")?;
2708        }
2709        // A blank / whitespace-only tag is an invisible operator typo
2710        // that would render an empty filter chip on the Jobs page —
2711        // reject it like the other present-but-blank display fields.
2712        for tag in &self.tags {
2713            if tag.trim().is_empty() {
2714                return Err("tags must not contain empty entries".to_string());
2715            }
2716        }
2717        Ok(())
2718    }
2719}
2720
2721#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
2722#[serde(rename_all = "lowercase")]
2723pub enum ExecuteShell {
2724    Powershell,
2725    Cmd,
2726}
2727
2728impl From<ExecuteShell> for Shell {
2729    fn from(s: ExecuteShell) -> Self {
2730        match s {
2731            ExecuteShell::Powershell => Shell::Powershell,
2732            ExecuteShell::Cmd => Shell::Cmd,
2733        }
2734    }
2735}
2736
2737#[cfg(test)]
2738mod tests {
2739    use super::*;
2740
2741    #[test]
2742    fn inventory_payload_extracts_fenced_block() {
2743        // Readable message + fenced JSON → only the JSON, trimmed.
2744        let stdout = "Wi-Fi 設定を適用しました。\n\
2745            #KANADE-INVENTORY-BEGIN\n\
2746            {\"applied\": true}\n\
2747            #KANADE-INVENTORY-END\n";
2748        assert_eq!(inventory_payload(stdout), "{\"applied\": true}");
2749    }
2750
2751    #[test]
2752    fn inventory_payload_falls_back_to_whole_stdout() {
2753        // No fence (a plain inventory job) → whole stdout, trimmed.
2754        assert_eq!(
2755            inventory_payload("  {\"ram_gb\": 16}\n"),
2756            "{\"ram_gb\": 16}"
2757        );
2758    }
2759
2760    #[test]
2761    fn inventory_payload_handles_unterminated_fence() {
2762        // Closing marker missing (e.g. truncated) → everything after the
2763        // opener, trimmed.
2764        let stdout = "msg\n#KANADE-INVENTORY-BEGIN\n{\"a\": 1}";
2765        assert_eq!(inventory_payload(stdout), "{\"a\": 1}");
2766    }
2767
2768    #[test]
2769    fn inventory_payload_ignores_mid_line_sentinel() {
2770        // The marker echoed mid-line (not at a line start) must NOT be
2771        // treated as a fence — fall back to the whole stdout.
2772        let stdout = "see #KANADE-INVENTORY-BEGIN in the docs\nnot json";
2773        assert_eq!(inventory_payload(stdout), stdout.trim());
2774    }
2775
2776    #[test]
2777    fn fenced_payload_extracts_each_hint_block_independently() {
2778        // #821: one stdout carrying a user message + all three fenced
2779        // blocks — every consumer pulls only its own.
2780        let stdout = "\
2781done!
2782#KANADE-INVENTORY-BEGIN
2783{\"os\":\"win\"}
2784#KANADE-INVENTORY-END
2785#KANADE-CHECK-BEGIN
2786{\"status\":\"ok\"}
2787#KANADE-CHECK-END
2788#KANADE-COLLECT-BEGIN
2789{\"files\":[\"a\"]}
2790#KANADE-COLLECT-END
2791";
2792        assert_eq!(
2793            fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
2794            "{\"os\":\"win\"}"
2795        );
2796        assert_eq!(
2797            fenced_payload(stdout, CHECK_BLOCK_BEGIN, CHECK_BLOCK_END),
2798            "{\"status\":\"ok\"}"
2799        );
2800        assert_eq!(
2801            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2802            "{\"files\":[\"a\"]}"
2803        );
2804    }
2805
2806    #[test]
2807    fn fenced_payload_falls_back_to_whole_stdout_without_fence() {
2808        // A single-hint job needs no fence — the whole (trimmed) stdout is
2809        // the payload.
2810        let stdout = "  {\"files\":[\"a\"]}  ";
2811        assert_eq!(
2812            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2813            "{\"files\":[\"a\"]}"
2814        );
2815    }
2816
2817    #[test]
2818    fn fenced_payload_returns_empty_when_other_fences_present_but_mine_missing() {
2819        // Multi-hint output (inventory + check fenced) but the COLLECT
2820        // fence is missing — collect must NOT fall back to the whole
2821        // stdout (which holds the inventory/check blocks) and cross-parse
2822        // a sibling block; it gets "" → its JSON parse fails → no data.
2823        let stdout = "\
2824#KANADE-INVENTORY-BEGIN
2825{\"os\":\"win\"}
2826#KANADE-INVENTORY-END
2827#KANADE-CHECK-BEGIN
2828{\"status\":\"ok\"}
2829#KANADE-CHECK-END
2830";
2831        assert_eq!(
2832            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2833            ""
2834        );
2835        // ...while the hints that DID fence still extract correctly.
2836        assert_eq!(
2837            fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
2838            "{\"os\":\"win\"}"
2839        );
2840    }
2841
2842    /// The example check-job + schedule YAMLs shipped under `configs/`
2843    /// must stay valid as the schema evolves (#290 PR-C). `include_str!`
2844    /// pins them at compile time so a breaking edit fails `cargo test`
2845    /// rather than only `kanade job create` at deploy time.
2846    #[test]
2847    fn example_check_job_yamls_parse_and_validate() {
2848        let jobs = [
2849            (
2850                "check-bitlocker",
2851                include_str!("../../../configs/jobs/check-bitlocker.yaml"),
2852            ),
2853            (
2854                "check-av-signature",
2855                include_str!("../../../configs/jobs/check-av-signature.yaml"),
2856            ),
2857            (
2858                "check-cert-expiry",
2859                include_str!("../../../configs/jobs/check-cert-expiry.yaml"),
2860            ),
2861            (
2862                "check-disk-space",
2863                include_str!("../../../configs/jobs/check-disk-space.yaml"),
2864            ),
2865            (
2866                "check-pending-reboot",
2867                include_str!("../../../configs/jobs/check-pending-reboot.yaml"),
2868            ),
2869            (
2870                "check-defender-rtp",
2871                include_str!("../../../configs/jobs/check-defender-rtp.yaml"),
2872            ),
2873            (
2874                "check-firewall",
2875                include_str!("../../../configs/jobs/check-firewall.yaml"),
2876            ),
2877        ];
2878        for (name, yaml) in jobs {
2879            let m: Manifest =
2880                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} parse: {e}"));
2881            m.validate()
2882                .unwrap_or_else(|e| panic!("{name} validate: {e}"));
2883            let check = m
2884                .check
2885                .as_ref()
2886                .unwrap_or_else(|| panic!("{name} must carry a check: hint"));
2887            assert!(!check.name.trim().is_empty(), "{name} check.name empty");
2888            // These examples all read admin-only WMI / registry / netsh
2889            // state, so they run_as system. NOTE: that's a property of
2890            // these particular checks, NOT of the `check:` contract — a
2891            // check probing user-session state could run_as user.
2892            assert_eq!(
2893                m.execute.run_as,
2894                RunAs::System,
2895                "{name} should run_as system"
2896            );
2897        }
2898    }
2899
2900    /// The example user-invokable job YAMLs (#291) shipped under
2901    /// `configs/jobs/` must stay valid as the `client:` schema
2902    /// evolves. `include_str!` pins them at compile time so a breaking
2903    /// edit fails `cargo test`, not `kanade job create` at deploy.
2904    #[test]
2905    fn example_client_job_yamls_parse_and_validate() {
2906        let jobs = [
2907            (
2908                "fix-teams-cache",
2909                "troubleshoot",
2910                include_str!("../../../configs/jobs/fix-teams-cache.yaml"),
2911            ),
2912            (
2913                "chrome-update",
2914                "software_update",
2915                include_str!("../../../configs/jobs/chrome-update.yaml"),
2916            ),
2917            (
2918                "install-slack",
2919                "catalog",
2920                include_str!("../../../configs/jobs/install-slack.yaml"),
2921            ),
2922            (
2923                "fix-defender-rtp",
2924                "troubleshoot",
2925                include_str!("../../../configs/jobs/fix-defender-rtp.yaml"),
2926            ),
2927            // #792 custom category ("settings") + #809 message/inventory.
2928            (
2929                "example-power-plan",
2930                "settings",
2931                include_str!("../../../configs/jobs/example-power-plan.yaml"),
2932            ),
2933            // #792: diagnostics moved to its own "support" tab.
2934            (
2935                "collect-diagnostics",
2936                "support",
2937                include_str!("../../../configs/jobs/collect-diagnostics.yaml"),
2938            ),
2939        ];
2940        for (id, category, yaml) in jobs {
2941            let m: Manifest =
2942                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
2943            m.validate()
2944                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
2945            assert_eq!(m.id, id, "{id} id mismatch");
2946            let client = m
2947                .client
2948                .as_ref()
2949                .unwrap_or_else(|| panic!("{id} must carry a client: block"));
2950            assert!(!client.name.trim().is_empty(), "{id} client.name empty");
2951            assert_eq!(client.category, category, "{id} category");
2952        }
2953    }
2954
2955    /// #219: the shipped `collect:` example must stay valid as the
2956    /// schema evolves. `include_str!` pins it at compile time so a
2957    /// breaking edit (or a YAML typo in the PowerShell block) fails
2958    /// `cargo test` rather than `kanade job create` at deploy. It carries
2959    /// both `collect:` and `client:` (end-user-triggerable), which must
2960    /// compose.
2961    #[test]
2962    fn example_collect_job_yaml_parses_and_validates() {
2963        let yaml = include_str!("../../../configs/jobs/collect-diagnostics.yaml");
2964        let m: Manifest = serde_yaml::from_str(yaml).expect("collect-diagnostics parse");
2965        m.validate().expect("collect-diagnostics validate");
2966        assert_eq!(m.id, "collect-diagnostics");
2967        let collect = m.collect.as_ref().expect("collect: block present");
2968        assert!(!collect.name.trim().is_empty());
2969        assert_eq!(collect.files_field, "files");
2970        assert_eq!(collect.max_size_bytes(), 50_000_000);
2971        // collect + client compose — the Client App can trigger it.
2972        assert!(
2973            m.client.is_some(),
2974            "collect-diagnostics also carries client:"
2975        );
2976    }
2977
2978    /// The `emit: { type: events }` collector jobs under
2979    /// `configs/jobs/` feed the obs_events timeline. `include_str!`
2980    /// pins them at compile time so a breaking edit (e.g. an `emit:`
2981    /// paired with `check:`/`inventory:`, a bad watermark field, or a
2982    /// YAML typo in the PowerShell block) fails `cargo test` rather
2983    /// than `kanade job create` at deploy. Every one must carry an
2984    /// `emit.type=events` block and NO check/inventory (validate()
2985    /// rejects the pairing).
2986    #[test]
2987    fn example_event_collector_job_yamls_parse_and_validate() {
2988        let jobs = [
2989            // collect-winlog-events was retired in #841 PR2 — the scheduled
2990            // human-session / power timeline is now read natively by the
2991            // agent (kanade-agent `winlog` module via EvtQuery), no
2992            // PowerShell job. collect-winlog-logons-all stays as the
2993            // on-demand forensic all-token-logons companion.
2994            (
2995                "collect-winlog-logons-all",
2996                include_str!("../../../configs/jobs/collect-winlog-logons-all.yaml"),
2997            ),
2998            (
2999                "collect-wlan-events",
3000                include_str!("../../../configs/jobs/collect-wlan-events.yaml"),
3001            ),
3002        ];
3003        for (id, yaml) in jobs {
3004            // Strict parse so an unknown-key typo in these fixtures fails
3005            // here (not silently at deploy) — the runtime Manifest is
3006            // unknown-key-tolerant, so the lenient serde_yaml::from_str
3007            // wouldn't catch fixture drift (CodeRabbit #689).
3008            let m: Manifest =
3009                crate::strict::from_yaml_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
3010            m.validate()
3011                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
3012            assert_eq!(m.id, id, "{id} id mismatch");
3013            let emit = m
3014                .emit
3015                .as_ref()
3016                .unwrap_or_else(|| panic!("{id} must carry an emit: block"));
3017            assert_eq!(emit.kind, EmitKind::Events, "{id} emit.type");
3018            assert!(
3019                m.check.is_none() && m.inventory.is_none(),
3020                "{id}: emit jobs must not pair with check/inventory"
3021            );
3022        }
3023    }
3024
3025    /// The `inventory:` snapshot jobs under `configs/jobs/` project
3026    /// facts into `inventory_facts` + exploded tables. `include_str!`
3027    /// pins them at compile time so a breaking edit (bad explode
3028    /// schema, a YAML typo in the PowerShell block, an `inventory:`
3029    /// accidentally paired with `emit:`) fails `cargo test` rather
3030    /// than the projector at deploy. Each must carry an `inventory:`
3031    /// block and NO emit (validate() rejects the pairing).
3032    #[test]
3033    fn example_inventory_job_yamls_parse_and_validate() {
3034        let jobs = [
3035            (
3036                "inventory-hw",
3037                include_str!("../../../configs/jobs/inventory-hw.yaml"),
3038            ),
3039            (
3040                "inventory-sw",
3041                include_str!("../../../configs/jobs/inventory-sw.yaml"),
3042            ),
3043            (
3044                "inventory-driver",
3045                include_str!("../../../configs/jobs/inventory-driver.yaml"),
3046            ),
3047        ];
3048        for (id, yaml) in jobs {
3049            let m: Manifest =
3050                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
3051            m.validate()
3052                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
3053            assert_eq!(m.id, id, "{id} id mismatch");
3054            assert!(m.inventory.is_some(), "{id} must carry an inventory: block");
3055            assert!(m.emit.is_none(), "{id}: inventory jobs must not set emit:");
3056        }
3057    }
3058
3059    #[test]
3060    fn example_check_schedule_yamls_parse_and_validate() {
3061        let schedules = [
3062            (
3063                "check-bitlocker",
3064                include_str!("../../../configs/schedules/check-bitlocker.yaml"),
3065            ),
3066            (
3067                "check-av-signature",
3068                include_str!("../../../configs/schedules/check-av-signature.yaml"),
3069            ),
3070            (
3071                "check-cert-expiry",
3072                include_str!("../../../configs/schedules/check-cert-expiry.yaml"),
3073            ),
3074            (
3075                "check-disk-space",
3076                include_str!("../../../configs/schedules/check-disk-space.yaml"),
3077            ),
3078            (
3079                "check-pending-reboot",
3080                include_str!("../../../configs/schedules/check-pending-reboot.yaml"),
3081            ),
3082            (
3083                "check-defender-rtp",
3084                include_str!("../../../configs/schedules/check-defender-rtp.yaml"),
3085            ),
3086            (
3087                "check-firewall",
3088                include_str!("../../../configs/schedules/check-firewall.yaml"),
3089            ),
3090        ];
3091        for (name, yaml) in schedules {
3092            let s: Schedule =
3093                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
3094            s.validate()
3095                .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
3096            assert_eq!(s.job_id, name, "{name} schedule must reference its job");
3097        }
3098    }
3099
3100    /// Inventory schedule wrappers (`per_pc` cadence) must stay valid
3101    /// alongside the schedule schema. `include_str!` pins them so a
3102    /// breaking edit fails `cargo test`, not `kanade schedule create`.
3103    #[test]
3104    fn example_inventory_schedule_yamls_parse_and_validate() {
3105        let schedules = [
3106            (
3107                "inventory-hw",
3108                include_str!("../../../configs/schedules/inventory-hw.yaml"),
3109            ),
3110            (
3111                "inventory-sw",
3112                include_str!("../../../configs/schedules/inventory-sw.yaml"),
3113            ),
3114            (
3115                "inventory-driver",
3116                include_str!("../../../configs/schedules/inventory-driver.yaml"),
3117            ),
3118        ];
3119        for (name, yaml) in schedules {
3120            let s: Schedule =
3121                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
3122            s.validate()
3123                .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
3124            assert_eq!(s.job_id, name, "{name} schedule must reference its job");
3125        }
3126    }
3127
3128    #[test]
3129    fn target_is_specified_requires_at_least_one_field() {
3130        let empty = Target::default();
3131        assert!(!empty.is_specified());
3132
3133        let with_all = Target {
3134            all: true,
3135            ..Target::default()
3136        };
3137        assert!(with_all.is_specified());
3138
3139        let with_groups = Target {
3140            groups: vec!["canary".into()],
3141            ..Target::default()
3142        };
3143        assert!(with_groups.is_specified());
3144
3145        let with_pcs = Target {
3146            pcs: vec!["pc-01".into()],
3147            ..Target::default()
3148        };
3149        assert!(with_pcs.is_specified());
3150    }
3151
3152    #[test]
3153    fn manifest_deserialises_minimal_yaml() {
3154        // Matches jobs/echo-test.yaml. v0.18: no target/rollout/jitter
3155        // — those live on the schedule / exec request now.
3156        let yaml = r#"
3157id: echo-test
3158version: 0.0.1
3159execute:
3160  shell: powershell
3161  script: "echo 'kanade'"
3162  timeout: 30s
3163"#;
3164        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3165        assert_eq!(m.id, "echo-test");
3166        assert_eq!(m.version, "0.0.1");
3167        assert!(matches!(m.execute.shell, ExecuteShell::Powershell));
3168        assert_eq!(
3169            m.execute.script.as_deref().map(str::trim),
3170            Some("echo 'kanade'")
3171        );
3172        assert!(m.execute.script_file.is_none());
3173        assert!(m.execute.script_object.is_none());
3174        assert_eq!(m.execute.timeout, "30s");
3175        assert!(!m.require_approval);
3176        m.validate()
3177            .expect("inline-script manifest passes validation");
3178    }
3179
3180    #[test]
3181    fn manifest_parses_check_job_and_validates() {
3182        // An operator-defined health check (#290): a `check:` hint +
3183        // a PowerShell script that prints {status, detail}.
3184        let yaml = r#"
3185id: check-bitlocker
3186version: 0.1.0
3187execute:
3188  shell: powershell
3189  run_as: system
3190  timeout: 15s
3191  script: |
3192    [pscustomobject]@{ status = 'ok'; detail = 'all volumes protected' } | ConvertTo-Json -Compress
3193check:
3194  name: bitlocker
3195  troubleshoot: fix-bitlocker
3196"#;
3197        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3198        let check = m.check.as_ref().expect("check hint present");
3199        assert_eq!(check.name, "bitlocker");
3200        assert_eq!(check.troubleshoot.as_deref(), Some("fix-bitlocker"));
3201        // Field names default to the conventional "status" / "detail".
3202        assert_eq!(check.status_field, "status");
3203        assert_eq!(check.detail_field, "detail");
3204        assert!(m.inventory.is_none() && m.emit.is_none());
3205        m.validate().expect("check-only manifest passes validation");
3206    }
3207
3208    #[test]
3209    fn manifest_check_defaults_and_custom_fields() {
3210        // Minimal: only `name`; status/detail fields default.
3211        let m: Manifest = serde_yaml::from_str(
3212            r#"
3213id: check-disk
3214version: 0.1.0
3215execute:
3216  shell: powershell
3217  script: "[pscustomobject]@{ status = 'ok' } | ConvertTo-Json -Compress"
3218  timeout: 10s
3219check:
3220  name: disk_free
3221"#,
3222        )
3223        .expect("parse");
3224        let c = m.check.as_ref().unwrap();
3225        assert_eq!(c.name, "disk_free");
3226        assert_eq!(c.status_field, "status");
3227        assert_eq!(c.detail_field, "detail");
3228        assert!(c.troubleshoot.is_none());
3229        m.validate().expect("validates");
3230
3231        // The operator can point status/detail at any field of their
3232        // free-form inventory object.
3233        let m2: Manifest = serde_yaml::from_str(
3234            r#"
3235id: check-custom
3236version: 0.1.0
3237execute:
3238  shell: powershell
3239  script: "echo x"
3240  timeout: 10s
3241check:
3242  name: patch_level
3243  status_field: compliance
3244  detail_field: summary
3245"#,
3246        )
3247        .expect("parse");
3248        let c2 = m2.check.as_ref().unwrap();
3249        assert_eq!(c2.status_field, "compliance");
3250        assert_eq!(c2.detail_field, "summary");
3251    }
3252
3253    #[test]
3254    fn manifest_allows_check_composed_with_inventory() {
3255        // `check:` + `inventory:` COMPOSE on the same stdout object:
3256        // status/detail → Health tab, the rest → SPA projection +
3257        // explode sub-tables. Must pass validation.
3258        let yaml = r#"
3259id: check-bitlocker-detailed
3260version: 0.1.0
3261execute:
3262  shell: powershell
3263  script: "echo x"
3264  timeout: 10s
3265check:
3266  name: bitlocker
3267inventory:
3268  display:
3269    - { field: status, label: Status }
3270"#;
3271        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3272        assert!(m.check.is_some() && m.inventory.is_some());
3273        m.validate().expect("check + inventory compose");
3274    }
3275
3276    #[test]
3277    fn manifest_parses_collect_job_and_validates() {
3278        // #219: a `collect:` hint + a script that lists files on stdout.
3279        let yaml = r#"
3280id: collect-diagnostics
3281version: 0.1.0
3282execute:
3283  shell: powershell
3284  run_as: system
3285  timeout: 120s
3286  script: |
3287    @{ files = @("$env:KANADE_COLLECT_DIR/system.csv") } | ConvertTo-Json
3288collect:
3289  name: "Full diagnostics"
3290  description: "Event logs + process"
3291  max_size: 50MB
3292"#;
3293        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3294        let c = m.collect.as_ref().expect("collect hint present");
3295        assert_eq!(c.name, "Full diagnostics");
3296        assert_eq!(c.files_field, "files"); // default
3297        assert_eq!(c.max_size_bytes(), 50_000_000);
3298        m.validate().expect("collect-only manifest validates");
3299    }
3300
3301    #[test]
3302    fn manifest_finalize_powershell_validates_and_lowers() {
3303        let yaml = r#"
3304id: collect-fin
3305version: 0.1.0
3306execute:
3307  shell: powershell
3308  timeout: 120s
3309  script: |
3310    @{ files = @() } | ConvertTo-Json
3311collect:
3312  name: "diag"
3313  max_size: 50MB
3314finalize:
3315  shell: powershell
3316  timeout: 30s
3317  run_as: system
3318  script: |
3319    Write-Output "cleanup"
3320"#;
3321        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3322        m.validate().expect("powershell finalize validates");
3323        let lowered = m.finalize.as_ref().expect("finalize present").lower();
3324        assert_eq!(lowered.timeout_secs, 30);
3325        assert!(matches!(lowered.shell, Shell::Powershell));
3326        // #965: default is the one-call-after-all contract.
3327        assert!(!lowered.on_each_bundle);
3328    }
3329
3330    #[test]
3331    fn manifest_finalize_on_each_bundle_validates_with_collect_and_lowers() {
3332        // #965: on_each_bundle + a collect hint is the intended
3333        // combination — validates, and the flag survives lowering.
3334        let yaml = r#"
3335id: collect-fin-each
3336version: 0.1.0
3337execute:
3338  shell: powershell
3339  timeout: 120s
3340  script: |
3341    @{ files = @() } | ConvertTo-Json
3342collect:
3343  name: "diag"
3344  max_size: 50MB
3345finalize:
3346  shell: powershell
3347  on_each_bundle: true
3348  script: |
3349    Write-Output "cleanup"
3350"#;
3351        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3352        m.validate().expect("on_each_bundle + collect validates");
3353        let lowered = m.finalize.as_ref().expect("finalize present").lower();
3354        assert!(lowered.on_each_bundle, "flag survives lowering");
3355    }
3356
3357    #[test]
3358    fn manifest_finalize_on_each_bundle_without_collect_rejected() {
3359        // #965: a non-collect finalize has no bundles to iterate, so
3360        // on_each_bundle is a no-op — reject it at the write boundary so
3361        // the operator is told rather than silently getting nothing.
3362        let yaml = r#"
3363id: fin-each-no-collect
3364version: 0.1.0
3365execute:
3366  shell: powershell
3367  timeout: 120s
3368  script: |
3369    Write-Output "hi"
3370finalize:
3371  shell: powershell
3372  on_each_bundle: true
3373  script: |
3374    Write-Output "cleanup"
3375"#;
3376        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3377        let err = m
3378            .validate()
3379            .expect_err("on_each_bundle without collect rejected");
3380        assert!(err.contains("on_each_bundle"), "got: {err}");
3381        assert!(err.contains("collect"), "got: {err}");
3382    }
3383
3384    #[test]
3385    fn manifest_finalize_rejects_cmd_shell() {
3386        // cmd finalize is an injection risk (the agent injects JSON into
3387        // the hook's env; cmd.exe quoting doesn't nest) — validate must
3388        // reject it.
3389        let yaml = r#"
3390id: collect-fin-cmd
3391version: 0.1.0
3392execute:
3393  shell: powershell
3394  timeout: 120s
3395  script: |
3396    @{ files = @() } | ConvertTo-Json
3397finalize:
3398  shell: cmd
3399  script: |
3400    echo hi
3401"#;
3402        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3403        let err = m.validate().expect_err("cmd finalize rejected");
3404        assert!(err.contains("finalize.shell"), "got: {err}");
3405    }
3406
3407    #[test]
3408    fn manifest_finalize_rejects_empty_script() {
3409        let yaml = r#"
3410id: collect-fin-empty
3411version: 0.1.0
3412execute:
3413  shell: powershell
3414  timeout: 120s
3415  script: |
3416    @{ files = @() } | ConvertTo-Json
3417finalize:
3418  shell: powershell
3419  script: "   "
3420"#;
3421        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3422        let err = m.validate().expect_err("empty finalize script rejected");
3423        assert!(err.contains("finalize.script"), "got: {err}");
3424    }
3425
3426    #[test]
3427    fn manifest_collect_max_size_defaults_when_unset() {
3428        let m: Manifest = serde_yaml::from_str(
3429            r#"
3430id: collect-min
3431version: 0.1.0
3432execute:
3433  shell: powershell
3434  script: "echo x"
3435  timeout: 10s
3436collect:
3437  name: minimal
3438"#,
3439        )
3440        .expect("parse");
3441        let c = m.collect.as_ref().unwrap();
3442        assert!(c.max_size.is_none());
3443        assert_eq!(c.max_size_bytes(), DEFAULT_COLLECT_MAX_SIZE);
3444        m.validate().expect("validates");
3445    }
3446
3447    #[test]
3448    fn manifest_allows_collect_with_client() {
3449        // collect composes with client (client doesn't touch stdout):
3450        // an end user can trigger a collection from the Client App.
3451        let yaml = r#"
3452id: collect-diag-client
3453version: 0.1.0
3454execute:
3455  shell: powershell
3456  script: "echo x"
3457  timeout: 10s
3458collect:
3459  name: diagnostics
3460client:
3461  name: "Send diagnostics"
3462  category: troubleshoot
3463"#;
3464        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3465        assert!(m.collect.is_some() && m.client.is_some());
3466        m.validate().expect("collect + client compose");
3467    }
3468
3469    #[test]
3470    fn manifest_allows_inventory_check_collect_coexistence() {
3471        // #821: the three fenced hints now COMPOSE — each reads its own
3472        // `#KANADE-<KIND>` stdout block, so one job can do all three.
3473        let yaml = r#"
3474id: multi-hint
3475version: 0.1.0
3476execute:
3477  shell: powershell
3478  script: "echo x"
3479  timeout: 10s
3480inventory:
3481  display:
3482    - { field: status, label: Status }
3483check:
3484  name: health
3485collect:
3486  name: diag
3487"#;
3488        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3489        m.validate()
3490            .expect("inventory + check + collect coexist after #821");
3491    }
3492
3493    #[test]
3494    fn manifest_rejects_emit_combined_with_fenced_hints() {
3495        // `emit:` consumes stdout as NDJSON (and blanks it), so it still
3496        // can't share with any fenced hint — inventory, check, OR collect.
3497        for extra in [
3498            "inventory:\n  display:\n    - { field: s, label: S }\n",
3499            "check:\n  name: health\n",
3500            "collect:\n  name: diag\n",
3501        ] {
3502            let yaml = format!(
3503                "id: bad-emit-mix\nversion: 0.1.0\nexecute:\n  shell: powershell\n  \
3504                 script: \"echo x\"\n  timeout: 10s\nemit:\n  type: events\n{extra}"
3505            );
3506            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
3507            let err = m
3508                .validate()
3509                .expect_err("emit + fenced hint must be rejected");
3510            assert!(err.contains("emit"), "error mentions emit: {err}");
3511        }
3512    }
3513
3514    #[test]
3515    fn manifest_rejects_collect_empty_name_and_bad_size() {
3516        let empty_name: Manifest = serde_yaml::from_str(
3517            r#"
3518id: c
3519version: 0.1.0
3520execute: { shell: powershell, script: "echo x", timeout: 10s }
3521collect: { name: "  " }
3522"#,
3523        )
3524        .expect("parse");
3525        assert!(
3526            empty_name.validate().is_err(),
3527            "blank collect.name rejected"
3528        );
3529
3530        let bad_size: Manifest = serde_yaml::from_str(
3531            r#"
3532id: c
3533version: 0.1.0
3534execute: { shell: powershell, script: "echo x", timeout: 10s }
3535collect: { name: diag, max_size: "50 quux" }
3536"#,
3537        )
3538        .expect("parse");
3539        let err = bad_size.validate().expect_err("bad max_size rejected");
3540        assert!(err.contains("max_size"), "error mentions max_size: {err}");
3541    }
3542
3543    #[test]
3544    fn parse_size_bytes_units() {
3545        assert_eq!(parse_size_bytes("1024").unwrap(), 1024);
3546        assert_eq!(parse_size_bytes("1B").unwrap(), 1);
3547        assert_eq!(parse_size_bytes("50MB").unwrap(), 50_000_000);
3548        assert_eq!(parse_size_bytes("500 KB").unwrap(), 500_000);
3549        assert_eq!(parse_size_bytes("1GiB").unwrap(), 1024 * 1024 * 1024);
3550        assert_eq!(parse_size_bytes("2mib").unwrap(), 2 * 1024 * 1024);
3551        assert!(parse_size_bytes("").is_err());
3552        assert!(parse_size_bytes("MB").is_err());
3553        assert!(parse_size_bytes("12 zonks").is_err());
3554    }
3555
3556    #[test]
3557    fn manifest_rejects_check_combined_with_emit() {
3558        // `emit:` stdout is NDJSON (and omitted from the result), so
3559        // it can't pair with `check:` (which needs a single JSON
3560        // object on stdout).
3561        let yaml = r#"
3562id: bad-mix
3563version: 0.1.0
3564execute:
3565  shell: powershell
3566  script: "echo x"
3567  timeout: 10s
3568check:
3569  name: bitlocker
3570emit:
3571  type: events
3572"#;
3573        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3574        let err = m.validate().expect_err("emit + check must fail");
3575        assert!(err.contains("incompatible"), "err: {err}");
3576    }
3577
3578    #[test]
3579    fn manifest_rejects_emit_combined_with_inventory() {
3580        // The other half of the emit-incompatibility condition.
3581        let yaml = r#"
3582id: bad-mix-2
3583version: 0.1.0
3584execute:
3585  shell: powershell
3586  script: "echo x"
3587  timeout: 10s
3588emit:
3589  type: events
3590inventory:
3591  display:
3592    - { field: status, label: Status }
3593"#;
3594        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3595        let err = m.validate().expect_err("emit + inventory must fail");
3596        assert!(err.contains("incompatible"), "err: {err}");
3597    }
3598
3599    #[test]
3600    fn manifest_rejects_empty_check_field_names() {
3601        // Empty name / status_field / detail_field are invisible
3602        // runtime bugs (empty React key, agent reads the wrong field)
3603        // — reject them even though serde supplies non-empty defaults.
3604        let base = |inner: &str| {
3605            format!(
3606                "id: c\nversion: 0.1.0\nexecute:\n  shell: powershell\n  script: \"echo x\"\n  timeout: 10s\ncheck:\n{inner}"
3607            )
3608        };
3609        for inner in [
3610            "  name: \"\"\n",
3611            "  name: ok\n  status_field: \"\"\n",
3612            "  name: ok\n  detail_field: \"   \"\n",
3613            // present-but-blank troubleshoot → broken remediation id.
3614            "  name: ok\n  troubleshoot: \"  \"\n",
3615        ] {
3616            let m: Manifest = serde_yaml::from_str(&base(inner)).expect("parse");
3617            let err = m.validate().expect_err("empty field must fail");
3618            assert!(err.contains("must not be empty"), "err: {err}");
3619        }
3620    }
3621
3622    #[test]
3623    fn check_alert_decodes_with_defaults_and_validates() {
3624        let yaml = r#"
3625id: c
3626version: 0.1.0
3627execute:
3628  shell: powershell
3629  script: "echo x"
3630  timeout: 10s
3631check:
3632  name: bitlocker
3633  alert:
3634    notify_user: true
3635    title: "BitLocker 未準拠"
3636"#;
3637        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3638        m.validate().expect("valid alert");
3639        let alert = m.check.unwrap().alert.unwrap();
3640        // Defaults: on = [fail], priority = warn, body = None.
3641        assert_eq!(alert.on, vec![CheckAlertStatus::Fail]);
3642        assert_eq!(
3643            alert.priority,
3644            crate::ipc::notifications::NotificationPriority::Warn
3645        );
3646        assert!(alert.body.is_none());
3647        assert!(alert.notify_user);
3648    }
3649
3650    #[test]
3651    fn check_alert_validation_rejects_bad_configs() {
3652        let base = |alert: &str| {
3653            format!(
3654                "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}"
3655            )
3656        };
3657        let cases = [
3658            // No recipient.
3659            ("    title: t\n", "notify_user and/or notify_groups"),
3660            // Empty title.
3661            (
3662                "    notify_user: true\n    title: \"  \"\n",
3663                "title must not be empty",
3664            ),
3665            // Empty `on`.
3666            (
3667                "    notify_user: true\n    title: t\n    on: []\n",
3668                "on must list at least one status",
3669            ),
3670            // Blank group name.
3671            (
3672                "    notify_groups: [\"  \"]\n    title: t\n",
3673                "notify_groups must not contain blanks",
3674            ),
3675            // alert requires fleet: true.
3676            (
3677                "    notify_user: true\n    title: t\n  fleet: false\n",
3678                "requires fleet: true",
3679            ),
3680            // email opt-in without a group to address.
3681            (
3682                "    notify_user: true\n    email: true\n    title: t\n",
3683                "email requires notify_groups",
3684            ),
3685        ];
3686        for (alert, want) in cases {
3687            let m: Manifest = serde_yaml::from_str(&base(alert)).expect("parse");
3688            let err = m.validate().expect_err("bad alert must fail");
3689            assert!(err.contains(want), "for {alert:?}: got {err}");
3690        }
3691    }
3692
3693    #[test]
3694    fn manifest_client_absent_by_default() {
3695        // A plain operator job (the overwhelming majority) carries no
3696        // `client:` block, so it never surfaces in the end-user
3697        // catalog.
3698        let yaml = r#"
3699id: echo-test
3700version: 0.0.1
3701execute:
3702  shell: powershell
3703  script: "echo 'kanade'"
3704  timeout: 30s
3705"#;
3706        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3707        assert!(m.client.is_none());
3708        m.validate().expect("operator-only job validates");
3709    }
3710
3711    #[test]
3712    fn manifest_client_parses_and_validates() {
3713        // The Client App "困ったとき" remediation job shape: a
3714        // user-invokable troubleshoot job with the end-user fields the
3715        // KLP `jobs.list` wire needs, grouped under `client:`.
3716        let yaml = r#"
3717id: fix-teams-cache
3718version: 1.0.0
3719execute:
3720  shell: powershell
3721  script: "echo clearing"
3722  timeout: 60s
3723client:
3724  name: "Teams のキャッシュをクリア"
3725  description: "Teams が重いときに試してください"
3726  category: troubleshoot
3727  icon: brush-cleaning
3728"#;
3729        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3730        let c = m.client.as_ref().expect("client block present");
3731        assert_eq!(c.name, "Teams のキャッシュをクリア");
3732        assert_eq!(
3733            c.description.as_deref(),
3734            Some("Teams が重いときに試してください")
3735        );
3736        assert_eq!(c.category, "troubleshoot");
3737        assert_eq!(c.icon.as_deref(), Some("brush-cleaning"));
3738        m.validate().expect("user-invokable job validates");
3739    }
3740
3741    #[test]
3742    fn manifest_client_minimal_only_name_and_category() {
3743        // description + icon are optional; name + category are the
3744        // serde-required minimum.
3745        let yaml = r#"
3746id: install-slack
3747version: 1.0.0
3748execute:
3749  shell: powershell
3750  script: "echo install"
3751  timeout: 600s
3752client:
3753  name: Slack
3754  category: catalog
3755"#;
3756        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3757        let c = m.client.as_ref().expect("client present");
3758        assert_eq!(c.category, "catalog");
3759        assert!(c.description.is_none() && c.icon.is_none());
3760        m.validate().expect("minimal client validates");
3761    }
3762
3763    #[test]
3764    fn manifest_client_rejects_blank_name() {
3765        // serde guarantees `name`/`category` are present; the one gap
3766        // is a present-but-blank name → empty catalog row title.
3767        let yaml = r#"
3768id: j
3769version: 1.0.0
3770execute:
3771  shell: powershell
3772  script: "echo x"
3773  timeout: 30s
3774client:
3775  name: "   "
3776  category: catalog
3777"#;
3778        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3779        let err = m.validate().expect_err("blank name must fail");
3780        assert!(err.contains("client.name"), "err: {err}");
3781    }
3782
3783    #[test]
3784    fn manifest_client_rejects_blank_optional_fields() {
3785        // description / icon are optional, but a present-but-blank
3786        // value is a bug (empty subtitle / dangling icon name) — reject
3787        // it, mirroring the check: block's troubleshoot guard.
3788        for (field, line) in [
3789            ("client.description", "  description: \"  \"\n"),
3790            ("client.icon", "  icon: \"\"\n"),
3791            // #792: the new category tab-metadata fields get the same
3792            // present-but-blank guard.
3793            ("client.category_label", "  category_label: \"  \"\n"),
3794            ("client.category_icon", "  category_icon: \"\"\n"),
3795        ] {
3796            let yaml = format!(
3797                "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}"
3798            );
3799            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
3800            let err = m.validate().expect_err("blank optional field must fail");
3801            assert!(err.contains(field), "expected {field} in err: {err}");
3802        }
3803    }
3804
3805    #[test]
3806    fn manifest_client_rejects_blank_category() {
3807        // #792: category is a free-form key now; serde keeps it required,
3808        // but a present-but-blank value would group the job under an empty
3809        // tab — validate() must reject it.
3810        let yaml = r#"
3811id: j
3812version: 1.0.0
3813execute:
3814  shell: powershell
3815  script: "echo x"
3816  timeout: 30s
3817client:
3818  name: "A job"
3819  category: "   "
3820"#;
3821        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3822        let err = m.validate().expect_err("blank category must fail");
3823        assert!(err.contains("client.category"), "err: {err}");
3824    }
3825
3826    #[test]
3827    fn target_matches_pc_group_and_all() {
3828        // #816: pc match, group match, all, and the no-match case.
3829        let by_pc = Target {
3830            pcs: vec!["PC1".into()],
3831            ..Default::default()
3832        };
3833        assert!(by_pc.matches("PC1", &[]));
3834        assert!(!by_pc.matches("PC2", &["g1".into()]));
3835
3836        let by_group = Target {
3837            groups: vec!["g1".into()],
3838            ..Default::default()
3839        };
3840        assert!(by_group.matches("PC2", &["g1".into()]));
3841        assert!(!by_group.matches("PC2", &["g2".into()]));
3842
3843        let all = Target {
3844            all: true,
3845            ..Default::default()
3846        };
3847        assert!(all.matches("anyPC", &[]));
3848    }
3849
3850    #[test]
3851    fn manifest_client_rejects_empty_visible_to() {
3852        // #816: a present-but-empty visible_to (no all/groups/pcs) would
3853        // hide the job from everyone — validate() must reject it.
3854        let yaml = r#"
3855id: j
3856version: 1.0.0
3857execute:
3858  shell: powershell
3859  script: "echo x"
3860  timeout: 30s
3861client:
3862  name: "A job"
3863  category: troubleshoot
3864  visible_to: {}
3865"#;
3866        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3867        let err = m.validate().expect_err("empty visible_to must fail");
3868        assert!(err.contains("client.visible_to"), "err: {err}");
3869    }
3870
3871    #[test]
3872    fn manifest_client_accepts_visible_to_groups() {
3873        let yaml = r#"
3874id: j
3875version: 1.0.0
3876execute:
3877  shell: powershell
3878  script: "echo x"
3879  timeout: 30s
3880client:
3881  name: "A job"
3882  category: settings
3883  visible_to:
3884    groups: [wifi-affected]
3885"#;
3886        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3887        m.validate().expect("visible_to with a group validates");
3888        let vt = m.client.unwrap().visible_to.unwrap();
3889        assert_eq!(vt.groups, vec!["wifi-affected".to_string()]);
3890    }
3891
3892    #[test]
3893    fn manifest_client_show_when_accepts_scalar_and_seq() {
3894        use crate::ipc::state::CheckStatus;
3895        // `is:` accepts a single status (author ergonomics) ...
3896        let scalar = r#"
3897id: office-update
3898version: 1.0.0
3899execute:
3900  shell: powershell
3901  script: "echo x"
3902  timeout: 30s
3903client:
3904  name: "Office を最新に更新"
3905  category: software_update
3906  show_when:
3907    check: office-up-to-date
3908    is: fail
3909"#;
3910        let m: Manifest = serde_yaml::from_str(scalar).expect("parse scalar");
3911        m.validate().expect("scalar show_when validates");
3912        let sw = m.client.unwrap().show_when.unwrap();
3913        assert_eq!(sw.check, "office-up-to-date");
3914        assert_eq!(sw.is, vec![CheckStatus::Fail]);
3915
3916        // ... and a list (e.g. fail-open on a not-yet-run check).
3917        let seq = scalar.replace("is: fail", "is: [fail, unknown]");
3918        let m: Manifest = serde_yaml::from_str(&seq).expect("parse seq");
3919        m.validate().expect("seq show_when validates");
3920        assert_eq!(
3921            m.client.unwrap().show_when.unwrap().is,
3922            vec![CheckStatus::Fail, CheckStatus::Unknown]
3923        );
3924    }
3925
3926    #[test]
3927    fn manifest_client_show_when_rejects_empty() {
3928        // A malformed check slug (here: internal spaces — a typo that could
3929        // never match a real check name) or an empty status list would
3930        // silently hide the job forever — validate() must reject both.
3931        let bad_check = r#"
3932id: j
3933version: 1.0.0
3934execute:
3935  shell: powershell
3936  script: "echo x"
3937  timeout: 30s
3938client:
3939  name: "A job"
3940  category: software_update
3941  show_when:
3942    check: "office up to date"
3943    is: fail
3944"#;
3945        let m: Manifest = serde_yaml::from_str(bad_check).expect("parse");
3946        let err = m.validate().expect_err("malformed check slug must fail");
3947        assert!(err.contains("client.show_when.check"), "err: {err}");
3948
3949        let empty_is = r#"
3950id: j
3951version: 1.0.0
3952execute:
3953  shell: powershell
3954  script: "echo x"
3955  timeout: 30s
3956client:
3957  name: "A job"
3958  category: software_update
3959  show_when:
3960    check: office-up-to-date
3961    is: []
3962"#;
3963        let m: Manifest = serde_yaml::from_str(empty_is).expect("parse");
3964        let err = m.validate().expect_err("empty is[] must fail");
3965        assert!(err.contains("client.show_when.is"), "err: {err}");
3966    }
3967
3968    #[test]
3969    fn manifest_client_confirm_accepts_bool_and_struct() {
3970        // `confirm:` deserializes from a bare bool or a struct. A bool
3971        // sets `enabled` (message stays default); a struct carries a custom
3972        // message and defaults `enabled` to true.
3973        let base = r#"
3974id: j
3975version: 1.0.0
3976execute:
3977  shell: powershell
3978  script: "echo x"
3979  timeout: 30s
3980client:
3981  name: "Wi-Fi 省電力を切る"
3982  category: settings
3983"#;
3984        // `confirm: false` ⇒ dialog suppressed.
3985        let off: Manifest =
3986            serde_yaml::from_str(&format!("{base}  confirm: false\n")).expect("parse false");
3987        off.validate().expect("confirm: false validates");
3988        let c = off.client.unwrap().confirm.unwrap();
3989        assert!(!c.enabled);
3990        assert!(c.message.is_none());
3991
3992        // `confirm: true` ⇒ same as omitting (dialog shown, default message).
3993        let on: Manifest =
3994            serde_yaml::from_str(&format!("{base}  confirm: true\n")).expect("parse true");
3995        let c = on.client.unwrap().confirm.unwrap();
3996        assert!(c.enabled);
3997        assert!(c.message.is_none());
3998
3999        // Struct with only a message ⇒ enabled defaults true, custom text.
4000        let msg: Manifest = serde_yaml::from_str(&format!(
4001            "{base}  confirm:\n    message: \"再インストールには数分かかります。よろしいですか?\"\n"
4002        ))
4003        .expect("parse struct");
4004        msg.validate().expect("confirm message validates");
4005        let c = msg.client.unwrap().confirm.unwrap();
4006        assert!(c.enabled);
4007        assert_eq!(
4008            c.message.as_deref(),
4009            Some("再インストールには数分かかります。よろしいですか?")
4010        );
4011
4012        // Absent ⇒ None (historical default handled by the client).
4013        let none: Manifest = serde_yaml::from_str(base).expect("parse none");
4014        assert!(none.client.unwrap().confirm.is_none());
4015
4016        // Explicit `confirm: null` is schema-valid (the field is Option) and
4017        // must map to None, not a parse error (Gemini #960).
4018        let null: Manifest =
4019            serde_yaml::from_str(&format!("{base}  confirm: null\n")).expect("parse null");
4020        assert!(null.client.unwrap().confirm.is_none());
4021    }
4022
4023    #[test]
4024    fn manifest_client_confirm_rejects_blank_message() {
4025        // A present-but-blank custom message would render an empty dialog
4026        // title — validate() must reject it, like the other display fields.
4027        let yaml = r#"
4028id: j
4029version: 1.0.0
4030execute:
4031  shell: powershell
4032  script: "echo x"
4033  timeout: 30s
4034client:
4035  name: "A job"
4036  category: settings
4037  confirm:
4038    message: "   "
4039"#;
4040        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4041        let err = m.validate().expect_err("blank confirm.message must fail");
4042        assert!(err.contains("client.confirm.message"), "err: {err}");
4043    }
4044
4045    #[test]
4046    fn manifest_client_requires_category_at_parse() {
4047        // A `client:` block missing `category` is a hard parse error
4048        // (serde required field) — no manual validate() needed.
4049        let yaml = r#"
4050id: j
4051version: 1.0.0
4052execute:
4053  shell: powershell
4054  script: "echo x"
4055  timeout: 30s
4056client:
4057  name: "A job"
4058"#;
4059        let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
4060        assert!(
4061            r.is_err(),
4062            "missing category must be a parse error, got {r:?}"
4063        );
4064    }
4065
4066    #[test]
4067    fn manifest_client_rejects_unknown_field() {
4068        // #492: the strict create boundary catches a fat-fingered
4069        // `displayname:` (with its path) instead of silently
4070        // dropping it; the tolerant read path accepts it.
4071        let yaml = r#"
4072id: j
4073version: 1.0.0
4074execute:
4075  shell: powershell
4076  script: "echo x"
4077  timeout: 30s
4078client:
4079  name: "A job"
4080  category: catalog
4081  displayname: oops
4082"#;
4083        let r = crate::strict::from_yaml_str::<Manifest>(yaml);
4084        let err = r.expect_err("unknown client field must be rejected at the write boundary");
4085        // serde_ignored renders the Option layer as `?`:
4086        // `client.?.displayname`. Assert on the leaf key.
4087        assert!(err.contains("displayname"), "{err}");
4088        // The READ path tolerates the same payload (gradual-upgrade
4089        // contract: an old agent must accept a newer writer's field).
4090        let m: Manifest = serde_yaml::from_str(yaml).expect("tolerant read");
4091        assert_eq!(m.client.as_ref().map(|c| c.name.as_str()), Some("A job"));
4092    }
4093
4094    #[test]
4095    fn manifest_tags_default_empty() {
4096        // The overwhelming majority of jobs carry no tags; the field
4097        // must default to an empty Vec (not fail to parse) and skip
4098        // serialisation so old readers never see the key.
4099        let yaml = r#"
4100id: echo-test
4101version: 0.0.1
4102execute:
4103  shell: powershell
4104  script: "echo 'kanade'"
4105  timeout: 30s
4106"#;
4107        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4108        assert!(m.tags.is_empty());
4109        m.validate().expect("tag-less job validates");
4110        // skip_serializing_if = empty ⇒ the key is absent from JSON.
4111        let json = serde_json::to_string(&m).expect("serialize");
4112        assert!(
4113            !json.contains("tags"),
4114            "empty tags must not serialise: {json}"
4115        );
4116    }
4117
4118    #[test]
4119    fn manifest_parses_and_validates_tags() {
4120        let yaml = r#"
4121id: check-bitlocker
4122version: 0.1.0
4123execute:
4124  shell: powershell
4125  script: "echo x"
4126  timeout: 30s
4127tags: [security, windows, health-check]
4128"#;
4129        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4130        assert_eq!(m.tags, vec!["security", "windows", "health-check"]);
4131        m.validate().expect("tagged job validates");
4132        // Round-trips through JSON (the wire format the SPA reads).
4133        let json = serde_json::to_string(&m).expect("serialize");
4134        assert!(json.contains("\"tags\""), "non-empty tags must serialise");
4135    }
4136
4137    #[test]
4138    fn manifest_rejects_blank_tag() {
4139        // A whitespace-only tag renders an empty filter chip — reject
4140        // it at the write boundary like the other blank display fields.
4141        let yaml = r#"
4142id: j
4143version: 0.1.0
4144execute:
4145  shell: powershell
4146  script: "echo x"
4147  timeout: 30s
4148tags: [ok, "   "]
4149"#;
4150        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4151        let err = m.validate().expect_err("blank tag must fail");
4152        assert!(err.contains("tags must not contain empty"), "err: {err}");
4153    }
4154
4155    #[test]
4156    fn validate_rejects_unknown_tier_and_accepts_known() {
4157        let base =
4158            "id: t\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: x\n  timeout: 30s\n";
4159        // A typo / future tier decodes to Tier::Unknown (#[serde(other)]) and
4160        // must FAIL CLOSED — never fall back to unrestricted endpoint dispatch.
4161        let bogus: Manifest =
4162            serde_yaml::from_str(&format!("{base}tier: controler\n")).expect("parse");
4163        let err = bogus.validate().expect_err("unknown tier must be rejected");
4164        assert!(err.contains("tier"), "err: {err}");
4165        // The two known tiers pass.
4166        serde_yaml::from_str::<Manifest>(&format!("{base}tier: controller\n"))
4167            .unwrap()
4168            .validate()
4169            .expect("controller tier is valid");
4170        serde_yaml::from_str::<Manifest>(&format!("{base}tier: endpoint\n"))
4171            .unwrap()
4172            .validate()
4173            .expect("endpoint tier is valid");
4174    }
4175
4176    #[test]
4177    fn feed_payload_extracts_fenced_block() {
4178        let stdout = "fetched 1500 KEV entries\n\
4179            #KANADE-FEED-BEGIN\n\
4180            {\"vulnerabilities\": []}\n\
4181            #KANADE-FEED-END\n";
4182        assert_eq!(feed_payload(stdout), "{\"vulnerabilities\": []}");
4183    }
4184
4185    #[test]
4186    fn validate_feed_rules() {
4187        let base =
4188            "id: f\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: x\n  timeout: 30s\n";
4189        // A well-formed feed (controller implied; no explicit tier) passes.
4190        serde_yaml::from_str::<Manifest>(&format!(
4191            "{base}feed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4192        ))
4193        .unwrap()
4194        .validate()
4195        .expect("a well-formed feed is valid");
4196
4197        // Empty primary_key is rejected (no item_id → every row dropped).
4198        let err = serde_yaml::from_str::<Manifest>(&format!(
4199            "{base}feed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: []\n"
4200        ))
4201        .unwrap()
4202        .validate()
4203        .expect_err("empty primary_key must be rejected");
4204        assert!(err.contains("primary_key"), "err: {err}");
4205
4206        // A duplicate feed id clobbers a partition — rejected.
4207        let err = serde_yaml::from_str::<Manifest>(&format!(
4208            "{base}feed:\n  - id: dup\n    field: a\n    primary_key: [k]\n  - id: dup\n    field: b\n    primary_key: [k]\n"
4209        ))
4210        .unwrap()
4211        .validate()
4212        .expect_err("duplicate feed id must be rejected");
4213        assert!(err.contains("more than once"), "err: {err}");
4214
4215        // `feed:` + explicit `tier: endpoint` is contradictory — rejected.
4216        let err = serde_yaml::from_str::<Manifest>(&format!(
4217            "{base}tier: endpoint\nfeed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4218        ))
4219        .unwrap()
4220        .validate()
4221        .expect_err("feed + tier: endpoint must be rejected");
4222        assert!(err.contains("controller tier"), "err: {err}");
4223
4224        // `feed:` + `emit:` is incompatible — emit consumes stdout whole, so
4225        // the feed's fence never reaches the projector.
4226        let err = serde_yaml::from_str::<Manifest>(&format!(
4227            "{base}emit:\n  type: events\nfeed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4228        ))
4229        .unwrap()
4230        .validate()
4231        .expect_err("feed + emit must be rejected");
4232        assert!(err.contains("emit"), "err: {err}");
4233    }
4234
4235    // #720 — wrap an `aggregate:` YAML block (already indented as a
4236    // top-level key body) into an otherwise-minimal valid manifest.
4237    fn manifest_with_aggregate(aggregate_block: &str) -> Manifest {
4238        let yaml = format!(
4239            "id: t\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: echo hi\n  timeout: 30s\n{aggregate_block}"
4240        );
4241        serde_yaml::from_str(&yaml).expect("parse aggregate manifest")
4242    }
4243
4244    #[test]
4245    fn aggregate_accepts_full_valid_spec() {
4246        // count+group_by+exclude+sample_minutes, ratio+bool_path,
4247        // timeline+time_bucket, fleet ranking via group_by: pc_id, and a
4248        // bare total stat — alongside emit (composes with every hint).
4249        let m = manifest_with_aggregate(
4250            "emit:\n  type: events\naggregate:\n\
4251             - { dashboard: Utilization, title: Top apps, kind: app_sample, agg: count, group_by: foreground.app, sample_minutes: 2, exclude: [LockApp], render: bar }\n\
4252             - { dashboard: Utilization, title: Active ratio, kind: presence, agg: ratio, bool_path: active, sample_minutes: 5, render: gauge }\n\
4253             - { dashboard: Utilization, title: By hour, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: timeline }\n\
4254             - { dashboard: Reliability, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
4255             - { dashboard: Reliability, title: Total crashes, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
4256        );
4257        m.validate().expect("valid aggregate spec");
4258    }
4259
4260    #[test]
4261    fn aggregate_rejects_empty_list() {
4262        let m = manifest_with_aggregate("aggregate: []\n");
4263        let err = m.validate().expect_err("empty list must fail");
4264        assert!(err.contains("at least one widget"), "err: {err}");
4265    }
4266
4267    #[test]
4268    fn aggregate_rejects_ratio_without_bool_path() {
4269        let m = manifest_with_aggregate(
4270            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, render: gauge }\n",
4271        );
4272        let err = m.validate().expect_err("ratio needs bool_path");
4273        assert!(err.contains("agg=ratio requires `bool_path`"), "err: {err}");
4274    }
4275
4276    #[test]
4277    fn aggregate_rejects_sum_without_value_path() {
4278        let m = manifest_with_aggregate(
4279            "aggregate:\n- { dashboard: D, title: T, kind: io, agg: sum, render: bar }\n",
4280        );
4281        let err = m.validate().expect_err("sum needs value_path");
4282        assert!(err.contains("agg=sum requires `value_path`"), "err: {err}");
4283    }
4284
4285    #[test]
4286    fn aggregate_rejects_pc_id_group_without_fleet() {
4287        let m = manifest_with_aggregate(
4288            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: count, group_by: pc_id, render: bar }\n",
4289        );
4290        let err = m.validate().expect_err("pc_id grouping needs fleet");
4291        assert!(
4292            err.contains("pc_id is only valid with scope: fleet"),
4293            "err: {err}"
4294        );
4295    }
4296
4297    #[test]
4298    fn aggregate_rejects_transform_with_pc_id_group() {
4299        let m = manifest_with_aggregate(
4300            "aggregate:\n- { dashboard: D, title: T, scope: fleet, kind: web_visit, agg: count, group_by: pc_id, transform: host, render: bar }\n",
4301        );
4302        let err = m
4303            .validate()
4304            .expect_err("transform on pc_id grouping must fail");
4305        assert!(
4306            err.contains("transform is not valid with group_by: pc_id"),
4307            "err: {err}"
4308        );
4309    }
4310
4311    #[test]
4312    fn aggregate_rejects_timeline_without_bucket() {
4313        let m = manifest_with_aggregate(
4314            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, bool_path: active, render: timeline }\n",
4315        );
4316        let err = m.validate().expect_err("timeline needs a bucket");
4317        assert!(
4318            err.contains("render=timeline requires `time_bucket`"),
4319            "err: {err}"
4320        );
4321    }
4322
4323    #[test]
4324    fn aggregate_rejects_bucket_on_non_timeline() {
4325        let m = manifest_with_aggregate(
4326            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: gauge }\n",
4327        );
4328        let err = m.validate().expect_err("bucket only on timeline");
4329        assert!(
4330            err.contains("time_bucket is only valid with render: timeline"),
4331            "err: {err}"
4332        );
4333    }
4334
4335    #[test]
4336    fn aggregate_rejects_unsafe_json_path() {
4337        // A path with characters outside [A-Za-z0-9_.] could break out of
4338        // the `'$.' || ?` bind — reject at create time.
4339        let m = manifest_with_aggregate(
4340            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: \"foo'; DROP\", render: bar }\n",
4341        );
4342        let err = m.validate().expect_err("unsafe path must fail");
4343        assert!(err.contains("dotted JSON path"), "err: {err}");
4344    }
4345
4346    #[test]
4347    fn aggregate_rejects_blank_title() {
4348        let m = manifest_with_aggregate(
4349            "aggregate:\n- { dashboard: D, title: \"  \", kind: k, agg: count, render: stat }\n",
4350        );
4351        let err = m.validate().expect_err("blank title must fail");
4352        assert!(err.contains("title must not be empty"), "err: {err}");
4353    }
4354
4355    #[test]
4356    fn aggregate_rejects_blank_kind() {
4357        let m = manifest_with_aggregate(
4358            "aggregate:\n- { dashboard: D, title: T, kind: \" \", agg: count, render: stat }\n",
4359        );
4360        let err = m.validate().expect_err("blank kind must fail");
4361        assert!(err.contains("kind must not be empty"), "err: {err}");
4362    }
4363
4364    #[test]
4365    fn aggregate_rejects_blank_source_when_set() {
4366        let m = manifest_with_aggregate(
4367            "aggregate:\n- { dashboard: D, title: T, kind: k, source: \"\", agg: count, render: stat }\n",
4368        );
4369        let err = m.validate().expect_err("blank source must fail");
4370        assert!(
4371            err.contains("source must not be empty when set"),
4372            "err: {err}"
4373        );
4374    }
4375
4376    #[test]
4377    fn aggregate_accepts_description_and_rejects_blank() {
4378        let ok = manifest_with_aggregate(
4379            "aggregate:\n- { dashboard: D, title: T, description: \"samples x 2 min\", kind: k, agg: count, render: stat }\n",
4380        );
4381        ok.validate()
4382            .expect("description is a valid optional field");
4383        assert_eq!(
4384            ok.aggregate.as_ref().unwrap()[0].description.as_deref(),
4385            Some("samples x 2 min")
4386        );
4387        let bad = manifest_with_aggregate(
4388            "aggregate:\n- { dashboard: D, title: T, description: \"  \", kind: k, agg: count, render: stat }\n",
4389        );
4390        let err = bad.validate().expect_err("blank description must fail");
4391        assert!(
4392            err.contains("description must not be empty when set"),
4393            "err: {err}"
4394        );
4395    }
4396
4397    #[test]
4398    fn aggregate_rejects_count_with_value_path() {
4399        let m = manifest_with_aggregate(
4400            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, value_path: bytes, render: stat }\n",
4401        );
4402        let err = m.validate().expect_err("count must not use value_path");
4403        assert!(
4404            err.contains("agg=count does not use `value_path`"),
4405            "err: {err}"
4406        );
4407    }
4408
4409    #[test]
4410    fn aggregate_rejects_ratio_with_value_path() {
4411        let m = manifest_with_aggregate(
4412            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: ratio, bool_path: active, value_path: bytes, render: gauge }\n",
4413        );
4414        let err = m.validate().expect_err("ratio must not use value_path");
4415        assert!(
4416            err.contains("agg=ratio does not use `value_path`"),
4417            "err: {err}"
4418        );
4419    }
4420
4421    #[test]
4422    fn aggregate_rejects_gauge_without_ratio() {
4423        let m = manifest_with_aggregate(
4424            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, render: gauge }\n",
4425        );
4426        let err = m.validate().expect_err("gauge needs ratio");
4427        assert!(
4428            err.contains("render=gauge is only valid with agg: ratio"),
4429            "err: {err}"
4430        );
4431    }
4432
4433    #[test]
4434    fn aggregate_rejects_limit_without_group_by() {
4435        let m = manifest_with_aggregate(
4436            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, limit: 5, render: stat }\n",
4437        );
4438        let err = m.validate().expect_err("limit needs group_by");
4439        assert!(err.contains("limit requires `group_by`"), "err: {err}");
4440    }
4441
4442    #[test]
4443    fn aggregate_rejects_exclude_without_group_by() {
4444        let m = manifest_with_aggregate(
4445            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, exclude: [x], render: stat }\n",
4446        );
4447        let err = m.validate().expect_err("exclude needs group_by");
4448        assert!(err.contains("exclude requires `group_by`"), "err: {err}");
4449    }
4450
4451    #[test]
4452    fn aggregate_rejects_zero_limit_and_zero_sample_minutes() {
4453        let m = manifest_with_aggregate(
4454            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, limit: 0, render: bar }\n",
4455        );
4456        assert!(m.validate().unwrap_err().contains("limit must be > 0"));
4457        let m = manifest_with_aggregate(
4458            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, sample_minutes: 0, render: bar }\n",
4459        );
4460        assert!(
4461            m.validate()
4462                .unwrap_err()
4463                .contains("sample_minutes must be > 0")
4464        );
4465    }
4466
4467    #[test]
4468    fn aggregate_rejects_empty_exclude_entry() {
4469        let m = manifest_with_aggregate(
4470            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, exclude: [\"  \"], render: bar }\n",
4471        );
4472        let err = m.validate().expect_err("blank exclude entry must fail");
4473        assert!(
4474            err.contains("exclude must not contain empty entries"),
4475            "err: {err}"
4476        );
4477    }
4478
4479    #[test]
4480    fn aggregate_rejects_malformed_dotted_paths() {
4481        for bad in [".foo", "foo.", "foo..bar", "."] {
4482            let m = manifest_with_aggregate(&format!(
4483                "aggregate:\n- {{ dashboard: D, title: T, kind: k, agg: count, group_by: \"{bad}\", render: bar }}\n"
4484            ));
4485            let err = m.validate().expect_err("malformed path must fail");
4486            assert!(err.contains("dotted JSON path"), "path {bad}: {err}");
4487        }
4488    }
4489
4490    #[test]
4491    fn aggregate_rejects_unknown_enum_value() {
4492        // An unrecognised render string deserialises to the #492 Unknown
4493        // catch-all (so old readers don't choke); validate() rejects it as
4494        // a typo at create time.
4495        let m = manifest_with_aggregate(
4496            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, render: heatmap }\n",
4497        );
4498        let err = m.validate().expect_err("unknown render must fail");
4499        assert!(err.contains("render is not a known value"), "err: {err}");
4500    }
4501
4502    #[test]
4503    fn aggregate_accepts_order_field() {
4504        let m = manifest_with_aggregate(
4505            "aggregate:\n- { dashboard: D, title: T, order: -5, kind: k, agg: count, render: stat }\n",
4506        );
4507        m.validate().expect("order is a valid optional field");
4508        let w = &m.aggregate.as_ref().unwrap()[0];
4509        assert_eq!(w.order, Some(-5));
4510    }
4511
4512    #[test]
4513    fn aggregate_accepts_minimal_op_timeline() {
4514        // op_timeline needs no kind/agg — it reconstructs a fixed multi-kind
4515        // swimlane. A bare per-PC spec is valid, and `kind`/`agg` stay None.
4516        let m = manifest_with_aggregate(
4517            "aggregate:\n- { dashboard: Uptime, title: Operational state, scope: pc, render: op_timeline }\n",
4518        );
4519        m.validate().expect("minimal op_timeline is valid");
4520        let w = &m.aggregate.as_ref().unwrap()[0];
4521        assert_eq!(w.render, AggregateRender::OpTimeline);
4522        assert!(w.kind.is_none());
4523        assert!(w.agg.is_none());
4524    }
4525
4526    #[test]
4527    fn aggregate_rejects_op_timeline_with_fleet_scope() {
4528        let m = manifest_with_aggregate(
4529            "aggregate:\n- { dashboard: Uptime, title: T, scope: fleet, render: op_timeline }\n",
4530        );
4531        let err = m.validate().expect_err("op_timeline must be per-PC");
4532        assert!(
4533            err.contains("render=op_timeline requires scope: pc"),
4534            "err: {err}"
4535        );
4536    }
4537
4538    #[test]
4539    fn aggregate_rejects_op_timeline_with_aggregation_fields() {
4540        // Each aggregation knob the operator might paste in is rejected
4541        // (rather than silently ignored), pointing at the field to delete.
4542        for (block, field) in [
4543            ("kind: boot", "kind"),
4544            ("agg: count", "agg"),
4545            ("source: winlog:Security", "source"),
4546            ("group_by: pc_id", "group_by"),
4547            ("bool_path: active", "bool_path"),
4548            ("time_bucket: hour", "time_bucket"),
4549            ("limit: 5", "limit"),
4550        ] {
4551            let m = manifest_with_aggregate(&format!(
4552                "aggregate:\n- {{ dashboard: Uptime, title: T, scope: pc, {block}, render: op_timeline }}\n"
4553            ));
4554            let err = m
4555                .validate()
4556                .expect_err(&format!("op_timeline must reject {field}"));
4557            assert!(
4558                err.contains(&format!("render=op_timeline does not use `{field}`")),
4559                "field {field}: {err}"
4560            );
4561        }
4562    }
4563
4564    // ── #743 View resource ───────────────────────────────────────────
4565    fn view_from(yaml_body: &str) -> View {
4566        serde_yaml::from_str(&format!("id: v1\n{yaml_body}")).expect("parse view")
4567    }
4568
4569    #[test]
4570    fn view_accepts_valid_widgets() {
4571        let v = view_from(
4572            "widgets:\n\
4573             - { dashboard: Reliability, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
4574             - { dashboard: Reliability, title: Total, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
4575        );
4576        v.validate().expect("valid view");
4577    }
4578
4579    #[test]
4580    fn view_rejects_empty_widgets() {
4581        let v = view_from("widgets: []\n");
4582        let err = v.validate().expect_err("empty widgets must fail");
4583        assert!(err.contains("at least one widget"), "err: {err}");
4584    }
4585
4586    #[test]
4587    fn view_rejects_blank_id() {
4588        let v: View = serde_yaml::from_str(
4589            "id: \"  \"\nwidgets:\n- { dashboard: D, title: T, kind: k, agg: count, render: stat }\n",
4590        )
4591        .expect("parse");
4592        let err = v.validate().expect_err("blank id must fail");
4593        assert!(err.contains("view.id must"), "err: {err}");
4594    }
4595
4596    #[test]
4597    fn view_rejects_unsafe_id() {
4598        // A `/` or `..` in the id would break the KV key and the
4599        // `/api/views/{id}` URL segment — reject at create time.
4600        for bad in ["../etc", "a/b", "has space", "x;y"] {
4601            let v: View = serde_yaml::from_str(&format!(
4602                "id: \"{bad}\"\nwidgets:\n- {{ dashboard: D, title: T, kind: k, agg: count, render: stat }}\n",
4603            ))
4604            .expect("parse");
4605            let err = v.validate().expect_err("unsafe id must fail");
4606            assert!(err.contains("[A-Za-z0-9._-]"), "id {bad}: {err}");
4607        }
4608        assert!(is_valid_resource_id("dashboards-fleet.v1_2"));
4609    }
4610
4611    #[test]
4612    fn view_rejects_untrimmed_id() {
4613        // A padded id validated-as-trimmed but stored-raw would be a KV key
4614        // (and `/api/views/{id}` segment) nothing matches — reject it outright
4615        // (the id is used verbatim).
4616        let v: View = serde_yaml::from_str(
4617            "id: \" my-view \"\nwidgets:\n- { dashboard: D, title: T, kind: k, agg: count, render: stat }\n",
4618        )
4619        .expect("parse");
4620        let err = v.validate().expect_err("padded id must fail");
4621        assert!(err.contains("view.id must"), "err: {err}");
4622    }
4623
4624    #[test]
4625    fn view_reuses_shared_widget_validation() {
4626        // The same per-widget rule the job hint enforces (ratio needs
4627        // bool_path), reported under the `widgets[..]` field.
4628        let v = view_from(
4629            "widgets:\n- { dashboard: D, title: T, kind: presence, agg: ratio, render: gauge }\n",
4630        );
4631        let err = v.validate().expect_err("ratio without bool_path must fail");
4632        assert!(
4633            err.contains("widgets[0].agg=ratio requires `bool_path`"),
4634            "err: {err}"
4635        );
4636    }
4637
4638    // ── #vuln-roadmap PR3 SQL-backed views ───────────────────────────
4639    #[test]
4640    fn view_accepts_pure_sql_widgets() {
4641        // A view with only sql_widgets (no obs_events aggregate widgets) is
4642        // valid — the vulnerability-dashboard shape.
4643        let v = view_from(
4644            "sql_widgets:
4645  - title: KEV-affected hosts
4646    query: \"SELECT pc_id, 1 AS cves FROM inventory_sw_apps\"
4647    refresh: 6h
4648    render: { kind: table, columns: [pc_id, cves], labels: { cves: CVE count } }
4649    placement: { analytics: Security, dashboard: { pin: true } }
4650",
4651        );
4652        v.validate().expect("valid sql view");
4653        // refresh parses; pin/tab helpers read the placement.
4654        let w = &v.sql_widgets[0];
4655        assert_eq!(
4656            w.refresh_interval(),
4657            std::time::Duration::from_secs(6 * 3600)
4658        );
4659        assert!(w.placement.is_pinned());
4660        assert_eq!(w.placement.tab(), "Security");
4661    }
4662
4663    #[test]
4664    fn sql_widget_defaults_and_mix() {
4665        // No refresh ⇒ default; a view can mix aggregate + sql widgets.
4666        let v = view_from(
4667            "widgets:
4668  - { dashboard: D, title: T, kind: k, agg: count, render: stat }
4669sql_widgets:
4670  - title: N affected
4671    query: \"SELECT count(*) AS n FROM feeds\"
4672    render: { kind: stat, value: n }
4673    placement: { dashboard: { pin: true } }
4674",
4675        );
4676        v.validate().expect("mixed view is valid");
4677        assert_eq!(v.sql_widgets[0].refresh_interval(), DEFAULT_VIEW_REFRESH);
4678        // dashboard-only placement (no analytics tab) falls back to a label.
4679        assert_eq!(v.sql_widgets[0].placement.tab(), "Dashboard");
4680    }
4681
4682    #[test]
4683    fn sql_widget_validation_rules() {
4684        // helper: build a view with one sql_widget from an inline render+placement
4685        let mk = |render: &str, placement: &str| -> Result<(), String> {
4686            view_from(&format!(
4687                "sql_widgets:
4688  - title: W
4689    query: \"SELECT 1 AS a\"
4690    render: {render}
4691    placement: {placement}
4692"
4693            ))
4694            .validate()
4695        };
4696        // bar needs label + value
4697        let err = mk("{ kind: bar, value: a }", "{ analytics: T }").unwrap_err();
4698        assert!(
4699            err.contains("render.label is required for kind=bar"),
4700            "err: {err}"
4701        );
4702        // pie needs value
4703        let err = mk("{ kind: pie, label: a }", "{ analytics: T }").unwrap_err();
4704        assert!(
4705            err.contains("render.value is required for kind=pie"),
4706            "err: {err}"
4707        );
4708        // stat needs value
4709        let err = mk("{ kind: stat }", "{ analytics: T }").unwrap_err();
4710        assert!(
4711            err.contains("render.value is required for kind=stat"),
4712            "err: {err}"
4713        );
4714        // gauge needs value XOR num+den
4715        let err = mk("{ kind: gauge, num: a }", "{ analytics: T }").unwrap_err();
4716        assert!(err.contains("needs either `value`"), "err: {err}");
4717        mk("{ kind: gauge, value: a }", "{ analytics: T }").expect("gauge value ok");
4718        mk("{ kind: gauge, num: a, den: a }", "{ analytics: T }").expect("gauge num/den ok");
4719        // unknown kind rejected
4720        let err = mk("{ kind: sunburst }", "{ analytics: T }").unwrap_err();
4721        assert!(
4722            err.contains("render.kind is not a known value"),
4723            "err: {err}"
4724        );
4725        // placement must surface somewhere
4726        let err = mk("{ kind: table }", "{}").unwrap_err();
4727        assert!(err.contains("placement must set"), "err: {err}");
4728        // a `dashboard: { pin: false }` block still surfaces nowhere.
4729        let err = mk("{ kind: table }", "{ dashboard: { pin: false } }").unwrap_err();
4730        assert!(err.contains("placement must set"), "err: {err}");
4731        mk("{ kind: table }", "{ dashboard: { pin: true } }").expect("pinned dashboard ok");
4732        // limit: 0 on a bar/pie is an invisible widget — rejected.
4733        let err = mk(
4734            "{ kind: bar, label: a, value: a, limit: 0 }",
4735            "{ analytics: T }",
4736        )
4737        .unwrap_err();
4738        assert!(err.contains("limit must be >= 1"), "err: {err}");
4739        // bad refresh duration rejected
4740        let err = view_from(
4741            "sql_widgets:
4742  - { title: W, query: \"SELECT 1\", refresh: \"6 sidereal days\", render: { kind: table }, placement: { analytics: T } }
4743",
4744        )
4745        .validate()
4746        .unwrap_err();
4747        assert!(
4748            err.contains("refresh") && err.contains("not a valid duration"),
4749            "err: {err}"
4750        );
4751        // table is fine with no channels
4752        mk("{ kind: table }", "{ analytics: T }").expect("bare table ok");
4753    }
4754
4755    #[test]
4756    fn rewrite_pc_id_param_is_literal_and_boundary_aware() {
4757        // A real param outside any literal is rewritten + counted.
4758        let (sql, n) = rewrite_pc_id_param("SELECT * FROM t WHERE pc_id = :pc_id");
4759        assert_eq!(n, 1);
4760        assert!(sql.ends_with("pc_id = ?"), "sql: {sql}");
4761        // Appearing twice → two `?`, count 2 (one bind each — the caller binds
4762        // pc_id per occurrence since sqlx-sqlite has no named params).
4763        let (sql, n) = rewrite_pc_id_param("WHERE a = :pc_id AND (:pc_id IS NOT NULL)");
4764        assert_eq!(n, 2);
4765        assert_eq!(sql, "WHERE a = ? AND (? IS NOT NULL)");
4766        // Inside a string literal → copied verbatim, NOT counted (would else be
4767        // a bind-count mismatch → SQLITE_RANGE, and misclassify scope).
4768        let (sql, n) = rewrite_pc_id_param("SELECT 'see :pc_id docs' AS hint");
4769        assert_eq!(n, 0);
4770        assert_eq!(sql, "SELECT 'see :pc_id docs' AS hint");
4771        // Inside a comment → left alone.
4772        let (_, n) = rewrite_pc_id_param("SELECT 1 -- filter by :pc_id\n");
4773        assert_eq!(n, 0);
4774        // A longer identifier prefix (`:pc_idx`) is not our token.
4775        let (sql, n) = rewrite_pc_id_param("WHERE x = :pc_idx");
4776        assert_eq!(n, 0);
4777        assert_eq!(sql, "WHERE x = :pc_idx");
4778    }
4779
4780    #[test]
4781    fn validate_rejects_pinned_per_pc_widget() {
4782        // A per-PC widget (binds :pc_id) that also pins to the Dashboard is a
4783        // create-time contradiction (Dashboard is fleet-scope) — rejected.
4784        let err = view_from(
4785            "sql_widgets:
4786  - title: W
4787    query: \"SELECT count(*) AS n FROM inventory_sw_apps WHERE pc_id = :pc_id\"
4788    render: { kind: stat, value: n }
4789    placement: { analytics: Security, dashboard: { pin: true } }
4790",
4791        )
4792        .validate()
4793        .unwrap_err();
4794        assert!(err.contains("per-PC widget"), "err: {err}");
4795        // The same widget WITHOUT the pin is fine (per-PC, analytics only).
4796        view_from(
4797            "sql_widgets:
4798  - title: W
4799    query: \"SELECT count(*) AS n FROM inventory_sw_apps WHERE pc_id = :pc_id\"
4800    render: { kind: stat, value: n }
4801    placement: { analytics: Security }
4802",
4803        )
4804        .validate()
4805        .expect("per-PC analytics-only widget is valid");
4806    }
4807
4808    fn execute_with(
4809        script: Option<&str>,
4810        script_file: Option<&str>,
4811        script_object: Option<&str>,
4812    ) -> Execute {
4813        Execute {
4814            shell: ExecuteShell::Powershell,
4815            script: script.map(str::to_owned),
4816            script_file: script_file.map(str::to_owned),
4817            script_object: script_object.map(str::to_owned),
4818            timeout: "30s".into(),
4819            run_as: RunAs::default(),
4820            cwd: None,
4821        }
4822    }
4823
4824    #[test]
4825    fn validate_accepts_inline_script() {
4826        let e = execute_with(Some("echo hi"), None, None);
4827        assert!(e.validate_script_source().is_ok());
4828    }
4829
4830    #[test]
4831    fn validate_accepts_script_file_alone() {
4832        let e = execute_with(None, Some("scripts/cleanup.ps1"), None);
4833        assert!(e.validate_script_source().is_ok());
4834    }
4835
4836    #[test]
4837    fn validate_accepts_script_object_alone() {
4838        let e = execute_with(None, None, Some("cleanup/1.0.0"));
4839        assert!(e.validate_script_source().is_ok());
4840    }
4841
4842    #[test]
4843    fn validate_treats_empty_inline_script_as_unset() {
4844        // `script: ""` + `script_object` set is the natural shape
4845        // when an operator comments out the YAML block-scalar body
4846        // but leaves the key. Should pass.
4847        let e = execute_with(Some(""), None, Some("cleanup/1.0.0"));
4848        assert!(e.validate_script_source().is_ok());
4849    }
4850
4851    #[test]
4852    fn validate_rejects_zero_sources() {
4853        let e = execute_with(None, None, None);
4854        let err = e.validate_script_source().unwrap_err();
4855        assert!(err.contains("must be set"), "got: {err}");
4856    }
4857
4858    #[test]
4859    fn validate_rejects_empty_inline_only() {
4860        let e = execute_with(Some(""), None, None);
4861        let err = e.validate_script_source().unwrap_err();
4862        assert!(err.contains("must be set"), "got: {err}");
4863    }
4864
4865    #[test]
4866    fn validate_rejects_inline_plus_file() {
4867        let e = execute_with(Some("echo hi"), Some("scripts/cleanup.ps1"), None);
4868        let err = e.validate_script_source().unwrap_err();
4869        assert!(err.contains("only one of"), "got: {err}");
4870    }
4871
4872    #[test]
4873    fn validate_rejects_inline_plus_object() {
4874        let e = execute_with(Some("echo hi"), None, Some("cleanup/1.0.0"));
4875        let err = e.validate_script_source().unwrap_err();
4876        assert!(err.contains("only one of"), "got: {err}");
4877    }
4878
4879    #[test]
4880    fn validate_rejects_file_plus_object() {
4881        let e = execute_with(None, Some("scripts/cleanup.ps1"), Some("cleanup/1.0.0"));
4882        let err = e.validate_script_source().unwrap_err();
4883        assert!(err.contains("only one of"), "got: {err}");
4884    }
4885
4886    #[test]
4887    fn validate_rejects_all_three() {
4888        let e = execute_with(
4889            Some("echo hi"),
4890            Some("scripts/cleanup.ps1"),
4891            Some("cleanup/1.0.0"),
4892        );
4893        let err = e.validate_script_source().unwrap_err();
4894        assert!(err.contains("only one of"), "got: {err}");
4895    }
4896
4897    #[test]
4898    fn validate_rejects_blank_script_file() {
4899        // #918: a blank `script_file` used to count as "set" and pass
4900        // the exactly-one check, then fail at use time (the CLI reads
4901        // a file named "").
4902        for blank in ["", "   "] {
4903            let e = execute_with(None, Some(blank), None);
4904            let err = e.validate_script_source().unwrap_err();
4905            assert!(err.contains("script_file must not be blank"), "got: {err}");
4906        }
4907    }
4908
4909    #[test]
4910    fn validate_rejects_blank_script_object() {
4911        // #918: same for a blank `script_object` (would 404 every exec).
4912        for blank in ["", "   "] {
4913            let e = execute_with(None, None, Some(blank));
4914            let err = e.validate_script_source().unwrap_err();
4915            assert!(
4916                err.contains("script_object must not be blank"),
4917                "got: {err}"
4918            );
4919        }
4920    }
4921
4922    #[test]
4923    fn validate_treats_whitespace_inline_script_as_unset() {
4924        // #918: a whitespace-only inline body is a commented-out block,
4925        // not a real script — with no other source it's "zero sources".
4926        let e = execute_with(Some("   \n  "), None, None);
4927        let err = e.validate_script_source().unwrap_err();
4928        assert!(err.contains("must be set"), "got: {err}");
4929    }
4930
4931    #[test]
4932    fn validate_rejects_malformed_script_object_ref() {
4933        // #918: the ref must be `<name>/<version>`; a missing slash,
4934        // extra slash, blank half, or whitespace-padded half (the last
4935        // survives a JSON POST body and 404s at exec — gemini/claude
4936        // #943) can never resolve.
4937        for bad in [
4938            "no-slash", "a/b/c", "/1.0.0", "cleanup/", " / ", "foo/bar ", " foo/bar", "foo /bar",
4939        ] {
4940            let e = execute_with(None, None, Some(bad));
4941            let err = e.validate_script_source().unwrap_err();
4942            assert!(
4943                err.contains("must be `<name>/<version>`"),
4944                "for '{bad}', got: {err}"
4945            );
4946        }
4947    }
4948
4949    #[test]
4950    fn manifest_deserialises_script_object_yaml() {
4951        // SPEC §2.4.1 example shape with the Object Store
4952        // reference picked over inline.
4953        let yaml = r#"
4954id: cleanup-disk-temp
4955version: 1.0.1
4956execute:
4957  shell: powershell
4958  script_object: cleanup-disk-temp/1.0.1
4959  timeout: 600s
4960"#;
4961        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4962        assert_eq!(
4963            m.execute.script_object.as_deref(),
4964            Some("cleanup-disk-temp/1.0.1")
4965        );
4966        assert!(m.execute.script.is_none());
4967        m.validate()
4968            .expect("script_object-only manifest passes validation");
4969    }
4970
4971    #[test]
4972    fn manifest_rejects_typo_in_script_field_name() {
4973        // #492: the strict create boundary catches `script_objectt`
4974        // and similar fat-fingers (with the full path) instead of
4975        // letting them silently fall through to "all three unset".
4976        let yaml = r#"
4977id: typo
4978version: 1.0.0
4979execute:
4980  shell: powershell
4981  script_objectt: oops
4982  timeout: 30s
4983"#;
4984        let err = crate::strict::from_yaml_str::<Manifest>(yaml)
4985            .expect_err("typo'd execute field must be rejected at the write boundary");
4986        assert!(err.contains("execute.script_objectt"), "{err}");
4987    }
4988
4989    #[test]
4990    fn schedule_carries_target_and_rollout() {
4991        let yaml = r#"
4992id: hourly-cleanup-canary
4993when:
4994  per_pc: { every: 1h }
4995job_id: cleanup
4996enabled: true
4997target:
4998  groups: [canary, wave1]
4999jitter: 30s
5000rollout:
5001  strategy: wave
5002  waves:
5003    - { group: canary, delay: 0s }
5004    - { group: wave1,  delay: 5s }
5005"#;
5006        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5007        assert_eq!(s.id, "hourly-cleanup-canary");
5008        assert_eq!(s.job_id, "cleanup");
5009        assert_eq!(s.plan.target.groups, vec!["canary", "wave1"]);
5010        assert_eq!(s.plan.jitter.as_deref(), Some("30s"));
5011        let rollout = s.plan.rollout.expect("rollout present");
5012        assert_eq!(rollout.waves.len(), 2);
5013        assert_eq!(rollout.waves[0].group, "canary");
5014        assert_eq!(rollout.waves[1].delay, "5s");
5015        assert_eq!(rollout.strategy, RolloutStrategy::Wave);
5016    }
5017
5018    #[test]
5019    fn schedule_minimal_target_all() {
5020        let yaml = r#"
5021id: kitting
5022when:
5023  per_pc: once
5024enabled: true
5025job_id: scheduled-echo
5026target: { all: true }
5027"#;
5028        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5029        assert_eq!(s.id, "kitting");
5030        assert_eq!(s.when, When::PerPc(PerPolicy::Once(OnceLiteral::Once)));
5031        assert!(s.enabled);
5032        assert_eq!(s.job_id, "scheduled-echo");
5033        assert!(s.plan.target.all);
5034        assert!(s.plan.rollout.is_none());
5035        assert!(s.plan.jitter.is_none());
5036        assert!(s.active.is_empty());
5037    }
5038
5039    #[test]
5040    fn schedule_enabled_defaults_to_true() {
5041        let yaml = r#"
5042id: x
5043when:
5044  per_pc: once
5045job_id: y
5046target: { all: true }
5047"#;
5048        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5049        assert!(s.enabled);
5050    }
5051
5052    fn once_per_version_yaml(runs_on: &str, per: &str) -> String {
5053        format!(
5054            "id: x\nwhen:\n  {per}\njob_id: install-kanade-client\n\
5055             target: {{ groups: [dejisen] }}\nruns_on: {runs_on}\n"
5056        )
5057    }
5058
5059    #[test]
5060    fn per_pc_once_per_version_parses() {
5061        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5062            "backend",
5063            "per_pc: once_per_version",
5064        ))
5065        .expect("parse");
5066        assert_eq!(
5067            s.when,
5068            When::PerPc(PerPolicy::OncePerVersion(
5069                OncePerVersionLiteral::OncePerVersion
5070            ))
5071        );
5072    }
5073
5074    #[test]
5075    fn per_pc_once_per_version_lowers_to_version_mode_no_cooldown() {
5076        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5077            "backend",
5078            "per_pc: once_per_version",
5079        ))
5080        .expect("parse");
5081        let l = s.lowered();
5082        assert_eq!(l.mode, ExecMode::OncePerPcVersion);
5083        assert_eq!(l.cooldown, None, "version re-arm is not a cooldown");
5084    }
5085
5086    #[test]
5087    fn once_per_version_displays_and_serialises() {
5088        let w = When::PerPc(PerPolicy::OncePerVersion(
5089            OncePerVersionLiteral::OncePerVersion,
5090        ));
5091        assert_eq!(w.to_string(), "per_pc once_per_version");
5092        // serde round-trips through the ergonomic bare string.
5093        let json = serde_json::to_value(&w).unwrap();
5094        assert_eq!(json, serde_json::json!({ "per_pc": "once_per_version" }));
5095    }
5096
5097    #[test]
5098    fn once_per_version_rejects_typo() {
5099        // The distinct literal still catches typos (no free-form String).
5100        let r: Result<Schedule, _> = serde_yaml::from_str(&once_per_version_yaml(
5101            "backend",
5102            "per_pc: once_per_verison",
5103        ));
5104        assert!(r.is_err(), "typo should not parse");
5105    }
5106
5107    #[test]
5108    fn validate_accepts_once_per_version_on_backend() {
5109        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5110            "backend",
5111            "per_pc: once_per_version",
5112        ))
5113        .expect("parse");
5114        assert!(s.validate().is_ok(), "got: {:?}", s.validate());
5115    }
5116
5117    #[test]
5118    fn validate_rejects_once_per_version_on_agent() {
5119        let s: Schedule =
5120            serde_yaml::from_str(&once_per_version_yaml("agent", "per_pc: once_per_version"))
5121                .expect("parse");
5122        let err = s
5123            .validate()
5124            .expect_err("agent + once_per_version must be rejected");
5125        assert!(err.contains("once_per_version"), "got: {err}");
5126        assert!(err.contains("backend"), "got: {err}");
5127    }
5128
5129    #[test]
5130    fn validate_rejects_once_per_version_on_per_target() {
5131        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5132            "backend",
5133            "per_target: once_per_version",
5134        ))
5135        .expect("parse");
5136        let err = s
5137            .validate()
5138            .expect_err("per_target + once_per_version must be rejected");
5139        assert!(err.contains("once_per_version"), "got: {err}");
5140        assert!(err.contains("per_pc"), "got: {err}");
5141    }
5142
5143    #[test]
5144    fn schedule_tags_default_empty_and_skip_serialise() {
5145        let yaml = r#"
5146id: x
5147when:
5148  per_pc: once
5149job_id: y
5150target: { all: true }
5151"#;
5152        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5153        assert!(s.tags.is_empty());
5154        s.validate().expect("tag-less schedule validates");
5155        let json = serde_json::to_string(&s).expect("serialize");
5156        assert!(
5157            !json.contains("tags"),
5158            "empty tags must not serialise: {json}"
5159        );
5160    }
5161
5162    #[test]
5163    fn schedule_parses_and_validates_tags() {
5164        let yaml = r#"
5165id: weekly-cleanup
5166when:
5167  per_pc: { every: 1h }
5168job_id: cleanup
5169target: { all: true }
5170tags: [weekly, maintenance]
5171"#;
5172        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5173        assert_eq!(s.tags, vec!["weekly", "maintenance"]);
5174        s.validate().expect("tagged schedule validates");
5175    }
5176
5177    #[test]
5178    fn schedule_rejects_blank_tag() {
5179        let yaml = r#"
5180id: x
5181when:
5182  per_pc: once
5183job_id: y
5184target: { all: true }
5185tags: [ok, "  "]
5186"#;
5187        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5188        let err = s.validate().expect_err("blank tag must fail");
5189        assert!(err.contains("tags must not contain empty"), "err: {err}");
5190    }
5191
5192    // ---- `when` parsing (#418 Phase 1) ----
5193
5194    fn schedule_yaml_with(when_block: &str) -> String {
5195        format!(
5196            r#"
5197id: x
5198when:
5199{when_block}
5200job_id: y
5201target: {{ all: true }}
5202"#
5203        )
5204    }
5205
5206    #[test]
5207    fn when_per_pc_every_parses_unquoted_humantime() {
5208        // `6h` is digit-led but non-numeric → YAML string, same as
5209        // the old `cooldown: 6h` convention. No quotes needed.
5210        let s: Schedule =
5211            serde_yaml::from_str(&schedule_yaml_with("  per_pc: { every: 6h }")).expect("parse");
5212        assert_eq!(
5213            s.when,
5214            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() }))
5215        );
5216    }
5217
5218    #[test]
5219    fn when_per_target_every_parses() {
5220        let s: Schedule = serde_yaml::from_str(&schedule_yaml_with("  per_target: { every: 24h }"))
5221            .expect("parse");
5222        assert_eq!(
5223            s.when,
5224            When::PerTarget(PerPolicy::Every(EverySpec {
5225                every: "24h".into()
5226            }))
5227        );
5228    }
5229
5230    #[test]
5231    fn when_per_target_once_parses() {
5232        // Falls out of the shared PerPolicy shape and decide_fire
5233        // already implements it ("any one pc succeeds → skip the
5234        // target forever"), so it is allowed, not rejected.
5235        let s: Schedule =
5236            serde_yaml::from_str(&schedule_yaml_with("  per_target: once")).expect("parse");
5237        assert_eq!(s.when, When::PerTarget(PerPolicy::Once(OnceLiteral::Once)));
5238    }
5239
5240    #[test]
5241    fn when_calendar_time_parses() {
5242        let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(
5243            "  calendar:\n    at: \"09:00\"\n    days: [mon-fri]",
5244        ))
5245        .expect("parse");
5246        match &s.when {
5247            When::Calendar(c) => {
5248                assert_eq!(c.at, "09:00");
5249                assert_eq!(c.days, vec!["mon-fri"]);
5250            }
5251            other => panic!("expected calendar, got {other:?}"),
5252        }
5253    }
5254
5255    #[test]
5256    fn when_calendar_days_default_empty() {
5257        let s: Schedule =
5258            serde_yaml::from_str(&schedule_yaml_with("  calendar:\n    at: \"09:00\""))
5259                .expect("parse");
5260        match &s.when {
5261            When::Calendar(c) => assert!(c.days.is_empty(), "days defaults to empty (= daily)"),
5262            other => panic!("expected calendar, got {other:?}"),
5263        }
5264    }
5265
5266    #[test]
5267    fn when_calendar_datetime_parses_all_separators() {
5268        // one-shot: date+time in hyphen / ISO-T / slash forms
5269        for at in ["2026-06-10 09:00", "2026-06-10T09:00", "2026/06/10 09:00"] {
5270            let block = format!("  calendar:\n    at: \"{at}\"");
5271            let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(&block))
5272                .unwrap_or_else(|e| panic!("parse '{at}': {e}"));
5273            match &s.when {
5274                When::Calendar(c) => {
5275                    use chrono::Datelike;
5276                    let p = c.parse_at().expect("parse_at");
5277                    let d = p.date.expect("datetime at carries a date");
5278                    assert_eq!((d.year(), d.month(), d.day()), (2026, 6, 10), "for '{at}'");
5279                }
5280                other => panic!("expected calendar, got {other:?}"),
5281            }
5282        }
5283    }
5284
5285    #[test]
5286    fn when_rejects_bad_once_keyword() {
5287        // `onec` must be a parse error, not a silently-absorbed
5288        // string (OnceLiteral is a single-variant enum for exactly
5289        // this reason).
5290        let r: Result<Schedule, _> = serde_yaml::from_str(&schedule_yaml_with("  per_pc: onec"));
5291        assert!(r.is_err(), "expected parse error, got {r:?}");
5292    }
5293
5294    #[test]
5295    fn when_rejects_unknown_key_in_every() {
5296        // `{ evry: 6h }` still fails on the tolerant read path: the
5297        // required `every` key is missing, so no PerPolicy variant
5298        // matches (#492 removed deny_unknown_fields, but required
5299        // keys keep the untagged disambiguation honest).
5300        let r: Result<Schedule, _> =
5301            serde_yaml::from_str(&schedule_yaml_with("  per_pc: { evry: 6h }"));
5302        assert!(r.is_err(), "expected parse error, got {r:?}");
5303    }
5304
5305    #[test]
5306    fn when_rejects_unknown_variant() {
5307        let r: Result<Schedule, _> =
5308            serde_yaml::from_str(&schedule_yaml_with("  per_galaxy: once"));
5309        assert!(r.is_err(), "expected parse error, got {r:?}");
5310    }
5311
5312    #[test]
5313    fn when_rejects_old_top_level_cron_field() {
5314        // Pre-#418 shape: top-level `cron:` + no `when:`. Must fail
5315        // loudly (missing `when`), which is what turns stale KV
5316        // blobs into warn-skips after the upgrade.
5317        let yaml = r#"
5318id: x
5319cron: "* * * * * *"
5320job_id: y
5321target: { all: true }
5322"#;
5323        let r: Result<Schedule, _> = serde_yaml::from_str(yaml);
5324        assert!(r.is_err(), "expected parse error, got {r:?}");
5325    }
5326
5327    #[test]
5328    fn when_rejects_retired_cron_escape_hatch() {
5329        // #418 Phase 2 retired `when: { cron: "..." }`. A raw cron
5330        // is now an unknown variant → parse error (operators use the
5331        // calendar form instead).
5332        let r: Result<Schedule, _> =
5333            serde_yaml::from_str(&schedule_yaml_with("  cron: \"0 0 9 * * mon-fri\""));
5334        assert!(
5335            r.is_err(),
5336            "expected parse error for retired cron, got {r:?}"
5337        );
5338    }
5339
5340    #[test]
5341    fn when_round_trips_json_and_yaml() {
5342        // Round-trip through the full Schedule: that is the wire
5343        // unit for both stores (JSON catalog KV + YAML mirror), and
5344        // it exercises the singleton_map field attribute that keeps
5345        // serde_yaml on the map shape instead of `!per_pc` tags.
5346        for when in [
5347            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5348            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5349            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5350            When::PerTarget(PerPolicy::Every(EverySpec {
5351                every: "24h".into(),
5352            })),
5353            calendar("09:00", &["mon-fri"]),
5354            calendar("2026-06-10 09:00", &[]),
5355            When::On(vec![OnTrigger::Startup]),
5356            When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
5357            When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
5358            When::On(vec![OnTrigger::NetworkChange]),
5359        ] {
5360            // Event triggers are agent-only; the rest validate on backend.
5361            let runs_on = if matches!(when, When::On(_)) {
5362                RunsOn::Agent
5363            } else {
5364                RunsOn::Backend
5365            };
5366            let s = schedule_with(when.clone(), runs_on);
5367
5368            let json = serde_json::to_string(&s).expect("json serialise");
5369            let back: Schedule = serde_json::from_str(&json).expect("json deserialise");
5370            assert_eq!(back.when, when, "json round-trip for {when}");
5371
5372            let yaml = serde_yaml::to_string(&s).expect("yaml serialise");
5373            assert!(
5374                !yaml.contains('!'),
5375                "yaml must use the map shape, not tags: {yaml}"
5376            );
5377            let back: Schedule = serde_yaml::from_str(&yaml).expect("yaml deserialise");
5378            assert_eq!(back.when, when, "yaml round-trip for {when}");
5379        }
5380    }
5381
5382    #[test]
5383    fn when_once_serialises_as_bare_keyword() {
5384        // The wire shape operators see in the YAML mirror must stay
5385        // the ergonomic `per_pc: once`, not a one-variant map.
5386        let json = serde_json::to_value(When::PerPc(PerPolicy::Once(OnceLiteral::Once)))
5387            .expect("serialise");
5388        assert_eq!(json, serde_json::json!({ "per_pc": "once" }));
5389    }
5390
5391    #[test]
5392    fn when_displays_operator_summary() {
5393        for (when, expected) in [
5394            (
5395                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5396                "per_pc once",
5397            ),
5398            (
5399                When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5400                "per_pc every 6h",
5401            ),
5402            (
5403                When::PerTarget(PerPolicy::Every(EverySpec {
5404                    every: "24h".into(),
5405                })),
5406                "per_target every 24h",
5407            ),
5408            (calendar("09:00", &["mon-fri"]), "at 09:00 [mon-fri]"),
5409            (calendar("2026-06-10 09:00", &[]), "at 2026-06-10 09:00"),
5410            (When::On(vec![OnTrigger::Startup]), "on [startup]"),
5411            (
5412                When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
5413                "on [startup,logon]",
5414            ),
5415            (
5416                When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
5417                "on [lock,unlock]",
5418            ),
5419            (
5420                When::On(vec![OnTrigger::NetworkChange]),
5421                "on [network_change]",
5422            ),
5423        ] {
5424            assert_eq!(when.to_string(), expected);
5425        }
5426    }
5427
5428    // ---- lowering (#418: when → engine vocabulary) ----
5429
5430    fn schedule_with(when: When, runs_on: RunsOn) -> Schedule {
5431        Schedule {
5432            id: "x".into(),
5433            when,
5434            job_id: "y".into(),
5435            // #917: validate() now rejects a target that dispatches
5436            // nothing, so the baseline helper carries the simplest
5437            // specified target.
5438            plan: FanoutPlan {
5439                target: Target {
5440                    all: true,
5441                    ..Target::default()
5442                },
5443                ..FanoutPlan::default()
5444            },
5445            active: Active::default(),
5446            constraints: Constraints::default(),
5447            on_failure: OnFailure::default(),
5448            tz: ScheduleTz::default(),
5449            starting_deadline: None,
5450            runs_on,
5451            enabled: true,
5452            tags: Vec::new(),
5453            origin: None,
5454        }
5455    }
5456
5457    fn calendar(at: &str, days: &[&str]) -> When {
5458        When::Calendar(CalendarSpec {
5459            at: at.into(),
5460            days: days.iter().map(|d| (*d).to_string()).collect(),
5461        })
5462    }
5463
5464    #[test]
5465    fn next_calendar_fire_returns_next_utc_occurrence() {
5466        use chrono::TimeZone;
5467        // Daily 09:00, evaluated in UTC. From 08:00 the same day, the
5468        // next strict occurrence is 09:00 that day.
5469        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5470        s.tz = ScheduleTz::Utc;
5471        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 8, 0, 0).unwrap();
5472        let next = s.next_calendar_fire(now).expect("calendar has a next fire");
5473        assert_eq!(
5474            next,
5475            chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap()
5476        );
5477    }
5478
5479    #[test]
5480    fn next_calendar_fire_is_strictly_after_now() {
5481        use chrono::TimeZone;
5482        // Standing exactly on a fire instant must preview the *next*
5483        // one (inclusive = false), not the one firing right now.
5484        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5485        s.tz = ScheduleTz::Utc;
5486        let on_fire = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap();
5487        let next = s
5488            .next_calendar_fire(on_fire)
5489            .expect("calendar has a next fire");
5490        assert_eq!(
5491            next,
5492            chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()
5493        );
5494    }
5495
5496    #[test]
5497    fn next_calendar_fire_none_for_reconcile_shapes() {
5498        // `per_pc` / `per_target` lower to the every-minute poll cron —
5499        // no discrete upcoming event to preview, so `None`.
5500        let now = chrono::Utc::now();
5501        for when in [
5502            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5503            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5504            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5505            When::PerTarget(PerPolicy::Every(EverySpec {
5506                every: "24h".into(),
5507            })),
5508        ] {
5509            let s = schedule_with(when, RunsOn::Backend);
5510            assert!(
5511                s.next_calendar_fire(now).is_none(),
5512                "reconcile shapes have no calendar fire",
5513            );
5514        }
5515    }
5516
5517    // ---- preview_fires (#418 dry-run / preview) ----
5518
5519    fn cal_utc(at: &str, days: &[&str]) -> Schedule {
5520        let mut s = schedule_with(calendar(at, days), RunsOn::Backend);
5521        s.tz = ScheduleTz::Utc; // host-independent assertions
5522        s
5523    }
5524
5525    #[test]
5526    fn preview_lists_next_calendar_occurrences() {
5527        use chrono::TimeZone;
5528        // Weekday 09:00, from Wed 2026-06-10 00:00 UTC: the next five
5529        // fires skip the weekend (Sat 13 / Sun 14).
5530        let s = cal_utc("09:00", &["mon-fri"]);
5531        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5532        let got = s.preview_fires(now, 5);
5533        let want: Vec<_> = [
5534            (2026, 6, 10), // Wed
5535            (2026, 6, 11), // Thu
5536            (2026, 6, 12), // Fri
5537            (2026, 6, 15), // Mon (skips Sat 13 / Sun 14)
5538            (2026, 6, 16), // Tue
5539        ]
5540        .iter()
5541        .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
5542        .collect();
5543        assert_eq!(got, want);
5544    }
5545
5546    #[test]
5547    fn preview_handles_nth_and_last_weekday() {
5548        use chrono::TimeZone;
5549        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
5550        // 2nd Tuesday (Patch Tuesday): Jun 9, Jul 14 2026.
5551        let nth = cal_utc("09:00", &["tue#2"]).preview_fires(now, 2);
5552        assert_eq!(
5553            nth,
5554            vec![
5555                chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap(),
5556                chrono::Utc.with_ymd_and_hms(2026, 7, 14, 9, 0, 0).unwrap(),
5557            ]
5558        );
5559        // Last Friday of the month: Jun 26, Jul 31 2026.
5560        let last = cal_utc("22:00", &["friL"]).preview_fires(now, 2);
5561        assert_eq!(
5562            last,
5563            vec![
5564                chrono::Utc.with_ymd_and_hms(2026, 6, 26, 22, 0, 0).unwrap(),
5565                chrono::Utc.with_ymd_and_hms(2026, 7, 31, 22, 0, 0).unwrap(),
5566            ]
5567        );
5568    }
5569
5570    #[test]
5571    fn preview_is_empty_for_reconcile_and_zero_count() {
5572        let now = chrono::Utc::now();
5573        // reconcile shapes have no discrete fire times
5574        let recon = schedule_with(
5575            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5576            RunsOn::Backend,
5577        );
5578        assert!(recon.preview_fires(now, 5).is_empty());
5579        // count == 0 yields nothing even for a calendar
5580        assert!(cal_utc("09:00", &[]).preview_fires(now, 0).is_empty());
5581    }
5582
5583    #[test]
5584    fn preview_skips_outside_active_window() {
5585        use chrono::TimeZone;
5586        // Daily 09:00, active only [2026-06-15, 2026-06-17). Occurrences
5587        // before `from` are skipped; `until` is exclusive, so 06-17's
5588        // fire is out — leaving exactly the 15th and 16th.
5589        let mut s = cal_utc("09:00", &[]);
5590        s.active = Active {
5591            from: Some("2026-06-15".into()),
5592            until: Some("2026-06-17".into()),
5593        };
5594        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5595        let got = s.preview_fires(now, 5);
5596        assert_eq!(
5597            got,
5598            vec![
5599                chrono::Utc.with_ymd_and_hms(2026, 6, 15, 9, 0, 0).unwrap(),
5600                chrono::Utc.with_ymd_and_hms(2026, 6, 16, 9, 0, 0).unwrap(),
5601            ]
5602        );
5603    }
5604
5605    #[test]
5606    fn preview_empty_when_calendar_time_outside_window() {
5607        use chrono::TimeZone;
5608        // Fires at 09:00 but the maintenance window is overnight — it can
5609        // never run, so the preview is empty (matches
5610        // `calendar_outside_window`), and the scan still terminates.
5611        let mut s = cal_utc("09:00", &[]);
5612        s.constraints = Constraints {
5613            window: Some("22:00-05:00".into()),
5614            ..Constraints::default()
5615        };
5616        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5617        assert!(s.preview_fires(now, 5).is_empty());
5618        // Every candidate tick is rejected, so this also exercises the
5619        // SCAN_CAP bound: a large `count` must still terminate (and
5620        // return empty) rather than spin (claude #578 review).
5621        assert!(s.preview_fires(now, 50).is_empty());
5622    }
5623
5624    #[test]
5625    fn preview_past_one_shot_is_empty() {
5626        use chrono::TimeZone;
5627        // A dated one-shot whose instant has passed never fires again.
5628        let s = cal_utc("2026-06-10 09:00", &[]);
5629        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 0, 0, 0).unwrap();
5630        assert!(s.preview_fires(now, 5).is_empty());
5631        // …but from before it, the single future fire shows up.
5632        let before = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
5633        assert_eq!(
5634            s.preview_fires(before, 5),
5635            vec![chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()]
5636        );
5637    }
5638
5639    #[test]
5640    fn lowering_matches_the_418_table() {
5641        let cases = [
5642            (
5643                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5644                (POLL_CRON, ExecMode::OncePerPc, None),
5645            ),
5646            (
5647                When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5648                (POLL_CRON, ExecMode::OncePerPc, Some("6h")),
5649            ),
5650            (
5651                When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5652                (POLL_CRON, ExecMode::OncePerTarget, None),
5653            ),
5654            (
5655                When::PerTarget(PerPolicy::Every(EverySpec {
5656                    every: "24h".into(),
5657                })),
5658                (POLL_CRON, ExecMode::OncePerTarget, Some("24h")),
5659            ),
5660            // calendar repeating → 6-field cron
5661            (
5662                calendar("09:00", &["mon-fri"]),
5663                ("0 0 9 * * mon-fri", ExecMode::EveryTick, None),
5664            ),
5665            // calendar daily (no days) → DOW *
5666            (
5667                calendar("18:30", &[]),
5668                ("0 30 18 * * *", ExecMode::EveryTick, None),
5669            ),
5670            // calendar one-shot → 7-field year cron
5671            (
5672                calendar("2026-06-10 09:00", &[]),
5673                ("0 0 9 10 6 * 2026", ExecMode::EveryTick, None),
5674            ),
5675        ];
5676        for (when, (cron, mode, cooldown)) in cases {
5677            let l = schedule_with(when.clone(), RunsOn::Backend).lowered();
5678            assert_eq!(l.cron, cron, "cron for {when}");
5679            assert_eq!(l.mode, mode, "mode for {when}");
5680            assert_eq!(l.cooldown.as_deref(), cooldown, "cooldown for {when}");
5681        }
5682    }
5683
5684    #[test]
5685    fn lowered_carries_schedule_tz() {
5686        for (tz, want) in [
5687            (ScheduleTz::Local, ScheduleTz::Local),
5688            (ScheduleTz::Utc, ScheduleTz::Utc),
5689        ] {
5690            let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
5691            s.tz = tz;
5692            assert_eq!(s.lowered().tz, want, "calendar carries tz");
5693            // reconcile shapes carry tz too (for the active-window check)
5694            let mut s = schedule_with(
5695                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5696                RunsOn::Backend,
5697            );
5698            s.tz = tz;
5699            assert_eq!(s.lowered().tz, want, "reconcile carries tz");
5700        }
5701    }
5702
5703    #[test]
5704    fn poll_cron_is_accepted_by_the_engine_parser() {
5705        // POLL_CRON is system-generated — if the engine's parser
5706        // ever rejected it every reconcile schedule would die at
5707        // register time. Validate it with the same croner config
5708        // (Seconds::Required, dom_and_dow, year optional).
5709        croner::parser::CronParser::builder()
5710            .seconds(croner::parser::Seconds::Required)
5711            .dom_and_dow(true)
5712            .build()
5713            .parse(POLL_CRON)
5714            .expect("POLL_CRON must parse");
5715    }
5716
5717    // ---- Schedule::validate() (#418 decision F) ----
5718
5719    #[test]
5720    fn validate_accepts_reconcile_shapes() {
5721        for when in [
5722            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5723            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5724            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5725            When::PerTarget(PerPolicy::Every(EverySpec {
5726                every: "24h".into(),
5727            })),
5728        ] {
5729            schedule_with(when.clone(), RunsOn::Backend)
5730                .validate()
5731                .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
5732        }
5733    }
5734
5735    #[test]
5736    fn validate_accepts_per_pc_on_agent() {
5737        schedule_with(
5738            When::PerPc(PerPolicy::Every(EverySpec { every: "1h".into() })),
5739            RunsOn::Agent,
5740        )
5741        .validate()
5742        .expect("per_pc + agent is the offline-inventory shape");
5743    }
5744
5745    // ---- #418 event triggers (when: { on }) ----
5746
5747    #[test]
5748    fn validate_accepts_event_on_agent() {
5749        for triggers in [
5750            vec![OnTrigger::Startup],
5751            vec![OnTrigger::Logon],
5752            vec![OnTrigger::Lock],
5753            vec![OnTrigger::Unlock],
5754            vec![OnTrigger::NetworkChange],
5755            vec![
5756                OnTrigger::Startup,
5757                OnTrigger::Logon,
5758                OnTrigger::Lock,
5759                OnTrigger::Unlock,
5760                OnTrigger::NetworkChange,
5761            ],
5762        ] {
5763            schedule_with(When::On(triggers), RunsOn::Agent)
5764                .validate()
5765                .expect("when.on is valid on runs_on: agent");
5766        }
5767    }
5768
5769    #[test]
5770    fn validate_rejects_event_on_backend() {
5771        let err = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Backend)
5772            .validate()
5773            .unwrap_err();
5774        assert!(err.contains("when.on"), "got: {err}");
5775        assert!(err.contains("runs_on: agent"), "got: {err}");
5776    }
5777
5778    #[test]
5779    fn validate_rejects_empty_event_list() {
5780        let err = schedule_with(When::On(vec![]), RunsOn::Agent)
5781            .validate()
5782            .unwrap_err();
5783        assert!(err.contains("when.on"), "got: {err}");
5784        assert!(err.contains("at least one"), "got: {err}");
5785    }
5786
5787    #[test]
5788    fn event_schedule_lowers_to_event_mode_and_is_event() {
5789        let s = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Agent);
5790        assert!(s.is_event());
5791        assert_eq!(s.lowered().mode, ExecMode::Event);
5792        assert_eq!(s.event_triggers(), &[OnTrigger::Startup]);
5793        // non-event schedules report no triggers.
5794        let cal = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5795        assert!(!cal.is_event());
5796        assert!(cal.event_triggers().is_empty());
5797    }
5798
5799    // ---- #418 constraints.require (env gates) ----
5800
5801    fn require_schedule(req: Require, runs_on: RunsOn) -> Schedule {
5802        let mut s = schedule_with(
5803            When::PerPc(PerPolicy::Every(EverySpec { every: "1m".into() })),
5804            runs_on,
5805        );
5806        s.constraints.require = Some(req);
5807        s
5808    }
5809
5810    #[test]
5811    fn require_met_combinations() {
5812        use std::time::Duration;
5813        let idle = |m: u64| Some(Duration::from_secs(m * 60));
5814        // Builder for the sensed state: (ac, idle, cpu, network).
5815        let env = |ac, idle, cpu, net| EnvState {
5816            ac_online: ac,
5817            idle,
5818            cpu_pct: cpu,
5819            network_up: net,
5820        };
5821        // Empty require — always met regardless of sensed state.
5822        assert!(require_met(
5823            &Require::default(),
5824            &env(false, None, None, false)
5825        ));
5826        // ac_power: only on AC.
5827        let ac = Require {
5828            ac_power: true,
5829            ..Default::default()
5830        };
5831        assert!(!require_met(&ac, &env(false, None, None, true)));
5832        assert!(require_met(&ac, &env(true, None, None, false)));
5833        // idle: needs >= the configured min; None idle never satisfies.
5834        let idle10 = Require {
5835            idle: Some("10m".into()),
5836            ..Default::default()
5837        };
5838        assert!(!require_met(&idle10, &env(true, None, None, true)));
5839        assert!(!require_met(&idle10, &env(true, idle(5), None, true)));
5840        assert!(require_met(&idle10, &env(true, idle(15), None, true)));
5841        assert!(require_met(&idle10, &env(true, idle(10), None, true))); // boundary inclusive
5842        // cpu_below: needs CPU strictly < threshold; None cpu never satisfies.
5843        let cpu20 = Require {
5844            cpu_below: Some(20.0),
5845            ..Default::default()
5846        };
5847        assert!(!require_met(&cpu20, &env(true, None, None, true))); // no sample → fail-closed
5848        assert!(!require_met(&cpu20, &env(true, None, Some(20.0), true))); // == threshold
5849        assert!(!require_met(&cpu20, &env(true, None, Some(55.0), true))); // busy
5850        assert!(require_met(&cpu20, &env(true, None, Some(5.0), true))); // quiet
5851        // network: only when online.
5852        let net = Require {
5853            network: true,
5854            ..Default::default()
5855        };
5856        assert!(!require_met(&net, &env(true, None, None, false))); // offline
5857        assert!(require_met(&net, &env(true, None, None, true))); // online
5858        // all four: AND.
5859        let all = Require {
5860            ac_power: true,
5861            idle: Some("10m".into()),
5862            cpu_below: Some(20.0),
5863            network: true,
5864        };
5865        assert!(!require_met(&all, &env(false, idle(20), Some(5.0), true))); // on battery
5866        assert!(!require_met(&all, &env(true, idle(1), Some(5.0), true))); // not idle enough
5867        assert!(!require_met(&all, &env(true, idle(20), Some(50.0), true))); // busy
5868        assert!(!require_met(&all, &env(true, idle(20), Some(5.0), false))); // offline
5869        assert!(require_met(&all, &env(true, idle(20), Some(5.0), true)));
5870        // An unparseable idle is treated as no-requirement by require_met
5871        // (validate rejects it at create time, so this only guards a
5872        // hand-edited blob): ac still gates.
5873        let bad = Require {
5874            ac_power: true,
5875            idle: Some("garbage".into()),
5876            ..Default::default()
5877        };
5878        assert!(require_met(&bad, &env(true, None, None, true)));
5879        assert!(!require_met(&bad, &env(false, None, None, true)));
5880    }
5881
5882    #[test]
5883    fn validate_accepts_and_rejects_cpu_below() {
5884        // In-range accepted.
5885        require_schedule(
5886            Require {
5887                cpu_below: Some(20.0),
5888                ..Default::default()
5889            },
5890            RunsOn::Agent,
5891        )
5892        .validate()
5893        .expect("cpu_below 20 is valid");
5894        // Upper boundary: 100.0 is accepted (fires unless CPU is exactly
5895        // 100%). Pins the inclusive upper bound against a future c < 100.0.
5896        require_schedule(
5897            Require {
5898                cpu_below: Some(100.0),
5899                ..Default::default()
5900            },
5901            RunsOn::Agent,
5902        )
5903        .validate()
5904        .expect("cpu_below 100 is valid");
5905        // Out of range rejected (0 and >100).
5906        for bad in [0.0, -5.0, 100.1] {
5907            let err = require_schedule(
5908                Require {
5909                    cpu_below: Some(bad),
5910                    ..Default::default()
5911                },
5912                RunsOn::Agent,
5913            )
5914            .validate()
5915            .unwrap_err();
5916            assert!(
5917                err.contains("constraints.require.cpu_below"),
5918                "cpu_below {bad}: {err}"
5919            );
5920        }
5921    }
5922
5923    #[test]
5924    fn validate_accepts_require_on_agent() {
5925        require_schedule(
5926            Require {
5927                ac_power: true,
5928                idle: Some("10m".into()),
5929                cpu_below: Some(20.0),
5930                network: true,
5931            },
5932            RunsOn::Agent,
5933        )
5934        .validate()
5935        .expect("constraints.require is valid on runs_on: agent");
5936    }
5937
5938    #[test]
5939    fn validate_rejects_require_on_backend() {
5940        let err = require_schedule(
5941            Require {
5942                ac_power: true,
5943                ..Default::default()
5944            },
5945            RunsOn::Backend,
5946        )
5947        .validate()
5948        .unwrap_err();
5949        assert!(err.contains("constraints.require"), "got: {err}");
5950        assert!(err.contains("runs_on: agent"), "got: {err}");
5951
5952        // An idle-only require (ac_power: false) is also non-empty
5953        // (is_empty folds the fields) and must reject on backend too —
5954        // guards against a regression in Require::is_empty.
5955        let err = require_schedule(
5956            Require {
5957                idle: Some("10m".into()),
5958                ..Default::default()
5959            },
5960            RunsOn::Backend,
5961        )
5962        .validate()
5963        .unwrap_err();
5964        assert!(
5965            err.contains("constraints.require"),
5966            "idle-only on backend: {err}"
5967        );
5968    }
5969
5970    #[test]
5971    fn validate_rejects_bad_require_idle() {
5972        let err = require_schedule(
5973            Require {
5974                idle: Some("not-a-duration".into()),
5975                ..Default::default()
5976            },
5977            RunsOn::Agent,
5978        )
5979        .validate()
5980        .unwrap_err();
5981        assert!(err.contains("constraints.require.idle"), "got: {err}");
5982    }
5983
5984    #[test]
5985    fn require_round_trips_and_skips_empty() {
5986        // ac_power: false is skipped; an all-default require nested in
5987        // constraints is omitted (is_empty folds it in).
5988        let yaml = "id: s\nwhen: { per_pc: { every: 1m } }\njob_id: j\nruns_on: agent\n\
5989                    constraints: { require: { ac_power: true, idle: 10m, cpu_below: 20, \
5990                    network: true } }\n";
5991        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5992        let req = s.constraints.require.as_ref().expect("require present");
5993        assert!(req.ac_power);
5994        assert_eq!(req.idle.as_deref(), Some("10m"));
5995        assert_eq!(req.cpu_below, Some(20.0));
5996        assert!(req.network);
5997        // Re-serialize: idle + cpu_below + network present, ac_power true.
5998        let back = serde_json::to_string(&s.constraints).unwrap();
5999        assert!(back.contains("\"idle\":\"10m\""), "got: {back}");
6000        assert!(back.contains("\"cpu_below\":20"), "got: {back}");
6001        assert!(back.contains("\"network\":true"), "got: {back}");
6002        // An empty require is omitted entirely by is_empty.
6003        let mut empty = s.clone();
6004        empty.constraints.require = Some(Require::default());
6005        assert!(empty.constraints.is_empty());
6006    }
6007
6008    #[test]
6009    fn validate_rejects_per_target_on_agent() {
6010        let err = schedule_with(
6011            When::PerTarget(PerPolicy::Every(EverySpec {
6012                every: "24h".into(),
6013            })),
6014            RunsOn::Agent,
6015        )
6016        .validate()
6017        .unwrap_err();
6018        assert!(err.contains("per_target"), "got: {err}");
6019        assert!(err.contains("runs_on: agent"), "got: {err}");
6020
6021        // per_target: once is also backend-only.
6022        let err = schedule_with(
6023            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
6024            RunsOn::Agent,
6025        )
6026        .validate()
6027        .unwrap_err();
6028        assert!(err.contains("per_target"), "got (once): {err}");
6029        assert!(err.contains("runs_on: agent"), "got (once): {err}");
6030    }
6031
6032    #[test]
6033    fn validate_rejects_bad_every_duration() {
6034        let err = schedule_with(
6035            When::PerPc(PerPolicy::Every(EverySpec { every: "6x".into() })),
6036            RunsOn::Backend,
6037        )
6038        .validate()
6039        .unwrap_err();
6040        assert!(err.contains("when.every"), "got: {err}");
6041    }
6042
6043    #[test]
6044    fn validate_rejects_bad_jitter_and_starting_deadline() {
6045        let mut s = schedule_with(
6046            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6047            RunsOn::Backend,
6048        );
6049        s.plan.jitter = Some("5x".into());
6050        let err = s.validate().unwrap_err();
6051        assert!(err.contains("jitter"), "got: {err}");
6052
6053        let mut s = schedule_with(
6054            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6055            RunsOn::Backend,
6056        );
6057        s.starting_deadline = Some("soon".into());
6058        let err = s.validate().unwrap_err();
6059        assert!(err.contains("starting_deadline"), "got: {err}");
6060    }
6061
6062    #[test]
6063    fn validate_rejects_unspecified_target() {
6064        // #917 (1): an all-default target never dispatches anywhere —
6065        // runs_on: agent silently never fires, runs_on: backend
6066        // warn-fails every tick at the exec boundary. Both rejected.
6067        for runs_on in [RunsOn::Backend, RunsOn::Agent] {
6068            let mut s = schedule_with(When::PerPc(PerPolicy::Once(OnceLiteral::Once)), runs_on);
6069            s.plan.target = Target::default();
6070            let err = s.validate().unwrap_err();
6071            assert!(err.contains("target"), "for {runs_on:?}, got: {err}");
6072        }
6073    }
6074
6075    /// A Schedule with every top-level field populated so each one
6076    /// actually serialises (the optional ones are `skip_serializing_if`).
6077    fn fully_populated_schedule() -> Schedule {
6078        let mut s = schedule_with(
6079            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6080            RunsOn::Backend,
6081        );
6082        s.plan.rollout = Some(Rollout {
6083            strategy: RolloutStrategy::Wave,
6084            waves: vec![Wave {
6085                group: "canary".into(),
6086                delay: "0s".into(),
6087            }],
6088        });
6089        s.plan.jitter = Some("5m".into());
6090        s.plan.deadline_at = Some(chrono::Utc::now());
6091        s.active = Active {
6092            from: Some("2026-01-01 00:00".into()),
6093            until: Some("2026-12-31 00:00".into()),
6094        };
6095        s.constraints = Constraints {
6096            window: Some("09:00-17:00".into()),
6097            ..Constraints::default()
6098        };
6099        s.on_failure = OnFailure {
6100            retry: Some(Retry {
6101                max: 1,
6102                backoff: "10s".into(),
6103            }),
6104        };
6105        s.starting_deadline = Some("30m".into());
6106        s.tags = vec!["health".into()];
6107        s.origin = Some(RepoOrigin {
6108            path: "configs/schedules/x.yaml".into(),
6109            repo: None,
6110            script_file: None,
6111        });
6112        s
6113    }
6114
6115    #[test]
6116    fn schedule_top_level_keys_cover_serialized_fields() {
6117        // #924 drift guard: the hand-maintained TOP_LEVEL_KEYS list must
6118        // match exactly what a fully-populated Schedule serialises — so a
6119        // future field added to Schedule or FanoutPlan can't slip past
6120        // the flatten-aware strict guard by being forgotten here.
6121        let s = fully_populated_schedule();
6122        let value = serde_json::to_value(&s).expect("serialize schedule");
6123        let serialized: std::collections::BTreeSet<String> = value
6124            .as_object()
6125            .expect("schedule serialises to an object")
6126            .keys()
6127            .cloned()
6128            .collect();
6129        let listed: std::collections::BTreeSet<String> = Schedule::TOP_LEVEL_KEYS
6130            .iter()
6131            .map(|s| s.to_string())
6132            .collect();
6133        assert_eq!(
6134            serialized, listed,
6135            "TOP_LEVEL_KEYS is out of sync with Schedule's serialized fields \
6136             (flatten-aware strict guard would miss a real field or reject a valid one)"
6137        );
6138    }
6139
6140    #[test]
6141    fn strict_rejects_flatten_hidden_top_level_typo() {
6142        // #924: a top-level typo on a flattening type (jiter / enabledd)
6143        // is buffered into the flatten target by serde and hidden from
6144        // serde_ignored — the top-level guard must catch it. Verified on
6145        // both the YAML and JSON strict boundaries.
6146        let yaml = "\
6147id: s1
6148job_id: j1
6149when:
6150  per_pc: once
6151target:
6152  all: true
6153jiter: 5m
6154";
6155        let err = crate::strict::from_yaml_str::<Schedule>(yaml).unwrap_err();
6156        assert!(err.contains("jiter"), "got: {err}");
6157
6158        let json = serde_json::json!({
6159            "id": "s1",
6160            "job_id": "j1",
6161            "when": { "per_pc": "once" },
6162            "target": { "all": true },
6163            "enabledd": false,
6164        });
6165        let err = crate::strict::from_json_slice::<Schedule>(&serde_json::to_vec(&json).unwrap())
6166            .unwrap_err();
6167        assert!(err.contains("enabledd"), "got: {err}");
6168    }
6169
6170    #[test]
6171    fn strict_accepts_all_valid_schedule_top_level_keys() {
6172        // The guard must not reject any legitimate key — round-trip a
6173        // fully-populated schedule through the strict YAML boundary.
6174        let s = fully_populated_schedule();
6175        let yaml = serde_yaml::to_string(&s).expect("serialize");
6176        crate::strict::from_yaml_str::<Schedule>(&yaml)
6177            .expect("every serialized key must be accepted by the strict guard");
6178    }
6179
6180    #[test]
6181    fn strict_rejects_non_string_top_level_yaml_key() {
6182        // #924 (gemini #945): a YAML key isn't always a string — an
6183        // unquoted `true:` parses as a boolean, `123:` as a number. A
6184        // `filter_map` on `as_str()` would drop these and let them slip
6185        // past the flatten guard; `yaml_key_label` renders them so they
6186        // are still rejected. (serde_yaml is YAML 1.2, so `on:` stays a
6187        // *string* "on" — also rejected, just via the string path.)
6188        let base = "\
6189id: s1
6190job_id: j1
6191when:
6192  per_pc: once
6193target:
6194  all: true
6195";
6196        for (extra, needle) in [
6197            ("true: x\n", "true"),
6198            ("123: x\n", "123"),
6199            ("on: y\n", "on"),
6200        ] {
6201            let yaml = format!("{base}{extra}");
6202            let err = crate::strict::from_yaml_str::<Schedule>(&yaml).unwrap_err();
6203            assert!(err.contains(needle), "for '{extra}', got: {err}");
6204        }
6205    }
6206
6207    #[test]
6208    fn validate_accepts_waves_instead_of_target_on_backend() {
6209        // #917 (1): the exec boundary accepts rollout-only plans
6210        // (target then just labels the audit row) — so does validate.
6211        let mut s = schedule_with(
6212            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6213            RunsOn::Backend,
6214        );
6215        s.plan.target = Target::default();
6216        s.plan.rollout = Some(Rollout {
6217            strategy: RolloutStrategy::Wave,
6218            waves: vec![Wave {
6219                group: "canary".into(),
6220                delay: "0s".into(),
6221            }],
6222        });
6223        s.validate().expect("rollout-only plan should validate");
6224    }
6225
6226    #[test]
6227    fn validate_rejects_rollout_on_agent() {
6228        // #917 (1): rollout waves are backend-published; a runs_on:
6229        // agent schedule never reads them, so the combination is a
6230        // silent no-op — reject like max_concurrent-on-agent.
6231        let mut s = schedule_with(
6232            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6233            RunsOn::Agent,
6234        );
6235        s.plan.rollout = Some(Rollout {
6236            strategy: RolloutStrategy::Wave,
6237            waves: vec![Wave {
6238                group: "canary".into(),
6239                delay: "0s".into(),
6240            }],
6241        });
6242        let err = s.validate().unwrap_err();
6243        assert!(err.contains("rollout"), "got: {err}");
6244    }
6245
6246    #[test]
6247    fn validate_rejects_bad_waves() {
6248        // #917 (2): empty waves, blank group, unparseable delay — all
6249        // previously accepted and failed (or no-opped) at every fire.
6250        let base = || {
6251            schedule_with(
6252                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6253                RunsOn::Backend,
6254            )
6255        };
6256
6257        let mut s = base();
6258        s.plan.rollout = Some(Rollout {
6259            strategy: RolloutStrategy::Wave,
6260            waves: vec![],
6261        });
6262        let err = s.validate().unwrap_err();
6263        assert!(err.contains("at least one wave"), "got: {err}");
6264
6265        let mut s = base();
6266        s.plan.rollout = Some(Rollout {
6267            strategy: RolloutStrategy::Wave,
6268            waves: vec![Wave {
6269                group: "  ".into(),
6270                delay: "0s".into(),
6271            }],
6272        });
6273        let err = s.validate().unwrap_err();
6274        assert!(err.contains("waves[0].group"), "got: {err}");
6275
6276        let mut s = base();
6277        s.plan.rollout = Some(Rollout {
6278            strategy: RolloutStrategy::Wave,
6279            waves: vec![
6280                Wave {
6281                    group: "canary".into(),
6282                    delay: "0s".into(),
6283                },
6284                Wave {
6285                    group: "wave1".into(),
6286                    delay: "5 minuts".into(),
6287                },
6288            ],
6289        });
6290        let err = s.validate().unwrap_err();
6291        assert!(err.contains("waves[1].delay"), "got: {err}");
6292    }
6293
6294    #[test]
6295    fn validate_rejects_wave_delay_at_or_past_starting_deadline() {
6296        // #917 (3): the deadline is stamped once at tick time, so a
6297        // wave sleeping >= starting_deadline publishes already-expired
6298        // Commands — dead on arrival, every fire.
6299        let mut s = schedule_with(
6300            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6301            RunsOn::Backend,
6302        );
6303        s.starting_deadline = Some("30m".into());
6304        s.plan.rollout = Some(Rollout {
6305            strategy: RolloutStrategy::Wave,
6306            waves: vec![
6307                Wave {
6308                    group: "canary".into(),
6309                    delay: "0s".into(),
6310                },
6311                Wave {
6312                    group: "wave1".into(),
6313                    delay: "30m".into(),
6314                },
6315            ],
6316        });
6317        let err = s.validate().unwrap_err();
6318        assert!(
6319            err.contains("waves[1].delay") && err.contains("starting_deadline"),
6320            "got: {err}"
6321        );
6322
6323        // Strictly shorter is fine.
6324        s.plan.rollout.as_mut().unwrap().waves[1].delay = "29m".into();
6325        s.validate().expect("delay < deadline should validate");
6326    }
6327
6328    #[test]
6329    fn validate_rejects_operator_set_deadline_at() {
6330        // #917 (4): machine-stamped field — the scheduler overwrites it
6331        // on every fire, so a hand-set value is silently discarded.
6332        let mut s = schedule_with(
6333            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6334            RunsOn::Backend,
6335        );
6336        s.plan.deadline_at = Some(chrono::Utc::now());
6337        let err = s.validate().unwrap_err();
6338        assert!(
6339            err.contains("deadline_at") && err.contains("starting_deadline"),
6340            "got: {err}"
6341        );
6342    }
6343
6344    #[test]
6345    fn validate_accepts_calendar_shapes() {
6346        for when in [
6347            calendar("09:00", &["mon-fri"]),   // weekday morning
6348            calendar("00:00", &["sun"]),       // weekly
6349            calendar("18:30", &[]),            // daily
6350            calendar("2026-06-10 09:00", &[]), // one-shot
6351            calendar("2026/12/25 00:00", &[]), // one-shot, slash form
6352        ] {
6353            schedule_with(when.clone(), RunsOn::Backend)
6354                .validate()
6355                .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
6356        }
6357    }
6358
6359    #[test]
6360    fn validate_rejects_bad_at() {
6361        for bad in ["25:00", "09:60", "9", "noon", "2026-13-01 09:00"] {
6362            let err = schedule_with(calendar(bad, &[]), RunsOn::Backend)
6363                .validate()
6364                .unwrap_err();
6365            assert!(err.contains("when.at"), "for '{bad}', got: {err}");
6366        }
6367    }
6368
6369    #[test]
6370    fn validate_rejects_datetime_at_with_days() {
6371        // A dated `at` is a one-shot — pairing it with days is a
6372        // contradiction (the date already pins the day).
6373        let err = schedule_with(calendar("2026-06-10 09:00", &["mon"]), RunsOn::Backend)
6374            .validate()
6375            .unwrap_err();
6376        assert!(
6377            err.contains("one-shot") && err.contains("days"),
6378            "got: {err}"
6379        );
6380    }
6381
6382    #[test]
6383    fn validate_rejects_bad_day_name() {
6384        // A garbage DOW token is caught by the days pre-flight and
6385        // reported against `when.days`, not the confusing
6386        // "when.at lowered to invalid cron" (claude #432 review).
6387        let err = schedule_with(calendar("09:00", &["funday"]), RunsOn::Backend)
6388            .validate()
6389            .unwrap_err();
6390        assert!(err.contains("when.days"), "got: {err}");
6391        assert!(err.contains("funday"), "names the bad token: {err}");
6392        // a degenerate range like `mon-` reports the whole token, not
6393        // a cryptic empty part (claude #432 follow-up)
6394        let err = schedule_with(calendar("09:00", &["mon-"]), RunsOn::Backend)
6395            .validate()
6396            .unwrap_err();
6397        assert!(err.contains("'mon-'"), "names the whole token: {err}");
6398        // valid names / ranges / numeric / * all pass
6399        for ok in [
6400            calendar("09:00", &["mon-fri"]),
6401            calendar("09:00", &["mon", "wed", "sun"]),
6402            calendar("09:00", &["1-5"]),
6403        ] {
6404            schedule_with(ok.clone(), RunsOn::Backend)
6405                .validate()
6406                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6407        }
6408    }
6409
6410    #[test]
6411    fn validate_accepts_nth_weekday() {
6412        // #418: nth-weekday (Patch Tuesday). validate() also lowers to
6413        // a cron and parses it with croner, so passing here proves the
6414        // whole chain — token → DOW field → engine-acceptable cron.
6415        for ok in [
6416            calendar("09:00", &["tue#2"]),          // 2nd Tuesday
6417            calendar("09:00", &["fri#1"]),          // 1st Friday
6418            calendar("03:00", &["sun#5"]),          // 5th Sunday
6419            calendar("09:00", &["tue#2", "thu#2"]), // a list of nths
6420            calendar("09:00", &["2#2"]),            // numeric DOW + ordinal
6421            // Case-insensitive both sides: validate lowercases, croner
6422            // upper-cases the whole pattern before aliasing (claude #547).
6423            calendar("09:00", &["TUE#2"]),
6424        ] {
6425            schedule_with(ok.clone(), RunsOn::Backend)
6426                .validate()
6427                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6428        }
6429    }
6430
6431    #[test]
6432    fn validate_rejects_bad_nth_weekday() {
6433        // ordinal out of 1..5, a range with #, and a bad day before #.
6434        for bad in ["tue#0", "tue#6", "tue#x", "mon-fri#2", "funday#2"] {
6435            let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
6436                .validate()
6437                .unwrap_err();
6438            assert!(err.contains("when.days"), "for '{bad}', got: {err}");
6439        }
6440    }
6441
6442    #[test]
6443    fn validate_accepts_last_weekday() {
6444        // #418: last-weekday (`friL` = last Friday). Like the nth case,
6445        // validate() lowers to a cron and round-trips it through croner,
6446        // so passing proves token → DOW field → engine-acceptable cron
6447        // with the verified last-<dow>-of-month semantics.
6448        for ok in [
6449            calendar("09:00", &["friL"]),         // last Friday
6450            calendar("03:00", &["sunL"]),         // last Sunday
6451            calendar("22:00", &["5L"]),           // numeric DOW + last
6452            calendar("00:00", &["0L"]),           // numeric Sunday (0…
6453            calendar("00:00", &["7L"]),           // …and its 7 alias)
6454            calendar("09:00", &["monL", "friL"]), // a list of last-weekdays
6455            // Case-insensitive both the weekday and the `L` suffix:
6456            // validate lowercases the day, croner upper-cases the whole
6457            // pattern before aliasing (claude #547).
6458            calendar("09:00", &["FRIL"]),
6459            calendar("09:00", &["fril"]),
6460        ] {
6461            schedule_with(ok.clone(), RunsOn::Backend)
6462                .validate()
6463                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6464        }
6465    }
6466
6467    #[test]
6468    fn validate_rejects_bad_last_weekday() {
6469        // bare `L` (no weekday — a footgun croner reads as Saturday), a
6470        // range with L, a bad day before L, and an internal space that
6471        // would otherwise leak a malformed cron downstream (gemini #560).
6472        for bad in ["L", "l", "mon-friL", "fundayL", "8L", "*L", "fri L"] {
6473            let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
6474                .validate()
6475                .unwrap_err();
6476            assert!(err.contains("when.days"), "for '{bad}', got: {err}");
6477        }
6478    }
6479
6480    #[test]
6481    fn calendar_oneshot_instant_detects_past() {
6482        use chrono::TimeZone;
6483        // a dated `at` resolves to an absolute instant…
6484        let c = CalendarSpec {
6485            at: "2024-01-01 09:00".into(),
6486            days: vec![],
6487        };
6488        let t = c
6489            .oneshot_instant(ScheduleTz::Utc)
6490            .expect("one-shot instant");
6491        assert_eq!(
6492            t,
6493            chrono::Utc.with_ymd_and_hms(2024, 1, 1, 9, 0, 0).unwrap()
6494        );
6495        assert!(t < chrono::Utc::now(), "2024 is in the past");
6496        // …while a repeating (time-only) calendar has no instant
6497        let rep = CalendarSpec {
6498            at: "09:00".into(),
6499            days: vec!["mon-fri".into()],
6500        };
6501        assert!(rep.oneshot_instant(ScheduleTz::Utc).is_none());
6502    }
6503
6504    fn schedule_with_active(from: Option<&str>, until: Option<&str>) -> Schedule {
6505        let mut s = schedule_with(
6506            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6507            RunsOn::Backend,
6508        );
6509        s.active = Active {
6510            from: from.map(str::to_owned),
6511            until: until.map(str::to_owned),
6512        };
6513        s
6514    }
6515
6516    #[test]
6517    fn validate_accepts_active_window() {
6518        schedule_with_active(Some("2026-07-01"), Some("2026-08-01T12:00:00+09:00"))
6519            .validate()
6520            .expect("date + rfc3339 bounds should validate");
6521    }
6522
6523    #[test]
6524    fn validate_rejects_unparseable_active_bound() {
6525        let err = schedule_with_active(Some("July 1st"), None)
6526            .validate()
6527            .unwrap_err();
6528        assert!(err.contains("active"), "got: {err}");
6529    }
6530
6531    #[test]
6532    fn validate_rejects_from_not_before_until() {
6533        let err = schedule_with_active(Some("2026-08-01"), Some("2026-07-01"))
6534            .validate()
6535            .unwrap_err();
6536        assert!(err.contains("strictly before"), "got: {err}");
6537
6538        let err = schedule_with_active(Some("2026-07-01"), Some("2026-07-01"))
6539            .validate()
6540            .unwrap_err();
6541        assert!(err.contains("strictly before"), "got: {err}");
6542    }
6543
6544    // ---- Active window semantics ----
6545
6546    #[test]
6547    fn active_window_is_half_open() {
6548        use chrono::TimeZone;
6549        let active = Active {
6550            from: Some("2026-07-01".into()),
6551            until: Some("2026-08-01".into()),
6552        };
6553        // UTC tz so the date bounds are UTC midnight.
6554        let at = |y, m, d, h| chrono::Utc.with_ymd_and_hms(y, m, d, h, 0, 0).unwrap();
6555        let c = |t| active.contains(t, ScheduleTz::Utc);
6556        assert!(!c(at(2026, 6, 30, 23)), "before from");
6557        assert!(c(at(2026, 7, 1, 0)), "at from (inclusive)");
6558        assert!(c(at(2026, 7, 15, 12)), "inside");
6559        assert!(!c(at(2026, 8, 1, 0)), "at until (exclusive)");
6560        assert!(!c(at(2026, 8, 2, 0)), "after until");
6561    }
6562
6563    #[test]
6564    fn active_empty_window_is_always_active() {
6565        assert!(Active::default().contains(chrono::Utc::now(), ScheduleTz::Local));
6566    }
6567
6568    #[test]
6569    fn active_rfc3339_bound_honours_offset_regardless_of_tz() {
6570        use chrono::TimeZone;
6571        let active = Active {
6572            from: Some("2026-07-01T09:00:00+09:00".into()),
6573            until: None,
6574        };
6575        // RFC3339 carries its own offset → tz arg is ignored.
6576        // 09:00 JST = 00:00 UTC.
6577        for tz in [ScheduleTz::Utc, ScheduleTz::Local] {
6578            assert!(
6579                !active.contains(
6580                    chrono::Utc
6581                        .with_ymd_and_hms(2026, 6, 30, 23, 59, 0)
6582                        .unwrap(),
6583                    tz
6584                )
6585            );
6586            assert!(active.contains(
6587                chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap(),
6588                tz
6589            ));
6590        }
6591    }
6592
6593    #[test]
6594    fn active_date_bound_respects_tz() {
6595        // A bare `YYYY-MM-DD` bound is midnight *in the schedule's
6596        // tz* (#418 Phase 2). The UTC interpretation is exact and
6597        // host-independent; assert that precisely.
6598        use chrono::TimeZone;
6599        let utc = Active::parse_bound("2026-07-01", ScheduleTz::Utc).expect("utc");
6600        assert_eq!(
6601            utc,
6602            chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap()
6603        );
6604
6605        // The local interpretation must equal what chrono::Local
6606        // computes for the same wall-clock midnight — proves the tz
6607        // path is wired to the host zone (the magnitude vs UTC is
6608        // host-dependent, so we compare against Local directly rather
6609        // than hard-coding the JST offset, keeping CI green on UTC
6610        // runners).
6611        let local = Active::parse_bound("2026-07-01", ScheduleTz::Local).expect("local");
6612        let want = chrono::Local
6613            .with_ymd_and_hms(2026, 7, 1, 0, 0, 0)
6614            .single()
6615            .expect("local midnight is unambiguous")
6616            .with_timezone(&chrono::Utc);
6617        assert_eq!(local, want, "date bound resolved in host-local tz");
6618    }
6619
6620    #[test]
6621    fn active_empty_is_skipped_when_serialising() {
6622        let s = schedule_with(
6623            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6624            RunsOn::Backend,
6625        );
6626        let json = serde_json::to_value(&s).expect("serialise");
6627        assert!(
6628            json.get("active").is_none(),
6629            "empty active must not appear on the wire: {json}"
6630        );
6631    }
6632
6633    // ---- constraints.window (#418 Phase 3) ----
6634
6635    fn with_window(win: &str) -> Schedule {
6636        let mut s = schedule_with(
6637            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6638            RunsOn::Backend,
6639        );
6640        s.constraints.window = Some(win.into());
6641        s
6642    }
6643
6644    #[test]
6645    fn constraints_window_parses_and_round_trips() {
6646        let yaml = r#"
6647id: x
6648when:
6649  per_pc: { every: 6h }
6650job_id: y
6651target: { all: true }
6652constraints:
6653  window: "22:00-05:00"
6654"#;
6655        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6656        assert_eq!(s.constraints.window.as_deref(), Some("22:00-05:00"));
6657        let back: Schedule =
6658            serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
6659        assert_eq!(back.constraints.window.as_deref(), Some("22:00-05:00"));
6660    }
6661
6662    #[test]
6663    fn constraints_empty_is_skipped_when_serialising() {
6664        let s = schedule_with(
6665            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6666            RunsOn::Backend,
6667        );
6668        let json = serde_json::to_value(&s).expect("serialise");
6669        assert!(
6670            json.get("constraints").is_none(),
6671            "empty constraints must not appear on the wire: {json}"
6672        );
6673    }
6674
6675    #[test]
6676    fn window_no_constraint_always_allows() {
6677        let c = Constraints::default();
6678        assert!(c.allows(chrono::Utc::now(), ScheduleTz::Local));
6679    }
6680
6681    #[test]
6682    fn window_same_day_is_half_open() {
6683        use chrono::TimeZone;
6684        let s = with_window("09:00-17:00");
6685        let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
6686        let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
6687        assert!(!a(at(8, 59)), "before start");
6688        assert!(a(at(9, 0)), "at start (inclusive)");
6689        assert!(a(at(16, 59)), "inside");
6690        assert!(!a(at(17, 0)), "at end (exclusive)");
6691        assert!(!a(at(23, 0)), "after end");
6692    }
6693
6694    #[test]
6695    fn window_crossing_midnight() {
6696        use chrono::TimeZone;
6697        let s = with_window("22:00-05:00");
6698        let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
6699        let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
6700        assert!(a(at(22, 0)), "at start tonight");
6701        assert!(a(at(23, 30)), "late tonight");
6702        assert!(a(at(3, 0)), "early tomorrow");
6703        assert!(!a(at(5, 0)), "at end (exclusive)");
6704        assert!(!a(at(12, 0)), "midday outside");
6705        assert!(!a(at(21, 59)), "just before start");
6706    }
6707
6708    #[test]
6709    fn window_respects_tz() {
6710        // The same instant is inside the window under one tz and may
6711        // be outside under another. Compare UTC vs Local via the
6712        // host's own offset (kept CI-green on UTC runners like the
6713        // active tz test does).
6714        use chrono::TimeZone;
6715        let s = with_window("09:00-17:00");
6716        let noon_utc = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 12, 0, 0).unwrap();
6717        // Under UTC, 12:00 is inside 09:00-17:00.
6718        assert!(s.constraints.allows(noon_utc, ScheduleTz::Utc));
6719        // Under Local, the verdict tracks the host wall-clock time;
6720        // assert it matches a direct wall_time membership check.
6721        let local_t = noon_utc.with_timezone(&chrono::Local).time();
6722        let in_local = local_t >= chrono::NaiveTime::from_hms_opt(9, 0, 0).unwrap()
6723            && local_t < chrono::NaiveTime::from_hms_opt(17, 0, 0).unwrap();
6724        assert_eq!(s.constraints.allows(noon_utc, ScheduleTz::Local), in_local);
6725    }
6726
6727    #[test]
6728    fn validate_accepts_good_window() {
6729        for w in ["09:00-17:00", "22:00-05:00", "00:00-23:59"] {
6730            with_window(w)
6731                .validate()
6732                .unwrap_or_else(|e| panic!("'{w}' should validate: {e}"));
6733        }
6734    }
6735
6736    #[test]
6737    fn validate_rejects_bad_window() {
6738        for bad in ["9-5", "22:00", "22:00-22:00", "25:00-05:00", "09:00_17:00"] {
6739            let err = with_window(bad).validate().unwrap_err();
6740            assert!(
6741                err.contains("constraints.window"),
6742                "for '{bad}', got: {err}"
6743            );
6744        }
6745    }
6746
6747    // ---- constraints.skip_dates (#418 holiday exclusion) ----
6748
6749    fn with_skip_dates(dates: &[&str]) -> Schedule {
6750        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
6751        s.tz = ScheduleTz::Utc; // host-independent date assertions
6752        s.constraints.skip_dates = dates.iter().map(|d| (*d).to_string()).collect();
6753        s
6754    }
6755
6756    #[test]
6757    fn allows_blocks_listed_skip_date() {
6758        use chrono::TimeZone;
6759        let s = with_skip_dates(&["2026-06-10", "2026-12-25"]);
6760        // Any time on a listed date is blocked (whole day).
6761        let on = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap();
6762        assert!(!s.constraints.allows(on, ScheduleTz::Utc));
6763        let on_midnight = chrono::Utc.with_ymd_and_hms(2026, 12, 25, 0, 0, 0).unwrap();
6764        assert!(!s.constraints.allows(on_midnight, ScheduleTz::Utc));
6765        // A date not in the list fires normally.
6766        let off = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
6767        assert!(s.constraints.allows(off, ScheduleTz::Utc));
6768    }
6769
6770    #[test]
6771    fn allows_corrupt_skip_date_fails_closed() {
6772        use chrono::TimeZone;
6773        // A garbled entry (only reachable via hand-edited KV) blocks
6774        // rather than silently re-enabling fires — same posture as a
6775        // corrupt window.
6776        let s = with_skip_dates(&["not-a-date"]);
6777        let any = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
6778        assert!(!s.constraints.allows(any, ScheduleTz::Utc));
6779    }
6780
6781    #[test]
6782    fn validate_accepts_good_skip_dates() {
6783        with_skip_dates(&["2026-01-01", "2026-12-25", "2027-05-03"])
6784            .validate()
6785            .expect("well-formed skip dates should validate");
6786    }
6787
6788    #[test]
6789    fn validate_rejects_bad_skip_date() {
6790        for bad in ["2026-13-01", "01-01-2026", "nope", "2026/01/01"] {
6791            let err = with_skip_dates(&[bad]).validate().unwrap_err();
6792            assert!(
6793                err.contains("constraints.skip_dates"),
6794                "for '{bad}', got: {err}"
6795            );
6796        }
6797    }
6798
6799    #[test]
6800    fn preview_skips_holidays() {
6801        use chrono::TimeZone;
6802        // Daily 09:00 with two of the next five days marked as holidays
6803        // — preview drops exactly those, since it gates on `allows`.
6804        let mut s = cal_utc("09:00", &[]);
6805        s.constraints.skip_dates = vec!["2026-06-11".into(), "2026-06-13".into()];
6806        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
6807        let got = s.preview_fires(now, 4);
6808        let want: Vec<_> = [
6809            (2026, 6, 10),
6810            (2026, 6, 12), // skips 06-11
6811            (2026, 6, 14), // skips 06-13
6812            (2026, 6, 15),
6813        ]
6814        .iter()
6815        .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
6816        .collect();
6817        assert_eq!(got, want);
6818    }
6819
6820    // ---- constraints.max_concurrent (#418) ----
6821
6822    fn with_max_concurrent(max: u32, runs_on: RunsOn) -> Schedule {
6823        let mut s = schedule_with(
6824            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6825            runs_on,
6826        );
6827        s.constraints.max_concurrent = Some(max);
6828        s
6829    }
6830
6831    #[test]
6832    fn validate_accepts_backend_max_concurrent() {
6833        with_max_concurrent(5, RunsOn::Backend)
6834            .validate()
6835            .expect("backend max_concurrent should validate");
6836    }
6837
6838    #[test]
6839    fn validate_rejects_max_concurrent_on_agent() {
6840        // Decision E: a central running-instance cap needs a central
6841        // counter, which agents don't have.
6842        let err = with_max_concurrent(5, RunsOn::Agent)
6843            .validate()
6844            .unwrap_err();
6845        assert!(err.contains("constraints.max_concurrent"), "got: {err}");
6846        assert!(err.contains("runs_on: agent"), "got: {err}");
6847    }
6848
6849    #[test]
6850    fn validate_rejects_zero_max_concurrent() {
6851        let err = with_max_concurrent(0, RunsOn::Backend)
6852            .validate()
6853            .unwrap_err();
6854        assert!(err.contains("max_concurrent must be >= 1"), "got: {err}");
6855    }
6856
6857    #[test]
6858    fn max_concurrent_round_trips_and_skips_when_absent() {
6859        let s = with_max_concurrent(3, RunsOn::Backend);
6860        let json = serde_json::to_value(&s.constraints).expect("ser");
6861        assert_eq!(json.get("max_concurrent").and_then(|v| v.as_u64()), Some(3));
6862        // A schedule with no constraints omits the whole block.
6863        let bare = schedule_with(
6864            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6865            RunsOn::Backend,
6866        );
6867        assert!(bare.constraints.is_empty());
6868    }
6869
6870    #[test]
6871    fn window_fail_closed_on_corrupt_blob() {
6872        // A malformed window (only reachable via a hand-edited KV
6873        // blob — validate() rejects it at create) must BLOCK, not
6874        // silently allow fires during a change-freeze (gemini #452).
6875        let s = with_window("22:00_05:00");
6876        assert!(
6877            !s.constraints.allows(chrono::Utc::now(), ScheduleTz::Utc),
6878            "corrupt window fails closed"
6879        );
6880        // …and the scheduler can surface why it's stuck.
6881        assert!(
6882            s.bad_window().is_some(),
6883            "bad_window reports the parse error"
6884        );
6885        assert!(with_window("22:00-05:00").bad_window().is_none());
6886    }
6887
6888    #[test]
6889    fn calendar_outside_window_is_flagged() {
6890        // at 09:00 can never fall in 22:00-05:00 → never fires.
6891        let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
6892        s.constraints.window = Some("22:00-05:00".into());
6893        assert!(s.calendar_outside_window(), "09:00 is not in 22:00-05:00");
6894
6895        // at 23:00 IS inside the overnight window → fine.
6896        let mut s = schedule_with(calendar("23:00", &[]), RunsOn::Backend);
6897        s.constraints.window = Some("22:00-05:00".into());
6898        assert!(!s.calendar_outside_window(), "23:00 is in 22:00-05:00");
6899
6900        // reconcile shapes are never flagged (they poll every minute).
6901        let mut s = schedule_with(
6902            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6903            RunsOn::Backend,
6904        );
6905        s.constraints.window = Some("22:00-05:00".into());
6906        assert!(!s.calendar_outside_window(), "reconcile is unaffected");
6907
6908        // no window → never flagged.
6909        let s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
6910        assert!(!s.calendar_outside_window());
6911    }
6912
6913    // ---- on_failure.retry (#418 Phase 4) ----
6914
6915    fn with_retry(max: u32, backoff: &str) -> Schedule {
6916        let mut s = schedule_with(
6917            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6918            RunsOn::Backend,
6919        );
6920        s.on_failure.retry = Some(Retry {
6921            max,
6922            backoff: backoff.into(),
6923        });
6924        s
6925    }
6926
6927    #[test]
6928    fn on_failure_parses_and_round_trips() {
6929        let yaml = r#"
6930id: x
6931when:
6932  per_pc: { every: 6h }
6933job_id: y
6934target: { all: true }
6935on_failure:
6936  retry: { max: 3, backoff: 10m }
6937"#;
6938        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6939        let r = s.on_failure.retry.as_ref().expect("retry present");
6940        assert_eq!(r.max, 3);
6941        assert_eq!(r.backoff, "10m");
6942        let back: Schedule =
6943            serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
6944        assert_eq!(back.on_failure, s.on_failure);
6945    }
6946
6947    #[test]
6948    fn on_failure_empty_is_skipped_when_serialising() {
6949        let s = schedule_with(
6950            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6951            RunsOn::Backend,
6952        );
6953        let json = serde_json::to_value(&s).expect("serialise");
6954        assert!(
6955            json.get("on_failure").is_none(),
6956            "empty on_failure must not appear on the wire: {json}"
6957        );
6958    }
6959
6960    #[test]
6961    fn validate_accepts_good_retry() {
6962        for (max, backoff) in [(1, "30s"), (3, "10m"), (10, "1h")] {
6963            with_retry(max, backoff)
6964                .validate()
6965                .unwrap_or_else(|e| panic!("retry {{max:{max}, backoff:{backoff}}}: {e}"));
6966        }
6967    }
6968
6969    #[test]
6970    fn validate_rejects_bad_backoff() {
6971        let err = with_retry(3, "soon").validate().unwrap_err();
6972        assert!(err.contains("on_failure.retry.backoff"), "got: {err}");
6973    }
6974
6975    #[test]
6976    fn validate_rejects_sub_second_backoff() {
6977        // "500ms" parses as humantime but lowers to 0s on the wire —
6978        // reject it so the operator doesn't get a silent no-wait
6979        // (coderabbit #466).
6980        for bad in ["500ms", "0s", "999ms"] {
6981            let err = with_retry(3, bad).validate().unwrap_err();
6982            assert!(
6983                err.contains("on_failure.retry.backoff must be >= 1s"),
6984                "for '{bad}', got: {err}"
6985            );
6986        }
6987    }
6988
6989    #[test]
6990    fn validate_rejects_out_of_range_max() {
6991        for bad in [0u32, 11, 1000] {
6992            let err = with_retry(bad, "10m").validate().unwrap_err();
6993            assert!(
6994                err.contains("on_failure.retry.max"),
6995                "for max={bad}, got: {err}"
6996            );
6997        }
6998    }
6999
7000    #[test]
7001    fn lowered_retry_reduces_backoff_to_seconds() {
7002        let s = with_retry(3, "10m");
7003        let spec = s.on_failure.lowered_retry().expect("a retry policy");
7004        assert_eq!(spec.max, 3);
7005        assert_eq!(spec.backoff_secs, 600);
7006    }
7007
7008    #[test]
7009    fn lowered_retry_is_none_without_policy() {
7010        let s = schedule_with(
7011            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7012            RunsOn::Backend,
7013        );
7014        assert!(s.on_failure.lowered_retry().is_none());
7015    }
7016
7017    // ---- global change-freeze (#418 Phase 5) ----
7018
7019    #[test]
7020    fn freeze_empty_window_is_always_active() {
7021        // The big-red-button shape: no bounds = frozen until cleared.
7022        let f = Freeze::default();
7023        assert!(f.is_active(chrono::Utc::now()));
7024    }
7025
7026    #[test]
7027    fn freeze_window_is_half_open() {
7028        use chrono::TimeZone;
7029        let f = Freeze {
7030            from: Some("2026-12-20T00:00:00+00:00".into()),
7031            until: Some("2027-01-05T00:00:00+00:00".into()),
7032            reason: Some("year-end".into()),
7033            tz: ScheduleTz::Utc,
7034        };
7035        let at = |y, mo, d| chrono::Utc.with_ymd_and_hms(y, mo, d, 0, 0, 0).unwrap();
7036        assert!(!f.is_active(at(2026, 12, 19)), "before from = not frozen");
7037        assert!(f.is_active(at(2026, 12, 20)), "from is inclusive");
7038        assert!(f.is_active(at(2026, 12, 31)), "inside window");
7039        assert!(!f.is_active(at(2027, 1, 5)), "until is exclusive");
7040        assert!(!f.is_active(at(2027, 1, 6)), "after until = not frozen");
7041    }
7042
7043    #[test]
7044    fn freeze_fails_closed_on_corrupt_bound() {
7045        // A freeze is a safety switch: an unparseable bound (only
7046        // reachable via a hand-edited KV blob) must read as FROZEN, not
7047        // "fire normally" (coderabbit #472) — the opposite of `active`,
7048        // which fail-opens.
7049        let f = Freeze {
7050            from: Some("not-a-date".into()),
7051            until: None,
7052            reason: None,
7053            tz: ScheduleTz::Utc,
7054        };
7055        assert!(f.is_active(chrono::Utc::now()), "corrupt bound → frozen");
7056    }
7057
7058    #[test]
7059    fn freeze_validate_accepts_good_bounds() {
7060        Freeze {
7061            from: Some("2026-12-20".into()),
7062            until: Some("2027-01-05T12:00:00+09:00".into()),
7063            reason: None,
7064            tz: ScheduleTz::Local,
7065        }
7066        .validate()
7067        .expect("date + rfc3339 bounds should validate");
7068        // Empty (indefinite) freeze is valid.
7069        Freeze::default().validate().expect("empty freeze is valid");
7070    }
7071
7072    #[test]
7073    fn freeze_validate_rejects_bad_bound_and_inverted_window() {
7074        let err = Freeze {
7075            from: Some("never".into()),
7076            ..Default::default()
7077        }
7078        .validate()
7079        .unwrap_err();
7080        assert!(err.contains("freeze:"), "got: {err}");
7081
7082        let inverted = Freeze {
7083            from: Some("2027-01-05".into()),
7084            until: Some("2026-12-20".into()),
7085            ..Default::default()
7086        }
7087        .validate()
7088        .unwrap_err();
7089        assert!(inverted.contains("freeze.from"), "got: {inverted}");
7090    }
7091
7092    #[test]
7093    fn freeze_round_trips_and_skips_empty_fields() {
7094        let f = Freeze {
7095            from: None,
7096            until: Some("2027-01-05".into()),
7097            reason: Some("INC-1234".into()),
7098            tz: ScheduleTz::Utc,
7099        };
7100        let json = serde_json::to_value(&f).expect("serialise");
7101        assert!(json.get("from").is_none(), "empty from omitted: {json}");
7102        let back: Freeze = serde_json::from_value(json).expect("round-trip");
7103        assert_eq!(back, f);
7104    }
7105
7106    #[test]
7107    fn shipped_schedule_configs_parse_and_validate() {
7108        // Every YAML under configs/schedules/ must parse with the
7109        // current Schedule serde AND pass validate() — keeps the
7110        // shipped examples from drifting out of sync with the model
7111        // (#418 removed back-compat, so drift = broken at create).
7112        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../configs/schedules");
7113        let mut seen = 0;
7114        for entry in std::fs::read_dir(&dir).expect("read configs/schedules") {
7115            let path = entry.expect("dir entry").path();
7116            if path.extension().and_then(|e| e.to_str()) != Some("yaml") {
7117                continue;
7118            }
7119            let body = std::fs::read_to_string(&path).expect("read yaml");
7120            let s: Schedule = serde_yaml::from_str(&body)
7121                .unwrap_or_else(|e| panic!("{} failed to parse: {e}", path.display()));
7122            s.validate()
7123                .unwrap_or_else(|e| panic!("{} failed validate(): {e}", path.display()));
7124            seen += 1;
7125        }
7126        assert!(seen > 0, "no schedule YAMLs found in {}", dir.display());
7127    }
7128
7129    // ---- pre-existing enum wire formats (unchanged by #418) ----
7130
7131    #[test]
7132    fn exec_mode_serialises_snake_case() {
7133        for (mode, expected) in [
7134            (ExecMode::EveryTick, "every_tick"),
7135            (ExecMode::OncePerPc, "once_per_pc"),
7136            (ExecMode::OncePerTarget, "once_per_target"),
7137        ] {
7138            let s = serde_json::to_value(mode).expect("serialise");
7139            assert_eq!(s, serde_json::Value::String(expected.into()));
7140            let back: ExecMode = serde_json::from_value(serde_json::Value::String(expected.into()))
7141                .expect("deserialise");
7142            assert_eq!(back, mode, "round-trip for {expected}");
7143        }
7144    }
7145
7146    #[test]
7147    fn schedule_runs_on_defaults_to_backend() {
7148        let yaml = r#"
7149id: x
7150when:
7151  per_pc: once
7152job_id: y
7153target: { all: true }
7154"#;
7155        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7156        assert_eq!(s.runs_on, RunsOn::Backend);
7157    }
7158
7159    #[test]
7160    fn schedule_runs_on_agent_parses() {
7161        let yaml = r#"
7162id: offline-inv
7163when:
7164  per_pc: { every: 1h }
7165job_id: inventory-hw
7166target: { all: true }
7167runs_on: agent
7168"#;
7169        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7170        assert_eq!(s.runs_on, RunsOn::Agent);
7171        assert_eq!(s.lowered().mode, ExecMode::OncePerPc);
7172    }
7173
7174    #[test]
7175    fn runs_on_serialises_snake_case() {
7176        for (mode, expected) in [(RunsOn::Backend, "backend"), (RunsOn::Agent, "agent")] {
7177            let s = serde_json::to_value(mode).expect("serialise");
7178            assert_eq!(s, serde_json::Value::String(expected.into()));
7179            let back: RunsOn = serde_json::from_value(serde_json::Value::String(expected.into()))
7180                .expect("deserialise");
7181            assert_eq!(back, mode);
7182        }
7183    }
7184
7185    #[test]
7186    fn execute_shell_into_wire_shell() {
7187        assert_eq!(Shell::from(ExecuteShell::Powershell), Shell::Powershell);
7188        assert_eq!(Shell::from(ExecuteShell::Cmd), Shell::Cmd);
7189    }
7190
7191    #[test]
7192    fn manifest_staleness_defaults_to_cached() {
7193        let yaml = r#"
7194id: x
7195version: 1.0.0
7196execute:
7197  shell: powershell
7198  script: "echo"
7199  timeout: 1s
7200"#;
7201        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7202        assert_eq!(m.staleness, Staleness::Cached);
7203    }
7204
7205    #[test]
7206    fn manifest_strict_staleness_parses() {
7207        let yaml = r#"
7208id: urgent-patch
7209version: 2.5.1
7210execute:
7211  shell: powershell
7212  script: Install-Hotfix
7213  timeout: 5m
7214staleness:
7215  mode: strict
7216  max_cache_age: 0s
7217"#;
7218        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7219        match m.staleness {
7220            Staleness::Strict { max_cache_age } => assert_eq!(max_cache_age, "0s"),
7221            other => panic!("expected strict, got {other:?}"),
7222        }
7223    }
7224
7225    #[test]
7226    fn manifest_unchecked_staleness_parses() {
7227        let yaml = r#"
7228id: legacy
7229version: 0.1.0
7230execute:
7231  shell: cmd
7232  script: "echo"
7233  timeout: 1s
7234staleness:
7235  mode: unchecked
7236"#;
7237        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7238        assert_eq!(m.staleness, Staleness::Unchecked);
7239    }
7240
7241    #[test]
7242    fn missing_required_field_errors() {
7243        // `id` missing.
7244        let yaml = r#"
7245version: 1.0.0
7246target: { all: true }
7247execute:
7248  shell: powershell
7249  script: "echo"
7250  timeout: 1s
7251"#;
7252        let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
7253        assert!(r.is_err(), "expected error, got {:?}", r);
7254    }
7255
7256    #[test]
7257    fn display_field_table_kind_round_trips_with_nested_columns() {
7258        // #39: `type: table` + `columns:` on a DisplayField gets
7259        // round-tripped through serde so the SPA receives the
7260        // nested schema verbatim. Nested columns themselves are
7261        // DisplayFields so they can carry `type: bytes` /
7262        // `type: number` for cell formatting.
7263        let yaml = r#"
7264id: inv-hw
7265version: 1.0.0
7266execute:
7267  shell: powershell
7268  script: "echo"
7269  timeout: 60s
7270inventory:
7271  display:
7272    - field: hostname
7273      label: Hostname
7274    - field: disks
7275      label: Disks
7276      type: table
7277      columns:
7278        - field: device_id
7279          label: Drive
7280        - field: size_bytes
7281          label: Size
7282          type: bytes
7283        - field: free_bytes
7284          label: Free
7285          type: bytes
7286        - field: file_system
7287          label: FS
7288"#;
7289        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7290        let inv = m.inventory.as_ref().expect("inventory hint");
7291        let disks = inv
7292            .display
7293            .iter()
7294            .find(|d| d.field == "disks")
7295            .expect("disks display row");
7296        assert_eq!(disks.kind.as_deref(), Some("table"));
7297        let cols = disks.columns.as_ref().expect("table needs columns");
7298        assert_eq!(cols.len(), 4);
7299        assert_eq!(cols[1].field, "size_bytes");
7300        assert_eq!(cols[1].kind.as_deref(), Some("bytes"));
7301    }
7302
7303    #[test]
7304    fn display_field_scalar_kind_keeps_columns_none() {
7305        // Defensive: when type is a scalar (`bytes` / `number` /
7306        // `timestamp`) the `columns` field stays None — the SPA
7307        // uses its presence as the "render nested table" signal,
7308        // so it must not leak in via serde defaults.
7309        let yaml = r#"
7310id: x
7311version: 1.0.0
7312execute:
7313  shell: powershell
7314  script: "echo"
7315  timeout: 5s
7316inventory:
7317  display:
7318    - { field: ram_bytes, label: RAM, type: bytes }
7319"#;
7320        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7321        let inv = m.inventory.as_ref().unwrap();
7322        assert!(inv.display[0].columns.is_none());
7323    }
7324
7325    // ---- GroupDef (#1032 dynamic groups) ----
7326
7327    fn group_def(yaml: &str) -> Result<GroupDef, String> {
7328        let g: GroupDef = crate::strict::from_yaml_str(yaml).map_err(|e| e.to_string())?;
7329        g.validate().map(|()| g)
7330    }
7331
7332    #[test]
7333    fn group_def_static_members_valid() {
7334        let g = group_def("id: pilot\nmembers: [PC-A, PC-B]\n").expect("valid static group");
7335        assert_eq!(g.members, vec!["PC-A", "PC-B"]);
7336        assert!(g.dynamic_query().is_none());
7337    }
7338
7339    #[test]
7340    fn group_def_dynamic_query_valid() {
7341        let g = group_def(
7342            "id: clients\nquery: \"SELECT pc_id FROM agents WHERE hostname LIKE 'X%'\"\nrefresh: 30m\n",
7343        )
7344        .expect("valid dynamic group");
7345        assert_eq!(
7346            g.dynamic_query(),
7347            Some("SELECT pc_id FROM agents WHERE hostname LIKE 'X%'")
7348        );
7349        assert_eq!(g.refresh_interval(), std::time::Duration::from_secs(1800));
7350    }
7351
7352    #[test]
7353    fn group_def_refresh_defaults_when_absent() {
7354        let g = group_def("id: c\nquery: \"SELECT pc_id FROM agents\"\n").unwrap();
7355        assert_eq!(g.refresh_interval(), DEFAULT_GROUP_REFRESH);
7356    }
7357
7358    #[test]
7359    fn group_def_rejects_neither_members_nor_query() {
7360        let err = group_def("id: empty\n").unwrap_err();
7361        assert!(err.contains("either"), "err: {err}");
7362    }
7363
7364    #[test]
7365    fn group_def_rejects_both_members_and_query() {
7366        let err = group_def("id: both\nmembers: [PC-A]\nquery: \"SELECT pc_id FROM agents\"\n")
7367            .unwrap_err();
7368        assert!(err.contains("mutually exclusive"), "err: {err}");
7369    }
7370
7371    #[test]
7372    fn group_def_blank_query_is_unset_not_both() {
7373        // An empty-string query reads as unset, so a members group with a
7374        // commented-out (emptied) query is still valid, not a "both set" error.
7375        let g =
7376            group_def("id: pilot\nmembers: [PC-A]\nquery: \"\"\n").expect("blank query = unset");
7377        assert!(g.dynamic_query().is_none());
7378    }
7379
7380    #[test]
7381    fn group_def_rejects_bad_id_charset() {
7382        let err = group_def("id: bad/id\nmembers: [PC-A]\n").unwrap_err();
7383        assert!(err.contains("group.id"), "err: {err}");
7384    }
7385
7386    #[test]
7387    fn group_def_rejects_untrimmed_id() {
7388        // A padded id validated-as-trimmed but stored-raw would be a KV key
7389        // nothing matches — reject it outright (the id is used verbatim).
7390        let err = group_def("id: \" clients \"\nmembers: [PC-A]\n").unwrap_err();
7391        assert!(err.contains("group.id"), "err: {err}");
7392    }
7393
7394    #[test]
7395    fn group_def_rejects_bad_refresh() {
7396        let err =
7397            group_def("id: c\nquery: \"SELECT pc_id FROM agents\"\nrefresh: soon\n").unwrap_err();
7398        assert!(err.contains("refresh"), "err: {err}");
7399    }
7400
7401    #[test]
7402    fn group_def_rejects_unknown_key() {
7403        // Strict parse (#492) — a typo'd key is an operator error, not silently
7404        // dropped.
7405        let err = group_def("id: c\nmembers: [PC-A]\nrlue: x\n").unwrap_err();
7406        assert!(err.to_lowercase().contains("unknown"), "err: {err}");
7407    }
7408
7409    // ---- checked-in JSON Schema freshness (docs/schemas/) ----
7410
7411    /// The JSON Schemas under `docs/schemas/` must match what
7412    /// `schema_for!` produces today — a Cargo.lock-style freshness guard
7413    /// so a `Schedule` / `Manifest` field change can't silently drift
7414    /// the operator-facing schema. The SPA editor, the backend
7415    /// `/api/schemas/*` endpoints, and these files all read the same
7416    /// derived shape; this test fails CI if the checked-in copy lags.
7417    /// Regenerate with:
7418    ///   `UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current`
7419    #[test]
7420    fn schema_files_are_current() {
7421        assert_schema_file("schedule.schema.json", &schemars::schema_for!(Schedule));
7422        assert_schema_file("job.schema.json", &schemars::schema_for!(Manifest));
7423        assert_schema_file("view.schema.json", &schemars::schema_for!(View));
7424        assert_schema_file("group-def.schema.json", &schemars::schema_for!(GroupDef));
7425    }
7426
7427    fn assert_schema_file(name: &str, schema: &schemars::Schema) {
7428        let generated = serde_json::to_string_pretty(schema).expect("serialize schema") + "\n";
7429        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7430            .join("../../docs/schemas")
7431            .join(name);
7432        if std::env::var_os("UPDATE_SCHEMAS").is_some() {
7433            std::fs::create_dir_all(path.parent().unwrap()).expect("mkdir docs/schemas");
7434            std::fs::write(&path, &generated).unwrap_or_else(|e| panic!("write {path:?}: {e}"));
7435            return;
7436        }
7437        // Normalize CRLF→LF before comparing: `.gitattributes` already
7438        // pins these files to `eol=lf`, but a stray CRLF working-tree
7439        // copy (autocrlf, a tool rewrite) shouldn't turn a *content*-
7440        // freshness check into a confusing line-ending failure — that's
7441        // .gitattributes' job, not this test's (gemini #588).
7442        let on_disk = std::fs::read_to_string(&path)
7443            .unwrap_or_else(|e| {
7444                panic!(
7445                    "read {path:?}: {e}\n\
7446                     generate it with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
7447                )
7448            })
7449            .replace("\r\n", "\n");
7450        assert_eq!(
7451            on_disk, generated,
7452            "{name} is stale — a Schedule/Manifest schema change isn't reflected in docs/schemas/. \
7453             Refresh with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
7454        );
7455    }
7456}
7457
7458/// Periodic schedule (spec §2.4.3). v0.18.0 carries the fanout plan
7459/// (target + optional rollout + optional jitter) inline; the
7460/// referenced job (`job_id` → [`BUCKET_JOBS`]) supplies only the
7461/// script body. Two schedules of the same job can target different
7462/// groups on different cadences without copying the manifest.
7463///
7464/// #418 Phase 1: the cadence is the single [`When`] field. The old
7465/// `cron` × `mode` × `cooldown` × `auto_disable_when_done` quartet
7466/// is gone (no back-compat — pre-Phase-1 KV blobs fail to parse and
7467/// are warn-skipped; re-`schedule create` to upgrade them). The
7468/// engine underneath is unchanged: [`Schedule::lowered`] maps `when`
7469/// onto the same (cron, ExecMode, cooldown) trio the scheduler and
7470/// `decide_fire` always ran on.
7471#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
7472pub struct Schedule {
7473    pub id: String,
7474    /// When to fire — a reconcile cadence (`per_pc` / `per_target`)
7475    /// or a calendar time trigger (`at` / `days`). See [`When`].
7476    ///
7477    /// `singleton_map`: serde_yaml 0.9 renders externally-tagged
7478    /// enums as `!per_pc` YAML tags by default; this keeps the
7479    /// operator-facing map shape (`when: { per_pc: once }`). JSON
7480    /// output is identical either way, and the schemars schema
7481    /// (external tagging = oneOf of single-key objects) already
7482    /// matches the singleton-map wire shape.
7483    #[serde(with = "serde_yaml::with::singleton_map")]
7484    #[schemars(with = "When")]
7485    pub when: When,
7486    /// Key into [`crate::kv::BUCKET_JOBS`]. Must equal a registered
7487    /// Manifest's `id`.
7488    pub job_id: String,
7489    /// Who + how-to-phase + when-to-stagger. The Manifest doesn't
7490    /// carry these any more — same job + different fanout = different
7491    /// schedule.
7492    #[serde(flatten)]
7493    pub plan: FanoutPlan,
7494    /// Optional validity window. Outside `[from, until)` the
7495    /// schedule is dormant — still registered, still visible, but
7496    /// every tick is skipped (deleted ≠ dormant: a campaign that
7497    /// ended stays inspectable and can be re-armed by editing the
7498    /// window). Checked at tick time on both the backend scheduler
7499    /// and the agent's local scheduler.
7500    #[serde(default, skip_serializing_if = "Active::is_empty")]
7501    pub active: Active,
7502    /// #418 operational constraints gating *when within an active
7503    /// period* a fire may happen: a maintenance `window`, a fleet
7504    /// `max_concurrent` cap, and `skip_dates` (holiday exclusion). The
7505    /// wall-clock ones are evaluated in the schedule's `tz`; future
7506    /// `require` (env gates) lands in the same namespace. Checked at
7507    /// tick time on both schedulers (and surfaced by `preview`).
7508    #[serde(default, skip_serializing_if = "Constraints::is_empty")]
7509    pub constraints: Constraints,
7510    /// #418 Phase 4: what to do after a fire's script comes back
7511    /// failed. Currently just `retry` (fixed-backoff in-process
7512    /// re-run); future `notify` / `disable` join the same namespace.
7513    /// Applied fire-side in `handle_command` (the retry policy is
7514    /// lowered onto every Command this schedule produces), so it
7515    /// covers both `runs_on` locations.
7516    #[serde(default, skip_serializing_if = "OnFailure::is_empty")]
7517    pub on_failure: OnFailure,
7518    /// #418 Phase 2: the timezone this schedule's wall-clock fields
7519    /// are evaluated in — both the calendar `at` firing time AND the
7520    /// `active.{from,until}` window bounds. `local` (default) = the
7521    /// running host's TZ (the agent's for `runs_on: agent`, the
7522    /// backend server's otherwise); `utc` for TZ-independent
7523    /// schedules. Reconcile shapes (`per_pc`/`per_target`) ignore it
7524    /// for firing (poll cron runs every minute regardless) but still
7525    /// honor it for the `active` window.
7526    #[serde(default)]
7527    pub tz: ScheduleTz,
7528    /// v0.22: optional humantime window after a cron tick during
7529    /// which the Command is still considered "live". The scheduler
7530    /// computes `tick_at + starting_deadline` and stamps it onto
7531    /// each Command as `deadline_at`; agents skip Commands they
7532    /// receive after that absolute time. `None` (default) = no
7533    /// deadline, meaning a Command queued in the broker / stream
7534    /// during agent downtime runs whenever the agent reconnects —
7535    /// good for kitting / inventory / cleanup. Set this for
7536    /// time-of-day notifications, lunch reminders, etc., where
7537    /// "fire 3 hours late" would be wrong.
7538    #[serde(default, skip_serializing_if = "Option::is_none")]
7539    pub starting_deadline: Option<String>,
7540    /// v0.23: where does the cron tick happen? `Backend` (default,
7541    /// historical) = backend's scheduler fires Commands via NATS;
7542    /// agents passively receive. `Agent` = each targeted agent runs
7543    /// its own internal cron and fires locally, so the schedule
7544    /// keeps ticking even when the broker is unreachable (laptop on
7545    /// the train, broker maintenance window, full WAN outage). The
7546    /// two locations are mutually exclusive — when `Agent`, the
7547    /// backend scheduler stays out and just keeps the definition in
7548    /// KV for agents to read.
7549    #[serde(default)]
7550    pub runs_on: RunsOn,
7551    #[serde(default = "default_true")]
7552    pub enabled: bool,
7553    /// Free-form operator taxonomy for the Schedules page — the
7554    /// schedule-side mirror of `Manifest.tags` (added in #640; a plain
7555    /// code ref rather than an intra-doc link, since that field isn't
7556    /// on this branch until #640 merges). Purely a SPA-side
7557    /// organisational aid (search / filter chips alongside the
7558    /// id-prefix grouping); the scheduler never reads it, so any
7559    /// string is allowed and it carries no firing semantics. A
7560    /// schedule's own tags are independent of its job's: the same job
7561    /// may back a `weekly` maintenance schedule and a `canary` rollout
7562    /// schedule. Empty by default and `skip_serializing_if`-elided per
7563    /// the #492 gradual-upgrade wire rule.
7564    #[serde(default, skip_serializing_if = "Vec::is_empty")]
7565    pub tags: Vec<String>,
7566    /// GitOps provenance (#695) — see [`RepoOrigin`]. Stamped by
7567    /// `kanade schedule create` when the source YAML lives inside a Git
7568    /// work tree, so the SPA renders the schedule read-only and points
7569    /// edits back at the repo (SPEC design principle #3: 設定駆動 YAML +
7570    /// Git), parity with a job's [`Manifest::origin`]. `None` for
7571    /// SPA-born schedules and ones applied from outside any repo. Purely
7572    /// informational — the scheduler never reads it. New field ⇒ #492
7573    /// wire rule (`default` + `skip_serializing_if`).
7574    #[serde(default, skip_serializing_if = "Option::is_none")]
7575    pub origin: Option<RepoOrigin>,
7576}
7577
7578impl Schedule {
7579    /// Every valid top-level key on a Schedule YAML/JSON document —
7580    /// this struct's own fields PLUS the fields of the
7581    /// `#[serde(flatten)] plan: FanoutPlan`. The strict create
7582    /// boundary needs this because serde's flatten buffering hides
7583    /// unknown top-level keys from `serde_ignored`, so a typo like
7584    /// `jiter:` or `enabledd:` would otherwise be silently dropped
7585    /// (#924). Kept in sync with the field list by
7586    /// `schedule_top_level_keys_cover_serialized_fields`.
7587    pub const TOP_LEVEL_KEYS: &'static [&'static str] = &[
7588        // Schedule's own fields:
7589        "id",
7590        "when",
7591        "job_id",
7592        "active",
7593        "constraints",
7594        "on_failure",
7595        "tz",
7596        "starting_deadline",
7597        "runs_on",
7598        "enabled",
7599        "tags",
7600        "origin",
7601        // flattened FanoutPlan:
7602        "target",
7603        "rollout",
7604        "jitter",
7605        "deadline_at",
7606    ];
7607}
7608
7609impl crate::strict::StrictSchema for Schedule {
7610    fn strict_top_level_keys() -> Option<&'static [&'static str]> {
7611        Some(Self::TOP_LEVEL_KEYS)
7612    }
7613}
7614
7615/// Manifest has no `#[serde(flatten)]` field, so `serde_ignored`
7616/// already catches every top-level typo — the default (`None`) is
7617/// correct.
7618impl crate::strict::StrictSchema for Manifest {}
7619
7620/// View likewise has no flattened field.
7621impl crate::strict::StrictSchema for View {}
7622
7623/// GroupDef likewise has no flattened field.
7624impl crate::strict::StrictSchema for GroupDef {}
7625
7626/// v0.23 — where the cron tick fires from.
7627#[derive(
7628    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
7629)]
7630#[serde(rename_all = "snake_case")]
7631pub enum RunsOn {
7632    /// Backend's central scheduler ticks and publishes Commands to
7633    /// NATS. Historical default, what every pre-v0.23 schedule
7634    /// uses. Agent offline ⇒ Command queued in STREAM_EXEC; agent
7635    /// reconnects ⇒ catch-up via [`command_replay`](crate)
7636    /// (see kanade-agent's command_replay module).
7637    #[default]
7638    Backend,
7639    /// Each targeted agent runs the cron tick locally. Survives
7640    /// broker / WAN outages. Best for laptops / mobile devices that
7641    /// roam off the corporate network. Agent must be online for the
7642    /// initial schedule + job-catalog pull, but once cached the
7643    /// agent fires the script standalone.
7644    Agent,
7645}
7646
7647/// Per-pc/per-target dedup semantics for a [`Schedule`] (v0.19).
7648#[derive(
7649    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
7650)]
7651#[serde(rename_all = "snake_case")]
7652pub enum ExecMode {
7653    /// Fire on every cron tick at the whole target. Historical
7654    /// (pre-v0.19) behavior; no dedup.
7655    #[default]
7656    EveryTick,
7657    /// Fire at each pc until that pc succeeds; then skip it until
7658    /// the optional cooldown elapses (or forever if no cooldown).
7659    /// Use for kitting / first-boot / per-pc compliance checks.
7660    OncePerPc,
7661    /// Fire at the whole target until **any** pc succeeds; then
7662    /// skip the whole target until the optional cooldown elapses
7663    /// (or forever if no cooldown). Use for "one delegate is
7664    /// enough" tasks like license check-in.
7665    OncePerTarget,
7666    /// Like [`OncePerPc`](ExecMode::OncePerPc), but the "already
7667    /// succeeded ⇒ skip" check is scoped to the CURRENT manifest
7668    /// version: a pc whose only successful run recorded an OLDER
7669    /// manifest version re-fires so the new version reaches it. Bumping
7670    /// the job's YAML `version` is the redistribution trigger. Plain
7671    /// `OncePerPc` (kitting) is version-blind — a pc that ever succeeded
7672    /// is skipped forever; this mode re-arms per version. per_pc only —
7673    /// `Schedule::validate` rejects `per_target: once_per_version`.
7674    OncePerPcVersion,
7675    /// #418 OS-native event trigger (`when: { on: [...] }`). There is
7676    /// no cron — the agent fires it from an OS event source (boot /
7677    /// session-change), not a tick — so the scheduler skips
7678    /// `tokio-cron` registration for it. Each event occurrence fires
7679    /// once, gated by the standard freeze / active / window /
7680    /// skip_dates checks.
7681    Event,
7682}
7683
7684/// #418 Phase 1 — the single "when does this fire" axis.
7685///
7686/// Replaces the old `cron` + `mode` + `cooldown` trio whose
7687/// interactions were implicit (cron doubled as both a real
7688/// time-of-day trigger and a reconcile poll period; contradictory
7689/// combinations silently no-opped). Two shapes:
7690///
7691/// * **reconcile** (`per_pc` / `per_target`) — desired-state: "each
7692///   pc (or one delegate) should have run this within `every`".
7693///   The poll period is system-generated ([`POLL_CRON`], every
7694///   minute) and no longer the operator's concern.
7695/// * **calendar** (`{ at, days }`) — a wall-clock time trigger
7696///   (#418 Phase 2, replacing the old raw-cron escape hatch). Fires
7697///   the whole target at the given time, no dedup. `at: "09:00"` +
7698///   `days` repeats; `at: "2026-06-10 09:00"` (a date+time) fires
7699///   exactly once. Evaluated in the schedule's top-level `tz`.
7700#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7701#[serde(rename_all = "snake_case")]
7702pub enum When {
7703    /// Fire at each targeted pc: `once` (kitting — succeed once,
7704    /// skip forever, forever catching brand-new / re-imaged pcs)
7705    /// or `{ every: <humantime> }` (patrol — re-arm per pc after
7706    /// the interval).
7707    PerPc(PerPolicy),
7708    /// Fire until **any** one pc of the target succeeds, then skip
7709    /// the whole target (`once`) or re-arm after `every`. Needs
7710    /// fleet-wide completion data, so it is backend-only —
7711    /// `runs_on: agent` + `per_target` is rejected by
7712    /// [`Schedule::validate`].
7713    PerTarget(PerPolicy),
7714    /// Calendar time trigger: `{ at: "09:00", days: [mon-fri] }`
7715    /// (repeating) or `{ at: "2026-06-10 09:00" }` (one-shot). Fires
7716    /// the whole target at that wall-clock time in the schedule's
7717    /// `tz` — no dedup, no cooldown.
7718    Calendar(CalendarSpec),
7719    /// #418 OS-native event trigger: `when: { on: [startup, logon] }`.
7720    /// Fires when the agent observes the listed OS event(s) rather than
7721    /// on a clock — there is no cron. `runs_on: agent` only (the agent
7722    /// owns the event source); [`Schedule::validate`] rejects it on
7723    /// `backend` and rejects an empty list. Each event occurrence fires
7724    /// once, gated by the same freeze / active / `constraints.window` /
7725    /// `skip_dates` checks as the cron path. `startup` fires once per OS
7726    /// boot (deduped via the host boot time); a `starting_deadline`, if
7727    /// set, limits it to "agent came up within that long after boot".
7728    On(Vec<OnTrigger>),
7729}
7730
7731/// An OS event the agent can fire a schedule on (#418 `when: { on }`).
7732#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash)]
7733#[serde(rename_all = "snake_case")]
7734pub enum OnTrigger {
7735    /// Once per OS boot (the agent's first run for that boot). Catches
7736    /// freshly-imaged / reinstalled hosts at their next startup.
7737    Startup,
7738    /// On an interactive-session user logon — console, RDP, or
7739    /// auto-logon (Windows `WTS_SESSION_LOGON`). Does not fire for
7740    /// service / network / batch logons (no interactive session).
7741    Logon,
7742    /// When the workstation is locked (Win+L / idle lock; Windows
7743    /// `WTS_SESSION_LOCK`). Use for step-away compliance / cleanup.
7744    Lock,
7745    /// When the workstation is unlocked — the user returns to a locked
7746    /// session (Windows `WTS_SESSION_UNLOCK`). Use to re-check
7747    /// compliance / refresh state when work resumes.
7748    Unlock,
7749    /// When the host's network changes — IP address table change on
7750    /// connect / disconnect / DHCP renew / VPN / Wi-Fi roam (Windows
7751    /// `NotifyAddrChange`). Debounced agent-side (a burst of changes
7752    /// from one transition fires once after the network settles), so
7753    /// use it for "re-check connectivity / re-register on network move"
7754    /// rather than expecting one fire per raw adapter event.
7755    ///
7756    /// IPv4 only: `NotifyAddrChange` watches the IPv4 address table, so a
7757    /// transition that touches only IPv6 addresses won't fire. In practice
7758    /// dual-stack networks change both tables together, but a pure-IPv6
7759    /// move (e.g. an IPv6-only Wi-Fi roam) is not detected.
7760    NetworkChange,
7761}
7762
7763/// Calendar time trigger (#418 Phase 2). `at` is either a time of
7764/// day (`"HH:MM"`, repeating — combine with `days`) or a full
7765/// date+time (`"YYYY-MM-DD HH:MM"`, a one-shot that fires once and
7766/// never again). Evaluated in the schedule's top-level `tz`.
7767#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7768pub struct CalendarSpec {
7769    /// `"HH:MM"` (24h) for a repeating trigger, or
7770    /// `"YYYY-MM-DD HH:MM"` (hyphen / slash / `T` separators all
7771    /// accepted) for a one-shot. Parsed lazily —
7772    /// [`Schedule::validate`] rejects garbage at create time.
7773    pub at: String,
7774    /// Day-of-week filter for a time-of-day `at`: `["mon-fri"]`,
7775    /// `["mon","wed","fri"]`, … (passed verbatim to the cron DOW
7776    /// field, so ranges and names both work). An **nth-weekday**
7777    /// `["tue#2"]` fires only on the 2nd Tuesday of each month
7778    /// ("Patch Tuesday"); the ordinal is `1..5`. A **last-weekday**
7779    /// `["friL"]` fires only on the last Friday of each month (handy
7780    /// for monthly maintenance). Empty = every day. Must be empty
7781    /// when `at` carries a date (the date already pins the day).
7782    #[serde(default, skip_serializing_if = "Vec::is_empty")]
7783    pub days: Vec<String>,
7784}
7785
7786/// Parsed `CalendarSpec.at`: the wall-clock minute/hour, plus the
7787/// date for a one-shot (`None` = repeating time-of-day).
7788struct ParsedAt {
7789    minute: u32,
7790    hour: u32,
7791    date: Option<chrono::NaiveDate>,
7792}
7793
7794impl CalendarSpec {
7795    /// Parse `at`: a date+time (`YYYY-MM-DD HH:MM`, hyphen / slash /
7796    /// `T` separators) is a one-shot; a bare `HH:MM` is repeating.
7797    fn parse_at(&self) -> Result<ParsedAt, String> {
7798        use chrono::Timelike;
7799        let s = self.at.trim();
7800        for fmt in ["%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y/%m/%d %H:%M"] {
7801            if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, fmt) {
7802                return Ok(ParsedAt {
7803                    minute: dt.minute(),
7804                    hour: dt.hour(),
7805                    date: Some(dt.date()),
7806                });
7807            }
7808        }
7809        if let Ok(t) = chrono::NaiveTime::parse_from_str(s, "%H:%M") {
7810            return Ok(ParsedAt {
7811                minute: t.minute(),
7812                hour: t.hour(),
7813                date: None,
7814            });
7815        }
7816        Err(format!(
7817            "when.at: unparseable '{}' (want HH:MM or YYYY-MM-DD HH:MM)",
7818            self.at
7819        ))
7820    }
7821
7822    /// Pre-flight check on the `days` tokens so a bad day name gives
7823    /// a `when.days:`-scoped error instead of croner's confusing
7824    /// "when.at lowered to invalid cron" (claude #432 review). Each
7825    /// token is a day name (`mon`..`sun`), a numeric DOW (`0`..`7`),
7826    /// `*`, a `-` range of those, an **nth-weekday** like `tue#2`
7827    /// (2nd Tuesday of the month — "Patch Tuesday"), or a
7828    /// **last-weekday** like `friL` (last Friday of the month).
7829    fn validate_days(&self) -> Result<(), String> {
7830        const NAMES: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
7831        let is_day = |p: &str| NAMES.contains(&p) || p.parse::<u8>().is_ok_and(|n| n <= 7);
7832        for tok in &self.days {
7833            // Report the whole token on a malformed range like `mon-`
7834            // (which would otherwise split to a cryptic empty part —
7835            // claude #432 follow-up).
7836            let invalid = |reason: &str| {
7837                Err(format!(
7838                    "when.days: invalid day token '{tok}' ({reason}; \
7839                     want mon..sun, 0-7, a range like mon-fri, an nth-weekday \
7840                     like tue#2, a last-weekday like friL, or *)"
7841                ))
7842            };
7843            // #418: nth-weekday suffix (`tue#2` = 2nd Tuesday). Croner
7844            // accepts `<dow>#<n>` (n = 1..5) in the DOW field, and
7845            // `to_cron` passes the token through verbatim, so the
7846            // engine fires only on that occurrence. It's a single
7847            // weekday + ordinal — not combinable with a range.
7848            if let Some((day_part, nth_part)) = tok.split_once('#') {
7849                // Normalize once and use `d` consistently (gemini #547);
7850                // the outer `invalid` already echoes the raw `tok`.
7851                let d = day_part.trim().to_ascii_lowercase();
7852                if d.contains('-') || !is_day(&d) {
7853                    return invalid("the part before # must be a single weekday");
7854                }
7855                match nth_part.trim().parse::<u8>() {
7856                    Ok(n) if (1..=5).contains(&n) => {}
7857                    _ => return invalid("the # ordinal must be 1..5 (e.g. tue#2 = 2nd Tuesday)"),
7858                }
7859                continue;
7860            }
7861            // #418: last-weekday suffix (`friL` = last Friday of the
7862            // month — the monthly-maintenance sibling of Patch Tuesday).
7863            // Croner accepts `<dow>L` in the DOW field with verified
7864            // last-<dow>-of-month semantics, and `to_cron` passes it
7865            // through verbatim. A single weekday + `L` — bare `L` and
7866            // ranges are rejected (croner would read bare `L` as
7867            // Saturday, which is a confusing footgun).
7868            if let Some(day_part) = tok.strip_suffix(['L', 'l']) {
7869                // No `.trim()`: a cron DOW token can't carry internal
7870                // whitespace, so `"fri L"` must be *rejected* here (its
7871                // strip leaves `"fri "`, and `is_day` catches the space)
7872                // rather than trimmed into a clean `"fri"` that then
7873                // produces a malformed `fri L` cron downstream and a
7874                // confusing croner error (gemini #560).
7875                let d = day_part.to_ascii_lowercase();
7876                if d.is_empty() {
7877                    return invalid("`L` (last-weekday) needs a weekday before it, e.g. friL");
7878                }
7879                if d.contains('-') || !is_day(&d) {
7880                    return invalid(
7881                        "the part before L must be a single weekday (e.g. friL = last Friday)",
7882                    );
7883                }
7884                continue;
7885            }
7886            for part in tok.split('-') {
7887                let p = part.trim().to_ascii_lowercase();
7888                if p.is_empty() {
7889                    return invalid("empty range bound");
7890                }
7891                if p != "*" && !is_day(&p) {
7892                    return invalid(&format!("'{part}' is not a day"));
7893                }
7894            }
7895        }
7896        Ok(())
7897    }
7898
7899    /// For a one-shot (`at` carries a date), the absolute instant it
7900    /// fires in `tz`. `None` for a repeating calendar. Used to warn
7901    /// about a one-shot whose date is already in the past (it would
7902    /// never fire).
7903    pub fn oneshot_instant(&self, tz: ScheduleTz) -> Option<chrono::DateTime<chrono::Utc>> {
7904        let p = self.parse_at().ok()?;
7905        let date = p.date?;
7906        let naive = date.and_hms_opt(p.hour, p.minute, 0)?;
7907        tz.naive_to_utc(naive)
7908    }
7909
7910    /// The wall-clock time-of-day this calendar fires at (`None` if
7911    /// `at` is unparseable — validate() guards that). Used to detect
7912    /// a calendar whose fire time can never fall inside its
7913    /// `constraints.window` (claude #452 review).
7914    pub fn fire_time(&self) -> Option<chrono::NaiveTime> {
7915        let p = self.parse_at().ok()?;
7916        chrono::NaiveTime::from_hms_opt(p.hour, p.minute, 0)
7917    }
7918
7919    /// Lower to the cron string the scheduler engine runs. Repeating
7920    /// → 6-field `0 {min} {hour} * * {dow}`; one-shot → 7-field
7921    /// `0 {min} {hour} {day} {month} * {year}` (a past year never
7922    /// fires — that's what makes it one-shot).
7923    fn to_cron(&self) -> Result<String, String> {
7924        use chrono::Datelike;
7925        let ParsedAt { minute, hour, date } = self.parse_at()?;
7926        match date {
7927            Some(d) => {
7928                if !self.days.is_empty() {
7929                    return Err(
7930                        "when.at with a date is a one-shot and cannot be combined with days".into(),
7931                    );
7932                }
7933                Ok(format!(
7934                    "0 {minute} {hour} {} {} * {}",
7935                    d.day(),
7936                    d.month(),
7937                    d.year()
7938                ))
7939            }
7940            None => {
7941                let dow = if self.days.is_empty() {
7942                    "*".to_string()
7943                } else {
7944                    self.validate_days()?;
7945                    self.days.join(",")
7946                };
7947                Ok(format!("0 {minute} {hour} * * {dow}"))
7948            }
7949        }
7950    }
7951}
7952
7953/// The timezone a schedule's wall-clock fields (`when.at`,
7954/// `active.{from,until}`) are evaluated in (#418 Phase 2).
7955#[derive(
7956    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
7957)]
7958#[serde(rename_all = "snake_case")]
7959pub enum ScheduleTz {
7960    /// The running host's local timezone — the agent's for
7961    /// `runs_on: agent`, the backend server's otherwise. Default.
7962    #[default]
7963    Local,
7964    /// UTC — for timezone-independent schedules.
7965    Utc,
7966}
7967
7968impl ScheduleTz {
7969    /// Interpret a naive (zoneless) datetime as being in this tz and
7970    /// convert to UTC. On a DST *fold* (the local time occurs twice
7971    /// when clocks go back) we pick `.earliest()` rather than
7972    /// rejecting it; `None` is reserved for a true DST *gap* (a local
7973    /// time that never exists). `Utc` is fixed-offset so neither ever
7974    /// happens; `Local` is whatever timezone the running host is set
7975    /// to and *can* hit a gap/fold on any DST-observing host — not
7976    /// just the JST we run today (gemini + claude #432 review).
7977    fn naive_to_utc(self, naive: chrono::NaiveDateTime) -> Option<chrono::DateTime<chrono::Utc>> {
7978        use chrono::TimeZone;
7979        match self {
7980            ScheduleTz::Utc => Some(chrono::DateTime::from_naive_utc_and_offset(
7981                naive,
7982                chrono::Utc,
7983            )),
7984            ScheduleTz::Local => chrono::Local
7985                .from_local_datetime(&naive)
7986                .earliest()
7987                .map(|dt| dt.with_timezone(&chrono::Utc)),
7988        }
7989    }
7990
7991    /// The wall-clock time-of-day `now` reads as in this tz — used by
7992    /// [`Constraints::allows`] to test a maintenance window
7993    /// (#418 Phase 3). `Utc` is the naive UTC time; `Local` is the
7994    /// running host's local time.
7995    fn wall_time(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveTime {
7996        match self {
7997            ScheduleTz::Utc => now.time(),
7998            ScheduleTz::Local => now.with_timezone(&chrono::Local).time(),
7999        }
8000    }
8001
8002    /// The wall-clock *date* `now` reads as in this tz — used by
8003    /// [`Constraints::allows`] to test `skip_dates` (#418 holiday
8004    /// exclusion). Same tz semantics as [`Self::wall_time`].
8005    fn wall_date(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveDate {
8006        match self {
8007            ScheduleTz::Utc => now.date_naive(),
8008            ScheduleTz::Local => now.with_timezone(&chrono::Local).date_naive(),
8009        }
8010    }
8011
8012    /// Stable lowercase wire/display label (`local` / `utc`) — matches
8013    /// the serde `snake_case` representation. Used for the preview
8014    /// response's `tz` field so the JSON shape isn't coupled to the
8015    /// `Debug` repr (claude #578 review).
8016    pub fn as_str(self) -> &'static str {
8017        match self {
8018            ScheduleTz::Local => "local",
8019            ScheduleTz::Utc => "utc",
8020        }
8021    }
8022}
8023
8024impl std::fmt::Display for ScheduleTz {
8025    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8026        f.write_str(self.as_str())
8027    }
8028}
8029
8030/// `once` / `once_per_version` / `{ every: <humantime> }` — shared by
8031/// `per_pc` / `per_target`. Untagged so the YAML stays the bare keyword
8032/// or a one-key map, nothing more ceremonial. `once_per_version` is
8033/// per_pc + backend only (see the variant doc and `Schedule::validate`).
8034#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8035#[serde(untagged)]
8036pub enum PerPolicy {
8037    /// The bare string `once`: succeed once, then skip permanently
8038    /// (cooldown = infinity), version-blind.
8039    Once(OnceLiteral),
8040    /// The bare string `once_per_version`: succeed once *per manifest
8041    /// version*, then skip until the job's YAML `version` changes. Like
8042    /// `once` but re-arms each pc when the version it succeeded at is no
8043    /// longer current — the version-aware redistribution shape. per_pc
8044    /// only (`Schedule::validate` rejects it on `per_target`).
8045    OncePerVersion(OncePerVersionLiteral),
8046    /// Re-arm after the humantime interval, e.g. `{ every: 6h }`.
8047    Every(EverySpec),
8048}
8049
8050/// Single-variant enum so serde accepts exactly the string `once`
8051/// (a free-form `String` would swallow typos like `onec`).
8052#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
8053#[serde(rename_all = "snake_case")]
8054pub enum OnceLiteral {
8055    Once,
8056}
8057
8058/// Single-variant enum so serde accepts exactly the string
8059/// `once_per_version` (mirrors [`OnceLiteral`]'s typo-catching). The
8060/// distinct literal — rather than a bool field on `once` — keeps the
8061/// ergonomic bare-string surface (`per_pc: once_per_version`).
8062#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
8063#[serde(rename_all = "snake_case")]
8064pub enum OncePerVersionLiteral {
8065    OncePerVersion,
8066}
8067
8068/// `{ every: <humantime> }`. Standalone struct (not an inline
8069/// struct variant). `{ evry: 6h }` still fails to parse (the
8070/// required `every` key is missing), and the create boundaries
8071/// reject the unknown `evry` via [`crate::strict`] with its path —
8072/// while agents reading a future writer's extra fields tolerate
8073/// them (#492).
8074#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8075pub struct EverySpec {
8076    /// Humantime interval (`10m`, `6h`, `1d`...). Parsed lazily —
8077    /// [`Schedule::validate`] rejects garbage at create time.
8078    pub every: String,
8079}
8080
8081impl PerPolicy {
8082    /// The cooldown this policy lowers to: `once` = `None`
8083    /// (permanent skip), `every` = the interval.
8084    fn cooldown(&self) -> Option<String> {
8085        match self {
8086            // Both `once` shapes lower to "no time-based re-arm". The
8087            // version-aware re-arm for `once_per_version` is not a
8088            // cooldown — it is the version filter the scheduler applies
8089            // to the completion set, so the cooldown stays None here.
8090            PerPolicy::Once(_) | PerPolicy::OncePerVersion(_) => None,
8091            PerPolicy::Every(EverySpec { every }) => Some(every.clone()),
8092        }
8093    }
8094}
8095
8096impl std::fmt::Display for When {
8097    /// Operator-facing one-liner (`per_pc once` / `per_pc every 6h`
8098    /// / `at 09:00 [mon-fri]` / `at 2026-06-10 09:00`) for log
8099    /// lines, audit payloads and the API's `ScheduleSummary`.
8100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8101        let policy = |p: &PerPolicy| match p {
8102            PerPolicy::Once(_) => "once".to_string(),
8103            PerPolicy::OncePerVersion(_) => "once_per_version".to_string(),
8104            PerPolicy::Every(EverySpec { every }) => format!("every {every}"),
8105        };
8106        match self {
8107            When::PerPc(p) => write!(f, "per_pc {}", policy(p)),
8108            When::PerTarget(p) => write!(f, "per_target {}", policy(p)),
8109            When::Calendar(c) if c.days.is_empty() => write!(f, "at {}", c.at),
8110            When::Calendar(c) => write!(f, "at {} [{}]", c.at, c.days.join(",")),
8111            When::On(triggers) => {
8112                let names: Vec<&str> = triggers.iter().map(|t| t.as_str()).collect();
8113                write!(f, "on [{}]", names.join(","))
8114            }
8115        }
8116    }
8117}
8118
8119impl OnTrigger {
8120    /// Lowercase wire/display label (matches the serde `snake_case`).
8121    pub fn as_str(self) -> &'static str {
8122        match self {
8123            OnTrigger::Startup => "startup",
8124            OnTrigger::Logon => "logon",
8125            OnTrigger::Lock => "lock",
8126            OnTrigger::Unlock => "unlock",
8127            OnTrigger::NetworkChange => "network_change",
8128        }
8129    }
8130}
8131
8132/// Optional validity window for a [`Schedule`] (#418 decision G).
8133/// Half-open `[from, until)`; either bound may be omitted. Bounds
8134/// are `YYYY-MM-DD` (= that day's 00:00 in the schedule's `tz`) or
8135/// full RFC3339 (offset is honored as-is, `tz` ignored). Kept as
8136/// strings so the JSON Schema the SPA editor consumes stays two
8137/// plain string fields, mirroring `jitter` / `starting_deadline`.
8138///
8139/// #418 Phase 2: bounds are evaluated in the schedule's top-level
8140/// `tz` (was UTC-only in Phase 1) so `tz: local` makes both the
8141/// calendar `at` AND the `active` window local — one consistent
8142/// timezone per schedule.
8143#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
8144pub struct Active {
8145    /// Dormant before this instant.
8146    #[serde(default, skip_serializing_if = "Option::is_none")]
8147    pub from: Option<String>,
8148    /// Dormant from this instant on (exclusive).
8149    #[serde(default, skip_serializing_if = "Option::is_none")]
8150    pub until: Option<String>,
8151}
8152
8153impl Active {
8154    /// `skip_serializing_if` helper — an empty window means "always
8155    /// active" and is omitted from the wire format entirely.
8156    pub fn is_empty(&self) -> bool {
8157        self.from.is_none() && self.until.is_none()
8158    }
8159
8160    /// Parse one bound: RFC3339 first (offset honored, `tz`
8161    /// ignored), then bare `YYYY-MM-DD` (00:00 in `tz`).
8162    pub fn parse_bound(s: &str, tz: ScheduleTz) -> Result<chrono::DateTime<chrono::Utc>, String> {
8163        if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
8164            return Ok(dt.with_timezone(&chrono::Utc));
8165        }
8166        if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
8167            let midnight = d.and_hms_opt(0, 0, 0).expect("00:00:00 is always valid");
8168            return tz.naive_to_utc(midnight).ok_or_else(|| {
8169                format!("active: bound '{s}' falls in a DST gap for the schedule's tz")
8170            });
8171        }
8172        Err(format!(
8173            "active: unparseable bound '{s}' (want YYYY-MM-DD or RFC3339)"
8174        ))
8175    }
8176
8177    /// Is `now` inside the window? Unparseable bounds are treated
8178    /// as absent here (fail-open) — [`Schedule::validate`] is the
8179    /// place that rejects them loudly; this runs on every tick and
8180    /// must never panic on a stale KV blob.
8181    pub fn contains(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
8182        let bound = |s: &Option<String>| s.as_deref().and_then(|s| Self::parse_bound(s, tz).ok());
8183        if bound(&self.from).is_some_and(|from| now < from) {
8184            return false;
8185        }
8186        if bound(&self.until).is_some_and(|until| now >= until) {
8187            return false;
8188        }
8189        true
8190    }
8191}
8192
8193/// Host-environment gate (#418 `constraints.require`). Fire only when
8194/// the target host is in the required state. Sensed **in-process by the
8195/// agent** (Win32), so it is `runs_on: agent` only — the backend cannot
8196/// read a target host's power/idle state ([`Schedule::validate`]
8197/// rejects it on `runs_on: backend`, symmetric with `when: { on }`).
8198///
8199/// Evaluated at fire time as a skip-this-tick gate (NOT in
8200/// [`Constraints::allows`], which stays pure for `preview`): a reconcile
8201/// cadence re-checks every minute (so it effectively defers until the
8202/// state is met — the intended pairing); a `calendar` fire that lands
8203/// while the state is unmet is simply missed, same as `window`. It is
8204/// therefore a *runtime* gate and does not appear in `preview`.
8205// No `Eq`: `cpu_below: Option<f64>` is only `PartialEq` (f64 is not Eq).
8206#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
8207pub struct Require {
8208    /// Fire only while on **AC power** (skip on battery). Reads
8209    /// `GetSystemPowerStatus`; an unknown/unreadable status is treated
8210    /// as not-on-AC (fail-closed — a restrictive gate must not fire
8211    /// when it can't confirm the condition). `false` (default) = no
8212    /// power requirement.
8213    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
8214    pub ac_power: bool,
8215    /// Fire only when the active console session has had **no keyboard /
8216    /// mouse input for at least this long** (humantime, e.g. `"10m"`) —
8217    /// "don't run while the user is actively working". Input-based
8218    /// (simpler than Task Scheduler's CPU/disk-aware idle). A
8219    /// headless / disconnected console (no interactive user) trivially
8220    /// satisfies it. `None` (default) = no idle requirement. Parsed
8221    /// lazily; [`Schedule::validate`] rejects garbage at create time.
8222    #[serde(default, skip_serializing_if = "Option::is_none")]
8223    pub idle: Option<String>,
8224    /// Fire only when the **whole-machine CPU usage is below this
8225    /// percent** (0–100; e.g. `20.0` = "system CPU < 20%") — "don't run
8226    /// while the box is busy". Reuses the agent's `host_perf` system CPU%
8227    /// sample (`sysinfo` mean over cores), so the reading is up to one
8228    /// `host_perf` cadence old (default 60s) — fine as a "generally
8229    /// busy?" proxy, and more accurate than a fresh one-shot read (CPU%
8230    /// needs two samples). An unavailable sample (host_perf not warmed
8231    /// up yet, or stale) is treated as "not below" (fail-closed — a
8232    /// restrictive gate must not fire when it can't confirm). `None`
8233    /// (default) = no CPU requirement. [`Schedule::validate`] rejects an
8234    /// out-of-range value at create time.
8235    #[serde(default, skip_serializing_if = "Option::is_none")]
8236    pub cpu_below: Option<f64>,
8237    /// Fire only when the host has **internet connectivity** (Windows
8238    /// `GetNetworkConnectivityHint` reports InternetAccess) — "don't run
8239    /// until online" for jobs that download / phone home. A captive
8240    /// portal (ConstrainedInternetAccess), LAN-only (LocalAccess), or
8241    /// unknown/unreadable state is treated as offline (fail-closed) — a
8242    /// portal would just fail a download, so we hold the run. For VPN /
8243    /// SASE / app-specific conditions, use a custom script gate (separate
8244    /// slice). `false` (default) = no network requirement.
8245    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
8246    pub network: bool,
8247}
8248
8249impl Require {
8250    /// `skip_serializing_if` helper for an embedded empty `require`.
8251    pub fn is_empty(&self) -> bool {
8252        !self.ac_power && self.idle.is_none() && self.cpu_below.is_none() && !self.network
8253    }
8254
8255    /// Parsed minimum-idle duration (`None` = no idle requirement, or an
8256    /// unparseable value — `validate` rejects the latter at create time).
8257    pub fn min_idle(&self) -> Option<std::time::Duration> {
8258        self.idle
8259            .as_deref()
8260            .and_then(|s| humantime::parse_duration(s.trim()).ok())
8261    }
8262
8263    /// First unparseable field for create-time rejection (mirrors
8264    /// [`Constraints::bad_skip_date`]).
8265    pub fn bad_idle(&self) -> Option<String> {
8266        self.idle.as_deref().and_then(|s| {
8267            humantime::parse_duration(s.trim())
8268                .err()
8269                .map(|e| format!("constraints.require.idle: invalid duration '{s}': {e}"))
8270        })
8271    }
8272}
8273
8274/// Host-environment state sensed by the agent, fed to [`require_met`].
8275/// A named struct (not positional args) so the growing set of sensed
8276/// signals — several of them `bool` — can't be transposed at a call
8277/// site. The Win32 sensing lives in `kanade-agent::env_gate`.
8278#[derive(Debug, Clone, Copy, Default)]
8279pub struct EnvState {
8280    /// Is the host on AC power (`false` if on battery or unreadable).
8281    pub ac_online: bool,
8282    /// How long the console has been idle (`None` = couldn't determine).
8283    pub idle: Option<std::time::Duration>,
8284    /// Whole-machine CPU usage 0–100 (`None` = no sample yet).
8285    pub cpu_pct: Option<f64>,
8286    /// Does the host have internet connectivity (`false` if offline /
8287    /// LAN-only / unreadable).
8288    pub network_up: bool,
8289}
8290
8291/// Pure env-gate decision (#418 `constraints.require`). The Win32
8292/// sensing lives in the agent (`kanade-agent::env_gate`); this is the
8293/// testable core, fed the already-sensed [`EnvState`]. Deliberately a
8294/// free fn (not folded into [`Constraints::allows`]) so `allows` stays
8295/// pure and `preview` never evaluates a runtime gate. Each set
8296/// requirement is a restrictive AND: any unmet (or unknown) gate skips.
8297pub fn require_met(req: &Require, env: &EnvState) -> bool {
8298    if req.ac_power && !env.ac_online {
8299        return false;
8300    }
8301    if let Some(min) = req.min_idle() {
8302        match env.idle {
8303            Some(d) if d >= min => {}
8304            _ => return false,
8305        }
8306    }
8307    if let Some(max) = req.cpu_below {
8308        match env.cpu_pct {
8309            Some(p) if p < max => {}
8310            _ => return false,
8311        }
8312    }
8313    if req.network && !env.network_up {
8314        return false;
8315    }
8316    true
8317}
8318
8319/// [`Active`] decides *over what date range* a schedule is live,
8320/// `Constraints` decides *when, within an active period,* a fire is
8321/// allowed: `window` (a maintenance time-of-day window),
8322/// `max_concurrent` (a fleet-wide running-instance cap), `skip_dates`
8323/// (holiday exclusion) and `require` (host-environment gates, agent-only
8324/// — see [`Require`]).
8325// No `Eq`: contains `require: Option<Require>` which holds an f64.
8326#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
8327pub struct Constraints {
8328    /// `"HH:MM-HH:MM"` wall-clock window (evaluated in the schedule's
8329    /// `tz`). Fires outside it are skipped — mainly for reconcile
8330    /// cadences ("patrol every 6h, but only fire overnight") and
8331    /// daytime change-freezes. `start > end` crosses midnight
8332    /// (`"22:00-05:00"` = 22:00 through 05:00 next morning). Parsed
8333    /// lazily; [`Schedule::validate`] rejects garbage at create time.
8334    #[serde(default, skip_serializing_if = "Option::is_none")]
8335    pub window: Option<String>,
8336    /// Fleet-wide cap on how many instances of this schedule's job may
8337    /// run **at the same time** (#418 "同時実行ハード上限"). The
8338    /// backend scheduler counts the job's still-in-flight runs
8339    /// (`execution_results.finished_at IS NULL`) each tick and only
8340    /// dispatches to as many remaining pcs as there are free slots —
8341    /// a rolling window that refills as runs complete. Useful for
8342    /// disk/CPU/network-heavy jobs you don't want hammering the whole
8343    /// fleet at once.
8344    ///
8345    /// **Backend-only** (it needs a central counter): combining it
8346    /// with `runs_on: agent` is rejected by [`Schedule::validate`]
8347    /// (#418 decision E — "中央上限には中央が要る"). Most meaningful
8348    /// for `per_pc` reconcile cadences, where the poll re-ticks and
8349    /// refills slots. `None` (default) = no cap.
8350    #[serde(default, skip_serializing_if = "Option::is_none")]
8351    pub max_concurrent: Option<u32>,
8352    /// Calendar dates the schedule must **not** fire on — holidays,
8353    /// blackout days, one-off freeze dates (#418 "祝日除外"). Each is
8354    /// `YYYY-MM-DD`, evaluated as a wall-clock date in the schedule's
8355    /// `tz`. Applies to every `when` shape (a reconcile cadence skips
8356    /// the whole day; a calendar fire landing on the date is
8357    /// suppressed) and is honored by both the live scheduler and
8358    /// `preview`, since both gate on [`Constraints::allows`]. Empty
8359    /// (default) = no skips. Operator-supplied: there is no built-in
8360    /// holiday calendar — list the dates you care about. Parsed lazily;
8361    /// [`Schedule::validate`] rejects a malformed date at create time.
8362    #[serde(default, skip_serializing_if = "Vec::is_empty")]
8363    pub skip_dates: Vec<String>,
8364    /// Host-environment gate (#418): fire only when the target host is
8365    /// in the required state (on AC power, idle). Agent-sensed at fire
8366    /// time, `runs_on: agent` only. See [`Require`]. `None` (default) =
8367    /// no environment requirement.
8368    #[serde(default, skip_serializing_if = "Option::is_none")]
8369    pub require: Option<Require>,
8370}
8371
8372impl Constraints {
8373    /// `skip_serializing_if` helper — empty constraints are omitted
8374    /// from the wire format entirely.
8375    pub fn is_empty(&self) -> bool {
8376        self.window.is_none()
8377            && self.max_concurrent.is_none()
8378            && self.skip_dates.is_empty()
8379            && self.require.as_ref().is_none_or(Require::is_empty)
8380    }
8381
8382    /// The first unparseable `skip_dates` entry, if any — the
8383    /// scheduler logs it at register time so a fail-closed
8384    /// (never-firing) schedule from a hand-edited KV blob is
8385    /// diagnosable, mirroring [`Schedule::bad_window`].
8386    pub fn bad_skip_date(&self) -> Option<String> {
8387        self.skip_dates.iter().find_map(|s| {
8388            chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d")
8389                .err()
8390                .map(|e| format!("constraints.skip_dates: invalid date '{s}': {e}"))
8391        })
8392    }
8393
8394    /// Parse `"HH:MM-HH:MM"` into `(start, end)`. Equal bounds are an
8395    /// error (a zero-width or all-day window is ambiguous — write no
8396    /// window for "always").
8397    pub fn parse_window(s: &str) -> Result<(chrono::NaiveTime, chrono::NaiveTime), String> {
8398        let (a, b) = s
8399            .split_once('-')
8400            .ok_or_else(|| format!("constraints.window: '{s}' must be 'HH:MM-HH:MM'"))?;
8401        let parse = |part: &str| {
8402            chrono::NaiveTime::parse_from_str(part.trim(), "%H:%M")
8403                .map_err(|e| format!("constraints.window: invalid time '{}': {e}", part.trim()))
8404        };
8405        let (start, end) = (parse(a)?, parse(b)?);
8406        if start == end {
8407            return Err(format!(
8408                "constraints.window: start and end are equal ('{s}'); omit window for 'always'"
8409            ));
8410        }
8411        Ok((start, end))
8412    }
8413
8414    /// Is a fire allowed at `now` (evaluated in `tz`)? No window =
8415    /// always allowed. Half-open `[start, end)`; `start > end`
8416    /// crosses midnight.
8417    ///
8418    /// **Fail-closed** on an unparseable window (returns `false`,
8419    /// gemini #452 review): a window is a *restrictive* constraint
8420    /// (change-freeze / overnight-only), so a corrupt one must NOT
8421    /// silently allow fires during the restricted hours. Bad windows
8422    /// are rejected at create time by [`Schedule::validate`]; this
8423    /// only bites a hand-edited KV blob, where blocking is the safe
8424    /// direction. The scheduler warns at register time
8425    /// ([`Schedule::bad_window`]) so a stuck schedule is diagnosable.
8426    /// The tick path never panics regardless.
8427    pub fn allows(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
8428        // #418 holiday / blackout dates: never fire on a listed wall
8429        // date (in `tz`). Checked before the window since a skipped day
8430        // overrides any within-window allowance. Fail-closed on a
8431        // corrupt entry (same posture as `window`): a skip date is a
8432        // *restrictive* constraint, so a garbled one must not silently
8433        // re-enable fires — it blocks until fixed (`validate` rejects it
8434        // at create time; `bad_skip_date` lets the scheduler warn).
8435        if !self.skip_dates.is_empty() {
8436            let today = tz.wall_date(now);
8437            let blocked = self.skip_dates.iter().any(|s| {
8438                match chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d") {
8439                    Ok(d) => d == today,
8440                    Err(_) => true, // corrupt entry → fail-closed (block)
8441                }
8442            });
8443            if blocked {
8444                return false;
8445            }
8446        }
8447        match self.window.as_deref() {
8448            // No window → always allowed.
8449            None => true,
8450            // Window set: membership, or fail-closed if unparseable
8451            // (`window_contains` returns None for a corrupt window).
8452            Some(_) => self.window_contains(tz.wall_time(now)).unwrap_or(false),
8453        }
8454    }
8455
8456    /// Membership of a wall-clock time-of-day in the window. `None`
8457    /// when there is no window or it's unparseable (callers decide
8458    /// the failure direction). `start > end` crosses midnight.
8459    fn window_contains(&self, t: chrono::NaiveTime) -> Option<bool> {
8460        let (start, end) = Self::parse_window(self.window.as_deref()?).ok()?;
8461        Some(if start <= end {
8462            start <= t && t < end
8463        } else {
8464            t >= start || t < end
8465        })
8466    }
8467}
8468
8469/// What to do when a fire's script fails (#418 Phase 4 — the "高"
8470/// retry/backoff gap). Where [`Constraints`] gates *whether* a fire
8471/// happens, `OnFailure` decides what happens *after* one ran and
8472/// came back bad. Only `retry` so far; future `notify` / `disable`
8473/// would join the same namespace.
8474#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
8475pub struct OnFailure {
8476    /// Re-run the script in-process when it exits non-zero (or times
8477    /// out), up to a cap, with a fixed backoff between attempts.
8478    /// `None` (default) = no retry: a failed run is published as-is
8479    /// and (for reconcile cadences) simply re-fires on the next poll
8480    /// tick. See [`Retry`].
8481    #[serde(default, skip_serializing_if = "Option::is_none")]
8482    pub retry: Option<Retry>,
8483}
8484
8485impl OnFailure {
8486    /// `skip_serializing_if` helper — an empty policy is omitted from
8487    /// the wire format entirely.
8488    pub fn is_empty(&self) -> bool {
8489        self.retry.is_none()
8490    }
8491
8492    /// Lower the operator-facing `retry` (humantime backoff) onto the
8493    /// engine vocabulary the agent's executor runs on (backoff in
8494    /// whole seconds). Single seam shared by the backend command
8495    /// builder and the agent's local scheduler so the two stamp the
8496    /// same [`crate::wire::RetrySpec`] onto every Command. Returns
8497    /// `None` when there is no retry policy or the backoff is
8498    /// unparseable (validate() rejects the latter at create time;
8499    /// this stays fail-safe = "no retry" for a hand-edited KV blob
8500    /// rather than panicking on the fire path).
8501    pub fn lowered_retry(&self) -> Option<crate::wire::RetrySpec> {
8502        let r = self.retry.as_ref()?;
8503        let backoff_secs = humantime::parse_duration(&r.backoff).ok()?.as_secs();
8504        Some(crate::wire::RetrySpec {
8505            max: r.max,
8506            backoff_secs,
8507        })
8508    }
8509}
8510
8511/// Fixed-backoff retry policy (#418 Phase 4). `max` is the number of
8512/// *additional* attempts after the first run (so `max: 3` = up to 4
8513/// total executions); `backoff` is the humantime delay slept between
8514/// attempts. The retry happens fire-side (inside `kanade fire` /
8515/// `handle_command`) on every OS for the PoC — the Windows-native
8516/// "restart on failure" Task Scheduler path is deferred to the
8517/// native-delegation phase (#418 decision H).
8518#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8519pub struct Retry {
8520    /// Max additional attempts after the first failure. Bounded
8521    /// `1..=10` by [`Schedule::validate`] — a typo'd `max: 1000`
8522    /// with a short backoff would otherwise pin a flapping script in
8523    /// a tight loop for the whole window.
8524    pub max: u32,
8525    /// Humantime delay slept between attempts (`"10m"`, `"30s"`).
8526    pub backoff: String,
8527}
8528
8529/// Fleet-wide change-freeze (#418 Phase 5 — the "メンテナンス窓 /
8530/// 変更凍結" gap's global half). Where [`Constraints::window`] is a
8531/// *per-schedule* time-of-day gate, a `Freeze` is a *single, fleet-
8532/// global* "stop all automated change" switch the operator flips
8533/// during an incident or a year-end change-freeze. It lives in its
8534/// own KV singleton ([`crate::kv::KEY_FREEZE`]); when present and
8535/// active, both the backend scheduler and every agent's local
8536/// scheduler skip *every* fire.
8537///
8538/// Shapes:
8539/// * `{}` (no bounds) — frozen indefinitely until the operator
8540///   clears it (incident "big red button").
8541/// * `{ from, until }` — frozen only within `[from, until)`,
8542///   evaluated in `tz` (planned change-freeze; auto-thaws).
8543///
8544/// The KV key being *absent* means "not frozen" — so clearing the
8545/// freeze is a KV delete, and `is_active` only ever runs on a freeze
8546/// the operator actually set.
8547#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
8548pub struct Freeze {
8549    /// Frozen from this instant (RFC3339 or bare `YYYY-MM-DD` in
8550    /// `tz`). `None` ⇒ frozen from the beginning of time.
8551    #[serde(default, skip_serializing_if = "Option::is_none")]
8552    pub from: Option<String>,
8553    /// Thawed from this instant on, exclusive. `None` ⇒ frozen with
8554    /// no scheduled end (manual clear required).
8555    #[serde(default, skip_serializing_if = "Option::is_none")]
8556    pub until: Option<String>,
8557    /// Operator-supplied note surfaced on the freeze-skip log and the
8558    /// SPA banner ("year-end change freeze", "INC-1234"). Advisory.
8559    #[serde(default, skip_serializing_if = "Option::is_none")]
8560    pub reason: Option<String>,
8561    /// Timezone the bare-date bounds are evaluated in (RFC3339 bounds
8562    /// carry their own offset). Defaults to host-local like a
8563    /// schedule's `tz`.
8564    #[serde(default)]
8565    pub tz: ScheduleTz,
8566}
8567
8568impl Freeze {
8569    /// Is the fleet frozen at `now`? An empty window (`from`/`until`
8570    /// both absent) is frozen unconditionally; otherwise membership of
8571    /// `[from, until)` in `tz`. Half-open like [`Active::contains`],
8572    /// but **fails CLOSED** on an unparseable bound — a freeze is a
8573    /// safety switch, so a corrupt window (only reachable via a
8574    /// hand-edited KV blob; `validate` rejects it at set time) must
8575    /// mean "frozen", not "fire normally" (coderabbit #472). This is
8576    /// the one deliberate divergence from `active`'s fail-OPEN
8577    /// behaviour, where an unparseable bound dormant-skips a schedule.
8578    pub fn is_active(&self, now: chrono::DateTime<chrono::Utc>) -> bool {
8579        // Parse a bound; an unparseable one short-circuits the whole
8580        // check to `true` (frozen) via the closure's `None` sentinel
8581        // handled below.
8582        let bound = |s: &Option<String>| -> Result<Option<chrono::DateTime<chrono::Utc>>, ()> {
8583            match s.as_deref() {
8584                None => Ok(None),
8585                Some(raw) => Active::parse_bound(raw, self.tz).map(Some).map_err(|_| ()),
8586            }
8587        };
8588        let (from, until) = match (bound(&self.from), bound(&self.until)) {
8589            (Ok(f), Ok(u)) => (f, u),
8590            // Any corrupt bound → fail closed (frozen).
8591            _ => return true,
8592        };
8593        if from.is_some_and(|f| now < f) {
8594            return false;
8595        }
8596        if until.is_some_and(|u| now >= u) {
8597            return false;
8598        }
8599        true
8600    }
8601
8602    /// Reject unparseable bounds / `from >= until` at set time (the
8603    /// API + CLI counterpart to [`Schedule::validate`]).
8604    pub fn validate(&self) -> Result<(), String> {
8605        let from = self
8606            .from
8607            .as_deref()
8608            .map(|s| Active::parse_bound(s, self.tz))
8609            .transpose()
8610            .map_err(|e| e.replace("active:", "freeze:"))?;
8611        let until = self
8612            .until
8613            .as_deref()
8614            .map(|s| Active::parse_bound(s, self.tz))
8615            .transpose()
8616            .map_err(|e| e.replace("active:", "freeze:"))?;
8617        if let (Some(f), Some(u)) = (from, until) {
8618            if f >= u {
8619                return Err(format!(
8620                    "freeze.from ({}) must be strictly before freeze.until ({})",
8621                    self.from.as_deref().unwrap_or_default(),
8622                    self.until.as_deref().unwrap_or_default(),
8623                ));
8624            }
8625        }
8626        Ok(())
8627    }
8628}
8629
8630/// The system-generated poll cadence every reconcile-shaped `when`
8631/// lowers to. Operators never write this: the real inter-run
8632/// spacing is the `every` cooldown; this only bounds "how soon do
8633/// we notice somebody is due" (#418 decision B took the poll
8634/// period away from the operator).
8635pub const POLL_CRON: &str = "0 * * * * *";
8636
8637/// What a [`When`] lowers to — the exact (cron, mode, cooldown)
8638/// trio the pre-#418 engine ran on. Keeping the engine vocabulary
8639/// unchanged is what lets Phase 1 swap the operator surface without
8640/// touching the tick / dedup machinery.
8641pub struct Lowered {
8642    /// Cron handed to `tokio-cron-scheduler` — [`POLL_CRON`] for
8643    /// reconcile shapes, a 6/7-field cron for calendar shapes.
8644    pub cron: String,
8645    /// Dedup semantics for `decide_fire`.
8646    pub mode: ExecMode,
8647    /// Humantime re-arm interval (`None` = succeed once, skip
8648    /// forever).
8649    pub cooldown: Option<String>,
8650    /// Timezone to evaluate `cron` in (#418 Phase 2). The scheduler
8651    /// passes this to `Job::new_async_tz`. Reconcile shapes carry
8652    /// the schedule's tz too even though POLL_CRON is tz-agnostic,
8653    /// so the same value drives the `active`-window check.
8654    pub tz: ScheduleTz,
8655}
8656
8657impl Schedule {
8658    /// The error message if this schedule's `constraints.window` is
8659    /// set but unparseable, else `None`. The scheduler logs this at
8660    /// register time so a fail-closed (never-firing) schedule from a
8661    /// hand-edited KV blob is diagnosable (gemini #452 review).
8662    pub fn bad_window(&self) -> Option<String> {
8663        let w = self.constraints.window.as_deref()?;
8664        Constraints::parse_window(w).err()
8665    }
8666
8667    /// True when this is a `calendar` schedule whose fire time can
8668    /// never fall inside its `constraints.window` — the cron fires,
8669    /// the window check rejects it, and (firing only at that
8670    /// time-of-day) it effectively never runs. An easy misconfig to
8671    /// set up by accident; the scheduler warns at register time
8672    /// (claude #452 review). Reconcile shapes poll every minute, so
8673    /// they always catch the window opening and aren't affected.
8674    pub fn calendar_outside_window(&self) -> bool {
8675        let When::Calendar(c) = &self.when else {
8676            return false;
8677        };
8678        let Some(t) = c.fire_time() else {
8679            return false;
8680        };
8681        matches!(self.constraints.window_contains(t), Some(false))
8682    }
8683
8684    /// Up to `count` future instants this schedule will fire, as
8685    /// absolute UTC, strictly after `now` — the dry-run / preview
8686    /// surface (#418 "ドライラン / プレビュー"). Only **calendar**
8687    /// schedules have discrete fire times; reconcile shapes
8688    /// (`per_pc`/`per_target`) poll every minute gated by cooldown, so
8689    /// they return an empty vec and the caller describes the cadence
8690    /// instead. Occurrences outside the `active.{from,until}` window or
8691    /// the `constraints.window` are **skipped**, so the list reflects
8692    /// when the schedule will ACTUALLY run, not the raw cron ticks.
8693    /// Evaluated in the schedule's `tz`, exactly like the scheduler's
8694    /// `Job::new_async_tz`, and with the same croner config the
8695    /// scheduler / [`Schedule::validate`] use, so a preview can never
8696    /// disagree with a real fire. A schedule that can never fire (a
8697    /// calendar time wholly outside its window, a past one-shot,
8698    /// `enabled: false` is *not* considered here — callers gate on
8699    /// `enabled` separately) yields an empty vec.
8700    pub fn preview_fires(
8701        &self,
8702        now: chrono::DateTime<chrono::Utc>,
8703        count: usize,
8704    ) -> Vec<chrono::DateTime<chrono::Utc>> {
8705        use croner::parser::{CronParser, Seconds};
8706        if !matches!(self.when, When::Calendar(_)) {
8707            return Vec::new();
8708        }
8709        // Same lowering + croner config as `next_calendar_fire` and the
8710        // live scheduler, so a preview can never disagree with a real
8711        // fire. `preview_fires` adds the N-occurrence walk and the
8712        // active / window filtering on top of that single seam.
8713        let lowered = self.lowered();
8714        let Ok(cron) = CronParser::builder()
8715            .seconds(Seconds::Required)
8716            .dom_and_dow(true)
8717            .build()
8718            .parse(&lowered.cron)
8719        else {
8720            return Vec::new();
8721        };
8722        let accept = |utc: chrono::DateTime<chrono::Utc>| {
8723            self.active.contains(utc, self.tz) && self.constraints.allows(utc, self.tz)
8724        };
8725        match self.tz {
8726            ScheduleTz::Utc => Self::next_occurrences(&cron, now, count, accept),
8727            ScheduleTz::Local => {
8728                Self::next_occurrences(&cron, now.with_timezone(&chrono::Local), count, accept)
8729            }
8730        }
8731    }
8732
8733    /// Walk croner forward from `after` collecting up to `count`
8734    /// accepted occurrences (converted to UTC). Generic over the tz the
8735    /// cron is evaluated in so `preview_fires` can run it in either
8736    /// `Utc` or `Local` without duplicating the loop.
8737    fn next_occurrences<Tz>(
8738        cron: &croner::Cron,
8739        after: chrono::DateTime<Tz>,
8740        count: usize,
8741        accept: impl Fn(chrono::DateTime<chrono::Utc>) -> bool,
8742    ) -> Vec<chrono::DateTime<chrono::Utc>>
8743    where
8744        Tz: chrono::TimeZone,
8745    {
8746        // Bound the scan so an `active`/window dead-end (every future
8747        // tick rejected) can't spin forever: ~4096 raw ticks covers
8748        // >10y of a daily calendar while staying instant for croner.
8749        const SCAN_CAP: usize = 4096;
8750        let mut out = Vec::with_capacity(count.min(SCAN_CAP));
8751        let mut cursor = after;
8752        let mut scanned = 0usize;
8753        while out.len() < count && scanned < SCAN_CAP {
8754            scanned += 1;
8755            let Ok(next) = cron.find_next_occurrence(&cursor, false) else {
8756                break;
8757            };
8758            let utc = next.with_timezone(&chrono::Utc);
8759            if accept(utc) {
8760                out.push(utc);
8761            }
8762            // `find_next_occurrence(.., inclusive = false)` already
8763            // advances strictly past `cursor`, so handing it `next`
8764            // verbatim gets the following occurrence — no manual +1s
8765            // nudge (and `DateTime<Tz>` is `Copy`, so no clone).
8766            cursor = next;
8767        }
8768        out
8769    }
8770
8771    /// Lower the operator-facing `when` onto the engine vocabulary.
8772    /// Single seam shared by the backend scheduler and the agent's
8773    /// local scheduler so the two can never drift.
8774    pub fn lowered(&self) -> Lowered {
8775        let tz = self.tz;
8776        match &self.when {
8777            When::PerPc(p) => Lowered {
8778                cron: POLL_CRON.into(),
8779                // `once_per_version` re-arms each pc when the manifest
8780                // version changes; the scheduler keys that dedup on
8781                // `execution_results.version`. Plain `once` / `every`
8782                // stay version-blind.
8783                mode: match p {
8784                    PerPolicy::OncePerVersion(_) => ExecMode::OncePerPcVersion,
8785                    PerPolicy::Once(_) | PerPolicy::Every(_) => ExecMode::OncePerPc,
8786                },
8787                cooldown: p.cooldown(),
8788                tz,
8789            },
8790            When::PerTarget(p) => Lowered {
8791                cron: POLL_CRON.into(),
8792                mode: ExecMode::OncePerTarget,
8793                cooldown: p.cooldown(),
8794                tz,
8795            },
8796            // `to_cron` only fails on a malformed `at` (rejected by
8797            // validate() at create time). For a hand-edited KV blob
8798            // that slipped past, emit a deliberately-invalid cron so
8799            // register()'s Job::new_async_tz fails → warn+skip,
8800            // rather than firing at the wrong time.
8801            When::Calendar(c) => Lowered {
8802                cron: c
8803                    .to_cron()
8804                    .unwrap_or_else(|_| "# invalid calendar at".into()),
8805                mode: ExecMode::EveryTick,
8806                cooldown: None,
8807                tz,
8808            },
8809            // Event triggers have no cron — the agent fires them from an
8810            // OS event source. The `# event-trigger` cron is never
8811            // registered (the scheduler branches on `is_event()` first),
8812            // but keep it deliberately-invalid as a belt-and-suspenders
8813            // so a stray registration would fail rather than misfire.
8814            When::On(_) => Lowered {
8815                cron: "# event-trigger (no cron)".into(),
8816                mode: ExecMode::Event,
8817                cooldown: None,
8818                tz,
8819            },
8820        }
8821    }
8822
8823    /// True when this schedule fires from an OS event (`when: { on }`)
8824    /// rather than a clock — the agent skips `tokio-cron` registration
8825    /// for these and drives them from boot / session-change instead.
8826    pub fn is_event(&self) -> bool {
8827        matches!(self.when, When::On(_))
8828    }
8829
8830    /// The OS event triggers this schedule listens for, or `&[]` when it
8831    /// is not an event schedule.
8832    pub fn event_triggers(&self) -> &[OnTrigger] {
8833        match &self.when {
8834            When::On(t) => t,
8835            _ => &[],
8836        }
8837    }
8838
8839    /// The next absolute (UTC) time this schedule fires, or `None` when
8840    /// it has no discrete upcoming fire to preview.
8841    ///
8842    /// Used by the KLP `maintenance.list` preview ("what's about to
8843    /// happen on my PC", SPEC §2.1). Returns `None` for:
8844    ///
8845    /// - reconcile shapes (`per_pc` / `per_target`) — they lower to the
8846    ///   every-minute [`POLL_CRON`] and re-converge state continuously,
8847    ///   so "next fire" is always ~60s away and means nothing to a user
8848    ///   previewing upcoming maintenance;
8849    /// - a calendar schedule whose lowered cron won't parse (a
8850    ///   hand-edited KV blob that slipped past [`Schedule::validate`]);
8851    /// - a cron with no future occurrence.
8852    ///
8853    /// The wall-clock fire is evaluated in the schedule's own `tz`
8854    /// (matching the live tick's `Job::new_async_tz`) then normalised
8855    /// to UTC for the wire. `inclusive = false`: strictly the *next*
8856    /// fire after `now`, never one matching the current instant.
8857    pub fn next_calendar_fire(
8858        &self,
8859        now: chrono::DateTime<chrono::Utc>,
8860    ) -> Option<chrono::DateTime<chrono::Utc>> {
8861        if !matches!(self.when, When::Calendar(_)) {
8862            return None;
8863        }
8864        let lowered = self.lowered();
8865        // Same parser configuration tokio-cron-scheduler 0.15 uses
8866        // internally, so this can never compute a fire the live
8867        // scheduler wouldn't (seconds required, DOM-and-DOW honored).
8868        let cron = croner::parser::CronParser::builder()
8869            .seconds(croner::parser::Seconds::Required)
8870            .dom_and_dow(true)
8871            .build()
8872            .parse(&lowered.cron)
8873            .ok()?;
8874        match lowered.tz {
8875            ScheduleTz::Utc => cron.find_next_occurrence(&now, false).ok(),
8876            ScheduleTz::Local => {
8877                let now_local = now.with_timezone(&chrono::Local);
8878                cron.find_next_occurrence(&now_local, false)
8879                    .ok()
8880                    .map(|t| t.with_timezone(&chrono::Utc))
8881            }
8882        }
8883    }
8884
8885    /// Cross-field semantic checks that don't fit pure serde derive
8886    /// — the [`Manifest::validate`] counterpart (#418 decision F;
8887    /// pre-Phase-1 a broken schedule was accepted at create time
8888    /// and silently warn-skipped at tick time). Run at every create
8889    /// site: `kanade schedule create` (client-side) and
8890    /// `POST /api/schedules`. The job_id-exists check lives in the
8891    /// API handler instead — it needs the JOBS KV.
8892    pub fn validate(&self) -> Result<(), String> {
8893        if matches!(self.runs_on, RunsOn::Agent) && matches!(self.when, When::PerTarget(_)) {
8894            return Err(
8895                "when.per_target needs fleet-wide completion data and is backend-only; \
8896                 it cannot be combined with runs_on: agent (each agent self-schedules, \
8897                 so per-target dedup would be deduping across a target of 1)"
8898                    .into(),
8899            );
8900        }
8901        // `once_per_version` is a per_pc-only shape: it re-arms an
8902        // individual pc when the manifest version it succeeded at is no
8903        // longer current. "One delegate per version" for a whole target
8904        // has no clear meaning, so reject it rather than silently
8905        // lowering to plain per_target (version-blind).
8906        if matches!(self.when, When::PerTarget(PerPolicy::OncePerVersion(_))) {
8907            return Err(
8908                "when.per_target: once_per_version is not supported — once_per_version \
8909                 re-arms per pc per manifest version, which only makes sense for per_pc. \
8910                 Use `per_pc: once_per_version`."
8911                    .into(),
8912            );
8913        }
8914        // `once_per_version` keys its dedup on the backend's
8915        // `execution_results.version` history. A runs_on: agent schedule
8916        // self-schedules from the agent's local completion map, which has
8917        // no per-version record, so it is backend-only (symmetric with
8918        // per_target). Reject it rather than silently degrade to
8919        // version-blind kitting-once on the agent.
8920        if matches!(self.runs_on, RunsOn::Agent)
8921            && matches!(self.when, When::PerPc(PerPolicy::OncePerVersion(_)))
8922        {
8923            return Err(
8924                "when.per_pc: once_per_version keys its dedup on the backend's per-version \
8925                 completion history and is backend-only; it cannot be combined with \
8926                 runs_on: agent (the agent self-schedules with no per-version record). \
8927                 Use runs_on: backend."
8928                    .into(),
8929            );
8930        }
8931        // #418 event triggers: the agent owns the OS event source
8932        // (boot / session-change), so `when: { on }` is agent-only and
8933        // needs at least one trigger.
8934        if let When::On(triggers) = &self.when {
8935            if !matches!(self.runs_on, RunsOn::Agent) {
8936                return Err(
8937                    "when.on (OS event trigger) is fired by the agent's own event \
8938                     source, so it requires runs_on: agent"
8939                        .into(),
8940                );
8941            }
8942            if triggers.is_empty() {
8943                return Err(
8944                    "when.on must list at least one trigger (e.g. [startup, logon])".into(),
8945                );
8946            }
8947        }
8948        if let Some(cd) = self.lowered().cooldown.as_deref() {
8949            humantime::parse_duration(cd)
8950                .map_err(|e| format!("when.every: invalid duration '{cd}': {e}"))?;
8951        }
8952        if let When::Calendar(c) = &self.when {
8953            // Lower the calendar form to its cron (catches a bad `at`
8954            // and the date+days conflict), then validate that cron
8955            // with the same parser configuration tokio-cron-scheduler
8956            // 0.15 uses internally (croner, seconds required,
8957            // DOM-and-DOW both honored, year optional) — create-time
8958            // validation can never accept what register() rejects.
8959            let cron = c.to_cron()?;
8960            croner::parser::CronParser::builder()
8961                .seconds(croner::parser::Seconds::Required)
8962                .dom_and_dow(true)
8963                .build()
8964                .parse(&cron)
8965                .map_err(|e| format!("when.at lowered to invalid cron '{cron}': {e}"))?;
8966        }
8967        // The other humantime strings on the schedule (claude #419
8968        // review): runtime degrades gracefully on both (bad jitter →
8969        // silent no-op, bad starting_deadline → warn + skipped tick),
8970        // but "rejected at create time" should cover every field the
8971        // operator can typo, not just `when`.
8972        if let Some(j) = &self.plan.jitter {
8973            humantime::parse_duration(j)
8974                .map_err(|e| format!("jitter: invalid duration '{j}': {e}"))?;
8975        }
8976        if let Some(sd) = &self.starting_deadline {
8977            humantime::parse_duration(sd)
8978                .map_err(|e| format!("starting_deadline: invalid duration '{sd}': {e}"))?;
8979        }
8980        // #917: the plan side got almost no create-time checks, so
8981        // several never-fires / fails-every-tick shapes were accepted
8982        // and only surfaced at dispatch time — or never:
8983        //
8984        // (1) a target that dispatches nothing. A runs_on: agent
8985        // schedule matches each agent against `target` (rollout waves
8986        // are backend-published and never reach that path), so an
8987        // unspecified target silently never fires; a runs_on: backend
8988        // one warn-fails every tick at the exec boundary, which
8989        // rejects the same shape with the same message.
8990        let has_waves = self
8991            .plan
8992            .rollout
8993            .as_ref()
8994            .is_some_and(|r| !r.waves.is_empty());
8995        if matches!(self.runs_on, RunsOn::Agent) {
8996            if !self.plan.target.is_specified() {
8997                return Err(
8998                    "target must specify at least one of `all` / `groups` / `pcs` — a \
8999                     runs_on: agent schedule matches each agent against `target`, so an \
9000                     unspecified target never fires anywhere"
9001                        .into(),
9002                );
9003            }
9004            if self.plan.rollout.is_some() {
9005                return Err(
9006                    "rollout waves are published by the backend and are ignored by \
9007                     runs_on: agent schedules (each agent self-schedules from `target`); \
9008                     drop `rollout:` or use runs_on: backend"
9009                        .into(),
9010                );
9011            }
9012        } else if !has_waves && !self.plan.target.is_specified() {
9013            return Err(
9014                "target must specify at least one of `all` / `groups` / `pcs` \
9015                 (or set `rollout.waves`) — the exec boundary rejects an \
9016                 unspecified target, so the schedule would fail every tick"
9017                    .into(),
9018            );
9019        }
9020        // (2) rollout waves were never validated: a blank group or an
9021        // unparseable delay failed at EVERY fire (the CLI doesn't even
9022        // expose waves, so the failure was always deferred to dispatch)
9023        // and an empty list dispatched nothing. (3) A wave delayed to
9024        // or past starting_deadline is dead on arrival: the deadline is
9025        // stamped once at tick time and the Command is serialised
9026        // before the wave sleep, so agents receive it already expired
9027        // (a synthetic exit-125 skip on every fire).
9028        if let Some(rollout) = &self.plan.rollout {
9029            if rollout.waves.is_empty() {
9030                return Err(
9031                    "rollout.waves must list at least one wave; omit `rollout:` for a \
9032                     one-shot fan-out of `target`"
9033                        .into(),
9034                );
9035            }
9036            let deadline = self
9037                .starting_deadline
9038                .as_deref()
9039                .and_then(|sd| humantime::parse_duration(sd).ok());
9040            for (i, wave) in rollout.waves.iter().enumerate() {
9041                if wave.group.trim().is_empty() {
9042                    return Err(format!("rollout.waves[{i}].group must not be blank"));
9043                }
9044                let delay = humantime::parse_duration(&wave.delay).map_err(|e| {
9045                    format!(
9046                        "rollout.waves[{i}].delay: invalid duration '{}': {e}",
9047                        wave.delay
9048                    )
9049                })?;
9050                if let Some(deadline) = deadline
9051                    && delay >= deadline
9052                {
9053                    return Err(format!(
9054                        "rollout.waves[{i}].delay ('{}') must be shorter than \
9055                         starting_deadline ('{}'): the deadline is stamped at tick time, \
9056                         so this wave's Commands would already be expired when published \
9057                         (skipped by every agent, every fire)",
9058                        wave.delay,
9059                        self.starting_deadline.as_deref().unwrap_or_default(),
9060                    ));
9061                }
9062            }
9063        }
9064        // (4) deadline_at is machine-stamped: the scheduler overwrites
9065        // it from `tick + starting_deadline` on every fire, so an
9066        // operator-set value is silently discarded — reject it and
9067        // point at the knob that does what they meant. (Ad-hoc POST
9068        // /api/exec bodies are a different write path and may still
9069        // carry it.)
9070        if self.plan.deadline_at.is_some() {
9071            return Err(
9072                "deadline_at is computed by the scheduler (tick time + starting_deadline) \
9073                 and overwritten on every fire — set `starting_deadline` instead"
9074                    .into(),
9075            );
9076        }
9077        let from = self
9078            .active
9079            .from
9080            .as_deref()
9081            .map(|s| Active::parse_bound(s, self.tz))
9082            .transpose()?;
9083        let until = self
9084            .active
9085            .until
9086            .as_deref()
9087            .map(|s| Active::parse_bound(s, self.tz))
9088            .transpose()?;
9089        if let (Some(f), Some(u)) = (from, until) {
9090            if f >= u {
9091                return Err(format!(
9092                    "active.from ({}) must be strictly before active.until ({})",
9093                    self.active.from.as_deref().unwrap_or_default(),
9094                    self.active.until.as_deref().unwrap_or_default(),
9095                ));
9096            }
9097        }
9098        // #418 Phase 3: a bad maintenance window is rejected at create
9099        // time (parse_window also catches equal bounds).
9100        if let Some(w) = self.constraints.window.as_deref() {
9101            Constraints::parse_window(w)?;
9102        }
9103        // #418 holiday exclusion: reject a malformed skip date at create
9104        // time so the fail-closed `allows` path only ever bites a
9105        // hand-edited KV blob, not a fresh `kanade schedule create`.
9106        if let Some(err) = self.constraints.bad_skip_date() {
9107            return Err(err);
9108        }
9109        // #418: constraints.max_concurrent is a central running-instance
9110        // cap, so it needs the backend's counter — reject it on
9111        // runs_on: agent (decision E), and reject a meaningless 0.
9112        if let Some(mc) = self.constraints.max_concurrent {
9113            // Check the structural incompatibility (agent has no central
9114            // counter) before the value range, so a `max_concurrent: 0`
9115            // + `runs_on: agent` combo reports the more fundamental
9116            // problem first (claude #542).
9117            if matches!(self.runs_on, RunsOn::Agent) {
9118                return Err(
9119                    "constraints.max_concurrent needs a central counter and is backend-only; \
9120                     it cannot be combined with runs_on: agent (each agent self-schedules, \
9121                     so there is no fleet-wide count to cap against)"
9122                        .into(),
9123                );
9124            }
9125            if mc == 0 {
9126                return Err(
9127                    "constraints.max_concurrent must be >= 1 (0 would never fire; \
9128                     omit it for no cap)"
9129                        .into(),
9130                );
9131            }
9132        }
9133        // #418: constraints.require (host-state env gates: ac_power /
9134        // idle / cpu_below / network) is sensed in-process by the agent,
9135        // so it needs runs_on: agent — the backend can't read a target
9136        // host's power / idle / cpu / connectivity state. Symmetric with
9137        // `when: { on }` (also agent-only); inverse of max_concurrent
9138        // (backend-only).
9139        if let Some(req) = &self.constraints.require {
9140            if !req.is_empty() && matches!(self.runs_on, RunsOn::Backend) {
9141                return Err(
9142                    "constraints.require (host-state env gates: ac_power / idle / cpu_below / \
9143                     network) is sensed in-process by the agent and needs runs_on: agent; the \
9144                     backend cannot read a target host's power / idle / cpu / connectivity state"
9145                        .into(),
9146                );
9147            }
9148            // Reject a malformed idle duration at create time so the
9149            // fail-closed runtime path only ever bites a hand-edited
9150            // KV blob (mirror skip_dates / on_failure.retry).
9151            if let Some(err) = req.bad_idle() {
9152                return Err(err);
9153            }
9154            // cpu_below is a percent — reject out-of-range so a typo
9155            // can't make a schedule that never (>=100 is always-busy?
9156            // no — <0 never matches) or trivially fires.
9157            if let Some(c) = req.cpu_below
9158                && !(c > 0.0 && c <= 100.0)
9159            {
9160                return Err(format!(
9161                    "constraints.require.cpu_below must be in (0, 100] percent (got {c}); \
9162                     omit it for no CPU requirement"
9163                ));
9164            }
9165        }
9166        // #418 Phase 4: a bad on_failure.retry is rejected at create
9167        // time — backoff must be valid humantime, and max is bounded
9168        // so a typo can't pin a flapping script in a tight loop.
9169        if let Some(r) = &self.on_failure.retry {
9170            let backoff = humantime::parse_duration(&r.backoff).map_err(|e| {
9171                format!(
9172                    "on_failure.retry.backoff: invalid duration '{}': {e}",
9173                    r.backoff
9174                )
9175            })?;
9176            // The wire form lowers backoff to whole seconds, so a
9177            // sub-second value would silently become a 0s no-wait
9178            // (coderabbit #466). Reject it rather than honour a backoff
9179            // the operator can't actually get.
9180            if backoff.as_secs() < 1 {
9181                return Err(format!(
9182                    "on_failure.retry.backoff must be >= 1s (got '{}'); sub-second backoffs \
9183                     round to 0 on the wire",
9184                    r.backoff
9185                ));
9186            }
9187            if !(1..=10).contains(&r.max) {
9188                return Err(format!(
9189                    "on_failure.retry.max must be 1..=10 (got {}); it counts additional \
9190                     attempts after the first run",
9191                    r.max
9192                ));
9193            }
9194        }
9195        // A blank / whitespace-only tag renders an empty filter chip on
9196        // the Schedules page — reject it at create time, mirroring the
9197        // Manifest::validate tag guard.
9198        for tag in &self.tags {
9199            if tag.trim().is_empty() {
9200                return Err("tags must not contain empty entries".to_string());
9201            }
9202        }
9203        Ok(())
9204    }
9205}
9206
9207/// Shared `serde(default)` for `bool` fields that default to `true`
9208/// (e.g. `CheckHint::fleet` / `CheckHint::health`). Generic name so it
9209/// doesn't read as "fleet" when reused for `health`.
9210fn default_true() -> bool {
9211    true
9212}