Skip to main content

kanade_shared/
manifest.rs

1use serde::{Deserialize, Serialize};
2
3use crate::wire::{FinalizeCommand, RunAs, Shell, Staleness};
4
5/// YAML job manifest (= registered "what to run", v0.18.0+).
6///
7/// Owns only script-intrinsic fields. **Who** (`target`), **how to
8/// phase fanout** (`rollout`), and **when to stagger start**
9/// (`jitter`) all moved to the Schedule / exec request side — same
10/// script can now be fired against different targets / rollouts
11/// without copying the script body.
12///
13/// #492: these types are READ fleet-wide (agents decode them from
14/// BUCKET_JOBS / BUCKET_SCHEDULES and inside live Commands), so they
15/// must tolerate unknown fields — `deny_unknown_fields` here made a
16/// gradually-upgrading fleet's OLD agents reject the whole object
17/// the moment a newer backend added any field. Operator typo
18/// protection (the old reason for the attribute) lives at the WRITE
19/// boundaries instead: `kanade job/schedule create` and the backend
20/// POST extractor parse via [`crate::strict`], which rejects unknown
21/// keys with their full paths. The wire rule: new fields always get
22/// `#[serde(default)]` (+ `skip_serializing_if` while old readers
23/// may still be strict).
24#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
25pub struct Manifest {
26    pub id: String,
27    pub version: String,
28    #[serde(default)]
29    pub description: Option<String>,
30    pub execute: Execute,
31    #[serde(default)]
32    pub require_approval: bool,
33    /// Opt-in marker that this job produces a JSON inventory fact
34    /// payload on stdout. When present, the backend's results
35    /// projector parses `ExecResult.stdout` as JSON and upserts an
36    /// `inventory_facts` row keyed by `(pc_id, manifest.id)`. The
37    /// `display` sub-config drives the SPA's Inventory page render.
38    #[serde(default)]
39    pub inventory: Option<InventoryHint>,
40    /// Issue #246: opt-in marker that this job emits per-line
41    /// observability events on stdout (one JSON `ObsEvent` per
42    /// newline). When present, the agent — after the script exits
43    /// successfully — parses each non-empty stdout line as an
44    /// `ObsEvent`, publishes it on `obs.<pc_id>` via the
45    /// `obs_outbox`, and (intentionally) **omits the stdout from
46    /// the `ExecResult`** so the timeline data doesn't double up
47    /// in `execution_results.stdout` (which would multiply rows
48    /// by ~50/day/PC of noise).
49    ///
50    /// Distinct from `inventory:` (single JSON object → projector
51    /// upsert) — events are append-only timeline points consumed
52    /// by the dedicated `obs_events` table.
53    #[serde(default)]
54    pub emit: Option<EmitConfig>,
55    /// #290: opt-in marker that this job is an operator-defined
56    /// **health check** whose result feeds the Client App's Health
57    /// tab over KLP (`StateSnapshot.checks`). The script prints a
58    /// free-form JSON object on stdout (like any inventory job); the
59    /// agent reads the [`CheckHint::status_field`] value dynamically
60    /// into a [`crate::ipc::state::Check`] named `check.name`.
61    /// Cadence / windows / conditions come from
62    /// the job's Schedule (exactly like inventory) — there is
63    /// deliberately no interval here. **Composes with `inventory:` and
64    /// `collect:`** (#821): each reads its own `#KANADE-<KIND>`-fenced
65    /// stdout block, so one job can drive a check, project inventory
66    /// facts, and collect files in a single run. Only `emit:` (NDJSON
67    /// stdout) is incompatible. A check-only job may skip the fence
68    /// (whole stdout is the JSON); a multi-hint job fences each block.
69    #[serde(default)]
70    pub check: Option<CheckHint>,
71    /// #219: opt-in marker that this job COLLECTS files into a bundle.
72    /// The script does the collection work and prints a single JSON
73    /// object on stdout carrying a `files` array of paths (the field
74    /// name is [`CollectHint::files_field`], default `"files"`); the
75    /// agent — after the script exits successfully — zips those files,
76    /// uploads the archive to the `OBJECT_COLLECTIONS` Object Store
77    /// bucket (key `<pc_id>/<job_id>/<timestamp>.zip`), and records the
78    /// key in [`crate::wire::ExecResult::collect_object`]. The operator
79    /// downloads bundles from the SPA Collect page.
80    ///
81    /// Like `inventory:` / `check:` this reads a JSON object from stdout.
82    /// #821: it reads its own `#KANADE-COLLECT-BEGIN/END`-fenced block,
83    /// so it **composes with `inventory:` / `check:`** (and a user
84    /// message) on one stdout — only `emit:` (NDJSON) is incompatible
85    /// (enforced in [`Manifest::validate`]). A collect-only job may skip
86    /// the fence. It also composes with `client:` — a `collect:` +
87    /// `client:` job lets an end user trigger a collection from the
88    /// Client App (the same-host agent runs it).
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub collect: Option<CollectHint>,
91    /// #720: opt-in declarative aggregation over `obs_events` that drives
92    /// the SPA **Analytics** page. Unlike the other hints this one never
93    /// touches stdout and is never delivered to the agent — it's a pure
94    /// *read spec* the backend reads from `BUCKET_JOBS` at query time and
95    /// turns into `json_extract` aggregation SQL. Each entry is one widget
96    /// (a `dashboard:` tab groups them); `scope:` selects per-PC vs
97    /// fleet-wide rollup. Because it consumes nothing at run time it
98    /// composes with every other hint (typically paired with `emit:`,
99    /// which produces the events it reads). See [`AggregateWidget`].
100    ///
101    /// New field ⇒ #492 wire rule (`default` + `skip_serializing_if`).
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub aggregate: Option<Vec<AggregateWidget>>,
104    /// v0.26: Layer 2 staleness policy (SPEC.md §2.6.2). Controls
105    /// what the agent does at fire time when it can't verify the
106    /// `script_current` / `script_status` KV values are fresh —
107    /// especially relevant for `runs_on: agent` schedules where
108    /// the agent may fire from cache while offline. Defaults to
109    /// `Staleness::Cached` (silently use cached values), which
110    /// matches every pre-v0.26 Manifest.
111    #[serde(default)]
112    pub staleness: Staleness,
113    /// #291: opt-in marker that this job is offered to **end users**
114    /// in the Client App's job tabs over KLP (`jobs.list` →
115    /// `jobs.execute`). Parallel to [`inventory`] / [`check`] /
116    /// [`emit`]: the block's mere presence is the opt-in, and it
117    /// groups the end-user presentation fields (name / category /
118    /// icon) that only make sense for a user-facing job. `None`
119    /// (the default) ⇒ an operator-only job — inventory, checks,
120    /// scheduled maintenance — that never surfaces in the catalog.
121    ///
122    /// The agent re-reads this at every `jobs.list` / `jobs.execute`
123    /// (SPEC §2.1), so removing the block takes a job out of a
124    /// running client on its next action.
125    ///
126    /// [`inventory`]: Manifest::inventory
127    /// [`check`]: Manifest::check
128    /// [`emit`]: Manifest::emit
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub client: Option<ClientHint>,
131    /// Free-form operator taxonomy for the Jobs catalog. Purely a
132    /// SPA-side organisational aid — agents / scheduler / projector
133    /// never read it — so it carries no runtime semantics and any
134    /// string is allowed (`security`, `weekly`, `windows`, …). Jobs
135    /// cross-cut (a `check-bitlocker` is at once a health-check, a
136    /// security control, and Windows-specific), which is why this is
137    /// a multi-valued list rather than the single closed-enum
138    /// [`ClientHint::category`] (whose values are the end-user Client
139    /// App's tabs, a different concern). The operator Jobs page groups
140    /// rows by id-prefix for free; tags add the orthogonal filter axis
141    /// prefixes can't express.
142    ///
143    /// Empty by default (the overwhelming majority of jobs), and a
144    /// new field, so it follows the #492 wire rule: `serde(default)`
145    /// plus `skip_serializing_if` keep gradually-upgrading old readers
146    /// from tripping over its absence / presence.
147    #[serde(default, skip_serializing_if = "Vec::is_empty")]
148    pub tags: Vec<String>,
149    /// GitOps provenance (#678) — see [`RepoOrigin`]. Stamped by
150    /// `kanade job create` when the source YAML lives inside a Git work
151    /// tree, so the SPA can render the job read-only and point edits
152    /// back at the repo instead of letting a ClickOps edit silently
153    /// diverge from Git (SPEC design principle #3: 設定駆動 YAML + Git).
154    /// `None` for SPA-born jobs and for manifests applied from outside
155    /// any Git repo. Purely informational: agents / scheduler /
156    /// projector never read it, and it survives `script_file:` inlining
157    /// (it's orthogonal to the exactly-one-of script-source rule). New
158    /// field ⇒ #492 wire rule (`default` + `skip_serializing_if`).
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub origin: Option<RepoOrigin>,
161    /// Job-generic post-step hook. When set, the agent runs this script
162    /// AFTER the main `execute:` script exits cleanly (and, for a
163    /// `collect:` job, after the bundle finishes uploading), so the
164    /// operator can delete / move / notify based on what the step
165    /// produced. Best-effort: a finalize failure is logged but never
166    /// fails the run — the upload (if any) already succeeded.
167    ///
168    /// For `collect:` jobs the agent injects the environment variable
169    /// `KANADE_COLLECT_RESULT` — a JSON object
170    /// `{ "ok": true, "bundles": [ { "key", "uploaded", "files": [...] } ] }`
171    /// — so the hook acts on exactly the files that were bundled and
172    /// uploaded (e.g. deletes only the `uploaded` ones). Composes with
173    /// every hint. New field ⇒ #492 wire rule (`default` +
174    /// `skip_serializing_if`).
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub finalize: Option<FinalizeSpec>,
177    /// #vuln-roadmap: declarative **external-data feeds**. Each entry fetches
178    /// global reference data (a vulnerability catalog, an EOL table, a license
179    /// roster) and projects it into the shared `feeds` table keyed
180    /// `(feed_id, item_id)` — fleet-wide, with no `pc_id`, unlike the per-PC
181    /// inventory [`ExplodeSpec`]. The job's script (run on the trusted
182    /// controller tier) fetches + shapes the data and prints the array under
183    /// each spec's [`field`](FeedSpec::field) inside a
184    /// `#KANADE-FEED-BEGIN/END` fence; the projector replaces that feed's rows
185    /// wholesale. A non-empty `feed:` **implies** `tier: controller` (the
186    /// dispatch guard treats it as such), so an external fetch never lands on
187    /// an employee endpoint. Composes with the other fenced hints. New field ⇒
188    /// #492 wire rule (`default` + `skip_serializing_if`). See [`FeedSpec`].
189    #[serde(default, skip_serializing_if = "Vec::is_empty")]
190    pub feed: Vec<FeedSpec>,
191    /// Execution tier (#vuln-roadmap). `None` / `endpoint` (default) ⇒ the
192    /// job dispatches to the targeted fleet agents like any job. `controller`
193    /// ⇒ it may run ONLY on trusted infra hosts — the backend constrains
194    /// dispatch to members of the operator-configured `controller_group`
195    /// (`server_settings` KV), and refuses to run anywhere if that group is
196    /// unset (fail-safe). This keeps `feed:` (external-fetch) and future
197    /// privileged hints off employee endpoints. The `feed:` hint implies
198    /// `controller`; it can also be set explicitly. New field ⇒ #492 wire
199    /// rule (`default` + `skip_serializing_if`).
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub tier: Option<Tier>,
202}
203
204/// Execution tier for a [`Manifest`] — see [`Manifest::tier`]. `endpoint`
205/// is the default (a normal fleet job); `controller` restricts dispatch to
206/// the trusted `controller_group`. `Unknown` is the #492 forward-compat
207/// catch-all: an older reader still *decodes* a job that names a future
208/// tier (so it doesn't fail the whole document), but `Manifest::validate()`
209/// **rejects** it — for a security field we fail closed rather than fall
210/// back to unrestricted `endpoint` dispatch (a future tier is presumably
211/// *more* restrictive, and a typo'd `controller` must not silently widen).
212#[derive(
213    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
214)]
215#[serde(rename_all = "snake_case")]
216#[non_exhaustive]
217pub enum Tier {
218    /// Dispatch to the targeted fleet agents (the default).
219    #[default]
220    Endpoint,
221    /// Dispatch only to members of the configured `controller_group`.
222    Controller,
223    /// #492 forward-compat catch-all (a future tier this build can't act on).
224    #[serde(other)]
225    Unknown,
226}
227
228/// GitOps provenance for a repo-managed YAML artifact — a [`Manifest`]
229/// (#678) or a [`Schedule`] (#695). Populated by `kanade job create` /
230/// `kanade schedule create` from the Git context of the source YAML;
231/// the SPA reads it to render Git-managed entries read-only and link
232/// the operator back at the repo. Never consulted by the runtime.
233#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
234pub struct RepoOrigin {
235    /// Repo-relative path of the source YAML — the primary edit target
236    /// the SPA surfaces (e.g. `configs/jobs/foo.yaml`). Forward slashes
237    /// regardless of the authoring OS.
238    pub path: String,
239    /// `origin` remote URL, when the repo has one. Lets the SPA turn
240    /// `path` into a clickable link; `None` for remote-less repos.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub repo: Option<String>,
243    /// Repo-relative path of the `script_file:` a job manifest inlined,
244    /// when it used one — a secondary pointer shown beneath `path`.
245    /// Always `None` for schedules (they carry no script).
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    pub script_file: Option<String>,
248}
249
250/// "Who + how + when-to-stagger" — the fanout-plan side of an exec.
251/// Used both as the POST `/api/exec/{job_id}` body and as the embedded
252/// `target` / `rollout` / `jitter` slot on [`Schedule`]. Centralising
253/// here keeps the validation + serialisation logic in one place.
254#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default)]
255pub struct FanoutPlan {
256    #[serde(default)]
257    pub target: Target,
258    /// Optional wave rollout — when present, the backend publishes
259    /// each wave's group subject on its own delay schedule instead
260    /// of fanning out the `target` block in one go. `target` then
261    /// only labels the deploy for the audit log.
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub rollout: Option<Rollout>,
264    /// Optional humantime jitter; agent uses it to randomise
265    /// execution start. Lives here (not on the script) so different
266    /// schedules / ad-hoc fires of the same job can pick different
267    /// stagger windows.
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub jitter: Option<String>,
270    /// Absolute time the scheduler stamps on each emitted Command
271    /// when this exec was driven by a [`Schedule`] with
272    /// `starting_deadline`. Agents receiving a Command after this
273    /// instant publish a synthetic skipped-result instead of
274    /// running the script. `None` (default) = no deadline / catch
275    /// up whenever delivered. Computed by the scheduler from
276    /// `tick_at + starting_deadline` and overwritten on every fire —
277    /// on a Schedule, setting it by hand is rejected at create time
278    /// (#917, use `starting_deadline`); it remains settable on an
279    /// ad-hoc POST /api/exec body.
280    #[serde(default, skip_serializing_if = "Option::is_none")]
281    pub deadline_at: Option<chrono::DateTime<chrono::Utc>>,
282}
283
284/// Sentinel lines that fence a hint's structured JSON payload inside an
285/// otherwise human-readable job stdout. Each stdout-reading hint
286/// (`inventory:` / `check:` / `collect:`) has its OWN `#KANADE-<KIND>-
287/// BEGIN`/`-END` pair, so one job can carry several of them at once
288/// (and/or a user-facing message) on its single stdout stream — every
289/// consumer extracts only its own block via [`fenced_payload`].
290///
291/// Originated for inventory (#793): a `client:` job couldn't put both a
292/// friendly message and a JSON object on one stdout (the Client App
293/// renders stdout verbatim, the projector needs JSON). #821 generalised
294/// it so inventory / check / collect can coexist. `emit:` is the
295/// exception — its stdout is line-delimited NDJSON consumed whole, so it
296/// never fences and never coexists with the others.
297///
298/// A job carrying a SINGLE hint may still skip the fence —
299/// [`fenced_payload`] falls back to the whole stdout — but a job
300/// COMBINING hints must fence each block (else every consumer would try
301/// to parse the same whole stdout).
302pub const INVENTORY_BLOCK_BEGIN: &str = "#KANADE-INVENTORY-BEGIN";
303/// Closing marker — see [`INVENTORY_BLOCK_BEGIN`].
304pub const INVENTORY_BLOCK_END: &str = "#KANADE-INVENTORY-END";
305/// Check-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
306pub const CHECK_BLOCK_BEGIN: &str = "#KANADE-CHECK-BEGIN";
307/// Check-payload closing marker.
308pub const CHECK_BLOCK_END: &str = "#KANADE-CHECK-END";
309/// Collect-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
310pub const COLLECT_BLOCK_BEGIN: &str = "#KANADE-COLLECT-BEGIN";
311/// Collect-payload closing marker.
312pub const COLLECT_BLOCK_END: &str = "#KANADE-COLLECT-END";
313/// Feed-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
314pub const FEED_BLOCK_BEGIN: &str = "#KANADE-FEED-BEGIN";
315/// Feed-payload closing marker.
316pub const FEED_BLOCK_END: &str = "#KANADE-FEED-END";
317
318/// Extract a hint's fenced block when the `begin` marker is present, else
319/// `None`. An unterminated fence (closing marker missing, e.g. truncated
320/// output) takes everything after the opener. Trimmed so surrounding
321/// message text / whitespace never reaches the JSON parser.
322pub fn fenced_payload_if_present<'a>(stdout: &'a str, begin: &str, end: &str) -> Option<&'a str> {
323    let b = find_line_marker(stdout, begin)?;
324    let after = &stdout[b + begin.len()..];
325    let inner = match find_line_marker(after, end) {
326        Some(e) => &after[..e],
327        None => after,
328    };
329    Some(inner.trim())
330}
331
332/// True if stdout carries ANY `#KANADE-<KIND>-BEGIN` fence at a line
333/// start — i.e. the script opted into fenced output. Used to decide
334/// whether a missing fence means "single-hint, use the whole stdout" or
335/// "multi-hint author error / truncation, this hint just has no block".
336pub fn has_any_hint_fence(stdout: &str) -> bool {
337    [
338        INVENTORY_BLOCK_BEGIN,
339        CHECK_BLOCK_BEGIN,
340        COLLECT_BLOCK_BEGIN,
341        FEED_BLOCK_BEGIN,
342    ]
343    .iter()
344    .any(|m| find_line_marker(stdout, m).is_some())
345}
346
347/// Extract one hint's JSON payload from a job's stdout. When the hint's
348/// own `#KANADE-<KIND>` fence is present, return that block. When it's
349/// absent, fall back to the WHOLE stdout only for an unfenced (single-
350/// hint) job; if any OTHER hint's fence is present (#821 multi-hint
351/// output) return `""` instead — the script opted into fences but this
352/// block is missing (author error or truncation), so this consumer must
353/// NOT grab a sibling hint's block. An empty payload fails the consumer's
354/// JSON parse and degrades to "no data for this hint", never cross-parse.
355pub fn fenced_payload<'a>(stdout: &'a str, begin: &str, end: &str) -> &'a str {
356    if let Some(p) = fenced_payload_if_present(stdout, begin, end) {
357        return p;
358    }
359    if has_any_hint_fence(stdout) {
360        ""
361    } else {
362        stdout.trim()
363    }
364}
365
366/// Inventory's fenced payload — [`fenced_payload`] with the inventory
367/// markers. Kept as a named helper for the projector call site.
368pub fn inventory_payload(stdout: &str) -> &str {
369    fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END)
370}
371
372/// Feed's fenced payload — [`fenced_payload`] with the feed markers. Kept as
373/// a named helper for the projector call site.
374pub fn feed_payload(stdout: &str) -> &str {
375    fenced_payload(stdout, FEED_BLOCK_BEGIN, FEED_BLOCK_END)
376}
377
378/// Find `needle` only where it begins a line (start of `hay` or right
379/// after a `\n`). Anchoring to line start means a script echoing the
380/// literal sentinel mid-message (e.g. printing a command name) can't
381/// false-trigger the fence (Claude #793).
382fn find_line_marker(hay: &str, needle: &str) -> Option<usize> {
383    if hay.starts_with(needle) {
384        return Some(0);
385    }
386    hay.find(&format!("\n{needle}")).map(|p| p + 1)
387}
388
389/// Manifest sub-section: how the SPA should render the inventory
390/// facts this job produces. Each field name (`field`) is a top-level
391/// key in the stdout JSON, e.g. `hostname`, `ram_gb`.
392///
393/// Two render modes:
394///   * `display` — vertical "field / value" per PC, used by the
395///     `/inventory?pc=<id>` detail view. ALL columns the operator
396///     wants visible on the detail page.
397///   * `summary` — horizontal table across the fleet (row = PC,
398///     column = field) on `/inventory`. Optional; when omitted the
399///     SPA falls back to `display`, but operators usually want a
400///     trimmer "hostname / OS / CPU / RAM" set for the fleet view.
401#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
402pub struct InventoryHint {
403    /// Detail-view columns, in order.
404    pub display: Vec<DisplayField>,
405    /// Optional fleet-list columns (row = PC). Defaults to `display`
406    /// when omitted, but operators usually pick a 3-5 column subset.
407    #[serde(default, skip_serializing_if = "Option::is_none")]
408    pub summary: Option<Vec<DisplayField>>,
409    /// v0.31 / #40: payload arrays that should be exploded into
410    /// per-element rows of a derived SQLite table. Lets operators
411    /// answer cross-PC questions ("which PCs still have Chrome <
412    /// 120?", "C: >90% full") with normal SQL filters + indexes
413    /// instead of grepping JSON. The projector creates the derived
414    /// table on register and replaces this PC's rows on each result
415    /// (DELETE WHERE pc_id=? AND job_id=? + bulk INSERT). See
416    /// [`ExplodeSpec`] for the per-spec schema.
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub explode: Option<Vec<ExplodeSpec>>,
419    /// v0.35 / #93: top-level scalar fields whose changes the
420    /// projector logs to `inventory_history` (one event per
421    /// changed field per scan). Pairs with `explode[].track_history`
422    /// — that covers array elements; this covers single-valued
423    /// fields like `ram_bytes` / `os_version` / `cpu_model` /
424    /// `os_build` that operators want to track for "did the RAM
425    /// get upgraded?" / "when did Win 11 land on this PC?" /
426    /// "BIOS / firmware bumped?" questions. Field name = `field_path`
427    /// in the history row, `identity_json` is NULL, `before_json`
428    /// / `after_json` each carry `{"value": <prior or new value>}`.
429    /// First-ever observation of a scalar (no prior facts row)
430    /// emits `added`; subsequent value changes emit `changed`. No
431    /// `removed` events — a scalar disappearing from the payload
432    /// is rare and the operator can still see the last value via
433    /// the `before_json` of the most recent change.
434    #[serde(default, skip_serializing_if = "Option::is_none")]
435    pub history_scalars: Option<Vec<String>>,
436}
437
438/// Manifest sub-section (#290): marks a job as an operator-defined
439/// **health check**. Parallel to [`InventoryHint`] / `EmitConfig`.
440/// The stdout contract is a free-form JSON object (same as any
441/// inventory job) from which the agent reads `status_field` /
442/// `detail_field` to build the KLP [`crate::ipc::state::Check`] shown
443/// on the Client App's Health tab.
444///
445/// There is deliberately **no timing field** — when / how often /
446/// in which window a check runs is driven by the job's Schedule,
447/// exactly like inventory jobs, so operators get the full `when:` /
448/// rollout / `runs_on` expressiveness for free.
449///
450/// A check's stdout is a **free-form inventory object** (arbitrary
451/// key/value pairs + arrays) — same as any inventory job — that also
452/// carries a status field. `check:` adds only the health semantics on
453/// top: which field is the ok/warn/fail/unknown status, an optional
454/// one-line summary field, and a remediation job. Everything else
455/// (rich per-PC detail, `explode` sub-tables like a software list) is
456/// driven by a co-present [`InventoryHint`] and rendered with the
457/// SAME display logic the SPA Inventory page uses — on the Client App
458/// too. This keeps checks maximally expressive without a bespoke
459/// payload type.
460#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
461pub struct CheckHint {
462    /// Stable check id → [`Check.name`](crate::ipc::state::Check),
463    /// the SPA/Client React key + analytics label. Unique within the
464    /// fleet's check set. Machine-friendly slug (`disk_space`,
465    /// `defender_rtp`); for the human-facing row title see [`label`].
466    ///
467    /// [`label`]: CheckHint::label
468    pub name: String,
469    /// Optional human-facing display title →
470    /// [`Check.label`](crate::ipc::state::Check). The Client App's
471    /// Health tab and the operator SPA's Compliance page render this
472    /// instead of the [`name`](CheckHint::name) slug when set
473    /// (`"ウイルス対策のリアルタイム保護"` reads better than
474    /// `defender_rtp`). Falls back to the slug when absent, so it's
475    /// purely additive. Author it in the check's language — there's no
476    /// per-locale variant; checks are operator-defined per fleet.
477    #[serde(default, skip_serializing_if = "Option::is_none")]
478    pub label: Option<String>,
479    /// Top-level stdout field whose string value
480    /// (`ok`/`warn`/`fail`/`unknown`) becomes the Health-tab light
481    /// ([`CheckStatus`](crate::ipc::state::CheckStatus)). Defaults to
482    /// `"status"`; a missing / unparseable value → `unknown`.
483    #[serde(default = "default_status_field")]
484    pub status_field: String,
485    /// Top-level stdout field used as the Health-tab row's one-line
486    /// summary. Defaults to `"detail"`; absent in the payload → no
487    /// detail line (the rich breakdown lives in the inventory view).
488    #[serde(default = "default_detail_field")]
489    pub detail_field: String,
490    /// Optional remediation job id →
491    /// [`Check.troubleshoot`](crate::ipc::state::Check). The Client
492    /// App shows a "修復する" button when present; that job must be
493    /// `user_invokable`.
494    #[serde(default, skip_serializing_if = "Option::is_none")]
495    pub troubleshoot: Option<String>,
496    /// #290 PR-E: when `true` (default), the backend also projects this
497    /// check's `status` / `detail` into the `check_status` table so the
498    /// operator SPA gets a fleet-wide compliance view for free — no
499    /// `inventory:` block needed. Set `fleet: false` for a client-only
500    /// check the operator doesn't want surfaced across the fleet.
501    #[serde(default = "default_true")]
502    pub fleet: bool,
503    /// When `true` (default), this check is shown on the Client App's
504    /// Health tab (the end user sees its ok/warn/fail row). Set
505    /// `health: false` for a **gate-only** check — one that exists purely
506    /// to drive a `client.show_when` display gate (e.g. `myapp-up-to-date`)
507    /// and would just be noise as a Health row. The agent still records it
508    /// into `StateSnapshot.checks` (so `show_when` can read it and the gate
509    /// keeps working); only the Client App's Health *rendering* skips it,
510    /// via the [`Check.health_hidden`](crate::ipc::state::Check::health_hidden)
511    /// wire flag. Orthogonal to [`fleet`](CheckHint::fleet): `fleet` gates
512    /// the operator SPA fleet view, `health` gates the end-user Health tab,
513    /// so a pure gate detector typically sets neither (`fleet: false` +
514    /// `health: false`) to stay invisible everywhere while still driving
515    /// the gate.
516    #[serde(default = "default_true")]
517    pub health: bool,
518    /// Optional auto-notification on a compliance transition. When set, the
519    /// backend publishes an end-user notification the moment this check
520    /// transitions *into* one of [`CheckAlert::on`] (e.g. ok → fail) — to
521    /// the failing PC's user and/or operator groups. Fired once per
522    /// transition (not on every poll). Requires `fleet: true` (the alert
523    /// rides the same projection that fills `check_status`).
524    #[serde(default, skip_serializing_if = "Option::is_none")]
525    pub alert: Option<CheckAlert>,
526}
527
528/// Auto-notification rule for a [`CheckHint`] (compliance alerting). When a
529/// check's status transitions into one of [`on`](Self::on), the backend
530/// publishes a notification to the failing PC's user
531/// ([`notify_user`](Self::notify_user)) and/or operator groups
532/// ([`notify_groups`](Self::notify_groups)). Deliberately config-driven:
533/// who gets told, how loud, and the wording all live in the manifest, not
534/// hardcoded in the backend.
535#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
536pub struct CheckAlert {
537    /// Statuses that fire the alert on *transition into* them (a check that
538    /// stays failing doesn't re-alert every poll). Defaults to `[fail]`.
539    /// `ok` is not representable — [`CheckAlertStatus`] has no `Ok` variant,
540    /// so a YAML `on: [ok]` fails to deserialize (before `validate()` is
541    /// even reached); "recovered" notifications are out of scope.
542    #[serde(default = "default_alert_on")]
543    pub on: Vec<CheckAlertStatus>,
544    /// Notify the user(s) on the failing PC (`notifications.pc.<pc_id>`).
545    #[serde(default)]
546    pub notify_user: bool,
547    /// Notify these operator groups (`notifications.group.<name>`).
548    #[serde(default, skip_serializing_if = "Vec::is_empty")]
549    pub notify_groups: Vec<String>,
550    /// Notification priority (colour/label only — toasting is the separate
551    /// `toast` flag). Defaults to `warn`.
552    #[serde(default = "default_alert_priority")]
553    pub priority: crate::ipc::notifications::NotificationPriority,
554    /// Require the recipient to click 確認 to dismiss.
555    #[serde(default)]
556    pub require_ack: bool,
557    /// Surface an OS toast (launches a closed Client App, Action Center
558    /// while locked). Recommended `true` for `notify_user` so a
559    /// non-emergency "your PC is non-compliant" nudge still reaches a user
560    /// whose app is closed.
561    #[serde(default)]
562    pub toast: bool,
563    /// Also send the alert by email, to every address mapped to the
564    /// `notify_groups` (via the `group_contacts` KV, edited on the SPA
565    /// Groups page). Opt-in: defaults to `false`, so an existing alert
566    /// never starts emailing on its own. Requires `notify_groups` to be
567    /// non-empty (there is no per-PC user email) and the backend's
568    /// `[mail]` config to be present; otherwise the email is a logged
569    /// no-op while the in-app/toast notification still fires.
570    #[serde(default)]
571    pub email: bool,
572    /// Notification title (required). May use the same `{…}` placeholders
573    /// as [`body`](Self::body).
574    pub title: String,
575    /// Notification body template. Placeholders: `{pc_id}`, `{name}` (check
576    /// slug), `{label}` (check label, falls back to slug), `{status}`,
577    /// `{detail}` (the check's one-line summary), `{last_logon}` (the PC's
578    /// last sign-in account). Absent → empty body.
579    #[serde(default, skip_serializing_if = "Option::is_none")]
580    pub body: Option<String>,
581}
582
583/// A check status that can trigger a [`CheckAlert`]. Mirrors the
584/// projected `check_status.status` values minus `ok` (alerting on `ok` is
585/// rejected at validation).
586#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash)]
587#[serde(rename_all = "snake_case")]
588pub enum CheckAlertStatus {
589    Warn,
590    Fail,
591    Unknown,
592}
593
594impl CheckAlertStatus {
595    /// The wire string, matching the projected `check_status.status`.
596    pub fn as_str(self) -> &'static str {
597        match self {
598            Self::Warn => "warn",
599            Self::Fail => "fail",
600            Self::Unknown => "unknown",
601        }
602    }
603}
604
605fn default_alert_on() -> Vec<CheckAlertStatus> {
606    vec![CheckAlertStatus::Fail]
607}
608
609fn default_alert_priority() -> crate::ipc::notifications::NotificationPriority {
610    crate::ipc::notifications::NotificationPriority::Warn
611}
612
613fn default_status_field() -> String {
614    "status".to_string()
615}
616
617fn default_detail_field() -> String {
618    "detail".to_string()
619}
620
621fn default_files_field() -> String {
622    "files".to_string()
623}
624
625/// Fallback cap on a collect bundle's total input size when the
626/// manifest's `collect.max_size` is unset. 50 MB (decimal).
627pub const DEFAULT_COLLECT_MAX_SIZE: u64 = 50 * 1_000_000;
628
629/// Manifest sub-section (#219): marks a job as a **file collector** and
630/// carries how the collected bundle presents in the SPA. Parallel to
631/// [`InventoryHint`] / [`CheckHint`] — the block's presence is the
632/// opt-in. The script prints a single JSON object on stdout whose
633/// [`files_field`](CollectHint::files_field) key holds an array of file
634/// paths to bundle (env vars are expanded); the agent zips them and
635/// uploads to `OBJECT_COLLECTIONS`. See [`Manifest::collect`].
636#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
637pub struct CollectHint {
638    /// Operator/end-user-facing title for the collection, shown as the
639    /// bundle's heading on the SPA Collect page (and the Client App row
640    /// when paired with `client:`). Required; validated non-empty.
641    pub name: String,
642    /// Optional one-line description of what the bundle contains.
643    #[serde(default, skip_serializing_if = "Option::is_none")]
644    pub description: Option<String>,
645    /// Human-readable cap on the bundle's total input size
646    /// (`"50MB"`, `"500KB"`, `"1GiB"`). The agent refuses to build a
647    /// bundle whose listed files exceed this. `None` ⇒
648    /// [`DEFAULT_COLLECT_MAX_SIZE`]. Parsed by [`parse_size_bytes`];
649    /// [`Manifest::validate`] rejects an unparseable value at create
650    /// time.
651    ///
652    /// Note: this bounds the **uncompressed** bytes the agent reads off
653    /// disk, not the resulting zip. Text logs compress well, so the
654    /// download is usually much smaller; many tiny files add a little
655    /// per-entry zip overhead. Read it as "how much the agent reads +
656    /// packs", not "the exact download size".
657    #[serde(default, skip_serializing_if = "Option::is_none")]
658    pub max_size: Option<String>,
659    /// Top-level stdout JSON key holding the array of file paths to
660    /// bundle. Defaults to `"files"`.
661    #[serde(default = "default_files_field")]
662    pub files_field: String,
663}
664
665impl CollectHint {
666    /// The effective size cap in bytes — the parsed `max_size` or
667    /// [`DEFAULT_COLLECT_MAX_SIZE`] when unset. Assumes `max_size` (if
668    /// present) already passed [`Manifest::validate`]; falls back to the
669    /// default on a parse error rather than panicking on the fire path.
670    pub fn max_size_bytes(&self) -> u64 {
671        match &self.max_size {
672            Some(s) => parse_size_bytes(s).unwrap_or(DEFAULT_COLLECT_MAX_SIZE),
673            None => DEFAULT_COLLECT_MAX_SIZE,
674        }
675    }
676}
677
678/// Parse a human-readable byte size (`"50MB"`, `"500 KB"`, `"1GiB"`,
679/// `"1024"`). Decimal units (KB/MB/GB) are 1000-based; binary units
680/// (KiB/MiB/GiB) are 1024-based; a bare number (or `B`) is bytes.
681/// Case-insensitive. Shared by `collect.max_size` validation and the
682/// agent's bundle-size enforcement.
683pub fn parse_size_bytes(s: &str) -> Result<u64, String> {
684    let t = s.trim();
685    if t.is_empty() {
686        return Err("size must not be empty".to_string());
687    }
688    let split = t.find(|c: char| !c.is_ascii_digit()).unwrap_or(t.len());
689    let (num_str, unit_raw) = t.split_at(split);
690    if num_str.is_empty() {
691        return Err(format!("size '{s}': missing leading number"));
692    }
693    let num: u64 = num_str
694        .parse()
695        .map_err(|_| format!("size '{s}': bad number '{num_str}'"))?;
696    let mult: u64 = match unit_raw.trim().to_ascii_lowercase().as_str() {
697        "" | "b" => 1,
698        "kb" => 1_000,
699        "mb" => 1_000_000,
700        "gb" => 1_000_000_000,
701        "kib" => 1024,
702        "mib" => 1024 * 1024,
703        "gib" => 1024 * 1024 * 1024,
704        other => {
705            return Err(format!(
706                "size '{s}': unknown unit '{other}' (use B/KB/MB/GB/KiB/MiB/GiB)"
707            ));
708        }
709    };
710    num.checked_mul(mult)
711        .ok_or_else(|| format!("size '{s}': overflow"))
712}
713
714/// Manifest sub-section (#291): marks a job as **user-invokable**
715/// from the Client App and carries how it presents to the end user.
716/// Parallel to [`InventoryHint`] / [`CheckHint`] / `EmitConfig` —
717/// the block's presence is the opt-in (no separate boolean), and its
718/// required fields (`name`, `category`) are enforced by serde at
719/// parse time, so a half-filled catalog entry fails
720/// `kanade job create` instead of rendering a nameless / tab-less row.
721///
722/// The agent maps this 1:1 into the KLP
723/// [`UserInvokableJob`](crate::ipc::jobs::UserInvokableJob) wire shape
724/// that `jobs.list` returns; the Client App renders one row per job in
725/// the tab named by `category`.
726#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
727pub struct ClientHint {
728    /// End-user-facing title for the job row. The operator-internal
729    /// `Manifest::id` slug is rarely what an end user should read, so
730    /// this is required (and validated non-empty by
731    /// [`Manifest::validate`]). Maps to `UserInvokableJob::display_name`.
732    pub name: String,
733    /// Optional one-line subtitle under `name` in the Client App.
734    /// Distinct from the operator-facing top-level
735    /// [`Manifest::description`] — this one is written for the end
736    /// user. Maps to `UserInvokableJob::display_description`.
737    #[serde(default, skip_serializing_if = "Option::is_none")]
738    pub description: Option<String>,
739    /// Which Client App tab the job lives in — a **free-form category
740    /// key** (#792). The Client App renders one tab per distinct key.
741    /// Well-known keys (`software_update`, `troubleshoot`, `catalog`)
742    /// carry built-in tab labels/icons; any other key defines a new tab
743    /// (style it with `category_label` / `category_icon`). Required and
744    /// validated non-empty — without it the agent can't place the job.
745    /// Note: the `software_update` key also drives the agent's
746    /// maintenance / auto-reboot grouping.
747    pub category: String,
748    /// Optional display name for the category's TAB. Set it on (at least
749    /// one of) a custom category's jobs to name the tab; `None` ⇒ a
750    /// built-in default for a well-known key, else the key itself.
751    #[serde(default, skip_serializing_if = "Option::is_none")]
752    pub category_label: Option<String>,
753    /// Optional icon for the category's TAB (lucide name or `data:` URL).
754    /// `None` ⇒ Client App default for the key.
755    #[serde(default, skip_serializing_if = "Option::is_none")]
756    pub category_icon: Option<String>,
757    /// Optional sort order for the TAB; lower sorts first. `None` ⇒
758    /// default (well-known keys keep their familiar order; custom keys
759    /// sort after, then by label).
760    #[serde(default, skip_serializing_if = "Option::is_none")]
761    pub category_order: Option<i64>,
762    /// Optional icon hint for the job ROW — a lucide-react icon name
763    /// or a `data:` URL. `None` ⇒ the Client App falls back to the
764    /// category's icon. Surfaced verbatim in `jobs.list[].icon`.
765    #[serde(default, skip_serializing_if = "Option::is_none")]
766    pub icon: Option<String>,
767    /// Optional visibility scope for the end-user Client App (#816).
768    ///
769    /// `None` ⇒ visible to every PC (current behavior). When set, only
770    /// agents whose `pc_id` / group membership match the [`Target`] list
771    /// the job in `jobs.list` and may run it via KLP `jobs.execute`.
772    ///
773    /// This gates the END-USER surface ONLY. Operators are unaffected:
774    /// `POST /api/exec/{job_id}` (SPA / `kanade exec`) is a separate path
775    /// that never consults `client:`, so an operator can still run the
776    /// job on any PC regardless of `visible_to`. Reuses the schedule
777    /// `Target` shape (`all` / `groups` / `pcs`); a present-but-empty
778    /// target is rejected by [`Manifest::validate`].
779    #[serde(default, skip_serializing_if = "Option::is_none")]
780    pub visible_to: Option<Target>,
781    /// Optional **dynamic display gate** keyed on a health check's result.
782    ///
783    /// `None` ⇒ always listed (current behavior). When set, the agent
784    /// lists the job in `jobs.list` ONLY while the named [`check:`] slug's
785    /// latest result is one of [`ShowWhen::is`]. The canonical use is an
786    /// update action that hides itself once the machine is already current:
787    /// pair the update job with a `check:` that reports `ok` when up to
788    /// date and gate on `is: [fail]`.
789    ///
790    /// Evaluated agent-side at `jobs.list` time against the live
791    /// `StateSnapshot.checks`, which is **keyed by check name** — so the
792    /// detector `check:` and this job may live in *different* manifests and
793    /// still share one slug. Distinct from [`visible_to`](ClientHint::visible_to):
794    /// that gates BOTH listing and `jobs.execute` (an authorization
795    /// boundary); `show_when` gates listing ONLY (a UX hint), so it can't
796    /// cause a list/execute race. New field ⇒ #492 wire rule.
797    ///
798    /// [`check:`]: crate::manifest::CheckHint
799    #[serde(default, skip_serializing_if = "Option::is_none")]
800    pub show_when: Option<ShowWhen>,
801    /// Optional **confirmation-dialog** config for the Client App's 実行
802    /// button.
803    ///
804    /// `None` ⇒ the historical default: the client shows a modal
805    /// confirmation with a built-in 「「{name}」を実行しますか?」 message
806    /// before firing the job (a mis-click guard for a possibly heavy /
807    /// destructive action). When set, the operator controls it:
808    /// - a bare bool — `confirm: false` runs immediately with **no** prompt;
809    ///   `confirm: true` is the same as omitting the block (default message);
810    /// - a struct — `confirm: { message: "…" }` shows the dialog with a
811    ///   custom message (and, redundantly with the scalar, `enabled: false`
812    ///   to suppress it).
813    ///
814    /// Gates the END-USER Client App surface only — the operator `POST
815    /// /api/exec` path never consults `client:`, so an operator-driven run
816    /// is unaffected. New field ⇒ #492 wire rule (`serde(default)` +
817    /// `skip_serializing_if`). Deserializes from bool-or-struct via
818    /// [`de_confirm`]; the JSON schema advertises the struct form (the
819    /// scalar is author ergonomics, like [`ShowWhen::is`]).
820    #[serde(
821        default,
822        deserialize_with = "de_confirm",
823        skip_serializing_if = "Option::is_none"
824    )]
825    pub confirm: Option<ConfirmHint>,
826}
827
828/// Confirmation-dialog config for a [`ClientHint`] — see
829/// [`ClientHint::confirm`]. Controls the Client App's pre-run modal:
830/// whether it appears at all (`enabled`) and what it says (`message`).
831///
832/// Authored as either a bare bool (`confirm: false` / `true`) or a struct
833/// (`confirm: { message: "…" }`); both normalise here via [`de_confirm`].
834#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
835pub struct ConfirmHint {
836    /// Whether the Client App shows the confirmation dialog before running.
837    /// `false` fires the job immediately with no prompt. Defaults to `true`
838    /// (so an author who only sets `message` still gets the dialog, and the
839    /// struct form never accidentally suppresses it).
840    #[serde(default = "default_confirm_enabled")]
841    pub enabled: bool,
842    /// Custom dialog message. `None` ⇒ the client's built-in
843    /// 「「{name}」を実行しますか?」. Only meaningful while `enabled`;
844    /// rejected if present-but-blank by [`Manifest::validate`].
845    #[serde(default, skip_serializing_if = "Option::is_none")]
846    pub message: Option<String>,
847}
848
849/// `enabled` defaults to `true`: the historical behaviour is "always
850/// confirm", so a struct form that omits `enabled` (e.g. sets only
851/// `message`) still shows the dialog.
852fn default_confirm_enabled() -> bool {
853    true
854}
855
856/// Accept either a bare bool (`confirm: false` / `confirm: true`) or a
857/// struct (`confirm: { message: "…" }`) for [`ClientHint::confirm`],
858/// normalising to a [`ConfirmHint`]. The bool is pure author ergonomics —
859/// `false` ⇒ suppress the dialog, `true` ⇒ default message — while the
860/// struct carries a custom message. Called only when the key is present
861/// (absence is handled by `serde(default)` ⇒ `None`). An explicit
862/// `confirm: null` — which the generated schema permits (the field is
863/// `Option`) — maps to `None` too, so it can't produce a parse error;
864/// deserializing through `Option<BoolOrHint>` handles that cleanly (Gemini
865/// #960).
866fn de_confirm<'de, D>(d: D) -> Result<Option<ConfirmHint>, D::Error>
867where
868    D: serde::Deserializer<'de>,
869{
870    #[derive(Deserialize)]
871    #[serde(untagged)]
872    enum BoolOrHint {
873        Bool(bool),
874        Hint(ConfirmHint),
875    }
876    Ok(Option::<BoolOrHint>::deserialize(d)?.map(|b| match b {
877        BoolOrHint::Bool(enabled) => ConfirmHint {
878            enabled,
879            message: None,
880        },
881        BoolOrHint::Hint(h) => h,
882    }))
883}
884
885/// Dynamic display gate for a [`ClientHint`] — see
886/// [`ClientHint::show_when`]. Shows the job only while the named check's
887/// latest status is one of [`is`](ShowWhen::is).
888#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
889pub struct ShowWhen {
890    /// The `check:` slug (a [`CheckHint::name`](crate::manifest::CheckHint::name))
891    /// whose latest status gates this job. May be defined by a *different*
892    /// manifest: checks are keyed by name in the agent's snapshot, so a
893    /// standalone detector job and this one can share a slug. A check that
894    /// has never run (absent from the snapshot) does NOT match — the job
895    /// stays hidden until the detector first reports (fails closed, like
896    /// `visible_to`).
897    pub check: String,
898    /// The check status(es) in which the job is SHOWN. Accepts a single
899    /// status (`is: fail`) or a list (`is: [fail, unknown]`); both
900    /// deserialize to a `Vec`. The `length(min = 1)` schema constraint +
901    /// [`Manifest::validate`] both reject an empty set (it would match
902    /// nothing and silently hide the job) so schema-driven tooling and the
903    /// write path agree.
904    #[serde(deserialize_with = "de_one_or_many_check_status")]
905    #[schemars(length(min = 1))]
906    pub is: Vec<crate::ipc::state::CheckStatus>,
907}
908
909/// Accept either a single `CheckStatus` (`is: fail`) or a sequence
910/// (`is: [fail, unknown]`) for [`ShowWhen::is`], normalising to a `Vec`.
911/// The scalar form is purely author ergonomics; the JSON schema advertises
912/// the canonical array form (`#[schemars(with = ...)]`).
913fn de_one_or_many_check_status<'de, D>(
914    d: D,
915) -> Result<Vec<crate::ipc::state::CheckStatus>, D::Error>
916where
917    D: serde::Deserializer<'de>,
918{
919    use crate::ipc::state::CheckStatus;
920    #[derive(Deserialize)]
921    #[serde(untagged)]
922    enum OneOrMany {
923        One(CheckStatus),
924        Many(Vec<CheckStatus>),
925    }
926    Ok(match OneOrMany::deserialize(d)? {
927        OneOrMany::One(c) => vec![c],
928        OneOrMany::Many(v) => v,
929    })
930}
931
932/// #720 — one widget on the SPA **Analytics** page: a declarative
933/// aggregation over the `obs_events` table. The backend reads these off
934/// `Manifest::aggregate` (from `BUCKET_JOBS`) at query time and builds
935/// the `json_extract` GROUP BY / time-bucket SQL from these generic
936/// primitives, so an operator can chart any emitted event without a Rust
937/// change. The reference shapes are the attendance dashboards
938/// (presence / app_sample / web_visit), but the same DSL covers logon /
939/// reboot / agent-health trends, etc.
940#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
941pub struct AggregateWidget {
942    /// Tab this widget lives under on the Analytics page. Widgets from
943    /// every job are collected and grouped by this label, so the same
944    /// string across jobs builds one multi-source dashboard. Required.
945    pub dashboard: String,
946    /// Widget heading. Required, validated non-empty.
947    pub title: String,
948    /// Optional one-line subtitle shown muted under the `title` on the
949    /// Analytics page — room for a unit, a caveat, or what the number
950    /// means ("samples × 2 min", "Security 4624 only"). Rejected if
951    /// present-but-blank.
952    #[serde(default, skip_serializing_if = "Option::is_none")]
953    pub description: Option<String>,
954    /// Optional sort weight (#743). Once the order-aware sort lands (PR2)
955    /// widgets render in `(order, dashboard, title)` order, so a lower
956    /// `order` pulls a widget — and its tab — earlier; equal/absent `order`
957    /// falls back to the alphabetical `(dashboard, title)` ordering. Treated
958    /// as `0` when unset, so a fleet with no `order` anywhere stays purely
959    /// alphabetical (today's behaviour); negatives are allowed to pin
960    /// something first. (This field only carries the value; the backend
961    /// applies it.)
962    #[serde(default, skip_serializing_if = "Option::is_none")]
963    pub order: Option<i32>,
964    /// Promote this widget to the main Dashboard, not just the Analytics
965    /// page (#vuln-roadmap PR3). The Dashboard fetches the pinned subset
966    /// (`/api/analytics?pinned=true`, fleet scope) and renders it with the
967    /// same widget components. Operator-controlled, so any config-driven
968    /// view (e.g. a future vulnerability rollup) can surface up front
969    /// without a bespoke card. Defaults to `false`. Pin a `scope: fleet`
970    /// widget — a `pc`-scoped one needs a selected PC and won't render on
971    /// the fleet Dashboard.
972    // `Not::not` is `!self`, so this skips serializing the field when it's
973    // `false` — keeps `pin_dashboard: false` out of the stored job/view JSON,
974    // matching how the optional fields above omit their defaults.
975    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
976    pub pin_dashboard: bool,
977    /// `pc` rolls up a single selected PC; `fleet` rolls up all PCs
978    /// (and unlocks `group_by: pc_id` to rank PCs against each other).
979    /// Defaults to `pc`.
980    #[serde(default)]
981    pub scope: AggregateScope,
982    /// `obs_events.kind` this widget reads (e.g. `app_sample`,
983    /// `presence`, `unexpected_shutdown`). Required for every aggregation
984    /// render (`bar`/`gauge`/`timeline`/`stat`); rejected for
985    /// `op_timeline`, which reconstructs a fixed multi-kind operational
986    /// swimlane (power/session/sleep) baked into the SPA and so reads no
987    /// single `kind`.
988    #[serde(default, skip_serializing_if = "Option::is_none")]
989    pub kind: Option<String>,
990    /// Optional `obs_events.source` filter, when one `kind` is emitted by
991    /// more than one collector.
992    #[serde(default, skip_serializing_if = "Option::is_none")]
993    pub source: Option<String>,
994    /// How to roll the matching events up. See [`AggregateAgg`]. Required
995    /// for every aggregation render; rejected for `op_timeline` (which
996    /// performs no rollup — it returns the raw operational events and the
997    /// SPA folds them into lane spans).
998    #[serde(default, skip_serializing_if = "Option::is_none")]
999    pub agg: Option<AggregateAgg>,
1000    /// Dotted JSON path (no `$.` prefix) to group by for `agg: count` /
1001    /// `sum` — e.g. `foreground.app`. The literal `pc_id` is special:
1002    /// it groups by the `pc_id` column (fleet ranking), not a payload
1003    /// field. Omit for a single total. Required when `agg: sum` needs a
1004    /// breakdown; for `agg: count` omitting it yields the grand total.
1005    #[serde(default, skip_serializing_if = "Option::is_none")]
1006    pub group_by: Option<String>,
1007    /// Dotted JSON path to a boolean for `agg: ratio` (e.g. `active`):
1008    /// the widget reports `true_count / total`. Required when `agg: ratio`.
1009    #[serde(default, skip_serializing_if = "Option::is_none")]
1010    pub bool_path: Option<String>,
1011    /// Dotted JSON path to a number for `agg: sum`. Required when `agg: sum`.
1012    #[serde(default, skip_serializing_if = "Option::is_none")]
1013    pub value_path: Option<String>,
1014    /// Optional value transform applied before grouping. Currently only
1015    /// `host` (parse a URL down to its host) — used by the top-sites
1016    /// widget, where SQLite can't parse a URL so the backend does it in
1017    /// Rust. See [`AggregateTransform`].
1018    #[serde(default, skip_serializing_if = "Option::is_none")]
1019    pub transform: Option<AggregateTransform>,
1020    /// Optional sampling cadence in minutes. When set, a `count` is also
1021    /// reported as estimated time (`count × sample_minutes`) — e.g. a
1022    /// 2-minute app sampler turns 11 samples into ~22 minutes. Must be ≥ 1.
1023    #[serde(default, skip_serializing_if = "Option::is_none")]
1024    #[schemars(range(min = 1))]
1025    pub sample_minutes: Option<u32>,
1026    /// Grouped values to drop from the rollup (e.g. `["LockApp"]` so the
1027    /// lock screen doesn't top the app ranking). Empty by default.
1028    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1029    pub exclude: Vec<String>,
1030    /// Optional time bucketing — `hour` buckets events by local
1031    /// hour-of-day for a `timeline` render. See [`AggregateTimeBucket`].
1032    #[serde(default, skip_serializing_if = "Option::is_none")]
1033    pub time_bucket: Option<AggregateTimeBucket>,
1034    /// Top-N cap for grouped renders (`bar`). Defaults to 10 when unset.
1035    #[serde(default, skip_serializing_if = "Option::is_none")]
1036    #[schemars(range(min = 1))]
1037    pub limit: Option<u32>,
1038    /// Which widget the SPA draws. See [`AggregateRender`].
1039    pub render: AggregateRender,
1040}
1041
1042/// Per-PC vs fleet-wide rollup for an [`AggregateWidget`].
1043#[derive(
1044    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
1045)]
1046#[serde(rename_all = "lowercase")]
1047#[non_exhaustive]
1048pub enum AggregateScope {
1049    /// Roll up the single PC the operator selected. The default.
1050    #[default]
1051    Pc,
1052    /// Roll up across every PC. Unlocks `group_by: pc_id`.
1053    Fleet,
1054    /// #492 forward-compat catch-all — a Manifest is read fleet-wide, so
1055    /// an older reader must tolerate a future variant rather than failing
1056    /// to decode the whole job. The backend skips an `Unknown` widget.
1057    #[serde(other)]
1058    Unknown,
1059}
1060
1061/// The rollup function for an [`AggregateWidget`].
1062#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1063#[serde(rename_all = "lowercase")]
1064#[non_exhaustive]
1065pub enum AggregateAgg {
1066    /// Row count, optionally grouped (`group_by`) and time-estimated
1067    /// (`sample_minutes`).
1068    Count,
1069    /// `true_count / total` over `bool_path`.
1070    Ratio,
1071    /// Sum of `value_path`, optionally grouped.
1072    Sum,
1073    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1074    #[serde(other)]
1075    Unknown,
1076}
1077
1078/// Optional pre-grouping value transform for an [`AggregateWidget`].
1079#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1080#[serde(rename_all = "lowercase")]
1081#[non_exhaustive]
1082pub enum AggregateTransform {
1083    /// Parse the grouped value as a URL and keep only its host.
1084    Host,
1085    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1086    #[serde(other)]
1087    Unknown,
1088}
1089
1090/// Time bucketing for an [`AggregateWidget`] (drives a `timeline`).
1091#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1092#[serde(rename_all = "lowercase")]
1093#[non_exhaustive]
1094pub enum AggregateTimeBucket {
1095    /// Bucket by local hour-of-day (0–23), summed over the window.
1096    Hour,
1097    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1098    #[serde(other)]
1099    Unknown,
1100}
1101
1102/// Which visual the SPA renders an [`AggregateWidget`] as.
1103#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1104#[serde(rename_all = "lowercase")]
1105#[non_exhaustive]
1106pub enum AggregateRender {
1107    /// Ranked horizontal bars (a grouped `count` / `sum`).
1108    Bar,
1109    /// A single ratio dial (`agg: ratio`).
1110    Gauge,
1111    /// 24-hour activity strip (`time_bucket: hour`).
1112    Timeline,
1113    /// A single headline number (an ungrouped total).
1114    Stat,
1115    /// Per-PC operational swimlane (power / session / sleep) reconstructed
1116    /// from a fixed multi-kind event set. Unlike the aggregation renders it
1117    /// reads no single `kind`/`agg`: the backend returns the raw events in
1118    /// the window and the SPA folds them into lane spans (shared with the
1119    /// Events page strip). Per-PC only (`scope: pc`).
1120    #[serde(rename = "op_timeline")]
1121    OpTimeline,
1122    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1123    #[serde(other)]
1124    Unknown,
1125}
1126
1127/// True if `p` is a well-formed dotted JSON path of `[A-Za-z0-9_]`
1128/// segments joined by single dots — the shape safe to bind into
1129/// `json_extract(payload, '$.' || ?)`. The charset blocks injection; the
1130/// segment check additionally rejects `"."`, `".foo"`, `"foo."`,
1131/// `"foo..bar"`, which would pass the charset but produce a malformed
1132/// `$.` path that errors at query time. Accepts `pc_id`, `foreground.app`,
1133/// `active`, etc.
1134fn is_valid_json_path(p: &str) -> bool {
1135    !p.is_empty()
1136        && p.split('.').all(|seg| {
1137            !seg.is_empty() && seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
1138        })
1139}
1140
1141/// Per-widget validation for a list of [`AggregateWidget`]s — shared by
1142/// the `aggregate:` job hint ([`Manifest::validate`]) and the standalone
1143/// [`View`] resource (#743) so the two can't diverge. `field` names the
1144/// containing key for error messages (`"aggregate"` or `"widgets"`).
1145///
1146/// Enforces: non-empty list; non-empty dashboard/title (and `kind`/`agg`
1147/// for every aggregation render); a blank-when-set `source`; rejection of
1148/// any #492 `Unknown` enum (an operator typo at create time); safe dotted
1149/// JSON paths; the value path each `agg` needs (and rejection of mis-paired
1150/// ones); `pc_id` grouping only in `fleet` scope; `transform`/`limit`/
1151/// `exclude` only with a `group_by`; positive `limit`/`sample_minutes`;
1152/// `gauge`⇔`ratio`; and `timeline`⇔`time_bucket`. A `render: op_timeline`
1153/// widget is validated separately (per-PC, no aggregation knobs) — see
1154/// [`validate_op_timeline_widget`].
1155pub fn validate_aggregate_widgets(widgets: &[AggregateWidget], field: &str) -> Result<(), String> {
1156    if widgets.is_empty() {
1157        return Err(format!(
1158            "`{field}:` must list at least one widget when present"
1159        ));
1160    }
1161    for (i, w) in widgets.iter().enumerate() {
1162        let at = format!("{field}[{i}]");
1163        for (label, value) in [("dashboard", &w.dashboard), ("title", &w.title)] {
1164            if value.trim().is_empty() {
1165                return Err(format!("{at}.{label} must not be empty"));
1166            }
1167        }
1168        // A present-but-blank `description` renders an empty muted line —
1169        // reject it so the subtitle only shows when it says something.
1170        if let Some(description) = &w.description {
1171            if description.trim().is_empty() {
1172                return Err(format!("{at}.description must not be empty when set"));
1173            }
1174        }
1175        // Reject values that fell through to the #492 `Unknown` catch-all:
1176        // at create time on the current version that's an operator typo. (A
1177        // genuinely-future variant only reaches an older reader via a stored
1178        // resource, which is never re-validated, so forward-compat holds.)
1179        if w.scope == AggregateScope::Unknown {
1180            return Err(format!("{at}.scope is not a known value (pc | fleet)"));
1181        }
1182        if w.render == AggregateRender::Unknown {
1183            return Err(format!(
1184                "{at}.render is not a known value (bar | gauge | timeline | stat | op_timeline)"
1185            ));
1186        }
1187        // `op_timeline` reconstructs a fixed per-PC operational swimlane
1188        // (power/session/sleep) from a baked-in multi-kind set — it uses none
1189        // of the aggregation knobs, so validate it on its own terms (per-PC,
1190        // no `kind`/`agg`/grouping) and skip the rollup rules below.
1191        if w.render == AggregateRender::OpTimeline {
1192            validate_op_timeline_widget(w, &at)?;
1193            continue;
1194        }
1195        // Every other render is an aggregation over a single `kind`.
1196        if w.kind.as_deref().map(str::trim).unwrap_or("").is_empty() {
1197            return Err(format!("{at}.kind must not be empty"));
1198        }
1199        let agg = match w.agg {
1200            Some(AggregateAgg::Unknown) => {
1201                return Err(format!(
1202                    "{at}.agg is not a known value (count | ratio | sum)"
1203                ));
1204            }
1205            Some(agg) => agg,
1206            None => return Err(format!("{at}.agg is required")),
1207        };
1208        // A present-but-blank `source` is a no-op filter — reject like the
1209        // other blank-when-set guards.
1210        if let Some(source) = &w.source {
1211            if source.trim().is_empty() {
1212                return Err(format!("{at}.source must not be empty when set"));
1213            }
1214        }
1215        if w.transform == Some(AggregateTransform::Unknown) {
1216            return Err(format!("{at}.transform is not a known value (host)"));
1217        }
1218        if w.time_bucket == Some(AggregateTimeBucket::Unknown) {
1219            return Err(format!("{at}.time_bucket is not a known value (hour)"));
1220        }
1221        for (label, path) in [
1222            ("group_by", &w.group_by),
1223            ("bool_path", &w.bool_path),
1224            ("value_path", &w.value_path),
1225        ] {
1226            if let Some(p) = path {
1227                if !is_valid_json_path(p) {
1228                    return Err(format!(
1229                        "{at}.{label} '{p}' must be a dotted JSON path of [A-Za-z0-9_] segments"
1230                    ));
1231                }
1232            }
1233        }
1234        // Each agg uses exactly one value path; reject a mis-paired path so
1235        // a typo fails at create rather than being ignored.
1236        match agg {
1237            // count: grouped → ranking, ungrouped → grand total.
1238            AggregateAgg::Count => {
1239                for (label, path) in [("bool_path", &w.bool_path), ("value_path", &w.value_path)] {
1240                    if path.is_some() {
1241                        return Err(format!("{at}.agg=count does not use `{label}`"));
1242                    }
1243                }
1244            }
1245            AggregateAgg::Ratio => {
1246                if w.bool_path.is_none() {
1247                    return Err(format!("{at}.agg=ratio requires `bool_path`"));
1248                }
1249                if w.value_path.is_some() {
1250                    return Err(format!("{at}.agg=ratio does not use `value_path`"));
1251                }
1252            }
1253            AggregateAgg::Sum => {
1254                if w.value_path.is_none() {
1255                    return Err(format!("{at}.agg=sum requires `value_path`"));
1256                }
1257                if w.bool_path.is_some() {
1258                    return Err(format!("{at}.agg=sum does not use `bool_path`"));
1259                }
1260            }
1261            // Rejected above; arm exists only for exhaustiveness.
1262            AggregateAgg::Unknown => {}
1263        }
1264        // Ranking PCs against each other only means something across the
1265        // fleet — within one PC it's a single bar.
1266        if w.group_by.as_deref() == Some("pc_id") && w.scope != AggregateScope::Fleet {
1267            return Err(format!(
1268                "{at}.group_by: pc_id is only valid with scope: fleet"
1269            ));
1270        }
1271        // `transform` rewrites the grouped PAYLOAD value (URL→host); it's
1272        // meaningless on a `pc_id` grouping (the pc_id column, not a payload
1273        // field), so reject the combo at create time.
1274        if w.transform.is_some() && w.group_by.as_deref() == Some("pc_id") {
1275            return Err(format!("{at}.transform is not valid with group_by: pc_id"));
1276        }
1277        // limit / transform / exclude all operate on grouped values, so
1278        // without a `group_by` they're silent no-ops — reject.
1279        if w.group_by.is_none() {
1280            if w.limit.is_some() {
1281                return Err(format!("{at}.limit requires `group_by`"));
1282            }
1283            if w.transform.is_some() {
1284                return Err(format!("{at}.transform requires `group_by`"));
1285            }
1286            if !w.exclude.is_empty() {
1287                return Err(format!("{at}.exclude requires `group_by`"));
1288            }
1289        }
1290        if w.limit == Some(0) {
1291            return Err(format!("{at}.limit must be > 0"));
1292        }
1293        if w.sample_minutes == Some(0) {
1294            return Err(format!("{at}.sample_minutes must be > 0"));
1295        }
1296        for ex in &w.exclude {
1297            if ex.trim().is_empty() {
1298                return Err(format!("{at}.exclude must not contain empty entries"));
1299            }
1300        }
1301        // A gauge draws a single ratio dial — only meaningful for agg: ratio.
1302        if w.render == AggregateRender::Gauge && agg != AggregateAgg::Ratio {
1303            return Err(format!("{at}.render=gauge is only valid with agg: ratio"));
1304        }
1305        // A timeline needs a bucket; a bucket on any other render is a no-op
1306        // that signals operator confusion — reject both.
1307        match (w.render, &w.time_bucket) {
1308            (AggregateRender::Timeline, None) => {
1309                return Err(format!("{at}.render=timeline requires `time_bucket`"));
1310            }
1311            (r, Some(_)) if r != AggregateRender::Timeline => {
1312                return Err(format!(
1313                    "{at}.time_bucket is only valid with render: timeline"
1314                ));
1315            }
1316            _ => {}
1317        }
1318    }
1319    Ok(())
1320}
1321
1322/// Validate a `render: op_timeline` widget. It draws a fixed per-PC
1323/// operational swimlane (power / session / sleep) reconstructed by the SPA
1324/// from a baked-in multi-kind event set, so it uses none of the aggregation
1325/// knobs: require `scope: pc` and reject every field that only makes sense
1326/// for a rollup (`kind`/`source`/`agg`/`group_by`/`bool_path`/`value_path`/
1327/// `transform`/`sample_minutes`/`exclude`/`time_bucket`/`limit`). Rejecting
1328/// the unused fields (rather than ignoring them) keeps an operator typo from
1329/// silently doing nothing, matching the rest of this validator.
1330fn validate_op_timeline_widget(w: &AggregateWidget, at: &str) -> Result<(), String> {
1331    // Per-PC only: a fleet-wide swimlane of every PC's spans is unbounded
1332    // and unreadable, and the backend only computes it in per-PC scope.
1333    if w.scope != AggregateScope::Pc {
1334        return Err(format!("{at}.render=op_timeline requires scope: pc"));
1335    }
1336    // Each unused field, with the name the operator wrote, so the error
1337    // points at exactly what to delete.
1338    if w.kind.is_some() {
1339        return Err(format!("{at}.render=op_timeline does not use `kind`"));
1340    }
1341    if w.source.is_some() {
1342        return Err(format!("{at}.render=op_timeline does not use `source`"));
1343    }
1344    if w.agg.is_some() {
1345        return Err(format!("{at}.render=op_timeline does not use `agg`"));
1346    }
1347    for (label, set) in [
1348        ("group_by", w.group_by.is_some()),
1349        ("bool_path", w.bool_path.is_some()),
1350        ("value_path", w.value_path.is_some()),
1351        ("transform", w.transform.is_some()),
1352        ("sample_minutes", w.sample_minutes.is_some()),
1353        ("time_bucket", w.time_bucket.is_some()),
1354        ("limit", w.limit.is_some()),
1355        ("exclude", !w.exclude.is_empty()),
1356    ] {
1357        if set {
1358            return Err(format!("{at}.render=op_timeline does not use `{label}`"));
1359        }
1360    }
1361    Ok(())
1362}
1363
1364/// Default materialization cadence for a [`SqlWidget`] whose `refresh` is
1365/// unset — 1 hour. A view over feed/inventory tables changes only as fast as
1366/// its underlying feed refresh (often daily), so an hour is fresh enough while
1367/// keeping an expensive correlation join off the ~30s Dashboard poll path.
1368pub const DEFAULT_VIEW_REFRESH: std::time::Duration = std::time::Duration::from_secs(3600);
1369
1370/// #vuln-roadmap PR3: a **SQL-backed, materialized** widget on a [`View`].
1371///
1372/// Where an [`AggregateWidget`] encodes an `obs_events` rollup in structured
1373/// YAML fields, a `SqlWidget` carries a raw read-only `SELECT`/`WITH` over the
1374/// projector's tables (inventory `explode:` tables, `feeds`, `check_status`,
1375/// …) — the correlation that powers a vulnerability / EOL / license dashboard
1376/// is just a `JOIN`, far more expressive than a YAML DSL. The backend runs the
1377/// query in the read-only sandbox (`api::query`), caches the result on the
1378/// `refresh` cadence, and maps it to the same render-ready shape the existing
1379/// widget components consume, via [`RenderSpec`]. See [`View::sql_widgets`].
1380#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1381pub struct SqlWidget {
1382    /// Widget heading. Required, validated non-empty.
1383    pub title: String,
1384    /// Optional muted subtitle (a unit, a caveat). Rejected if present-blank.
1385    #[serde(default, skip_serializing_if = "Option::is_none")]
1386    pub description: Option<String>,
1387    /// The read-only SQL. Executed in the `api::query` sandbox: a single
1388    /// `SELECT`/`WITH` on a `SQLITE_OPEN_READONLY` connection, row-capped and
1389    /// time-bounded. The backend validates it read-only at `view create` and
1390    /// again at run time; a write verb / stacked statement is rejected.
1391    pub query: String,
1392    /// How the query's result columns map to a visual — see [`RenderSpec`].
1393    pub render: RenderSpec,
1394    /// Materialization cadence as a humantime duration (`"6h"`, `"30m"`).
1395    /// Absent ⇒ [`DEFAULT_VIEW_REFRESH`]. The backend re-runs the query at
1396    /// most this often; reads in between hit the cache.
1397    #[serde(default, skip_serializing_if = "Option::is_none")]
1398    pub refresh: Option<String>,
1399    /// Where the widget surfaces — an Analytics tab and/or a pinned Dashboard
1400    /// card. At least one must be set (else it renders nowhere).
1401    pub placement: Placement,
1402}
1403
1404impl SqlWidget {
1405    /// The effective refresh cadence — the parsed `refresh` or
1406    /// [`DEFAULT_VIEW_REFRESH`]. Falls back to the default on an unparseable
1407    /// value rather than panicking on the read path (validation already
1408    /// rejected a bad value at `view create`).
1409    pub fn refresh_interval(&self) -> std::time::Duration {
1410        self.refresh
1411            .as_deref()
1412            .and_then(|s| humantime::parse_duration(s).ok())
1413            .unwrap_or(DEFAULT_VIEW_REFRESH)
1414    }
1415}
1416
1417/// How a [`SqlWidget`]'s SQL result columns map onto a visual. A `kind` names
1418/// the chart; the channel fields (`value`, `label`, `columns`, …) name which
1419/// result columns feed it. Only the channels a `kind` uses are read; the
1420/// backend validates the named columns exist in the result. New chart types
1421/// are "one renderer + the same mapping", so this stays a flat, additive shape.
1422#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Hash)]
1423pub struct RenderSpec {
1424    /// Which visual to render the result as.
1425    pub kind: RenderKind,
1426    /// `table` only: the columns to show, in order. Absent ⇒ every result
1427    /// column (the universal default).
1428    #[serde(default, skip_serializing_if = "Option::is_none")]
1429    pub columns: Option<Vec<String>>,
1430    /// `table` only: optional per-column header relabelling (result column →
1431    /// display name). Columns not listed keep their SQL name.
1432    #[serde(default, skip_serializing_if = "Option::is_none")]
1433    pub labels: Option<std::collections::BTreeMap<String, String>>,
1434    /// `stat` / `bar` / `pie` / `gauge`: the result column holding the numeric
1435    /// value (`stat`/`gauge` read the first row; `bar`/`pie` read every row).
1436    #[serde(default, skip_serializing_if = "Option::is_none")]
1437    pub value: Option<String>,
1438    /// `bar` / `pie`: the result column holding each row's category label.
1439    #[serde(default, skip_serializing_if = "Option::is_none")]
1440    pub label: Option<String>,
1441    /// `bar` / `pie`: keep only the top-N rows (by value). Absent ⇒ all rows.
1442    #[serde(default, skip_serializing_if = "Option::is_none")]
1443    pub limit: Option<u32>,
1444    /// `pie` only: render as a donut (a hole with the total in the centre).
1445    #[serde(default, skip_serializing_if = "Option::is_none")]
1446    pub donut: Option<bool>,
1447    /// `gauge` only: the numerator column (paired with `den`). Alternative to
1448    /// a precomputed `value` ratio.
1449    #[serde(default, skip_serializing_if = "Option::is_none")]
1450    pub num: Option<String>,
1451    /// `gauge` only: the denominator column (paired with `num`).
1452    #[serde(default, skip_serializing_if = "Option::is_none")]
1453    pub den: Option<String>,
1454}
1455
1456/// The chart kind for a [`RenderSpec`]. `table` and `pie` are new in PR3; the
1457/// rest reuse the existing `obs_events` widget renderers.
1458#[derive(
1459    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash, Default,
1460)]
1461#[serde(rename_all = "lowercase")]
1462pub enum RenderKind {
1463    /// The full result grid (new renderer). The universal default.
1464    #[default]
1465    Table,
1466    /// A single headline number from the first row's `value` cell.
1467    Stat,
1468    /// Ranked horizontal bars — `label` + `value` per row, optional top-N.
1469    Bar,
1470    /// Parts-of-a-whole (new renderer) — `label` + `value` per row.
1471    Pie,
1472    /// A ratio dial — a `value` ratio, or a `num`/`den` pair.
1473    Gauge,
1474    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1475    #[serde(other)]
1476    Unknown,
1477}
1478
1479/// Where a [`SqlWidget`] surfaces in the SPA. Mirrors the placement an
1480/// [`AggregateWidget`] expresses via `dashboard` + `pin_dashboard`, but as an
1481/// explicit block since a SQL widget lives on a standalone view.
1482#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1483pub struct Placement {
1484    /// The Analytics tab this widget groups under (the `AggregateWidget`
1485    /// `dashboard` analogue). Absent ⇒ not shown on the Analytics page.
1486    #[serde(default, skip_serializing_if = "Option::is_none")]
1487    pub analytics: Option<String>,
1488    /// Promote to the main Dashboard (reuses #900's pinned section). Absent ⇒
1489    /// not pinned.
1490    #[serde(default, skip_serializing_if = "Option::is_none")]
1491    pub dashboard: Option<DashboardPlacement>,
1492}
1493
1494impl Placement {
1495    /// True when the widget is pinned to the main Dashboard.
1496    pub fn is_pinned(&self) -> bool {
1497        self.dashboard.as_ref().is_some_and(|d| d.pin)
1498    }
1499    /// The Analytics tab name, or a fallback so a dashboard-only widget still
1500    /// carries a group label for the shared widget list.
1501    pub fn tab(&self) -> &str {
1502        self.analytics.as_deref().unwrap_or("Dashboard")
1503    }
1504}
1505
1506/// The `placement.dashboard` block — see [`Placement::dashboard`].
1507#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1508pub struct DashboardPlacement {
1509    /// Pin this widget to the main Dashboard's promoted section.
1510    #[serde(default)]
1511    pub pin: bool,
1512}
1513
1514/// Per-widget validation for a list of [`SqlWidget`]s — shared by the
1515/// [`View`] resource so authoring errors surface at `view create`. `field`
1516/// names the containing key for error messages. The read-only SQL check is
1517/// NOT here (it lives in the backend `api::query` sandbox, which kanade-shared
1518/// can't depend on) — this validates structure: non-empty title/query, a
1519/// known `kind`, the channels each `kind` needs, a real placement, and a
1520/// parseable `refresh`.
1521pub fn validate_sql_widgets(widgets: &[SqlWidget], field: &str) -> Result<(), String> {
1522    for (i, w) in widgets.iter().enumerate() {
1523        let at = format!("{field}[{i}]");
1524        if w.title.trim().is_empty() {
1525            return Err(format!("{at}.title must not be empty"));
1526        }
1527        if w.query.trim().is_empty() {
1528            return Err(format!("{at}.query must not be empty"));
1529        }
1530        if let Some(description) = &w.description {
1531            if description.trim().is_empty() {
1532                return Err(format!("{at}.description must not be empty when set"));
1533            }
1534        }
1535        if let Some(refresh) = &w.refresh {
1536            humantime::parse_duration(refresh)
1537                .map_err(|e| format!("{at}.refresh '{refresh}' is not a valid duration: {e}"))?;
1538        }
1539        // A widget that surfaces nowhere is an invisible no-op. A
1540        // `dashboard:` block with `pin: false` doesn't count — it pins
1541        // nowhere — so gate on the effective pin, not the block's presence
1542        // (Gemini / CodeRabbit).
1543        if w.placement.analytics.is_none() && !w.placement.is_pinned() {
1544            return Err(format!(
1545                "{at}.placement must set `analytics` and/or pin to `dashboard` (else the widget renders nowhere)"
1546            ));
1547        }
1548        if let Some(tab) = &w.placement.analytics {
1549            if tab.trim().is_empty() {
1550                return Err(format!(
1551                    "{at}.placement.analytics must not be empty when set"
1552                ));
1553            }
1554        }
1555        // A per-PC widget (its query binds `:pc_id`) renders only in the
1556        // per-PC Analytics scope, bound to the selected PC. The Dashboard's
1557        // pinned section is fleet-scope and never sends a PC, so a pinned
1558        // per-PC widget would be silently dropped on every request — reject
1559        // the contradiction at create time rather than let it vanish (claude
1560        // review). Literal-aware so a `:pc_id` inside a string literal doesn't
1561        // trip it (see [`rewrite_pc_id_param`]).
1562        if w.placement.is_pinned() && rewrite_pc_id_param(&w.query).1 > 0 {
1563            return Err(format!(
1564                "{at}: a per-PC widget (its query binds `:pc_id`) cannot pin to the Dashboard \
1565                 (the Dashboard is fleet-scope, it never selects a PC) — use `analytics` placement only"
1566            ));
1567        }
1568        validate_render_spec(&w.render, &at)?;
1569    }
1570    Ok(())
1571}
1572
1573/// The named parameter a per-PC [`SqlWidget`] binds to the selected PC. Its
1574/// presence in a widget's query is what makes the widget per-PC.
1575pub const PC_ID_PARAM: &str = ":pc_id";
1576
1577/// Rewrite every *real* `:pc_id` parameter in a widget query to a positional
1578/// `?`, returning `(rewritten_sql, count)`. "Real" = OUTSIDE string literals,
1579/// quoted identifiers and comments, and a whole token (the char after `:pc_id`
1580/// isn't a word char, so `:pc_idx` is left alone). One scanner shared by three
1581/// call sites so they can't disagree on how many `?` SQLite will actually see:
1582///   * per-PC scope detection (`count > 0` ⇒ the widget is per-PC),
1583///   * the backend's bind path (sqlx-sqlite binds POSITIONAL `?` only, not
1584///     `:name`, so the token must be rewritten and bound once per occurrence),
1585///   * and `validate_sql_widgets`' pinned-per-PC rejection above.
1586///
1587/// The literal/comment skipping mirrors the read-only sandbox's
1588/// `strip_sql_noise`, so a `:pc_id` inside `SELECT 'see :pc_id docs'` is copied
1589/// verbatim and NOT counted — it would otherwise be miscounted (a bind-count
1590/// mismatch → `SQLITE_RANGE`) and misclassify the widget's scope (Gemini /
1591/// claude review).
1592pub fn rewrite_pc_id_param(sql: &str) -> (String, usize) {
1593    let mut out = String::with_capacity(sql.len());
1594    let mut count = 0usize;
1595    let mut chars = sql.char_indices().peekable();
1596    while let Some((idx, c)) = chars.next() {
1597        match c {
1598            // String literal / quoted identifier — copy verbatim, honouring the
1599            // doubled-quote escape (`''` / `""` stays inside).
1600            '\'' | '"' => {
1601                out.push(c);
1602                let quote = c;
1603                while let Some((_, d)) = chars.next() {
1604                    out.push(d);
1605                    if d == quote {
1606                        if chars.peek().map(|&(_, e)| e) == Some(quote) {
1607                            let (_, e) = chars.next().unwrap();
1608                            out.push(e);
1609                        } else {
1610                            break;
1611                        }
1612                    }
1613                }
1614            }
1615            // Line comment — copy to end of line.
1616            '-' if chars.peek().map(|&(_, e)| e) == Some('-') => {
1617                out.push(c);
1618                for (_, d) in chars.by_ref() {
1619                    out.push(d);
1620                    if d == '\n' {
1621                        break;
1622                    }
1623                }
1624            }
1625            // Block comment — copy to `*/`.
1626            '/' if chars.peek().map(|&(_, e)| e) == Some('*') => {
1627                out.push(c);
1628                let (_, star) = chars.next().unwrap();
1629                out.push(star);
1630                let mut prev = ' ';
1631                for (_, d) in chars.by_ref() {
1632                    out.push(d);
1633                    if prev == '*' && d == '/' {
1634                        break;
1635                    }
1636                    prev = d;
1637                }
1638            }
1639            // A `:pc_id` token outside any literal/comment — rewrite if it's a
1640            // whole token (not the prefix of `:pc_idx`).
1641            ':' if sql[idx..].starts_with(PC_ID_PARAM) => {
1642                let after = idx + PC_ID_PARAM.len();
1643                let next_is_word = sql[after..]
1644                    .chars()
1645                    .next()
1646                    .is_some_and(|w| w.is_alphanumeric() || w == '_');
1647                if next_is_word {
1648                    out.push(c);
1649                } else {
1650                    out.push('?');
1651                    count += 1;
1652                    for _ in 0..PC_ID_PARAM.chars().count() - 1 {
1653                        chars.next();
1654                    }
1655                }
1656            }
1657            _ => out.push(c),
1658        }
1659    }
1660    (out, count)
1661}
1662
1663/// Validate a [`RenderSpec`]: reject the #492 `Unknown` catch-all (an operator
1664/// typo at create time) and require the channel columns each `kind` reads.
1665fn validate_render_spec(r: &RenderSpec, at: &str) -> Result<(), String> {
1666    // A channel column is "given" when present and non-blank.
1667    let given = |v: &Option<String>| v.as_deref().map(str::trim).is_some_and(|s| !s.is_empty());
1668    match r.kind {
1669        RenderKind::Unknown => {
1670            return Err(format!(
1671                "{at}.render.kind is not a known value (table | stat | bar | pie | gauge)"
1672            ));
1673        }
1674        RenderKind::Table => {
1675            // `columns` optional; if given, each name must be non-blank.
1676            if let Some(cols) = &r.columns {
1677                if cols.iter().any(|c| c.trim().is_empty()) {
1678                    return Err(format!("{at}.render.columns must not contain blank names"));
1679                }
1680            }
1681            if let Some(labels) = &r.labels {
1682                for (k, v) in labels {
1683                    if k.trim().is_empty() || v.trim().is_empty() {
1684                        return Err(format!(
1685                            "{at}.render.labels keys and values must be non-empty"
1686                        ));
1687                    }
1688                }
1689            }
1690        }
1691        RenderKind::Stat => {
1692            if !given(&r.value) {
1693                return Err(format!("{at}.render.value is required for kind=stat"));
1694            }
1695        }
1696        RenderKind::Bar | RenderKind::Pie => {
1697            let kind = if r.kind == RenderKind::Bar {
1698                "bar"
1699            } else {
1700                "pie"
1701            };
1702            if !given(&r.label) {
1703                return Err(format!("{at}.render.label is required for kind={kind}"));
1704            }
1705            if !given(&r.value) {
1706                return Err(format!("{at}.render.value is required for kind={kind}"));
1707            }
1708            // `limit: 0` truncates to no rows — an invisible widget, almost
1709            // certainly a typo. Omit `limit` for "all rows" (CodeRabbit).
1710            if r.limit == Some(0) {
1711                return Err(format!(
1712                    "{at}.render.limit must be >= 1 (omit it to keep all rows)"
1713                ));
1714            }
1715        }
1716        RenderKind::Gauge => {
1717            // Either a precomputed `value` ratio, or a `num`/`den` pair —
1718            // exactly one of the two forms.
1719            match (given(&r.value), given(&r.num), given(&r.den)) {
1720                (true, false, false) => {}
1721                (false, true, true) => {}
1722                _ => {
1723                    return Err(format!(
1724                        "{at}.render for kind=gauge needs either `value` (a ratio) or both `num` and `den`"
1725                    ));
1726                }
1727            }
1728        }
1729    }
1730    Ok(())
1731}
1732
1733/// A standalone declarative read/aggregation for the Analytics page (#743).
1734///
1735/// A **view** aggregates stored fleet data (`obs_events`, …) without an
1736/// `execute` or a schedule — unlike a [`Manifest`] it only declares
1737/// [`AggregateWidget`]s. (The first line is concise on purpose: `schemars`
1738/// uses it as the generated schema's `title`.) The backend reads views from
1739/// `BUCKET_VIEWS` at
1740/// query time and merges their widgets with the co-located `aggregate:`
1741/// hints on jobs, so a cross-cutting dashboard (one that charts events
1742/// emitted by several other jobs / the agent) has a home that doesn't need
1743/// a noop job carrier. Stored JSON in `BUCKET_VIEWS`, keyed by `id`.
1744#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1745pub struct View {
1746    /// Stable identifier (the KV key). Required, validated non-empty.
1747    pub id: String,
1748    /// Optional human description shown on the Views admin page.
1749    #[serde(default, skip_serializing_if = "Option::is_none")]
1750    pub description: Option<String>,
1751    /// The `obs_events` aggregate widgets this view contributes to the
1752    /// Analytics page. Optional since PR3 — a view may instead (or also)
1753    /// carry [`sql_widgets`](View::sql_widgets); a view must have at least one
1754    /// widget across the two lists.
1755    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1756    pub widgets: Vec<AggregateWidget>,
1757    /// #vuln-roadmap PR3: SQL-backed, materialized widgets — raw read-only SQL
1758    /// over the projector tables (inventory/feeds/…) mapped to a visual. This
1759    /// is how a correlation dashboard (vulnerability / EOL / license) is
1760    /// expressed as config. See [`SqlWidget`].
1761    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1762    pub sql_widgets: Vec<SqlWidget>,
1763    /// Free-form operator taxonomy (same role as [`Manifest::tags`]).
1764    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1765    pub tags: Vec<String>,
1766    /// GitOps provenance (#678), stamped by `kanade view create` from the
1767    /// source YAML's Git context — same as [`Manifest::origin`].
1768    #[serde(default, skip_serializing_if = "Option::is_none")]
1769    pub origin: Option<RepoOrigin>,
1770}
1771
1772/// True if `id` is a safe resource identifier — non-empty and only
1773/// `[A-Za-z0-9._-]`. A view `id` becomes a NATS KV key *and* a URL path
1774/// segment (`/api/views/{id}`), so this blocks `/`, `..`, whitespace and
1775/// other characters that would break the KV key or let a CLI arg wander
1776/// the URL space. (#743 / #744 follow-up — a deliberately small charset
1777/// rather than the looser set NATS technically allows.)
1778pub fn is_valid_resource_id(id: &str) -> bool {
1779    !id.is_empty()
1780        && id
1781            .chars()
1782            .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-')
1783}
1784
1785impl View {
1786    pub fn validate(&self) -> Result<(), String> {
1787        if !is_valid_resource_id(self.id.trim()) {
1788            return Err(
1789                "view.id must be non-empty and only [A-Za-z0-9._-] (it's a KV key + URL segment)"
1790                    .to_string(),
1791            );
1792        }
1793        // A view must contribute at least one widget across the two lists;
1794        // `validate_aggregate_widgets` rejects an empty `widgets` on its own,
1795        // so only call it when that list is non-empty (a pure-SQL view is
1796        // valid with an empty `widgets`).
1797        if self.widgets.is_empty() && self.sql_widgets.is_empty() {
1798            return Err(
1799                "view must declare at least one widget (`widgets:` and/or `sql_widgets:`)"
1800                    .to_string(),
1801            );
1802        }
1803        if !self.widgets.is_empty() {
1804            validate_aggregate_widgets(&self.widgets, "widgets")?;
1805        }
1806        validate_sql_widgets(&self.sql_widgets, "sql_widgets")?;
1807        for tag in &self.tags {
1808            if tag.trim().is_empty() {
1809                return Err("tags must not contain empty entries".to_string());
1810            }
1811        }
1812        Ok(())
1813    }
1814}
1815
1816/// Issue #246 — `emit:` manifest block for jobs whose stdout is
1817/// NDJSON observability events (one `ObsEvent` per line). Parallel
1818/// to `inventory:` but for the append-only timeline pipeline; see
1819/// `Manifest::emit` for the full contract.
1820#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1821pub struct EmitConfig {
1822    /// What kind of payload the agent should expect on stdout. Only
1823    /// `events` is defined today (parses each non-empty line as
1824    /// `ObsEvent` and publishes on `obs.<pc_id>`); future variants
1825    /// (e.g. metrics streams, structured trace events) plug in here.
1826    #[serde(rename = "type")]
1827    pub kind: EmitKind,
1828    /// Operator hint for where the script keeps its own state — the
1829    /// watermark file the PowerShell / sh body reads + writes
1830    /// between runs so it only emits NEW events since the last
1831    /// poll. The agent doesn't read this; it's documentation that
1832    /// the SPA (and `kanade job edit`) can surface to operators
1833    /// reviewing the manifest. Optional; the script is allowed to
1834    /// keep state anywhere (registry, env, etc.) — the field's
1835    /// presence makes the convention discoverable.
1836    #[serde(default, skip_serializing_if = "Option::is_none")]
1837    pub watermark_path: Option<String>,
1838}
1839
1840/// `emit.type` enum. Lowercase serde so manifests read
1841/// `type: events` rather than `Events`.
1842#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1843#[serde(rename_all = "lowercase")]
1844pub enum EmitKind {
1845    /// Per-line `ObsEvent` JSON. Agent parses + publishes on
1846    /// `obs.<pc_id>`, drops the stdout from the resulting
1847    /// `ExecResult`.
1848    Events,
1849}
1850
1851/// v0.31 / #40: declarative "flatten this JSON array into a real
1852/// SQLite table" spec on an inventory manifest. The projector
1853/// creates the table on first registration (CREATE TABLE IF NOT
1854/// EXISTS + indexes) and writes a row per element of
1855/// `payload[field]` on every result, scoped by (pc_id, job_id) so
1856/// each PC's rows replace cleanly without a per-PC schema.
1857#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1858pub struct ExplodeSpec {
1859    /// JSON array key under the payload to explode. E.g. `"apps"`
1860    /// for `payload: { apps: [{...}, {...}] }`.
1861    pub field: String,
1862    /// Derived SQLite table name. Operators choose this — pick
1863    /// something namespaced + stable (`inventory_sw_apps`, not
1864    /// `apps`) so multiple inventory manifests don't collide on a
1865    /// generic name.
1866    pub table: String,
1867    /// Element-level fields that uniquely identify a row inside one
1868    /// PC's payload. The full PK is `(pc_id, job_id) + these
1869    /// columns`. Required — operators must think about uniqueness
1870    /// (e.g. `["name", "source"]` for installed apps because the
1871    /// same name appears in multiple uninstall hives).
1872    ///
1873    /// v0.31 / #41: same tuple drives history identity. When
1874    /// `track_history` is on, the projector serialises these
1875    /// fields' values into `inventory_history.identity_json` for
1876    /// every change event, so queries like "every PC that ever
1877    /// installed Chrome (any source)" filter on identity_json
1878    /// content without a per-manifest schema.
1879    pub primary_key: Vec<String>,
1880    /// Per-element fields that become columns in the derived table.
1881    pub columns: Vec<ExplodeColumn>,
1882    /// v0.31 / #41: when true (default false), the projector
1883    /// diffs each PC's incoming payload against the prior rows
1884    /// for the same (pc_id, job_id) BEFORE the DELETE-then-INSERT
1885    /// replace, and writes added / removed / changed events into
1886    /// `inventory_history`. Lets operators answer time-dimension
1887    /// questions ("when did Chrome 120 first appear on PC X?",
1888    /// "what's the Win 11 23H2 rollout curve") without storing
1889    /// per-scan snapshots. Off by default so operators opt in
1890    /// per-spec — history has a real storage cost on long-lived
1891    /// deployments (mitigated by the 90-day default retention
1892    /// sweeper, see `cleanup` module).
1893    #[serde(default)]
1894    pub track_history: bool,
1895}
1896
1897/// One column in an [`ExplodeSpec`]'s derived table.
1898#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1899pub struct ExplodeColumn {
1900    /// JSON key under each array element. Becomes the column name
1901    /// in the derived SQLite table — we don't rename.
1902    pub field: String,
1903    /// SQLite affinity: `"text"` (default), `"integer"`, `"real"`.
1904    /// Storage maps directly via `sqlx::query.bind(...)`; type
1905    /// mismatches at INSERT-time fail loudly rather than silently
1906    /// dropping the row.
1907    #[serde(default, skip_serializing_if = "Option::is_none")]
1908    #[serde(rename = "type")]
1909    pub kind: Option<String>,
1910    /// When true, the projector creates a `CREATE INDEX` on this
1911    /// column at table-creation time. Boost for the common-filter
1912    /// columns (`name`, `version`) — operators mark them
1913    /// explicitly, the projector won't guess.
1914    #[serde(default)]
1915    pub index: bool,
1916}
1917
1918/// #vuln-roadmap: one declarative **external-data feed** on a `feed:`
1919/// manifest — see [`Manifest::feed`]. Unlike inventory [`ExplodeSpec`]
1920/// (keyed per `(pc_id, job_id)`), a feed is GLOBAL fleet-wide reference
1921/// data: the controller-tier job's script fetches + shapes it, prints the
1922/// array under [`field`](FeedSpec::field) inside a `#KANADE-FEED-BEGIN/END`
1923/// fence, and the projector REPLACES that feed's rows wholesale in the
1924/// shared `feeds` table keyed `(feed_id, item_id)`. The full element JSON
1925/// lands in a `data` column, so a `view:` SQL `json_extract`s whatever
1926/// shape the feed carries — no per-feed schema, no dynamic DDL. One
1927/// manifest may declare several feeds.
1928#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1929pub struct FeedSpec {
1930    /// Stable feed identifier — the `feed_id` partition in the shared
1931    /// `feeds` table. Operators choose this; namespace it (`cisa-kev`,
1932    /// `endoflife-windows`) so feeds don't collide. A new result for the
1933    /// same id replaces that partition wholesale.
1934    pub id: String,
1935    /// JSON array key under the (fenced) payload to ingest. E.g.
1936    /// `"vulnerabilities"` for `{ vulnerabilities: [{...}, {...}] }`.
1937    pub field: String,
1938    /// Element-level field(s) whose values uniquely identify an item
1939    /// within the feed — they form the `item_id` key (joined for a
1940    /// composite key). Required: operators must think about uniqueness
1941    /// (e.g. `["cveID"]` for CISA KEV). An element missing any of these is
1942    /// skipped (it has no stable identity).
1943    pub primary_key: Vec<String>,
1944}
1945
1946#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1947pub struct DisplayField {
1948    /// Top-level key in the stdout JSON.
1949    pub field: String,
1950    /// Human-readable column header.
1951    pub label: String,
1952    /// Optional render hint — `"number"`, `"bytes"`, `"timestamp"`,
1953    /// or `"table"` (#39). Defaults to plain text rendering on the
1954    /// SPA side. `"table"` expects the field's value to be a JSON
1955    /// array of objects and renders a nested sub-table on the
1956    /// per-PC detail page using `columns` as the schema; the fleet
1957    /// summary view falls back to showing the row count for
1958    /// `"table"` cells so the wide list stays compact.
1959    #[serde(default, skip_serializing_if = "Option::is_none")]
1960    #[serde(rename = "type")]
1961    pub kind: Option<String>,
1962    /// v0.30 / #39: when `kind == "table"`, the SPA renders the
1963    /// field's value (an array of objects like
1964    /// `disks: [{ device_id, size_bytes, ... }]`) as a nested
1965    /// sub-table using these columns. Each column is itself a
1966    /// `DisplayField`, so the nested cells reuse the same render
1967    /// hints (`bytes`, `number`, `timestamp`) — no parallel format
1968    /// pipeline. Ignored for any other `kind`.
1969    #[serde(default, skip_serializing_if = "Option::is_none")]
1970    pub columns: Option<Vec<DisplayField>>,
1971}
1972
1973#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1974pub struct Rollout {
1975    #[serde(default)]
1976    pub strategy: RolloutStrategy,
1977    pub waves: Vec<Wave>,
1978}
1979
1980#[derive(
1981    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
1982)]
1983#[serde(rename_all = "lowercase")]
1984pub enum RolloutStrategy {
1985    #[default]
1986    Wave,
1987}
1988
1989#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1990pub struct Wave {
1991    pub group: String,
1992    /// humantime delay measured from the deploy's publish time. wave[0]
1993    /// typically has "0s"; subsequent waves use minutes / hours.
1994    pub delay: String,
1995}
1996
1997#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default)]
1998pub struct Target {
1999    #[serde(default)]
2000    pub groups: Vec<String>,
2001    #[serde(default)]
2002    pub pcs: Vec<String>,
2003    #[serde(default)]
2004    pub all: bool,
2005}
2006
2007impl Target {
2008    /// At least one of all / groups / pcs is set.
2009    pub fn is_specified(&self) -> bool {
2010        self.all || !self.groups.is_empty() || !self.pcs.is_empty()
2011    }
2012
2013    /// Whether a PC (its `pc_id` + group membership) falls in this target:
2014    /// `all`, or the pc is listed, or it belongs to a listed group. Used
2015    /// by the agent to scope `client.visible_to` (#816). An unspecified
2016    /// target matches nobody (callers should treat "no target" as
2017    /// "visible to all" before calling this).
2018    pub fn matches(&self, pc_id: &str, groups: &[String]) -> bool {
2019        self.all
2020            || self.pcs.iter().any(|p| p == pc_id)
2021            || self.groups.iter().any(|g| groups.contains(g))
2022    }
2023}
2024
2025#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2026pub struct Execute {
2027    pub shell: ExecuteShell,
2028    /// Inline script body. Mutually exclusive with [`script_file`]
2029    /// and [`script_object`]; exactly one of the three must be set
2030    /// (enforced by [`Execute::validate_script_source`] at the
2031    /// write-side parse boundaries — `kanade job create` and
2032    /// `POST /api/jobs`).
2033    ///
2034    /// Empty string is treated as **unset** so operators can swap
2035    /// to a `script_file:` / `script_object:` alternative just by
2036    /// commenting out the body, without having to also drop the
2037    /// `script:` key entirely.
2038    ///
2039    /// [`script_file`]: Self::script_file
2040    /// [`script_object`]: Self::script_object
2041    #[serde(default, skip_serializing_if = "Option::is_none")]
2042    pub script: Option<String>,
2043    /// Repo-local file path resolved by the operator-side CLI at
2044    /// `kanade job create` time. The CLI reads the file, slots its
2045    /// contents into `script`, and clears this field before
2046    /// POSTing — so the backend / agents never see `script_file`
2047    /// in stored manifests. SPEC §2.4.1.
2048    ///
2049    /// The resolver shipped with #210: `kanade job create` /
2050    /// `kanade job validate` inline this field end-to-end. Because
2051    /// resolution is CLI-side (it needs the operator's filesystem),
2052    /// `POST /api/jobs` rejects a manifest that still carries it
2053    /// (#918) — a stored `script_file` job would 400 at every exec.
2054    /// Inline the script or use `script_object` when writing through
2055    /// the API / SPA editor.
2056    #[serde(default, skip_serializing_if = "Option::is_none")]
2057    pub script_file: Option<String>,
2058    /// Object Store reference (`<name>/<version>`) into the
2059    /// `scripts` bucket (`OBJECT_SCRIPTS`). Agents fetch the body
2060    /// at Execute time via `/api/script-objects/{name}/{version}`
2061    /// and cache it locally. SPEC §2.4.1.
2062    ///
2063    /// Fully wired (#210/#211): the backend resolves the digest at
2064    /// exec submission (`api::exec::resolve_script_source`), the agent
2065    /// fetches + sha-verifies + caches the body (`script_cache`), and
2066    /// `kanade script` CRUDs the store. Unlike `script_file:` (inlined
2067    /// CLI-side, git-managed), this keeps the body in versioned,
2068    /// digest-pinned object storage — the ops-managed counterpart.
2069    #[serde(default, skip_serializing_if = "Option::is_none")]
2070    pub script_object: Option<String>,
2071    /// humantime duration string (e.g. "30s", "10m"). Script-intrinsic
2072    /// — represents how long this script reasonably takes to run.
2073    pub timeout: String,
2074    /// Token + session combination the agent uses to launch the
2075    /// script (v0.21). Default = [`RunAs::System`] (Session 0,
2076    /// LocalSystem privileges, no GUI) — matches pre-v0.21 behavior.
2077    #[serde(default)]
2078    pub run_as: RunAs,
2079    /// Working directory for the spawned child (v0.21.1). When
2080    /// unset, the child inherits the agent's cwd — on Windows that
2081    /// means `%SystemRoot%\System32` for the prod service, which is
2082    /// almost never what operators actually want. Use an absolute
2083    /// path; relative paths are passed through to the OS verbatim.
2084    /// `%PROGRAMDATA%` works for `run_as: system`; for `run_as: user`
2085    /// you'd want `%USERPROFILE%` (but expansion happens in the
2086    /// shell, so write `$env:USERPROFILE` for PowerShell, or set
2087    /// it via teravars before `kanade job create`).
2088    #[serde(default, skip_serializing_if = "Option::is_none")]
2089    pub cwd: Option<String>,
2090}
2091
2092impl Execute {
2093    /// Treat an empty — or whitespace-only (#918) — `script:` body as
2094    /// "intentionally unset". Operators commenting out a block-scalar
2095    /// tend to leave the key behind, and failing the validator on
2096    /// `script: ""` would surprise them; a body of blank lines can't
2097    /// be a real script either, only a commented-out one, and letting
2098    /// it count as "set" shipped a validated do-nothing job.
2099    fn has_inline_script(&self) -> bool {
2100        matches!(&self.script, Some(s) if !s.trim().is_empty())
2101    }
2102
2103    /// Enforce that exactly one of `script` / `script_file` /
2104    /// `script_object` is set. Called at the write-side parse
2105    /// boundaries (CLI `kanade job create` + backend
2106    /// `POST /api/jobs`) so ambiguous YAML is rejected before it
2107    /// reaches the JOBS KV. Read paths (projector, agent
2108    /// scheduler, list endpoints) skip this check — they only ever
2109    /// see what the write path already validated.
2110    pub fn validate_script_source(&self) -> Result<(), String> {
2111        // #918: a blank-but-present alternate source is a typo, not a
2112        // choice — `script_file: ""` used to count as "set", pass the
2113        // exactly-one check, and only fail at use time (the CLI reads
2114        // a file named ""; a stored blank script_object 404s on every
2115        // exec). Reject it with the field named. Inline `script` keeps
2116        // its documented empty-means-unset semantics instead — see
2117        // `has_inline_script`.
2118        if matches!(&self.script_file, Some(s) if s.trim().is_empty()) {
2119            return Err(
2120                "execute.script_file must not be blank when set (drop the key to use \
2121                 another source)"
2122                    .into(),
2123            );
2124        }
2125        if matches!(&self.script_object, Some(s) if s.trim().is_empty()) {
2126            return Err(
2127                "execute.script_object must not be blank when set (drop the key to use \
2128                 another source)"
2129                    .into(),
2130            );
2131        }
2132        let inline = self.has_inline_script();
2133        let file = self.script_file.is_some();
2134        let obj = self.script_object.is_some();
2135        let set = [inline, file, obj].into_iter().filter(|b| *b).count();
2136        match set {
2137            1 => {}
2138            0 => {
2139                return Err(
2140                    "execute: one of `script`, `script_file`, `script_object` must be set".into(),
2141                );
2142            }
2143            _ => {
2144                return Err(format!(
2145                    "execute: only one of `script` / `script_file` / `script_object` may be set \
2146                     (got script={inline}, script_file={file}, script_object={obj})"
2147                ));
2148            }
2149        }
2150        // #918: a script_object ref is `<name>/<version>` — the agent
2151        // fetches the body via `/api/script-objects/{name}/{version}`
2152        // and the backend uses the ref *verbatim* as the Object Store
2153        // key (`resolve_script_source`), so each half must be a
2154        // well-formed resource id: exactly one slash, and both halves
2155        // [A-Za-z0-9._-]. `is_valid_resource_id` also rejects a half
2156        // that's blank OR merely whitespace-padded (`"foo/bar "`) —
2157        // padding survives a JSON POST body (unlike a YAML plain
2158        // scalar) and would 404 on every exec (gemini/claude #943).
2159        if let Some(obj_ref) = self.script_object.as_deref() {
2160            let parts: Vec<&str> = obj_ref.split('/').collect();
2161            if parts.len() != 2 || parts.iter().any(|p| !is_valid_resource_id(p)) {
2162                return Err(format!(
2163                    "execute.script_object must be `<name>/<version>` with each half \
2164                     [A-Za-z0-9._-] (got '{obj_ref}'); publish bodies with \
2165                     `kanade script publish <name> <version>`"
2166                ));
2167            }
2168        }
2169        Ok(())
2170    }
2171}
2172
2173/// Job-generic post-step hook (see [`Manifest::finalize`]). Runs after
2174/// the main `execute:` script (and the collect upload) on a clean exit,
2175/// with the step's structured result injected via an environment
2176/// variable. P1 supports an inline `script:` only — `script_file:` /
2177/// `script_object:` are follow-ups.
2178#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2179pub struct FinalizeSpec {
2180    pub shell: ExecuteShell,
2181    /// Inline script body (required; inline-only in P1).
2182    pub script: String,
2183    /// humantime duration string (e.g. `"60s"`, `"5m"`). Defaults to
2184    /// `60s` when unset.
2185    #[serde(default = "default_finalize_timeout")]
2186    pub timeout: String,
2187    /// Token + session combination, like [`Execute::run_as`]. Defaults
2188    /// to [`RunAs::System`].
2189    #[serde(default)]
2190    pub run_as: RunAs,
2191    /// Working directory for the hook child, like [`Execute::cwd`].
2192    #[serde(default, skip_serializing_if = "Option::is_none")]
2193    pub cwd: Option<String>,
2194    /// #965: for a `collect:` job, run this hook once per uploaded
2195    /// bundle (with a single-bundle `KANADE_COLLECT_RESULT`) as each
2196    /// bundle uploads, instead of once after the whole set. Lets an
2197    /// interrupted collect still clean up the days it managed to
2198    /// upload (partial progress sticks), breaking the
2199    /// offline-before-finalize backlog spiral.
2200    ///
2201    /// **Opt-in** (default `false` = one call after all bundles, the
2202    /// established contract) because per-bundle changes the hook's
2203    /// payload (all → one) and invocation count (1 → N), which would
2204    /// break a hook written for the all-at-once assumption (cross-bundle
2205    /// aggregation, once-only side effects, all-or-nothing). Only valid
2206    /// with a `collect:` hint — [`Manifest::validate`] rejects it
2207    /// otherwise, since a non-collect finalize has no bundles to iterate.
2208    #[serde(default)]
2209    pub on_each_bundle: bool,
2210}
2211
2212/// Default `finalize.timeout` when the operator omits it.
2213fn default_finalize_timeout() -> String {
2214    "60s".to_string()
2215}
2216
2217impl FinalizeSpec {
2218    /// Lower to the wire form forwarded onto a [`Command`]. The timeout
2219    /// parse falls back to 60s — [`Manifest::validate`] already rejects
2220    /// an unparseable value at create time, so the fire path uses a safe
2221    /// default rather than failing (mirrors
2222    /// [`CollectHint::max_size_bytes`]). A sub-second timeout floors at
2223    /// 1s for the same reason `build_command` does.
2224    pub fn lower(&self) -> FinalizeCommand {
2225        let timeout_secs = humantime::parse_duration(&self.timeout)
2226            .map(|d| d.as_secs().max(1))
2227            .unwrap_or(60);
2228        FinalizeCommand {
2229            shell: self.shell.into(),
2230            script: self.script.clone(),
2231            timeout_secs,
2232            run_as: self.run_as,
2233            cwd: self.cwd.clone(),
2234            on_each_bundle: self.on_each_bundle,
2235        }
2236    }
2237}
2238
2239impl Manifest {
2240    /// Cross-field semantic checks that don't fit into pure serde
2241    /// derive. Currently delegates to
2242    /// [`Execute::validate_script_source`] — see that method's
2243    /// docs for the rationale on which call sites should run this.
2244    pub fn validate(&self) -> Result<(), String> {
2245        self.execute.validate_script_source()?;
2246        // Fail CLOSED on an unrecognised execution tier. `#[serde(other)]`
2247        // turns a typo (`tier: controler`) or a future tier into
2248        // `Tier::Unknown`; without this check the controller gate would
2249        // fall back to normal endpoint dispatch, so an operator who *meant*
2250        // to confine a job to the controller tier would silently get
2251        // fleet-wide dispatch (CodeRabbit #905). Rejecting it at the write
2252        // boundary surfaces the typo at `job create`, and — since
2253        // `exec_manifest` re-validates — a hand-poked KV manifest can't slip
2254        // a controller-tier job onto endpoints either.
2255        if matches!(self.tier, Some(Tier::Unknown)) {
2256            return Err(
2257                "tier: unrecognised execution tier — use `endpoint` or `controller` \
2258                 (this is a typo, or a tier a newer kanade supports that this backend does not)"
2259                    .to_string(),
2260            );
2261        }
2262        // #vuln-roadmap: a `feed:` spec drives the global `feeds`
2263        // projection. id / item_id are stored as *values* (the `feeds`
2264        // table is fixed-schema — no identifier splicing), but blank
2265        // values are silent projection bugs: a blank id collides every
2266        // feed under "", a blank field never matches the payload array,
2267        // and an empty primary_key yields no item_id (every row dropped).
2268        // Reject them at the write boundary so `kanade job create` surfaces
2269        // the typo instead of producing an empty/garbled feed at run time.
2270        let mut seen_feed_ids: Vec<&str> = Vec::new();
2271        for spec in &self.feed {
2272            let id = spec.id.trim();
2273            if id.is_empty() {
2274                return Err("feed.id must not be empty".to_string());
2275            }
2276            if spec.field.trim().is_empty() {
2277                return Err(format!("feed '{id}' field must not be empty"));
2278            }
2279            if spec.primary_key.is_empty() {
2280                return Err(format!("feed '{id}' needs at least one primary_key field"));
2281            }
2282            if spec.primary_key.iter().any(|k| k.trim().is_empty()) {
2283                return Err(format!(
2284                    "feed '{id}' primary_key must not contain blank entries"
2285                ));
2286            }
2287            // Two specs sharing an id both target the same `feeds`
2288            // partition and would clobber each other on every run —
2289            // reject the ambiguity rather than let last-write-wins.
2290            if seen_feed_ids.contains(&id) {
2291                return Err(format!("feed id '{id}' is declared more than once"));
2292            }
2293            seen_feed_ids.push(id);
2294        }
2295        // A `feed:` job fetches external data and MUST run on the trusted
2296        // controller tier — the dispatch guard (`requires_controller`) treats
2297        // a non-empty `feed:` as implying `controller`. An explicit
2298        // `tier: endpoint` contradicts that intent; reject it rather than
2299        // silently overriding, so the operator can't believe a feed runs on
2300        // endpoints. Omitting `tier:` (the default) is fine — the implication
2301        // confines it; `tier: controller` is the redundant-but-explicit form.
2302        if !self.feed.is_empty() && matches!(self.tier, Some(Tier::Endpoint)) {
2303            return Err(
2304                "feed: requires the controller tier — remove `tier: endpoint` (a feed: job \
2305                 fetches external data and is confined to the controller_group)"
2306                    .to_string(),
2307            );
2308        }
2309        // A present-but-empty finalize script is an invisible no-op
2310        // (the hook would run an empty body); reject it at the write
2311        // boundary. Inline-only in P1, so `script` is the sole source.
2312        if let Some(finalize) = &self.finalize {
2313            if finalize.script.trim().is_empty() {
2314                return Err("finalize.script must not be empty".to_string());
2315            }
2316            // Reject an unparseable timeout at the write boundary so the
2317            // operator sees the error at `job create` rather than getting
2318            // a silent fire-time fallback (`FinalizeSpec::lower` floors to
2319            // 60s, which would otherwise mask a typo).
2320            if humantime::parse_duration(&finalize.timeout).is_err() {
2321                return Err(format!(
2322                    "finalize.timeout '{}' is not a valid duration",
2323                    finalize.timeout
2324                ));
2325            }
2326            // Disallow cmd for finalize: the agent injects the result JSON
2327            // into the hook's environment, and cmd.exe quoting doesn't
2328            // nest — JSON's `"` plus shell metacharacters in a collected
2329            // path/key could break out into command injection at the
2330            // agent's (often LocalSystem) privilege. PowerShell's
2331            // single-quote escaping is safe, and finalize hooks are
2332            // PowerShell by convention anyway.
2333            if finalize.shell == ExecuteShell::Cmd {
2334                return Err(
2335                    "finalize.shell: cmd is not supported for finalize hooks (shell-injection \
2336                     risk when the result JSON is injected into the environment); use powershell"
2337                        .to_string(),
2338                );
2339            }
2340            // #965: per-bundle finalize only means anything for a
2341            // collect: job — a non-collect finalize has no bundles to
2342            // iterate (it runs once after the script). Reject the
2343            // combination at the write boundary so a confused operator
2344            // is told rather than silently getting a no-op.
2345            if finalize.on_each_bundle && self.collect.is_none() {
2346                return Err(
2347                    "finalize.on_each_bundle: true requires a collect: hint — a non-collect \
2348                     finalize has no bundles to iterate (it runs once after the script)"
2349                        .to_string(),
2350                );
2351            }
2352        }
2353        // Stdout-format compatibility (#821). `inventory:` / `check:` /
2354        // `collect:` now COMPOSE: each reads its own `#KANADE-<KIND>-
2355        // BEGIN/END`-fenced JSON block from stdout, so a single job can
2356        // project inventory facts, drive a Health-tab check, AND collect
2357        // files in one run. (A single-hint job may still skip the fence;
2358        // a multi-hint job must fence each block.)
2359        //
2360        // `emit:` remains the exception — its stdout is line-delimited
2361        // NDJSON consumed whole and then omitted from the result — so it
2362        // can't share stdout with any fenced hint. `feed:` is another fenced
2363        // stdout consumer (`#KANADE-FEED`), so it belongs in this exclusion
2364        // too: with `emit:` present the projector never sees the feed's fence
2365        // (CodeRabbit).
2366        if self.emit.is_some()
2367            && (self.inventory.is_some()
2368                || self.check.is_some()
2369                || self.collect.is_some()
2370                || !self.feed.is_empty())
2371        {
2372            return Err(
2373                "`emit:` is incompatible with `inventory:` / `check:` / `collect:` / `feed:` — \
2374                 emit's stdout is NDJSON timeline events (consumed whole and omitted from the \
2375                 result), while the others read fenced JSON blocks from stdout"
2376                    .to_string(),
2377            );
2378        }
2379        // A check's `name` is the Health-tab row id (React key); the
2380        // field names tell the agent where to read status/detail.
2381        // An empty value is an invisible runtime bug, and the serde
2382        // defaults don't guard an operator who writes `status_field:
2383        // ""` explicitly — reject all three here.
2384        if let Some(check) = &self.check {
2385            for (label, value) in [
2386                ("check.name", &check.name),
2387                ("check.status_field", &check.status_field),
2388                ("check.detail_field", &check.detail_field),
2389            ] {
2390                if value.trim().is_empty() {
2391                    return Err(format!("{label} must not be empty"));
2392                }
2393            }
2394            // A present-but-blank `troubleshoot` is a broken
2395            // remediation job id (the "修復する" button would target
2396            // an empty manifest id) — reject it too.
2397            if let Some(troubleshoot) = &check.troubleshoot {
2398                if troubleshoot.trim().is_empty() {
2399                    return Err("check.troubleshoot must not be empty when set".to_string());
2400                }
2401            }
2402            // A present-but-blank `label` would render an empty row
2403            // title on the Health tab / Compliance page — reject it so
2404            // the slug fallback only ever kicks in when label is absent.
2405            if let Some(label) = &check.label {
2406                if label.trim().is_empty() {
2407                    return Err("check.label must not be empty when set".to_string());
2408                }
2409            }
2410            if let Some(alert) = &check.alert {
2411                // An alert that names no recipient is a silent no-op.
2412                if !alert.notify_user && alert.notify_groups.is_empty() {
2413                    return Err("check.alert must set notify_user and/or notify_groups".to_string());
2414                }
2415                if alert.title.trim().is_empty() {
2416                    return Err("check.alert.title must not be empty".to_string());
2417                }
2418                // `on: []` would never fire; an empty group name resolves to
2419                // a malformed `notifications.group.` subject.
2420                if alert.on.is_empty() {
2421                    return Err("check.alert.on must list at least one status".to_string());
2422                }
2423                if alert.notify_groups.iter().any(|g| g.trim().is_empty()) {
2424                    return Err("check.alert.notify_groups must not contain blanks".to_string());
2425                }
2426                // Email is addressed via group_contacts (group → email), so
2427                // there must be a group to map. notify_user has no email.
2428                if alert.email && alert.notify_groups.is_empty() {
2429                    return Err(
2430                        "check.alert.email requires notify_groups (email is addressed per group, not per user)"
2431                            .to_string(),
2432                    );
2433                }
2434                // The alert rides the `check_status` projection, which only
2435                // runs for `fleet: true`.
2436                if !check.fleet {
2437                    return Err(
2438                        "check.alert requires fleet: true (the alert rides the compliance projection)"
2439                            .to_string(),
2440                    );
2441                }
2442            }
2443        }
2444        // #291: a `client:` job is rendered in the Client App's
2445        // catalog (`jobs.list` → `jobs.execute`). serde already makes
2446        // `name` + `category` required at parse time; the only gap is
2447        // a present-but-blank `name`, which would render an empty row
2448        // title — reject it like the other display-id fields.
2449        if let Some(client) = &self.client {
2450            if client.name.trim().is_empty() {
2451                return Err("client.name must not be empty".to_string());
2452            }
2453            // #792: category is a free-form key now, so a blank one would
2454            // group the job under an empty tab — reject it like `name`.
2455            if client.category.trim().is_empty() {
2456                return Err("client.category must not be empty".to_string());
2457            }
2458            // Optional display fields, when present, must be
2459            // meaningful: a blank `description` renders an empty
2460            // subtitle and a blank `icon` is a dangling lucide name.
2461            // Same present-but-blank guard the `check:` block applies
2462            // to its optional `troubleshoot` id.
2463            for (label, value) in [
2464                ("client.description", &client.description),
2465                ("client.icon", &client.icon),
2466                ("client.category_label", &client.category_label),
2467                ("client.category_icon", &client.category_icon),
2468            ] {
2469                if let Some(v) = value {
2470                    if v.trim().is_empty() {
2471                        return Err(format!("{label} must not be empty when set"));
2472                    }
2473                }
2474            }
2475            // #816: a present-but-empty `visible_to` (no all/groups/pcs)
2476            // would hide the job from everyone in the Client App — almost
2477            // certainly a mistake. Require at least one selector; omit the
2478            // whole block to mean "visible to all".
2479            if let Some(t) = &client.visible_to {
2480                if !t.is_specified() {
2481                    return Err(
2482                        "client.visible_to must set at least one of all / groups / pcs (omit it for all PCs)"
2483                            .to_string(),
2484                    );
2485                }
2486            }
2487            // show_when: a dynamic display gate keyed on a check result. A
2488            // malformed check slug matches nothing and an empty status list
2489            // matches nothing — both would silently hide the job forever,
2490            // so reject them at create time rather than at a confused
2491            // "why isn't my job showing?" later. The slug must be a clean
2492            // resource id (same charset checks/jobs use): a typo with spaces
2493            // or punctuation can never match a real check name, so catch it
2494            // here instead of failing closed at runtime. (Whether the slug
2495            // names a check that actually EXISTS can't be checked here —
2496            // checks are keyed by name across manifests — so a valid-but-
2497            // unknown slug stays a runtime miss = hidden, the documented
2498            // fail-closed behavior.)
2499            if let Some(sw) = &client.show_when {
2500                if !is_valid_resource_id(sw.check.trim()) {
2501                    return Err(
2502                        "client.show_when.check must be a non-empty check slug ([A-Za-z0-9._-])"
2503                            .to_string(),
2504                    );
2505                }
2506                if sw.is.is_empty() {
2507                    return Err(
2508                        "client.show_when.is must list at least one check status".to_string()
2509                    );
2510                }
2511            }
2512            // confirm: a present-but-blank custom message would render an
2513            // empty dialog title — reject it like the other display fields.
2514            // (A `confirm: false` / `enabled: false` with no message is fine:
2515            // the dialog is suppressed, so there's nothing to render.)
2516            if let Some(c) = &client.confirm {
2517                if let Some(msg) = &c.message {
2518                    if msg.trim().is_empty() {
2519                        return Err("client.confirm.message must not be empty when set".to_string());
2520                    }
2521                }
2522            }
2523        }
2524        // #219: a `collect:` job's `name` heads the bundle on the SPA
2525        // Collect page (and the Client App row when paired with
2526        // `client:`), `files_field` tells the agent where to read the
2527        // path list, and `max_size` must be a parseable size so a typo
2528        // is caught at create time rather than silently capping the
2529        // bundle at the default on the fire path.
2530        if let Some(collect) = &self.collect {
2531            if collect.name.trim().is_empty() {
2532                return Err("collect.name must not be empty".to_string());
2533            }
2534            if collect.files_field.trim().is_empty() {
2535                return Err("collect.files_field must not be empty".to_string());
2536            }
2537            if let Some(description) = &collect.description {
2538                if description.trim().is_empty() {
2539                    return Err("collect.description must not be empty when set".to_string());
2540                }
2541            }
2542            if let Some(max_size) = &collect.max_size {
2543                parse_size_bytes(max_size).map_err(|e| format!("collect.max_size: {e}"))?;
2544            }
2545        }
2546        // #720/#743: `aggregate:` is a pure read-spec (it never touches
2547        // stdout and is never sent to an agent), so it composes with every
2548        // other hint. The per-widget rules are shared with the standalone
2549        // `view` resource — see [`validate_aggregate_widgets`].
2550        if let Some(widgets) = &self.aggregate {
2551            validate_aggregate_widgets(widgets, "aggregate")?;
2552        }
2553        // A blank / whitespace-only tag is an invisible operator typo
2554        // that would render an empty filter chip on the Jobs page —
2555        // reject it like the other present-but-blank display fields.
2556        for tag in &self.tags {
2557            if tag.trim().is_empty() {
2558                return Err("tags must not contain empty entries".to_string());
2559            }
2560        }
2561        Ok(())
2562    }
2563}
2564
2565#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
2566#[serde(rename_all = "lowercase")]
2567pub enum ExecuteShell {
2568    Powershell,
2569    Cmd,
2570}
2571
2572impl From<ExecuteShell> for Shell {
2573    fn from(s: ExecuteShell) -> Self {
2574        match s {
2575            ExecuteShell::Powershell => Shell::Powershell,
2576            ExecuteShell::Cmd => Shell::Cmd,
2577        }
2578    }
2579}
2580
2581#[cfg(test)]
2582mod tests {
2583    use super::*;
2584
2585    #[test]
2586    fn inventory_payload_extracts_fenced_block() {
2587        // Readable message + fenced JSON → only the JSON, trimmed.
2588        let stdout = "Wi-Fi 設定を適用しました。\n\
2589            #KANADE-INVENTORY-BEGIN\n\
2590            {\"applied\": true}\n\
2591            #KANADE-INVENTORY-END\n";
2592        assert_eq!(inventory_payload(stdout), "{\"applied\": true}");
2593    }
2594
2595    #[test]
2596    fn inventory_payload_falls_back_to_whole_stdout() {
2597        // No fence (a plain inventory job) → whole stdout, trimmed.
2598        assert_eq!(
2599            inventory_payload("  {\"ram_gb\": 16}\n"),
2600            "{\"ram_gb\": 16}"
2601        );
2602    }
2603
2604    #[test]
2605    fn inventory_payload_handles_unterminated_fence() {
2606        // Closing marker missing (e.g. truncated) → everything after the
2607        // opener, trimmed.
2608        let stdout = "msg\n#KANADE-INVENTORY-BEGIN\n{\"a\": 1}";
2609        assert_eq!(inventory_payload(stdout), "{\"a\": 1}");
2610    }
2611
2612    #[test]
2613    fn inventory_payload_ignores_mid_line_sentinel() {
2614        // The marker echoed mid-line (not at a line start) must NOT be
2615        // treated as a fence — fall back to the whole stdout.
2616        let stdout = "see #KANADE-INVENTORY-BEGIN in the docs\nnot json";
2617        assert_eq!(inventory_payload(stdout), stdout.trim());
2618    }
2619
2620    #[test]
2621    fn fenced_payload_extracts_each_hint_block_independently() {
2622        // #821: one stdout carrying a user message + all three fenced
2623        // blocks — every consumer pulls only its own.
2624        let stdout = "\
2625done!
2626#KANADE-INVENTORY-BEGIN
2627{\"os\":\"win\"}
2628#KANADE-INVENTORY-END
2629#KANADE-CHECK-BEGIN
2630{\"status\":\"ok\"}
2631#KANADE-CHECK-END
2632#KANADE-COLLECT-BEGIN
2633{\"files\":[\"a\"]}
2634#KANADE-COLLECT-END
2635";
2636        assert_eq!(
2637            fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
2638            "{\"os\":\"win\"}"
2639        );
2640        assert_eq!(
2641            fenced_payload(stdout, CHECK_BLOCK_BEGIN, CHECK_BLOCK_END),
2642            "{\"status\":\"ok\"}"
2643        );
2644        assert_eq!(
2645            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2646            "{\"files\":[\"a\"]}"
2647        );
2648    }
2649
2650    #[test]
2651    fn fenced_payload_falls_back_to_whole_stdout_without_fence() {
2652        // A single-hint job needs no fence — the whole (trimmed) stdout is
2653        // the payload.
2654        let stdout = "  {\"files\":[\"a\"]}  ";
2655        assert_eq!(
2656            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2657            "{\"files\":[\"a\"]}"
2658        );
2659    }
2660
2661    #[test]
2662    fn fenced_payload_returns_empty_when_other_fences_present_but_mine_missing() {
2663        // Multi-hint output (inventory + check fenced) but the COLLECT
2664        // fence is missing — collect must NOT fall back to the whole
2665        // stdout (which holds the inventory/check blocks) and cross-parse
2666        // a sibling block; it gets "" → its JSON parse fails → no data.
2667        let stdout = "\
2668#KANADE-INVENTORY-BEGIN
2669{\"os\":\"win\"}
2670#KANADE-INVENTORY-END
2671#KANADE-CHECK-BEGIN
2672{\"status\":\"ok\"}
2673#KANADE-CHECK-END
2674";
2675        assert_eq!(
2676            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2677            ""
2678        );
2679        // ...while the hints that DID fence still extract correctly.
2680        assert_eq!(
2681            fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
2682            "{\"os\":\"win\"}"
2683        );
2684    }
2685
2686    /// The example check-job + schedule YAMLs shipped under `configs/`
2687    /// must stay valid as the schema evolves (#290 PR-C). `include_str!`
2688    /// pins them at compile time so a breaking edit fails `cargo test`
2689    /// rather than only `kanade job create` at deploy time.
2690    #[test]
2691    fn example_check_job_yamls_parse_and_validate() {
2692        let jobs = [
2693            (
2694                "check-bitlocker",
2695                include_str!("../../../configs/jobs/check-bitlocker.yaml"),
2696            ),
2697            (
2698                "check-av-signature",
2699                include_str!("../../../configs/jobs/check-av-signature.yaml"),
2700            ),
2701            (
2702                "check-cert-expiry",
2703                include_str!("../../../configs/jobs/check-cert-expiry.yaml"),
2704            ),
2705            (
2706                "check-disk-space",
2707                include_str!("../../../configs/jobs/check-disk-space.yaml"),
2708            ),
2709            (
2710                "check-pending-reboot",
2711                include_str!("../../../configs/jobs/check-pending-reboot.yaml"),
2712            ),
2713            (
2714                "check-defender-rtp",
2715                include_str!("../../../configs/jobs/check-defender-rtp.yaml"),
2716            ),
2717            (
2718                "check-firewall",
2719                include_str!("../../../configs/jobs/check-firewall.yaml"),
2720            ),
2721        ];
2722        for (name, yaml) in jobs {
2723            let m: Manifest =
2724                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} parse: {e}"));
2725            m.validate()
2726                .unwrap_or_else(|e| panic!("{name} validate: {e}"));
2727            let check = m
2728                .check
2729                .as_ref()
2730                .unwrap_or_else(|| panic!("{name} must carry a check: hint"));
2731            assert!(!check.name.trim().is_empty(), "{name} check.name empty");
2732            // These examples all read admin-only WMI / registry / netsh
2733            // state, so they run_as system. NOTE: that's a property of
2734            // these particular checks, NOT of the `check:` contract — a
2735            // check probing user-session state could run_as user.
2736            assert_eq!(
2737                m.execute.run_as,
2738                RunAs::System,
2739                "{name} should run_as system"
2740            );
2741        }
2742    }
2743
2744    /// The example user-invokable job YAMLs (#291) shipped under
2745    /// `configs/jobs/` must stay valid as the `client:` schema
2746    /// evolves. `include_str!` pins them at compile time so a breaking
2747    /// edit fails `cargo test`, not `kanade job create` at deploy.
2748    #[test]
2749    fn example_client_job_yamls_parse_and_validate() {
2750        let jobs = [
2751            (
2752                "fix-teams-cache",
2753                "troubleshoot",
2754                include_str!("../../../configs/jobs/fix-teams-cache.yaml"),
2755            ),
2756            (
2757                "chrome-update",
2758                "software_update",
2759                include_str!("../../../configs/jobs/chrome-update.yaml"),
2760            ),
2761            (
2762                "install-slack",
2763                "catalog",
2764                include_str!("../../../configs/jobs/install-slack.yaml"),
2765            ),
2766            (
2767                "fix-defender-rtp",
2768                "troubleshoot",
2769                include_str!("../../../configs/jobs/fix-defender-rtp.yaml"),
2770            ),
2771            // #792 custom category ("settings") + #809 message/inventory.
2772            (
2773                "example-power-plan",
2774                "settings",
2775                include_str!("../../../configs/jobs/example-power-plan.yaml"),
2776            ),
2777            // #792: diagnostics moved to its own "support" tab.
2778            (
2779                "collect-diagnostics",
2780                "support",
2781                include_str!("../../../configs/jobs/collect-diagnostics.yaml"),
2782            ),
2783        ];
2784        for (id, category, yaml) in jobs {
2785            let m: Manifest =
2786                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
2787            m.validate()
2788                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
2789            assert_eq!(m.id, id, "{id} id mismatch");
2790            let client = m
2791                .client
2792                .as_ref()
2793                .unwrap_or_else(|| panic!("{id} must carry a client: block"));
2794            assert!(!client.name.trim().is_empty(), "{id} client.name empty");
2795            assert_eq!(client.category, category, "{id} category");
2796        }
2797    }
2798
2799    /// #219: the shipped `collect:` example must stay valid as the
2800    /// schema evolves. `include_str!` pins it at compile time so a
2801    /// breaking edit (or a YAML typo in the PowerShell block) fails
2802    /// `cargo test` rather than `kanade job create` at deploy. It carries
2803    /// both `collect:` and `client:` (end-user-triggerable), which must
2804    /// compose.
2805    #[test]
2806    fn example_collect_job_yaml_parses_and_validates() {
2807        let yaml = include_str!("../../../configs/jobs/collect-diagnostics.yaml");
2808        let m: Manifest = serde_yaml::from_str(yaml).expect("collect-diagnostics parse");
2809        m.validate().expect("collect-diagnostics validate");
2810        assert_eq!(m.id, "collect-diagnostics");
2811        let collect = m.collect.as_ref().expect("collect: block present");
2812        assert!(!collect.name.trim().is_empty());
2813        assert_eq!(collect.files_field, "files");
2814        assert_eq!(collect.max_size_bytes(), 50_000_000);
2815        // collect + client compose — the Client App can trigger it.
2816        assert!(
2817            m.client.is_some(),
2818            "collect-diagnostics also carries client:"
2819        );
2820    }
2821
2822    /// The `emit: { type: events }` collector jobs under
2823    /// `configs/jobs/` feed the obs_events timeline. `include_str!`
2824    /// pins them at compile time so a breaking edit (e.g. an `emit:`
2825    /// paired with `check:`/`inventory:`, a bad watermark field, or a
2826    /// YAML typo in the PowerShell block) fails `cargo test` rather
2827    /// than `kanade job create` at deploy. Every one must carry an
2828    /// `emit.type=events` block and NO check/inventory (validate()
2829    /// rejects the pairing).
2830    #[test]
2831    fn example_event_collector_job_yamls_parse_and_validate() {
2832        let jobs = [
2833            // collect-winlog-events was retired in #841 PR2 — the scheduled
2834            // human-session / power timeline is now read natively by the
2835            // agent (kanade-agent `winlog` module via EvtQuery), no
2836            // PowerShell job. collect-winlog-logons-all stays as the
2837            // on-demand forensic all-token-logons companion.
2838            (
2839                "collect-winlog-logons-all",
2840                include_str!("../../../configs/jobs/collect-winlog-logons-all.yaml"),
2841            ),
2842            (
2843                "collect-wlan-events",
2844                include_str!("../../../configs/jobs/collect-wlan-events.yaml"),
2845            ),
2846        ];
2847        for (id, yaml) in jobs {
2848            // Strict parse so an unknown-key typo in these fixtures fails
2849            // here (not silently at deploy) — the runtime Manifest is
2850            // unknown-key-tolerant, so the lenient serde_yaml::from_str
2851            // wouldn't catch fixture drift (CodeRabbit #689).
2852            let m: Manifest =
2853                crate::strict::from_yaml_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
2854            m.validate()
2855                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
2856            assert_eq!(m.id, id, "{id} id mismatch");
2857            let emit = m
2858                .emit
2859                .as_ref()
2860                .unwrap_or_else(|| panic!("{id} must carry an emit: block"));
2861            assert_eq!(emit.kind, EmitKind::Events, "{id} emit.type");
2862            assert!(
2863                m.check.is_none() && m.inventory.is_none(),
2864                "{id}: emit jobs must not pair with check/inventory"
2865            );
2866        }
2867    }
2868
2869    /// The `inventory:` snapshot jobs under `configs/jobs/` project
2870    /// facts into `inventory_facts` + exploded tables. `include_str!`
2871    /// pins them at compile time so a breaking edit (bad explode
2872    /// schema, a YAML typo in the PowerShell block, an `inventory:`
2873    /// accidentally paired with `emit:`) fails `cargo test` rather
2874    /// than the projector at deploy. Each must carry an `inventory:`
2875    /// block and NO emit (validate() rejects the pairing).
2876    #[test]
2877    fn example_inventory_job_yamls_parse_and_validate() {
2878        let jobs = [
2879            (
2880                "inventory-hw",
2881                include_str!("../../../configs/jobs/inventory-hw.yaml"),
2882            ),
2883            (
2884                "inventory-sw",
2885                include_str!("../../../configs/jobs/inventory-sw.yaml"),
2886            ),
2887            (
2888                "inventory-driver",
2889                include_str!("../../../configs/jobs/inventory-driver.yaml"),
2890            ),
2891        ];
2892        for (id, yaml) in jobs {
2893            let m: Manifest =
2894                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
2895            m.validate()
2896                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
2897            assert_eq!(m.id, id, "{id} id mismatch");
2898            assert!(m.inventory.is_some(), "{id} must carry an inventory: block");
2899            assert!(m.emit.is_none(), "{id}: inventory jobs must not set emit:");
2900        }
2901    }
2902
2903    #[test]
2904    fn example_check_schedule_yamls_parse_and_validate() {
2905        let schedules = [
2906            (
2907                "check-bitlocker",
2908                include_str!("../../../configs/schedules/check-bitlocker.yaml"),
2909            ),
2910            (
2911                "check-av-signature",
2912                include_str!("../../../configs/schedules/check-av-signature.yaml"),
2913            ),
2914            (
2915                "check-cert-expiry",
2916                include_str!("../../../configs/schedules/check-cert-expiry.yaml"),
2917            ),
2918            (
2919                "check-disk-space",
2920                include_str!("../../../configs/schedules/check-disk-space.yaml"),
2921            ),
2922            (
2923                "check-pending-reboot",
2924                include_str!("../../../configs/schedules/check-pending-reboot.yaml"),
2925            ),
2926            (
2927                "check-defender-rtp",
2928                include_str!("../../../configs/schedules/check-defender-rtp.yaml"),
2929            ),
2930            (
2931                "check-firewall",
2932                include_str!("../../../configs/schedules/check-firewall.yaml"),
2933            ),
2934        ];
2935        for (name, yaml) in schedules {
2936            let s: Schedule =
2937                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
2938            s.validate()
2939                .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
2940            assert_eq!(s.job_id, name, "{name} schedule must reference its job");
2941        }
2942    }
2943
2944    /// Inventory schedule wrappers (`per_pc` cadence) must stay valid
2945    /// alongside the schedule schema. `include_str!` pins them so a
2946    /// breaking edit fails `cargo test`, not `kanade schedule create`.
2947    #[test]
2948    fn example_inventory_schedule_yamls_parse_and_validate() {
2949        let schedules = [
2950            (
2951                "inventory-hw",
2952                include_str!("../../../configs/schedules/inventory-hw.yaml"),
2953            ),
2954            (
2955                "inventory-sw",
2956                include_str!("../../../configs/schedules/inventory-sw.yaml"),
2957            ),
2958            (
2959                "inventory-driver",
2960                include_str!("../../../configs/schedules/inventory-driver.yaml"),
2961            ),
2962        ];
2963        for (name, yaml) in schedules {
2964            let s: Schedule =
2965                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
2966            s.validate()
2967                .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
2968            assert_eq!(s.job_id, name, "{name} schedule must reference its job");
2969        }
2970    }
2971
2972    #[test]
2973    fn target_is_specified_requires_at_least_one_field() {
2974        let empty = Target::default();
2975        assert!(!empty.is_specified());
2976
2977        let with_all = Target {
2978            all: true,
2979            ..Target::default()
2980        };
2981        assert!(with_all.is_specified());
2982
2983        let with_groups = Target {
2984            groups: vec!["canary".into()],
2985            ..Target::default()
2986        };
2987        assert!(with_groups.is_specified());
2988
2989        let with_pcs = Target {
2990            pcs: vec!["pc-01".into()],
2991            ..Target::default()
2992        };
2993        assert!(with_pcs.is_specified());
2994    }
2995
2996    #[test]
2997    fn manifest_deserialises_minimal_yaml() {
2998        // Matches jobs/echo-test.yaml. v0.18: no target/rollout/jitter
2999        // — those live on the schedule / exec request now.
3000        let yaml = r#"
3001id: echo-test
3002version: 0.0.1
3003execute:
3004  shell: powershell
3005  script: "echo 'kanade'"
3006  timeout: 30s
3007"#;
3008        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3009        assert_eq!(m.id, "echo-test");
3010        assert_eq!(m.version, "0.0.1");
3011        assert!(matches!(m.execute.shell, ExecuteShell::Powershell));
3012        assert_eq!(
3013            m.execute.script.as_deref().map(str::trim),
3014            Some("echo 'kanade'")
3015        );
3016        assert!(m.execute.script_file.is_none());
3017        assert!(m.execute.script_object.is_none());
3018        assert_eq!(m.execute.timeout, "30s");
3019        assert!(!m.require_approval);
3020        m.validate()
3021            .expect("inline-script manifest passes validation");
3022    }
3023
3024    #[test]
3025    fn manifest_parses_check_job_and_validates() {
3026        // An operator-defined health check (#290): a `check:` hint +
3027        // a PowerShell script that prints {status, detail}.
3028        let yaml = r#"
3029id: check-bitlocker
3030version: 0.1.0
3031execute:
3032  shell: powershell
3033  run_as: system
3034  timeout: 15s
3035  script: |
3036    [pscustomobject]@{ status = 'ok'; detail = 'all volumes protected' } | ConvertTo-Json -Compress
3037check:
3038  name: bitlocker
3039  troubleshoot: fix-bitlocker
3040"#;
3041        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3042        let check = m.check.as_ref().expect("check hint present");
3043        assert_eq!(check.name, "bitlocker");
3044        assert_eq!(check.troubleshoot.as_deref(), Some("fix-bitlocker"));
3045        // Field names default to the conventional "status" / "detail".
3046        assert_eq!(check.status_field, "status");
3047        assert_eq!(check.detail_field, "detail");
3048        assert!(m.inventory.is_none() && m.emit.is_none());
3049        m.validate().expect("check-only manifest passes validation");
3050    }
3051
3052    #[test]
3053    fn manifest_check_defaults_and_custom_fields() {
3054        // Minimal: only `name`; status/detail fields default.
3055        let m: Manifest = serde_yaml::from_str(
3056            r#"
3057id: check-disk
3058version: 0.1.0
3059execute:
3060  shell: powershell
3061  script: "[pscustomobject]@{ status = 'ok' } | ConvertTo-Json -Compress"
3062  timeout: 10s
3063check:
3064  name: disk_free
3065"#,
3066        )
3067        .expect("parse");
3068        let c = m.check.as_ref().unwrap();
3069        assert_eq!(c.name, "disk_free");
3070        assert_eq!(c.status_field, "status");
3071        assert_eq!(c.detail_field, "detail");
3072        assert!(c.troubleshoot.is_none());
3073        m.validate().expect("validates");
3074
3075        // The operator can point status/detail at any field of their
3076        // free-form inventory object.
3077        let m2: Manifest = serde_yaml::from_str(
3078            r#"
3079id: check-custom
3080version: 0.1.0
3081execute:
3082  shell: powershell
3083  script: "echo x"
3084  timeout: 10s
3085check:
3086  name: patch_level
3087  status_field: compliance
3088  detail_field: summary
3089"#,
3090        )
3091        .expect("parse");
3092        let c2 = m2.check.as_ref().unwrap();
3093        assert_eq!(c2.status_field, "compliance");
3094        assert_eq!(c2.detail_field, "summary");
3095    }
3096
3097    #[test]
3098    fn manifest_allows_check_composed_with_inventory() {
3099        // `check:` + `inventory:` COMPOSE on the same stdout object:
3100        // status/detail → Health tab, the rest → SPA projection +
3101        // explode sub-tables. Must pass validation.
3102        let yaml = r#"
3103id: check-bitlocker-detailed
3104version: 0.1.0
3105execute:
3106  shell: powershell
3107  script: "echo x"
3108  timeout: 10s
3109check:
3110  name: bitlocker
3111inventory:
3112  display:
3113    - { field: status, label: Status }
3114"#;
3115        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3116        assert!(m.check.is_some() && m.inventory.is_some());
3117        m.validate().expect("check + inventory compose");
3118    }
3119
3120    #[test]
3121    fn manifest_parses_collect_job_and_validates() {
3122        // #219: a `collect:` hint + a script that lists files on stdout.
3123        let yaml = r#"
3124id: collect-diagnostics
3125version: 0.1.0
3126execute:
3127  shell: powershell
3128  run_as: system
3129  timeout: 120s
3130  script: |
3131    @{ files = @("$env:KANADE_COLLECT_DIR/system.csv") } | ConvertTo-Json
3132collect:
3133  name: "Full diagnostics"
3134  description: "Event logs + process"
3135  max_size: 50MB
3136"#;
3137        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3138        let c = m.collect.as_ref().expect("collect hint present");
3139        assert_eq!(c.name, "Full diagnostics");
3140        assert_eq!(c.files_field, "files"); // default
3141        assert_eq!(c.max_size_bytes(), 50_000_000);
3142        m.validate().expect("collect-only manifest validates");
3143    }
3144
3145    #[test]
3146    fn manifest_finalize_powershell_validates_and_lowers() {
3147        let yaml = r#"
3148id: collect-fin
3149version: 0.1.0
3150execute:
3151  shell: powershell
3152  timeout: 120s
3153  script: |
3154    @{ files = @() } | ConvertTo-Json
3155collect:
3156  name: "diag"
3157  max_size: 50MB
3158finalize:
3159  shell: powershell
3160  timeout: 30s
3161  run_as: system
3162  script: |
3163    Write-Output "cleanup"
3164"#;
3165        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3166        m.validate().expect("powershell finalize validates");
3167        let lowered = m.finalize.as_ref().expect("finalize present").lower();
3168        assert_eq!(lowered.timeout_secs, 30);
3169        assert!(matches!(lowered.shell, Shell::Powershell));
3170        // #965: default is the one-call-after-all contract.
3171        assert!(!lowered.on_each_bundle);
3172    }
3173
3174    #[test]
3175    fn manifest_finalize_on_each_bundle_validates_with_collect_and_lowers() {
3176        // #965: on_each_bundle + a collect hint is the intended
3177        // combination — validates, and the flag survives lowering.
3178        let yaml = r#"
3179id: collect-fin-each
3180version: 0.1.0
3181execute:
3182  shell: powershell
3183  timeout: 120s
3184  script: |
3185    @{ files = @() } | ConvertTo-Json
3186collect:
3187  name: "diag"
3188  max_size: 50MB
3189finalize:
3190  shell: powershell
3191  on_each_bundle: true
3192  script: |
3193    Write-Output "cleanup"
3194"#;
3195        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3196        m.validate().expect("on_each_bundle + collect validates");
3197        let lowered = m.finalize.as_ref().expect("finalize present").lower();
3198        assert!(lowered.on_each_bundle, "flag survives lowering");
3199    }
3200
3201    #[test]
3202    fn manifest_finalize_on_each_bundle_without_collect_rejected() {
3203        // #965: a non-collect finalize has no bundles to iterate, so
3204        // on_each_bundle is a no-op — reject it at the write boundary so
3205        // the operator is told rather than silently getting nothing.
3206        let yaml = r#"
3207id: fin-each-no-collect
3208version: 0.1.0
3209execute:
3210  shell: powershell
3211  timeout: 120s
3212  script: |
3213    Write-Output "hi"
3214finalize:
3215  shell: powershell
3216  on_each_bundle: true
3217  script: |
3218    Write-Output "cleanup"
3219"#;
3220        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3221        let err = m
3222            .validate()
3223            .expect_err("on_each_bundle without collect rejected");
3224        assert!(err.contains("on_each_bundle"), "got: {err}");
3225        assert!(err.contains("collect"), "got: {err}");
3226    }
3227
3228    #[test]
3229    fn manifest_finalize_rejects_cmd_shell() {
3230        // cmd finalize is an injection risk (the agent injects JSON into
3231        // the hook's env; cmd.exe quoting doesn't nest) — validate must
3232        // reject it.
3233        let yaml = r#"
3234id: collect-fin-cmd
3235version: 0.1.0
3236execute:
3237  shell: powershell
3238  timeout: 120s
3239  script: |
3240    @{ files = @() } | ConvertTo-Json
3241finalize:
3242  shell: cmd
3243  script: |
3244    echo hi
3245"#;
3246        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3247        let err = m.validate().expect_err("cmd finalize rejected");
3248        assert!(err.contains("finalize.shell"), "got: {err}");
3249    }
3250
3251    #[test]
3252    fn manifest_finalize_rejects_empty_script() {
3253        let yaml = r#"
3254id: collect-fin-empty
3255version: 0.1.0
3256execute:
3257  shell: powershell
3258  timeout: 120s
3259  script: |
3260    @{ files = @() } | ConvertTo-Json
3261finalize:
3262  shell: powershell
3263  script: "   "
3264"#;
3265        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3266        let err = m.validate().expect_err("empty finalize script rejected");
3267        assert!(err.contains("finalize.script"), "got: {err}");
3268    }
3269
3270    #[test]
3271    fn manifest_collect_max_size_defaults_when_unset() {
3272        let m: Manifest = serde_yaml::from_str(
3273            r#"
3274id: collect-min
3275version: 0.1.0
3276execute:
3277  shell: powershell
3278  script: "echo x"
3279  timeout: 10s
3280collect:
3281  name: minimal
3282"#,
3283        )
3284        .expect("parse");
3285        let c = m.collect.as_ref().unwrap();
3286        assert!(c.max_size.is_none());
3287        assert_eq!(c.max_size_bytes(), DEFAULT_COLLECT_MAX_SIZE);
3288        m.validate().expect("validates");
3289    }
3290
3291    #[test]
3292    fn manifest_allows_collect_with_client() {
3293        // collect composes with client (client doesn't touch stdout):
3294        // an end user can trigger a collection from the Client App.
3295        let yaml = r#"
3296id: collect-diag-client
3297version: 0.1.0
3298execute:
3299  shell: powershell
3300  script: "echo x"
3301  timeout: 10s
3302collect:
3303  name: diagnostics
3304client:
3305  name: "Send diagnostics"
3306  category: troubleshoot
3307"#;
3308        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3309        assert!(m.collect.is_some() && m.client.is_some());
3310        m.validate().expect("collect + client compose");
3311    }
3312
3313    #[test]
3314    fn manifest_allows_inventory_check_collect_coexistence() {
3315        // #821: the three fenced hints now COMPOSE — each reads its own
3316        // `#KANADE-<KIND>` stdout block, so one job can do all three.
3317        let yaml = r#"
3318id: multi-hint
3319version: 0.1.0
3320execute:
3321  shell: powershell
3322  script: "echo x"
3323  timeout: 10s
3324inventory:
3325  display:
3326    - { field: status, label: Status }
3327check:
3328  name: health
3329collect:
3330  name: diag
3331"#;
3332        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3333        m.validate()
3334            .expect("inventory + check + collect coexist after #821");
3335    }
3336
3337    #[test]
3338    fn manifest_rejects_emit_combined_with_fenced_hints() {
3339        // `emit:` consumes stdout as NDJSON (and blanks it), so it still
3340        // can't share with any fenced hint — inventory, check, OR collect.
3341        for extra in [
3342            "inventory:\n  display:\n    - { field: s, label: S }\n",
3343            "check:\n  name: health\n",
3344            "collect:\n  name: diag\n",
3345        ] {
3346            let yaml = format!(
3347                "id: bad-emit-mix\nversion: 0.1.0\nexecute:\n  shell: powershell\n  \
3348                 script: \"echo x\"\n  timeout: 10s\nemit:\n  type: events\n{extra}"
3349            );
3350            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
3351            let err = m
3352                .validate()
3353                .expect_err("emit + fenced hint must be rejected");
3354            assert!(err.contains("emit"), "error mentions emit: {err}");
3355        }
3356    }
3357
3358    #[test]
3359    fn manifest_rejects_collect_empty_name_and_bad_size() {
3360        let empty_name: Manifest = serde_yaml::from_str(
3361            r#"
3362id: c
3363version: 0.1.0
3364execute: { shell: powershell, script: "echo x", timeout: 10s }
3365collect: { name: "  " }
3366"#,
3367        )
3368        .expect("parse");
3369        assert!(
3370            empty_name.validate().is_err(),
3371            "blank collect.name rejected"
3372        );
3373
3374        let bad_size: Manifest = serde_yaml::from_str(
3375            r#"
3376id: c
3377version: 0.1.0
3378execute: { shell: powershell, script: "echo x", timeout: 10s }
3379collect: { name: diag, max_size: "50 quux" }
3380"#,
3381        )
3382        .expect("parse");
3383        let err = bad_size.validate().expect_err("bad max_size rejected");
3384        assert!(err.contains("max_size"), "error mentions max_size: {err}");
3385    }
3386
3387    #[test]
3388    fn parse_size_bytes_units() {
3389        assert_eq!(parse_size_bytes("1024").unwrap(), 1024);
3390        assert_eq!(parse_size_bytes("1B").unwrap(), 1);
3391        assert_eq!(parse_size_bytes("50MB").unwrap(), 50_000_000);
3392        assert_eq!(parse_size_bytes("500 KB").unwrap(), 500_000);
3393        assert_eq!(parse_size_bytes("1GiB").unwrap(), 1024 * 1024 * 1024);
3394        assert_eq!(parse_size_bytes("2mib").unwrap(), 2 * 1024 * 1024);
3395        assert!(parse_size_bytes("").is_err());
3396        assert!(parse_size_bytes("MB").is_err());
3397        assert!(parse_size_bytes("12 zonks").is_err());
3398    }
3399
3400    #[test]
3401    fn manifest_rejects_check_combined_with_emit() {
3402        // `emit:` stdout is NDJSON (and omitted from the result), so
3403        // it can't pair with `check:` (which needs a single JSON
3404        // object on stdout).
3405        let yaml = r#"
3406id: bad-mix
3407version: 0.1.0
3408execute:
3409  shell: powershell
3410  script: "echo x"
3411  timeout: 10s
3412check:
3413  name: bitlocker
3414emit:
3415  type: events
3416"#;
3417        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3418        let err = m.validate().expect_err("emit + check must fail");
3419        assert!(err.contains("incompatible"), "err: {err}");
3420    }
3421
3422    #[test]
3423    fn manifest_rejects_emit_combined_with_inventory() {
3424        // The other half of the emit-incompatibility condition.
3425        let yaml = r#"
3426id: bad-mix-2
3427version: 0.1.0
3428execute:
3429  shell: powershell
3430  script: "echo x"
3431  timeout: 10s
3432emit:
3433  type: events
3434inventory:
3435  display:
3436    - { field: status, label: Status }
3437"#;
3438        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3439        let err = m.validate().expect_err("emit + inventory must fail");
3440        assert!(err.contains("incompatible"), "err: {err}");
3441    }
3442
3443    #[test]
3444    fn manifest_rejects_empty_check_field_names() {
3445        // Empty name / status_field / detail_field are invisible
3446        // runtime bugs (empty React key, agent reads the wrong field)
3447        // — reject them even though serde supplies non-empty defaults.
3448        let base = |inner: &str| {
3449            format!(
3450                "id: c\nversion: 0.1.0\nexecute:\n  shell: powershell\n  script: \"echo x\"\n  timeout: 10s\ncheck:\n{inner}"
3451            )
3452        };
3453        for inner in [
3454            "  name: \"\"\n",
3455            "  name: ok\n  status_field: \"\"\n",
3456            "  name: ok\n  detail_field: \"   \"\n",
3457            // present-but-blank troubleshoot → broken remediation id.
3458            "  name: ok\n  troubleshoot: \"  \"\n",
3459        ] {
3460            let m: Manifest = serde_yaml::from_str(&base(inner)).expect("parse");
3461            let err = m.validate().expect_err("empty field must fail");
3462            assert!(err.contains("must not be empty"), "err: {err}");
3463        }
3464    }
3465
3466    #[test]
3467    fn check_alert_decodes_with_defaults_and_validates() {
3468        let yaml = r#"
3469id: c
3470version: 0.1.0
3471execute:
3472  shell: powershell
3473  script: "echo x"
3474  timeout: 10s
3475check:
3476  name: bitlocker
3477  alert:
3478    notify_user: true
3479    title: "BitLocker 未準拠"
3480"#;
3481        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3482        m.validate().expect("valid alert");
3483        let alert = m.check.unwrap().alert.unwrap();
3484        // Defaults: on = [fail], priority = warn, body = None.
3485        assert_eq!(alert.on, vec![CheckAlertStatus::Fail]);
3486        assert_eq!(
3487            alert.priority,
3488            crate::ipc::notifications::NotificationPriority::Warn
3489        );
3490        assert!(alert.body.is_none());
3491        assert!(alert.notify_user);
3492    }
3493
3494    #[test]
3495    fn check_alert_validation_rejects_bad_configs() {
3496        let base = |alert: &str| {
3497            format!(
3498                "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}"
3499            )
3500        };
3501        let cases = [
3502            // No recipient.
3503            ("    title: t\n", "notify_user and/or notify_groups"),
3504            // Empty title.
3505            (
3506                "    notify_user: true\n    title: \"  \"\n",
3507                "title must not be empty",
3508            ),
3509            // Empty `on`.
3510            (
3511                "    notify_user: true\n    title: t\n    on: []\n",
3512                "on must list at least one status",
3513            ),
3514            // Blank group name.
3515            (
3516                "    notify_groups: [\"  \"]\n    title: t\n",
3517                "notify_groups must not contain blanks",
3518            ),
3519            // alert requires fleet: true.
3520            (
3521                "    notify_user: true\n    title: t\n  fleet: false\n",
3522                "requires fleet: true",
3523            ),
3524            // email opt-in without a group to address.
3525            (
3526                "    notify_user: true\n    email: true\n    title: t\n",
3527                "email requires notify_groups",
3528            ),
3529        ];
3530        for (alert, want) in cases {
3531            let m: Manifest = serde_yaml::from_str(&base(alert)).expect("parse");
3532            let err = m.validate().expect_err("bad alert must fail");
3533            assert!(err.contains(want), "for {alert:?}: got {err}");
3534        }
3535    }
3536
3537    #[test]
3538    fn manifest_client_absent_by_default() {
3539        // A plain operator job (the overwhelming majority) carries no
3540        // `client:` block, so it never surfaces in the end-user
3541        // catalog.
3542        let yaml = r#"
3543id: echo-test
3544version: 0.0.1
3545execute:
3546  shell: powershell
3547  script: "echo 'kanade'"
3548  timeout: 30s
3549"#;
3550        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3551        assert!(m.client.is_none());
3552        m.validate().expect("operator-only job validates");
3553    }
3554
3555    #[test]
3556    fn manifest_client_parses_and_validates() {
3557        // The Client App "困ったとき" remediation job shape: a
3558        // user-invokable troubleshoot job with the end-user fields the
3559        // KLP `jobs.list` wire needs, grouped under `client:`.
3560        let yaml = r#"
3561id: fix-teams-cache
3562version: 1.0.0
3563execute:
3564  shell: powershell
3565  script: "echo clearing"
3566  timeout: 60s
3567client:
3568  name: "Teams のキャッシュをクリア"
3569  description: "Teams が重いときに試してください"
3570  category: troubleshoot
3571  icon: brush-cleaning
3572"#;
3573        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3574        let c = m.client.as_ref().expect("client block present");
3575        assert_eq!(c.name, "Teams のキャッシュをクリア");
3576        assert_eq!(
3577            c.description.as_deref(),
3578            Some("Teams が重いときに試してください")
3579        );
3580        assert_eq!(c.category, "troubleshoot");
3581        assert_eq!(c.icon.as_deref(), Some("brush-cleaning"));
3582        m.validate().expect("user-invokable job validates");
3583    }
3584
3585    #[test]
3586    fn manifest_client_minimal_only_name_and_category() {
3587        // description + icon are optional; name + category are the
3588        // serde-required minimum.
3589        let yaml = r#"
3590id: install-slack
3591version: 1.0.0
3592execute:
3593  shell: powershell
3594  script: "echo install"
3595  timeout: 600s
3596client:
3597  name: Slack
3598  category: catalog
3599"#;
3600        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3601        let c = m.client.as_ref().expect("client present");
3602        assert_eq!(c.category, "catalog");
3603        assert!(c.description.is_none() && c.icon.is_none());
3604        m.validate().expect("minimal client validates");
3605    }
3606
3607    #[test]
3608    fn manifest_client_rejects_blank_name() {
3609        // serde guarantees `name`/`category` are present; the one gap
3610        // is a present-but-blank name → empty catalog row title.
3611        let yaml = r#"
3612id: j
3613version: 1.0.0
3614execute:
3615  shell: powershell
3616  script: "echo x"
3617  timeout: 30s
3618client:
3619  name: "   "
3620  category: catalog
3621"#;
3622        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3623        let err = m.validate().expect_err("blank name must fail");
3624        assert!(err.contains("client.name"), "err: {err}");
3625    }
3626
3627    #[test]
3628    fn manifest_client_rejects_blank_optional_fields() {
3629        // description / icon are optional, but a present-but-blank
3630        // value is a bug (empty subtitle / dangling icon name) — reject
3631        // it, mirroring the check: block's troubleshoot guard.
3632        for (field, line) in [
3633            ("client.description", "  description: \"  \"\n"),
3634            ("client.icon", "  icon: \"\"\n"),
3635            // #792: the new category tab-metadata fields get the same
3636            // present-but-blank guard.
3637            ("client.category_label", "  category_label: \"  \"\n"),
3638            ("client.category_icon", "  category_icon: \"\"\n"),
3639        ] {
3640            let yaml = format!(
3641                "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}"
3642            );
3643            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
3644            let err = m.validate().expect_err("blank optional field must fail");
3645            assert!(err.contains(field), "expected {field} in err: {err}");
3646        }
3647    }
3648
3649    #[test]
3650    fn manifest_client_rejects_blank_category() {
3651        // #792: category is a free-form key now; serde keeps it required,
3652        // but a present-but-blank value would group the job under an empty
3653        // tab — validate() must reject it.
3654        let yaml = r#"
3655id: j
3656version: 1.0.0
3657execute:
3658  shell: powershell
3659  script: "echo x"
3660  timeout: 30s
3661client:
3662  name: "A job"
3663  category: "   "
3664"#;
3665        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3666        let err = m.validate().expect_err("blank category must fail");
3667        assert!(err.contains("client.category"), "err: {err}");
3668    }
3669
3670    #[test]
3671    fn target_matches_pc_group_and_all() {
3672        // #816: pc match, group match, all, and the no-match case.
3673        let by_pc = Target {
3674            pcs: vec!["PC1".into()],
3675            ..Default::default()
3676        };
3677        assert!(by_pc.matches("PC1", &[]));
3678        assert!(!by_pc.matches("PC2", &["g1".into()]));
3679
3680        let by_group = Target {
3681            groups: vec!["g1".into()],
3682            ..Default::default()
3683        };
3684        assert!(by_group.matches("PC2", &["g1".into()]));
3685        assert!(!by_group.matches("PC2", &["g2".into()]));
3686
3687        let all = Target {
3688            all: true,
3689            ..Default::default()
3690        };
3691        assert!(all.matches("anyPC", &[]));
3692    }
3693
3694    #[test]
3695    fn manifest_client_rejects_empty_visible_to() {
3696        // #816: a present-but-empty visible_to (no all/groups/pcs) would
3697        // hide the job from everyone — validate() must reject it.
3698        let yaml = r#"
3699id: j
3700version: 1.0.0
3701execute:
3702  shell: powershell
3703  script: "echo x"
3704  timeout: 30s
3705client:
3706  name: "A job"
3707  category: troubleshoot
3708  visible_to: {}
3709"#;
3710        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3711        let err = m.validate().expect_err("empty visible_to must fail");
3712        assert!(err.contains("client.visible_to"), "err: {err}");
3713    }
3714
3715    #[test]
3716    fn manifest_client_accepts_visible_to_groups() {
3717        let yaml = r#"
3718id: j
3719version: 1.0.0
3720execute:
3721  shell: powershell
3722  script: "echo x"
3723  timeout: 30s
3724client:
3725  name: "A job"
3726  category: settings
3727  visible_to:
3728    groups: [wifi-affected]
3729"#;
3730        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3731        m.validate().expect("visible_to with a group validates");
3732        let vt = m.client.unwrap().visible_to.unwrap();
3733        assert_eq!(vt.groups, vec!["wifi-affected".to_string()]);
3734    }
3735
3736    #[test]
3737    fn manifest_client_show_when_accepts_scalar_and_seq() {
3738        use crate::ipc::state::CheckStatus;
3739        // `is:` accepts a single status (author ergonomics) ...
3740        let scalar = r#"
3741id: office-update
3742version: 1.0.0
3743execute:
3744  shell: powershell
3745  script: "echo x"
3746  timeout: 30s
3747client:
3748  name: "Office を最新に更新"
3749  category: software_update
3750  show_when:
3751    check: office-up-to-date
3752    is: fail
3753"#;
3754        let m: Manifest = serde_yaml::from_str(scalar).expect("parse scalar");
3755        m.validate().expect("scalar show_when validates");
3756        let sw = m.client.unwrap().show_when.unwrap();
3757        assert_eq!(sw.check, "office-up-to-date");
3758        assert_eq!(sw.is, vec![CheckStatus::Fail]);
3759
3760        // ... and a list (e.g. fail-open on a not-yet-run check).
3761        let seq = scalar.replace("is: fail", "is: [fail, unknown]");
3762        let m: Manifest = serde_yaml::from_str(&seq).expect("parse seq");
3763        m.validate().expect("seq show_when validates");
3764        assert_eq!(
3765            m.client.unwrap().show_when.unwrap().is,
3766            vec![CheckStatus::Fail, CheckStatus::Unknown]
3767        );
3768    }
3769
3770    #[test]
3771    fn manifest_client_show_when_rejects_empty() {
3772        // A malformed check slug (here: internal spaces — a typo that could
3773        // never match a real check name) or an empty status list would
3774        // silently hide the job forever — validate() must reject both.
3775        let bad_check = r#"
3776id: j
3777version: 1.0.0
3778execute:
3779  shell: powershell
3780  script: "echo x"
3781  timeout: 30s
3782client:
3783  name: "A job"
3784  category: software_update
3785  show_when:
3786    check: "office up to date"
3787    is: fail
3788"#;
3789        let m: Manifest = serde_yaml::from_str(bad_check).expect("parse");
3790        let err = m.validate().expect_err("malformed check slug must fail");
3791        assert!(err.contains("client.show_when.check"), "err: {err}");
3792
3793        let empty_is = r#"
3794id: j
3795version: 1.0.0
3796execute:
3797  shell: powershell
3798  script: "echo x"
3799  timeout: 30s
3800client:
3801  name: "A job"
3802  category: software_update
3803  show_when:
3804    check: office-up-to-date
3805    is: []
3806"#;
3807        let m: Manifest = serde_yaml::from_str(empty_is).expect("parse");
3808        let err = m.validate().expect_err("empty is[] must fail");
3809        assert!(err.contains("client.show_when.is"), "err: {err}");
3810    }
3811
3812    #[test]
3813    fn manifest_client_confirm_accepts_bool_and_struct() {
3814        // `confirm:` deserializes from a bare bool or a struct. A bool
3815        // sets `enabled` (message stays default); a struct carries a custom
3816        // message and defaults `enabled` to true.
3817        let base = r#"
3818id: j
3819version: 1.0.0
3820execute:
3821  shell: powershell
3822  script: "echo x"
3823  timeout: 30s
3824client:
3825  name: "Wi-Fi 省電力を切る"
3826  category: settings
3827"#;
3828        // `confirm: false` ⇒ dialog suppressed.
3829        let off: Manifest =
3830            serde_yaml::from_str(&format!("{base}  confirm: false\n")).expect("parse false");
3831        off.validate().expect("confirm: false validates");
3832        let c = off.client.unwrap().confirm.unwrap();
3833        assert!(!c.enabled);
3834        assert!(c.message.is_none());
3835
3836        // `confirm: true` ⇒ same as omitting (dialog shown, default message).
3837        let on: Manifest =
3838            serde_yaml::from_str(&format!("{base}  confirm: true\n")).expect("parse true");
3839        let c = on.client.unwrap().confirm.unwrap();
3840        assert!(c.enabled);
3841        assert!(c.message.is_none());
3842
3843        // Struct with only a message ⇒ enabled defaults true, custom text.
3844        let msg: Manifest = serde_yaml::from_str(&format!(
3845            "{base}  confirm:\n    message: \"再インストールには数分かかります。よろしいですか?\"\n"
3846        ))
3847        .expect("parse struct");
3848        msg.validate().expect("confirm message validates");
3849        let c = msg.client.unwrap().confirm.unwrap();
3850        assert!(c.enabled);
3851        assert_eq!(
3852            c.message.as_deref(),
3853            Some("再インストールには数分かかります。よろしいですか?")
3854        );
3855
3856        // Absent ⇒ None (historical default handled by the client).
3857        let none: Manifest = serde_yaml::from_str(base).expect("parse none");
3858        assert!(none.client.unwrap().confirm.is_none());
3859
3860        // Explicit `confirm: null` is schema-valid (the field is Option) and
3861        // must map to None, not a parse error (Gemini #960).
3862        let null: Manifest =
3863            serde_yaml::from_str(&format!("{base}  confirm: null\n")).expect("parse null");
3864        assert!(null.client.unwrap().confirm.is_none());
3865    }
3866
3867    #[test]
3868    fn manifest_client_confirm_rejects_blank_message() {
3869        // A present-but-blank custom message would render an empty dialog
3870        // title — validate() must reject it, like the other display fields.
3871        let yaml = r#"
3872id: j
3873version: 1.0.0
3874execute:
3875  shell: powershell
3876  script: "echo x"
3877  timeout: 30s
3878client:
3879  name: "A job"
3880  category: settings
3881  confirm:
3882    message: "   "
3883"#;
3884        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3885        let err = m.validate().expect_err("blank confirm.message must fail");
3886        assert!(err.contains("client.confirm.message"), "err: {err}");
3887    }
3888
3889    #[test]
3890    fn manifest_client_requires_category_at_parse() {
3891        // A `client:` block missing `category` is a hard parse error
3892        // (serde required field) — no manual validate() needed.
3893        let yaml = r#"
3894id: j
3895version: 1.0.0
3896execute:
3897  shell: powershell
3898  script: "echo x"
3899  timeout: 30s
3900client:
3901  name: "A job"
3902"#;
3903        let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
3904        assert!(
3905            r.is_err(),
3906            "missing category must be a parse error, got {r:?}"
3907        );
3908    }
3909
3910    #[test]
3911    fn manifest_client_rejects_unknown_field() {
3912        // #492: the strict create boundary catches a fat-fingered
3913        // `displayname:` (with its path) instead of silently
3914        // dropping it; the tolerant read path accepts it.
3915        let yaml = r#"
3916id: j
3917version: 1.0.0
3918execute:
3919  shell: powershell
3920  script: "echo x"
3921  timeout: 30s
3922client:
3923  name: "A job"
3924  category: catalog
3925  displayname: oops
3926"#;
3927        let r = crate::strict::from_yaml_str::<Manifest>(yaml);
3928        let err = r.expect_err("unknown client field must be rejected at the write boundary");
3929        // serde_ignored renders the Option layer as `?`:
3930        // `client.?.displayname`. Assert on the leaf key.
3931        assert!(err.contains("displayname"), "{err}");
3932        // The READ path tolerates the same payload (gradual-upgrade
3933        // contract: an old agent must accept a newer writer's field).
3934        let m: Manifest = serde_yaml::from_str(yaml).expect("tolerant read");
3935        assert_eq!(m.client.as_ref().map(|c| c.name.as_str()), Some("A job"));
3936    }
3937
3938    #[test]
3939    fn manifest_tags_default_empty() {
3940        // The overwhelming majority of jobs carry no tags; the field
3941        // must default to an empty Vec (not fail to parse) and skip
3942        // serialisation so old readers never see the key.
3943        let yaml = r#"
3944id: echo-test
3945version: 0.0.1
3946execute:
3947  shell: powershell
3948  script: "echo 'kanade'"
3949  timeout: 30s
3950"#;
3951        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3952        assert!(m.tags.is_empty());
3953        m.validate().expect("tag-less job validates");
3954        // skip_serializing_if = empty ⇒ the key is absent from JSON.
3955        let json = serde_json::to_string(&m).expect("serialize");
3956        assert!(
3957            !json.contains("tags"),
3958            "empty tags must not serialise: {json}"
3959        );
3960    }
3961
3962    #[test]
3963    fn manifest_parses_and_validates_tags() {
3964        let yaml = r#"
3965id: check-bitlocker
3966version: 0.1.0
3967execute:
3968  shell: powershell
3969  script: "echo x"
3970  timeout: 30s
3971tags: [security, windows, health-check]
3972"#;
3973        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3974        assert_eq!(m.tags, vec!["security", "windows", "health-check"]);
3975        m.validate().expect("tagged job validates");
3976        // Round-trips through JSON (the wire format the SPA reads).
3977        let json = serde_json::to_string(&m).expect("serialize");
3978        assert!(json.contains("\"tags\""), "non-empty tags must serialise");
3979    }
3980
3981    #[test]
3982    fn manifest_rejects_blank_tag() {
3983        // A whitespace-only tag renders an empty filter chip — reject
3984        // it at the write boundary like the other blank display fields.
3985        let yaml = r#"
3986id: j
3987version: 0.1.0
3988execute:
3989  shell: powershell
3990  script: "echo x"
3991  timeout: 30s
3992tags: [ok, "   "]
3993"#;
3994        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3995        let err = m.validate().expect_err("blank tag must fail");
3996        assert!(err.contains("tags must not contain empty"), "err: {err}");
3997    }
3998
3999    #[test]
4000    fn validate_rejects_unknown_tier_and_accepts_known() {
4001        let base =
4002            "id: t\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: x\n  timeout: 30s\n";
4003        // A typo / future tier decodes to Tier::Unknown (#[serde(other)]) and
4004        // must FAIL CLOSED — never fall back to unrestricted endpoint dispatch.
4005        let bogus: Manifest =
4006            serde_yaml::from_str(&format!("{base}tier: controler\n")).expect("parse");
4007        let err = bogus.validate().expect_err("unknown tier must be rejected");
4008        assert!(err.contains("tier"), "err: {err}");
4009        // The two known tiers pass.
4010        serde_yaml::from_str::<Manifest>(&format!("{base}tier: controller\n"))
4011            .unwrap()
4012            .validate()
4013            .expect("controller tier is valid");
4014        serde_yaml::from_str::<Manifest>(&format!("{base}tier: endpoint\n"))
4015            .unwrap()
4016            .validate()
4017            .expect("endpoint tier is valid");
4018    }
4019
4020    #[test]
4021    fn feed_payload_extracts_fenced_block() {
4022        let stdout = "fetched 1500 KEV entries\n\
4023            #KANADE-FEED-BEGIN\n\
4024            {\"vulnerabilities\": []}\n\
4025            #KANADE-FEED-END\n";
4026        assert_eq!(feed_payload(stdout), "{\"vulnerabilities\": []}");
4027    }
4028
4029    #[test]
4030    fn validate_feed_rules() {
4031        let base =
4032            "id: f\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: x\n  timeout: 30s\n";
4033        // A well-formed feed (controller implied; no explicit tier) passes.
4034        serde_yaml::from_str::<Manifest>(&format!(
4035            "{base}feed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4036        ))
4037        .unwrap()
4038        .validate()
4039        .expect("a well-formed feed is valid");
4040
4041        // Empty primary_key is rejected (no item_id → every row dropped).
4042        let err = serde_yaml::from_str::<Manifest>(&format!(
4043            "{base}feed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: []\n"
4044        ))
4045        .unwrap()
4046        .validate()
4047        .expect_err("empty primary_key must be rejected");
4048        assert!(err.contains("primary_key"), "err: {err}");
4049
4050        // A duplicate feed id clobbers a partition — rejected.
4051        let err = serde_yaml::from_str::<Manifest>(&format!(
4052            "{base}feed:\n  - id: dup\n    field: a\n    primary_key: [k]\n  - id: dup\n    field: b\n    primary_key: [k]\n"
4053        ))
4054        .unwrap()
4055        .validate()
4056        .expect_err("duplicate feed id must be rejected");
4057        assert!(err.contains("more than once"), "err: {err}");
4058
4059        // `feed:` + explicit `tier: endpoint` is contradictory — rejected.
4060        let err = serde_yaml::from_str::<Manifest>(&format!(
4061            "{base}tier: endpoint\nfeed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4062        ))
4063        .unwrap()
4064        .validate()
4065        .expect_err("feed + tier: endpoint must be rejected");
4066        assert!(err.contains("controller tier"), "err: {err}");
4067
4068        // `feed:` + `emit:` is incompatible — emit consumes stdout whole, so
4069        // the feed's fence never reaches the projector.
4070        let err = serde_yaml::from_str::<Manifest>(&format!(
4071            "{base}emit:\n  type: events\nfeed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4072        ))
4073        .unwrap()
4074        .validate()
4075        .expect_err("feed + emit must be rejected");
4076        assert!(err.contains("emit"), "err: {err}");
4077    }
4078
4079    // #720 — wrap an `aggregate:` YAML block (already indented as a
4080    // top-level key body) into an otherwise-minimal valid manifest.
4081    fn manifest_with_aggregate(aggregate_block: &str) -> Manifest {
4082        let yaml = format!(
4083            "id: t\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: echo hi\n  timeout: 30s\n{aggregate_block}"
4084        );
4085        serde_yaml::from_str(&yaml).expect("parse aggregate manifest")
4086    }
4087
4088    #[test]
4089    fn aggregate_accepts_full_valid_spec() {
4090        // count+group_by+exclude+sample_minutes, ratio+bool_path,
4091        // timeline+time_bucket, fleet ranking via group_by: pc_id, and a
4092        // bare total stat — alongside emit (composes with every hint).
4093        let m = manifest_with_aggregate(
4094            "emit:\n  type: events\naggregate:\n\
4095             - { dashboard: Utilization, title: Top apps, kind: app_sample, agg: count, group_by: foreground.app, sample_minutes: 2, exclude: [LockApp], render: bar }\n\
4096             - { dashboard: Utilization, title: Active ratio, kind: presence, agg: ratio, bool_path: active, sample_minutes: 5, render: gauge }\n\
4097             - { dashboard: Utilization, title: By hour, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: timeline }\n\
4098             - { dashboard: Reliability, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
4099             - { dashboard: Reliability, title: Total crashes, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
4100        );
4101        m.validate().expect("valid aggregate spec");
4102    }
4103
4104    #[test]
4105    fn aggregate_rejects_empty_list() {
4106        let m = manifest_with_aggregate("aggregate: []\n");
4107        let err = m.validate().expect_err("empty list must fail");
4108        assert!(err.contains("at least one widget"), "err: {err}");
4109    }
4110
4111    #[test]
4112    fn aggregate_rejects_ratio_without_bool_path() {
4113        let m = manifest_with_aggregate(
4114            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, render: gauge }\n",
4115        );
4116        let err = m.validate().expect_err("ratio needs bool_path");
4117        assert!(err.contains("agg=ratio requires `bool_path`"), "err: {err}");
4118    }
4119
4120    #[test]
4121    fn aggregate_rejects_sum_without_value_path() {
4122        let m = manifest_with_aggregate(
4123            "aggregate:\n- { dashboard: D, title: T, kind: io, agg: sum, render: bar }\n",
4124        );
4125        let err = m.validate().expect_err("sum needs value_path");
4126        assert!(err.contains("agg=sum requires `value_path`"), "err: {err}");
4127    }
4128
4129    #[test]
4130    fn aggregate_rejects_pc_id_group_without_fleet() {
4131        let m = manifest_with_aggregate(
4132            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: count, group_by: pc_id, render: bar }\n",
4133        );
4134        let err = m.validate().expect_err("pc_id grouping needs fleet");
4135        assert!(
4136            err.contains("pc_id is only valid with scope: fleet"),
4137            "err: {err}"
4138        );
4139    }
4140
4141    #[test]
4142    fn aggregate_rejects_transform_with_pc_id_group() {
4143        let m = manifest_with_aggregate(
4144            "aggregate:\n- { dashboard: D, title: T, scope: fleet, kind: web_visit, agg: count, group_by: pc_id, transform: host, render: bar }\n",
4145        );
4146        let err = m
4147            .validate()
4148            .expect_err("transform on pc_id grouping must fail");
4149        assert!(
4150            err.contains("transform is not valid with group_by: pc_id"),
4151            "err: {err}"
4152        );
4153    }
4154
4155    #[test]
4156    fn aggregate_rejects_timeline_without_bucket() {
4157        let m = manifest_with_aggregate(
4158            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, bool_path: active, render: timeline }\n",
4159        );
4160        let err = m.validate().expect_err("timeline needs a bucket");
4161        assert!(
4162            err.contains("render=timeline requires `time_bucket`"),
4163            "err: {err}"
4164        );
4165    }
4166
4167    #[test]
4168    fn aggregate_rejects_bucket_on_non_timeline() {
4169        let m = manifest_with_aggregate(
4170            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: gauge }\n",
4171        );
4172        let err = m.validate().expect_err("bucket only on timeline");
4173        assert!(
4174            err.contains("time_bucket is only valid with render: timeline"),
4175            "err: {err}"
4176        );
4177    }
4178
4179    #[test]
4180    fn aggregate_rejects_unsafe_json_path() {
4181        // A path with characters outside [A-Za-z0-9_.] could break out of
4182        // the `'$.' || ?` bind — reject at create time.
4183        let m = manifest_with_aggregate(
4184            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: \"foo'; DROP\", render: bar }\n",
4185        );
4186        let err = m.validate().expect_err("unsafe path must fail");
4187        assert!(err.contains("dotted JSON path"), "err: {err}");
4188    }
4189
4190    #[test]
4191    fn aggregate_rejects_blank_title() {
4192        let m = manifest_with_aggregate(
4193            "aggregate:\n- { dashboard: D, title: \"  \", kind: k, agg: count, render: stat }\n",
4194        );
4195        let err = m.validate().expect_err("blank title must fail");
4196        assert!(err.contains("title must not be empty"), "err: {err}");
4197    }
4198
4199    #[test]
4200    fn aggregate_rejects_blank_kind() {
4201        let m = manifest_with_aggregate(
4202            "aggregate:\n- { dashboard: D, title: T, kind: \" \", agg: count, render: stat }\n",
4203        );
4204        let err = m.validate().expect_err("blank kind must fail");
4205        assert!(err.contains("kind must not be empty"), "err: {err}");
4206    }
4207
4208    #[test]
4209    fn aggregate_rejects_blank_source_when_set() {
4210        let m = manifest_with_aggregate(
4211            "aggregate:\n- { dashboard: D, title: T, kind: k, source: \"\", agg: count, render: stat }\n",
4212        );
4213        let err = m.validate().expect_err("blank source must fail");
4214        assert!(
4215            err.contains("source must not be empty when set"),
4216            "err: {err}"
4217        );
4218    }
4219
4220    #[test]
4221    fn aggregate_accepts_description_and_rejects_blank() {
4222        let ok = manifest_with_aggregate(
4223            "aggregate:\n- { dashboard: D, title: T, description: \"samples x 2 min\", kind: k, agg: count, render: stat }\n",
4224        );
4225        ok.validate()
4226            .expect("description is a valid optional field");
4227        assert_eq!(
4228            ok.aggregate.as_ref().unwrap()[0].description.as_deref(),
4229            Some("samples x 2 min")
4230        );
4231        let bad = manifest_with_aggregate(
4232            "aggregate:\n- { dashboard: D, title: T, description: \"  \", kind: k, agg: count, render: stat }\n",
4233        );
4234        let err = bad.validate().expect_err("blank description must fail");
4235        assert!(
4236            err.contains("description must not be empty when set"),
4237            "err: {err}"
4238        );
4239    }
4240
4241    #[test]
4242    fn aggregate_rejects_count_with_value_path() {
4243        let m = manifest_with_aggregate(
4244            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, value_path: bytes, render: stat }\n",
4245        );
4246        let err = m.validate().expect_err("count must not use value_path");
4247        assert!(
4248            err.contains("agg=count does not use `value_path`"),
4249            "err: {err}"
4250        );
4251    }
4252
4253    #[test]
4254    fn aggregate_rejects_ratio_with_value_path() {
4255        let m = manifest_with_aggregate(
4256            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: ratio, bool_path: active, value_path: bytes, render: gauge }\n",
4257        );
4258        let err = m.validate().expect_err("ratio must not use value_path");
4259        assert!(
4260            err.contains("agg=ratio does not use `value_path`"),
4261            "err: {err}"
4262        );
4263    }
4264
4265    #[test]
4266    fn aggregate_rejects_gauge_without_ratio() {
4267        let m = manifest_with_aggregate(
4268            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, render: gauge }\n",
4269        );
4270        let err = m.validate().expect_err("gauge needs ratio");
4271        assert!(
4272            err.contains("render=gauge is only valid with agg: ratio"),
4273            "err: {err}"
4274        );
4275    }
4276
4277    #[test]
4278    fn aggregate_rejects_limit_without_group_by() {
4279        let m = manifest_with_aggregate(
4280            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, limit: 5, render: stat }\n",
4281        );
4282        let err = m.validate().expect_err("limit needs group_by");
4283        assert!(err.contains("limit requires `group_by`"), "err: {err}");
4284    }
4285
4286    #[test]
4287    fn aggregate_rejects_exclude_without_group_by() {
4288        let m = manifest_with_aggregate(
4289            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, exclude: [x], render: stat }\n",
4290        );
4291        let err = m.validate().expect_err("exclude needs group_by");
4292        assert!(err.contains("exclude requires `group_by`"), "err: {err}");
4293    }
4294
4295    #[test]
4296    fn aggregate_rejects_zero_limit_and_zero_sample_minutes() {
4297        let m = manifest_with_aggregate(
4298            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, limit: 0, render: bar }\n",
4299        );
4300        assert!(m.validate().unwrap_err().contains("limit must be > 0"));
4301        let m = manifest_with_aggregate(
4302            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, sample_minutes: 0, render: bar }\n",
4303        );
4304        assert!(
4305            m.validate()
4306                .unwrap_err()
4307                .contains("sample_minutes must be > 0")
4308        );
4309    }
4310
4311    #[test]
4312    fn aggregate_rejects_empty_exclude_entry() {
4313        let m = manifest_with_aggregate(
4314            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, exclude: [\"  \"], render: bar }\n",
4315        );
4316        let err = m.validate().expect_err("blank exclude entry must fail");
4317        assert!(
4318            err.contains("exclude must not contain empty entries"),
4319            "err: {err}"
4320        );
4321    }
4322
4323    #[test]
4324    fn aggregate_rejects_malformed_dotted_paths() {
4325        for bad in [".foo", "foo.", "foo..bar", "."] {
4326            let m = manifest_with_aggregate(&format!(
4327                "aggregate:\n- {{ dashboard: D, title: T, kind: k, agg: count, group_by: \"{bad}\", render: bar }}\n"
4328            ));
4329            let err = m.validate().expect_err("malformed path must fail");
4330            assert!(err.contains("dotted JSON path"), "path {bad}: {err}");
4331        }
4332    }
4333
4334    #[test]
4335    fn aggregate_rejects_unknown_enum_value() {
4336        // An unrecognised render string deserialises to the #492 Unknown
4337        // catch-all (so old readers don't choke); validate() rejects it as
4338        // a typo at create time.
4339        let m = manifest_with_aggregate(
4340            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, render: heatmap }\n",
4341        );
4342        let err = m.validate().expect_err("unknown render must fail");
4343        assert!(err.contains("render is not a known value"), "err: {err}");
4344    }
4345
4346    #[test]
4347    fn aggregate_accepts_order_field() {
4348        let m = manifest_with_aggregate(
4349            "aggregate:\n- { dashboard: D, title: T, order: -5, kind: k, agg: count, render: stat }\n",
4350        );
4351        m.validate().expect("order is a valid optional field");
4352        let w = &m.aggregate.as_ref().unwrap()[0];
4353        assert_eq!(w.order, Some(-5));
4354    }
4355
4356    #[test]
4357    fn aggregate_accepts_minimal_op_timeline() {
4358        // op_timeline needs no kind/agg — it reconstructs a fixed multi-kind
4359        // swimlane. A bare per-PC spec is valid, and `kind`/`agg` stay None.
4360        let m = manifest_with_aggregate(
4361            "aggregate:\n- { dashboard: Uptime, title: Operational state, scope: pc, render: op_timeline }\n",
4362        );
4363        m.validate().expect("minimal op_timeline is valid");
4364        let w = &m.aggregate.as_ref().unwrap()[0];
4365        assert_eq!(w.render, AggregateRender::OpTimeline);
4366        assert!(w.kind.is_none());
4367        assert!(w.agg.is_none());
4368    }
4369
4370    #[test]
4371    fn aggregate_rejects_op_timeline_with_fleet_scope() {
4372        let m = manifest_with_aggregate(
4373            "aggregate:\n- { dashboard: Uptime, title: T, scope: fleet, render: op_timeline }\n",
4374        );
4375        let err = m.validate().expect_err("op_timeline must be per-PC");
4376        assert!(
4377            err.contains("render=op_timeline requires scope: pc"),
4378            "err: {err}"
4379        );
4380    }
4381
4382    #[test]
4383    fn aggregate_rejects_op_timeline_with_aggregation_fields() {
4384        // Each aggregation knob the operator might paste in is rejected
4385        // (rather than silently ignored), pointing at the field to delete.
4386        for (block, field) in [
4387            ("kind: boot", "kind"),
4388            ("agg: count", "agg"),
4389            ("source: winlog:Security", "source"),
4390            ("group_by: pc_id", "group_by"),
4391            ("bool_path: active", "bool_path"),
4392            ("time_bucket: hour", "time_bucket"),
4393            ("limit: 5", "limit"),
4394        ] {
4395            let m = manifest_with_aggregate(&format!(
4396                "aggregate:\n- {{ dashboard: Uptime, title: T, scope: pc, {block}, render: op_timeline }}\n"
4397            ));
4398            let err = m
4399                .validate()
4400                .expect_err(&format!("op_timeline must reject {field}"));
4401            assert!(
4402                err.contains(&format!("render=op_timeline does not use `{field}`")),
4403                "field {field}: {err}"
4404            );
4405        }
4406    }
4407
4408    // ── #743 View resource ───────────────────────────────────────────
4409    fn view_from(yaml_body: &str) -> View {
4410        serde_yaml::from_str(&format!("id: v1\n{yaml_body}")).expect("parse view")
4411    }
4412
4413    #[test]
4414    fn view_accepts_valid_widgets() {
4415        let v = view_from(
4416            "widgets:\n\
4417             - { dashboard: Reliability, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
4418             - { dashboard: Reliability, title: Total, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
4419        );
4420        v.validate().expect("valid view");
4421    }
4422
4423    #[test]
4424    fn view_rejects_empty_widgets() {
4425        let v = view_from("widgets: []\n");
4426        let err = v.validate().expect_err("empty widgets must fail");
4427        assert!(err.contains("at least one widget"), "err: {err}");
4428    }
4429
4430    #[test]
4431    fn view_rejects_blank_id() {
4432        let v: View = serde_yaml::from_str(
4433            "id: \"  \"\nwidgets:\n- { dashboard: D, title: T, kind: k, agg: count, render: stat }\n",
4434        )
4435        .expect("parse");
4436        let err = v.validate().expect_err("blank id must fail");
4437        assert!(err.contains("view.id must"), "err: {err}");
4438    }
4439
4440    #[test]
4441    fn view_rejects_unsafe_id() {
4442        // A `/` or `..` in the id would break the KV key and the
4443        // `/api/views/{id}` URL segment — reject at create time.
4444        for bad in ["../etc", "a/b", "has space", "x;y"] {
4445            let v: View = serde_yaml::from_str(&format!(
4446                "id: \"{bad}\"\nwidgets:\n- {{ dashboard: D, title: T, kind: k, agg: count, render: stat }}\n",
4447            ))
4448            .expect("parse");
4449            let err = v.validate().expect_err("unsafe id must fail");
4450            assert!(err.contains("[A-Za-z0-9._-]"), "id {bad}: {err}");
4451        }
4452        assert!(is_valid_resource_id("dashboards-fleet.v1_2"));
4453    }
4454
4455    #[test]
4456    fn view_reuses_shared_widget_validation() {
4457        // The same per-widget rule the job hint enforces (ratio needs
4458        // bool_path), reported under the `widgets[..]` field.
4459        let v = view_from(
4460            "widgets:\n- { dashboard: D, title: T, kind: presence, agg: ratio, render: gauge }\n",
4461        );
4462        let err = v.validate().expect_err("ratio without bool_path must fail");
4463        assert!(
4464            err.contains("widgets[0].agg=ratio requires `bool_path`"),
4465            "err: {err}"
4466        );
4467    }
4468
4469    // ── #vuln-roadmap PR3 SQL-backed views ───────────────────────────
4470    #[test]
4471    fn view_accepts_pure_sql_widgets() {
4472        // A view with only sql_widgets (no obs_events aggregate widgets) is
4473        // valid — the vulnerability-dashboard shape.
4474        let v = view_from(
4475            "sql_widgets:
4476  - title: KEV-affected hosts
4477    query: \"SELECT pc_id, 1 AS cves FROM inventory_sw_apps\"
4478    refresh: 6h
4479    render: { kind: table, columns: [pc_id, cves], labels: { cves: CVE count } }
4480    placement: { analytics: Security, dashboard: { pin: true } }
4481",
4482        );
4483        v.validate().expect("valid sql view");
4484        // refresh parses; pin/tab helpers read the placement.
4485        let w = &v.sql_widgets[0];
4486        assert_eq!(
4487            w.refresh_interval(),
4488            std::time::Duration::from_secs(6 * 3600)
4489        );
4490        assert!(w.placement.is_pinned());
4491        assert_eq!(w.placement.tab(), "Security");
4492    }
4493
4494    #[test]
4495    fn sql_widget_defaults_and_mix() {
4496        // No refresh ⇒ default; a view can mix aggregate + sql widgets.
4497        let v = view_from(
4498            "widgets:
4499  - { dashboard: D, title: T, kind: k, agg: count, render: stat }
4500sql_widgets:
4501  - title: N affected
4502    query: \"SELECT count(*) AS n FROM feeds\"
4503    render: { kind: stat, value: n }
4504    placement: { dashboard: { pin: true } }
4505",
4506        );
4507        v.validate().expect("mixed view is valid");
4508        assert_eq!(v.sql_widgets[0].refresh_interval(), DEFAULT_VIEW_REFRESH);
4509        // dashboard-only placement (no analytics tab) falls back to a label.
4510        assert_eq!(v.sql_widgets[0].placement.tab(), "Dashboard");
4511    }
4512
4513    #[test]
4514    fn sql_widget_validation_rules() {
4515        // helper: build a view with one sql_widget from an inline render+placement
4516        let mk = |render: &str, placement: &str| -> Result<(), String> {
4517            view_from(&format!(
4518                "sql_widgets:
4519  - title: W
4520    query: \"SELECT 1 AS a\"
4521    render: {render}
4522    placement: {placement}
4523"
4524            ))
4525            .validate()
4526        };
4527        // bar needs label + value
4528        let err = mk("{ kind: bar, value: a }", "{ analytics: T }").unwrap_err();
4529        assert!(
4530            err.contains("render.label is required for kind=bar"),
4531            "err: {err}"
4532        );
4533        // pie needs value
4534        let err = mk("{ kind: pie, label: a }", "{ analytics: T }").unwrap_err();
4535        assert!(
4536            err.contains("render.value is required for kind=pie"),
4537            "err: {err}"
4538        );
4539        // stat needs value
4540        let err = mk("{ kind: stat }", "{ analytics: T }").unwrap_err();
4541        assert!(
4542            err.contains("render.value is required for kind=stat"),
4543            "err: {err}"
4544        );
4545        // gauge needs value XOR num+den
4546        let err = mk("{ kind: gauge, num: a }", "{ analytics: T }").unwrap_err();
4547        assert!(err.contains("needs either `value`"), "err: {err}");
4548        mk("{ kind: gauge, value: a }", "{ analytics: T }").expect("gauge value ok");
4549        mk("{ kind: gauge, num: a, den: a }", "{ analytics: T }").expect("gauge num/den ok");
4550        // unknown kind rejected
4551        let err = mk("{ kind: sunburst }", "{ analytics: T }").unwrap_err();
4552        assert!(
4553            err.contains("render.kind is not a known value"),
4554            "err: {err}"
4555        );
4556        // placement must surface somewhere
4557        let err = mk("{ kind: table }", "{}").unwrap_err();
4558        assert!(err.contains("placement must set"), "err: {err}");
4559        // a `dashboard: { pin: false }` block still surfaces nowhere.
4560        let err = mk("{ kind: table }", "{ dashboard: { pin: false } }").unwrap_err();
4561        assert!(err.contains("placement must set"), "err: {err}");
4562        mk("{ kind: table }", "{ dashboard: { pin: true } }").expect("pinned dashboard ok");
4563        // limit: 0 on a bar/pie is an invisible widget — rejected.
4564        let err = mk(
4565            "{ kind: bar, label: a, value: a, limit: 0 }",
4566            "{ analytics: T }",
4567        )
4568        .unwrap_err();
4569        assert!(err.contains("limit must be >= 1"), "err: {err}");
4570        // bad refresh duration rejected
4571        let err = view_from(
4572            "sql_widgets:
4573  - { title: W, query: \"SELECT 1\", refresh: \"6 sidereal days\", render: { kind: table }, placement: { analytics: T } }
4574",
4575        )
4576        .validate()
4577        .unwrap_err();
4578        assert!(
4579            err.contains("refresh") && err.contains("not a valid duration"),
4580            "err: {err}"
4581        );
4582        // table is fine with no channels
4583        mk("{ kind: table }", "{ analytics: T }").expect("bare table ok");
4584    }
4585
4586    #[test]
4587    fn rewrite_pc_id_param_is_literal_and_boundary_aware() {
4588        // A real param outside any literal is rewritten + counted.
4589        let (sql, n) = rewrite_pc_id_param("SELECT * FROM t WHERE pc_id = :pc_id");
4590        assert_eq!(n, 1);
4591        assert!(sql.ends_with("pc_id = ?"), "sql: {sql}");
4592        // Appearing twice → two `?`, count 2 (one bind each — the caller binds
4593        // pc_id per occurrence since sqlx-sqlite has no named params).
4594        let (sql, n) = rewrite_pc_id_param("WHERE a = :pc_id AND (:pc_id IS NOT NULL)");
4595        assert_eq!(n, 2);
4596        assert_eq!(sql, "WHERE a = ? AND (? IS NOT NULL)");
4597        // Inside a string literal → copied verbatim, NOT counted (would else be
4598        // a bind-count mismatch → SQLITE_RANGE, and misclassify scope).
4599        let (sql, n) = rewrite_pc_id_param("SELECT 'see :pc_id docs' AS hint");
4600        assert_eq!(n, 0);
4601        assert_eq!(sql, "SELECT 'see :pc_id docs' AS hint");
4602        // Inside a comment → left alone.
4603        let (_, n) = rewrite_pc_id_param("SELECT 1 -- filter by :pc_id\n");
4604        assert_eq!(n, 0);
4605        // A longer identifier prefix (`:pc_idx`) is not our token.
4606        let (sql, n) = rewrite_pc_id_param("WHERE x = :pc_idx");
4607        assert_eq!(n, 0);
4608        assert_eq!(sql, "WHERE x = :pc_idx");
4609    }
4610
4611    #[test]
4612    fn validate_rejects_pinned_per_pc_widget() {
4613        // A per-PC widget (binds :pc_id) that also pins to the Dashboard is a
4614        // create-time contradiction (Dashboard is fleet-scope) — rejected.
4615        let err = view_from(
4616            "sql_widgets:
4617  - title: W
4618    query: \"SELECT count(*) AS n FROM inventory_sw_apps WHERE pc_id = :pc_id\"
4619    render: { kind: stat, value: n }
4620    placement: { analytics: Security, dashboard: { pin: true } }
4621",
4622        )
4623        .validate()
4624        .unwrap_err();
4625        assert!(err.contains("per-PC widget"), "err: {err}");
4626        // The same widget WITHOUT the pin is fine (per-PC, analytics only).
4627        view_from(
4628            "sql_widgets:
4629  - title: W
4630    query: \"SELECT count(*) AS n FROM inventory_sw_apps WHERE pc_id = :pc_id\"
4631    render: { kind: stat, value: n }
4632    placement: { analytics: Security }
4633",
4634        )
4635        .validate()
4636        .expect("per-PC analytics-only widget is valid");
4637    }
4638
4639    fn execute_with(
4640        script: Option<&str>,
4641        script_file: Option<&str>,
4642        script_object: Option<&str>,
4643    ) -> Execute {
4644        Execute {
4645            shell: ExecuteShell::Powershell,
4646            script: script.map(str::to_owned),
4647            script_file: script_file.map(str::to_owned),
4648            script_object: script_object.map(str::to_owned),
4649            timeout: "30s".into(),
4650            run_as: RunAs::default(),
4651            cwd: None,
4652        }
4653    }
4654
4655    #[test]
4656    fn validate_accepts_inline_script() {
4657        let e = execute_with(Some("echo hi"), None, None);
4658        assert!(e.validate_script_source().is_ok());
4659    }
4660
4661    #[test]
4662    fn validate_accepts_script_file_alone() {
4663        let e = execute_with(None, Some("scripts/cleanup.ps1"), None);
4664        assert!(e.validate_script_source().is_ok());
4665    }
4666
4667    #[test]
4668    fn validate_accepts_script_object_alone() {
4669        let e = execute_with(None, None, Some("cleanup/1.0.0"));
4670        assert!(e.validate_script_source().is_ok());
4671    }
4672
4673    #[test]
4674    fn validate_treats_empty_inline_script_as_unset() {
4675        // `script: ""` + `script_object` set is the natural shape
4676        // when an operator comments out the YAML block-scalar body
4677        // but leaves the key. Should pass.
4678        let e = execute_with(Some(""), None, Some("cleanup/1.0.0"));
4679        assert!(e.validate_script_source().is_ok());
4680    }
4681
4682    #[test]
4683    fn validate_rejects_zero_sources() {
4684        let e = execute_with(None, None, None);
4685        let err = e.validate_script_source().unwrap_err();
4686        assert!(err.contains("must be set"), "got: {err}");
4687    }
4688
4689    #[test]
4690    fn validate_rejects_empty_inline_only() {
4691        let e = execute_with(Some(""), None, None);
4692        let err = e.validate_script_source().unwrap_err();
4693        assert!(err.contains("must be set"), "got: {err}");
4694    }
4695
4696    #[test]
4697    fn validate_rejects_inline_plus_file() {
4698        let e = execute_with(Some("echo hi"), Some("scripts/cleanup.ps1"), None);
4699        let err = e.validate_script_source().unwrap_err();
4700        assert!(err.contains("only one of"), "got: {err}");
4701    }
4702
4703    #[test]
4704    fn validate_rejects_inline_plus_object() {
4705        let e = execute_with(Some("echo hi"), None, Some("cleanup/1.0.0"));
4706        let err = e.validate_script_source().unwrap_err();
4707        assert!(err.contains("only one of"), "got: {err}");
4708    }
4709
4710    #[test]
4711    fn validate_rejects_file_plus_object() {
4712        let e = execute_with(None, Some("scripts/cleanup.ps1"), Some("cleanup/1.0.0"));
4713        let err = e.validate_script_source().unwrap_err();
4714        assert!(err.contains("only one of"), "got: {err}");
4715    }
4716
4717    #[test]
4718    fn validate_rejects_all_three() {
4719        let e = execute_with(
4720            Some("echo hi"),
4721            Some("scripts/cleanup.ps1"),
4722            Some("cleanup/1.0.0"),
4723        );
4724        let err = e.validate_script_source().unwrap_err();
4725        assert!(err.contains("only one of"), "got: {err}");
4726    }
4727
4728    #[test]
4729    fn validate_rejects_blank_script_file() {
4730        // #918: a blank `script_file` used to count as "set" and pass
4731        // the exactly-one check, then fail at use time (the CLI reads
4732        // a file named "").
4733        for blank in ["", "   "] {
4734            let e = execute_with(None, Some(blank), None);
4735            let err = e.validate_script_source().unwrap_err();
4736            assert!(err.contains("script_file must not be blank"), "got: {err}");
4737        }
4738    }
4739
4740    #[test]
4741    fn validate_rejects_blank_script_object() {
4742        // #918: same for a blank `script_object` (would 404 every exec).
4743        for blank in ["", "   "] {
4744            let e = execute_with(None, None, Some(blank));
4745            let err = e.validate_script_source().unwrap_err();
4746            assert!(
4747                err.contains("script_object must not be blank"),
4748                "got: {err}"
4749            );
4750        }
4751    }
4752
4753    #[test]
4754    fn validate_treats_whitespace_inline_script_as_unset() {
4755        // #918: a whitespace-only inline body is a commented-out block,
4756        // not a real script — with no other source it's "zero sources".
4757        let e = execute_with(Some("   \n  "), None, None);
4758        let err = e.validate_script_source().unwrap_err();
4759        assert!(err.contains("must be set"), "got: {err}");
4760    }
4761
4762    #[test]
4763    fn validate_rejects_malformed_script_object_ref() {
4764        // #918: the ref must be `<name>/<version>`; a missing slash,
4765        // extra slash, blank half, or whitespace-padded half (the last
4766        // survives a JSON POST body and 404s at exec — gemini/claude
4767        // #943) can never resolve.
4768        for bad in [
4769            "no-slash", "a/b/c", "/1.0.0", "cleanup/", " / ", "foo/bar ", " foo/bar", "foo /bar",
4770        ] {
4771            let e = execute_with(None, None, Some(bad));
4772            let err = e.validate_script_source().unwrap_err();
4773            assert!(
4774                err.contains("must be `<name>/<version>`"),
4775                "for '{bad}', got: {err}"
4776            );
4777        }
4778    }
4779
4780    #[test]
4781    fn manifest_deserialises_script_object_yaml() {
4782        // SPEC §2.4.1 example shape with the Object Store
4783        // reference picked over inline.
4784        let yaml = r#"
4785id: cleanup-disk-temp
4786version: 1.0.1
4787execute:
4788  shell: powershell
4789  script_object: cleanup-disk-temp/1.0.1
4790  timeout: 600s
4791"#;
4792        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4793        assert_eq!(
4794            m.execute.script_object.as_deref(),
4795            Some("cleanup-disk-temp/1.0.1")
4796        );
4797        assert!(m.execute.script.is_none());
4798        m.validate()
4799            .expect("script_object-only manifest passes validation");
4800    }
4801
4802    #[test]
4803    fn manifest_rejects_typo_in_script_field_name() {
4804        // #492: the strict create boundary catches `script_objectt`
4805        // and similar fat-fingers (with the full path) instead of
4806        // letting them silently fall through to "all three unset".
4807        let yaml = r#"
4808id: typo
4809version: 1.0.0
4810execute:
4811  shell: powershell
4812  script_objectt: oops
4813  timeout: 30s
4814"#;
4815        let err = crate::strict::from_yaml_str::<Manifest>(yaml)
4816            .expect_err("typo'd execute field must be rejected at the write boundary");
4817        assert!(err.contains("execute.script_objectt"), "{err}");
4818    }
4819
4820    #[test]
4821    fn schedule_carries_target_and_rollout() {
4822        let yaml = r#"
4823id: hourly-cleanup-canary
4824when:
4825  per_pc: { every: 1h }
4826job_id: cleanup
4827enabled: true
4828target:
4829  groups: [canary, wave1]
4830jitter: 30s
4831rollout:
4832  strategy: wave
4833  waves:
4834    - { group: canary, delay: 0s }
4835    - { group: wave1,  delay: 5s }
4836"#;
4837        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4838        assert_eq!(s.id, "hourly-cleanup-canary");
4839        assert_eq!(s.job_id, "cleanup");
4840        assert_eq!(s.plan.target.groups, vec!["canary", "wave1"]);
4841        assert_eq!(s.plan.jitter.as_deref(), Some("30s"));
4842        let rollout = s.plan.rollout.expect("rollout present");
4843        assert_eq!(rollout.waves.len(), 2);
4844        assert_eq!(rollout.waves[0].group, "canary");
4845        assert_eq!(rollout.waves[1].delay, "5s");
4846        assert_eq!(rollout.strategy, RolloutStrategy::Wave);
4847    }
4848
4849    #[test]
4850    fn schedule_minimal_target_all() {
4851        let yaml = r#"
4852id: kitting
4853when:
4854  per_pc: once
4855enabled: true
4856job_id: scheduled-echo
4857target: { all: true }
4858"#;
4859        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4860        assert_eq!(s.id, "kitting");
4861        assert_eq!(s.when, When::PerPc(PerPolicy::Once(OnceLiteral::Once)));
4862        assert!(s.enabled);
4863        assert_eq!(s.job_id, "scheduled-echo");
4864        assert!(s.plan.target.all);
4865        assert!(s.plan.rollout.is_none());
4866        assert!(s.plan.jitter.is_none());
4867        assert!(s.active.is_empty());
4868    }
4869
4870    #[test]
4871    fn schedule_enabled_defaults_to_true() {
4872        let yaml = r#"
4873id: x
4874when:
4875  per_pc: once
4876job_id: y
4877target: { all: true }
4878"#;
4879        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4880        assert!(s.enabled);
4881    }
4882
4883    #[test]
4884    fn schedule_tags_default_empty_and_skip_serialise() {
4885        let yaml = r#"
4886id: x
4887when:
4888  per_pc: once
4889job_id: y
4890target: { all: true }
4891"#;
4892        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4893        assert!(s.tags.is_empty());
4894        s.validate().expect("tag-less schedule validates");
4895        let json = serde_json::to_string(&s).expect("serialize");
4896        assert!(
4897            !json.contains("tags"),
4898            "empty tags must not serialise: {json}"
4899        );
4900    }
4901
4902    #[test]
4903    fn schedule_parses_and_validates_tags() {
4904        let yaml = r#"
4905id: weekly-cleanup
4906when:
4907  per_pc: { every: 1h }
4908job_id: cleanup
4909target: { all: true }
4910tags: [weekly, maintenance]
4911"#;
4912        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4913        assert_eq!(s.tags, vec!["weekly", "maintenance"]);
4914        s.validate().expect("tagged schedule validates");
4915    }
4916
4917    #[test]
4918    fn schedule_rejects_blank_tag() {
4919        let yaml = r#"
4920id: x
4921when:
4922  per_pc: once
4923job_id: y
4924target: { all: true }
4925tags: [ok, "  "]
4926"#;
4927        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4928        let err = s.validate().expect_err("blank tag must fail");
4929        assert!(err.contains("tags must not contain empty"), "err: {err}");
4930    }
4931
4932    // ---- `when` parsing (#418 Phase 1) ----
4933
4934    fn schedule_yaml_with(when_block: &str) -> String {
4935        format!(
4936            r#"
4937id: x
4938when:
4939{when_block}
4940job_id: y
4941target: {{ all: true }}
4942"#
4943        )
4944    }
4945
4946    #[test]
4947    fn when_per_pc_every_parses_unquoted_humantime() {
4948        // `6h` is digit-led but non-numeric → YAML string, same as
4949        // the old `cooldown: 6h` convention. No quotes needed.
4950        let s: Schedule =
4951            serde_yaml::from_str(&schedule_yaml_with("  per_pc: { every: 6h }")).expect("parse");
4952        assert_eq!(
4953            s.when,
4954            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() }))
4955        );
4956    }
4957
4958    #[test]
4959    fn when_per_target_every_parses() {
4960        let s: Schedule = serde_yaml::from_str(&schedule_yaml_with("  per_target: { every: 24h }"))
4961            .expect("parse");
4962        assert_eq!(
4963            s.when,
4964            When::PerTarget(PerPolicy::Every(EverySpec {
4965                every: "24h".into()
4966            }))
4967        );
4968    }
4969
4970    #[test]
4971    fn when_per_target_once_parses() {
4972        // Falls out of the shared PerPolicy shape and decide_fire
4973        // already implements it ("any one pc succeeds → skip the
4974        // target forever"), so it is allowed, not rejected.
4975        let s: Schedule =
4976            serde_yaml::from_str(&schedule_yaml_with("  per_target: once")).expect("parse");
4977        assert_eq!(s.when, When::PerTarget(PerPolicy::Once(OnceLiteral::Once)));
4978    }
4979
4980    #[test]
4981    fn when_calendar_time_parses() {
4982        let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(
4983            "  calendar:\n    at: \"09:00\"\n    days: [mon-fri]",
4984        ))
4985        .expect("parse");
4986        match &s.when {
4987            When::Calendar(c) => {
4988                assert_eq!(c.at, "09:00");
4989                assert_eq!(c.days, vec!["mon-fri"]);
4990            }
4991            other => panic!("expected calendar, got {other:?}"),
4992        }
4993    }
4994
4995    #[test]
4996    fn when_calendar_days_default_empty() {
4997        let s: Schedule =
4998            serde_yaml::from_str(&schedule_yaml_with("  calendar:\n    at: \"09:00\""))
4999                .expect("parse");
5000        match &s.when {
5001            When::Calendar(c) => assert!(c.days.is_empty(), "days defaults to empty (= daily)"),
5002            other => panic!("expected calendar, got {other:?}"),
5003        }
5004    }
5005
5006    #[test]
5007    fn when_calendar_datetime_parses_all_separators() {
5008        // one-shot: date+time in hyphen / ISO-T / slash forms
5009        for at in ["2026-06-10 09:00", "2026-06-10T09:00", "2026/06/10 09:00"] {
5010            let block = format!("  calendar:\n    at: \"{at}\"");
5011            let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(&block))
5012                .unwrap_or_else(|e| panic!("parse '{at}': {e}"));
5013            match &s.when {
5014                When::Calendar(c) => {
5015                    use chrono::Datelike;
5016                    let p = c.parse_at().expect("parse_at");
5017                    let d = p.date.expect("datetime at carries a date");
5018                    assert_eq!((d.year(), d.month(), d.day()), (2026, 6, 10), "for '{at}'");
5019                }
5020                other => panic!("expected calendar, got {other:?}"),
5021            }
5022        }
5023    }
5024
5025    #[test]
5026    fn when_rejects_bad_once_keyword() {
5027        // `onec` must be a parse error, not a silently-absorbed
5028        // string (OnceLiteral is a single-variant enum for exactly
5029        // this reason).
5030        let r: Result<Schedule, _> = serde_yaml::from_str(&schedule_yaml_with("  per_pc: onec"));
5031        assert!(r.is_err(), "expected parse error, got {r:?}");
5032    }
5033
5034    #[test]
5035    fn when_rejects_unknown_key_in_every() {
5036        // `{ evry: 6h }` still fails on the tolerant read path: the
5037        // required `every` key is missing, so no PerPolicy variant
5038        // matches (#492 removed deny_unknown_fields, but required
5039        // keys keep the untagged disambiguation honest).
5040        let r: Result<Schedule, _> =
5041            serde_yaml::from_str(&schedule_yaml_with("  per_pc: { evry: 6h }"));
5042        assert!(r.is_err(), "expected parse error, got {r:?}");
5043    }
5044
5045    #[test]
5046    fn when_rejects_unknown_variant() {
5047        let r: Result<Schedule, _> =
5048            serde_yaml::from_str(&schedule_yaml_with("  per_galaxy: once"));
5049        assert!(r.is_err(), "expected parse error, got {r:?}");
5050    }
5051
5052    #[test]
5053    fn when_rejects_old_top_level_cron_field() {
5054        // Pre-#418 shape: top-level `cron:` + no `when:`. Must fail
5055        // loudly (missing `when`), which is what turns stale KV
5056        // blobs into warn-skips after the upgrade.
5057        let yaml = r#"
5058id: x
5059cron: "* * * * * *"
5060job_id: y
5061target: { all: true }
5062"#;
5063        let r: Result<Schedule, _> = serde_yaml::from_str(yaml);
5064        assert!(r.is_err(), "expected parse error, got {r:?}");
5065    }
5066
5067    #[test]
5068    fn when_rejects_retired_cron_escape_hatch() {
5069        // #418 Phase 2 retired `when: { cron: "..." }`. A raw cron
5070        // is now an unknown variant → parse error (operators use the
5071        // calendar form instead).
5072        let r: Result<Schedule, _> =
5073            serde_yaml::from_str(&schedule_yaml_with("  cron: \"0 0 9 * * mon-fri\""));
5074        assert!(
5075            r.is_err(),
5076            "expected parse error for retired cron, got {r:?}"
5077        );
5078    }
5079
5080    #[test]
5081    fn when_round_trips_json_and_yaml() {
5082        // Round-trip through the full Schedule: that is the wire
5083        // unit for both stores (JSON catalog KV + YAML mirror), and
5084        // it exercises the singleton_map field attribute that keeps
5085        // serde_yaml on the map shape instead of `!per_pc` tags.
5086        for when in [
5087            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5088            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5089            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5090            When::PerTarget(PerPolicy::Every(EverySpec {
5091                every: "24h".into(),
5092            })),
5093            calendar("09:00", &["mon-fri"]),
5094            calendar("2026-06-10 09:00", &[]),
5095            When::On(vec![OnTrigger::Startup]),
5096            When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
5097            When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
5098            When::On(vec![OnTrigger::NetworkChange]),
5099        ] {
5100            // Event triggers are agent-only; the rest validate on backend.
5101            let runs_on = if matches!(when, When::On(_)) {
5102                RunsOn::Agent
5103            } else {
5104                RunsOn::Backend
5105            };
5106            let s = schedule_with(when.clone(), runs_on);
5107
5108            let json = serde_json::to_string(&s).expect("json serialise");
5109            let back: Schedule = serde_json::from_str(&json).expect("json deserialise");
5110            assert_eq!(back.when, when, "json round-trip for {when}");
5111
5112            let yaml = serde_yaml::to_string(&s).expect("yaml serialise");
5113            assert!(
5114                !yaml.contains('!'),
5115                "yaml must use the map shape, not tags: {yaml}"
5116            );
5117            let back: Schedule = serde_yaml::from_str(&yaml).expect("yaml deserialise");
5118            assert_eq!(back.when, when, "yaml round-trip for {when}");
5119        }
5120    }
5121
5122    #[test]
5123    fn when_once_serialises_as_bare_keyword() {
5124        // The wire shape operators see in the YAML mirror must stay
5125        // the ergonomic `per_pc: once`, not a one-variant map.
5126        let json = serde_json::to_value(When::PerPc(PerPolicy::Once(OnceLiteral::Once)))
5127            .expect("serialise");
5128        assert_eq!(json, serde_json::json!({ "per_pc": "once" }));
5129    }
5130
5131    #[test]
5132    fn when_displays_operator_summary() {
5133        for (when, expected) in [
5134            (
5135                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5136                "per_pc once",
5137            ),
5138            (
5139                When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5140                "per_pc every 6h",
5141            ),
5142            (
5143                When::PerTarget(PerPolicy::Every(EverySpec {
5144                    every: "24h".into(),
5145                })),
5146                "per_target every 24h",
5147            ),
5148            (calendar("09:00", &["mon-fri"]), "at 09:00 [mon-fri]"),
5149            (calendar("2026-06-10 09:00", &[]), "at 2026-06-10 09:00"),
5150            (When::On(vec![OnTrigger::Startup]), "on [startup]"),
5151            (
5152                When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
5153                "on [startup,logon]",
5154            ),
5155            (
5156                When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
5157                "on [lock,unlock]",
5158            ),
5159            (
5160                When::On(vec![OnTrigger::NetworkChange]),
5161                "on [network_change]",
5162            ),
5163        ] {
5164            assert_eq!(when.to_string(), expected);
5165        }
5166    }
5167
5168    // ---- lowering (#418: when → engine vocabulary) ----
5169
5170    fn schedule_with(when: When, runs_on: RunsOn) -> Schedule {
5171        Schedule {
5172            id: "x".into(),
5173            when,
5174            job_id: "y".into(),
5175            // #917: validate() now rejects a target that dispatches
5176            // nothing, so the baseline helper carries the simplest
5177            // specified target.
5178            plan: FanoutPlan {
5179                target: Target {
5180                    all: true,
5181                    ..Target::default()
5182                },
5183                ..FanoutPlan::default()
5184            },
5185            active: Active::default(),
5186            constraints: Constraints::default(),
5187            on_failure: OnFailure::default(),
5188            tz: ScheduleTz::default(),
5189            starting_deadline: None,
5190            runs_on,
5191            enabled: true,
5192            tags: Vec::new(),
5193            origin: None,
5194        }
5195    }
5196
5197    fn calendar(at: &str, days: &[&str]) -> When {
5198        When::Calendar(CalendarSpec {
5199            at: at.into(),
5200            days: days.iter().map(|d| (*d).to_string()).collect(),
5201        })
5202    }
5203
5204    #[test]
5205    fn next_calendar_fire_returns_next_utc_occurrence() {
5206        use chrono::TimeZone;
5207        // Daily 09:00, evaluated in UTC. From 08:00 the same day, the
5208        // next strict occurrence is 09:00 that day.
5209        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5210        s.tz = ScheduleTz::Utc;
5211        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 8, 0, 0).unwrap();
5212        let next = s.next_calendar_fire(now).expect("calendar has a next fire");
5213        assert_eq!(
5214            next,
5215            chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap()
5216        );
5217    }
5218
5219    #[test]
5220    fn next_calendar_fire_is_strictly_after_now() {
5221        use chrono::TimeZone;
5222        // Standing exactly on a fire instant must preview the *next*
5223        // one (inclusive = false), not the one firing right now.
5224        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5225        s.tz = ScheduleTz::Utc;
5226        let on_fire = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap();
5227        let next = s
5228            .next_calendar_fire(on_fire)
5229            .expect("calendar has a next fire");
5230        assert_eq!(
5231            next,
5232            chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()
5233        );
5234    }
5235
5236    #[test]
5237    fn next_calendar_fire_none_for_reconcile_shapes() {
5238        // `per_pc` / `per_target` lower to the every-minute poll cron —
5239        // no discrete upcoming event to preview, so `None`.
5240        let now = chrono::Utc::now();
5241        for when in [
5242            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5243            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5244            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5245            When::PerTarget(PerPolicy::Every(EverySpec {
5246                every: "24h".into(),
5247            })),
5248        ] {
5249            let s = schedule_with(when, RunsOn::Backend);
5250            assert!(
5251                s.next_calendar_fire(now).is_none(),
5252                "reconcile shapes have no calendar fire",
5253            );
5254        }
5255    }
5256
5257    // ---- preview_fires (#418 dry-run / preview) ----
5258
5259    fn cal_utc(at: &str, days: &[&str]) -> Schedule {
5260        let mut s = schedule_with(calendar(at, days), RunsOn::Backend);
5261        s.tz = ScheduleTz::Utc; // host-independent assertions
5262        s
5263    }
5264
5265    #[test]
5266    fn preview_lists_next_calendar_occurrences() {
5267        use chrono::TimeZone;
5268        // Weekday 09:00, from Wed 2026-06-10 00:00 UTC: the next five
5269        // fires skip the weekend (Sat 13 / Sun 14).
5270        let s = cal_utc("09:00", &["mon-fri"]);
5271        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5272        let got = s.preview_fires(now, 5);
5273        let want: Vec<_> = [
5274            (2026, 6, 10), // Wed
5275            (2026, 6, 11), // Thu
5276            (2026, 6, 12), // Fri
5277            (2026, 6, 15), // Mon (skips Sat 13 / Sun 14)
5278            (2026, 6, 16), // Tue
5279        ]
5280        .iter()
5281        .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
5282        .collect();
5283        assert_eq!(got, want);
5284    }
5285
5286    #[test]
5287    fn preview_handles_nth_and_last_weekday() {
5288        use chrono::TimeZone;
5289        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
5290        // 2nd Tuesday (Patch Tuesday): Jun 9, Jul 14 2026.
5291        let nth = cal_utc("09:00", &["tue#2"]).preview_fires(now, 2);
5292        assert_eq!(
5293            nth,
5294            vec![
5295                chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap(),
5296                chrono::Utc.with_ymd_and_hms(2026, 7, 14, 9, 0, 0).unwrap(),
5297            ]
5298        );
5299        // Last Friday of the month: Jun 26, Jul 31 2026.
5300        let last = cal_utc("22:00", &["friL"]).preview_fires(now, 2);
5301        assert_eq!(
5302            last,
5303            vec![
5304                chrono::Utc.with_ymd_and_hms(2026, 6, 26, 22, 0, 0).unwrap(),
5305                chrono::Utc.with_ymd_and_hms(2026, 7, 31, 22, 0, 0).unwrap(),
5306            ]
5307        );
5308    }
5309
5310    #[test]
5311    fn preview_is_empty_for_reconcile_and_zero_count() {
5312        let now = chrono::Utc::now();
5313        // reconcile shapes have no discrete fire times
5314        let recon = schedule_with(
5315            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5316            RunsOn::Backend,
5317        );
5318        assert!(recon.preview_fires(now, 5).is_empty());
5319        // count == 0 yields nothing even for a calendar
5320        assert!(cal_utc("09:00", &[]).preview_fires(now, 0).is_empty());
5321    }
5322
5323    #[test]
5324    fn preview_skips_outside_active_window() {
5325        use chrono::TimeZone;
5326        // Daily 09:00, active only [2026-06-15, 2026-06-17). Occurrences
5327        // before `from` are skipped; `until` is exclusive, so 06-17's
5328        // fire is out — leaving exactly the 15th and 16th.
5329        let mut s = cal_utc("09:00", &[]);
5330        s.active = Active {
5331            from: Some("2026-06-15".into()),
5332            until: Some("2026-06-17".into()),
5333        };
5334        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5335        let got = s.preview_fires(now, 5);
5336        assert_eq!(
5337            got,
5338            vec![
5339                chrono::Utc.with_ymd_and_hms(2026, 6, 15, 9, 0, 0).unwrap(),
5340                chrono::Utc.with_ymd_and_hms(2026, 6, 16, 9, 0, 0).unwrap(),
5341            ]
5342        );
5343    }
5344
5345    #[test]
5346    fn preview_empty_when_calendar_time_outside_window() {
5347        use chrono::TimeZone;
5348        // Fires at 09:00 but the maintenance window is overnight — it can
5349        // never run, so the preview is empty (matches
5350        // `calendar_outside_window`), and the scan still terminates.
5351        let mut s = cal_utc("09:00", &[]);
5352        s.constraints = Constraints {
5353            window: Some("22:00-05:00".into()),
5354            ..Constraints::default()
5355        };
5356        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5357        assert!(s.preview_fires(now, 5).is_empty());
5358        // Every candidate tick is rejected, so this also exercises the
5359        // SCAN_CAP bound: a large `count` must still terminate (and
5360        // return empty) rather than spin (claude #578 review).
5361        assert!(s.preview_fires(now, 50).is_empty());
5362    }
5363
5364    #[test]
5365    fn preview_past_one_shot_is_empty() {
5366        use chrono::TimeZone;
5367        // A dated one-shot whose instant has passed never fires again.
5368        let s = cal_utc("2026-06-10 09:00", &[]);
5369        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 0, 0, 0).unwrap();
5370        assert!(s.preview_fires(now, 5).is_empty());
5371        // …but from before it, the single future fire shows up.
5372        let before = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
5373        assert_eq!(
5374            s.preview_fires(before, 5),
5375            vec![chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()]
5376        );
5377    }
5378
5379    #[test]
5380    fn lowering_matches_the_418_table() {
5381        let cases = [
5382            (
5383                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5384                (POLL_CRON, ExecMode::OncePerPc, None),
5385            ),
5386            (
5387                When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5388                (POLL_CRON, ExecMode::OncePerPc, Some("6h")),
5389            ),
5390            (
5391                When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5392                (POLL_CRON, ExecMode::OncePerTarget, None),
5393            ),
5394            (
5395                When::PerTarget(PerPolicy::Every(EverySpec {
5396                    every: "24h".into(),
5397                })),
5398                (POLL_CRON, ExecMode::OncePerTarget, Some("24h")),
5399            ),
5400            // calendar repeating → 6-field cron
5401            (
5402                calendar("09:00", &["mon-fri"]),
5403                ("0 0 9 * * mon-fri", ExecMode::EveryTick, None),
5404            ),
5405            // calendar daily (no days) → DOW *
5406            (
5407                calendar("18:30", &[]),
5408                ("0 30 18 * * *", ExecMode::EveryTick, None),
5409            ),
5410            // calendar one-shot → 7-field year cron
5411            (
5412                calendar("2026-06-10 09:00", &[]),
5413                ("0 0 9 10 6 * 2026", ExecMode::EveryTick, None),
5414            ),
5415        ];
5416        for (when, (cron, mode, cooldown)) in cases {
5417            let l = schedule_with(when.clone(), RunsOn::Backend).lowered();
5418            assert_eq!(l.cron, cron, "cron for {when}");
5419            assert_eq!(l.mode, mode, "mode for {when}");
5420            assert_eq!(l.cooldown.as_deref(), cooldown, "cooldown for {when}");
5421        }
5422    }
5423
5424    #[test]
5425    fn lowered_carries_schedule_tz() {
5426        for (tz, want) in [
5427            (ScheduleTz::Local, ScheduleTz::Local),
5428            (ScheduleTz::Utc, ScheduleTz::Utc),
5429        ] {
5430            let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
5431            s.tz = tz;
5432            assert_eq!(s.lowered().tz, want, "calendar carries tz");
5433            // reconcile shapes carry tz too (for the active-window check)
5434            let mut s = schedule_with(
5435                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5436                RunsOn::Backend,
5437            );
5438            s.tz = tz;
5439            assert_eq!(s.lowered().tz, want, "reconcile carries tz");
5440        }
5441    }
5442
5443    #[test]
5444    fn poll_cron_is_accepted_by_the_engine_parser() {
5445        // POLL_CRON is system-generated — if the engine's parser
5446        // ever rejected it every reconcile schedule would die at
5447        // register time. Validate it with the same croner config
5448        // (Seconds::Required, dom_and_dow, year optional).
5449        croner::parser::CronParser::builder()
5450            .seconds(croner::parser::Seconds::Required)
5451            .dom_and_dow(true)
5452            .build()
5453            .parse(POLL_CRON)
5454            .expect("POLL_CRON must parse");
5455    }
5456
5457    // ---- Schedule::validate() (#418 decision F) ----
5458
5459    #[test]
5460    fn validate_accepts_reconcile_shapes() {
5461        for when in [
5462            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5463            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5464            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5465            When::PerTarget(PerPolicy::Every(EverySpec {
5466                every: "24h".into(),
5467            })),
5468        ] {
5469            schedule_with(when.clone(), RunsOn::Backend)
5470                .validate()
5471                .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
5472        }
5473    }
5474
5475    #[test]
5476    fn validate_accepts_per_pc_on_agent() {
5477        schedule_with(
5478            When::PerPc(PerPolicy::Every(EverySpec { every: "1h".into() })),
5479            RunsOn::Agent,
5480        )
5481        .validate()
5482        .expect("per_pc + agent is the offline-inventory shape");
5483    }
5484
5485    // ---- #418 event triggers (when: { on }) ----
5486
5487    #[test]
5488    fn validate_accepts_event_on_agent() {
5489        for triggers in [
5490            vec![OnTrigger::Startup],
5491            vec![OnTrigger::Logon],
5492            vec![OnTrigger::Lock],
5493            vec![OnTrigger::Unlock],
5494            vec![OnTrigger::NetworkChange],
5495            vec![
5496                OnTrigger::Startup,
5497                OnTrigger::Logon,
5498                OnTrigger::Lock,
5499                OnTrigger::Unlock,
5500                OnTrigger::NetworkChange,
5501            ],
5502        ] {
5503            schedule_with(When::On(triggers), RunsOn::Agent)
5504                .validate()
5505                .expect("when.on is valid on runs_on: agent");
5506        }
5507    }
5508
5509    #[test]
5510    fn validate_rejects_event_on_backend() {
5511        let err = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Backend)
5512            .validate()
5513            .unwrap_err();
5514        assert!(err.contains("when.on"), "got: {err}");
5515        assert!(err.contains("runs_on: agent"), "got: {err}");
5516    }
5517
5518    #[test]
5519    fn validate_rejects_empty_event_list() {
5520        let err = schedule_with(When::On(vec![]), RunsOn::Agent)
5521            .validate()
5522            .unwrap_err();
5523        assert!(err.contains("when.on"), "got: {err}");
5524        assert!(err.contains("at least one"), "got: {err}");
5525    }
5526
5527    #[test]
5528    fn event_schedule_lowers_to_event_mode_and_is_event() {
5529        let s = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Agent);
5530        assert!(s.is_event());
5531        assert_eq!(s.lowered().mode, ExecMode::Event);
5532        assert_eq!(s.event_triggers(), &[OnTrigger::Startup]);
5533        // non-event schedules report no triggers.
5534        let cal = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5535        assert!(!cal.is_event());
5536        assert!(cal.event_triggers().is_empty());
5537    }
5538
5539    // ---- #418 constraints.require (env gates) ----
5540
5541    fn require_schedule(req: Require, runs_on: RunsOn) -> Schedule {
5542        let mut s = schedule_with(
5543            When::PerPc(PerPolicy::Every(EverySpec { every: "1m".into() })),
5544            runs_on,
5545        );
5546        s.constraints.require = Some(req);
5547        s
5548    }
5549
5550    #[test]
5551    fn require_met_combinations() {
5552        use std::time::Duration;
5553        let idle = |m: u64| Some(Duration::from_secs(m * 60));
5554        // Builder for the sensed state: (ac, idle, cpu, network).
5555        let env = |ac, idle, cpu, net| EnvState {
5556            ac_online: ac,
5557            idle,
5558            cpu_pct: cpu,
5559            network_up: net,
5560        };
5561        // Empty require — always met regardless of sensed state.
5562        assert!(require_met(
5563            &Require::default(),
5564            &env(false, None, None, false)
5565        ));
5566        // ac_power: only on AC.
5567        let ac = Require {
5568            ac_power: true,
5569            ..Default::default()
5570        };
5571        assert!(!require_met(&ac, &env(false, None, None, true)));
5572        assert!(require_met(&ac, &env(true, None, None, false)));
5573        // idle: needs >= the configured min; None idle never satisfies.
5574        let idle10 = Require {
5575            idle: Some("10m".into()),
5576            ..Default::default()
5577        };
5578        assert!(!require_met(&idle10, &env(true, None, None, true)));
5579        assert!(!require_met(&idle10, &env(true, idle(5), None, true)));
5580        assert!(require_met(&idle10, &env(true, idle(15), None, true)));
5581        assert!(require_met(&idle10, &env(true, idle(10), None, true))); // boundary inclusive
5582        // cpu_below: needs CPU strictly < threshold; None cpu never satisfies.
5583        let cpu20 = Require {
5584            cpu_below: Some(20.0),
5585            ..Default::default()
5586        };
5587        assert!(!require_met(&cpu20, &env(true, None, None, true))); // no sample → fail-closed
5588        assert!(!require_met(&cpu20, &env(true, None, Some(20.0), true))); // == threshold
5589        assert!(!require_met(&cpu20, &env(true, None, Some(55.0), true))); // busy
5590        assert!(require_met(&cpu20, &env(true, None, Some(5.0), true))); // quiet
5591        // network: only when online.
5592        let net = Require {
5593            network: true,
5594            ..Default::default()
5595        };
5596        assert!(!require_met(&net, &env(true, None, None, false))); // offline
5597        assert!(require_met(&net, &env(true, None, None, true))); // online
5598        // all four: AND.
5599        let all = Require {
5600            ac_power: true,
5601            idle: Some("10m".into()),
5602            cpu_below: Some(20.0),
5603            network: true,
5604        };
5605        assert!(!require_met(&all, &env(false, idle(20), Some(5.0), true))); // on battery
5606        assert!(!require_met(&all, &env(true, idle(1), Some(5.0), true))); // not idle enough
5607        assert!(!require_met(&all, &env(true, idle(20), Some(50.0), true))); // busy
5608        assert!(!require_met(&all, &env(true, idle(20), Some(5.0), false))); // offline
5609        assert!(require_met(&all, &env(true, idle(20), Some(5.0), true)));
5610        // An unparseable idle is treated as no-requirement by require_met
5611        // (validate rejects it at create time, so this only guards a
5612        // hand-edited blob): ac still gates.
5613        let bad = Require {
5614            ac_power: true,
5615            idle: Some("garbage".into()),
5616            ..Default::default()
5617        };
5618        assert!(require_met(&bad, &env(true, None, None, true)));
5619        assert!(!require_met(&bad, &env(false, None, None, true)));
5620    }
5621
5622    #[test]
5623    fn validate_accepts_and_rejects_cpu_below() {
5624        // In-range accepted.
5625        require_schedule(
5626            Require {
5627                cpu_below: Some(20.0),
5628                ..Default::default()
5629            },
5630            RunsOn::Agent,
5631        )
5632        .validate()
5633        .expect("cpu_below 20 is valid");
5634        // Upper boundary: 100.0 is accepted (fires unless CPU is exactly
5635        // 100%). Pins the inclusive upper bound against a future c < 100.0.
5636        require_schedule(
5637            Require {
5638                cpu_below: Some(100.0),
5639                ..Default::default()
5640            },
5641            RunsOn::Agent,
5642        )
5643        .validate()
5644        .expect("cpu_below 100 is valid");
5645        // Out of range rejected (0 and >100).
5646        for bad in [0.0, -5.0, 100.1] {
5647            let err = require_schedule(
5648                Require {
5649                    cpu_below: Some(bad),
5650                    ..Default::default()
5651                },
5652                RunsOn::Agent,
5653            )
5654            .validate()
5655            .unwrap_err();
5656            assert!(
5657                err.contains("constraints.require.cpu_below"),
5658                "cpu_below {bad}: {err}"
5659            );
5660        }
5661    }
5662
5663    #[test]
5664    fn validate_accepts_require_on_agent() {
5665        require_schedule(
5666            Require {
5667                ac_power: true,
5668                idle: Some("10m".into()),
5669                cpu_below: Some(20.0),
5670                network: true,
5671            },
5672            RunsOn::Agent,
5673        )
5674        .validate()
5675        .expect("constraints.require is valid on runs_on: agent");
5676    }
5677
5678    #[test]
5679    fn validate_rejects_require_on_backend() {
5680        let err = require_schedule(
5681            Require {
5682                ac_power: true,
5683                ..Default::default()
5684            },
5685            RunsOn::Backend,
5686        )
5687        .validate()
5688        .unwrap_err();
5689        assert!(err.contains("constraints.require"), "got: {err}");
5690        assert!(err.contains("runs_on: agent"), "got: {err}");
5691
5692        // An idle-only require (ac_power: false) is also non-empty
5693        // (is_empty folds the fields) and must reject on backend too —
5694        // guards against a regression in Require::is_empty.
5695        let err = require_schedule(
5696            Require {
5697                idle: Some("10m".into()),
5698                ..Default::default()
5699            },
5700            RunsOn::Backend,
5701        )
5702        .validate()
5703        .unwrap_err();
5704        assert!(
5705            err.contains("constraints.require"),
5706            "idle-only on backend: {err}"
5707        );
5708    }
5709
5710    #[test]
5711    fn validate_rejects_bad_require_idle() {
5712        let err = require_schedule(
5713            Require {
5714                idle: Some("not-a-duration".into()),
5715                ..Default::default()
5716            },
5717            RunsOn::Agent,
5718        )
5719        .validate()
5720        .unwrap_err();
5721        assert!(err.contains("constraints.require.idle"), "got: {err}");
5722    }
5723
5724    #[test]
5725    fn require_round_trips_and_skips_empty() {
5726        // ac_power: false is skipped; an all-default require nested in
5727        // constraints is omitted (is_empty folds it in).
5728        let yaml = "id: s\nwhen: { per_pc: { every: 1m } }\njob_id: j\nruns_on: agent\n\
5729                    constraints: { require: { ac_power: true, idle: 10m, cpu_below: 20, \
5730                    network: true } }\n";
5731        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5732        let req = s.constraints.require.as_ref().expect("require present");
5733        assert!(req.ac_power);
5734        assert_eq!(req.idle.as_deref(), Some("10m"));
5735        assert_eq!(req.cpu_below, Some(20.0));
5736        assert!(req.network);
5737        // Re-serialize: idle + cpu_below + network present, ac_power true.
5738        let back = serde_json::to_string(&s.constraints).unwrap();
5739        assert!(back.contains("\"idle\":\"10m\""), "got: {back}");
5740        assert!(back.contains("\"cpu_below\":20"), "got: {back}");
5741        assert!(back.contains("\"network\":true"), "got: {back}");
5742        // An empty require is omitted entirely by is_empty.
5743        let mut empty = s.clone();
5744        empty.constraints.require = Some(Require::default());
5745        assert!(empty.constraints.is_empty());
5746    }
5747
5748    #[test]
5749    fn validate_rejects_per_target_on_agent() {
5750        let err = schedule_with(
5751            When::PerTarget(PerPolicy::Every(EverySpec {
5752                every: "24h".into(),
5753            })),
5754            RunsOn::Agent,
5755        )
5756        .validate()
5757        .unwrap_err();
5758        assert!(err.contains("per_target"), "got: {err}");
5759        assert!(err.contains("runs_on: agent"), "got: {err}");
5760
5761        // per_target: once is also backend-only.
5762        let err = schedule_with(
5763            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5764            RunsOn::Agent,
5765        )
5766        .validate()
5767        .unwrap_err();
5768        assert!(err.contains("per_target"), "got (once): {err}");
5769        assert!(err.contains("runs_on: agent"), "got (once): {err}");
5770    }
5771
5772    #[test]
5773    fn validate_rejects_bad_every_duration() {
5774        let err = schedule_with(
5775            When::PerPc(PerPolicy::Every(EverySpec { every: "6x".into() })),
5776            RunsOn::Backend,
5777        )
5778        .validate()
5779        .unwrap_err();
5780        assert!(err.contains("when.every"), "got: {err}");
5781    }
5782
5783    #[test]
5784    fn validate_rejects_bad_jitter_and_starting_deadline() {
5785        let mut s = schedule_with(
5786            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5787            RunsOn::Backend,
5788        );
5789        s.plan.jitter = Some("5x".into());
5790        let err = s.validate().unwrap_err();
5791        assert!(err.contains("jitter"), "got: {err}");
5792
5793        let mut s = schedule_with(
5794            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5795            RunsOn::Backend,
5796        );
5797        s.starting_deadline = Some("soon".into());
5798        let err = s.validate().unwrap_err();
5799        assert!(err.contains("starting_deadline"), "got: {err}");
5800    }
5801
5802    #[test]
5803    fn validate_rejects_unspecified_target() {
5804        // #917 (1): an all-default target never dispatches anywhere —
5805        // runs_on: agent silently never fires, runs_on: backend
5806        // warn-fails every tick at the exec boundary. Both rejected.
5807        for runs_on in [RunsOn::Backend, RunsOn::Agent] {
5808            let mut s = schedule_with(When::PerPc(PerPolicy::Once(OnceLiteral::Once)), runs_on);
5809            s.plan.target = Target::default();
5810            let err = s.validate().unwrap_err();
5811            assert!(err.contains("target"), "for {runs_on:?}, got: {err}");
5812        }
5813    }
5814
5815    /// A Schedule with every top-level field populated so each one
5816    /// actually serialises (the optional ones are `skip_serializing_if`).
5817    fn fully_populated_schedule() -> Schedule {
5818        let mut s = schedule_with(
5819            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5820            RunsOn::Backend,
5821        );
5822        s.plan.rollout = Some(Rollout {
5823            strategy: RolloutStrategy::Wave,
5824            waves: vec![Wave {
5825                group: "canary".into(),
5826                delay: "0s".into(),
5827            }],
5828        });
5829        s.plan.jitter = Some("5m".into());
5830        s.plan.deadline_at = Some(chrono::Utc::now());
5831        s.active = Active {
5832            from: Some("2026-01-01 00:00".into()),
5833            until: Some("2026-12-31 00:00".into()),
5834        };
5835        s.constraints = Constraints {
5836            window: Some("09:00-17:00".into()),
5837            ..Constraints::default()
5838        };
5839        s.on_failure = OnFailure {
5840            retry: Some(Retry {
5841                max: 1,
5842                backoff: "10s".into(),
5843            }),
5844        };
5845        s.starting_deadline = Some("30m".into());
5846        s.tags = vec!["health".into()];
5847        s.origin = Some(RepoOrigin {
5848            path: "configs/schedules/x.yaml".into(),
5849            repo: None,
5850            script_file: None,
5851        });
5852        s
5853    }
5854
5855    #[test]
5856    fn schedule_top_level_keys_cover_serialized_fields() {
5857        // #924 drift guard: the hand-maintained TOP_LEVEL_KEYS list must
5858        // match exactly what a fully-populated Schedule serialises — so a
5859        // future field added to Schedule or FanoutPlan can't slip past
5860        // the flatten-aware strict guard by being forgotten here.
5861        let s = fully_populated_schedule();
5862        let value = serde_json::to_value(&s).expect("serialize schedule");
5863        let serialized: std::collections::BTreeSet<String> = value
5864            .as_object()
5865            .expect("schedule serialises to an object")
5866            .keys()
5867            .cloned()
5868            .collect();
5869        let listed: std::collections::BTreeSet<String> = Schedule::TOP_LEVEL_KEYS
5870            .iter()
5871            .map(|s| s.to_string())
5872            .collect();
5873        assert_eq!(
5874            serialized, listed,
5875            "TOP_LEVEL_KEYS is out of sync with Schedule's serialized fields \
5876             (flatten-aware strict guard would miss a real field or reject a valid one)"
5877        );
5878    }
5879
5880    #[test]
5881    fn strict_rejects_flatten_hidden_top_level_typo() {
5882        // #924: a top-level typo on a flattening type (jiter / enabledd)
5883        // is buffered into the flatten target by serde and hidden from
5884        // serde_ignored — the top-level guard must catch it. Verified on
5885        // both the YAML and JSON strict boundaries.
5886        let yaml = "\
5887id: s1
5888job_id: j1
5889when:
5890  per_pc: once
5891target:
5892  all: true
5893jiter: 5m
5894";
5895        let err = crate::strict::from_yaml_str::<Schedule>(yaml).unwrap_err();
5896        assert!(err.contains("jiter"), "got: {err}");
5897
5898        let json = serde_json::json!({
5899            "id": "s1",
5900            "job_id": "j1",
5901            "when": { "per_pc": "once" },
5902            "target": { "all": true },
5903            "enabledd": false,
5904        });
5905        let err = crate::strict::from_json_slice::<Schedule>(&serde_json::to_vec(&json).unwrap())
5906            .unwrap_err();
5907        assert!(err.contains("enabledd"), "got: {err}");
5908    }
5909
5910    #[test]
5911    fn strict_accepts_all_valid_schedule_top_level_keys() {
5912        // The guard must not reject any legitimate key — round-trip a
5913        // fully-populated schedule through the strict YAML boundary.
5914        let s = fully_populated_schedule();
5915        let yaml = serde_yaml::to_string(&s).expect("serialize");
5916        crate::strict::from_yaml_str::<Schedule>(&yaml)
5917            .expect("every serialized key must be accepted by the strict guard");
5918    }
5919
5920    #[test]
5921    fn strict_rejects_non_string_top_level_yaml_key() {
5922        // #924 (gemini #945): a YAML key isn't always a string — an
5923        // unquoted `true:` parses as a boolean, `123:` as a number. A
5924        // `filter_map` on `as_str()` would drop these and let them slip
5925        // past the flatten guard; `yaml_key_label` renders them so they
5926        // are still rejected. (serde_yaml is YAML 1.2, so `on:` stays a
5927        // *string* "on" — also rejected, just via the string path.)
5928        let base = "\
5929id: s1
5930job_id: j1
5931when:
5932  per_pc: once
5933target:
5934  all: true
5935";
5936        for (extra, needle) in [
5937            ("true: x\n", "true"),
5938            ("123: x\n", "123"),
5939            ("on: y\n", "on"),
5940        ] {
5941            let yaml = format!("{base}{extra}");
5942            let err = crate::strict::from_yaml_str::<Schedule>(&yaml).unwrap_err();
5943            assert!(err.contains(needle), "for '{extra}', got: {err}");
5944        }
5945    }
5946
5947    #[test]
5948    fn validate_accepts_waves_instead_of_target_on_backend() {
5949        // #917 (1): the exec boundary accepts rollout-only plans
5950        // (target then just labels the audit row) — so does validate.
5951        let mut s = schedule_with(
5952            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5953            RunsOn::Backend,
5954        );
5955        s.plan.target = Target::default();
5956        s.plan.rollout = Some(Rollout {
5957            strategy: RolloutStrategy::Wave,
5958            waves: vec![Wave {
5959                group: "canary".into(),
5960                delay: "0s".into(),
5961            }],
5962        });
5963        s.validate().expect("rollout-only plan should validate");
5964    }
5965
5966    #[test]
5967    fn validate_rejects_rollout_on_agent() {
5968        // #917 (1): rollout waves are backend-published; a runs_on:
5969        // agent schedule never reads them, so the combination is a
5970        // silent no-op — reject like max_concurrent-on-agent.
5971        let mut s = schedule_with(
5972            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5973            RunsOn::Agent,
5974        );
5975        s.plan.rollout = Some(Rollout {
5976            strategy: RolloutStrategy::Wave,
5977            waves: vec![Wave {
5978                group: "canary".into(),
5979                delay: "0s".into(),
5980            }],
5981        });
5982        let err = s.validate().unwrap_err();
5983        assert!(err.contains("rollout"), "got: {err}");
5984    }
5985
5986    #[test]
5987    fn validate_rejects_bad_waves() {
5988        // #917 (2): empty waves, blank group, unparseable delay — all
5989        // previously accepted and failed (or no-opped) at every fire.
5990        let base = || {
5991            schedule_with(
5992                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5993                RunsOn::Backend,
5994            )
5995        };
5996
5997        let mut s = base();
5998        s.plan.rollout = Some(Rollout {
5999            strategy: RolloutStrategy::Wave,
6000            waves: vec![],
6001        });
6002        let err = s.validate().unwrap_err();
6003        assert!(err.contains("at least one wave"), "got: {err}");
6004
6005        let mut s = base();
6006        s.plan.rollout = Some(Rollout {
6007            strategy: RolloutStrategy::Wave,
6008            waves: vec![Wave {
6009                group: "  ".into(),
6010                delay: "0s".into(),
6011            }],
6012        });
6013        let err = s.validate().unwrap_err();
6014        assert!(err.contains("waves[0].group"), "got: {err}");
6015
6016        let mut s = base();
6017        s.plan.rollout = Some(Rollout {
6018            strategy: RolloutStrategy::Wave,
6019            waves: vec![
6020                Wave {
6021                    group: "canary".into(),
6022                    delay: "0s".into(),
6023                },
6024                Wave {
6025                    group: "wave1".into(),
6026                    delay: "5 minuts".into(),
6027                },
6028            ],
6029        });
6030        let err = s.validate().unwrap_err();
6031        assert!(err.contains("waves[1].delay"), "got: {err}");
6032    }
6033
6034    #[test]
6035    fn validate_rejects_wave_delay_at_or_past_starting_deadline() {
6036        // #917 (3): the deadline is stamped once at tick time, so a
6037        // wave sleeping >= starting_deadline publishes already-expired
6038        // Commands — dead on arrival, every fire.
6039        let mut s = schedule_with(
6040            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6041            RunsOn::Backend,
6042        );
6043        s.starting_deadline = Some("30m".into());
6044        s.plan.rollout = Some(Rollout {
6045            strategy: RolloutStrategy::Wave,
6046            waves: vec![
6047                Wave {
6048                    group: "canary".into(),
6049                    delay: "0s".into(),
6050                },
6051                Wave {
6052                    group: "wave1".into(),
6053                    delay: "30m".into(),
6054                },
6055            ],
6056        });
6057        let err = s.validate().unwrap_err();
6058        assert!(
6059            err.contains("waves[1].delay") && err.contains("starting_deadline"),
6060            "got: {err}"
6061        );
6062
6063        // Strictly shorter is fine.
6064        s.plan.rollout.as_mut().unwrap().waves[1].delay = "29m".into();
6065        s.validate().expect("delay < deadline should validate");
6066    }
6067
6068    #[test]
6069    fn validate_rejects_operator_set_deadline_at() {
6070        // #917 (4): machine-stamped field — the scheduler overwrites it
6071        // on every fire, so a hand-set value is silently discarded.
6072        let mut s = schedule_with(
6073            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6074            RunsOn::Backend,
6075        );
6076        s.plan.deadline_at = Some(chrono::Utc::now());
6077        let err = s.validate().unwrap_err();
6078        assert!(
6079            err.contains("deadline_at") && err.contains("starting_deadline"),
6080            "got: {err}"
6081        );
6082    }
6083
6084    #[test]
6085    fn validate_accepts_calendar_shapes() {
6086        for when in [
6087            calendar("09:00", &["mon-fri"]),   // weekday morning
6088            calendar("00:00", &["sun"]),       // weekly
6089            calendar("18:30", &[]),            // daily
6090            calendar("2026-06-10 09:00", &[]), // one-shot
6091            calendar("2026/12/25 00:00", &[]), // one-shot, slash form
6092        ] {
6093            schedule_with(when.clone(), RunsOn::Backend)
6094                .validate()
6095                .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
6096        }
6097    }
6098
6099    #[test]
6100    fn validate_rejects_bad_at() {
6101        for bad in ["25:00", "09:60", "9", "noon", "2026-13-01 09:00"] {
6102            let err = schedule_with(calendar(bad, &[]), RunsOn::Backend)
6103                .validate()
6104                .unwrap_err();
6105            assert!(err.contains("when.at"), "for '{bad}', got: {err}");
6106        }
6107    }
6108
6109    #[test]
6110    fn validate_rejects_datetime_at_with_days() {
6111        // A dated `at` is a one-shot — pairing it with days is a
6112        // contradiction (the date already pins the day).
6113        let err = schedule_with(calendar("2026-06-10 09:00", &["mon"]), RunsOn::Backend)
6114            .validate()
6115            .unwrap_err();
6116        assert!(
6117            err.contains("one-shot") && err.contains("days"),
6118            "got: {err}"
6119        );
6120    }
6121
6122    #[test]
6123    fn validate_rejects_bad_day_name() {
6124        // A garbage DOW token is caught by the days pre-flight and
6125        // reported against `when.days`, not the confusing
6126        // "when.at lowered to invalid cron" (claude #432 review).
6127        let err = schedule_with(calendar("09:00", &["funday"]), RunsOn::Backend)
6128            .validate()
6129            .unwrap_err();
6130        assert!(err.contains("when.days"), "got: {err}");
6131        assert!(err.contains("funday"), "names the bad token: {err}");
6132        // a degenerate range like `mon-` reports the whole token, not
6133        // a cryptic empty part (claude #432 follow-up)
6134        let err = schedule_with(calendar("09:00", &["mon-"]), RunsOn::Backend)
6135            .validate()
6136            .unwrap_err();
6137        assert!(err.contains("'mon-'"), "names the whole token: {err}");
6138        // valid names / ranges / numeric / * all pass
6139        for ok in [
6140            calendar("09:00", &["mon-fri"]),
6141            calendar("09:00", &["mon", "wed", "sun"]),
6142            calendar("09:00", &["1-5"]),
6143        ] {
6144            schedule_with(ok.clone(), RunsOn::Backend)
6145                .validate()
6146                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6147        }
6148    }
6149
6150    #[test]
6151    fn validate_accepts_nth_weekday() {
6152        // #418: nth-weekday (Patch Tuesday). validate() also lowers to
6153        // a cron and parses it with croner, so passing here proves the
6154        // whole chain — token → DOW field → engine-acceptable cron.
6155        for ok in [
6156            calendar("09:00", &["tue#2"]),          // 2nd Tuesday
6157            calendar("09:00", &["fri#1"]),          // 1st Friday
6158            calendar("03:00", &["sun#5"]),          // 5th Sunday
6159            calendar("09:00", &["tue#2", "thu#2"]), // a list of nths
6160            calendar("09:00", &["2#2"]),            // numeric DOW + ordinal
6161            // Case-insensitive both sides: validate lowercases, croner
6162            // upper-cases the whole pattern before aliasing (claude #547).
6163            calendar("09:00", &["TUE#2"]),
6164        ] {
6165            schedule_with(ok.clone(), RunsOn::Backend)
6166                .validate()
6167                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6168        }
6169    }
6170
6171    #[test]
6172    fn validate_rejects_bad_nth_weekday() {
6173        // ordinal out of 1..5, a range with #, and a bad day before #.
6174        for bad in ["tue#0", "tue#6", "tue#x", "mon-fri#2", "funday#2"] {
6175            let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
6176                .validate()
6177                .unwrap_err();
6178            assert!(err.contains("when.days"), "for '{bad}', got: {err}");
6179        }
6180    }
6181
6182    #[test]
6183    fn validate_accepts_last_weekday() {
6184        // #418: last-weekday (`friL` = last Friday). Like the nth case,
6185        // validate() lowers to a cron and round-trips it through croner,
6186        // so passing proves token → DOW field → engine-acceptable cron
6187        // with the verified last-<dow>-of-month semantics.
6188        for ok in [
6189            calendar("09:00", &["friL"]),         // last Friday
6190            calendar("03:00", &["sunL"]),         // last Sunday
6191            calendar("22:00", &["5L"]),           // numeric DOW + last
6192            calendar("00:00", &["0L"]),           // numeric Sunday (0…
6193            calendar("00:00", &["7L"]),           // …and its 7 alias)
6194            calendar("09:00", &["monL", "friL"]), // a list of last-weekdays
6195            // Case-insensitive both the weekday and the `L` suffix:
6196            // validate lowercases the day, croner upper-cases the whole
6197            // pattern before aliasing (claude #547).
6198            calendar("09:00", &["FRIL"]),
6199            calendar("09:00", &["fril"]),
6200        ] {
6201            schedule_with(ok.clone(), RunsOn::Backend)
6202                .validate()
6203                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6204        }
6205    }
6206
6207    #[test]
6208    fn validate_rejects_bad_last_weekday() {
6209        // bare `L` (no weekday — a footgun croner reads as Saturday), a
6210        // range with L, a bad day before L, and an internal space that
6211        // would otherwise leak a malformed cron downstream (gemini #560).
6212        for bad in ["L", "l", "mon-friL", "fundayL", "8L", "*L", "fri L"] {
6213            let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
6214                .validate()
6215                .unwrap_err();
6216            assert!(err.contains("when.days"), "for '{bad}', got: {err}");
6217        }
6218    }
6219
6220    #[test]
6221    fn calendar_oneshot_instant_detects_past() {
6222        use chrono::TimeZone;
6223        // a dated `at` resolves to an absolute instant…
6224        let c = CalendarSpec {
6225            at: "2024-01-01 09:00".into(),
6226            days: vec![],
6227        };
6228        let t = c
6229            .oneshot_instant(ScheduleTz::Utc)
6230            .expect("one-shot instant");
6231        assert_eq!(
6232            t,
6233            chrono::Utc.with_ymd_and_hms(2024, 1, 1, 9, 0, 0).unwrap()
6234        );
6235        assert!(t < chrono::Utc::now(), "2024 is in the past");
6236        // …while a repeating (time-only) calendar has no instant
6237        let rep = CalendarSpec {
6238            at: "09:00".into(),
6239            days: vec!["mon-fri".into()],
6240        };
6241        assert!(rep.oneshot_instant(ScheduleTz::Utc).is_none());
6242    }
6243
6244    fn schedule_with_active(from: Option<&str>, until: Option<&str>) -> Schedule {
6245        let mut s = schedule_with(
6246            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6247            RunsOn::Backend,
6248        );
6249        s.active = Active {
6250            from: from.map(str::to_owned),
6251            until: until.map(str::to_owned),
6252        };
6253        s
6254    }
6255
6256    #[test]
6257    fn validate_accepts_active_window() {
6258        schedule_with_active(Some("2026-07-01"), Some("2026-08-01T12:00:00+09:00"))
6259            .validate()
6260            .expect("date + rfc3339 bounds should validate");
6261    }
6262
6263    #[test]
6264    fn validate_rejects_unparseable_active_bound() {
6265        let err = schedule_with_active(Some("July 1st"), None)
6266            .validate()
6267            .unwrap_err();
6268        assert!(err.contains("active"), "got: {err}");
6269    }
6270
6271    #[test]
6272    fn validate_rejects_from_not_before_until() {
6273        let err = schedule_with_active(Some("2026-08-01"), Some("2026-07-01"))
6274            .validate()
6275            .unwrap_err();
6276        assert!(err.contains("strictly before"), "got: {err}");
6277
6278        let err = schedule_with_active(Some("2026-07-01"), Some("2026-07-01"))
6279            .validate()
6280            .unwrap_err();
6281        assert!(err.contains("strictly before"), "got: {err}");
6282    }
6283
6284    // ---- Active window semantics ----
6285
6286    #[test]
6287    fn active_window_is_half_open() {
6288        use chrono::TimeZone;
6289        let active = Active {
6290            from: Some("2026-07-01".into()),
6291            until: Some("2026-08-01".into()),
6292        };
6293        // UTC tz so the date bounds are UTC midnight.
6294        let at = |y, m, d, h| chrono::Utc.with_ymd_and_hms(y, m, d, h, 0, 0).unwrap();
6295        let c = |t| active.contains(t, ScheduleTz::Utc);
6296        assert!(!c(at(2026, 6, 30, 23)), "before from");
6297        assert!(c(at(2026, 7, 1, 0)), "at from (inclusive)");
6298        assert!(c(at(2026, 7, 15, 12)), "inside");
6299        assert!(!c(at(2026, 8, 1, 0)), "at until (exclusive)");
6300        assert!(!c(at(2026, 8, 2, 0)), "after until");
6301    }
6302
6303    #[test]
6304    fn active_empty_window_is_always_active() {
6305        assert!(Active::default().contains(chrono::Utc::now(), ScheduleTz::Local));
6306    }
6307
6308    #[test]
6309    fn active_rfc3339_bound_honours_offset_regardless_of_tz() {
6310        use chrono::TimeZone;
6311        let active = Active {
6312            from: Some("2026-07-01T09:00:00+09:00".into()),
6313            until: None,
6314        };
6315        // RFC3339 carries its own offset → tz arg is ignored.
6316        // 09:00 JST = 00:00 UTC.
6317        for tz in [ScheduleTz::Utc, ScheduleTz::Local] {
6318            assert!(
6319                !active.contains(
6320                    chrono::Utc
6321                        .with_ymd_and_hms(2026, 6, 30, 23, 59, 0)
6322                        .unwrap(),
6323                    tz
6324                )
6325            );
6326            assert!(active.contains(
6327                chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap(),
6328                tz
6329            ));
6330        }
6331    }
6332
6333    #[test]
6334    fn active_date_bound_respects_tz() {
6335        // A bare `YYYY-MM-DD` bound is midnight *in the schedule's
6336        // tz* (#418 Phase 2). The UTC interpretation is exact and
6337        // host-independent; assert that precisely.
6338        use chrono::TimeZone;
6339        let utc = Active::parse_bound("2026-07-01", ScheduleTz::Utc).expect("utc");
6340        assert_eq!(
6341            utc,
6342            chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap()
6343        );
6344
6345        // The local interpretation must equal what chrono::Local
6346        // computes for the same wall-clock midnight — proves the tz
6347        // path is wired to the host zone (the magnitude vs UTC is
6348        // host-dependent, so we compare against Local directly rather
6349        // than hard-coding the JST offset, keeping CI green on UTC
6350        // runners).
6351        let local = Active::parse_bound("2026-07-01", ScheduleTz::Local).expect("local");
6352        let want = chrono::Local
6353            .with_ymd_and_hms(2026, 7, 1, 0, 0, 0)
6354            .single()
6355            .expect("local midnight is unambiguous")
6356            .with_timezone(&chrono::Utc);
6357        assert_eq!(local, want, "date bound resolved in host-local tz");
6358    }
6359
6360    #[test]
6361    fn active_empty_is_skipped_when_serialising() {
6362        let s = schedule_with(
6363            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6364            RunsOn::Backend,
6365        );
6366        let json = serde_json::to_value(&s).expect("serialise");
6367        assert!(
6368            json.get("active").is_none(),
6369            "empty active must not appear on the wire: {json}"
6370        );
6371    }
6372
6373    // ---- constraints.window (#418 Phase 3) ----
6374
6375    fn with_window(win: &str) -> Schedule {
6376        let mut s = schedule_with(
6377            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6378            RunsOn::Backend,
6379        );
6380        s.constraints.window = Some(win.into());
6381        s
6382    }
6383
6384    #[test]
6385    fn constraints_window_parses_and_round_trips() {
6386        let yaml = r#"
6387id: x
6388when:
6389  per_pc: { every: 6h }
6390job_id: y
6391target: { all: true }
6392constraints:
6393  window: "22:00-05:00"
6394"#;
6395        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6396        assert_eq!(s.constraints.window.as_deref(), Some("22:00-05:00"));
6397        let back: Schedule =
6398            serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
6399        assert_eq!(back.constraints.window.as_deref(), Some("22:00-05:00"));
6400    }
6401
6402    #[test]
6403    fn constraints_empty_is_skipped_when_serialising() {
6404        let s = schedule_with(
6405            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6406            RunsOn::Backend,
6407        );
6408        let json = serde_json::to_value(&s).expect("serialise");
6409        assert!(
6410            json.get("constraints").is_none(),
6411            "empty constraints must not appear on the wire: {json}"
6412        );
6413    }
6414
6415    #[test]
6416    fn window_no_constraint_always_allows() {
6417        let c = Constraints::default();
6418        assert!(c.allows(chrono::Utc::now(), ScheduleTz::Local));
6419    }
6420
6421    #[test]
6422    fn window_same_day_is_half_open() {
6423        use chrono::TimeZone;
6424        let s = with_window("09:00-17:00");
6425        let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
6426        let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
6427        assert!(!a(at(8, 59)), "before start");
6428        assert!(a(at(9, 0)), "at start (inclusive)");
6429        assert!(a(at(16, 59)), "inside");
6430        assert!(!a(at(17, 0)), "at end (exclusive)");
6431        assert!(!a(at(23, 0)), "after end");
6432    }
6433
6434    #[test]
6435    fn window_crossing_midnight() {
6436        use chrono::TimeZone;
6437        let s = with_window("22:00-05:00");
6438        let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
6439        let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
6440        assert!(a(at(22, 0)), "at start tonight");
6441        assert!(a(at(23, 30)), "late tonight");
6442        assert!(a(at(3, 0)), "early tomorrow");
6443        assert!(!a(at(5, 0)), "at end (exclusive)");
6444        assert!(!a(at(12, 0)), "midday outside");
6445        assert!(!a(at(21, 59)), "just before start");
6446    }
6447
6448    #[test]
6449    fn window_respects_tz() {
6450        // The same instant is inside the window under one tz and may
6451        // be outside under another. Compare UTC vs Local via the
6452        // host's own offset (kept CI-green on UTC runners like the
6453        // active tz test does).
6454        use chrono::TimeZone;
6455        let s = with_window("09:00-17:00");
6456        let noon_utc = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 12, 0, 0).unwrap();
6457        // Under UTC, 12:00 is inside 09:00-17:00.
6458        assert!(s.constraints.allows(noon_utc, ScheduleTz::Utc));
6459        // Under Local, the verdict tracks the host wall-clock time;
6460        // assert it matches a direct wall_time membership check.
6461        let local_t = noon_utc.with_timezone(&chrono::Local).time();
6462        let in_local = local_t >= chrono::NaiveTime::from_hms_opt(9, 0, 0).unwrap()
6463            && local_t < chrono::NaiveTime::from_hms_opt(17, 0, 0).unwrap();
6464        assert_eq!(s.constraints.allows(noon_utc, ScheduleTz::Local), in_local);
6465    }
6466
6467    #[test]
6468    fn validate_accepts_good_window() {
6469        for w in ["09:00-17:00", "22:00-05:00", "00:00-23:59"] {
6470            with_window(w)
6471                .validate()
6472                .unwrap_or_else(|e| panic!("'{w}' should validate: {e}"));
6473        }
6474    }
6475
6476    #[test]
6477    fn validate_rejects_bad_window() {
6478        for bad in ["9-5", "22:00", "22:00-22:00", "25:00-05:00", "09:00_17:00"] {
6479            let err = with_window(bad).validate().unwrap_err();
6480            assert!(
6481                err.contains("constraints.window"),
6482                "for '{bad}', got: {err}"
6483            );
6484        }
6485    }
6486
6487    // ---- constraints.skip_dates (#418 holiday exclusion) ----
6488
6489    fn with_skip_dates(dates: &[&str]) -> Schedule {
6490        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
6491        s.tz = ScheduleTz::Utc; // host-independent date assertions
6492        s.constraints.skip_dates = dates.iter().map(|d| (*d).to_string()).collect();
6493        s
6494    }
6495
6496    #[test]
6497    fn allows_blocks_listed_skip_date() {
6498        use chrono::TimeZone;
6499        let s = with_skip_dates(&["2026-06-10", "2026-12-25"]);
6500        // Any time on a listed date is blocked (whole day).
6501        let on = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap();
6502        assert!(!s.constraints.allows(on, ScheduleTz::Utc));
6503        let on_midnight = chrono::Utc.with_ymd_and_hms(2026, 12, 25, 0, 0, 0).unwrap();
6504        assert!(!s.constraints.allows(on_midnight, ScheduleTz::Utc));
6505        // A date not in the list fires normally.
6506        let off = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
6507        assert!(s.constraints.allows(off, ScheduleTz::Utc));
6508    }
6509
6510    #[test]
6511    fn allows_corrupt_skip_date_fails_closed() {
6512        use chrono::TimeZone;
6513        // A garbled entry (only reachable via hand-edited KV) blocks
6514        // rather than silently re-enabling fires — same posture as a
6515        // corrupt window.
6516        let s = with_skip_dates(&["not-a-date"]);
6517        let any = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
6518        assert!(!s.constraints.allows(any, ScheduleTz::Utc));
6519    }
6520
6521    #[test]
6522    fn validate_accepts_good_skip_dates() {
6523        with_skip_dates(&["2026-01-01", "2026-12-25", "2027-05-03"])
6524            .validate()
6525            .expect("well-formed skip dates should validate");
6526    }
6527
6528    #[test]
6529    fn validate_rejects_bad_skip_date() {
6530        for bad in ["2026-13-01", "01-01-2026", "nope", "2026/01/01"] {
6531            let err = with_skip_dates(&[bad]).validate().unwrap_err();
6532            assert!(
6533                err.contains("constraints.skip_dates"),
6534                "for '{bad}', got: {err}"
6535            );
6536        }
6537    }
6538
6539    #[test]
6540    fn preview_skips_holidays() {
6541        use chrono::TimeZone;
6542        // Daily 09:00 with two of the next five days marked as holidays
6543        // — preview drops exactly those, since it gates on `allows`.
6544        let mut s = cal_utc("09:00", &[]);
6545        s.constraints.skip_dates = vec!["2026-06-11".into(), "2026-06-13".into()];
6546        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
6547        let got = s.preview_fires(now, 4);
6548        let want: Vec<_> = [
6549            (2026, 6, 10),
6550            (2026, 6, 12), // skips 06-11
6551            (2026, 6, 14), // skips 06-13
6552            (2026, 6, 15),
6553        ]
6554        .iter()
6555        .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
6556        .collect();
6557        assert_eq!(got, want);
6558    }
6559
6560    // ---- constraints.max_concurrent (#418) ----
6561
6562    fn with_max_concurrent(max: u32, runs_on: RunsOn) -> Schedule {
6563        let mut s = schedule_with(
6564            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6565            runs_on,
6566        );
6567        s.constraints.max_concurrent = Some(max);
6568        s
6569    }
6570
6571    #[test]
6572    fn validate_accepts_backend_max_concurrent() {
6573        with_max_concurrent(5, RunsOn::Backend)
6574            .validate()
6575            .expect("backend max_concurrent should validate");
6576    }
6577
6578    #[test]
6579    fn validate_rejects_max_concurrent_on_agent() {
6580        // Decision E: a central running-instance cap needs a central
6581        // counter, which agents don't have.
6582        let err = with_max_concurrent(5, RunsOn::Agent)
6583            .validate()
6584            .unwrap_err();
6585        assert!(err.contains("constraints.max_concurrent"), "got: {err}");
6586        assert!(err.contains("runs_on: agent"), "got: {err}");
6587    }
6588
6589    #[test]
6590    fn validate_rejects_zero_max_concurrent() {
6591        let err = with_max_concurrent(0, RunsOn::Backend)
6592            .validate()
6593            .unwrap_err();
6594        assert!(err.contains("max_concurrent must be >= 1"), "got: {err}");
6595    }
6596
6597    #[test]
6598    fn max_concurrent_round_trips_and_skips_when_absent() {
6599        let s = with_max_concurrent(3, RunsOn::Backend);
6600        let json = serde_json::to_value(&s.constraints).expect("ser");
6601        assert_eq!(json.get("max_concurrent").and_then(|v| v.as_u64()), Some(3));
6602        // A schedule with no constraints omits the whole block.
6603        let bare = schedule_with(
6604            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6605            RunsOn::Backend,
6606        );
6607        assert!(bare.constraints.is_empty());
6608    }
6609
6610    #[test]
6611    fn window_fail_closed_on_corrupt_blob() {
6612        // A malformed window (only reachable via a hand-edited KV
6613        // blob — validate() rejects it at create) must BLOCK, not
6614        // silently allow fires during a change-freeze (gemini #452).
6615        let s = with_window("22:00_05:00");
6616        assert!(
6617            !s.constraints.allows(chrono::Utc::now(), ScheduleTz::Utc),
6618            "corrupt window fails closed"
6619        );
6620        // …and the scheduler can surface why it's stuck.
6621        assert!(
6622            s.bad_window().is_some(),
6623            "bad_window reports the parse error"
6624        );
6625        assert!(with_window("22:00-05:00").bad_window().is_none());
6626    }
6627
6628    #[test]
6629    fn calendar_outside_window_is_flagged() {
6630        // at 09:00 can never fall in 22:00-05:00 → never fires.
6631        let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
6632        s.constraints.window = Some("22:00-05:00".into());
6633        assert!(s.calendar_outside_window(), "09:00 is not in 22:00-05:00");
6634
6635        // at 23:00 IS inside the overnight window → fine.
6636        let mut s = schedule_with(calendar("23:00", &[]), RunsOn::Backend);
6637        s.constraints.window = Some("22:00-05:00".into());
6638        assert!(!s.calendar_outside_window(), "23:00 is in 22:00-05:00");
6639
6640        // reconcile shapes are never flagged (they poll every minute).
6641        let mut s = schedule_with(
6642            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6643            RunsOn::Backend,
6644        );
6645        s.constraints.window = Some("22:00-05:00".into());
6646        assert!(!s.calendar_outside_window(), "reconcile is unaffected");
6647
6648        // no window → never flagged.
6649        let s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
6650        assert!(!s.calendar_outside_window());
6651    }
6652
6653    // ---- on_failure.retry (#418 Phase 4) ----
6654
6655    fn with_retry(max: u32, backoff: &str) -> Schedule {
6656        let mut s = schedule_with(
6657            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6658            RunsOn::Backend,
6659        );
6660        s.on_failure.retry = Some(Retry {
6661            max,
6662            backoff: backoff.into(),
6663        });
6664        s
6665    }
6666
6667    #[test]
6668    fn on_failure_parses_and_round_trips() {
6669        let yaml = r#"
6670id: x
6671when:
6672  per_pc: { every: 6h }
6673job_id: y
6674target: { all: true }
6675on_failure:
6676  retry: { max: 3, backoff: 10m }
6677"#;
6678        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6679        let r = s.on_failure.retry.as_ref().expect("retry present");
6680        assert_eq!(r.max, 3);
6681        assert_eq!(r.backoff, "10m");
6682        let back: Schedule =
6683            serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
6684        assert_eq!(back.on_failure, s.on_failure);
6685    }
6686
6687    #[test]
6688    fn on_failure_empty_is_skipped_when_serialising() {
6689        let s = schedule_with(
6690            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6691            RunsOn::Backend,
6692        );
6693        let json = serde_json::to_value(&s).expect("serialise");
6694        assert!(
6695            json.get("on_failure").is_none(),
6696            "empty on_failure must not appear on the wire: {json}"
6697        );
6698    }
6699
6700    #[test]
6701    fn validate_accepts_good_retry() {
6702        for (max, backoff) in [(1, "30s"), (3, "10m"), (10, "1h")] {
6703            with_retry(max, backoff)
6704                .validate()
6705                .unwrap_or_else(|e| panic!("retry {{max:{max}, backoff:{backoff}}}: {e}"));
6706        }
6707    }
6708
6709    #[test]
6710    fn validate_rejects_bad_backoff() {
6711        let err = with_retry(3, "soon").validate().unwrap_err();
6712        assert!(err.contains("on_failure.retry.backoff"), "got: {err}");
6713    }
6714
6715    #[test]
6716    fn validate_rejects_sub_second_backoff() {
6717        // "500ms" parses as humantime but lowers to 0s on the wire —
6718        // reject it so the operator doesn't get a silent no-wait
6719        // (coderabbit #466).
6720        for bad in ["500ms", "0s", "999ms"] {
6721            let err = with_retry(3, bad).validate().unwrap_err();
6722            assert!(
6723                err.contains("on_failure.retry.backoff must be >= 1s"),
6724                "for '{bad}', got: {err}"
6725            );
6726        }
6727    }
6728
6729    #[test]
6730    fn validate_rejects_out_of_range_max() {
6731        for bad in [0u32, 11, 1000] {
6732            let err = with_retry(bad, "10m").validate().unwrap_err();
6733            assert!(
6734                err.contains("on_failure.retry.max"),
6735                "for max={bad}, got: {err}"
6736            );
6737        }
6738    }
6739
6740    #[test]
6741    fn lowered_retry_reduces_backoff_to_seconds() {
6742        let s = with_retry(3, "10m");
6743        let spec = s.on_failure.lowered_retry().expect("a retry policy");
6744        assert_eq!(spec.max, 3);
6745        assert_eq!(spec.backoff_secs, 600);
6746    }
6747
6748    #[test]
6749    fn lowered_retry_is_none_without_policy() {
6750        let s = schedule_with(
6751            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6752            RunsOn::Backend,
6753        );
6754        assert!(s.on_failure.lowered_retry().is_none());
6755    }
6756
6757    // ---- global change-freeze (#418 Phase 5) ----
6758
6759    #[test]
6760    fn freeze_empty_window_is_always_active() {
6761        // The big-red-button shape: no bounds = frozen until cleared.
6762        let f = Freeze::default();
6763        assert!(f.is_active(chrono::Utc::now()));
6764    }
6765
6766    #[test]
6767    fn freeze_window_is_half_open() {
6768        use chrono::TimeZone;
6769        let f = Freeze {
6770            from: Some("2026-12-20T00:00:00+00:00".into()),
6771            until: Some("2027-01-05T00:00:00+00:00".into()),
6772            reason: Some("year-end".into()),
6773            tz: ScheduleTz::Utc,
6774        };
6775        let at = |y, mo, d| chrono::Utc.with_ymd_and_hms(y, mo, d, 0, 0, 0).unwrap();
6776        assert!(!f.is_active(at(2026, 12, 19)), "before from = not frozen");
6777        assert!(f.is_active(at(2026, 12, 20)), "from is inclusive");
6778        assert!(f.is_active(at(2026, 12, 31)), "inside window");
6779        assert!(!f.is_active(at(2027, 1, 5)), "until is exclusive");
6780        assert!(!f.is_active(at(2027, 1, 6)), "after until = not frozen");
6781    }
6782
6783    #[test]
6784    fn freeze_fails_closed_on_corrupt_bound() {
6785        // A freeze is a safety switch: an unparseable bound (only
6786        // reachable via a hand-edited KV blob) must read as FROZEN, not
6787        // "fire normally" (coderabbit #472) — the opposite of `active`,
6788        // which fail-opens.
6789        let f = Freeze {
6790            from: Some("not-a-date".into()),
6791            until: None,
6792            reason: None,
6793            tz: ScheduleTz::Utc,
6794        };
6795        assert!(f.is_active(chrono::Utc::now()), "corrupt bound → frozen");
6796    }
6797
6798    #[test]
6799    fn freeze_validate_accepts_good_bounds() {
6800        Freeze {
6801            from: Some("2026-12-20".into()),
6802            until: Some("2027-01-05T12:00:00+09:00".into()),
6803            reason: None,
6804            tz: ScheduleTz::Local,
6805        }
6806        .validate()
6807        .expect("date + rfc3339 bounds should validate");
6808        // Empty (indefinite) freeze is valid.
6809        Freeze::default().validate().expect("empty freeze is valid");
6810    }
6811
6812    #[test]
6813    fn freeze_validate_rejects_bad_bound_and_inverted_window() {
6814        let err = Freeze {
6815            from: Some("never".into()),
6816            ..Default::default()
6817        }
6818        .validate()
6819        .unwrap_err();
6820        assert!(err.contains("freeze:"), "got: {err}");
6821
6822        let inverted = Freeze {
6823            from: Some("2027-01-05".into()),
6824            until: Some("2026-12-20".into()),
6825            ..Default::default()
6826        }
6827        .validate()
6828        .unwrap_err();
6829        assert!(inverted.contains("freeze.from"), "got: {inverted}");
6830    }
6831
6832    #[test]
6833    fn freeze_round_trips_and_skips_empty_fields() {
6834        let f = Freeze {
6835            from: None,
6836            until: Some("2027-01-05".into()),
6837            reason: Some("INC-1234".into()),
6838            tz: ScheduleTz::Utc,
6839        };
6840        let json = serde_json::to_value(&f).expect("serialise");
6841        assert!(json.get("from").is_none(), "empty from omitted: {json}");
6842        let back: Freeze = serde_json::from_value(json).expect("round-trip");
6843        assert_eq!(back, f);
6844    }
6845
6846    #[test]
6847    fn shipped_schedule_configs_parse_and_validate() {
6848        // Every YAML under configs/schedules/ must parse with the
6849        // current Schedule serde AND pass validate() — keeps the
6850        // shipped examples from drifting out of sync with the model
6851        // (#418 removed back-compat, so drift = broken at create).
6852        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../configs/schedules");
6853        let mut seen = 0;
6854        for entry in std::fs::read_dir(&dir).expect("read configs/schedules") {
6855            let path = entry.expect("dir entry").path();
6856            if path.extension().and_then(|e| e.to_str()) != Some("yaml") {
6857                continue;
6858            }
6859            let body = std::fs::read_to_string(&path).expect("read yaml");
6860            let s: Schedule = serde_yaml::from_str(&body)
6861                .unwrap_or_else(|e| panic!("{} failed to parse: {e}", path.display()));
6862            s.validate()
6863                .unwrap_or_else(|e| panic!("{} failed validate(): {e}", path.display()));
6864            seen += 1;
6865        }
6866        assert!(seen > 0, "no schedule YAMLs found in {}", dir.display());
6867    }
6868
6869    // ---- pre-existing enum wire formats (unchanged by #418) ----
6870
6871    #[test]
6872    fn exec_mode_serialises_snake_case() {
6873        for (mode, expected) in [
6874            (ExecMode::EveryTick, "every_tick"),
6875            (ExecMode::OncePerPc, "once_per_pc"),
6876            (ExecMode::OncePerTarget, "once_per_target"),
6877        ] {
6878            let s = serde_json::to_value(mode).expect("serialise");
6879            assert_eq!(s, serde_json::Value::String(expected.into()));
6880            let back: ExecMode = serde_json::from_value(serde_json::Value::String(expected.into()))
6881                .expect("deserialise");
6882            assert_eq!(back, mode, "round-trip for {expected}");
6883        }
6884    }
6885
6886    #[test]
6887    fn schedule_runs_on_defaults_to_backend() {
6888        let yaml = r#"
6889id: x
6890when:
6891  per_pc: once
6892job_id: y
6893target: { all: true }
6894"#;
6895        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6896        assert_eq!(s.runs_on, RunsOn::Backend);
6897    }
6898
6899    #[test]
6900    fn schedule_runs_on_agent_parses() {
6901        let yaml = r#"
6902id: offline-inv
6903when:
6904  per_pc: { every: 1h }
6905job_id: inventory-hw
6906target: { all: true }
6907runs_on: agent
6908"#;
6909        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6910        assert_eq!(s.runs_on, RunsOn::Agent);
6911        assert_eq!(s.lowered().mode, ExecMode::OncePerPc);
6912    }
6913
6914    #[test]
6915    fn runs_on_serialises_snake_case() {
6916        for (mode, expected) in [(RunsOn::Backend, "backend"), (RunsOn::Agent, "agent")] {
6917            let s = serde_json::to_value(mode).expect("serialise");
6918            assert_eq!(s, serde_json::Value::String(expected.into()));
6919            let back: RunsOn = serde_json::from_value(serde_json::Value::String(expected.into()))
6920                .expect("deserialise");
6921            assert_eq!(back, mode);
6922        }
6923    }
6924
6925    #[test]
6926    fn execute_shell_into_wire_shell() {
6927        assert_eq!(Shell::from(ExecuteShell::Powershell), Shell::Powershell);
6928        assert_eq!(Shell::from(ExecuteShell::Cmd), Shell::Cmd);
6929    }
6930
6931    #[test]
6932    fn manifest_staleness_defaults_to_cached() {
6933        let yaml = r#"
6934id: x
6935version: 1.0.0
6936execute:
6937  shell: powershell
6938  script: "echo"
6939  timeout: 1s
6940"#;
6941        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
6942        assert_eq!(m.staleness, Staleness::Cached);
6943    }
6944
6945    #[test]
6946    fn manifest_strict_staleness_parses() {
6947        let yaml = r#"
6948id: urgent-patch
6949version: 2.5.1
6950execute:
6951  shell: powershell
6952  script: Install-Hotfix
6953  timeout: 5m
6954staleness:
6955  mode: strict
6956  max_cache_age: 0s
6957"#;
6958        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
6959        match m.staleness {
6960            Staleness::Strict { max_cache_age } => assert_eq!(max_cache_age, "0s"),
6961            other => panic!("expected strict, got {other:?}"),
6962        }
6963    }
6964
6965    #[test]
6966    fn manifest_unchecked_staleness_parses() {
6967        let yaml = r#"
6968id: legacy
6969version: 0.1.0
6970execute:
6971  shell: cmd
6972  script: "echo"
6973  timeout: 1s
6974staleness:
6975  mode: unchecked
6976"#;
6977        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
6978        assert_eq!(m.staleness, Staleness::Unchecked);
6979    }
6980
6981    #[test]
6982    fn missing_required_field_errors() {
6983        // `id` missing.
6984        let yaml = r#"
6985version: 1.0.0
6986target: { all: true }
6987execute:
6988  shell: powershell
6989  script: "echo"
6990  timeout: 1s
6991"#;
6992        let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
6993        assert!(r.is_err(), "expected error, got {:?}", r);
6994    }
6995
6996    #[test]
6997    fn display_field_table_kind_round_trips_with_nested_columns() {
6998        // #39: `type: table` + `columns:` on a DisplayField gets
6999        // round-tripped through serde so the SPA receives the
7000        // nested schema verbatim. Nested columns themselves are
7001        // DisplayFields so they can carry `type: bytes` /
7002        // `type: number` for cell formatting.
7003        let yaml = r#"
7004id: inv-hw
7005version: 1.0.0
7006execute:
7007  shell: powershell
7008  script: "echo"
7009  timeout: 60s
7010inventory:
7011  display:
7012    - field: hostname
7013      label: Hostname
7014    - field: disks
7015      label: Disks
7016      type: table
7017      columns:
7018        - field: device_id
7019          label: Drive
7020        - field: size_bytes
7021          label: Size
7022          type: bytes
7023        - field: free_bytes
7024          label: Free
7025          type: bytes
7026        - field: file_system
7027          label: FS
7028"#;
7029        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7030        let inv = m.inventory.as_ref().expect("inventory hint");
7031        let disks = inv
7032            .display
7033            .iter()
7034            .find(|d| d.field == "disks")
7035            .expect("disks display row");
7036        assert_eq!(disks.kind.as_deref(), Some("table"));
7037        let cols = disks.columns.as_ref().expect("table needs columns");
7038        assert_eq!(cols.len(), 4);
7039        assert_eq!(cols[1].field, "size_bytes");
7040        assert_eq!(cols[1].kind.as_deref(), Some("bytes"));
7041    }
7042
7043    #[test]
7044    fn display_field_scalar_kind_keeps_columns_none() {
7045        // Defensive: when type is a scalar (`bytes` / `number` /
7046        // `timestamp`) the `columns` field stays None — the SPA
7047        // uses its presence as the "render nested table" signal,
7048        // so it must not leak in via serde defaults.
7049        let yaml = r#"
7050id: x
7051version: 1.0.0
7052execute:
7053  shell: powershell
7054  script: "echo"
7055  timeout: 5s
7056inventory:
7057  display:
7058    - { field: ram_bytes, label: RAM, type: bytes }
7059"#;
7060        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7061        let inv = m.inventory.as_ref().unwrap();
7062        assert!(inv.display[0].columns.is_none());
7063    }
7064
7065    // ---- checked-in JSON Schema freshness (docs/schemas/) ----
7066
7067    /// The JSON Schemas under `docs/schemas/` must match what
7068    /// `schema_for!` produces today — a Cargo.lock-style freshness guard
7069    /// so a `Schedule` / `Manifest` field change can't silently drift
7070    /// the operator-facing schema. The SPA editor, the backend
7071    /// `/api/schemas/*` endpoints, and these files all read the same
7072    /// derived shape; this test fails CI if the checked-in copy lags.
7073    /// Regenerate with:
7074    ///   `UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current`
7075    #[test]
7076    fn schema_files_are_current() {
7077        assert_schema_file("schedule.schema.json", &schemars::schema_for!(Schedule));
7078        assert_schema_file("job.schema.json", &schemars::schema_for!(Manifest));
7079        assert_schema_file("view.schema.json", &schemars::schema_for!(View));
7080    }
7081
7082    fn assert_schema_file(name: &str, schema: &schemars::Schema) {
7083        let generated = serde_json::to_string_pretty(schema).expect("serialize schema") + "\n";
7084        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7085            .join("../../docs/schemas")
7086            .join(name);
7087        if std::env::var_os("UPDATE_SCHEMAS").is_some() {
7088            std::fs::create_dir_all(path.parent().unwrap()).expect("mkdir docs/schemas");
7089            std::fs::write(&path, &generated).unwrap_or_else(|e| panic!("write {path:?}: {e}"));
7090            return;
7091        }
7092        // Normalize CRLF→LF before comparing: `.gitattributes` already
7093        // pins these files to `eol=lf`, but a stray CRLF working-tree
7094        // copy (autocrlf, a tool rewrite) shouldn't turn a *content*-
7095        // freshness check into a confusing line-ending failure — that's
7096        // .gitattributes' job, not this test's (gemini #588).
7097        let on_disk = std::fs::read_to_string(&path)
7098            .unwrap_or_else(|e| {
7099                panic!(
7100                    "read {path:?}: {e}\n\
7101                     generate it with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
7102                )
7103            })
7104            .replace("\r\n", "\n");
7105        assert_eq!(
7106            on_disk, generated,
7107            "{name} is stale — a Schedule/Manifest schema change isn't reflected in docs/schemas/. \
7108             Refresh with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
7109        );
7110    }
7111}
7112
7113/// Periodic schedule (spec §2.4.3). v0.18.0 carries the fanout plan
7114/// (target + optional rollout + optional jitter) inline; the
7115/// referenced job (`job_id` → [`BUCKET_JOBS`]) supplies only the
7116/// script body. Two schedules of the same job can target different
7117/// groups on different cadences without copying the manifest.
7118///
7119/// #418 Phase 1: the cadence is the single [`When`] field. The old
7120/// `cron` × `mode` × `cooldown` × `auto_disable_when_done` quartet
7121/// is gone (no back-compat — pre-Phase-1 KV blobs fail to parse and
7122/// are warn-skipped; re-`schedule create` to upgrade them). The
7123/// engine underneath is unchanged: [`Schedule::lowered`] maps `when`
7124/// onto the same (cron, ExecMode, cooldown) trio the scheduler and
7125/// `decide_fire` always ran on.
7126#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
7127pub struct Schedule {
7128    pub id: String,
7129    /// When to fire — a reconcile cadence (`per_pc` / `per_target`)
7130    /// or a calendar time trigger (`at` / `days`). See [`When`].
7131    ///
7132    /// `singleton_map`: serde_yaml 0.9 renders externally-tagged
7133    /// enums as `!per_pc` YAML tags by default; this keeps the
7134    /// operator-facing map shape (`when: { per_pc: once }`). JSON
7135    /// output is identical either way, and the schemars schema
7136    /// (external tagging = oneOf of single-key objects) already
7137    /// matches the singleton-map wire shape.
7138    #[serde(with = "serde_yaml::with::singleton_map")]
7139    #[schemars(with = "When")]
7140    pub when: When,
7141    /// Key into [`crate::kv::BUCKET_JOBS`]. Must equal a registered
7142    /// Manifest's `id`.
7143    pub job_id: String,
7144    /// Who + how-to-phase + when-to-stagger. The Manifest doesn't
7145    /// carry these any more — same job + different fanout = different
7146    /// schedule.
7147    #[serde(flatten)]
7148    pub plan: FanoutPlan,
7149    /// Optional validity window. Outside `[from, until)` the
7150    /// schedule is dormant — still registered, still visible, but
7151    /// every tick is skipped (deleted ≠ dormant: a campaign that
7152    /// ended stays inspectable and can be re-armed by editing the
7153    /// window). Checked at tick time on both the backend scheduler
7154    /// and the agent's local scheduler.
7155    #[serde(default, skip_serializing_if = "Active::is_empty")]
7156    pub active: Active,
7157    /// #418 operational constraints gating *when within an active
7158    /// period* a fire may happen: a maintenance `window`, a fleet
7159    /// `max_concurrent` cap, and `skip_dates` (holiday exclusion). The
7160    /// wall-clock ones are evaluated in the schedule's `tz`; future
7161    /// `require` (env gates) lands in the same namespace. Checked at
7162    /// tick time on both schedulers (and surfaced by `preview`).
7163    #[serde(default, skip_serializing_if = "Constraints::is_empty")]
7164    pub constraints: Constraints,
7165    /// #418 Phase 4: what to do after a fire's script comes back
7166    /// failed. Currently just `retry` (fixed-backoff in-process
7167    /// re-run); future `notify` / `disable` join the same namespace.
7168    /// Applied fire-side in `handle_command` (the retry policy is
7169    /// lowered onto every Command this schedule produces), so it
7170    /// covers both `runs_on` locations.
7171    #[serde(default, skip_serializing_if = "OnFailure::is_empty")]
7172    pub on_failure: OnFailure,
7173    /// #418 Phase 2: the timezone this schedule's wall-clock fields
7174    /// are evaluated in — both the calendar `at` firing time AND the
7175    /// `active.{from,until}` window bounds. `local` (default) = the
7176    /// running host's TZ (the agent's for `runs_on: agent`, the
7177    /// backend server's otherwise); `utc` for TZ-independent
7178    /// schedules. Reconcile shapes (`per_pc`/`per_target`) ignore it
7179    /// for firing (poll cron runs every minute regardless) but still
7180    /// honor it for the `active` window.
7181    #[serde(default)]
7182    pub tz: ScheduleTz,
7183    /// v0.22: optional humantime window after a cron tick during
7184    /// which the Command is still considered "live". The scheduler
7185    /// computes `tick_at + starting_deadline` and stamps it onto
7186    /// each Command as `deadline_at`; agents skip Commands they
7187    /// receive after that absolute time. `None` (default) = no
7188    /// deadline, meaning a Command queued in the broker / stream
7189    /// during agent downtime runs whenever the agent reconnects —
7190    /// good for kitting / inventory / cleanup. Set this for
7191    /// time-of-day notifications, lunch reminders, etc., where
7192    /// "fire 3 hours late" would be wrong.
7193    #[serde(default, skip_serializing_if = "Option::is_none")]
7194    pub starting_deadline: Option<String>,
7195    /// v0.23: where does the cron tick happen? `Backend` (default,
7196    /// historical) = backend's scheduler fires Commands via NATS;
7197    /// agents passively receive. `Agent` = each targeted agent runs
7198    /// its own internal cron and fires locally, so the schedule
7199    /// keeps ticking even when the broker is unreachable (laptop on
7200    /// the train, broker maintenance window, full WAN outage). The
7201    /// two locations are mutually exclusive — when `Agent`, the
7202    /// backend scheduler stays out and just keeps the definition in
7203    /// KV for agents to read.
7204    #[serde(default)]
7205    pub runs_on: RunsOn,
7206    #[serde(default = "default_true")]
7207    pub enabled: bool,
7208    /// Free-form operator taxonomy for the Schedules page — the
7209    /// schedule-side mirror of `Manifest.tags` (added in #640; a plain
7210    /// code ref rather than an intra-doc link, since that field isn't
7211    /// on this branch until #640 merges). Purely a SPA-side
7212    /// organisational aid (search / filter chips alongside the
7213    /// id-prefix grouping); the scheduler never reads it, so any
7214    /// string is allowed and it carries no firing semantics. A
7215    /// schedule's own tags are independent of its job's: the same job
7216    /// may back a `weekly` maintenance schedule and a `canary` rollout
7217    /// schedule. Empty by default and `skip_serializing_if`-elided per
7218    /// the #492 gradual-upgrade wire rule.
7219    #[serde(default, skip_serializing_if = "Vec::is_empty")]
7220    pub tags: Vec<String>,
7221    /// GitOps provenance (#695) — see [`RepoOrigin`]. Stamped by
7222    /// `kanade schedule create` when the source YAML lives inside a Git
7223    /// work tree, so the SPA renders the schedule read-only and points
7224    /// edits back at the repo (SPEC design principle #3: 設定駆動 YAML +
7225    /// Git), parity with a job's [`Manifest::origin`]. `None` for
7226    /// SPA-born schedules and ones applied from outside any repo. Purely
7227    /// informational — the scheduler never reads it. New field ⇒ #492
7228    /// wire rule (`default` + `skip_serializing_if`).
7229    #[serde(default, skip_serializing_if = "Option::is_none")]
7230    pub origin: Option<RepoOrigin>,
7231}
7232
7233impl Schedule {
7234    /// Every valid top-level key on a Schedule YAML/JSON document —
7235    /// this struct's own fields PLUS the fields of the
7236    /// `#[serde(flatten)] plan: FanoutPlan`. The strict create
7237    /// boundary needs this because serde's flatten buffering hides
7238    /// unknown top-level keys from `serde_ignored`, so a typo like
7239    /// `jiter:` or `enabledd:` would otherwise be silently dropped
7240    /// (#924). Kept in sync with the field list by
7241    /// `schedule_top_level_keys_cover_serialized_fields`.
7242    pub const TOP_LEVEL_KEYS: &'static [&'static str] = &[
7243        // Schedule's own fields:
7244        "id",
7245        "when",
7246        "job_id",
7247        "active",
7248        "constraints",
7249        "on_failure",
7250        "tz",
7251        "starting_deadline",
7252        "runs_on",
7253        "enabled",
7254        "tags",
7255        "origin",
7256        // flattened FanoutPlan:
7257        "target",
7258        "rollout",
7259        "jitter",
7260        "deadline_at",
7261    ];
7262}
7263
7264impl crate::strict::StrictSchema for Schedule {
7265    fn strict_top_level_keys() -> Option<&'static [&'static str]> {
7266        Some(Self::TOP_LEVEL_KEYS)
7267    }
7268}
7269
7270/// Manifest has no `#[serde(flatten)]` field, so `serde_ignored`
7271/// already catches every top-level typo — the default (`None`) is
7272/// correct.
7273impl crate::strict::StrictSchema for Manifest {}
7274
7275/// View likewise has no flattened field.
7276impl crate::strict::StrictSchema for View {}
7277
7278/// v0.23 — where the cron tick fires from.
7279#[derive(
7280    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
7281)]
7282#[serde(rename_all = "snake_case")]
7283pub enum RunsOn {
7284    /// Backend's central scheduler ticks and publishes Commands to
7285    /// NATS. Historical default, what every pre-v0.23 schedule
7286    /// uses. Agent offline ⇒ Command queued in STREAM_EXEC; agent
7287    /// reconnects ⇒ catch-up via [`command_replay`](crate)
7288    /// (see kanade-agent's command_replay module).
7289    #[default]
7290    Backend,
7291    /// Each targeted agent runs the cron tick locally. Survives
7292    /// broker / WAN outages. Best for laptops / mobile devices that
7293    /// roam off the corporate network. Agent must be online for the
7294    /// initial schedule + job-catalog pull, but once cached the
7295    /// agent fires the script standalone.
7296    Agent,
7297}
7298
7299/// Per-pc/per-target dedup semantics for a [`Schedule`] (v0.19).
7300#[derive(
7301    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
7302)]
7303#[serde(rename_all = "snake_case")]
7304pub enum ExecMode {
7305    /// Fire on every cron tick at the whole target. Historical
7306    /// (pre-v0.19) behavior; no dedup.
7307    #[default]
7308    EveryTick,
7309    /// Fire at each pc until that pc succeeds; then skip it until
7310    /// the optional cooldown elapses (or forever if no cooldown).
7311    /// Use for kitting / first-boot / per-pc compliance checks.
7312    OncePerPc,
7313    /// Fire at the whole target until **any** pc succeeds; then
7314    /// skip the whole target until the optional cooldown elapses
7315    /// (or forever if no cooldown). Use for "one delegate is
7316    /// enough" tasks like license check-in.
7317    OncePerTarget,
7318    /// #418 OS-native event trigger (`when: { on: [...] }`). There is
7319    /// no cron — the agent fires it from an OS event source (boot /
7320    /// session-change), not a tick — so the scheduler skips
7321    /// `tokio-cron` registration for it. Each event occurrence fires
7322    /// once, gated by the standard freeze / active / window /
7323    /// skip_dates checks.
7324    Event,
7325}
7326
7327/// #418 Phase 1 — the single "when does this fire" axis.
7328///
7329/// Replaces the old `cron` + `mode` + `cooldown` trio whose
7330/// interactions were implicit (cron doubled as both a real
7331/// time-of-day trigger and a reconcile poll period; contradictory
7332/// combinations silently no-opped). Two shapes:
7333///
7334/// * **reconcile** (`per_pc` / `per_target`) — desired-state: "each
7335///   pc (or one delegate) should have run this within `every`".
7336///   The poll period is system-generated ([`POLL_CRON`], every
7337///   minute) and no longer the operator's concern.
7338/// * **calendar** (`{ at, days }`) — a wall-clock time trigger
7339///   (#418 Phase 2, replacing the old raw-cron escape hatch). Fires
7340///   the whole target at the given time, no dedup. `at: "09:00"` +
7341///   `days` repeats; `at: "2026-06-10 09:00"` (a date+time) fires
7342///   exactly once. Evaluated in the schedule's top-level `tz`.
7343#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7344#[serde(rename_all = "snake_case")]
7345pub enum When {
7346    /// Fire at each targeted pc: `once` (kitting — succeed once,
7347    /// skip forever, forever catching brand-new / re-imaged pcs)
7348    /// or `{ every: <humantime> }` (patrol — re-arm per pc after
7349    /// the interval).
7350    PerPc(PerPolicy),
7351    /// Fire until **any** one pc of the target succeeds, then skip
7352    /// the whole target (`once`) or re-arm after `every`. Needs
7353    /// fleet-wide completion data, so it is backend-only —
7354    /// `runs_on: agent` + `per_target` is rejected by
7355    /// [`Schedule::validate`].
7356    PerTarget(PerPolicy),
7357    /// Calendar time trigger: `{ at: "09:00", days: [mon-fri] }`
7358    /// (repeating) or `{ at: "2026-06-10 09:00" }` (one-shot). Fires
7359    /// the whole target at that wall-clock time in the schedule's
7360    /// `tz` — no dedup, no cooldown.
7361    Calendar(CalendarSpec),
7362    /// #418 OS-native event trigger: `when: { on: [startup, logon] }`.
7363    /// Fires when the agent observes the listed OS event(s) rather than
7364    /// on a clock — there is no cron. `runs_on: agent` only (the agent
7365    /// owns the event source); [`Schedule::validate`] rejects it on
7366    /// `backend` and rejects an empty list. Each event occurrence fires
7367    /// once, gated by the same freeze / active / `constraints.window` /
7368    /// `skip_dates` checks as the cron path. `startup` fires once per OS
7369    /// boot (deduped via the host boot time); a `starting_deadline`, if
7370    /// set, limits it to "agent came up within that long after boot".
7371    On(Vec<OnTrigger>),
7372}
7373
7374/// An OS event the agent can fire a schedule on (#418 `when: { on }`).
7375#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash)]
7376#[serde(rename_all = "snake_case")]
7377pub enum OnTrigger {
7378    /// Once per OS boot (the agent's first run for that boot). Catches
7379    /// freshly-imaged / reinstalled hosts at their next startup.
7380    Startup,
7381    /// On an interactive-session user logon — console, RDP, or
7382    /// auto-logon (Windows `WTS_SESSION_LOGON`). Does not fire for
7383    /// service / network / batch logons (no interactive session).
7384    Logon,
7385    /// When the workstation is locked (Win+L / idle lock; Windows
7386    /// `WTS_SESSION_LOCK`). Use for step-away compliance / cleanup.
7387    Lock,
7388    /// When the workstation is unlocked — the user returns to a locked
7389    /// session (Windows `WTS_SESSION_UNLOCK`). Use to re-check
7390    /// compliance / refresh state when work resumes.
7391    Unlock,
7392    /// When the host's network changes — IP address table change on
7393    /// connect / disconnect / DHCP renew / VPN / Wi-Fi roam (Windows
7394    /// `NotifyAddrChange`). Debounced agent-side (a burst of changes
7395    /// from one transition fires once after the network settles), so
7396    /// use it for "re-check connectivity / re-register on network move"
7397    /// rather than expecting one fire per raw adapter event.
7398    ///
7399    /// IPv4 only: `NotifyAddrChange` watches the IPv4 address table, so a
7400    /// transition that touches only IPv6 addresses won't fire. In practice
7401    /// dual-stack networks change both tables together, but a pure-IPv6
7402    /// move (e.g. an IPv6-only Wi-Fi roam) is not detected.
7403    NetworkChange,
7404}
7405
7406/// Calendar time trigger (#418 Phase 2). `at` is either a time of
7407/// day (`"HH:MM"`, repeating — combine with `days`) or a full
7408/// date+time (`"YYYY-MM-DD HH:MM"`, a one-shot that fires once and
7409/// never again). Evaluated in the schedule's top-level `tz`.
7410#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7411pub struct CalendarSpec {
7412    /// `"HH:MM"` (24h) for a repeating trigger, or
7413    /// `"YYYY-MM-DD HH:MM"` (hyphen / slash / `T` separators all
7414    /// accepted) for a one-shot. Parsed lazily —
7415    /// [`Schedule::validate`] rejects garbage at create time.
7416    pub at: String,
7417    /// Day-of-week filter for a time-of-day `at`: `["mon-fri"]`,
7418    /// `["mon","wed","fri"]`, … (passed verbatim to the cron DOW
7419    /// field, so ranges and names both work). An **nth-weekday**
7420    /// `["tue#2"]` fires only on the 2nd Tuesday of each month
7421    /// ("Patch Tuesday"); the ordinal is `1..5`. A **last-weekday**
7422    /// `["friL"]` fires only on the last Friday of each month (handy
7423    /// for monthly maintenance). Empty = every day. Must be empty
7424    /// when `at` carries a date (the date already pins the day).
7425    #[serde(default, skip_serializing_if = "Vec::is_empty")]
7426    pub days: Vec<String>,
7427}
7428
7429/// Parsed `CalendarSpec.at`: the wall-clock minute/hour, plus the
7430/// date for a one-shot (`None` = repeating time-of-day).
7431struct ParsedAt {
7432    minute: u32,
7433    hour: u32,
7434    date: Option<chrono::NaiveDate>,
7435}
7436
7437impl CalendarSpec {
7438    /// Parse `at`: a date+time (`YYYY-MM-DD HH:MM`, hyphen / slash /
7439    /// `T` separators) is a one-shot; a bare `HH:MM` is repeating.
7440    fn parse_at(&self) -> Result<ParsedAt, String> {
7441        use chrono::Timelike;
7442        let s = self.at.trim();
7443        for fmt in ["%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y/%m/%d %H:%M"] {
7444            if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, fmt) {
7445                return Ok(ParsedAt {
7446                    minute: dt.minute(),
7447                    hour: dt.hour(),
7448                    date: Some(dt.date()),
7449                });
7450            }
7451        }
7452        if let Ok(t) = chrono::NaiveTime::parse_from_str(s, "%H:%M") {
7453            return Ok(ParsedAt {
7454                minute: t.minute(),
7455                hour: t.hour(),
7456                date: None,
7457            });
7458        }
7459        Err(format!(
7460            "when.at: unparseable '{}' (want HH:MM or YYYY-MM-DD HH:MM)",
7461            self.at
7462        ))
7463    }
7464
7465    /// Pre-flight check on the `days` tokens so a bad day name gives
7466    /// a `when.days:`-scoped error instead of croner's confusing
7467    /// "when.at lowered to invalid cron" (claude #432 review). Each
7468    /// token is a day name (`mon`..`sun`), a numeric DOW (`0`..`7`),
7469    /// `*`, a `-` range of those, an **nth-weekday** like `tue#2`
7470    /// (2nd Tuesday of the month — "Patch Tuesday"), or a
7471    /// **last-weekday** like `friL` (last Friday of the month).
7472    fn validate_days(&self) -> Result<(), String> {
7473        const NAMES: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
7474        let is_day = |p: &str| NAMES.contains(&p) || p.parse::<u8>().is_ok_and(|n| n <= 7);
7475        for tok in &self.days {
7476            // Report the whole token on a malformed range like `mon-`
7477            // (which would otherwise split to a cryptic empty part —
7478            // claude #432 follow-up).
7479            let invalid = |reason: &str| {
7480                Err(format!(
7481                    "when.days: invalid day token '{tok}' ({reason}; \
7482                     want mon..sun, 0-7, a range like mon-fri, an nth-weekday \
7483                     like tue#2, a last-weekday like friL, or *)"
7484                ))
7485            };
7486            // #418: nth-weekday suffix (`tue#2` = 2nd Tuesday). Croner
7487            // accepts `<dow>#<n>` (n = 1..5) in the DOW field, and
7488            // `to_cron` passes the token through verbatim, so the
7489            // engine fires only on that occurrence. It's a single
7490            // weekday + ordinal — not combinable with a range.
7491            if let Some((day_part, nth_part)) = tok.split_once('#') {
7492                // Normalize once and use `d` consistently (gemini #547);
7493                // the outer `invalid` already echoes the raw `tok`.
7494                let d = day_part.trim().to_ascii_lowercase();
7495                if d.contains('-') || !is_day(&d) {
7496                    return invalid("the part before # must be a single weekday");
7497                }
7498                match nth_part.trim().parse::<u8>() {
7499                    Ok(n) if (1..=5).contains(&n) => {}
7500                    _ => return invalid("the # ordinal must be 1..5 (e.g. tue#2 = 2nd Tuesday)"),
7501                }
7502                continue;
7503            }
7504            // #418: last-weekday suffix (`friL` = last Friday of the
7505            // month — the monthly-maintenance sibling of Patch Tuesday).
7506            // Croner accepts `<dow>L` in the DOW field with verified
7507            // last-<dow>-of-month semantics, and `to_cron` passes it
7508            // through verbatim. A single weekday + `L` — bare `L` and
7509            // ranges are rejected (croner would read bare `L` as
7510            // Saturday, which is a confusing footgun).
7511            if let Some(day_part) = tok.strip_suffix(['L', 'l']) {
7512                // No `.trim()`: a cron DOW token can't carry internal
7513                // whitespace, so `"fri L"` must be *rejected* here (its
7514                // strip leaves `"fri "`, and `is_day` catches the space)
7515                // rather than trimmed into a clean `"fri"` that then
7516                // produces a malformed `fri L` cron downstream and a
7517                // confusing croner error (gemini #560).
7518                let d = day_part.to_ascii_lowercase();
7519                if d.is_empty() {
7520                    return invalid("`L` (last-weekday) needs a weekday before it, e.g. friL");
7521                }
7522                if d.contains('-') || !is_day(&d) {
7523                    return invalid(
7524                        "the part before L must be a single weekday (e.g. friL = last Friday)",
7525                    );
7526                }
7527                continue;
7528            }
7529            for part in tok.split('-') {
7530                let p = part.trim().to_ascii_lowercase();
7531                if p.is_empty() {
7532                    return invalid("empty range bound");
7533                }
7534                if p != "*" && !is_day(&p) {
7535                    return invalid(&format!("'{part}' is not a day"));
7536                }
7537            }
7538        }
7539        Ok(())
7540    }
7541
7542    /// For a one-shot (`at` carries a date), the absolute instant it
7543    /// fires in `tz`. `None` for a repeating calendar. Used to warn
7544    /// about a one-shot whose date is already in the past (it would
7545    /// never fire).
7546    pub fn oneshot_instant(&self, tz: ScheduleTz) -> Option<chrono::DateTime<chrono::Utc>> {
7547        let p = self.parse_at().ok()?;
7548        let date = p.date?;
7549        let naive = date.and_hms_opt(p.hour, p.minute, 0)?;
7550        tz.naive_to_utc(naive)
7551    }
7552
7553    /// The wall-clock time-of-day this calendar fires at (`None` if
7554    /// `at` is unparseable — validate() guards that). Used to detect
7555    /// a calendar whose fire time can never fall inside its
7556    /// `constraints.window` (claude #452 review).
7557    pub fn fire_time(&self) -> Option<chrono::NaiveTime> {
7558        let p = self.parse_at().ok()?;
7559        chrono::NaiveTime::from_hms_opt(p.hour, p.minute, 0)
7560    }
7561
7562    /// Lower to the cron string the scheduler engine runs. Repeating
7563    /// → 6-field `0 {min} {hour} * * {dow}`; one-shot → 7-field
7564    /// `0 {min} {hour} {day} {month} * {year}` (a past year never
7565    /// fires — that's what makes it one-shot).
7566    fn to_cron(&self) -> Result<String, String> {
7567        use chrono::Datelike;
7568        let ParsedAt { minute, hour, date } = self.parse_at()?;
7569        match date {
7570            Some(d) => {
7571                if !self.days.is_empty() {
7572                    return Err(
7573                        "when.at with a date is a one-shot and cannot be combined with days".into(),
7574                    );
7575                }
7576                Ok(format!(
7577                    "0 {minute} {hour} {} {} * {}",
7578                    d.day(),
7579                    d.month(),
7580                    d.year()
7581                ))
7582            }
7583            None => {
7584                let dow = if self.days.is_empty() {
7585                    "*".to_string()
7586                } else {
7587                    self.validate_days()?;
7588                    self.days.join(",")
7589                };
7590                Ok(format!("0 {minute} {hour} * * {dow}"))
7591            }
7592        }
7593    }
7594}
7595
7596/// The timezone a schedule's wall-clock fields (`when.at`,
7597/// `active.{from,until}`) are evaluated in (#418 Phase 2).
7598#[derive(
7599    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
7600)]
7601#[serde(rename_all = "snake_case")]
7602pub enum ScheduleTz {
7603    /// The running host's local timezone — the agent's for
7604    /// `runs_on: agent`, the backend server's otherwise. Default.
7605    #[default]
7606    Local,
7607    /// UTC — for timezone-independent schedules.
7608    Utc,
7609}
7610
7611impl ScheduleTz {
7612    /// Interpret a naive (zoneless) datetime as being in this tz and
7613    /// convert to UTC. On a DST *fold* (the local time occurs twice
7614    /// when clocks go back) we pick `.earliest()` rather than
7615    /// rejecting it; `None` is reserved for a true DST *gap* (a local
7616    /// time that never exists). `Utc` is fixed-offset so neither ever
7617    /// happens; `Local` is whatever timezone the running host is set
7618    /// to and *can* hit a gap/fold on any DST-observing host — not
7619    /// just the JST we run today (gemini + claude #432 review).
7620    fn naive_to_utc(self, naive: chrono::NaiveDateTime) -> Option<chrono::DateTime<chrono::Utc>> {
7621        use chrono::TimeZone;
7622        match self {
7623            ScheduleTz::Utc => Some(chrono::DateTime::from_naive_utc_and_offset(
7624                naive,
7625                chrono::Utc,
7626            )),
7627            ScheduleTz::Local => chrono::Local
7628                .from_local_datetime(&naive)
7629                .earliest()
7630                .map(|dt| dt.with_timezone(&chrono::Utc)),
7631        }
7632    }
7633
7634    /// The wall-clock time-of-day `now` reads as in this tz — used by
7635    /// [`Constraints::allows`] to test a maintenance window
7636    /// (#418 Phase 3). `Utc` is the naive UTC time; `Local` is the
7637    /// running host's local time.
7638    fn wall_time(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveTime {
7639        match self {
7640            ScheduleTz::Utc => now.time(),
7641            ScheduleTz::Local => now.with_timezone(&chrono::Local).time(),
7642        }
7643    }
7644
7645    /// The wall-clock *date* `now` reads as in this tz — used by
7646    /// [`Constraints::allows`] to test `skip_dates` (#418 holiday
7647    /// exclusion). Same tz semantics as [`Self::wall_time`].
7648    fn wall_date(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveDate {
7649        match self {
7650            ScheduleTz::Utc => now.date_naive(),
7651            ScheduleTz::Local => now.with_timezone(&chrono::Local).date_naive(),
7652        }
7653    }
7654
7655    /// Stable lowercase wire/display label (`local` / `utc`) — matches
7656    /// the serde `snake_case` representation. Used for the preview
7657    /// response's `tz` field so the JSON shape isn't coupled to the
7658    /// `Debug` repr (claude #578 review).
7659    pub fn as_str(self) -> &'static str {
7660        match self {
7661            ScheduleTz::Local => "local",
7662            ScheduleTz::Utc => "utc",
7663        }
7664    }
7665}
7666
7667impl std::fmt::Display for ScheduleTz {
7668    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7669        f.write_str(self.as_str())
7670    }
7671}
7672
7673/// `once` vs `{ every: <humantime> }` — shared by `per_pc` /
7674/// `per_target`. Untagged so the YAML stays the bare keyword or a
7675/// one-key map, nothing more ceremonial.
7676#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7677#[serde(untagged)]
7678pub enum PerPolicy {
7679    /// The bare string `once`: succeed once, then skip permanently
7680    /// (cooldown = infinity).
7681    Once(OnceLiteral),
7682    /// Re-arm after the humantime interval, e.g. `{ every: 6h }`.
7683    Every(EverySpec),
7684}
7685
7686/// Single-variant enum so serde accepts exactly the string `once`
7687/// (a free-form `String` would swallow typos like `onec`).
7688#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
7689#[serde(rename_all = "snake_case")]
7690pub enum OnceLiteral {
7691    Once,
7692}
7693
7694/// `{ every: <humantime> }`. Standalone struct (not an inline
7695/// struct variant). `{ evry: 6h }` still fails to parse (the
7696/// required `every` key is missing), and the create boundaries
7697/// reject the unknown `evry` via [`crate::strict`] with its path —
7698/// while agents reading a future writer's extra fields tolerate
7699/// them (#492).
7700#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7701pub struct EverySpec {
7702    /// Humantime interval (`10m`, `6h`, `1d`...). Parsed lazily —
7703    /// [`Schedule::validate`] rejects garbage at create time.
7704    pub every: String,
7705}
7706
7707impl PerPolicy {
7708    /// The cooldown this policy lowers to: `once` = `None`
7709    /// (permanent skip), `every` = the interval.
7710    fn cooldown(&self) -> Option<String> {
7711        match self {
7712            PerPolicy::Once(_) => None,
7713            PerPolicy::Every(EverySpec { every }) => Some(every.clone()),
7714        }
7715    }
7716}
7717
7718impl std::fmt::Display for When {
7719    /// Operator-facing one-liner (`per_pc once` / `per_pc every 6h`
7720    /// / `at 09:00 [mon-fri]` / `at 2026-06-10 09:00`) for log
7721    /// lines, audit payloads and the API's `ScheduleSummary`.
7722    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7723        let policy = |p: &PerPolicy| match p {
7724            PerPolicy::Once(_) => "once".to_string(),
7725            PerPolicy::Every(EverySpec { every }) => format!("every {every}"),
7726        };
7727        match self {
7728            When::PerPc(p) => write!(f, "per_pc {}", policy(p)),
7729            When::PerTarget(p) => write!(f, "per_target {}", policy(p)),
7730            When::Calendar(c) if c.days.is_empty() => write!(f, "at {}", c.at),
7731            When::Calendar(c) => write!(f, "at {} [{}]", c.at, c.days.join(",")),
7732            When::On(triggers) => {
7733                let names: Vec<&str> = triggers.iter().map(|t| t.as_str()).collect();
7734                write!(f, "on [{}]", names.join(","))
7735            }
7736        }
7737    }
7738}
7739
7740impl OnTrigger {
7741    /// Lowercase wire/display label (matches the serde `snake_case`).
7742    pub fn as_str(self) -> &'static str {
7743        match self {
7744            OnTrigger::Startup => "startup",
7745            OnTrigger::Logon => "logon",
7746            OnTrigger::Lock => "lock",
7747            OnTrigger::Unlock => "unlock",
7748            OnTrigger::NetworkChange => "network_change",
7749        }
7750    }
7751}
7752
7753/// Optional validity window for a [`Schedule`] (#418 decision G).
7754/// Half-open `[from, until)`; either bound may be omitted. Bounds
7755/// are `YYYY-MM-DD` (= that day's 00:00 in the schedule's `tz`) or
7756/// full RFC3339 (offset is honored as-is, `tz` ignored). Kept as
7757/// strings so the JSON Schema the SPA editor consumes stays two
7758/// plain string fields, mirroring `jitter` / `starting_deadline`.
7759///
7760/// #418 Phase 2: bounds are evaluated in the schedule's top-level
7761/// `tz` (was UTC-only in Phase 1) so `tz: local` makes both the
7762/// calendar `at` AND the `active` window local — one consistent
7763/// timezone per schedule.
7764#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
7765pub struct Active {
7766    /// Dormant before this instant.
7767    #[serde(default, skip_serializing_if = "Option::is_none")]
7768    pub from: Option<String>,
7769    /// Dormant from this instant on (exclusive).
7770    #[serde(default, skip_serializing_if = "Option::is_none")]
7771    pub until: Option<String>,
7772}
7773
7774impl Active {
7775    /// `skip_serializing_if` helper — an empty window means "always
7776    /// active" and is omitted from the wire format entirely.
7777    pub fn is_empty(&self) -> bool {
7778        self.from.is_none() && self.until.is_none()
7779    }
7780
7781    /// Parse one bound: RFC3339 first (offset honored, `tz`
7782    /// ignored), then bare `YYYY-MM-DD` (00:00 in `tz`).
7783    pub fn parse_bound(s: &str, tz: ScheduleTz) -> Result<chrono::DateTime<chrono::Utc>, String> {
7784        if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
7785            return Ok(dt.with_timezone(&chrono::Utc));
7786        }
7787        if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
7788            let midnight = d.and_hms_opt(0, 0, 0).expect("00:00:00 is always valid");
7789            return tz.naive_to_utc(midnight).ok_or_else(|| {
7790                format!("active: bound '{s}' falls in a DST gap for the schedule's tz")
7791            });
7792        }
7793        Err(format!(
7794            "active: unparseable bound '{s}' (want YYYY-MM-DD or RFC3339)"
7795        ))
7796    }
7797
7798    /// Is `now` inside the window? Unparseable bounds are treated
7799    /// as absent here (fail-open) — [`Schedule::validate`] is the
7800    /// place that rejects them loudly; this runs on every tick and
7801    /// must never panic on a stale KV blob.
7802    pub fn contains(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
7803        let bound = |s: &Option<String>| s.as_deref().and_then(|s| Self::parse_bound(s, tz).ok());
7804        if bound(&self.from).is_some_and(|from| now < from) {
7805            return false;
7806        }
7807        if bound(&self.until).is_some_and(|until| now >= until) {
7808            return false;
7809        }
7810        true
7811    }
7812}
7813
7814/// Host-environment gate (#418 `constraints.require`). Fire only when
7815/// the target host is in the required state. Sensed **in-process by the
7816/// agent** (Win32), so it is `runs_on: agent` only — the backend cannot
7817/// read a target host's power/idle state ([`Schedule::validate`]
7818/// rejects it on `runs_on: backend`, symmetric with `when: { on }`).
7819///
7820/// Evaluated at fire time as a skip-this-tick gate (NOT in
7821/// [`Constraints::allows`], which stays pure for `preview`): a reconcile
7822/// cadence re-checks every minute (so it effectively defers until the
7823/// state is met — the intended pairing); a `calendar` fire that lands
7824/// while the state is unmet is simply missed, same as `window`. It is
7825/// therefore a *runtime* gate and does not appear in `preview`.
7826// No `Eq`: `cpu_below: Option<f64>` is only `PartialEq` (f64 is not Eq).
7827#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
7828pub struct Require {
7829    /// Fire only while on **AC power** (skip on battery). Reads
7830    /// `GetSystemPowerStatus`; an unknown/unreadable status is treated
7831    /// as not-on-AC (fail-closed — a restrictive gate must not fire
7832    /// when it can't confirm the condition). `false` (default) = no
7833    /// power requirement.
7834    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
7835    pub ac_power: bool,
7836    /// Fire only when the active console session has had **no keyboard /
7837    /// mouse input for at least this long** (humantime, e.g. `"10m"`) —
7838    /// "don't run while the user is actively working". Input-based
7839    /// (simpler than Task Scheduler's CPU/disk-aware idle). A
7840    /// headless / disconnected console (no interactive user) trivially
7841    /// satisfies it. `None` (default) = no idle requirement. Parsed
7842    /// lazily; [`Schedule::validate`] rejects garbage at create time.
7843    #[serde(default, skip_serializing_if = "Option::is_none")]
7844    pub idle: Option<String>,
7845    /// Fire only when the **whole-machine CPU usage is below this
7846    /// percent** (0–100; e.g. `20.0` = "system CPU < 20%") — "don't run
7847    /// while the box is busy". Reuses the agent's `host_perf` system CPU%
7848    /// sample (`sysinfo` mean over cores), so the reading is up to one
7849    /// `host_perf` cadence old (default 60s) — fine as a "generally
7850    /// busy?" proxy, and more accurate than a fresh one-shot read (CPU%
7851    /// needs two samples). An unavailable sample (host_perf not warmed
7852    /// up yet, or stale) is treated as "not below" (fail-closed — a
7853    /// restrictive gate must not fire when it can't confirm). `None`
7854    /// (default) = no CPU requirement. [`Schedule::validate`] rejects an
7855    /// out-of-range value at create time.
7856    #[serde(default, skip_serializing_if = "Option::is_none")]
7857    pub cpu_below: Option<f64>,
7858    /// Fire only when the host has **internet connectivity** (Windows
7859    /// `GetNetworkConnectivityHint` reports InternetAccess) — "don't run
7860    /// until online" for jobs that download / phone home. A captive
7861    /// portal (ConstrainedInternetAccess), LAN-only (LocalAccess), or
7862    /// unknown/unreadable state is treated as offline (fail-closed) — a
7863    /// portal would just fail a download, so we hold the run. For VPN /
7864    /// SASE / app-specific conditions, use a custom script gate (separate
7865    /// slice). `false` (default) = no network requirement.
7866    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
7867    pub network: bool,
7868}
7869
7870impl Require {
7871    /// `skip_serializing_if` helper for an embedded empty `require`.
7872    pub fn is_empty(&self) -> bool {
7873        !self.ac_power && self.idle.is_none() && self.cpu_below.is_none() && !self.network
7874    }
7875
7876    /// Parsed minimum-idle duration (`None` = no idle requirement, or an
7877    /// unparseable value — `validate` rejects the latter at create time).
7878    pub fn min_idle(&self) -> Option<std::time::Duration> {
7879        self.idle
7880            .as_deref()
7881            .and_then(|s| humantime::parse_duration(s.trim()).ok())
7882    }
7883
7884    /// First unparseable field for create-time rejection (mirrors
7885    /// [`Constraints::bad_skip_date`]).
7886    pub fn bad_idle(&self) -> Option<String> {
7887        self.idle.as_deref().and_then(|s| {
7888            humantime::parse_duration(s.trim())
7889                .err()
7890                .map(|e| format!("constraints.require.idle: invalid duration '{s}': {e}"))
7891        })
7892    }
7893}
7894
7895/// Host-environment state sensed by the agent, fed to [`require_met`].
7896/// A named struct (not positional args) so the growing set of sensed
7897/// signals — several of them `bool` — can't be transposed at a call
7898/// site. The Win32 sensing lives in `kanade-agent::env_gate`.
7899#[derive(Debug, Clone, Copy, Default)]
7900pub struct EnvState {
7901    /// Is the host on AC power (`false` if on battery or unreadable).
7902    pub ac_online: bool,
7903    /// How long the console has been idle (`None` = couldn't determine).
7904    pub idle: Option<std::time::Duration>,
7905    /// Whole-machine CPU usage 0–100 (`None` = no sample yet).
7906    pub cpu_pct: Option<f64>,
7907    /// Does the host have internet connectivity (`false` if offline /
7908    /// LAN-only / unreadable).
7909    pub network_up: bool,
7910}
7911
7912/// Pure env-gate decision (#418 `constraints.require`). The Win32
7913/// sensing lives in the agent (`kanade-agent::env_gate`); this is the
7914/// testable core, fed the already-sensed [`EnvState`]. Deliberately a
7915/// free fn (not folded into [`Constraints::allows`]) so `allows` stays
7916/// pure and `preview` never evaluates a runtime gate. Each set
7917/// requirement is a restrictive AND: any unmet (or unknown) gate skips.
7918pub fn require_met(req: &Require, env: &EnvState) -> bool {
7919    if req.ac_power && !env.ac_online {
7920        return false;
7921    }
7922    if let Some(min) = req.min_idle() {
7923        match env.idle {
7924            Some(d) if d >= min => {}
7925            _ => return false,
7926        }
7927    }
7928    if let Some(max) = req.cpu_below {
7929        match env.cpu_pct {
7930            Some(p) if p < max => {}
7931            _ => return false,
7932        }
7933    }
7934    if req.network && !env.network_up {
7935        return false;
7936    }
7937    true
7938}
7939
7940/// [`Active`] decides *over what date range* a schedule is live,
7941/// `Constraints` decides *when, within an active period,* a fire is
7942/// allowed: `window` (a maintenance time-of-day window),
7943/// `max_concurrent` (a fleet-wide running-instance cap), `skip_dates`
7944/// (holiday exclusion) and `require` (host-environment gates, agent-only
7945/// — see [`Require`]).
7946// No `Eq`: contains `require: Option<Require>` which holds an f64.
7947#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
7948pub struct Constraints {
7949    /// `"HH:MM-HH:MM"` wall-clock window (evaluated in the schedule's
7950    /// `tz`). Fires outside it are skipped — mainly for reconcile
7951    /// cadences ("patrol every 6h, but only fire overnight") and
7952    /// daytime change-freezes. `start > end` crosses midnight
7953    /// (`"22:00-05:00"` = 22:00 through 05:00 next morning). Parsed
7954    /// lazily; [`Schedule::validate`] rejects garbage at create time.
7955    #[serde(default, skip_serializing_if = "Option::is_none")]
7956    pub window: Option<String>,
7957    /// Fleet-wide cap on how many instances of this schedule's job may
7958    /// run **at the same time** (#418 "同時実行ハード上限"). The
7959    /// backend scheduler counts the job's still-in-flight runs
7960    /// (`execution_results.finished_at IS NULL`) each tick and only
7961    /// dispatches to as many remaining pcs as there are free slots —
7962    /// a rolling window that refills as runs complete. Useful for
7963    /// disk/CPU/network-heavy jobs you don't want hammering the whole
7964    /// fleet at once.
7965    ///
7966    /// **Backend-only** (it needs a central counter): combining it
7967    /// with `runs_on: agent` is rejected by [`Schedule::validate`]
7968    /// (#418 decision E — "中央上限には中央が要る"). Most meaningful
7969    /// for `per_pc` reconcile cadences, where the poll re-ticks and
7970    /// refills slots. `None` (default) = no cap.
7971    #[serde(default, skip_serializing_if = "Option::is_none")]
7972    pub max_concurrent: Option<u32>,
7973    /// Calendar dates the schedule must **not** fire on — holidays,
7974    /// blackout days, one-off freeze dates (#418 "祝日除外"). Each is
7975    /// `YYYY-MM-DD`, evaluated as a wall-clock date in the schedule's
7976    /// `tz`. Applies to every `when` shape (a reconcile cadence skips
7977    /// the whole day; a calendar fire landing on the date is
7978    /// suppressed) and is honored by both the live scheduler and
7979    /// `preview`, since both gate on [`Constraints::allows`]. Empty
7980    /// (default) = no skips. Operator-supplied: there is no built-in
7981    /// holiday calendar — list the dates you care about. Parsed lazily;
7982    /// [`Schedule::validate`] rejects a malformed date at create time.
7983    #[serde(default, skip_serializing_if = "Vec::is_empty")]
7984    pub skip_dates: Vec<String>,
7985    /// Host-environment gate (#418): fire only when the target host is
7986    /// in the required state (on AC power, idle). Agent-sensed at fire
7987    /// time, `runs_on: agent` only. See [`Require`]. `None` (default) =
7988    /// no environment requirement.
7989    #[serde(default, skip_serializing_if = "Option::is_none")]
7990    pub require: Option<Require>,
7991}
7992
7993impl Constraints {
7994    /// `skip_serializing_if` helper — empty constraints are omitted
7995    /// from the wire format entirely.
7996    pub fn is_empty(&self) -> bool {
7997        self.window.is_none()
7998            && self.max_concurrent.is_none()
7999            && self.skip_dates.is_empty()
8000            && self.require.as_ref().is_none_or(Require::is_empty)
8001    }
8002
8003    /// The first unparseable `skip_dates` entry, if any — the
8004    /// scheduler logs it at register time so a fail-closed
8005    /// (never-firing) schedule from a hand-edited KV blob is
8006    /// diagnosable, mirroring [`Schedule::bad_window`].
8007    pub fn bad_skip_date(&self) -> Option<String> {
8008        self.skip_dates.iter().find_map(|s| {
8009            chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d")
8010                .err()
8011                .map(|e| format!("constraints.skip_dates: invalid date '{s}': {e}"))
8012        })
8013    }
8014
8015    /// Parse `"HH:MM-HH:MM"` into `(start, end)`. Equal bounds are an
8016    /// error (a zero-width or all-day window is ambiguous — write no
8017    /// window for "always").
8018    pub fn parse_window(s: &str) -> Result<(chrono::NaiveTime, chrono::NaiveTime), String> {
8019        let (a, b) = s
8020            .split_once('-')
8021            .ok_or_else(|| format!("constraints.window: '{s}' must be 'HH:MM-HH:MM'"))?;
8022        let parse = |part: &str| {
8023            chrono::NaiveTime::parse_from_str(part.trim(), "%H:%M")
8024                .map_err(|e| format!("constraints.window: invalid time '{}': {e}", part.trim()))
8025        };
8026        let (start, end) = (parse(a)?, parse(b)?);
8027        if start == end {
8028            return Err(format!(
8029                "constraints.window: start and end are equal ('{s}'); omit window for 'always'"
8030            ));
8031        }
8032        Ok((start, end))
8033    }
8034
8035    /// Is a fire allowed at `now` (evaluated in `tz`)? No window =
8036    /// always allowed. Half-open `[start, end)`; `start > end`
8037    /// crosses midnight.
8038    ///
8039    /// **Fail-closed** on an unparseable window (returns `false`,
8040    /// gemini #452 review): a window is a *restrictive* constraint
8041    /// (change-freeze / overnight-only), so a corrupt one must NOT
8042    /// silently allow fires during the restricted hours. Bad windows
8043    /// are rejected at create time by [`Schedule::validate`]; this
8044    /// only bites a hand-edited KV blob, where blocking is the safe
8045    /// direction. The scheduler warns at register time
8046    /// ([`Schedule::bad_window`]) so a stuck schedule is diagnosable.
8047    /// The tick path never panics regardless.
8048    pub fn allows(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
8049        // #418 holiday / blackout dates: never fire on a listed wall
8050        // date (in `tz`). Checked before the window since a skipped day
8051        // overrides any within-window allowance. Fail-closed on a
8052        // corrupt entry (same posture as `window`): a skip date is a
8053        // *restrictive* constraint, so a garbled one must not silently
8054        // re-enable fires — it blocks until fixed (`validate` rejects it
8055        // at create time; `bad_skip_date` lets the scheduler warn).
8056        if !self.skip_dates.is_empty() {
8057            let today = tz.wall_date(now);
8058            let blocked = self.skip_dates.iter().any(|s| {
8059                match chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d") {
8060                    Ok(d) => d == today,
8061                    Err(_) => true, // corrupt entry → fail-closed (block)
8062                }
8063            });
8064            if blocked {
8065                return false;
8066            }
8067        }
8068        match self.window.as_deref() {
8069            // No window → always allowed.
8070            None => true,
8071            // Window set: membership, or fail-closed if unparseable
8072            // (`window_contains` returns None for a corrupt window).
8073            Some(_) => self.window_contains(tz.wall_time(now)).unwrap_or(false),
8074        }
8075    }
8076
8077    /// Membership of a wall-clock time-of-day in the window. `None`
8078    /// when there is no window or it's unparseable (callers decide
8079    /// the failure direction). `start > end` crosses midnight.
8080    fn window_contains(&self, t: chrono::NaiveTime) -> Option<bool> {
8081        let (start, end) = Self::parse_window(self.window.as_deref()?).ok()?;
8082        Some(if start <= end {
8083            start <= t && t < end
8084        } else {
8085            t >= start || t < end
8086        })
8087    }
8088}
8089
8090/// What to do when a fire's script fails (#418 Phase 4 — the "高"
8091/// retry/backoff gap). Where [`Constraints`] gates *whether* a fire
8092/// happens, `OnFailure` decides what happens *after* one ran and
8093/// came back bad. Only `retry` so far; future `notify` / `disable`
8094/// would join the same namespace.
8095#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
8096pub struct OnFailure {
8097    /// Re-run the script in-process when it exits non-zero (or times
8098    /// out), up to a cap, with a fixed backoff between attempts.
8099    /// `None` (default) = no retry: a failed run is published as-is
8100    /// and (for reconcile cadences) simply re-fires on the next poll
8101    /// tick. See [`Retry`].
8102    #[serde(default, skip_serializing_if = "Option::is_none")]
8103    pub retry: Option<Retry>,
8104}
8105
8106impl OnFailure {
8107    /// `skip_serializing_if` helper — an empty policy is omitted from
8108    /// the wire format entirely.
8109    pub fn is_empty(&self) -> bool {
8110        self.retry.is_none()
8111    }
8112
8113    /// Lower the operator-facing `retry` (humantime backoff) onto the
8114    /// engine vocabulary the agent's executor runs on (backoff in
8115    /// whole seconds). Single seam shared by the backend command
8116    /// builder and the agent's local scheduler so the two stamp the
8117    /// same [`crate::wire::RetrySpec`] onto every Command. Returns
8118    /// `None` when there is no retry policy or the backoff is
8119    /// unparseable (validate() rejects the latter at create time;
8120    /// this stays fail-safe = "no retry" for a hand-edited KV blob
8121    /// rather than panicking on the fire path).
8122    pub fn lowered_retry(&self) -> Option<crate::wire::RetrySpec> {
8123        let r = self.retry.as_ref()?;
8124        let backoff_secs = humantime::parse_duration(&r.backoff).ok()?.as_secs();
8125        Some(crate::wire::RetrySpec {
8126            max: r.max,
8127            backoff_secs,
8128        })
8129    }
8130}
8131
8132/// Fixed-backoff retry policy (#418 Phase 4). `max` is the number of
8133/// *additional* attempts after the first run (so `max: 3` = up to 4
8134/// total executions); `backoff` is the humantime delay slept between
8135/// attempts. The retry happens fire-side (inside `kanade fire` /
8136/// `handle_command`) on every OS for the PoC — the Windows-native
8137/// "restart on failure" Task Scheduler path is deferred to the
8138/// native-delegation phase (#418 decision H).
8139#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8140pub struct Retry {
8141    /// Max additional attempts after the first failure. Bounded
8142    /// `1..=10` by [`Schedule::validate`] — a typo'd `max: 1000`
8143    /// with a short backoff would otherwise pin a flapping script in
8144    /// a tight loop for the whole window.
8145    pub max: u32,
8146    /// Humantime delay slept between attempts (`"10m"`, `"30s"`).
8147    pub backoff: String,
8148}
8149
8150/// Fleet-wide change-freeze (#418 Phase 5 — the "メンテナンス窓 /
8151/// 変更凍結" gap's global half). Where [`Constraints::window`] is a
8152/// *per-schedule* time-of-day gate, a `Freeze` is a *single, fleet-
8153/// global* "stop all automated change" switch the operator flips
8154/// during an incident or a year-end change-freeze. It lives in its
8155/// own KV singleton ([`crate::kv::KEY_FREEZE`]); when present and
8156/// active, both the backend scheduler and every agent's local
8157/// scheduler skip *every* fire.
8158///
8159/// Shapes:
8160/// * `{}` (no bounds) — frozen indefinitely until the operator
8161///   clears it (incident "big red button").
8162/// * `{ from, until }` — frozen only within `[from, until)`,
8163///   evaluated in `tz` (planned change-freeze; auto-thaws).
8164///
8165/// The KV key being *absent* means "not frozen" — so clearing the
8166/// freeze is a KV delete, and `is_active` only ever runs on a freeze
8167/// the operator actually set.
8168#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
8169pub struct Freeze {
8170    /// Frozen from this instant (RFC3339 or bare `YYYY-MM-DD` in
8171    /// `tz`). `None` ⇒ frozen from the beginning of time.
8172    #[serde(default, skip_serializing_if = "Option::is_none")]
8173    pub from: Option<String>,
8174    /// Thawed from this instant on, exclusive. `None` ⇒ frozen with
8175    /// no scheduled end (manual clear required).
8176    #[serde(default, skip_serializing_if = "Option::is_none")]
8177    pub until: Option<String>,
8178    /// Operator-supplied note surfaced on the freeze-skip log and the
8179    /// SPA banner ("year-end change freeze", "INC-1234"). Advisory.
8180    #[serde(default, skip_serializing_if = "Option::is_none")]
8181    pub reason: Option<String>,
8182    /// Timezone the bare-date bounds are evaluated in (RFC3339 bounds
8183    /// carry their own offset). Defaults to host-local like a
8184    /// schedule's `tz`.
8185    #[serde(default)]
8186    pub tz: ScheduleTz,
8187}
8188
8189impl Freeze {
8190    /// Is the fleet frozen at `now`? An empty window (`from`/`until`
8191    /// both absent) is frozen unconditionally; otherwise membership of
8192    /// `[from, until)` in `tz`. Half-open like [`Active::contains`],
8193    /// but **fails CLOSED** on an unparseable bound — a freeze is a
8194    /// safety switch, so a corrupt window (only reachable via a
8195    /// hand-edited KV blob; `validate` rejects it at set time) must
8196    /// mean "frozen", not "fire normally" (coderabbit #472). This is
8197    /// the one deliberate divergence from `active`'s fail-OPEN
8198    /// behaviour, where an unparseable bound dormant-skips a schedule.
8199    pub fn is_active(&self, now: chrono::DateTime<chrono::Utc>) -> bool {
8200        // Parse a bound; an unparseable one short-circuits the whole
8201        // check to `true` (frozen) via the closure's `None` sentinel
8202        // handled below.
8203        let bound = |s: &Option<String>| -> Result<Option<chrono::DateTime<chrono::Utc>>, ()> {
8204            match s.as_deref() {
8205                None => Ok(None),
8206                Some(raw) => Active::parse_bound(raw, self.tz).map(Some).map_err(|_| ()),
8207            }
8208        };
8209        let (from, until) = match (bound(&self.from), bound(&self.until)) {
8210            (Ok(f), Ok(u)) => (f, u),
8211            // Any corrupt bound → fail closed (frozen).
8212            _ => return true,
8213        };
8214        if from.is_some_and(|f| now < f) {
8215            return false;
8216        }
8217        if until.is_some_and(|u| now >= u) {
8218            return false;
8219        }
8220        true
8221    }
8222
8223    /// Reject unparseable bounds / `from >= until` at set time (the
8224    /// API + CLI counterpart to [`Schedule::validate`]).
8225    pub fn validate(&self) -> Result<(), String> {
8226        let from = self
8227            .from
8228            .as_deref()
8229            .map(|s| Active::parse_bound(s, self.tz))
8230            .transpose()
8231            .map_err(|e| e.replace("active:", "freeze:"))?;
8232        let until = self
8233            .until
8234            .as_deref()
8235            .map(|s| Active::parse_bound(s, self.tz))
8236            .transpose()
8237            .map_err(|e| e.replace("active:", "freeze:"))?;
8238        if let (Some(f), Some(u)) = (from, until) {
8239            if f >= u {
8240                return Err(format!(
8241                    "freeze.from ({}) must be strictly before freeze.until ({})",
8242                    self.from.as_deref().unwrap_or_default(),
8243                    self.until.as_deref().unwrap_or_default(),
8244                ));
8245            }
8246        }
8247        Ok(())
8248    }
8249}
8250
8251/// The system-generated poll cadence every reconcile-shaped `when`
8252/// lowers to. Operators never write this: the real inter-run
8253/// spacing is the `every` cooldown; this only bounds "how soon do
8254/// we notice somebody is due" (#418 decision B took the poll
8255/// period away from the operator).
8256pub const POLL_CRON: &str = "0 * * * * *";
8257
8258/// What a [`When`] lowers to — the exact (cron, mode, cooldown)
8259/// trio the pre-#418 engine ran on. Keeping the engine vocabulary
8260/// unchanged is what lets Phase 1 swap the operator surface without
8261/// touching the tick / dedup machinery.
8262pub struct Lowered {
8263    /// Cron handed to `tokio-cron-scheduler` — [`POLL_CRON`] for
8264    /// reconcile shapes, a 6/7-field cron for calendar shapes.
8265    pub cron: String,
8266    /// Dedup semantics for `decide_fire`.
8267    pub mode: ExecMode,
8268    /// Humantime re-arm interval (`None` = succeed once, skip
8269    /// forever).
8270    pub cooldown: Option<String>,
8271    /// Timezone to evaluate `cron` in (#418 Phase 2). The scheduler
8272    /// passes this to `Job::new_async_tz`. Reconcile shapes carry
8273    /// the schedule's tz too even though POLL_CRON is tz-agnostic,
8274    /// so the same value drives the `active`-window check.
8275    pub tz: ScheduleTz,
8276}
8277
8278impl Schedule {
8279    /// The error message if this schedule's `constraints.window` is
8280    /// set but unparseable, else `None`. The scheduler logs this at
8281    /// register time so a fail-closed (never-firing) schedule from a
8282    /// hand-edited KV blob is diagnosable (gemini #452 review).
8283    pub fn bad_window(&self) -> Option<String> {
8284        let w = self.constraints.window.as_deref()?;
8285        Constraints::parse_window(w).err()
8286    }
8287
8288    /// True when this is a `calendar` schedule whose fire time can
8289    /// never fall inside its `constraints.window` — the cron fires,
8290    /// the window check rejects it, and (firing only at that
8291    /// time-of-day) it effectively never runs. An easy misconfig to
8292    /// set up by accident; the scheduler warns at register time
8293    /// (claude #452 review). Reconcile shapes poll every minute, so
8294    /// they always catch the window opening and aren't affected.
8295    pub fn calendar_outside_window(&self) -> bool {
8296        let When::Calendar(c) = &self.when else {
8297            return false;
8298        };
8299        let Some(t) = c.fire_time() else {
8300            return false;
8301        };
8302        matches!(self.constraints.window_contains(t), Some(false))
8303    }
8304
8305    /// Up to `count` future instants this schedule will fire, as
8306    /// absolute UTC, strictly after `now` — the dry-run / preview
8307    /// surface (#418 "ドライラン / プレビュー"). Only **calendar**
8308    /// schedules have discrete fire times; reconcile shapes
8309    /// (`per_pc`/`per_target`) poll every minute gated by cooldown, so
8310    /// they return an empty vec and the caller describes the cadence
8311    /// instead. Occurrences outside the `active.{from,until}` window or
8312    /// the `constraints.window` are **skipped**, so the list reflects
8313    /// when the schedule will ACTUALLY run, not the raw cron ticks.
8314    /// Evaluated in the schedule's `tz`, exactly like the scheduler's
8315    /// `Job::new_async_tz`, and with the same croner config the
8316    /// scheduler / [`Schedule::validate`] use, so a preview can never
8317    /// disagree with a real fire. A schedule that can never fire (a
8318    /// calendar time wholly outside its window, a past one-shot,
8319    /// `enabled: false` is *not* considered here — callers gate on
8320    /// `enabled` separately) yields an empty vec.
8321    pub fn preview_fires(
8322        &self,
8323        now: chrono::DateTime<chrono::Utc>,
8324        count: usize,
8325    ) -> Vec<chrono::DateTime<chrono::Utc>> {
8326        use croner::parser::{CronParser, Seconds};
8327        if !matches!(self.when, When::Calendar(_)) {
8328            return Vec::new();
8329        }
8330        // Same lowering + croner config as `next_calendar_fire` and the
8331        // live scheduler, so a preview can never disagree with a real
8332        // fire. `preview_fires` adds the N-occurrence walk and the
8333        // active / window filtering on top of that single seam.
8334        let lowered = self.lowered();
8335        let Ok(cron) = CronParser::builder()
8336            .seconds(Seconds::Required)
8337            .dom_and_dow(true)
8338            .build()
8339            .parse(&lowered.cron)
8340        else {
8341            return Vec::new();
8342        };
8343        let accept = |utc: chrono::DateTime<chrono::Utc>| {
8344            self.active.contains(utc, self.tz) && self.constraints.allows(utc, self.tz)
8345        };
8346        match self.tz {
8347            ScheduleTz::Utc => Self::next_occurrences(&cron, now, count, accept),
8348            ScheduleTz::Local => {
8349                Self::next_occurrences(&cron, now.with_timezone(&chrono::Local), count, accept)
8350            }
8351        }
8352    }
8353
8354    /// Walk croner forward from `after` collecting up to `count`
8355    /// accepted occurrences (converted to UTC). Generic over the tz the
8356    /// cron is evaluated in so `preview_fires` can run it in either
8357    /// `Utc` or `Local` without duplicating the loop.
8358    fn next_occurrences<Tz>(
8359        cron: &croner::Cron,
8360        after: chrono::DateTime<Tz>,
8361        count: usize,
8362        accept: impl Fn(chrono::DateTime<chrono::Utc>) -> bool,
8363    ) -> Vec<chrono::DateTime<chrono::Utc>>
8364    where
8365        Tz: chrono::TimeZone,
8366    {
8367        // Bound the scan so an `active`/window dead-end (every future
8368        // tick rejected) can't spin forever: ~4096 raw ticks covers
8369        // >10y of a daily calendar while staying instant for croner.
8370        const SCAN_CAP: usize = 4096;
8371        let mut out = Vec::with_capacity(count.min(SCAN_CAP));
8372        let mut cursor = after;
8373        let mut scanned = 0usize;
8374        while out.len() < count && scanned < SCAN_CAP {
8375            scanned += 1;
8376            let Ok(next) = cron.find_next_occurrence(&cursor, false) else {
8377                break;
8378            };
8379            let utc = next.with_timezone(&chrono::Utc);
8380            if accept(utc) {
8381                out.push(utc);
8382            }
8383            // `find_next_occurrence(.., inclusive = false)` already
8384            // advances strictly past `cursor`, so handing it `next`
8385            // verbatim gets the following occurrence — no manual +1s
8386            // nudge (and `DateTime<Tz>` is `Copy`, so no clone).
8387            cursor = next;
8388        }
8389        out
8390    }
8391
8392    /// Lower the operator-facing `when` onto the engine vocabulary.
8393    /// Single seam shared by the backend scheduler and the agent's
8394    /// local scheduler so the two can never drift.
8395    pub fn lowered(&self) -> Lowered {
8396        let tz = self.tz;
8397        match &self.when {
8398            When::PerPc(p) => Lowered {
8399                cron: POLL_CRON.into(),
8400                mode: ExecMode::OncePerPc,
8401                cooldown: p.cooldown(),
8402                tz,
8403            },
8404            When::PerTarget(p) => Lowered {
8405                cron: POLL_CRON.into(),
8406                mode: ExecMode::OncePerTarget,
8407                cooldown: p.cooldown(),
8408                tz,
8409            },
8410            // `to_cron` only fails on a malformed `at` (rejected by
8411            // validate() at create time). For a hand-edited KV blob
8412            // that slipped past, emit a deliberately-invalid cron so
8413            // register()'s Job::new_async_tz fails → warn+skip,
8414            // rather than firing at the wrong time.
8415            When::Calendar(c) => Lowered {
8416                cron: c
8417                    .to_cron()
8418                    .unwrap_or_else(|_| "# invalid calendar at".into()),
8419                mode: ExecMode::EveryTick,
8420                cooldown: None,
8421                tz,
8422            },
8423            // Event triggers have no cron — the agent fires them from an
8424            // OS event source. The `# event-trigger` cron is never
8425            // registered (the scheduler branches on `is_event()` first),
8426            // but keep it deliberately-invalid as a belt-and-suspenders
8427            // so a stray registration would fail rather than misfire.
8428            When::On(_) => Lowered {
8429                cron: "# event-trigger (no cron)".into(),
8430                mode: ExecMode::Event,
8431                cooldown: None,
8432                tz,
8433            },
8434        }
8435    }
8436
8437    /// True when this schedule fires from an OS event (`when: { on }`)
8438    /// rather than a clock — the agent skips `tokio-cron` registration
8439    /// for these and drives them from boot / session-change instead.
8440    pub fn is_event(&self) -> bool {
8441        matches!(self.when, When::On(_))
8442    }
8443
8444    /// The OS event triggers this schedule listens for, or `&[]` when it
8445    /// is not an event schedule.
8446    pub fn event_triggers(&self) -> &[OnTrigger] {
8447        match &self.when {
8448            When::On(t) => t,
8449            _ => &[],
8450        }
8451    }
8452
8453    /// The next absolute (UTC) time this schedule fires, or `None` when
8454    /// it has no discrete upcoming fire to preview.
8455    ///
8456    /// Used by the KLP `maintenance.list` preview ("what's about to
8457    /// happen on my PC", SPEC §2.1). Returns `None` for:
8458    ///
8459    /// - reconcile shapes (`per_pc` / `per_target`) — they lower to the
8460    ///   every-minute [`POLL_CRON`] and re-converge state continuously,
8461    ///   so "next fire" is always ~60s away and means nothing to a user
8462    ///   previewing upcoming maintenance;
8463    /// - a calendar schedule whose lowered cron won't parse (a
8464    ///   hand-edited KV blob that slipped past [`Schedule::validate`]);
8465    /// - a cron with no future occurrence.
8466    ///
8467    /// The wall-clock fire is evaluated in the schedule's own `tz`
8468    /// (matching the live tick's `Job::new_async_tz`) then normalised
8469    /// to UTC for the wire. `inclusive = false`: strictly the *next*
8470    /// fire after `now`, never one matching the current instant.
8471    pub fn next_calendar_fire(
8472        &self,
8473        now: chrono::DateTime<chrono::Utc>,
8474    ) -> Option<chrono::DateTime<chrono::Utc>> {
8475        if !matches!(self.when, When::Calendar(_)) {
8476            return None;
8477        }
8478        let lowered = self.lowered();
8479        // Same parser configuration tokio-cron-scheduler 0.15 uses
8480        // internally, so this can never compute a fire the live
8481        // scheduler wouldn't (seconds required, DOM-and-DOW honored).
8482        let cron = croner::parser::CronParser::builder()
8483            .seconds(croner::parser::Seconds::Required)
8484            .dom_and_dow(true)
8485            .build()
8486            .parse(&lowered.cron)
8487            .ok()?;
8488        match lowered.tz {
8489            ScheduleTz::Utc => cron.find_next_occurrence(&now, false).ok(),
8490            ScheduleTz::Local => {
8491                let now_local = now.with_timezone(&chrono::Local);
8492                cron.find_next_occurrence(&now_local, false)
8493                    .ok()
8494                    .map(|t| t.with_timezone(&chrono::Utc))
8495            }
8496        }
8497    }
8498
8499    /// Cross-field semantic checks that don't fit pure serde derive
8500    /// — the [`Manifest::validate`] counterpart (#418 decision F;
8501    /// pre-Phase-1 a broken schedule was accepted at create time
8502    /// and silently warn-skipped at tick time). Run at every create
8503    /// site: `kanade schedule create` (client-side) and
8504    /// `POST /api/schedules`. The job_id-exists check lives in the
8505    /// API handler instead — it needs the JOBS KV.
8506    pub fn validate(&self) -> Result<(), String> {
8507        if matches!(self.runs_on, RunsOn::Agent) && matches!(self.when, When::PerTarget(_)) {
8508            return Err(
8509                "when.per_target needs fleet-wide completion data and is backend-only; \
8510                 it cannot be combined with runs_on: agent (each agent self-schedules, \
8511                 so per-target dedup would be deduping across a target of 1)"
8512                    .into(),
8513            );
8514        }
8515        // #418 event triggers: the agent owns the OS event source
8516        // (boot / session-change), so `when: { on }` is agent-only and
8517        // needs at least one trigger.
8518        if let When::On(triggers) = &self.when {
8519            if !matches!(self.runs_on, RunsOn::Agent) {
8520                return Err(
8521                    "when.on (OS event trigger) is fired by the agent's own event \
8522                     source, so it requires runs_on: agent"
8523                        .into(),
8524                );
8525            }
8526            if triggers.is_empty() {
8527                return Err(
8528                    "when.on must list at least one trigger (e.g. [startup, logon])".into(),
8529                );
8530            }
8531        }
8532        if let Some(cd) = self.lowered().cooldown.as_deref() {
8533            humantime::parse_duration(cd)
8534                .map_err(|e| format!("when.every: invalid duration '{cd}': {e}"))?;
8535        }
8536        if let When::Calendar(c) = &self.when {
8537            // Lower the calendar form to its cron (catches a bad `at`
8538            // and the date+days conflict), then validate that cron
8539            // with the same parser configuration tokio-cron-scheduler
8540            // 0.15 uses internally (croner, seconds required,
8541            // DOM-and-DOW both honored, year optional) — create-time
8542            // validation can never accept what register() rejects.
8543            let cron = c.to_cron()?;
8544            croner::parser::CronParser::builder()
8545                .seconds(croner::parser::Seconds::Required)
8546                .dom_and_dow(true)
8547                .build()
8548                .parse(&cron)
8549                .map_err(|e| format!("when.at lowered to invalid cron '{cron}': {e}"))?;
8550        }
8551        // The other humantime strings on the schedule (claude #419
8552        // review): runtime degrades gracefully on both (bad jitter →
8553        // silent no-op, bad starting_deadline → warn + skipped tick),
8554        // but "rejected at create time" should cover every field the
8555        // operator can typo, not just `when`.
8556        if let Some(j) = &self.plan.jitter {
8557            humantime::parse_duration(j)
8558                .map_err(|e| format!("jitter: invalid duration '{j}': {e}"))?;
8559        }
8560        if let Some(sd) = &self.starting_deadline {
8561            humantime::parse_duration(sd)
8562                .map_err(|e| format!("starting_deadline: invalid duration '{sd}': {e}"))?;
8563        }
8564        // #917: the plan side got almost no create-time checks, so
8565        // several never-fires / fails-every-tick shapes were accepted
8566        // and only surfaced at dispatch time — or never:
8567        //
8568        // (1) a target that dispatches nothing. A runs_on: agent
8569        // schedule matches each agent against `target` (rollout waves
8570        // are backend-published and never reach that path), so an
8571        // unspecified target silently never fires; a runs_on: backend
8572        // one warn-fails every tick at the exec boundary, which
8573        // rejects the same shape with the same message.
8574        let has_waves = self
8575            .plan
8576            .rollout
8577            .as_ref()
8578            .is_some_and(|r| !r.waves.is_empty());
8579        if matches!(self.runs_on, RunsOn::Agent) {
8580            if !self.plan.target.is_specified() {
8581                return Err(
8582                    "target must specify at least one of `all` / `groups` / `pcs` — a \
8583                     runs_on: agent schedule matches each agent against `target`, so an \
8584                     unspecified target never fires anywhere"
8585                        .into(),
8586                );
8587            }
8588            if self.plan.rollout.is_some() {
8589                return Err(
8590                    "rollout waves are published by the backend and are ignored by \
8591                     runs_on: agent schedules (each agent self-schedules from `target`); \
8592                     drop `rollout:` or use runs_on: backend"
8593                        .into(),
8594                );
8595            }
8596        } else if !has_waves && !self.plan.target.is_specified() {
8597            return Err(
8598                "target must specify at least one of `all` / `groups` / `pcs` \
8599                 (or set `rollout.waves`) — the exec boundary rejects an \
8600                 unspecified target, so the schedule would fail every tick"
8601                    .into(),
8602            );
8603        }
8604        // (2) rollout waves were never validated: a blank group or an
8605        // unparseable delay failed at EVERY fire (the CLI doesn't even
8606        // expose waves, so the failure was always deferred to dispatch)
8607        // and an empty list dispatched nothing. (3) A wave delayed to
8608        // or past starting_deadline is dead on arrival: the deadline is
8609        // stamped once at tick time and the Command is serialised
8610        // before the wave sleep, so agents receive it already expired
8611        // (a synthetic exit-125 skip on every fire).
8612        if let Some(rollout) = &self.plan.rollout {
8613            if rollout.waves.is_empty() {
8614                return Err(
8615                    "rollout.waves must list at least one wave; omit `rollout:` for a \
8616                     one-shot fan-out of `target`"
8617                        .into(),
8618                );
8619            }
8620            let deadline = self
8621                .starting_deadline
8622                .as_deref()
8623                .and_then(|sd| humantime::parse_duration(sd).ok());
8624            for (i, wave) in rollout.waves.iter().enumerate() {
8625                if wave.group.trim().is_empty() {
8626                    return Err(format!("rollout.waves[{i}].group must not be blank"));
8627                }
8628                let delay = humantime::parse_duration(&wave.delay).map_err(|e| {
8629                    format!(
8630                        "rollout.waves[{i}].delay: invalid duration '{}': {e}",
8631                        wave.delay
8632                    )
8633                })?;
8634                if let Some(deadline) = deadline
8635                    && delay >= deadline
8636                {
8637                    return Err(format!(
8638                        "rollout.waves[{i}].delay ('{}') must be shorter than \
8639                         starting_deadline ('{}'): the deadline is stamped at tick time, \
8640                         so this wave's Commands would already be expired when published \
8641                         (skipped by every agent, every fire)",
8642                        wave.delay,
8643                        self.starting_deadline.as_deref().unwrap_or_default(),
8644                    ));
8645                }
8646            }
8647        }
8648        // (4) deadline_at is machine-stamped: the scheduler overwrites
8649        // it from `tick + starting_deadline` on every fire, so an
8650        // operator-set value is silently discarded — reject it and
8651        // point at the knob that does what they meant. (Ad-hoc POST
8652        // /api/exec bodies are a different write path and may still
8653        // carry it.)
8654        if self.plan.deadline_at.is_some() {
8655            return Err(
8656                "deadline_at is computed by the scheduler (tick time + starting_deadline) \
8657                 and overwritten on every fire — set `starting_deadline` instead"
8658                    .into(),
8659            );
8660        }
8661        let from = self
8662            .active
8663            .from
8664            .as_deref()
8665            .map(|s| Active::parse_bound(s, self.tz))
8666            .transpose()?;
8667        let until = self
8668            .active
8669            .until
8670            .as_deref()
8671            .map(|s| Active::parse_bound(s, self.tz))
8672            .transpose()?;
8673        if let (Some(f), Some(u)) = (from, until) {
8674            if f >= u {
8675                return Err(format!(
8676                    "active.from ({}) must be strictly before active.until ({})",
8677                    self.active.from.as_deref().unwrap_or_default(),
8678                    self.active.until.as_deref().unwrap_or_default(),
8679                ));
8680            }
8681        }
8682        // #418 Phase 3: a bad maintenance window is rejected at create
8683        // time (parse_window also catches equal bounds).
8684        if let Some(w) = self.constraints.window.as_deref() {
8685            Constraints::parse_window(w)?;
8686        }
8687        // #418 holiday exclusion: reject a malformed skip date at create
8688        // time so the fail-closed `allows` path only ever bites a
8689        // hand-edited KV blob, not a fresh `kanade schedule create`.
8690        if let Some(err) = self.constraints.bad_skip_date() {
8691            return Err(err);
8692        }
8693        // #418: constraints.max_concurrent is a central running-instance
8694        // cap, so it needs the backend's counter — reject it on
8695        // runs_on: agent (decision E), and reject a meaningless 0.
8696        if let Some(mc) = self.constraints.max_concurrent {
8697            // Check the structural incompatibility (agent has no central
8698            // counter) before the value range, so a `max_concurrent: 0`
8699            // + `runs_on: agent` combo reports the more fundamental
8700            // problem first (claude #542).
8701            if matches!(self.runs_on, RunsOn::Agent) {
8702                return Err(
8703                    "constraints.max_concurrent needs a central counter and is backend-only; \
8704                     it cannot be combined with runs_on: agent (each agent self-schedules, \
8705                     so there is no fleet-wide count to cap against)"
8706                        .into(),
8707                );
8708            }
8709            if mc == 0 {
8710                return Err(
8711                    "constraints.max_concurrent must be >= 1 (0 would never fire; \
8712                     omit it for no cap)"
8713                        .into(),
8714                );
8715            }
8716        }
8717        // #418: constraints.require (host-state env gates: ac_power /
8718        // idle / cpu_below / network) is sensed in-process by the agent,
8719        // so it needs runs_on: agent — the backend can't read a target
8720        // host's power / idle / cpu / connectivity state. Symmetric with
8721        // `when: { on }` (also agent-only); inverse of max_concurrent
8722        // (backend-only).
8723        if let Some(req) = &self.constraints.require {
8724            if !req.is_empty() && matches!(self.runs_on, RunsOn::Backend) {
8725                return Err(
8726                    "constraints.require (host-state env gates: ac_power / idle / cpu_below / \
8727                     network) is sensed in-process by the agent and needs runs_on: agent; the \
8728                     backend cannot read a target host's power / idle / cpu / connectivity state"
8729                        .into(),
8730                );
8731            }
8732            // Reject a malformed idle duration at create time so the
8733            // fail-closed runtime path only ever bites a hand-edited
8734            // KV blob (mirror skip_dates / on_failure.retry).
8735            if let Some(err) = req.bad_idle() {
8736                return Err(err);
8737            }
8738            // cpu_below is a percent — reject out-of-range so a typo
8739            // can't make a schedule that never (>=100 is always-busy?
8740            // no — <0 never matches) or trivially fires.
8741            if let Some(c) = req.cpu_below
8742                && !(c > 0.0 && c <= 100.0)
8743            {
8744                return Err(format!(
8745                    "constraints.require.cpu_below must be in (0, 100] percent (got {c}); \
8746                     omit it for no CPU requirement"
8747                ));
8748            }
8749        }
8750        // #418 Phase 4: a bad on_failure.retry is rejected at create
8751        // time — backoff must be valid humantime, and max is bounded
8752        // so a typo can't pin a flapping script in a tight loop.
8753        if let Some(r) = &self.on_failure.retry {
8754            let backoff = humantime::parse_duration(&r.backoff).map_err(|e| {
8755                format!(
8756                    "on_failure.retry.backoff: invalid duration '{}': {e}",
8757                    r.backoff
8758                )
8759            })?;
8760            // The wire form lowers backoff to whole seconds, so a
8761            // sub-second value would silently become a 0s no-wait
8762            // (coderabbit #466). Reject it rather than honour a backoff
8763            // the operator can't actually get.
8764            if backoff.as_secs() < 1 {
8765                return Err(format!(
8766                    "on_failure.retry.backoff must be >= 1s (got '{}'); sub-second backoffs \
8767                     round to 0 on the wire",
8768                    r.backoff
8769                ));
8770            }
8771            if !(1..=10).contains(&r.max) {
8772                return Err(format!(
8773                    "on_failure.retry.max must be 1..=10 (got {}); it counts additional \
8774                     attempts after the first run",
8775                    r.max
8776                ));
8777            }
8778        }
8779        // A blank / whitespace-only tag renders an empty filter chip on
8780        // the Schedules page — reject it at create time, mirroring the
8781        // Manifest::validate tag guard.
8782        for tag in &self.tags {
8783            if tag.trim().is_empty() {
8784                return Err("tags must not contain empty entries".to_string());
8785            }
8786        }
8787        Ok(())
8788    }
8789}
8790
8791/// Shared `serde(default)` for `bool` fields that default to `true`
8792/// (e.g. `CheckHint::fleet` / `CheckHint::health`). Generic name so it
8793/// doesn't read as "fleet" when reused for `health`.
8794fn default_true() -> bool {
8795    true
8796}