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 `placement.analytics:` tab groups them); `scope:` selects per-PC vs
97    /// fleet-wide rollup. Because it consumes nothing at run time it
98    /// composes with every other hint (typically paired with `emit:`,
99    /// which produces the events it reads). See [`AggregateWidget`].
100    ///
101    /// New field ⇒ #492 wire rule (`default` + `skip_serializing_if`).
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub aggregate: Option<Vec<AggregateWidget>>,
104    /// v0.26: Layer 2 staleness policy (SPEC.md §2.6.2). Controls
105    /// what the agent does at fire time when it can't verify the
106    /// `script_current` / `script_status` KV values are fresh —
107    /// especially relevant for `runs_on: agent` schedules where
108    /// the agent may fire from cache while offline. Defaults to
109    /// `Staleness::Cached` (silently use cached values), which
110    /// matches every pre-v0.26 Manifest.
111    #[serde(default)]
112    pub staleness: Staleness,
113    /// #291: opt-in marker that this job is offered to **end users**
114    /// in the Client App's job tabs over KLP (`jobs.list` →
115    /// `jobs.execute`). Parallel to [`inventory`] / [`check`] /
116    /// [`emit`]: the block's mere presence is the opt-in, and it
117    /// groups the end-user presentation fields (name / category /
118    /// icon) that only make sense for a user-facing job. `None`
119    /// (the default) ⇒ an operator-only job — inventory, checks,
120    /// scheduled maintenance — that never surfaces in the catalog.
121    ///
122    /// The agent re-reads this at every `jobs.list` / `jobs.execute`
123    /// (SPEC §2.1), so removing the block takes a job out of a
124    /// running client on its next action.
125    ///
126    /// [`inventory`]: Manifest::inventory
127    /// [`check`]: Manifest::check
128    /// [`emit`]: Manifest::emit
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub client: Option<ClientHint>,
131    /// Free-form operator taxonomy for the Jobs catalog. Purely a
132    /// SPA-side organisational aid — agents / scheduler / projector
133    /// never read it — so it carries no runtime semantics and any
134    /// string is allowed (`security`, `weekly`, `windows`, …). Jobs
135    /// cross-cut (a `check-bitlocker` is at once a health-check, a
136    /// security control, and Windows-specific), which is why this is
137    /// a multi-valued list rather than the single closed-enum
138    /// [`ClientHint::category`] (whose values are the end-user Client
139    /// App's tabs, a different concern). The operator Jobs page groups
140    /// rows by id-prefix for free; tags add the orthogonal filter axis
141    /// prefixes can't express.
142    ///
143    /// Empty by default (the overwhelming majority of jobs), and a
144    /// new field, so it follows the #492 wire rule: `serde(default)`
145    /// plus `skip_serializing_if` keep gradually-upgrading old readers
146    /// from tripping over its absence / presence.
147    #[serde(default, skip_serializing_if = "Vec::is_empty")]
148    pub tags: Vec<String>,
149    /// GitOps provenance (#678) — see [`RepoOrigin`]. Stamped by
150    /// `kanade job create` when the source YAML lives inside a Git work
151    /// tree, so the SPA can render the job read-only and point edits
152    /// back at the repo instead of letting a ClickOps edit silently
153    /// diverge from Git (SPEC design principle #3: 設定駆動 YAML + Git).
154    /// `None` for SPA-born jobs and for manifests applied from outside
155    /// any Git repo. Purely informational: agents / scheduler /
156    /// projector never read it, and it survives `script_file:` inlining
157    /// (it's orthogonal to the exactly-one-of script-source rule). New
158    /// field ⇒ #492 wire rule (`default` + `skip_serializing_if`).
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub origin: Option<RepoOrigin>,
161    /// Job-generic post-step hook. When set, the agent runs this script
162    /// AFTER the main `execute:` script exits cleanly (and, for a
163    /// `collect:` job, after the bundle finishes uploading), so the
164    /// operator can delete / move / notify based on what the step
165    /// produced. Best-effort: a finalize failure is logged but never
166    /// fails the run — the upload (if any) already succeeded.
167    ///
168    /// For `collect:` jobs the agent injects the environment variable
169    /// `KANADE_COLLECT_RESULT` — a JSON object
170    /// `{ "ok": true, "bundles": [ { "key", "uploaded", "files": [...] } ] }`
171    /// — so the hook acts on exactly the files that were bundled and
172    /// uploaded (e.g. deletes only the `uploaded` ones). Composes with
173    /// every hint. New field ⇒ #492 wire rule (`default` +
174    /// `skip_serializing_if`).
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub finalize: Option<FinalizeSpec>,
177    /// #vuln-roadmap: declarative **external-data feeds**. Each entry fetches
178    /// global reference data (a vulnerability catalog, an EOL table, a license
179    /// roster) and projects it into the shared `feeds` table keyed
180    /// `(feed_id, item_id)` — fleet-wide, with no `pc_id`, unlike the per-PC
181    /// inventory [`ExplodeSpec`]. The job's script (run on the trusted
182    /// controller tier) fetches + shapes the data and prints the array under
183    /// each spec's [`field`](FeedSpec::field) inside a
184    /// `#KANADE-FEED-BEGIN/END` fence; the projector replaces that feed's rows
185    /// wholesale. A non-empty `feed:` **implies** `tier: controller` (the
186    /// dispatch guard treats it as such), so an external fetch never lands on
187    /// an employee endpoint. Composes with the other fenced hints. New field ⇒
188    /// #492 wire rule (`default` + `skip_serializing_if`). See [`FeedSpec`].
189    #[serde(default, skip_serializing_if = "Vec::is_empty")]
190    pub feed: Vec<FeedSpec>,
191    /// Execution tier (#vuln-roadmap). `None` / `endpoint` (default) ⇒ the
192    /// job dispatches to the targeted fleet agents like any job. `controller`
193    /// ⇒ it may run ONLY on trusted infra hosts — the backend constrains
194    /// dispatch to members of the operator-configured `controller_group`
195    /// (`server_settings` KV), and refuses to run anywhere if that group is
196    /// unset (fail-safe). This keeps `feed:` (external-fetch) and future
197    /// privileged hints off employee endpoints. The `feed:` hint implies
198    /// `controller`; it can also be set explicitly. New field ⇒ #492 wire
199    /// rule (`default` + `skip_serializing_if`).
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub tier: Option<Tier>,
202}
203
204/// Execution tier for a [`Manifest`] — see [`Manifest::tier`]. `endpoint`
205/// is the default (a normal fleet job); `controller` restricts dispatch to
206/// the trusted `controller_group`. `Unknown` is the #492 forward-compat
207/// catch-all: an older reader still *decodes* a job that names a future
208/// tier (so it doesn't fail the whole document), but `Manifest::validate()`
209/// **rejects** it — for a security field we fail closed rather than fall
210/// back to unrestricted `endpoint` dispatch (a future tier is presumably
211/// *more* restrictive, and a typo'd `controller` must not silently widen).
212#[derive(
213    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
214)]
215#[serde(rename_all = "snake_case")]
216#[non_exhaustive]
217pub enum Tier {
218    /// Dispatch to the targeted fleet agents (the default).
219    #[default]
220    Endpoint,
221    /// Dispatch only to members of the configured `controller_group`.
222    Controller,
223    /// #492 forward-compat catch-all (a future tier this build can't act on).
224    #[serde(other)]
225    Unknown,
226}
227
228/// GitOps provenance for a repo-managed YAML artifact — a [`Manifest`]
229/// (#678) or a [`Schedule`] (#695). Populated by `kanade job create` /
230/// `kanade schedule create` from the Git context of the source YAML;
231/// the SPA reads it to render Git-managed entries read-only and link
232/// the operator back at the repo. Never consulted by the runtime.
233#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
234pub struct RepoOrigin {
235    /// Repo-relative path of the source YAML — the primary edit target
236    /// the SPA surfaces (e.g. `configs/jobs/foo.yaml`). Forward slashes
237    /// regardless of the authoring OS.
238    pub path: String,
239    /// `origin` remote URL, when the repo has one. Lets the SPA turn
240    /// `path` into a clickable link; `None` for remote-less repos.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub repo: Option<String>,
243    /// Repo-relative path of the `script_file:` a job manifest inlined,
244    /// when it used one — a secondary pointer shown beneath `path`.
245    /// Always `None` for schedules (they carry no script).
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    pub script_file: Option<String>,
248}
249
250/// "Who + how + when-to-stagger" — the fanout-plan side of an exec.
251/// Used both as the POST `/api/exec/{job_id}` body and as the embedded
252/// `target` / `rollout` / `jitter` slot on [`Schedule`]. Centralising
253/// here keeps the validation + serialisation logic in one place.
254#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default)]
255pub struct FanoutPlan {
256    #[serde(default)]
257    pub target: Target,
258    /// Optional wave rollout — when present, the backend publishes
259    /// each wave's group subject on its own delay schedule instead
260    /// of fanning out the `target` block in one go. `target` then
261    /// only labels the deploy for the audit log.
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub rollout: Option<Rollout>,
264    /// Optional humantime jitter; agent uses it to randomise
265    /// execution start. Lives here (not on the script) so different
266    /// schedules / ad-hoc fires of the same job can pick different
267    /// stagger windows.
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub jitter: Option<String>,
270    /// Absolute time the scheduler stamps on each emitted Command
271    /// when this exec was driven by a [`Schedule`] with
272    /// `starting_deadline`. Agents receiving a Command after this
273    /// instant publish a synthetic skipped-result instead of
274    /// running the script. `None` (default) = no deadline / catch
275    /// up whenever delivered. Computed by the scheduler from
276    /// `tick_at + starting_deadline` and overwritten on every fire —
277    /// on a Schedule, setting it by hand is rejected at create time
278    /// (#917, use `starting_deadline`); it remains settable on an
279    /// ad-hoc POST /api/exec body.
280    #[serde(default, skip_serializing_if = "Option::is_none")]
281    pub deadline_at: Option<chrono::DateTime<chrono::Utc>>,
282}
283
284/// Sentinel lines that fence a hint's structured JSON payload inside an
285/// otherwise human-readable job stdout. Each stdout-reading hint
286/// (`inventory:` / `check:` / `collect:`) has its OWN `#KANADE-<KIND>-
287/// BEGIN`/`-END` pair, so one job can carry several of them at once
288/// (and/or a user-facing message) on its single stdout stream — every
289/// consumer extracts only its own block via [`fenced_payload`].
290///
291/// Originated for inventory (#793): a `client:` job couldn't put both a
292/// friendly message and a JSON object on one stdout (the Client App
293/// renders stdout verbatim, the projector needs JSON). #821 generalised
294/// it so inventory / check / collect can coexist. `emit:` is the
295/// exception — its stdout is line-delimited NDJSON consumed whole, so it
296/// never fences and never coexists with the others.
297///
298/// A job carrying a SINGLE hint may still skip the fence —
299/// [`fenced_payload`] falls back to the whole stdout — but a job
300/// COMBINING hints must fence each block (else every consumer would try
301/// to parse the same whole stdout).
302pub const INVENTORY_BLOCK_BEGIN: &str = "#KANADE-INVENTORY-BEGIN";
303/// Closing marker — see [`INVENTORY_BLOCK_BEGIN`].
304pub const INVENTORY_BLOCK_END: &str = "#KANADE-INVENTORY-END";
305/// Check-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
306pub const CHECK_BLOCK_BEGIN: &str = "#KANADE-CHECK-BEGIN";
307/// Check-payload closing marker.
308pub const CHECK_BLOCK_END: &str = "#KANADE-CHECK-END";
309/// Collect-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
310pub const COLLECT_BLOCK_BEGIN: &str = "#KANADE-COLLECT-BEGIN";
311/// Collect-payload closing marker.
312pub const COLLECT_BLOCK_END: &str = "#KANADE-COLLECT-END";
313/// Feed-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
314pub const FEED_BLOCK_BEGIN: &str = "#KANADE-FEED-BEGIN";
315/// Feed-payload closing marker.
316pub const FEED_BLOCK_END: &str = "#KANADE-FEED-END";
317
318/// Extract a hint's fenced block when the `begin` marker is present, else
319/// `None`. An unterminated fence (closing marker missing, e.g. truncated
320/// output) takes everything after the opener. Trimmed so surrounding
321/// message text / whitespace never reaches the JSON parser.
322pub fn fenced_payload_if_present<'a>(stdout: &'a str, begin: &str, end: &str) -> Option<&'a str> {
323    let b = find_line_marker(stdout, begin)?;
324    let after = &stdout[b + begin.len()..];
325    let inner = match find_line_marker(after, end) {
326        Some(e) => &after[..e],
327        None => after,
328    };
329    Some(inner.trim())
330}
331
332/// True if stdout carries ANY `#KANADE-<KIND>-BEGIN` fence at a line
333/// start — i.e. the script opted into fenced output. Used to decide
334/// whether a missing fence means "single-hint, use the whole stdout" or
335/// "multi-hint author error / truncation, this hint just has no block".
336pub fn has_any_hint_fence(stdout: &str) -> bool {
337    [
338        INVENTORY_BLOCK_BEGIN,
339        CHECK_BLOCK_BEGIN,
340        COLLECT_BLOCK_BEGIN,
341        FEED_BLOCK_BEGIN,
342    ]
343    .iter()
344    .any(|m| find_line_marker(stdout, m).is_some())
345}
346
347/// Extract one hint's JSON payload from a job's stdout. When the hint's
348/// own `#KANADE-<KIND>` fence is present, return that block. When it's
349/// absent, fall back to the WHOLE stdout only for an unfenced (single-
350/// hint) job; if any OTHER hint's fence is present (#821 multi-hint
351/// output) return `""` instead — the script opted into fences but this
352/// block is missing (author error or truncation), so this consumer must
353/// NOT grab a sibling hint's block. An empty payload fails the consumer's
354/// JSON parse and degrades to "no data for this hint", never cross-parse.
355pub fn fenced_payload<'a>(stdout: &'a str, begin: &str, end: &str) -> &'a str {
356    if let Some(p) = fenced_payload_if_present(stdout, begin, end) {
357        return p;
358    }
359    if has_any_hint_fence(stdout) {
360        ""
361    } else {
362        stdout.trim()
363    }
364}
365
366/// Inventory's fenced payload — [`fenced_payload`] with the inventory
367/// markers. Kept as a named helper for the projector call site.
368pub fn inventory_payload(stdout: &str) -> &str {
369    fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END)
370}
371
372/// Feed's fenced payload — [`fenced_payload`] with the feed markers. Kept as
373/// a named helper for the projector call site.
374pub fn feed_payload(stdout: &str) -> &str {
375    fenced_payload(stdout, FEED_BLOCK_BEGIN, FEED_BLOCK_END)
376}
377
378/// Find `needle` only where it begins a line (start of `hay` or right
379/// after a `\n`). Anchoring to line start means a script echoing the
380/// literal sentinel mid-message (e.g. printing a command name) can't
381/// false-trigger the fence (Claude #793).
382fn find_line_marker(hay: &str, needle: &str) -> Option<usize> {
383    if hay.starts_with(needle) {
384        return Some(0);
385    }
386    hay.find(&format!("\n{needle}")).map(|p| p + 1)
387}
388
389/// Manifest sub-section: how the SPA should render the inventory
390/// facts this job produces. Each field name (`field`) is a top-level
391/// key in the stdout JSON, e.g. `hostname`, `ram_gb`.
392///
393/// Two render modes:
394///   * `display` — vertical "field / value" per PC, used by the
395///     `/inventory?pc=<id>` detail view. ALL columns the operator
396///     wants visible on the detail page.
397///   * `summary` — horizontal table across the fleet (row = PC,
398///     column = field) on `/inventory`. Optional; when omitted the
399///     SPA falls back to `display`, but operators usually want a
400///     trimmer "hostname / OS / CPU / RAM" set for the fleet view.
401#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
402pub struct InventoryHint {
403    /// Detail-view columns, in order.
404    pub display: Vec<DisplayField>,
405    /// Optional fleet-list columns (row = PC). Defaults to `display`
406    /// when omitted, but operators usually pick a 3-5 column subset.
407    #[serde(default, skip_serializing_if = "Option::is_none")]
408    pub summary: Option<Vec<DisplayField>>,
409    /// v0.31 / #40: payload arrays that should be exploded into
410    /// per-element rows of a derived SQLite table. Lets operators
411    /// answer cross-PC questions ("which PCs still have Chrome <
412    /// 120?", "C: >90% full") with normal SQL filters + indexes
413    /// instead of grepping JSON. The projector creates the derived
414    /// table on register and replaces this PC's rows on each result
415    /// (DELETE WHERE pc_id=? AND job_id=? + bulk INSERT). See
416    /// [`ExplodeSpec`] for the per-spec schema.
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub explode: Option<Vec<ExplodeSpec>>,
419    /// v0.35 / #93: top-level scalar fields whose changes the
420    /// projector logs to `inventory_history` (one event per
421    /// changed field per scan). Pairs with `explode[].track_history`
422    /// — that covers array elements; this covers single-valued
423    /// fields like `ram_bytes` / `os_version` / `cpu_model` /
424    /// `os_build` that operators want to track for "did the RAM
425    /// get upgraded?" / "when did Win 11 land on this PC?" /
426    /// "BIOS / firmware bumped?" questions. Field name = `field_path`
427    /// in the history row, `identity_json` is NULL, `before_json`
428    /// / `after_json` each carry `{"value": <prior or new value>}`.
429    /// First-ever observation of a scalar (no prior facts row)
430    /// emits `added`; subsequent value changes emit `changed`. No
431    /// `removed` events — a scalar disappearing from the payload
432    /// is rare and the operator can still see the last value via
433    /// the `before_json` of the most recent change.
434    #[serde(default, skip_serializing_if = "Option::is_none")]
435    pub history_scalars: Option<Vec<String>>,
436}
437
438/// Manifest sub-section (#290): marks a job as an operator-defined
439/// **health check**. Parallel to [`InventoryHint`] / `EmitConfig`.
440/// The stdout contract is a free-form JSON object (same as any
441/// inventory job) from which the agent reads `status_field` /
442/// `detail_field` to build the KLP [`crate::ipc::state::Check`] shown
443/// on the Client App's Health tab.
444///
445/// There is deliberately **no timing field** — when / how often /
446/// in which window a check runs is driven by the job's Schedule,
447/// exactly like inventory jobs, so operators get the full `when:` /
448/// rollout / `runs_on` expressiveness for free.
449///
450/// A check's stdout is a **free-form inventory object** (arbitrary
451/// key/value pairs + arrays) — same as any inventory job — that also
452/// carries a status field. `check:` adds only the health semantics on
453/// top: which field is the ok/warn/fail/unknown status, an optional
454/// one-line summary field, and a remediation job. Everything else
455/// (rich per-PC detail, `explode` sub-tables like a software list) is
456/// driven by a co-present [`InventoryHint`] and rendered with the
457/// SAME display logic the SPA Inventory page uses — on the Client App
458/// too. This keeps checks maximally expressive without a bespoke
459/// payload type.
460#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
461pub struct CheckHint {
462    /// Stable check id → [`Check.name`](crate::ipc::state::Check),
463    /// the SPA/Client React key + analytics label. Unique within the
464    /// fleet's check set. Machine-friendly slug (`disk_space`,
465    /// `defender_rtp`); for the human-facing row title see [`label`].
466    ///
467    /// [`label`]: CheckHint::label
468    pub name: String,
469    /// Optional human-facing display title →
470    /// [`Check.label`](crate::ipc::state::Check). The Client App's
471    /// Health tab and the operator SPA's Compliance page render this
472    /// instead of the [`name`](CheckHint::name) slug when set
473    /// (`"ウイルス対策のリアルタイム保護"` reads better than
474    /// `defender_rtp`). Falls back to the slug when absent, so it's
475    /// purely additive. Author it in the check's language — there's no
476    /// per-locale variant; checks are operator-defined per fleet.
477    #[serde(default, skip_serializing_if = "Option::is_none")]
478    pub label: Option<String>,
479    /// Top-level stdout field whose string value
480    /// (`ok`/`warn`/`fail`/`unknown`) becomes the Health-tab light
481    /// ([`CheckStatus`](crate::ipc::state::CheckStatus)). Defaults to
482    /// `"status"`; a missing / unparseable value → `unknown`.
483    #[serde(default = "default_status_field")]
484    pub status_field: String,
485    /// Top-level stdout field used as the Health-tab row's one-line
486    /// summary. Defaults to `"detail"`; absent in the payload → no
487    /// detail line (the rich breakdown lives in the inventory view).
488    #[serde(default = "default_detail_field")]
489    pub detail_field: String,
490    /// Optional remediation job id →
491    /// [`Check.troubleshoot`](crate::ipc::state::Check). The Client
492    /// App shows a "修復する" button when present; that job must be
493    /// `user_invokable`.
494    #[serde(default, skip_serializing_if = "Option::is_none")]
495    pub troubleshoot: Option<String>,
496    /// #290 PR-E: when `true` (default), the backend also projects this
497    /// check's `status` / `detail` into the `check_status` table so the
498    /// operator SPA gets a fleet-wide compliance view for free — no
499    /// `inventory:` block needed. Set `fleet: false` for a client-only
500    /// check the operator doesn't want surfaced across the fleet.
501    #[serde(default = "default_true")]
502    pub fleet: bool,
503    /// When `true` (default), this check is shown on the Client App's
504    /// Health tab (the end user sees its ok/warn/fail row). Set
505    /// `health: false` for a **gate-only** check — one that exists purely
506    /// to drive a `client.show_when` display gate (e.g. `myapp-up-to-date`)
507    /// and would just be noise as a Health row. The agent still records it
508    /// into `StateSnapshot.checks` (so `show_when` can read it and the gate
509    /// keeps working); only the Client App's Health *rendering* skips it,
510    /// via the [`Check.health_hidden`](crate::ipc::state::Check::health_hidden)
511    /// wire flag. Orthogonal to [`fleet`](CheckHint::fleet): `fleet` gates
512    /// the operator SPA fleet view, `health` gates the end-user Health tab,
513    /// so a pure gate detector typically sets neither (`fleet: false` +
514    /// `health: false`) to stay invisible everywhere while still driving
515    /// the gate.
516    #[serde(default = "default_true")]
517    pub health: bool,
518    /// Optional auto-notification on a compliance transition. When set, the
519    /// backend publishes an end-user notification the moment this check
520    /// transitions *into* one of [`CheckAlert::on`] (e.g. ok → fail) — to
521    /// the failing PC's user and/or operator groups. Fired once per
522    /// transition (not on every poll). Requires `fleet: true` (the alert
523    /// rides the same projection that fills `check_status`).
524    #[serde(default, skip_serializing_if = "Option::is_none")]
525    pub alert: Option<CheckAlert>,
526}
527
528/// Auto-notification rule for a [`CheckHint`] (compliance alerting). When a
529/// check's status transitions into one of [`on`](Self::on), the backend
530/// publishes a notification to the failing PC's user
531/// ([`notify_user`](Self::notify_user)) and/or operator groups
532/// ([`notify_groups`](Self::notify_groups)). Deliberately config-driven:
533/// who gets told, how loud, and the wording all live in the manifest, not
534/// hardcoded in the backend.
535#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
536pub struct CheckAlert {
537    /// Statuses that fire the alert on *transition into* them (a check that
538    /// stays failing doesn't re-alert every poll). Defaults to `[fail]`.
539    /// `ok` is not representable — [`CheckAlertStatus`] has no `Ok` variant,
540    /// so a YAML `on: [ok]` fails to deserialize (before `validate()` is
541    /// even reached); "recovered" notifications are out of scope.
542    #[serde(default = "default_alert_on")]
543    pub on: Vec<CheckAlertStatus>,
544    /// Notify the user(s) on the failing PC (`notifications.pc.<pc_id>`).
545    #[serde(default)]
546    pub notify_user: bool,
547    /// Notify these operator groups (`notifications.group.<name>`).
548    #[serde(default, skip_serializing_if = "Vec::is_empty")]
549    pub notify_groups: Vec<String>,
550    /// Notification priority (colour/label only — toasting is the separate
551    /// `toast` flag). Defaults to `warn`.
552    #[serde(default = "default_alert_priority")]
553    pub priority: crate::ipc::notifications::NotificationPriority,
554    /// Require the recipient to click 確認 to dismiss.
555    #[serde(default)]
556    pub require_ack: bool,
557    /// Surface an OS toast (launches a closed Client App, Action Center
558    /// while locked). Recommended `true` for `notify_user` so a
559    /// non-emergency "your PC is non-compliant" nudge still reaches a user
560    /// whose app is closed.
561    #[serde(default)]
562    pub toast: bool,
563    /// Also send the alert by email, to every address mapped to the
564    /// `notify_groups` (via the `group_contacts` KV, edited on the SPA
565    /// Groups page). Opt-in: defaults to `false`, so an existing alert
566    /// never starts emailing on its own. Requires `notify_groups` to be
567    /// non-empty (there is no per-PC user email) and the backend's
568    /// `[mail]` config to be present; otherwise the email is a logged
569    /// no-op while the in-app/toast notification still fires.
570    #[serde(default)]
571    pub email: bool,
572    /// Notification title (required). May use the same `{…}` placeholders
573    /// as [`body`](Self::body).
574    pub title: String,
575    /// Notification body template. Placeholders: `{pc_id}`, `{name}` (check
576    /// slug), `{label}` (check label, falls back to slug), `{status}`,
577    /// `{detail}` (the check's one-line summary), `{last_logon}` (the PC's
578    /// last sign-in account). Absent → empty body.
579    #[serde(default, skip_serializing_if = "Option::is_none")]
580    pub body: Option<String>,
581}
582
583/// A check status that can trigger a [`CheckAlert`]. Mirrors the
584/// projected `check_status.status` values minus `ok` (alerting on `ok` is
585/// rejected at validation).
586#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash)]
587#[serde(rename_all = "snake_case")]
588pub enum CheckAlertStatus {
589    Warn,
590    Fail,
591    Unknown,
592}
593
594impl CheckAlertStatus {
595    /// The wire string, matching the projected `check_status.status`.
596    pub fn as_str(self) -> &'static str {
597        match self {
598            Self::Warn => "warn",
599            Self::Fail => "fail",
600            Self::Unknown => "unknown",
601        }
602    }
603}
604
605fn default_alert_on() -> Vec<CheckAlertStatus> {
606    vec![CheckAlertStatus::Fail]
607}
608
609fn default_alert_priority() -> crate::ipc::notifications::NotificationPriority {
610    crate::ipc::notifications::NotificationPriority::Warn
611}
612
613fn default_status_field() -> String {
614    "status".to_string()
615}
616
617fn default_detail_field() -> String {
618    "detail".to_string()
619}
620
621fn default_files_field() -> String {
622    "files".to_string()
623}
624
625/// Fallback cap on a collect bundle's total input size when the
626/// manifest's `collect.max_size` is unset. 50 MB (decimal).
627pub const DEFAULT_COLLECT_MAX_SIZE: u64 = 50 * 1_000_000;
628
629/// Manifest sub-section (#219): marks a job as a **file collector** and
630/// carries how the collected bundle presents in the SPA. Parallel to
631/// [`InventoryHint`] / [`CheckHint`] — the block's presence is the
632/// opt-in. The script prints a single JSON object on stdout whose
633/// [`files_field`](CollectHint::files_field) key holds an array of file
634/// paths to bundle (env vars are expanded); the agent zips them and
635/// uploads to `OBJECT_COLLECTIONS`. See [`Manifest::collect`].
636#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
637pub struct CollectHint {
638    /// Operator/end-user-facing title for the collection, shown as the
639    /// bundle's heading on the SPA Collect page (and the Client App row
640    /// when paired with `client:`). Required; validated non-empty.
641    pub name: String,
642    /// Optional one-line description of what the bundle contains.
643    #[serde(default, skip_serializing_if = "Option::is_none")]
644    pub description: Option<String>,
645    /// Human-readable cap on the bundle's total input size
646    /// (`"50MB"`, `"500KB"`, `"1GiB"`). The agent refuses to build a
647    /// bundle whose listed files exceed this. `None` ⇒
648    /// [`DEFAULT_COLLECT_MAX_SIZE`]. Parsed by [`parse_size_bytes`];
649    /// [`Manifest::validate`] rejects an unparseable value at create
650    /// time.
651    ///
652    /// Note: this bounds the **uncompressed** bytes the agent reads off
653    /// disk, not the resulting zip. Text logs compress well, so the
654    /// download is usually much smaller; many tiny files add a little
655    /// per-entry zip overhead. Read it as "how much the agent reads +
656    /// packs", not "the exact download size".
657    #[serde(default, skip_serializing_if = "Option::is_none")]
658    pub max_size: Option<String>,
659    /// Top-level stdout JSON key holding the array of file paths to
660    /// bundle. Defaults to `"files"`.
661    #[serde(default = "default_files_field")]
662    pub files_field: String,
663}
664
665impl CollectHint {
666    /// The effective size cap in bytes — the parsed `max_size` or
667    /// [`DEFAULT_COLLECT_MAX_SIZE`] when unset. Assumes `max_size` (if
668    /// present) already passed [`Manifest::validate`]; falls back to the
669    /// default on a parse error rather than panicking on the fire path.
670    pub fn max_size_bytes(&self) -> u64 {
671        match &self.max_size {
672            Some(s) => parse_size_bytes(s).unwrap_or(DEFAULT_COLLECT_MAX_SIZE),
673            None => DEFAULT_COLLECT_MAX_SIZE,
674        }
675    }
676}
677
678/// Parse a human-readable byte size (`"50MB"`, `"500 KB"`, `"1GiB"`,
679/// `"1024"`). Decimal units (KB/MB/GB) are 1000-based; binary units
680/// (KiB/MiB/GiB) are 1024-based; a bare number (or `B`) is bytes.
681/// Case-insensitive. Shared by `collect.max_size` validation and the
682/// agent's bundle-size enforcement.
683pub fn parse_size_bytes(s: &str) -> Result<u64, String> {
684    let t = s.trim();
685    if t.is_empty() {
686        return Err("size must not be empty".to_string());
687    }
688    let split = t.find(|c: char| !c.is_ascii_digit()).unwrap_or(t.len());
689    let (num_str, unit_raw) = t.split_at(split);
690    if num_str.is_empty() {
691        return Err(format!("size '{s}': missing leading number"));
692    }
693    let num: u64 = num_str
694        .parse()
695        .map_err(|_| format!("size '{s}': bad number '{num_str}'"))?;
696    let mult: u64 = match unit_raw.trim().to_ascii_lowercase().as_str() {
697        "" | "b" => 1,
698        "kb" => 1_000,
699        "mb" => 1_000_000,
700        "gb" => 1_000_000_000,
701        "kib" => 1024,
702        "mib" => 1024 * 1024,
703        "gib" => 1024 * 1024 * 1024,
704        other => {
705            return Err(format!(
706                "size '{s}': unknown unit '{other}' (use B/KB/MB/GB/KiB/MiB/GiB)"
707            ));
708        }
709    };
710    num.checked_mul(mult)
711        .ok_or_else(|| format!("size '{s}': overflow"))
712}
713
714/// Manifest sub-section (#291): marks a job as **user-invokable**
715/// from the Client App and carries how it presents to the end user.
716/// Parallel to [`InventoryHint`] / [`CheckHint`] / `EmitConfig` —
717/// the block's presence is the opt-in (no separate boolean), and its
718/// required fields (`name`, `category`) are enforced by serde at
719/// parse time, so a half-filled catalog entry fails
720/// `kanade job create` instead of rendering a nameless / tab-less row.
721///
722/// The agent maps this 1:1 into the KLP
723/// [`UserInvokableJob`](crate::ipc::jobs::UserInvokableJob) wire shape
724/// that `jobs.list` returns; the Client App renders one row per job in
725/// the tab named by `category`.
726#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
727pub struct ClientHint {
728    /// End-user-facing title for the job row. The operator-internal
729    /// `Manifest::id` slug is rarely what an end user should read, so
730    /// this is required (and validated non-empty by
731    /// [`Manifest::validate`]). Maps to `UserInvokableJob::display_name`.
732    pub name: String,
733    /// Optional one-line subtitle under `name` in the Client App.
734    /// Distinct from the operator-facing top-level
735    /// [`Manifest::description`] — this one is written for the end
736    /// user. Maps to `UserInvokableJob::display_description`.
737    #[serde(default, skip_serializing_if = "Option::is_none")]
738    pub description: Option<String>,
739    /// Which Client App tab the job lives in — a **free-form category
740    /// key** (#792). The Client App renders one tab per distinct key.
741    /// Well-known keys (`software_update`, `troubleshoot`, `catalog`)
742    /// carry built-in tab labels/icons; any other key defines a new tab
743    /// (style it with `category_label` / `category_icon`). Required and
744    /// validated non-empty — without it the agent can't place the job.
745    /// Note: the `software_update` key also drives the agent's
746    /// maintenance / auto-reboot grouping.
747    pub category: String,
748    /// Optional display name for the category's TAB. Set it on (at least
749    /// one of) a custom category's jobs to name the tab; `None` ⇒ a
750    /// built-in default for a well-known key, else the key itself.
751    #[serde(default, skip_serializing_if = "Option::is_none")]
752    pub category_label: Option<String>,
753    /// Optional icon for the category's TAB (lucide name or `data:` URL).
754    /// `None` ⇒ Client App default for the key.
755    #[serde(default, skip_serializing_if = "Option::is_none")]
756    pub category_icon: Option<String>,
757    /// Optional sort order for the TAB; lower sorts first. `None` ⇒
758    /// default (well-known keys keep their familiar order; custom keys
759    /// sort after, then by label).
760    #[serde(default, skip_serializing_if = "Option::is_none")]
761    pub category_order: Option<i64>,
762    /// Optional icon hint for the job ROW — a lucide-react icon name
763    /// or a `data:` URL. `None` ⇒ the Client App falls back to the
764    /// category's icon. Surfaced verbatim in `jobs.list[].icon`.
765    #[serde(default, skip_serializing_if = "Option::is_none")]
766    pub icon: Option<String>,
767    /// Optional visibility scope for the end-user Client App (#816).
768    ///
769    /// `None` ⇒ visible to every PC (current behavior). When set, only
770    /// agents whose `pc_id` / group membership match the [`Target`] list
771    /// the job in `jobs.list` and may run it via KLP `jobs.execute`.
772    ///
773    /// This gates the END-USER surface ONLY. Operators are unaffected:
774    /// `POST /api/exec/{job_id}` (SPA / `kanade exec`) is a separate path
775    /// that never consults `client:`, so an operator can still run the
776    /// job on any PC regardless of `visible_to`. Reuses the schedule
777    /// `Target` shape (`all` / `groups` / `pcs`); a present-but-empty
778    /// target is rejected by [`Manifest::validate`].
779    #[serde(default, skip_serializing_if = "Option::is_none")]
780    pub visible_to: Option<Target>,
781    /// Optional **dynamic display gate** keyed on a health check's result.
782    ///
783    /// `None` ⇒ always listed (current behavior). When set, the agent
784    /// lists the job in `jobs.list` ONLY while the named [`check:`] slug's
785    /// latest result is one of [`ShowWhen::is`]. The canonical use is an
786    /// update action that hides itself once the machine is already current:
787    /// pair the update job with a `check:` that reports `ok` when up to
788    /// date and gate on `is: [fail]`.
789    ///
790    /// Evaluated agent-side at `jobs.list` time against the live
791    /// `StateSnapshot.checks`, which is **keyed by check name** — so the
792    /// detector `check:` and this job may live in *different* manifests and
793    /// still share one slug. Distinct from [`visible_to`](ClientHint::visible_to):
794    /// that gates BOTH listing and `jobs.execute` (an authorization
795    /// boundary); `show_when` gates listing ONLY (a UX hint), so it can't
796    /// cause a list/execute race. New field ⇒ #492 wire rule.
797    ///
798    /// [`check:`]: crate::manifest::CheckHint
799    #[serde(default, skip_serializing_if = "Option::is_none")]
800    pub show_when: Option<ShowWhen>,
801    /// Optional **confirmation-dialog** config for the Client App's 実行
802    /// button.
803    ///
804    /// `None` ⇒ the historical default: the client shows a modal
805    /// confirmation with a built-in 「「{name}」を実行しますか?」 message
806    /// before firing the job (a mis-click guard for a possibly heavy /
807    /// destructive action). When set, the operator controls it:
808    /// - a bare bool — `confirm: false` runs immediately with **no** prompt;
809    ///   `confirm: true` is the same as omitting the block (default message);
810    /// - a struct — `confirm: { message: "…" }` shows the dialog with a
811    ///   custom message (and, redundantly with the scalar, `enabled: false`
812    ///   to suppress it).
813    ///
814    /// Gates the END-USER Client App surface only — the operator `POST
815    /// /api/exec` path never consults `client:`, so an operator-driven run
816    /// is unaffected. New field ⇒ #492 wire rule (`serde(default)` +
817    /// `skip_serializing_if`). Deserializes from bool-or-struct via
818    /// [`de_confirm`]; the JSON schema advertises the struct form (the
819    /// scalar is author ergonomics, like [`ShowWhen::is`]).
820    #[serde(
821        default,
822        deserialize_with = "de_confirm",
823        skip_serializing_if = "Option::is_none"
824    )]
825    pub confirm: Option<ConfirmHint>,
826    /// Optional **unlock scope** — the "裏コマンド" display gate. `None` (the
827    /// overwhelming default) ⇒ the job behaves as it always has. `Some(scope)`
828    /// ⇒ the job is **hidden from `jobs.list`** unless the calling OS user
829    /// currently holds an unlock grant for that scope, obtained by typing the
830    /// operator's secret code into the Client App (`support.unlock`).
831    ///
832    /// The intended use is helpdesk-only actions: a job that has no business
833    /// sitting in an end user's everyday catalog, but which the IT desk can
834    /// surface in seconds while walking that user through a problem — without
835    /// an operator-side exec, which needs SPA access and a correctly-cased
836    /// `pc_id`.
837    ///
838    /// The scope is a free-form slug (`support`, `admin`, …) matched against
839    /// the scopes configured in `ServerSettings::support_codes`, so one
840    /// deployment can run a first-line code and a stronger administrator code
841    /// side by side, each revealing a different set of jobs. A scope with no
842    /// configured code opens for nobody — a typo hides the job rather than
843    /// exposing it.
844    ///
845    /// **Listing only, like [`show_when`](ClientHint::show_when) and unlike
846    /// [`visible_to`](ClientHint::visible_to).** The agent does NOT re-check
847    /// it in `jobs.execute`, which has two consequences worth being explicit
848    /// about:
849    ///
850    /// - Anything the user can see, they can run — no race where the row is
851    ///   visible, the grant lapses, and pressing 実行 fails on a button they
852    ///   were just looking at.
853    /// - It is therefore **not a security boundary**: a standard user who
854    ///   speaks KLP to the agent's pipe directly and knows the job id can
855    ///   still run it. Approval controls for privileged work live on the
856    ///   operator (SPA) exec path; this hides a button, it does not guard a
857    ///   capability.
858    ///
859    /// The operator paths are unaffected in both directions: `POST
860    /// /api/exec/{job_id}` and `kanade exec` never consult `client:`, so an
861    /// operator can run the job on any PC whether or not anyone unlocked it.
862    /// New field ⇒ #492 wire rule (`serde(default)` + `skip_serializing_if`).
863    #[serde(default, skip_serializing_if = "Option::is_none")]
864    pub unlock: Option<String>,
865}
866
867/// Confirmation-dialog config for a [`ClientHint`] — see
868/// [`ClientHint::confirm`]. Controls the Client App's pre-run modal:
869/// whether it appears at all (`enabled`) and what it says (`message`).
870///
871/// Authored as either a bare bool (`confirm: false` / `true`) or a struct
872/// (`confirm: { message: "…" }`); both normalise here via [`de_confirm`].
873#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
874pub struct ConfirmHint {
875    /// Whether the Client App shows the confirmation dialog before running.
876    /// `false` fires the job immediately with no prompt. Defaults to `true`
877    /// (so an author who only sets `message` still gets the dialog, and the
878    /// struct form never accidentally suppresses it).
879    #[serde(default = "default_confirm_enabled")]
880    pub enabled: bool,
881    /// Custom dialog message. `None` ⇒ the client's built-in
882    /// 「「{name}」を実行しますか?」. Only meaningful while `enabled`;
883    /// rejected if present-but-blank by [`Manifest::validate`].
884    #[serde(default, skip_serializing_if = "Option::is_none")]
885    pub message: Option<String>,
886}
887
888/// `enabled` defaults to `true`: the historical behaviour is "always
889/// confirm", so a struct form that omits `enabled` (e.g. sets only
890/// `message`) still shows the dialog.
891fn default_confirm_enabled() -> bool {
892    true
893}
894
895/// Accept either a bare bool (`confirm: false` / `confirm: true`) or a
896/// struct (`confirm: { message: "…" }`) for [`ClientHint::confirm`],
897/// normalising to a [`ConfirmHint`]. The bool is pure author ergonomics —
898/// `false` ⇒ suppress the dialog, `true` ⇒ default message — while the
899/// struct carries a custom message. Called only when the key is present
900/// (absence is handled by `serde(default)` ⇒ `None`). An explicit
901/// `confirm: null` — which the generated schema permits (the field is
902/// `Option`) — maps to `None` too, so it can't produce a parse error;
903/// deserializing through `Option<BoolOrHint>` handles that cleanly (Gemini
904/// #960).
905fn de_confirm<'de, D>(d: D) -> Result<Option<ConfirmHint>, D::Error>
906where
907    D: serde::Deserializer<'de>,
908{
909    #[derive(Deserialize)]
910    #[serde(untagged)]
911    enum BoolOrHint {
912        Bool(bool),
913        Hint(ConfirmHint),
914    }
915    Ok(Option::<BoolOrHint>::deserialize(d)?.map(|b| match b {
916        BoolOrHint::Bool(enabled) => ConfirmHint {
917            enabled,
918            message: None,
919        },
920        BoolOrHint::Hint(h) => h,
921    }))
922}
923
924/// Dynamic display gate for a [`ClientHint`] — see
925/// [`ClientHint::show_when`]. Shows the job only while the named check's
926/// latest status is one of [`is`](ShowWhen::is).
927#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
928pub struct ShowWhen {
929    /// The `check:` slug (a [`CheckHint::name`](crate::manifest::CheckHint::name))
930    /// whose latest status gates this job. May be defined by a *different*
931    /// manifest: checks are keyed by name in the agent's snapshot, so a
932    /// standalone detector job and this one can share a slug. A check that
933    /// has never run (absent from the snapshot) does NOT match — the job
934    /// stays hidden until the detector first reports (fails closed, like
935    /// `visible_to`).
936    pub check: String,
937    /// The check status(es) in which the job is SHOWN. Accepts a single
938    /// status (`is: fail`) or a list (`is: [fail, unknown]`); both
939    /// deserialize to a `Vec`. The `length(min = 1)` schema constraint +
940    /// [`Manifest::validate`] both reject an empty set (it would match
941    /// nothing and silently hide the job) so schema-driven tooling and the
942    /// write path agree.
943    #[serde(deserialize_with = "de_one_or_many_check_status")]
944    #[schemars(length(min = 1))]
945    pub is: Vec<crate::ipc::state::CheckStatus>,
946}
947
948/// Accept either a single `CheckStatus` (`is: fail`) or a sequence
949/// (`is: [fail, unknown]`) for [`ShowWhen::is`], normalising to a `Vec`.
950/// The scalar form is purely author ergonomics; the JSON schema advertises
951/// the canonical array form (`#[schemars(with = ...)]`).
952fn de_one_or_many_check_status<'de, D>(
953    d: D,
954) -> Result<Vec<crate::ipc::state::CheckStatus>, D::Error>
955where
956    D: serde::Deserializer<'de>,
957{
958    use crate::ipc::state::CheckStatus;
959    #[derive(Deserialize)]
960    #[serde(untagged)]
961    enum OneOrMany {
962        One(CheckStatus),
963        Many(Vec<CheckStatus>),
964    }
965    Ok(match OneOrMany::deserialize(d)? {
966        OneOrMany::One(c) => vec![c],
967        OneOrMany::Many(v) => v,
968    })
969}
970
971/// #720 — one widget on the SPA **Analytics** page: a declarative
972/// aggregation over the `obs_events` table. The backend reads these off
973/// `Manifest::aggregate` (from `BUCKET_JOBS`) at query time and builds
974/// the `json_extract` GROUP BY / time-bucket SQL from these generic
975/// primitives, so an operator can chart any emitted event without a Rust
976/// change. The reference shapes are the attendance dashboards
977/// (presence / app_sample / web_visit), but the same DSL covers logon /
978/// reboot / agent-health trends, etc.
979#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
980pub struct AggregateWidget {
981    /// Where this widget surfaces — an Analytics tab and/or a pinned
982    /// Dashboard card. Same block a view's `sql_widgets:` uses, so the
983    /// two widget kinds are authored identically; previously this was a
984    /// flat `dashboard:` + `pin_dashboard:` pair that meant the same
985    /// thing in a different shape.
986    pub placement: Placement,
987    /// Widget heading. Required, validated non-empty.
988    pub title: String,
989    /// Optional one-line subtitle shown muted under the `title` on the
990    /// Analytics page — room for a unit, a caveat, or what the number
991    /// means ("samples × 2 min", "Security 4624 only"). Rejected if
992    /// present-but-blank.
993    #[serde(default, skip_serializing_if = "Option::is_none")]
994    pub description: Option<String>,
995    /// Optional sort weight (#743). Once the order-aware sort lands (PR2)
996    /// widgets render in `(order, dashboard, title)` order, so a lower
997    /// `order` pulls a widget — and its tab — earlier; equal/absent `order`
998    /// falls back to the alphabetical `(dashboard, title)` ordering. Treated
999    /// as `0` when unset, so a fleet with no `order` anywhere stays purely
1000    /// alphabetical (today's behaviour); negatives are allowed to pin
1001    /// something first. (This field only carries the value; the backend
1002    /// applies it.)
1003    #[serde(default, skip_serializing_if = "Option::is_none")]
1004    pub order: Option<i32>,
1005    /// `pc` rolls up a single selected PC; `fleet` rolls up all PCs
1006    /// (and unlocks `group_by: pc_id` to rank PCs against each other).
1007    /// Defaults to `pc`.
1008    #[serde(default)]
1009    pub scope: AggregateScope,
1010    /// `obs_events.kind` this widget reads (e.g. `app_sample`,
1011    /// `presence`, `unexpected_shutdown`). Required for every aggregation
1012    /// render (`bar`/`gauge`/`timeline`/`stat`); rejected for
1013    /// `op_timeline`, which reconstructs a fixed multi-kind operational
1014    /// swimlane (power/session/sleep) baked into the SPA and so reads no
1015    /// single `kind`.
1016    #[serde(default, skip_serializing_if = "Option::is_none")]
1017    pub kind: Option<String>,
1018    /// Optional `obs_events.source` filter, when one `kind` is emitted by
1019    /// more than one collector.
1020    #[serde(default, skip_serializing_if = "Option::is_none")]
1021    pub source: Option<String>,
1022    /// How to roll the matching events up. See [`AggregateAgg`]. Required
1023    /// for every aggregation render; rejected for `op_timeline` (which
1024    /// performs no rollup — it returns the raw operational events and the
1025    /// SPA folds them into lane spans).
1026    #[serde(default, skip_serializing_if = "Option::is_none")]
1027    pub agg: Option<AggregateAgg>,
1028    /// Dotted JSON path (no `$.` prefix) to group by for `agg: count` /
1029    /// `sum` — e.g. `foreground.app`. The literal `pc_id` is special:
1030    /// it groups by the `pc_id` column (fleet ranking), not a payload
1031    /// field. Omit for a single total. Required when `agg: sum` needs a
1032    /// breakdown; for `agg: count` omitting it yields the grand total.
1033    #[serde(default, skip_serializing_if = "Option::is_none")]
1034    pub group_by: Option<String>,
1035    /// Dotted JSON path to a boolean for `agg: ratio` (e.g. `active`):
1036    /// the widget reports `true_count / total`. Required when `agg: ratio`.
1037    #[serde(default, skip_serializing_if = "Option::is_none")]
1038    pub bool_path: Option<String>,
1039    /// Dotted JSON path to a number for `agg: sum`. Required when `agg: sum`.
1040    #[serde(default, skip_serializing_if = "Option::is_none")]
1041    pub value_path: Option<String>,
1042    /// Optional value transform applied before grouping. Currently only
1043    /// `host` (parse a URL down to its host) — used by the top-sites
1044    /// widget, where SQLite can't parse a URL so the backend does it in
1045    /// Rust. See [`AggregateTransform`].
1046    #[serde(default, skip_serializing_if = "Option::is_none")]
1047    pub transform: Option<AggregateTransform>,
1048    /// Optional sampling cadence in minutes. When set, a `count` is also
1049    /// reported as estimated time (`count × sample_minutes`) — e.g. a
1050    /// 2-minute app sampler turns 11 samples into ~22 minutes. Must be ≥ 1.
1051    #[serde(default, skip_serializing_if = "Option::is_none")]
1052    #[schemars(range(min = 1))]
1053    pub sample_minutes: Option<u32>,
1054    /// Grouped values to drop from the rollup (e.g. `["LockApp"]` so the
1055    /// lock screen doesn't top the app ranking). Empty by default.
1056    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1057    pub exclude: Vec<String>,
1058    /// Optional time bucketing — `hour` buckets events by local
1059    /// hour-of-day for a `timeline` render. See [`AggregateTimeBucket`].
1060    #[serde(default, skip_serializing_if = "Option::is_none")]
1061    pub time_bucket: Option<AggregateTimeBucket>,
1062    /// Top-N cap for grouped renders (`bar`). Defaults to 10 when unset.
1063    #[serde(default, skip_serializing_if = "Option::is_none")]
1064    #[schemars(range(min = 1))]
1065    pub limit: Option<u32>,
1066    /// Which widget the SPA draws. See [`AggregateRender`].
1067    pub render: AggregateRender,
1068}
1069
1070/// How much of the widget grid a widget asks for (#1257).
1071///
1072/// Both the Analytics page and the Dashboard's pinned strip lay widgets
1073/// out two-up on a wide screen. Until this existed, the width was
1074/// decided purely by `render`: `bar` / `timeline` / `op_timeline` /
1075/// `table` always claimed the full row, everything else a single
1076/// column. That is a sensible default but a bad rule — an operator who
1077/// pins two `bar` widgets that answer the same question (app usage
1078/// alongside browsing, say) cannot put them side by side, and each
1079/// pushes the rest of the page further down.
1080///
1081/// Absent ⇒ keep the per-`render` default, so every existing manifest
1082/// renders exactly as before.
1083#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1084#[serde(rename_all = "lowercase")]
1085#[non_exhaustive]
1086pub enum WidgetWidth {
1087    /// Span the whole widget row.
1088    Full,
1089    /// Take one column, so a sibling can share the row.
1090    Half,
1091    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1092    /// Rendered as if unset — a width hint is presentation-only, so an
1093    /// unreadable variant must not drop the widget.
1094    #[serde(other)]
1095    Unknown,
1096}
1097
1098/// Per-PC vs fleet-wide rollup for an [`AggregateWidget`].
1099#[derive(
1100    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
1101)]
1102#[serde(rename_all = "lowercase")]
1103#[non_exhaustive]
1104pub enum AggregateScope {
1105    /// Roll up the single PC the operator selected. The default.
1106    #[default]
1107    Pc,
1108    /// Roll up across every PC. Unlocks `group_by: pc_id`.
1109    Fleet,
1110    /// #492 forward-compat catch-all — a Manifest is read fleet-wide, so
1111    /// an older reader must tolerate a future variant rather than failing
1112    /// to decode the whole job. The backend skips an `Unknown` widget.
1113    #[serde(other)]
1114    Unknown,
1115}
1116
1117/// The rollup function for an [`AggregateWidget`].
1118#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1119#[serde(rename_all = "lowercase")]
1120#[non_exhaustive]
1121pub enum AggregateAgg {
1122    /// Row count, optionally grouped (`group_by`) and time-estimated
1123    /// (`sample_minutes`).
1124    Count,
1125    /// `true_count / total` over `bool_path`.
1126    Ratio,
1127    /// Sum of `value_path`, optionally grouped.
1128    Sum,
1129    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1130    #[serde(other)]
1131    Unknown,
1132}
1133
1134/// Optional pre-grouping value transform for an [`AggregateWidget`].
1135#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1136#[serde(rename_all = "lowercase")]
1137#[non_exhaustive]
1138pub enum AggregateTransform {
1139    /// Parse the grouped value as a URL and keep only its host.
1140    Host,
1141    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1142    #[serde(other)]
1143    Unknown,
1144}
1145
1146/// Time bucketing for an [`AggregateWidget`] (drives a `timeline`).
1147#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1148#[serde(rename_all = "lowercase")]
1149#[non_exhaustive]
1150pub enum AggregateTimeBucket {
1151    /// Bucket by local hour-of-day (0–23), summed over the window.
1152    Hour,
1153    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1154    #[serde(other)]
1155    Unknown,
1156}
1157
1158/// Which visual the SPA renders an [`AggregateWidget`] as.
1159#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1160#[serde(rename_all = "lowercase")]
1161#[non_exhaustive]
1162pub enum AggregateRender {
1163    /// Ranked horizontal bars (a grouped `count` / `sum`).
1164    Bar,
1165    /// A single ratio dial (`agg: ratio`).
1166    Gauge,
1167    /// 24-hour activity strip (`time_bucket: hour`).
1168    Timeline,
1169    /// A single headline number (an ungrouped total).
1170    Stat,
1171    /// Per-PC operational swimlane (power / session / sleep) reconstructed
1172    /// from a fixed multi-kind event set. Unlike the aggregation renders it
1173    /// reads no single `kind`/`agg`: the backend returns the raw events in
1174    /// the window and the SPA folds them into lane spans (shared with the
1175    /// Events page strip). Per-PC only (`scope: pc`).
1176    #[serde(rename = "op_timeline")]
1177    OpTimeline,
1178    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1179    #[serde(other)]
1180    Unknown,
1181}
1182
1183/// True if `p` is a well-formed dotted JSON path of `[A-Za-z0-9_]`
1184/// segments joined by single dots — the shape safe to bind into
1185/// `json_extract(payload, '$.' || ?)`. The charset blocks injection; the
1186/// segment check additionally rejects `"."`, `".foo"`, `"foo."`,
1187/// `"foo..bar"`, which would pass the charset but produce a malformed
1188/// `$.` path that errors at query time. Accepts `pc_id`, `foreground.app`,
1189/// `active`, etc.
1190fn is_valid_json_path(p: &str) -> bool {
1191    !p.is_empty()
1192        && p.split('.').all(|seg| {
1193            !seg.is_empty() && seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
1194        })
1195}
1196
1197/// Per-widget validation for a list of [`AggregateWidget`]s — shared by
1198/// the `aggregate:` job hint ([`Manifest::validate`]) and the standalone
1199/// [`View`] resource (#743) so the two can't diverge. `field` names the
1200/// containing key for error messages (`"aggregate"` or `"widgets"`).
1201///
1202/// Enforces: non-empty list; non-empty dashboard/title (and `kind`/`agg`
1203/// for every aggregation render); a blank-when-set `source`; rejection of
1204/// any #492 `Unknown` enum (an operator typo at create time); safe dotted
1205/// JSON paths; the value path each `agg` needs (and rejection of mis-paired
1206/// ones); `pc_id` grouping only in `fleet` scope; `transform`/`limit`/
1207/// `exclude` only with a `group_by`; positive `limit`/`sample_minutes`;
1208/// `gauge`⇔`ratio`; and `timeline`⇔`time_bucket`. A `render: op_timeline`
1209/// widget is validated separately (per-PC, no aggregation knobs) — see
1210/// [`validate_op_timeline_widget`].
1211pub fn validate_aggregate_widgets(widgets: &[AggregateWidget], field: &str) -> Result<(), String> {
1212    if widgets.is_empty() {
1213        return Err(format!(
1214            "`{field}:` must list at least one widget when present"
1215        ));
1216    }
1217    for (i, w) in widgets.iter().enumerate() {
1218        let at = format!("{field}[{i}]");
1219        if w.title.trim().is_empty() {
1220            return Err(format!("{at}.title must not be empty"));
1221        }
1222        // Same rule the SQL widgets get: a widget that is neither on a
1223        // tab nor pinned renders nowhere, which is never what was meant.
1224        validate_placement(&w.placement, &at)?;
1225        // A present-but-blank `description` renders an empty muted line —
1226        // reject it so the subtitle only shows when it says something.
1227        if let Some(description) = &w.description {
1228            if description.trim().is_empty() {
1229                return Err(format!("{at}.description must not be empty when set"));
1230            }
1231        }
1232        // Reject values that fell through to the #492 `Unknown` catch-all:
1233        // at create time on the current version that's an operator typo. (A
1234        // genuinely-future variant only reaches an older reader via a stored
1235        // resource, which is never re-validated, so forward-compat holds.)
1236        if w.scope == AggregateScope::Unknown {
1237            return Err(format!("{at}.scope is not a known value (pc | fleet)"));
1238        }
1239        if w.render == AggregateRender::Unknown {
1240            return Err(format!(
1241                "{at}.render is not a known value (bar | gauge | timeline | stat | op_timeline)"
1242            ));
1243        }
1244        // `op_timeline` reconstructs a fixed per-PC operational swimlane
1245        // (power/session/sleep) from a baked-in multi-kind set — it uses none
1246        // of the aggregation knobs, so validate it on its own terms (per-PC,
1247        // no `kind`/`agg`/grouping) and skip the rollup rules below.
1248        if w.render == AggregateRender::OpTimeline {
1249            validate_op_timeline_widget(w, &at)?;
1250            continue;
1251        }
1252        // Every other render is an aggregation over a single `kind`.
1253        if w.kind.as_deref().map(str::trim).unwrap_or("").is_empty() {
1254            return Err(format!("{at}.kind must not be empty"));
1255        }
1256        let agg = match w.agg {
1257            Some(AggregateAgg::Unknown) => {
1258                return Err(format!(
1259                    "{at}.agg is not a known value (count | ratio | sum)"
1260                ));
1261            }
1262            Some(agg) => agg,
1263            None => return Err(format!("{at}.agg is required")),
1264        };
1265        // A present-but-blank `source` is a no-op filter — reject like the
1266        // other blank-when-set guards.
1267        if let Some(source) = &w.source {
1268            if source.trim().is_empty() {
1269                return Err(format!("{at}.source must not be empty when set"));
1270            }
1271        }
1272        if w.transform == Some(AggregateTransform::Unknown) {
1273            return Err(format!("{at}.transform is not a known value (host)"));
1274        }
1275        if w.time_bucket == Some(AggregateTimeBucket::Unknown) {
1276            return Err(format!("{at}.time_bucket is not a known value (hour)"));
1277        }
1278        for (label, path) in [
1279            ("group_by", &w.group_by),
1280            ("bool_path", &w.bool_path),
1281            ("value_path", &w.value_path),
1282        ] {
1283            if let Some(p) = path {
1284                if !is_valid_json_path(p) {
1285                    return Err(format!(
1286                        "{at}.{label} '{p}' must be a dotted JSON path of [A-Za-z0-9_] segments"
1287                    ));
1288                }
1289            }
1290        }
1291        // Each agg uses exactly one value path; reject a mis-paired path so
1292        // a typo fails at create rather than being ignored.
1293        match agg {
1294            // count: grouped → ranking, ungrouped → grand total.
1295            AggregateAgg::Count => {
1296                for (label, path) in [("bool_path", &w.bool_path), ("value_path", &w.value_path)] {
1297                    if path.is_some() {
1298                        return Err(format!("{at}.agg=count does not use `{label}`"));
1299                    }
1300                }
1301            }
1302            AggregateAgg::Ratio => {
1303                if w.bool_path.is_none() {
1304                    return Err(format!("{at}.agg=ratio requires `bool_path`"));
1305                }
1306                if w.value_path.is_some() {
1307                    return Err(format!("{at}.agg=ratio does not use `value_path`"));
1308                }
1309            }
1310            AggregateAgg::Sum => {
1311                if w.value_path.is_none() {
1312                    return Err(format!("{at}.agg=sum requires `value_path`"));
1313                }
1314                if w.bool_path.is_some() {
1315                    return Err(format!("{at}.agg=sum does not use `bool_path`"));
1316                }
1317            }
1318            // Rejected above; arm exists only for exhaustiveness.
1319            AggregateAgg::Unknown => {}
1320        }
1321        // Ranking PCs against each other only means something across the
1322        // fleet — within one PC it's a single bar.
1323        if w.group_by.as_deref() == Some("pc_id") && w.scope != AggregateScope::Fleet {
1324            return Err(format!(
1325                "{at}.group_by: pc_id is only valid with scope: fleet"
1326            ));
1327        }
1328        // `transform` rewrites the grouped PAYLOAD value (URL→host); it's
1329        // meaningless on a `pc_id` grouping (the pc_id column, not a payload
1330        // field), so reject the combo at create time.
1331        if w.transform.is_some() && w.group_by.as_deref() == Some("pc_id") {
1332            return Err(format!("{at}.transform is not valid with group_by: pc_id"));
1333        }
1334        // limit / transform / exclude all operate on grouped values, so
1335        // without a `group_by` they're silent no-ops — reject.
1336        if w.group_by.is_none() {
1337            if w.limit.is_some() {
1338                return Err(format!("{at}.limit requires `group_by`"));
1339            }
1340            if w.transform.is_some() {
1341                return Err(format!("{at}.transform requires `group_by`"));
1342            }
1343            if !w.exclude.is_empty() {
1344                return Err(format!("{at}.exclude requires `group_by`"));
1345            }
1346        }
1347        if w.limit == Some(0) {
1348            return Err(format!("{at}.limit must be > 0"));
1349        }
1350        if w.sample_minutes == Some(0) {
1351            return Err(format!("{at}.sample_minutes must be > 0"));
1352        }
1353        for ex in &w.exclude {
1354            if ex.trim().is_empty() {
1355                return Err(format!("{at}.exclude must not contain empty entries"));
1356            }
1357        }
1358        // A gauge draws a single ratio dial — only meaningful for agg: ratio.
1359        if w.render == AggregateRender::Gauge && agg != AggregateAgg::Ratio {
1360            return Err(format!("{at}.render=gauge is only valid with agg: ratio"));
1361        }
1362        // A timeline needs a bucket; a bucket on any other render is a no-op
1363        // that signals operator confusion — reject both.
1364        match (w.render, &w.time_bucket) {
1365            (AggregateRender::Timeline, None) => {
1366                return Err(format!("{at}.render=timeline requires `time_bucket`"));
1367            }
1368            (r, Some(_)) if r != AggregateRender::Timeline => {
1369                return Err(format!(
1370                    "{at}.time_bucket is only valid with render: timeline"
1371                ));
1372            }
1373            _ => {}
1374        }
1375    }
1376    Ok(())
1377}
1378
1379/// Validate a `render: op_timeline` widget. It draws a fixed per-PC
1380/// operational swimlane (power / session / sleep) reconstructed by the SPA
1381/// from a baked-in multi-kind event set, so it uses none of the aggregation
1382/// knobs: require `scope: pc` and reject every field that only makes sense
1383/// for a rollup (`kind`/`source`/`agg`/`group_by`/`bool_path`/`value_path`/
1384/// `transform`/`sample_minutes`/`exclude`/`time_bucket`/`limit`). Rejecting
1385/// the unused fields (rather than ignoring them) keeps an operator typo from
1386/// silently doing nothing, matching the rest of this validator.
1387fn validate_op_timeline_widget(w: &AggregateWidget, at: &str) -> Result<(), String> {
1388    // Per-PC only: a fleet-wide swimlane of every PC's spans is unbounded
1389    // and unreadable, and the backend only computes it in per-PC scope.
1390    if w.scope != AggregateScope::Pc {
1391        return Err(format!("{at}.render=op_timeline requires scope: pc"));
1392    }
1393    // Each unused field, with the name the operator wrote, so the error
1394    // points at exactly what to delete.
1395    if w.kind.is_some() {
1396        return Err(format!("{at}.render=op_timeline does not use `kind`"));
1397    }
1398    if w.source.is_some() {
1399        return Err(format!("{at}.render=op_timeline does not use `source`"));
1400    }
1401    if w.agg.is_some() {
1402        return Err(format!("{at}.render=op_timeline does not use `agg`"));
1403    }
1404    for (label, set) in [
1405        ("group_by", w.group_by.is_some()),
1406        ("bool_path", w.bool_path.is_some()),
1407        ("value_path", w.value_path.is_some()),
1408        ("transform", w.transform.is_some()),
1409        ("sample_minutes", w.sample_minutes.is_some()),
1410        ("time_bucket", w.time_bucket.is_some()),
1411        ("limit", w.limit.is_some()),
1412        ("exclude", !w.exclude.is_empty()),
1413    ] {
1414        if set {
1415            return Err(format!("{at}.render=op_timeline does not use `{label}`"));
1416        }
1417    }
1418    Ok(())
1419}
1420
1421/// Default materialization cadence for a [`SqlWidget`] whose `refresh` is
1422/// unset — 1 hour. A view over feed/inventory tables changes only as fast as
1423/// its underlying feed refresh (often daily), so an hour is fresh enough while
1424/// keeping an expensive correlation join off the ~30s Dashboard poll path.
1425pub const DEFAULT_VIEW_REFRESH: std::time::Duration = std::time::Duration::from_secs(3600);
1426
1427/// #vuln-roadmap PR3: a **SQL-backed, materialized** widget on a [`View`].
1428///
1429/// Where an [`AggregateWidget`] encodes an `obs_events` rollup in structured
1430/// YAML fields, a `SqlWidget` carries a raw read-only `SELECT`/`WITH` over the
1431/// projector's tables (inventory `explode:` tables, `feeds`, `check_status`,
1432/// …) — the correlation that powers a vulnerability / EOL / license dashboard
1433/// is just a `JOIN`, far more expressive than a YAML DSL. The backend runs the
1434/// query in the read-only sandbox (`api::query`), caches the result on the
1435/// `refresh` cadence, and maps it to the same render-ready shape the existing
1436/// widget components consume, via [`RenderSpec`]. See [`View::sql_widgets`].
1437#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1438pub struct SqlWidget {
1439    /// Widget heading. Required, validated non-empty.
1440    pub title: String,
1441    /// Optional muted subtitle (a unit, a caveat). Rejected if present-blank.
1442    #[serde(default, skip_serializing_if = "Option::is_none")]
1443    pub description: Option<String>,
1444    /// The read-only SQL. Executed in the `api::query` sandbox: a single
1445    /// `SELECT`/`WITH` on a `SQLITE_OPEN_READONLY` connection, row-capped and
1446    /// time-bounded. The backend validates it read-only at `view create` and
1447    /// again at run time; a write verb / stacked statement is rejected.
1448    pub query: String,
1449    /// How the query's result columns map to a visual — see [`RenderSpec`].
1450    pub render: RenderSpec,
1451    /// Materialization cadence as a humantime duration (`"6h"`, `"30m"`).
1452    /// Absent ⇒ [`DEFAULT_VIEW_REFRESH`]. The backend re-runs the query at
1453    /// most this often; reads in between hit the cache.
1454    #[serde(default, skip_serializing_if = "Option::is_none")]
1455    pub refresh: Option<String>,
1456    /// Where the widget surfaces — an Analytics tab and/or a pinned Dashboard
1457    /// card. At least one must be set (else it renders nowhere).
1458    pub placement: Placement,
1459}
1460
1461impl SqlWidget {
1462    /// The effective refresh cadence — the parsed `refresh` or
1463    /// [`DEFAULT_VIEW_REFRESH`]. Falls back to the default on an unparseable
1464    /// value rather than panicking on the read path (validation already
1465    /// rejected a bad value at `view create`).
1466    pub fn refresh_interval(&self) -> std::time::Duration {
1467        self.refresh
1468            .as_deref()
1469            .and_then(|s| humantime::parse_duration(s).ok())
1470            .unwrap_or(DEFAULT_VIEW_REFRESH)
1471    }
1472}
1473
1474/// How a [`SqlWidget`]'s SQL result columns map onto a visual. A `kind` names
1475/// the chart; the channel fields (`value`, `label`, `columns`, …) name which
1476/// result columns feed it. Only the channels a `kind` uses are read; the
1477/// backend validates the named columns exist in the result. New chart types
1478/// are "one renderer + the same mapping", so this stays a flat, additive shape.
1479#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Hash)]
1480pub struct RenderSpec {
1481    /// Which visual to render the result as.
1482    pub kind: RenderKind,
1483    /// `table` only: the columns to show, in order. Absent ⇒ every result
1484    /// column (the universal default).
1485    #[serde(default, skip_serializing_if = "Option::is_none")]
1486    pub columns: Option<Vec<String>>,
1487    /// `table` only: optional per-column header relabelling (result column →
1488    /// display name). Columns not listed keep their SQL name.
1489    #[serde(default, skip_serializing_if = "Option::is_none")]
1490    pub labels: Option<std::collections::BTreeMap<String, String>>,
1491    /// `stat` / `bar` / `pie` / `gauge`: the result column holding the numeric
1492    /// value (`stat`/`gauge` read the first row; `bar`/`pie` read every row).
1493    #[serde(default, skip_serializing_if = "Option::is_none")]
1494    pub value: Option<String>,
1495    /// `bar` / `pie`: the result column holding each row's category label.
1496    #[serde(default, skip_serializing_if = "Option::is_none")]
1497    pub label: Option<String>,
1498    /// `bar` / `pie`: keep only the top-N rows (by value). Absent ⇒ all rows.
1499    #[serde(default, skip_serializing_if = "Option::is_none")]
1500    pub limit: Option<u32>,
1501    /// `pie` only: render as a donut (a hole with the total in the centre).
1502    #[serde(default, skip_serializing_if = "Option::is_none")]
1503    pub donut: Option<bool>,
1504    /// `gauge` only: the numerator column (paired with `den`). Alternative to
1505    /// a precomputed `value` ratio.
1506    #[serde(default, skip_serializing_if = "Option::is_none")]
1507    pub num: Option<String>,
1508    /// `gauge` only: the denominator column (paired with `num`).
1509    #[serde(default, skip_serializing_if = "Option::is_none")]
1510    pub den: Option<String>,
1511}
1512
1513/// The chart kind for a [`RenderSpec`]. `table` and `pie` are new in PR3; the
1514/// rest reuse the existing `obs_events` widget renderers.
1515#[derive(
1516    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash, Default,
1517)]
1518#[serde(rename_all = "lowercase")]
1519pub enum RenderKind {
1520    /// The full result grid (new renderer). The universal default.
1521    #[default]
1522    Table,
1523    /// A single headline number from the first row's `value` cell.
1524    Stat,
1525    /// Ranked horizontal bars — `label` + `value` per row, optional top-N.
1526    Bar,
1527    /// Parts-of-a-whole (new renderer) — `label` + `value` per row.
1528    Pie,
1529    /// A ratio dial — a `value` ratio, or a `num`/`den` pair.
1530    Gauge,
1531    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1532    #[serde(other)]
1533    Unknown,
1534}
1535
1536/// Where a widget surfaces in the SPA — an Analytics tab and/or a pinned
1537/// Dashboard card. Shared verbatim by both widget kinds: a job's
1538/// [`AggregateWidget`] and a view's [`SqlWidget`] are authored the same
1539/// way. (#1257 folded the aggregate side's flat `dashboard:` +
1540/// `pin_dashboard:` pair into this block; expressing one idea in two
1541/// shapes meant a width had to be invented twice.)
1542#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1543pub struct Placement {
1544    /// The Analytics tab this widget groups under. Absent ⇒ not shown on
1545    /// the Analytics page.
1546    ///
1547    /// Written either as a bare tab name or as a block, so the common
1548    /// case stays one line and a width is there when it's wanted:
1549    ///
1550    /// ```yaml
1551    /// analytics: app-usage
1552    /// # or
1553    /// analytics: { tab: app-usage, width: half }
1554    /// ```
1555    #[serde(
1556        default,
1557        deserialize_with = "de_analytics",
1558        skip_serializing_if = "Option::is_none"
1559    )]
1560    #[schemars(with = "Option<AnalyticsPlacementSchema>")]
1561    pub analytics: Option<AnalyticsPlacement>,
1562    /// Promote to the main Dashboard (reuses #900's pinned section). Absent ⇒
1563    /// not pinned.
1564    #[serde(default, skip_serializing_if = "Option::is_none")]
1565    pub dashboard: Option<DashboardPlacement>,
1566}
1567
1568impl Placement {
1569    /// True when the widget is pinned to the main Dashboard.
1570    pub fn is_pinned(&self) -> bool {
1571        self.dashboard.as_ref().is_some_and(|d| d.pin)
1572    }
1573    /// The Analytics tab name, or a fallback so a dashboard-only widget still
1574    /// carries a group label for the shared widget list.
1575    pub fn tab(&self) -> &str {
1576        self.analytics
1577            .as_ref()
1578            .map_or("Dashboard", |a| a.tab.as_str())
1579    }
1580    /// Width to render at on the surface being served. The two surfaces
1581    /// are independent: the Dashboard's pinned strip is a summary where
1582    /// two full-width widgets push everything else below the fold, while
1583    /// an Analytics tab gives the widget the room and usually wants the
1584    /// per-`render` default.
1585    pub fn width_for(&self, pinned: bool) -> Option<WidgetWidth> {
1586        if pinned {
1587            self.dashboard.as_ref().and_then(|d| d.width)
1588        } else {
1589            self.analytics.as_ref().and_then(|a| a.width)
1590        }
1591    }
1592}
1593
1594/// The `placement.analytics` block — see [`Placement::analytics`].
1595///
1596/// Deserialized from a bare string as well as a map, so
1597/// `analytics: app-usage` and `analytics: { tab: app-usage, width: half }`
1598/// both work. Serialized back as a bare string whenever no `width` is set,
1599/// which keeps the stored resource JSON in its terse form for every
1600/// widget that doesn't ask for a width — i.e. almost all of them.
1601#[derive(Deserialize, schemars::JsonSchema, Debug, Clone)]
1602pub struct AnalyticsPlacement {
1603    /// Tab this widget groups under. Widgets from every job/view are
1604    /// collected and grouped by this label, so the same string across
1605    /// sources builds one multi-source dashboard.
1606    pub tab: String,
1607    /// How much of the Analytics row this widget takes (#1257). Absent ⇒
1608    /// the per-`render` default.
1609    #[serde(default, skip_serializing_if = "Option::is_none")]
1610    pub width: Option<WidgetWidth>,
1611}
1612
1613impl Serialize for AnalyticsPlacement {
1614    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1615        match self.width {
1616            None => s.serialize_str(&self.tab),
1617            Some(width) => {
1618                use serde::ser::SerializeStruct;
1619                let mut st = s.serialize_struct("AnalyticsPlacement", 2)?;
1620                st.serialize_field("tab", &self.tab)?;
1621                st.serialize_field("width", &width)?;
1622                st.end()
1623            }
1624        }
1625    }
1626}
1627
1628/// Schema-only mirror of the two shapes [`de_analytics`] accepts.
1629///
1630/// Needed because the generated schema is what the SPA's YAML editor
1631/// validates against. Pointing `schemars` at [`AnalyticsPlacement`]
1632/// directly advertises only the block form, which would put a red
1633/// squiggle under `analytics: app-usage` — the bare-string form every
1634/// widget in `configs/` actually uses, and the one the field
1635/// serializes back to. The deserializer would still accept it; the
1636/// operator would just be told, in the editor we ship, that correct
1637/// config is wrong.
1638///
1639/// (Contrast [`ConfirmHint`], where the scalar really is a rarely-used
1640/// shorthand for the canonical struct, so advertising the struct alone
1641/// is a reasonable trade. Here the scalar is the canonical form.)
1642#[derive(schemars::JsonSchema)]
1643#[serde(untagged)]
1644#[allow(dead_code)] // constructed only by `schemars`, never at run time
1645enum AnalyticsPlacementSchema {
1646    /// `analytics: app-usage`
1647    Tab(String),
1648    /// `analytics: { tab: app-usage, width: half }`
1649    Block(AnalyticsPlacement),
1650}
1651
1652/// Reads [`Placement::analytics`] from either a bare tab name or a block.
1653/// An explicit `analytics: null` maps to `None` rather than erroring, the
1654/// same way [`de_confirm`] handles it.
1655fn de_analytics<'de, D>(d: D) -> Result<Option<AnalyticsPlacement>, D::Error>
1656where
1657    D: serde::Deserializer<'de>,
1658{
1659    #[derive(Deserialize)]
1660    #[serde(untagged)]
1661    enum StrOrBlock {
1662        Tab(String),
1663        Block(AnalyticsPlacement),
1664    }
1665    Ok(Option::<StrOrBlock>::deserialize(d)?.map(|v| match v {
1666        StrOrBlock::Tab(tab) => AnalyticsPlacement { tab, width: None },
1667        StrOrBlock::Block(b) => b,
1668    }))
1669}
1670
1671/// The `placement.dashboard` block — see [`Placement::dashboard`].
1672#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1673pub struct DashboardPlacement {
1674    /// Pin this widget to the main Dashboard's promoted section.
1675    #[serde(default)]
1676    pub pin: bool,
1677    /// How much of the Dashboard's pinned row this widget takes (#1257).
1678    /// Absent ⇒ the per-`render` default. See [`WidgetWidth`].
1679    ///
1680    /// Nested under `dashboard` on purpose: the Dashboard's pinned strip
1681    /// is a summary where two full-width widgets push everything else
1682    /// below the fold, while the Analytics page gives a widget the tab to
1683    /// itself and wants the default. Living here says "Dashboard only"
1684    /// structurally, instead of needing a `pin_`-prefixed name to say it.
1685    /// An `analytics` width can be added later by promoting that field to
1686    /// a string-or-block, without disturbing this one.
1687    #[serde(default, skip_serializing_if = "Option::is_none")]
1688    pub width: Option<WidgetWidth>,
1689}
1690
1691/// Shared placement rules for both widget kinds. `at` names the widget
1692/// for error messages.
1693///
1694/// A widget that surfaces nowhere is an invisible no-op. A `dashboard:`
1695/// block with `pin: false` doesn't count — it pins nowhere — so gate on
1696/// the effective pin, not the block's presence (Gemini / CodeRabbit).
1697pub fn validate_placement(p: &Placement, at: &str) -> Result<(), String> {
1698    if p.analytics.is_none() && !p.is_pinned() {
1699        return Err(format!(
1700            "{at}.placement must set `analytics` and/or pin to `dashboard` (else the widget renders nowhere)"
1701        ));
1702    }
1703    if let Some(a) = &p.analytics {
1704        if a.tab.trim().is_empty() {
1705            return Err(format!(
1706                "{at}.placement.analytics must not be empty when set"
1707            ));
1708        }
1709    }
1710    Ok(())
1711}
1712
1713/// Per-widget validation for a list of [`SqlWidget`]s — shared by the
1714/// [`View`] resource so authoring errors surface at `view create`. `field`
1715/// names the containing key for error messages. The read-only SQL check is
1716/// NOT here (it lives in the backend `api::query` sandbox, which kanade-shared
1717/// can't depend on) — this validates structure: non-empty title/query, a
1718/// known `kind`, the channels each `kind` needs, a real placement, and a
1719/// parseable `refresh`.
1720pub fn validate_sql_widgets(widgets: &[SqlWidget], field: &str) -> Result<(), String> {
1721    for (i, w) in widgets.iter().enumerate() {
1722        let at = format!("{field}[{i}]");
1723        if w.title.trim().is_empty() {
1724            return Err(format!("{at}.title must not be empty"));
1725        }
1726        if w.query.trim().is_empty() {
1727            return Err(format!("{at}.query must not be empty"));
1728        }
1729        if let Some(description) = &w.description {
1730            if description.trim().is_empty() {
1731                return Err(format!("{at}.description must not be empty when set"));
1732            }
1733        }
1734        if let Some(refresh) = &w.refresh {
1735            humantime::parse_duration(refresh)
1736                .map_err(|e| format!("{at}.refresh '{refresh}' is not a valid duration: {e}"))?;
1737        }
1738        validate_placement(&w.placement, &at)?;
1739        // A per-PC widget (its query binds `:pc_id`) renders only in the
1740        // per-PC Analytics scope, bound to the selected PC. The Dashboard's
1741        // pinned section is fleet-scope and never sends a PC, so a pinned
1742        // per-PC widget would be silently dropped on every request — reject
1743        // the contradiction at create time rather than let it vanish (claude
1744        // review). Literal-aware so a `:pc_id` inside a string literal doesn't
1745        // trip it (see [`rewrite_pc_id_param`]).
1746        if w.placement.is_pinned() && rewrite_pc_id_param(&w.query).1 > 0 {
1747            return Err(format!(
1748                "{at}: a per-PC widget (its query binds `:pc_id`) cannot pin to the Dashboard \
1749                 (the Dashboard is fleet-scope, it never selects a PC) — use `analytics` placement only"
1750            ));
1751        }
1752        validate_render_spec(&w.render, &at)?;
1753    }
1754    Ok(())
1755}
1756
1757/// The named parameter a per-PC [`SqlWidget`] binds to the selected PC. Its
1758/// presence in a widget's query is what makes the widget per-PC.
1759pub const PC_ID_PARAM: &str = ":pc_id";
1760
1761/// Rewrite every *real* `:pc_id` parameter in a widget query to a positional
1762/// `?`, returning `(rewritten_sql, count)`. "Real" = OUTSIDE string literals,
1763/// quoted identifiers and comments, and a whole token (the char after `:pc_id`
1764/// isn't a word char, so `:pc_idx` is left alone). One scanner shared by three
1765/// call sites so they can't disagree on how many `?` SQLite will actually see:
1766///   * per-PC scope detection (`count > 0` ⇒ the widget is per-PC),
1767///   * the backend's bind path (sqlx-sqlite binds POSITIONAL `?` only, not
1768///     `:name`, so the token must be rewritten and bound once per occurrence),
1769///   * and `validate_sql_widgets`' pinned-per-PC rejection above.
1770///
1771/// The literal/comment skipping mirrors the read-only sandbox's
1772/// `strip_sql_noise`, so a `:pc_id` inside `SELECT 'see :pc_id docs'` is copied
1773/// verbatim and NOT counted — it would otherwise be miscounted (a bind-count
1774/// mismatch → `SQLITE_RANGE`) and misclassify the widget's scope (Gemini /
1775/// claude review).
1776pub fn rewrite_pc_id_param(sql: &str) -> (String, usize) {
1777    let mut out = String::with_capacity(sql.len());
1778    let mut count = 0usize;
1779    let mut chars = sql.char_indices().peekable();
1780    while let Some((idx, c)) = chars.next() {
1781        match c {
1782            // String literal / quoted identifier — copy verbatim, honouring the
1783            // doubled-quote escape (`''` / `""` stays inside).
1784            '\'' | '"' => {
1785                out.push(c);
1786                let quote = c;
1787                while let Some((_, d)) = chars.next() {
1788                    out.push(d);
1789                    if d == quote {
1790                        if chars.peek().map(|&(_, e)| e) == Some(quote) {
1791                            let (_, e) = chars.next().unwrap();
1792                            out.push(e);
1793                        } else {
1794                            break;
1795                        }
1796                    }
1797                }
1798            }
1799            // Line comment — copy to end of line.
1800            '-' if chars.peek().map(|&(_, e)| e) == Some('-') => {
1801                out.push(c);
1802                for (_, d) in chars.by_ref() {
1803                    out.push(d);
1804                    if d == '\n' {
1805                        break;
1806                    }
1807                }
1808            }
1809            // Block comment — copy to `*/`.
1810            '/' if chars.peek().map(|&(_, e)| e) == Some('*') => {
1811                out.push(c);
1812                let (_, star) = chars.next().unwrap();
1813                out.push(star);
1814                let mut prev = ' ';
1815                for (_, d) in chars.by_ref() {
1816                    out.push(d);
1817                    if prev == '*' && d == '/' {
1818                        break;
1819                    }
1820                    prev = d;
1821                }
1822            }
1823            // A `:pc_id` token outside any literal/comment — rewrite if it's a
1824            // whole token (not the prefix of `:pc_idx`).
1825            ':' if sql[idx..].starts_with(PC_ID_PARAM) => {
1826                let after = idx + PC_ID_PARAM.len();
1827                let next_is_word = sql[after..]
1828                    .chars()
1829                    .next()
1830                    .is_some_and(|w| w.is_alphanumeric() || w == '_');
1831                if next_is_word {
1832                    out.push(c);
1833                } else {
1834                    out.push('?');
1835                    count += 1;
1836                    for _ in 0..PC_ID_PARAM.chars().count() - 1 {
1837                        chars.next();
1838                    }
1839                }
1840            }
1841            _ => out.push(c),
1842        }
1843    }
1844    (out, count)
1845}
1846
1847/// Validate a [`RenderSpec`]: reject the #492 `Unknown` catch-all (an operator
1848/// typo at create time) and require the channel columns each `kind` reads.
1849fn validate_render_spec(r: &RenderSpec, at: &str) -> Result<(), String> {
1850    // A channel column is "given" when present and non-blank.
1851    let given = |v: &Option<String>| v.as_deref().map(str::trim).is_some_and(|s| !s.is_empty());
1852    match r.kind {
1853        RenderKind::Unknown => {
1854            return Err(format!(
1855                "{at}.render.kind is not a known value (table | stat | bar | pie | gauge)"
1856            ));
1857        }
1858        RenderKind::Table => {
1859            // `columns` optional; if given, each name must be non-blank.
1860            if let Some(cols) = &r.columns {
1861                if cols.iter().any(|c| c.trim().is_empty()) {
1862                    return Err(format!("{at}.render.columns must not contain blank names"));
1863                }
1864            }
1865            if let Some(labels) = &r.labels {
1866                for (k, v) in labels {
1867                    if k.trim().is_empty() || v.trim().is_empty() {
1868                        return Err(format!(
1869                            "{at}.render.labels keys and values must be non-empty"
1870                        ));
1871                    }
1872                }
1873            }
1874        }
1875        RenderKind::Stat => {
1876            if !given(&r.value) {
1877                return Err(format!("{at}.render.value is required for kind=stat"));
1878            }
1879        }
1880        RenderKind::Bar | RenderKind::Pie => {
1881            let kind = if r.kind == RenderKind::Bar {
1882                "bar"
1883            } else {
1884                "pie"
1885            };
1886            if !given(&r.label) {
1887                return Err(format!("{at}.render.label is required for kind={kind}"));
1888            }
1889            if !given(&r.value) {
1890                return Err(format!("{at}.render.value is required for kind={kind}"));
1891            }
1892            // `limit: 0` truncates to no rows — an invisible widget, almost
1893            // certainly a typo. Omit `limit` for "all rows" (CodeRabbit).
1894            if r.limit == Some(0) {
1895                return Err(format!(
1896                    "{at}.render.limit must be >= 1 (omit it to keep all rows)"
1897                ));
1898            }
1899        }
1900        RenderKind::Gauge => {
1901            // Either a precomputed `value` ratio, or a `num`/`den` pair —
1902            // exactly one of the two forms.
1903            match (given(&r.value), given(&r.num), given(&r.den)) {
1904                (true, false, false) => {}
1905                (false, true, true) => {}
1906                _ => {
1907                    return Err(format!(
1908                        "{at}.render for kind=gauge needs either `value` (a ratio) or both `num` and `den`"
1909                    ));
1910                }
1911            }
1912        }
1913    }
1914    Ok(())
1915}
1916
1917/// A standalone declarative read/aggregation for the Analytics page (#743).
1918///
1919/// A **view** aggregates stored fleet data (`obs_events`, …) without an
1920/// `execute` or a schedule — unlike a [`Manifest`] it only declares
1921/// [`AggregateWidget`]s. (The first line is concise on purpose: `schemars`
1922/// uses it as the generated schema's `title`.) The backend reads views from
1923/// `BUCKET_VIEWS` at
1924/// query time and merges their widgets with the co-located `aggregate:`
1925/// hints on jobs, so a cross-cutting dashboard (one that charts events
1926/// emitted by several other jobs / the agent) has a home that doesn't need
1927/// a noop job carrier. Stored JSON in `BUCKET_VIEWS`, keyed by `id`.
1928#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1929pub struct View {
1930    /// Stable identifier (the KV key). Required, validated non-empty.
1931    pub id: String,
1932    /// Optional human description shown on the Views admin page.
1933    #[serde(default, skip_serializing_if = "Option::is_none")]
1934    pub description: Option<String>,
1935    /// The `obs_events` aggregate widgets this view contributes to the
1936    /// Analytics page. Optional since PR3 — a view may instead (or also)
1937    /// carry [`sql_widgets`](View::sql_widgets); a view must have at least one
1938    /// widget across the two lists.
1939    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1940    pub widgets: Vec<AggregateWidget>,
1941    /// #vuln-roadmap PR3: SQL-backed, materialized widgets — raw read-only SQL
1942    /// over the projector tables (inventory/feeds/…) mapped to a visual. This
1943    /// is how a correlation dashboard (vulnerability / EOL / license) is
1944    /// expressed as config. See [`SqlWidget`].
1945    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1946    pub sql_widgets: Vec<SqlWidget>,
1947    /// Free-form operator taxonomy (same role as [`Manifest::tags`]).
1948    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1949    pub tags: Vec<String>,
1950    /// GitOps provenance (#678), stamped by `kanade view create` from the
1951    /// source YAML's Git context — same as [`Manifest::origin`].
1952    #[serde(default, skip_serializing_if = "Option::is_none")]
1953    pub origin: Option<RepoOrigin>,
1954}
1955
1956/// True if `id` is a safe resource identifier — non-empty and only
1957/// `[A-Za-z0-9._-]`. A view `id` becomes a NATS KV key *and* a URL path
1958/// segment (`/api/views/{id}`), so this blocks `/`, `..`, whitespace and
1959/// other characters that would break the KV key or let a CLI arg wander
1960/// the URL space. (#743 / #744 follow-up — a deliberately small charset
1961/// rather than the looser set NATS technically allows.)
1962pub fn is_valid_resource_id(id: &str) -> bool {
1963    !id.is_empty()
1964        && id
1965            .chars()
1966            .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-')
1967}
1968
1969impl View {
1970    pub fn validate(&self) -> Result<(), String> {
1971        // Validate the id exactly as stored — no `.trim()`. `views::create`
1972        // uses `self.id` verbatim as the KV key and it's the `/api/views/{id}`
1973        // URL segment a lookup matches, so a padded id like `" my-view "` that
1974        // validated as its trimmed form but was stored raw would silently never
1975        // match. The charset excludes whitespace, so checking the untrimmed id
1976        // rejects such an id outright.
1977        if !is_valid_resource_id(&self.id) {
1978            return Err(
1979                "view.id must be non-empty and only [A-Za-z0-9._-] (it's a KV key + URL segment; \
1980                 no surrounding whitespace)"
1981                    .to_string(),
1982            );
1983        }
1984        // A view must contribute at least one widget across the two lists;
1985        // `validate_aggregate_widgets` rejects an empty `widgets` on its own,
1986        // so only call it when that list is non-empty (a pure-SQL view is
1987        // valid with an empty `widgets`).
1988        if self.widgets.is_empty() && self.sql_widgets.is_empty() {
1989            return Err(
1990                "view must declare at least one widget (`widgets:` and/or `sql_widgets:`)"
1991                    .to_string(),
1992            );
1993        }
1994        if !self.widgets.is_empty() {
1995            validate_aggregate_widgets(&self.widgets, "widgets")?;
1996        }
1997        validate_sql_widgets(&self.sql_widgets, "sql_widgets")?;
1998        for tag in &self.tags {
1999            if tag.trim().is_empty() {
2000                return Err("tags must not contain empty entries".to_string());
2001            }
2002        }
2003        Ok(())
2004    }
2005}
2006
2007/// Default membership-recompute cadence for a dynamic [`GroupDef`] whose
2008/// `refresh` is unset — 10 minutes. A group's SQL is evaluated lazily (only
2009/// when a schedule targeting it fires, or the members preview is requested)
2010/// and the result cached for this long, so fleet facts (inventory updates, a
2011/// newly-registered PC) reach the group within at most one cadence while an
2012/// expensive correlation query stays off the hot scheduler-tick path. A
2013/// static `members:` group ignores this (its membership is literal).
2014pub const DEFAULT_GROUP_REFRESH: std::time::Duration = std::time::Duration::from_secs(600);
2015
2016/// A **declared fleet group** (#1032): the third manifest kind alongside
2017/// [`Manifest`] (jobs) and [`Schedule`] (schedules), stored in
2018/// `BUCKET_GROUP_DEFS` keyed by [`id`](GroupDef::id).
2019///
2020/// (The first doc line deliberately does not start with `#NNN` — schemars
2021/// treats a leading `#` as a Markdown heading and would extract it as the
2022/// schema `title`, garbling it. Same reason [`View`]'s doc leads with prose.)
2023///
2024/// A group definition names a set of PCs in one of two mutually-exclusive
2025/// ways:
2026///   * **static** — a literal [`members`](GroupDef::members) list. Declared,
2027///     git-reviewable membership (the auditability win over hand-editing the
2028///     imperative `agent_groups` KV).
2029///   * **dynamic** — a read-only SQL [`query`](GroupDef::query) that returns a
2030///     `pc_id` column. Membership is *derived from the fleet's own facts*
2031///     (`agents`, `inventory_facts` + `json_extract(facts_json, …)`, `feeds`,
2032///     `check_status`, `explode:` tables — anything in the projector DB), so
2033///     "every client OS", "the servers sharing a hostname prefix", "machines
2034///     still on build 26100" are all just a `SELECT`. The query runs in the
2035///     backend read-only sandbox (`api::query`), never on the endpoint.
2036///
2037/// A schedule's `target.groups` resolves a defined group (static or dynamic)
2038/// **in addition to** the imperative `agent_groups` membership, so declared
2039/// groups and manually-assigned ones coexist and this never mutates
2040/// `agent_groups`.
2041#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2042pub struct GroupDef {
2043    /// Stable identifier (the KV key + URL segment + the name a schedule's
2044    /// `target.groups` references). Required; same `[A-Za-z0-9._-]` charset
2045    /// as a [`View`] id via [`is_valid_resource_id`].
2046    pub id: String,
2047    /// Optional human description shown on the groups admin page.
2048    #[serde(default, skip_serializing_if = "Option::is_none")]
2049    pub description: Option<String>,
2050    /// Static membership — a literal list of `pc_id`s. Mutually exclusive with
2051    /// [`query`](GroupDef::query); exactly one of the two must be set
2052    /// (enforced by [`GroupDef::validate`]).
2053    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2054    pub members: Vec<String>,
2055    /// Dynamic membership — a read-only `SELECT`/`WITH` returning a `pc_id`
2056    /// column. Mutually exclusive with [`members`](GroupDef::members). The
2057    /// backend validates it read-only at `group create` and again at run time;
2058    /// a write verb / stacked statement is rejected. Empty string is treated
2059    /// as unset so an operator can comment the body out to switch to
2060    /// `members:` without dropping the key.
2061    #[serde(default, skip_serializing_if = "Option::is_none")]
2062    pub query: Option<String>,
2063    /// Membership-recompute cadence for a dynamic group as a humantime
2064    /// duration (`"30m"`, `"6h"`). Absent ⇒ [`DEFAULT_GROUP_REFRESH`]. Ignored
2065    /// for a static group.
2066    #[serde(default, skip_serializing_if = "Option::is_none")]
2067    pub refresh: Option<String>,
2068    /// Free-form operator taxonomy (same role as [`Manifest::tags`]).
2069    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2070    pub tags: Vec<String>,
2071    /// GitOps provenance (#678), stamped by `kanade group def create` from the
2072    /// source YAML's Git context — same as [`View::origin`].
2073    #[serde(default, skip_serializing_if = "Option::is_none")]
2074    pub origin: Option<RepoOrigin>,
2075}
2076
2077impl GroupDef {
2078    /// The dynamic SQL body if this is a dynamic group — a non-blank `query`.
2079    /// (An empty-string `query` reads as unset, mirroring [`Execute::script`].)
2080    pub fn dynamic_query(&self) -> Option<&str> {
2081        self.query
2082            .as_deref()
2083            .map(str::trim)
2084            .filter(|q| !q.is_empty())
2085    }
2086
2087    /// The effective recompute cadence for a dynamic group — the parsed
2088    /// `refresh` or [`DEFAULT_GROUP_REFRESH`]. Falls back to the default on an
2089    /// unparseable value rather than panicking on the read path (validation
2090    /// already rejected a bad value at create time).
2091    pub fn refresh_interval(&self) -> std::time::Duration {
2092        self.refresh
2093            .as_deref()
2094            .and_then(|s| humantime::parse_duration(s).ok())
2095            .unwrap_or(DEFAULT_GROUP_REFRESH)
2096    }
2097
2098    pub fn validate(&self) -> Result<(), String> {
2099        // Validate the id EXACTLY as stored — no `.trim()`. The id is used
2100        // verbatim as the KV key (`group_defs::create` does `kv.put(&group.id,
2101        // …)`) and as the name a schedule's `target.groups` matches, so a
2102        // padded id like `" clients "` that validated as its trimmed form but
2103        // was stored raw would silently never match. The charset excludes
2104        // whitespace, so checking the untrimmed id rejects such an id outright.
2105        if !is_valid_resource_id(&self.id) {
2106            return Err(
2107                "group.id must be non-empty and only [A-Za-z0-9._-] (it's a KV key + URL segment; \
2108                 no surrounding whitespace)"
2109                    .to_string(),
2110            );
2111        }
2112        // Exactly one of members / query. A blank `query` counts as unset so
2113        // the "comment the body out" workflow lands on the members branch
2114        // rather than a confusing "both set" error.
2115        let has_members = !self.members.is_empty();
2116        let has_query = self.dynamic_query().is_some();
2117        match (has_members, has_query) {
2118            (false, false) => {
2119                return Err(
2120                    "group must declare either a static `members:` list or a dynamic `query:`"
2121                        .to_string(),
2122                );
2123            }
2124            (true, true) => {
2125                return Err(
2126                    "`members:` and `query:` are mutually exclusive — a group is either static or dynamic"
2127                        .to_string(),
2128                );
2129            }
2130            _ => {}
2131        }
2132        for m in &self.members {
2133            if m.trim().is_empty() {
2134                return Err("members must not contain empty entries".to_string());
2135            }
2136        }
2137        // A dynamic group's refresh must parse (a static group ignores it, but
2138        // reject a bad value either way so a later members→query switch can't
2139        // surprise the operator).
2140        if let Some(r) = &self.refresh
2141            && humantime::parse_duration(r).is_err()
2142        {
2143            return Err(format!(
2144                "group.refresh '{r}' is not a valid duration (e.g. '30m', '6h')"
2145            ));
2146        }
2147        for tag in &self.tags {
2148            if tag.trim().is_empty() {
2149                return Err("tags must not contain empty entries".to_string());
2150            }
2151        }
2152        Ok(())
2153    }
2154}
2155
2156/// Issue #246 — `emit:` manifest block for jobs whose stdout is
2157/// NDJSON observability events (one `ObsEvent` per line). Parallel
2158/// to `inventory:` but for the append-only timeline pipeline; see
2159/// `Manifest::emit` for the full contract.
2160#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2161pub struct EmitConfig {
2162    /// What kind of payload the agent should expect on stdout. Only
2163    /// `events` is defined today (parses each non-empty line as
2164    /// `ObsEvent` and publishes on `obs.<pc_id>`); future variants
2165    /// (e.g. metrics streams, structured trace events) plug in here.
2166    #[serde(rename = "type")]
2167    pub kind: EmitKind,
2168    /// Operator hint for where the script keeps its own state — the
2169    /// watermark file the PowerShell / sh body reads + writes
2170    /// between runs so it only emits NEW events since the last
2171    /// poll. The agent doesn't read this; it's documentation that
2172    /// the SPA (and `kanade job edit`) can surface to operators
2173    /// reviewing the manifest. Optional; the script is allowed to
2174    /// keep state anywhere (registry, env, etc.) — the field's
2175    /// presence makes the convention discoverable.
2176    #[serde(default, skip_serializing_if = "Option::is_none")]
2177    pub watermark_path: Option<String>,
2178}
2179
2180/// `emit.type` enum. Lowercase serde so manifests read
2181/// `type: events` rather than `Events`.
2182#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
2183#[serde(rename_all = "lowercase")]
2184pub enum EmitKind {
2185    /// Per-line `ObsEvent` JSON. Agent parses + publishes on
2186    /// `obs.<pc_id>`, drops the stdout from the resulting
2187    /// `ExecResult`.
2188    Events,
2189}
2190
2191/// v0.31 / #40: declarative "flatten this JSON array into a real
2192/// SQLite table" spec on an inventory manifest. The projector
2193/// creates the table on first registration (CREATE TABLE IF NOT
2194/// EXISTS + indexes) and writes a row per element of
2195/// `payload[field]` on every result, scoped by (pc_id, job_id) so
2196/// each PC's rows replace cleanly without a per-PC schema.
2197#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2198pub struct ExplodeSpec {
2199    /// JSON array key under the payload to explode. E.g. `"apps"`
2200    /// for `payload: { apps: [{...}, {...}] }`.
2201    pub field: String,
2202    /// Derived SQLite table name. Operators choose this — pick
2203    /// something namespaced + stable (`inventory_sw_apps`, not
2204    /// `apps`) so multiple inventory manifests don't collide on a
2205    /// generic name.
2206    pub table: String,
2207    /// Element-level fields that uniquely identify a row inside one
2208    /// PC's payload. The full PK is `(pc_id, job_id) + these
2209    /// columns`. Required — operators must think about uniqueness
2210    /// (e.g. `["name", "source"]` for installed apps because the
2211    /// same name appears in multiple uninstall hives).
2212    ///
2213    /// v0.31 / #41: same tuple drives history identity. When
2214    /// `track_history` is on, the projector serialises these
2215    /// fields' values into `inventory_history.identity_json` for
2216    /// every change event, so queries like "every PC that ever
2217    /// installed Chrome (any source)" filter on identity_json
2218    /// content without a per-manifest schema.
2219    pub primary_key: Vec<String>,
2220    /// Per-element fields that become columns in the derived table.
2221    pub columns: Vec<ExplodeColumn>,
2222    /// v0.31 / #41: when true (default false), the projector
2223    /// diffs each PC's incoming payload against the prior rows
2224    /// for the same (pc_id, job_id) BEFORE the DELETE-then-INSERT
2225    /// replace, and writes added / removed / changed events into
2226    /// `inventory_history`. Lets operators answer time-dimension
2227    /// questions ("when did Chrome 120 first appear on PC X?",
2228    /// "what's the Win 11 23H2 rollout curve") without storing
2229    /// per-scan snapshots. Off by default so operators opt in
2230    /// per-spec — history has a real storage cost on long-lived
2231    /// deployments (mitigated by the 90-day default retention
2232    /// sweeper, see `cleanup` module).
2233    #[serde(default)]
2234    pub track_history: bool,
2235}
2236
2237/// One column in an [`ExplodeSpec`]'s derived table.
2238#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2239pub struct ExplodeColumn {
2240    /// JSON key under each array element. Becomes the column name
2241    /// in the derived SQLite table — we don't rename.
2242    pub field: String,
2243    /// SQLite affinity: `"text"` (default), `"integer"`, `"real"`.
2244    /// Storage maps directly via `sqlx::query.bind(...)`; type
2245    /// mismatches at INSERT-time fail loudly rather than silently
2246    /// dropping the row.
2247    #[serde(default, skip_serializing_if = "Option::is_none")]
2248    #[serde(rename = "type")]
2249    pub kind: Option<String>,
2250    /// When true, the projector creates a `CREATE INDEX` on this
2251    /// column at table-creation time. Boost for the common-filter
2252    /// columns (`name`, `version`) — operators mark them
2253    /// explicitly, the projector won't guess.
2254    #[serde(default)]
2255    pub index: bool,
2256}
2257
2258/// #vuln-roadmap: one declarative **external-data feed** on a `feed:`
2259/// manifest — see [`Manifest::feed`]. Unlike inventory [`ExplodeSpec`]
2260/// (keyed per `(pc_id, job_id)`), a feed is GLOBAL fleet-wide reference
2261/// data: the controller-tier job's script fetches + shapes it, prints the
2262/// array under [`field`](FeedSpec::field) inside a `#KANADE-FEED-BEGIN/END`
2263/// fence, and the projector REPLACES that feed's rows wholesale in the
2264/// shared `feeds` table keyed `(feed_id, item_id)`. The full element JSON
2265/// lands in a `data` column, so a `view:` SQL `json_extract`s whatever
2266/// shape the feed carries — no per-feed schema, no dynamic DDL. One
2267/// manifest may declare several feeds.
2268#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2269pub struct FeedSpec {
2270    /// Stable feed identifier — the `feed_id` partition in the shared
2271    /// `feeds` table. Operators choose this; namespace it (`cisa-kev`,
2272    /// `endoflife-windows`) so feeds don't collide. A new result for the
2273    /// same id replaces that partition wholesale.
2274    pub id: String,
2275    /// JSON array key under the (fenced) payload to ingest. E.g.
2276    /// `"vulnerabilities"` for `{ vulnerabilities: [{...}, {...}] }`.
2277    pub field: String,
2278    /// Element-level field(s) whose values uniquely identify an item
2279    /// within the feed — they form the `item_id` key (joined for a
2280    /// composite key). Required: operators must think about uniqueness
2281    /// (e.g. `["cveID"]` for CISA KEV). An element missing any of these is
2282    /// skipped (it has no stable identity).
2283    pub primary_key: Vec<String>,
2284}
2285
2286#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2287pub struct DisplayField {
2288    /// Top-level key in the stdout JSON.
2289    pub field: String,
2290    /// Human-readable column header.
2291    pub label: String,
2292    /// Optional render hint — `"number"`, `"bytes"`, `"timestamp"`,
2293    /// or `"table"` (#39). Defaults to plain text rendering on the
2294    /// SPA side. `"table"` expects the field's value to be a JSON
2295    /// array of objects and renders a nested sub-table on the
2296    /// per-PC detail page using `columns` as the schema; the fleet
2297    /// summary view falls back to showing the row count for
2298    /// `"table"` cells so the wide list stays compact.
2299    #[serde(default, skip_serializing_if = "Option::is_none")]
2300    #[serde(rename = "type")]
2301    pub kind: Option<String>,
2302    /// v0.30 / #39: when `kind == "table"`, the SPA renders the
2303    /// field's value (an array of objects like
2304    /// `disks: [{ device_id, size_bytes, ... }]`) as a nested
2305    /// sub-table using these columns. Each column is itself a
2306    /// `DisplayField`, so the nested cells reuse the same render
2307    /// hints (`bytes`, `number`, `timestamp`) — no parallel format
2308    /// pipeline. Ignored for any other `kind`.
2309    #[serde(default, skip_serializing_if = "Option::is_none")]
2310    pub columns: Option<Vec<DisplayField>>,
2311}
2312
2313#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2314pub struct Rollout {
2315    #[serde(default)]
2316    pub strategy: RolloutStrategy,
2317    pub waves: Vec<Wave>,
2318}
2319
2320#[derive(
2321    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
2322)]
2323#[serde(rename_all = "lowercase")]
2324pub enum RolloutStrategy {
2325    #[default]
2326    Wave,
2327}
2328
2329#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2330pub struct Wave {
2331    pub group: String,
2332    /// humantime delay measured from the deploy's publish time. wave[0]
2333    /// typically has "0s"; subsequent waves use minutes / hours.
2334    pub delay: String,
2335}
2336
2337#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default)]
2338pub struct Target {
2339    #[serde(default)]
2340    pub groups: Vec<String>,
2341    #[serde(default)]
2342    pub pcs: Vec<String>,
2343    #[serde(default)]
2344    pub all: bool,
2345}
2346
2347impl Target {
2348    /// At least one of all / groups / pcs is set.
2349    pub fn is_specified(&self) -> bool {
2350        self.all || !self.groups.is_empty() || !self.pcs.is_empty()
2351    }
2352
2353    /// Whether a PC (its `pc_id` + group membership) falls in this target:
2354    /// `all`, or the pc is listed, or it belongs to a listed group. Used
2355    /// by the agent to scope `client.visible_to` (#816). An unspecified
2356    /// target matches nobody (callers should treat "no target" as
2357    /// "visible to all" before calling this).
2358    pub fn matches(&self, pc_id: &str, groups: &[String]) -> bool {
2359        self.all
2360            || self.pcs.iter().any(|p| p == pc_id)
2361            || self.groups.iter().any(|g| groups.contains(g))
2362    }
2363}
2364
2365#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2366pub struct Execute {
2367    /// Critical jobs can bypass the PC limit and consume no slot.
2368    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2369    pub bypass_local_limit: bool,
2370    pub shell: ExecuteShell,
2371    /// Inline script body. Mutually exclusive with [`script_file`]
2372    /// and [`script_object`]; exactly one of the three must be set
2373    /// (enforced by [`Execute::validate_script_source`] at the
2374    /// write-side parse boundaries — `kanade job create` and
2375    /// `POST /api/jobs`).
2376    ///
2377    /// Empty string is treated as **unset** so operators can swap
2378    /// to a `script_file:` / `script_object:` alternative just by
2379    /// commenting out the body, without having to also drop the
2380    /// `script:` key entirely.
2381    ///
2382    /// [`script_file`]: Self::script_file
2383    /// [`script_object`]: Self::script_object
2384    #[serde(default, skip_serializing_if = "Option::is_none")]
2385    pub script: Option<String>,
2386    /// Repo-local file path resolved by the operator-side CLI at
2387    /// `kanade job create` time. The CLI reads the file, slots its
2388    /// contents into `script`, and clears this field before
2389    /// POSTing — so the backend / agents never see `script_file`
2390    /// in stored manifests. SPEC §2.4.1.
2391    ///
2392    /// The resolver shipped with #210: `kanade job create` /
2393    /// `kanade job validate` inline this field end-to-end. Because
2394    /// resolution is CLI-side (it needs the operator's filesystem),
2395    /// `POST /api/jobs` rejects a manifest that still carries it
2396    /// (#918) — a stored `script_file` job would 400 at every exec.
2397    /// Inline the script or use `script_object` when writing through
2398    /// the API / SPA editor.
2399    #[serde(default, skip_serializing_if = "Option::is_none")]
2400    pub script_file: Option<String>,
2401    /// Object Store reference (`<name>/<version>`) into the
2402    /// `scripts` bucket (`OBJECT_SCRIPTS`). Agents fetch the body
2403    /// at Execute time via `/api/script-objects/{name}/{version}`
2404    /// and cache it locally. SPEC §2.4.1.
2405    ///
2406    /// Fully wired (#210/#211): the backend resolves the digest at
2407    /// exec submission (`api::exec::resolve_script_source`), the agent
2408    /// fetches + sha-verifies + caches the body (`script_cache`), and
2409    /// `kanade script` CRUDs the store. Unlike `script_file:` (inlined
2410    /// CLI-side, git-managed), this keeps the body in versioned,
2411    /// digest-pinned object storage — the ops-managed counterpart.
2412    #[serde(default, skip_serializing_if = "Option::is_none")]
2413    pub script_object: Option<String>,
2414    /// humantime duration string (e.g. "30s", "10m"). Script-intrinsic
2415    /// — represents how long this script reasonably takes to run.
2416    pub timeout: String,
2417    /// Token + session combination the agent uses to launch the
2418    /// script (v0.21). Default = [`RunAs::System`] (Session 0,
2419    /// LocalSystem privileges, no GUI; root on macOS) — matches
2420    /// pre-v0.21 behavior. `user` / `system_gui` run in the logged-in
2421    /// console user's session on Windows and macOS, and fail when
2422    /// nobody is logged in; Linux agents skip them.
2423    #[serde(default)]
2424    pub run_as: RunAs,
2425    /// Working directory for the spawned child (v0.21.1). When
2426    /// unset, the child inherits the agent's cwd — on Windows that
2427    /// means `%SystemRoot%\System32` for the prod service, which is
2428    /// almost never what operators actually want (a macOS `run_as:
2429    /// user` job starts in the user's home instead: the daemon's own
2430    /// cwd is its 0700 data dir). Use an absolute path; relative paths
2431    /// are passed through to the OS verbatim. The agent expands a
2432    /// leading `~` to the home of the identity the job runs as (the
2433    /// user for `run_as: user`), and on Windows `%FOO%` from that
2434    /// identity's environment — so `%PROGRAMDATA%` works for `run_as:
2435    /// system`, `~\src` / `%USERPROFILE%` for `run_as: user`. A macOS
2436    /// agent expands only `~`.
2437    #[serde(default, skip_serializing_if = "Option::is_none")]
2438    pub cwd: Option<String>,
2439}
2440
2441impl Execute {
2442    /// Treat an empty — or whitespace-only (#918) — `script:` body as
2443    /// "intentionally unset". Operators commenting out a block-scalar
2444    /// tend to leave the key behind, and failing the validator on
2445    /// `script: ""` would surprise them; a body of blank lines can't
2446    /// be a real script either, only a commented-out one, and letting
2447    /// it count as "set" shipped a validated do-nothing job.
2448    fn has_inline_script(&self) -> bool {
2449        matches!(&self.script, Some(s) if !s.trim().is_empty())
2450    }
2451
2452    /// Enforce that exactly one of `script` / `script_file` /
2453    /// `script_object` is set. Called at the write-side parse
2454    /// boundaries (CLI `kanade job create` + backend
2455    /// `POST /api/jobs`) so ambiguous YAML is rejected before it
2456    /// reaches the JOBS KV. Read paths (projector, agent
2457    /// scheduler, list endpoints) skip this check — they only ever
2458    /// see what the write path already validated.
2459    pub fn validate_script_source(&self) -> Result<(), String> {
2460        // #918: a blank-but-present alternate source is a typo, not a
2461        // choice — `script_file: ""` used to count as "set", pass the
2462        // exactly-one check, and only fail at use time (the CLI reads
2463        // a file named ""; a stored blank script_object 404s on every
2464        // exec). Reject it with the field named. Inline `script` keeps
2465        // its documented empty-means-unset semantics instead — see
2466        // `has_inline_script`.
2467        if matches!(&self.script_file, Some(s) if s.trim().is_empty()) {
2468            return Err(
2469                "execute.script_file must not be blank when set (drop the key to use \
2470                 another source)"
2471                    .into(),
2472            );
2473        }
2474        if matches!(&self.script_object, Some(s) if s.trim().is_empty()) {
2475            return Err(
2476                "execute.script_object must not be blank when set (drop the key to use \
2477                 another source)"
2478                    .into(),
2479            );
2480        }
2481        let inline = self.has_inline_script();
2482        let file = self.script_file.is_some();
2483        let obj = self.script_object.is_some();
2484        let set = [inline, file, obj].into_iter().filter(|b| *b).count();
2485        match set {
2486            1 => {}
2487            0 => {
2488                return Err(
2489                    "execute: one of `script`, `script_file`, `script_object` must be set".into(),
2490                );
2491            }
2492            _ => {
2493                return Err(format!(
2494                    "execute: only one of `script` / `script_file` / `script_object` may be set \
2495                     (got script={inline}, script_file={file}, script_object={obj})"
2496                ));
2497            }
2498        }
2499        // #918: a script_object ref is `<name>/<version>` — the agent
2500        // fetches the body via `/api/script-objects/{name}/{version}`
2501        // and the backend uses the ref *verbatim* as the Object Store
2502        // key (`resolve_script_source`), so each half must be a
2503        // well-formed resource id: exactly one slash, and both halves
2504        // [A-Za-z0-9._-]. `is_valid_resource_id` also rejects a half
2505        // that's blank OR merely whitespace-padded (`"foo/bar "`) —
2506        // padding survives a JSON POST body (unlike a YAML plain
2507        // scalar) and would 404 on every exec (gemini/claude #943).
2508        if let Some(obj_ref) = self.script_object.as_deref() {
2509            let parts: Vec<&str> = obj_ref.split('/').collect();
2510            if parts.len() != 2 || parts.iter().any(|p| !is_valid_resource_id(p)) {
2511                return Err(format!(
2512                    "execute.script_object must be `<name>/<version>` with each half \
2513                     [A-Za-z0-9._-] (got '{obj_ref}'); publish bodies with \
2514                     `kanade script publish <name> <version>`"
2515                ));
2516            }
2517        }
2518        Ok(())
2519    }
2520}
2521
2522/// Job-generic post-step hook (see [`Manifest::finalize`]). Runs after
2523/// the main `execute:` script (and the collect upload) on a clean exit,
2524/// with the step's structured result injected via an environment
2525/// variable. P1 supports an inline `script:` only — `script_file:` /
2526/// `script_object:` are follow-ups.
2527#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2528pub struct FinalizeSpec {
2529    pub shell: ExecuteShell,
2530    /// Inline script body (required; inline-only in P1).
2531    pub script: String,
2532    /// humantime duration string (e.g. `"60s"`, `"5m"`). Defaults to
2533    /// `60s` when unset.
2534    #[serde(default = "default_finalize_timeout")]
2535    pub timeout: String,
2536    /// Token + session combination, like [`Execute::run_as`]. Defaults
2537    /// to [`RunAs::System`].
2538    #[serde(default)]
2539    pub run_as: RunAs,
2540    /// Working directory for the hook child, like [`Execute::cwd`].
2541    #[serde(default, skip_serializing_if = "Option::is_none")]
2542    pub cwd: Option<String>,
2543    /// #965: for a `collect:` job, run this hook once per uploaded
2544    /// bundle (with a single-bundle `KANADE_COLLECT_RESULT`) as each
2545    /// bundle uploads, instead of once after the whole set. Lets an
2546    /// interrupted collect still clean up the days it managed to
2547    /// upload (partial progress sticks), breaking the
2548    /// offline-before-finalize backlog spiral.
2549    ///
2550    /// **Opt-in** (default `false` = one call after all bundles, the
2551    /// established contract) because per-bundle changes the hook's
2552    /// payload (all → one) and invocation count (1 → N), which would
2553    /// break a hook written for the all-at-once assumption (cross-bundle
2554    /// aggregation, once-only side effects, all-or-nothing). Only valid
2555    /// with a `collect:` hint — [`Manifest::validate`] rejects it
2556    /// otherwise, since a non-collect finalize has no bundles to iterate.
2557    #[serde(default)]
2558    pub on_each_bundle: bool,
2559}
2560
2561/// Default `finalize.timeout` when the operator omits it.
2562fn default_finalize_timeout() -> String {
2563    "60s".to_string()
2564}
2565
2566impl FinalizeSpec {
2567    /// Lower to the wire form forwarded onto a [`Command`]. The timeout
2568    /// parse falls back to 60s — [`Manifest::validate`] already rejects
2569    /// an unparseable value at create time, so the fire path uses a safe
2570    /// default rather than failing (mirrors
2571    /// [`CollectHint::max_size_bytes`]). A sub-second timeout floors at
2572    /// 1s for the same reason `build_command` does.
2573    pub fn lower(&self) -> FinalizeCommand {
2574        let timeout_secs = humantime::parse_duration(&self.timeout)
2575            .map(|d| d.as_secs().max(1))
2576            .unwrap_or(60);
2577        FinalizeCommand {
2578            shell: self.shell.into(),
2579            script: self.script.clone(),
2580            timeout_secs,
2581            run_as: self.run_as,
2582            cwd: self.cwd.clone(),
2583            on_each_bundle: self.on_each_bundle,
2584        }
2585    }
2586}
2587
2588impl Manifest {
2589    /// Cross-field semantic checks that don't fit into pure serde
2590    /// derive. Currently delegates to
2591    /// [`Execute::validate_script_source`] — see that method's
2592    /// docs for the rationale on which call sites should run this.
2593    pub fn validate(&self) -> Result<(), String> {
2594        self.execute.validate_script_source()?;
2595        // Fail CLOSED on an unrecognised execution tier. `#[serde(other)]`
2596        // turns a typo (`tier: controler`) or a future tier into
2597        // `Tier::Unknown`; without this check the controller gate would
2598        // fall back to normal endpoint dispatch, so an operator who *meant*
2599        // to confine a job to the controller tier would silently get
2600        // fleet-wide dispatch (CodeRabbit #905). Rejecting it at the write
2601        // boundary surfaces the typo at `job create`, and — since
2602        // `exec_manifest` re-validates — a hand-poked KV manifest can't slip
2603        // a controller-tier job onto endpoints either.
2604        if matches!(self.tier, Some(Tier::Unknown)) {
2605            return Err(
2606                "tier: unrecognised execution tier — use `endpoint` or `controller` \
2607                 (this is a typo, or a tier a newer kanade supports that this backend does not)"
2608                    .to_string(),
2609            );
2610        }
2611        // #vuln-roadmap: a `feed:` spec drives the global `feeds`
2612        // projection. id / item_id are stored as *values* (the `feeds`
2613        // table is fixed-schema — no identifier splicing), but blank
2614        // values are silent projection bugs: a blank id collides every
2615        // feed under "", a blank field never matches the payload array,
2616        // and an empty primary_key yields no item_id (every row dropped).
2617        // Reject them at the write boundary so `kanade job create` surfaces
2618        // the typo instead of producing an empty/garbled feed at run time.
2619        let mut seen_feed_ids: Vec<&str> = Vec::new();
2620        for spec in &self.feed {
2621            let id = spec.id.trim();
2622            if id.is_empty() {
2623                return Err("feed.id must not be empty".to_string());
2624            }
2625            if spec.field.trim().is_empty() {
2626                return Err(format!("feed '{id}' field must not be empty"));
2627            }
2628            if spec.primary_key.is_empty() {
2629                return Err(format!("feed '{id}' needs at least one primary_key field"));
2630            }
2631            if spec.primary_key.iter().any(|k| k.trim().is_empty()) {
2632                return Err(format!(
2633                    "feed '{id}' primary_key must not contain blank entries"
2634                ));
2635            }
2636            // Two specs sharing an id both target the same `feeds`
2637            // partition and would clobber each other on every run —
2638            // reject the ambiguity rather than let last-write-wins.
2639            if seen_feed_ids.contains(&id) {
2640                return Err(format!("feed id '{id}' is declared more than once"));
2641            }
2642            seen_feed_ids.push(id);
2643        }
2644        // A `feed:` job fetches external data and MUST run on the trusted
2645        // controller tier — the dispatch guard (`requires_controller`) treats
2646        // a non-empty `feed:` as implying `controller`. An explicit
2647        // `tier: endpoint` contradicts that intent; reject it rather than
2648        // silently overriding, so the operator can't believe a feed runs on
2649        // endpoints. Omitting `tier:` (the default) is fine — the implication
2650        // confines it; `tier: controller` is the redundant-but-explicit form.
2651        if !self.feed.is_empty() && matches!(self.tier, Some(Tier::Endpoint)) {
2652            return Err(
2653                "feed: requires the controller tier — remove `tier: endpoint` (a feed: job \
2654                 fetches external data and is confined to the controller_group)"
2655                    .to_string(),
2656            );
2657        }
2658        // A present-but-empty finalize script is an invisible no-op
2659        // (the hook would run an empty body); reject it at the write
2660        // boundary. Inline-only in P1, so `script` is the sole source.
2661        if let Some(finalize) = &self.finalize {
2662            if finalize.script.trim().is_empty() {
2663                return Err("finalize.script must not be empty".to_string());
2664            }
2665            // Reject an unparseable timeout at the write boundary so the
2666            // operator sees the error at `job create` rather than getting
2667            // a silent fire-time fallback (`FinalizeSpec::lower` floors to
2668            // 60s, which would otherwise mask a typo).
2669            if humantime::parse_duration(&finalize.timeout).is_err() {
2670                return Err(format!(
2671                    "finalize.timeout '{}' is not a valid duration",
2672                    finalize.timeout
2673                ));
2674            }
2675            // Disallow cmd for finalize: the agent injects the result JSON
2676            // into the hook's environment, and cmd.exe quoting doesn't
2677            // nest — JSON's `"` plus shell metacharacters in a collected
2678            // path/key could break out into command injection at the
2679            // agent's (often LocalSystem) privilege. PowerShell's
2680            // single-quote escaping is safe, and finalize hooks are
2681            // PowerShell by convention anyway.
2682            // `sh` is rejected for the same injection reason (its
2683            // single-word quoting doesn't nest around the JSON result
2684            // either), and additionally because the injected prelude is
2685            // PowerShell syntax (`$env:KANADE_COLLECT_RESULT = '...'`) —
2686            // it would be malformed in a POSIX shell. `pwsh` IS allowed:
2687            // it's PowerShell, so the prelude + single-quote escaping are
2688            // valid and safe.
2689            if matches!(finalize.shell, ExecuteShell::Cmd | ExecuteShell::Sh) {
2690                return Err(
2691                    "finalize.shell: cmd and sh are not supported for finalize hooks \
2692                     (shell-injection risk when the result JSON is injected, and the injected \
2693                     prelude is PowerShell syntax); use powershell or pwsh"
2694                        .to_string(),
2695                );
2696            }
2697            // #965: per-bundle finalize only means anything for a
2698            // collect: job — a non-collect finalize has no bundles to
2699            // iterate (it runs once after the script). Reject the
2700            // combination at the write boundary so a confused operator
2701            // is told rather than silently getting a no-op.
2702            if finalize.on_each_bundle && self.collect.is_none() {
2703                return Err(
2704                    "finalize.on_each_bundle: true requires a collect: hint — a non-collect \
2705                     finalize has no bundles to iterate (it runs once after the script)"
2706                        .to_string(),
2707                );
2708            }
2709        }
2710        // Stdout-format compatibility (#821). `inventory:` / `check:` /
2711        // `collect:` now COMPOSE: each reads its own `#KANADE-<KIND>-
2712        // BEGIN/END`-fenced JSON block from stdout, so a single job can
2713        // project inventory facts, drive a Health-tab check, AND collect
2714        // files in one run. (A single-hint job may still skip the fence;
2715        // a multi-hint job must fence each block.)
2716        //
2717        // `emit:` remains the exception — its stdout is line-delimited
2718        // NDJSON consumed whole and then omitted from the result — so it
2719        // can't share stdout with any fenced hint. `feed:` is another fenced
2720        // stdout consumer (`#KANADE-FEED`), so it belongs in this exclusion
2721        // too: with `emit:` present the projector never sees the feed's fence
2722        // (CodeRabbit).
2723        if self.emit.is_some()
2724            && (self.inventory.is_some()
2725                || self.check.is_some()
2726                || self.collect.is_some()
2727                || !self.feed.is_empty())
2728        {
2729            return Err(
2730                "`emit:` is incompatible with `inventory:` / `check:` / `collect:` / `feed:` — \
2731                 emit's stdout is NDJSON timeline events (consumed whole and omitted from the \
2732                 result), while the others read fenced JSON blocks from stdout"
2733                    .to_string(),
2734            );
2735        }
2736        // A check's `name` is the Health-tab row id (React key); the
2737        // field names tell the agent where to read status/detail.
2738        // An empty value is an invisible runtime bug, and the serde
2739        // defaults don't guard an operator who writes `status_field:
2740        // ""` explicitly — reject all three here.
2741        if let Some(check) = &self.check {
2742            for (label, value) in [
2743                ("check.name", &check.name),
2744                ("check.status_field", &check.status_field),
2745                ("check.detail_field", &check.detail_field),
2746            ] {
2747                if value.trim().is_empty() {
2748                    return Err(format!("{label} must not be empty"));
2749                }
2750            }
2751            // A present-but-blank `troubleshoot` is a broken
2752            // remediation job id (the "修復する" button would target
2753            // an empty manifest id) — reject it too.
2754            if let Some(troubleshoot) = &check.troubleshoot {
2755                if troubleshoot.trim().is_empty() {
2756                    return Err("check.troubleshoot must not be empty when set".to_string());
2757                }
2758            }
2759            // A present-but-blank `label` would render an empty row
2760            // title on the Health tab / Compliance page — reject it so
2761            // the slug fallback only ever kicks in when label is absent.
2762            if let Some(label) = &check.label {
2763                if label.trim().is_empty() {
2764                    return Err("check.label must not be empty when set".to_string());
2765                }
2766            }
2767            if let Some(alert) = &check.alert {
2768                // An alert that names no recipient is a silent no-op.
2769                if !alert.notify_user && alert.notify_groups.is_empty() {
2770                    return Err("check.alert must set notify_user and/or notify_groups".to_string());
2771                }
2772                if alert.title.trim().is_empty() {
2773                    return Err("check.alert.title must not be empty".to_string());
2774                }
2775                // `on: []` would never fire; an empty group name resolves to
2776                // a malformed `notifications.group.` subject.
2777                if alert.on.is_empty() {
2778                    return Err("check.alert.on must list at least one status".to_string());
2779                }
2780                if alert.notify_groups.iter().any(|g| g.trim().is_empty()) {
2781                    return Err("check.alert.notify_groups must not contain blanks".to_string());
2782                }
2783                // Email is addressed via group_contacts (group → email), so
2784                // there must be a group to map. notify_user has no email.
2785                if alert.email && alert.notify_groups.is_empty() {
2786                    return Err(
2787                        "check.alert.email requires notify_groups (email is addressed per group, not per user)"
2788                            .to_string(),
2789                    );
2790                }
2791                // The alert rides the `check_status` projection, which only
2792                // runs for `fleet: true`.
2793                if !check.fleet {
2794                    return Err(
2795                        "check.alert requires fleet: true (the alert rides the compliance projection)"
2796                            .to_string(),
2797                    );
2798                }
2799            }
2800        }
2801        // #291: a `client:` job is rendered in the Client App's
2802        // catalog (`jobs.list` → `jobs.execute`). serde already makes
2803        // `name` + `category` required at parse time; the only gap is
2804        // a present-but-blank `name`, which would render an empty row
2805        // title — reject it like the other display-id fields.
2806        if let Some(client) = &self.client {
2807            if client.name.trim().is_empty() {
2808                return Err("client.name must not be empty".to_string());
2809            }
2810            // #792: category is a free-form key now, so a blank one would
2811            // group the job under an empty tab — reject it like `name`.
2812            if client.category.trim().is_empty() {
2813                return Err("client.category must not be empty".to_string());
2814            }
2815            // Optional display fields, when present, must be
2816            // meaningful: a blank `description` renders an empty
2817            // subtitle and a blank `icon` is a dangling lucide name.
2818            // Same present-but-blank guard the `check:` block applies
2819            // to its optional `troubleshoot` id.
2820            for (label, value) in [
2821                ("client.description", &client.description),
2822                ("client.icon", &client.icon),
2823                ("client.category_label", &client.category_label),
2824                ("client.category_icon", &client.category_icon),
2825            ] {
2826                if let Some(v) = value {
2827                    if v.trim().is_empty() {
2828                        return Err(format!("{label} must not be empty when set"));
2829                    }
2830                }
2831            }
2832            // #816: a present-but-empty `visible_to` (no all/groups/pcs)
2833            // would hide the job from everyone in the Client App — almost
2834            // certainly a mistake. Require at least one selector; omit the
2835            // whole block to mean "visible to all".
2836            if let Some(t) = &client.visible_to {
2837                if !t.is_specified() {
2838                    return Err(
2839                        "client.visible_to must set at least one of all / groups / pcs (omit it for all PCs)"
2840                            .to_string(),
2841                    );
2842                }
2843            }
2844            // show_when: a dynamic display gate keyed on a check result. A
2845            // malformed check slug matches nothing and an empty status list
2846            // matches nothing — both would silently hide the job forever,
2847            // so reject them at create time rather than at a confused
2848            // "why isn't my job showing?" later. The slug must be a clean
2849            // resource id (same charset checks/jobs use): a typo with spaces
2850            // or punctuation can never match a real check name, so catch it
2851            // here instead of failing closed at runtime. (Whether the slug
2852            // names a check that actually EXISTS can't be checked here —
2853            // checks are keyed by name across manifests — so a valid-but-
2854            // unknown slug stays a runtime miss = hidden, the documented
2855            // fail-closed behavior.)
2856            if let Some(sw) = &client.show_when {
2857                if !is_valid_resource_id(sw.check.trim()) {
2858                    return Err(
2859                        "client.show_when.check must be a non-empty check slug ([A-Za-z0-9._-])"
2860                            .to_string(),
2861                    );
2862                }
2863                if sw.is.is_empty() {
2864                    return Err(
2865                        "client.show_when.is must list at least one check status".to_string()
2866                    );
2867                }
2868            }
2869            // confirm: a present-but-blank custom message would render an
2870            // empty dialog title — reject it like the other display fields.
2871            // (A `confirm: false` / `enabled: false` with no message is fine:
2872            // the dialog is suppressed, so there's nothing to render.)
2873            if let Some(c) = &client.confirm {
2874                if let Some(msg) = &c.message {
2875                    if msg.trim().is_empty() {
2876                        return Err("client.confirm.message must not be empty when set".to_string());
2877                    }
2878                }
2879            }
2880            // unlock: the scope slug is matched byte-for-byte against the
2881            // operator's configured `support_codes[].scope`, so a slug with
2882            // stray whitespace / punctuation can never match one — and
2883            // because the gate fails closed, the job would simply be
2884            // invisible forever with no error anywhere. Reject it at create
2885            // time. (Whether a code is actually CONFIGURED for the scope
2886            // can't be checked here — that lives in server settings, not the
2887            // manifest — so an unconfigured scope stays a runtime miss =
2888            // hidden.)
2889            //
2890            // Validated EXACTLY AS STORED — no `.trim()`, the same no-trim
2891            // rule `View::validate` / `AgentGroup::validate` spell out. The
2892            // backend trims a support code's scope before storing it, so a
2893            // padded manifest scope that validated as its trimmed form but
2894            // was stored raw would pass this check and then never match a
2895            // code — precisely the silent-forever-hidden failure this guard
2896            // exists to prevent.
2897            if let Some(scope) = &client.unlock {
2898                if !is_valid_resource_id(scope) {
2899                    return Err(
2900                        "client.unlock must be a non-empty unlock scope slug ([A-Za-z0-9._-]) \
2901                         with no surrounding whitespace"
2902                            .to_string(),
2903                    );
2904                }
2905            }
2906        }
2907        // #219: a `collect:` job's `name` heads the bundle on the SPA
2908        // Collect page (and the Client App row when paired with
2909        // `client:`), `files_field` tells the agent where to read the
2910        // path list, and `max_size` must be a parseable size so a typo
2911        // is caught at create time rather than silently capping the
2912        // bundle at the default on the fire path.
2913        if let Some(collect) = &self.collect {
2914            if collect.name.trim().is_empty() {
2915                return Err("collect.name must not be empty".to_string());
2916            }
2917            if collect.files_field.trim().is_empty() {
2918                return Err("collect.files_field must not be empty".to_string());
2919            }
2920            if let Some(description) = &collect.description {
2921                if description.trim().is_empty() {
2922                    return Err("collect.description must not be empty when set".to_string());
2923                }
2924            }
2925            if let Some(max_size) = &collect.max_size {
2926                parse_size_bytes(max_size).map_err(|e| format!("collect.max_size: {e}"))?;
2927            }
2928        }
2929        // #720/#743: `aggregate:` is a pure read-spec (it never touches
2930        // stdout and is never sent to an agent), so it composes with every
2931        // other hint. The per-widget rules are shared with the standalone
2932        // `view` resource — see [`validate_aggregate_widgets`].
2933        if let Some(widgets) = &self.aggregate {
2934            validate_aggregate_widgets(widgets, "aggregate")?;
2935        }
2936        // A blank / whitespace-only tag is an invisible operator typo
2937        // that would render an empty filter chip on the Jobs page —
2938        // reject it like the other present-but-blank display fields.
2939        for tag in &self.tags {
2940            if tag.trim().is_empty() {
2941                return Err("tags must not contain empty entries".to_string());
2942            }
2943        }
2944        Ok(())
2945    }
2946}
2947
2948#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
2949#[serde(rename_all = "lowercase")]
2950pub enum ExecuteShell {
2951    /// Windows PowerShell 5.1 (`powershell`).
2952    Powershell,
2953    /// `cmd.exe` (`cmd /C`). Windows only.
2954    Cmd,
2955    /// POSIX shell (`sh -c`). Linux/macOS.
2956    Sh,
2957    /// PowerShell 7, cross-platform (`pwsh`).
2958    Pwsh,
2959}
2960
2961impl From<ExecuteShell> for Shell {
2962    fn from(s: ExecuteShell) -> Self {
2963        match s {
2964            ExecuteShell::Powershell => Shell::Powershell,
2965            ExecuteShell::Cmd => Shell::Cmd,
2966            ExecuteShell::Sh => Shell::Sh,
2967            ExecuteShell::Pwsh => Shell::Pwsh,
2968        }
2969    }
2970}
2971
2972#[cfg(test)]
2973mod tests {
2974    use super::*;
2975
2976    #[test]
2977    fn inventory_payload_extracts_fenced_block() {
2978        // Readable message + fenced JSON → only the JSON, trimmed.
2979        let stdout = "Wi-Fi 設定を適用しました。\n\
2980            #KANADE-INVENTORY-BEGIN\n\
2981            {\"applied\": true}\n\
2982            #KANADE-INVENTORY-END\n";
2983        assert_eq!(inventory_payload(stdout), "{\"applied\": true}");
2984    }
2985
2986    #[test]
2987    fn inventory_payload_falls_back_to_whole_stdout() {
2988        // No fence (a plain inventory job) → whole stdout, trimmed.
2989        assert_eq!(
2990            inventory_payload("  {\"ram_gb\": 16}\n"),
2991            "{\"ram_gb\": 16}"
2992        );
2993    }
2994
2995    #[test]
2996    fn inventory_payload_handles_unterminated_fence() {
2997        // Closing marker missing (e.g. truncated) → everything after the
2998        // opener, trimmed.
2999        let stdout = "msg\n#KANADE-INVENTORY-BEGIN\n{\"a\": 1}";
3000        assert_eq!(inventory_payload(stdout), "{\"a\": 1}");
3001    }
3002
3003    #[test]
3004    fn inventory_payload_ignores_mid_line_sentinel() {
3005        // The marker echoed mid-line (not at a line start) must NOT be
3006        // treated as a fence — fall back to the whole stdout.
3007        let stdout = "see #KANADE-INVENTORY-BEGIN in the docs\nnot json";
3008        assert_eq!(inventory_payload(stdout), stdout.trim());
3009    }
3010
3011    #[test]
3012    fn fenced_payload_extracts_each_hint_block_independently() {
3013        // #821: one stdout carrying a user message + all three fenced
3014        // blocks — every consumer pulls only its own.
3015        let stdout = "\
3016done!
3017#KANADE-INVENTORY-BEGIN
3018{\"os\":\"win\"}
3019#KANADE-INVENTORY-END
3020#KANADE-CHECK-BEGIN
3021{\"status\":\"ok\"}
3022#KANADE-CHECK-END
3023#KANADE-COLLECT-BEGIN
3024{\"files\":[\"a\"]}
3025#KANADE-COLLECT-END
3026";
3027        assert_eq!(
3028            fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
3029            "{\"os\":\"win\"}"
3030        );
3031        assert_eq!(
3032            fenced_payload(stdout, CHECK_BLOCK_BEGIN, CHECK_BLOCK_END),
3033            "{\"status\":\"ok\"}"
3034        );
3035        assert_eq!(
3036            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
3037            "{\"files\":[\"a\"]}"
3038        );
3039    }
3040
3041    #[test]
3042    fn fenced_payload_falls_back_to_whole_stdout_without_fence() {
3043        // A single-hint job needs no fence — the whole (trimmed) stdout is
3044        // the payload.
3045        let stdout = "  {\"files\":[\"a\"]}  ";
3046        assert_eq!(
3047            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
3048            "{\"files\":[\"a\"]}"
3049        );
3050    }
3051
3052    #[test]
3053    fn fenced_payload_returns_empty_when_other_fences_present_but_mine_missing() {
3054        // Multi-hint output (inventory + check fenced) but the COLLECT
3055        // fence is missing — collect must NOT fall back to the whole
3056        // stdout (which holds the inventory/check blocks) and cross-parse
3057        // a sibling block; it gets "" → its JSON parse fails → no data.
3058        let stdout = "\
3059#KANADE-INVENTORY-BEGIN
3060{\"os\":\"win\"}
3061#KANADE-INVENTORY-END
3062#KANADE-CHECK-BEGIN
3063{\"status\":\"ok\"}
3064#KANADE-CHECK-END
3065";
3066        assert_eq!(
3067            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
3068            ""
3069        );
3070        // ...while the hints that DID fence still extract correctly.
3071        assert_eq!(
3072            fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
3073            "{\"os\":\"win\"}"
3074        );
3075    }
3076
3077    /// The example check-job + schedule YAMLs shipped under `configs/`
3078    /// must stay valid as the schema evolves (#290 PR-C). `include_str!`
3079    /// pins them at compile time so a breaking edit fails `cargo test`
3080    /// rather than only `kanade job create` at deploy time.
3081    #[test]
3082    fn example_check_job_yamls_parse_and_validate() {
3083        let jobs = [
3084            (
3085                "check-bitlocker",
3086                include_str!("../../../configs/jobs/check-bitlocker.yaml"),
3087            ),
3088            (
3089                "check-av-signature",
3090                include_str!("../../../configs/jobs/check-av-signature.yaml"),
3091            ),
3092            (
3093                "check-cert-expiry",
3094                include_str!("../../../configs/jobs/check-cert-expiry.yaml"),
3095            ),
3096            (
3097                "check-disk-space",
3098                include_str!("../../../configs/jobs/check-disk-space.yaml"),
3099            ),
3100            (
3101                "check-pending-reboot",
3102                include_str!("../../../configs/jobs/check-pending-reboot.yaml"),
3103            ),
3104            (
3105                "check-defender-rtp",
3106                include_str!("../../../configs/jobs/check-defender-rtp.yaml"),
3107            ),
3108            (
3109                "check-firewall",
3110                include_str!("../../../configs/jobs/check-firewall.yaml"),
3111            ),
3112        ];
3113        for (name, yaml) in jobs {
3114            let m: Manifest =
3115                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} parse: {e}"));
3116            m.validate()
3117                .unwrap_or_else(|e| panic!("{name} validate: {e}"));
3118            let check = m
3119                .check
3120                .as_ref()
3121                .unwrap_or_else(|| panic!("{name} must carry a check: hint"));
3122            assert!(!check.name.trim().is_empty(), "{name} check.name empty");
3123            // These examples all read admin-only WMI / registry / netsh
3124            // state, so they run_as system. NOTE: that's a property of
3125            // these particular checks, NOT of the `check:` contract — a
3126            // check probing user-session state could run_as user.
3127            assert_eq!(
3128                m.execute.run_as,
3129                RunAs::System,
3130                "{name} should run_as system"
3131            );
3132        }
3133    }
3134
3135    /// The example user-invokable job YAMLs (#291) shipped under
3136    /// `configs/jobs/` must stay valid as the `client:` schema
3137    /// evolves. `include_str!` pins them at compile time so a breaking
3138    /// edit fails `cargo test`, not `kanade job create` at deploy.
3139    #[test]
3140    fn example_client_job_yamls_parse_and_validate() {
3141        let jobs = [
3142            (
3143                "fix-teams-cache",
3144                "troubleshoot",
3145                include_str!("../../../configs/jobs/fix-teams-cache.yaml"),
3146            ),
3147            (
3148                "chrome-update",
3149                "software_update",
3150                include_str!("../../../configs/jobs/chrome-update.yaml"),
3151            ),
3152            (
3153                "install-slack",
3154                "catalog",
3155                include_str!("../../../configs/jobs/install-slack.yaml"),
3156            ),
3157            (
3158                "fix-defender-rtp",
3159                "troubleshoot",
3160                include_str!("../../../configs/jobs/fix-defender-rtp.yaml"),
3161            ),
3162            // #792 custom category ("settings") + #809 message/inventory.
3163            (
3164                "example-power-plan",
3165                "settings",
3166                include_str!("../../../configs/jobs/example-power-plan.yaml"),
3167            ),
3168            // #792: diagnostics moved to its own "support" tab.
3169            (
3170                "collect-diagnostics",
3171                "support",
3172                include_str!("../../../configs/jobs/collect-diagnostics.yaml"),
3173            ),
3174        ];
3175        for (id, category, yaml) in jobs {
3176            let m: Manifest =
3177                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
3178            m.validate()
3179                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
3180            assert_eq!(m.id, id, "{id} id mismatch");
3181            let client = m
3182                .client
3183                .as_ref()
3184                .unwrap_or_else(|| panic!("{id} must carry a client: block"));
3185            assert!(!client.name.trim().is_empty(), "{id} client.name empty");
3186            assert_eq!(client.category, category, "{id} category");
3187        }
3188    }
3189
3190    /// #219: the shipped `collect:` example must stay valid as the
3191    /// schema evolves. `include_str!` pins it at compile time so a
3192    /// breaking edit (or a YAML typo in the PowerShell block) fails
3193    /// `cargo test` rather than `kanade job create` at deploy. It carries
3194    /// both `collect:` and `client:` (end-user-triggerable), which must
3195    /// compose.
3196    #[test]
3197    fn example_collect_job_yaml_parses_and_validates() {
3198        let yaml = include_str!("../../../configs/jobs/collect-diagnostics.yaml");
3199        let m: Manifest = serde_yaml::from_str(yaml).expect("collect-diagnostics parse");
3200        m.validate().expect("collect-diagnostics validate");
3201        assert_eq!(m.id, "collect-diagnostics");
3202        let collect = m.collect.as_ref().expect("collect: block present");
3203        assert!(!collect.name.trim().is_empty());
3204        assert_eq!(collect.files_field, "files");
3205        assert_eq!(collect.max_size_bytes(), 50_000_000);
3206        // collect + client compose — the Client App can trigger it.
3207        assert!(
3208            m.client.is_some(),
3209            "collect-diagnostics also carries client:"
3210        );
3211    }
3212
3213    /// The `emit: { type: events }` collector jobs under
3214    /// `configs/jobs/` feed the obs_events timeline. `include_str!`
3215    /// pins them at compile time so a breaking edit (e.g. an `emit:`
3216    /// paired with `check:`/`inventory:`, a bad watermark field, or a
3217    /// YAML typo in the PowerShell block) fails `cargo test` rather
3218    /// than `kanade job create` at deploy. Every one must carry an
3219    /// `emit.type=events` block and NO check/inventory (validate()
3220    /// rejects the pairing).
3221    #[test]
3222    fn example_event_collector_job_yamls_parse_and_validate() {
3223        let jobs = [
3224            // collect-winlog-events was retired in #841 PR2 — the scheduled
3225            // human-session / power timeline is now read natively by the
3226            // agent (kanade-agent `winlog` module via EvtQuery), no
3227            // PowerShell job. collect-winlog-logons-all stays as the
3228            // on-demand forensic all-token-logons companion.
3229            (
3230                "collect-winlog-logons-all",
3231                include_str!("../../../configs/jobs/collect-winlog-logons-all.yaml"),
3232            ),
3233            (
3234                "collect-wlan-events",
3235                include_str!("../../../configs/jobs/collect-wlan-events.yaml"),
3236            ),
3237        ];
3238        for (id, yaml) in jobs {
3239            // Strict parse so an unknown-key typo in these fixtures fails
3240            // here (not silently at deploy) — the runtime Manifest is
3241            // unknown-key-tolerant, so the lenient serde_yaml::from_str
3242            // wouldn't catch fixture drift (CodeRabbit #689).
3243            let m: Manifest =
3244                crate::strict::from_yaml_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
3245            m.validate()
3246                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
3247            assert_eq!(m.id, id, "{id} id mismatch");
3248            let emit = m
3249                .emit
3250                .as_ref()
3251                .unwrap_or_else(|| panic!("{id} must carry an emit: block"));
3252            assert_eq!(emit.kind, EmitKind::Events, "{id} emit.type");
3253            assert!(
3254                m.check.is_none() && m.inventory.is_none(),
3255                "{id}: emit jobs must not pair with check/inventory"
3256            );
3257        }
3258    }
3259
3260    /// The `inventory:` snapshot jobs under `configs/jobs/` project
3261    /// facts into `inventory_facts` + exploded tables. `include_str!`
3262    /// pins them at compile time so a breaking edit (bad explode
3263    /// schema, a YAML typo in the PowerShell block, an `inventory:`
3264    /// accidentally paired with `emit:`) fails `cargo test` rather
3265    /// than the projector at deploy. Each must carry an `inventory:`
3266    /// block and NO emit (validate() rejects the pairing).
3267    #[test]
3268    fn example_inventory_job_yamls_parse_and_validate() {
3269        let jobs = [
3270            (
3271                "inventory-hw",
3272                include_str!("../../../configs/jobs/inventory-hw.yaml"),
3273            ),
3274            (
3275                "inventory-sw",
3276                include_str!("../../../configs/jobs/inventory-sw.yaml"),
3277            ),
3278            (
3279                "inventory-driver",
3280                include_str!("../../../configs/jobs/inventory-driver.yaml"),
3281            ),
3282        ];
3283        for (id, yaml) in jobs {
3284            let m: Manifest =
3285                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
3286            m.validate()
3287                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
3288            assert_eq!(m.id, id, "{id} id mismatch");
3289            assert!(m.inventory.is_some(), "{id} must carry an inventory: block");
3290            assert!(m.emit.is_none(), "{id}: inventory jobs must not set emit:");
3291        }
3292    }
3293
3294    #[test]
3295    fn example_check_schedule_yamls_parse_and_validate() {
3296        let schedules = [
3297            (
3298                "check-bitlocker",
3299                include_str!("../../../configs/schedules/check-bitlocker.yaml"),
3300            ),
3301            (
3302                "check-av-signature",
3303                include_str!("../../../configs/schedules/check-av-signature.yaml"),
3304            ),
3305            (
3306                "check-cert-expiry",
3307                include_str!("../../../configs/schedules/check-cert-expiry.yaml"),
3308            ),
3309            (
3310                "check-disk-space",
3311                include_str!("../../../configs/schedules/check-disk-space.yaml"),
3312            ),
3313            (
3314                "check-pending-reboot",
3315                include_str!("../../../configs/schedules/check-pending-reboot.yaml"),
3316            ),
3317            (
3318                "check-defender-rtp",
3319                include_str!("../../../configs/schedules/check-defender-rtp.yaml"),
3320            ),
3321            (
3322                "check-firewall",
3323                include_str!("../../../configs/schedules/check-firewall.yaml"),
3324            ),
3325        ];
3326        for (name, yaml) in schedules {
3327            let s: Schedule =
3328                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
3329            s.validate()
3330                .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
3331            assert_eq!(s.job_id, name, "{name} schedule must reference its job");
3332        }
3333    }
3334
3335    /// Inventory schedule wrappers (`per_pc` cadence) must stay valid
3336    /// alongside the schedule schema. `include_str!` pins them so a
3337    /// breaking edit fails `cargo test`, not `kanade schedule create`.
3338    #[test]
3339    fn example_inventory_schedule_yamls_parse_and_validate() {
3340        let schedules = [
3341            (
3342                "inventory-hw",
3343                include_str!("../../../configs/schedules/inventory-hw.yaml"),
3344            ),
3345            (
3346                "inventory-sw",
3347                include_str!("../../../configs/schedules/inventory-sw.yaml"),
3348            ),
3349            (
3350                "inventory-driver",
3351                include_str!("../../../configs/schedules/inventory-driver.yaml"),
3352            ),
3353        ];
3354        for (name, yaml) in schedules {
3355            let s: Schedule =
3356                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
3357            s.validate()
3358                .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
3359            assert_eq!(s.job_id, name, "{name} schedule must reference its job");
3360        }
3361    }
3362
3363    #[test]
3364    fn target_is_specified_requires_at_least_one_field() {
3365        let empty = Target::default();
3366        assert!(!empty.is_specified());
3367
3368        let with_all = Target {
3369            all: true,
3370            ..Target::default()
3371        };
3372        assert!(with_all.is_specified());
3373
3374        let with_groups = Target {
3375            groups: vec!["canary".into()],
3376            ..Target::default()
3377        };
3378        assert!(with_groups.is_specified());
3379
3380        let with_pcs = Target {
3381            pcs: vec!["pc-01".into()],
3382            ..Target::default()
3383        };
3384        assert!(with_pcs.is_specified());
3385    }
3386
3387    #[test]
3388    fn manifest_deserialises_minimal_yaml() {
3389        // Matches jobs/echo-test.yaml. v0.18: no target/rollout/jitter
3390        // — those live on the schedule / exec request now.
3391        let yaml = r#"
3392id: echo-test
3393version: 0.0.1
3394execute:
3395  shell: powershell
3396  script: "echo 'kanade'"
3397  timeout: 30s
3398"#;
3399        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3400        assert_eq!(m.id, "echo-test");
3401        assert_eq!(m.version, "0.0.1");
3402        assert!(matches!(m.execute.shell, ExecuteShell::Powershell));
3403        assert_eq!(
3404            m.execute.script.as_deref().map(str::trim),
3405            Some("echo 'kanade'")
3406        );
3407        assert!(m.execute.script_file.is_none());
3408        assert!(m.execute.script_object.is_none());
3409        assert_eq!(m.execute.timeout, "30s");
3410        assert!(!m.require_approval);
3411        m.validate()
3412            .expect("inline-script manifest passes validation");
3413    }
3414
3415    #[test]
3416    fn manifest_parses_check_job_and_validates() {
3417        // An operator-defined health check (#290): a `check:` hint +
3418        // a PowerShell script that prints {status, detail}.
3419        let yaml = r#"
3420id: check-bitlocker
3421version: 0.1.0
3422execute:
3423  shell: powershell
3424  run_as: system
3425  timeout: 15s
3426  script: |
3427    [pscustomobject]@{ status = 'ok'; detail = 'all volumes protected' } | ConvertTo-Json -Compress
3428check:
3429  name: bitlocker
3430  troubleshoot: fix-bitlocker
3431"#;
3432        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3433        let check = m.check.as_ref().expect("check hint present");
3434        assert_eq!(check.name, "bitlocker");
3435        assert_eq!(check.troubleshoot.as_deref(), Some("fix-bitlocker"));
3436        // Field names default to the conventional "status" / "detail".
3437        assert_eq!(check.status_field, "status");
3438        assert_eq!(check.detail_field, "detail");
3439        assert!(m.inventory.is_none() && m.emit.is_none());
3440        m.validate().expect("check-only manifest passes validation");
3441    }
3442
3443    #[test]
3444    fn manifest_check_defaults_and_custom_fields() {
3445        // Minimal: only `name`; status/detail fields default.
3446        let m: Manifest = serde_yaml::from_str(
3447            r#"
3448id: check-disk
3449version: 0.1.0
3450execute:
3451  shell: powershell
3452  script: "[pscustomobject]@{ status = 'ok' } | ConvertTo-Json -Compress"
3453  timeout: 10s
3454check:
3455  name: disk_free
3456"#,
3457        )
3458        .expect("parse");
3459        let c = m.check.as_ref().unwrap();
3460        assert_eq!(c.name, "disk_free");
3461        assert_eq!(c.status_field, "status");
3462        assert_eq!(c.detail_field, "detail");
3463        assert!(c.troubleshoot.is_none());
3464        m.validate().expect("validates");
3465
3466        // The operator can point status/detail at any field of their
3467        // free-form inventory object.
3468        let m2: Manifest = serde_yaml::from_str(
3469            r#"
3470id: check-custom
3471version: 0.1.0
3472execute:
3473  shell: powershell
3474  script: "echo x"
3475  timeout: 10s
3476check:
3477  name: patch_level
3478  status_field: compliance
3479  detail_field: summary
3480"#,
3481        )
3482        .expect("parse");
3483        let c2 = m2.check.as_ref().unwrap();
3484        assert_eq!(c2.status_field, "compliance");
3485        assert_eq!(c2.detail_field, "summary");
3486    }
3487
3488    #[test]
3489    fn manifest_allows_check_composed_with_inventory() {
3490        // `check:` + `inventory:` COMPOSE on the same stdout object:
3491        // status/detail → Health tab, the rest → SPA projection +
3492        // explode sub-tables. Must pass validation.
3493        let yaml = r#"
3494id: check-bitlocker-detailed
3495version: 0.1.0
3496execute:
3497  shell: powershell
3498  script: "echo x"
3499  timeout: 10s
3500check:
3501  name: bitlocker
3502inventory:
3503  display:
3504    - { field: status, label: Status }
3505"#;
3506        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3507        assert!(m.check.is_some() && m.inventory.is_some());
3508        m.validate().expect("check + inventory compose");
3509    }
3510
3511    #[test]
3512    fn manifest_parses_collect_job_and_validates() {
3513        // #219: a `collect:` hint + a script that lists files on stdout.
3514        let yaml = r#"
3515id: collect-diagnostics
3516version: 0.1.0
3517execute:
3518  shell: powershell
3519  run_as: system
3520  timeout: 120s
3521  script: |
3522    @{ files = @("$env:KANADE_COLLECT_DIR/system.csv") } | ConvertTo-Json
3523collect:
3524  name: "Full diagnostics"
3525  description: "Event logs + process"
3526  max_size: 50MB
3527"#;
3528        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3529        let c = m.collect.as_ref().expect("collect hint present");
3530        assert_eq!(c.name, "Full diagnostics");
3531        assert_eq!(c.files_field, "files"); // default
3532        assert_eq!(c.max_size_bytes(), 50_000_000);
3533        m.validate().expect("collect-only manifest validates");
3534    }
3535
3536    #[test]
3537    fn manifest_finalize_powershell_validates_and_lowers() {
3538        let yaml = r#"
3539id: collect-fin
3540version: 0.1.0
3541execute:
3542  shell: powershell
3543  timeout: 120s
3544  script: |
3545    @{ files = @() } | ConvertTo-Json
3546collect:
3547  name: "diag"
3548  max_size: 50MB
3549finalize:
3550  shell: powershell
3551  timeout: 30s
3552  run_as: system
3553  script: |
3554    Write-Output "cleanup"
3555"#;
3556        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3557        m.validate().expect("powershell finalize validates");
3558        let lowered = m.finalize.as_ref().expect("finalize present").lower();
3559        assert_eq!(lowered.timeout_secs, 30);
3560        assert!(matches!(lowered.shell, Shell::Powershell));
3561        // #965: default is the one-call-after-all contract.
3562        assert!(!lowered.on_each_bundle);
3563    }
3564
3565    #[test]
3566    fn manifest_finalize_on_each_bundle_validates_with_collect_and_lowers() {
3567        // #965: on_each_bundle + a collect hint is the intended
3568        // combination — validates, and the flag survives lowering.
3569        let yaml = r#"
3570id: collect-fin-each
3571version: 0.1.0
3572execute:
3573  shell: powershell
3574  timeout: 120s
3575  script: |
3576    @{ files = @() } | ConvertTo-Json
3577collect:
3578  name: "diag"
3579  max_size: 50MB
3580finalize:
3581  shell: powershell
3582  on_each_bundle: true
3583  script: |
3584    Write-Output "cleanup"
3585"#;
3586        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3587        m.validate().expect("on_each_bundle + collect validates");
3588        let lowered = m.finalize.as_ref().expect("finalize present").lower();
3589        assert!(lowered.on_each_bundle, "flag survives lowering");
3590    }
3591
3592    #[test]
3593    fn manifest_finalize_on_each_bundle_without_collect_rejected() {
3594        // #965: a non-collect finalize has no bundles to iterate, so
3595        // on_each_bundle is a no-op — reject it at the write boundary so
3596        // the operator is told rather than silently getting nothing.
3597        let yaml = r#"
3598id: fin-each-no-collect
3599version: 0.1.0
3600execute:
3601  shell: powershell
3602  timeout: 120s
3603  script: |
3604    Write-Output "hi"
3605finalize:
3606  shell: powershell
3607  on_each_bundle: true
3608  script: |
3609    Write-Output "cleanup"
3610"#;
3611        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3612        let err = m
3613            .validate()
3614            .expect_err("on_each_bundle without collect rejected");
3615        assert!(err.contains("on_each_bundle"), "got: {err}");
3616        assert!(err.contains("collect"), "got: {err}");
3617    }
3618
3619    #[test]
3620    fn manifest_finalize_rejects_cmd_shell() {
3621        // cmd finalize is an injection risk (the agent injects JSON into
3622        // the hook's env; cmd.exe quoting doesn't nest) — validate must
3623        // reject it.
3624        let yaml = r#"
3625id: collect-fin-cmd
3626version: 0.1.0
3627execute:
3628  shell: powershell
3629  timeout: 120s
3630  script: |
3631    @{ files = @() } | ConvertTo-Json
3632finalize:
3633  shell: cmd
3634  script: |
3635    echo hi
3636"#;
3637        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3638        let err = m.validate().expect_err("cmd finalize rejected");
3639        assert!(err.contains("finalize.shell"), "got: {err}");
3640    }
3641
3642    #[test]
3643    fn manifest_finalize_rejects_sh_shell() {
3644        // sh finalize is rejected for the same reason as cmd: the agent
3645        // injects the result JSON, and the injected prelude is PowerShell
3646        // syntax that a POSIX shell can't run.
3647        let yaml = r#"
3648id: collect-fin-sh
3649version: 0.1.0
3650execute:
3651  shell: powershell
3652  timeout: 120s
3653  script: |
3654    @{ files = @() } | ConvertTo-Json
3655finalize:
3656  shell: sh
3657  script: |
3658    echo hi
3659"#;
3660        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3661        let err = m.validate().expect_err("sh finalize rejected");
3662        assert!(err.contains("finalize.shell"), "got: {err}");
3663    }
3664
3665    #[test]
3666    fn manifest_finalize_accepts_pwsh_shell() {
3667        // pwsh IS PowerShell, so the injected prelude + single-quote
3668        // escaping are valid and safe — a pwsh finalize must validate.
3669        let yaml = r#"
3670id: collect-fin-pwsh
3671version: 0.1.0
3672execute:
3673  shell: pwsh
3674  timeout: 120s
3675  script: |
3676    @{ files = @() } | ConvertTo-Json
3677finalize:
3678  shell: pwsh
3679  script: |
3680    Write-Output hi
3681"#;
3682        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3683        m.validate().expect("pwsh finalize accepted");
3684    }
3685
3686    #[test]
3687    fn manifest_finalize_rejects_empty_script() {
3688        let yaml = r#"
3689id: collect-fin-empty
3690version: 0.1.0
3691execute:
3692  shell: powershell
3693  timeout: 120s
3694  script: |
3695    @{ files = @() } | ConvertTo-Json
3696finalize:
3697  shell: powershell
3698  script: "   "
3699"#;
3700        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3701        let err = m.validate().expect_err("empty finalize script rejected");
3702        assert!(err.contains("finalize.script"), "got: {err}");
3703    }
3704
3705    #[test]
3706    fn manifest_collect_max_size_defaults_when_unset() {
3707        let m: Manifest = serde_yaml::from_str(
3708            r#"
3709id: collect-min
3710version: 0.1.0
3711execute:
3712  shell: powershell
3713  script: "echo x"
3714  timeout: 10s
3715collect:
3716  name: minimal
3717"#,
3718        )
3719        .expect("parse");
3720        let c = m.collect.as_ref().unwrap();
3721        assert!(c.max_size.is_none());
3722        assert_eq!(c.max_size_bytes(), DEFAULT_COLLECT_MAX_SIZE);
3723        m.validate().expect("validates");
3724    }
3725
3726    #[test]
3727    fn manifest_allows_collect_with_client() {
3728        // collect composes with client (client doesn't touch stdout):
3729        // an end user can trigger a collection from the Client App.
3730        let yaml = r#"
3731id: collect-diag-client
3732version: 0.1.0
3733execute:
3734  shell: powershell
3735  script: "echo x"
3736  timeout: 10s
3737collect:
3738  name: diagnostics
3739client:
3740  name: "Send diagnostics"
3741  category: troubleshoot
3742"#;
3743        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3744        assert!(m.collect.is_some() && m.client.is_some());
3745        m.validate().expect("collect + client compose");
3746    }
3747
3748    #[test]
3749    fn manifest_allows_inventory_check_collect_coexistence() {
3750        // #821: the three fenced hints now COMPOSE — each reads its own
3751        // `#KANADE-<KIND>` stdout block, so one job can do all three.
3752        let yaml = r#"
3753id: multi-hint
3754version: 0.1.0
3755execute:
3756  shell: powershell
3757  script: "echo x"
3758  timeout: 10s
3759inventory:
3760  display:
3761    - { field: status, label: Status }
3762check:
3763  name: health
3764collect:
3765  name: diag
3766"#;
3767        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3768        m.validate()
3769            .expect("inventory + check + collect coexist after #821");
3770    }
3771
3772    #[test]
3773    fn manifest_rejects_emit_combined_with_fenced_hints() {
3774        // `emit:` consumes stdout as NDJSON (and blanks it), so it still
3775        // can't share with any fenced hint — inventory, check, OR collect.
3776        for extra in [
3777            "inventory:\n  display:\n    - { field: s, label: S }\n",
3778            "check:\n  name: health\n",
3779            "collect:\n  name: diag\n",
3780        ] {
3781            let yaml = format!(
3782                "id: bad-emit-mix\nversion: 0.1.0\nexecute:\n  shell: powershell\n  \
3783                 script: \"echo x\"\n  timeout: 10s\nemit:\n  type: events\n{extra}"
3784            );
3785            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
3786            let err = m
3787                .validate()
3788                .expect_err("emit + fenced hint must be rejected");
3789            assert!(err.contains("emit"), "error mentions emit: {err}");
3790        }
3791    }
3792
3793    #[test]
3794    fn manifest_rejects_collect_empty_name_and_bad_size() {
3795        let empty_name: Manifest = serde_yaml::from_str(
3796            r#"
3797id: c
3798version: 0.1.0
3799execute: { shell: powershell, script: "echo x", timeout: 10s }
3800collect: { name: "  " }
3801"#,
3802        )
3803        .expect("parse");
3804        assert!(
3805            empty_name.validate().is_err(),
3806            "blank collect.name rejected"
3807        );
3808
3809        let bad_size: Manifest = serde_yaml::from_str(
3810            r#"
3811id: c
3812version: 0.1.0
3813execute: { shell: powershell, script: "echo x", timeout: 10s }
3814collect: { name: diag, max_size: "50 quux" }
3815"#,
3816        )
3817        .expect("parse");
3818        let err = bad_size.validate().expect_err("bad max_size rejected");
3819        assert!(err.contains("max_size"), "error mentions max_size: {err}");
3820    }
3821
3822    #[test]
3823    fn parse_size_bytes_units() {
3824        assert_eq!(parse_size_bytes("1024").unwrap(), 1024);
3825        assert_eq!(parse_size_bytes("1B").unwrap(), 1);
3826        assert_eq!(parse_size_bytes("50MB").unwrap(), 50_000_000);
3827        assert_eq!(parse_size_bytes("500 KB").unwrap(), 500_000);
3828        assert_eq!(parse_size_bytes("1GiB").unwrap(), 1024 * 1024 * 1024);
3829        assert_eq!(parse_size_bytes("2mib").unwrap(), 2 * 1024 * 1024);
3830        assert!(parse_size_bytes("").is_err());
3831        assert!(parse_size_bytes("MB").is_err());
3832        assert!(parse_size_bytes("12 zonks").is_err());
3833    }
3834
3835    #[test]
3836    fn manifest_rejects_check_combined_with_emit() {
3837        // `emit:` stdout is NDJSON (and omitted from the result), so
3838        // it can't pair with `check:` (which needs a single JSON
3839        // object on stdout).
3840        let yaml = r#"
3841id: bad-mix
3842version: 0.1.0
3843execute:
3844  shell: powershell
3845  script: "echo x"
3846  timeout: 10s
3847check:
3848  name: bitlocker
3849emit:
3850  type: events
3851"#;
3852        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3853        let err = m.validate().expect_err("emit + check must fail");
3854        assert!(err.contains("incompatible"), "err: {err}");
3855    }
3856
3857    #[test]
3858    fn manifest_rejects_emit_combined_with_inventory() {
3859        // The other half of the emit-incompatibility condition.
3860        let yaml = r#"
3861id: bad-mix-2
3862version: 0.1.0
3863execute:
3864  shell: powershell
3865  script: "echo x"
3866  timeout: 10s
3867emit:
3868  type: events
3869inventory:
3870  display:
3871    - { field: status, label: Status }
3872"#;
3873        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3874        let err = m.validate().expect_err("emit + inventory must fail");
3875        assert!(err.contains("incompatible"), "err: {err}");
3876    }
3877
3878    #[test]
3879    fn manifest_rejects_empty_check_field_names() {
3880        // Empty name / status_field / detail_field are invisible
3881        // runtime bugs (empty React key, agent reads the wrong field)
3882        // — reject them even though serde supplies non-empty defaults.
3883        let base = |inner: &str| {
3884            format!(
3885                "id: c\nversion: 0.1.0\nexecute:\n  shell: powershell\n  script: \"echo x\"\n  timeout: 10s\ncheck:\n{inner}"
3886            )
3887        };
3888        for inner in [
3889            "  name: \"\"\n",
3890            "  name: ok\n  status_field: \"\"\n",
3891            "  name: ok\n  detail_field: \"   \"\n",
3892            // present-but-blank troubleshoot → broken remediation id.
3893            "  name: ok\n  troubleshoot: \"  \"\n",
3894        ] {
3895            let m: Manifest = serde_yaml::from_str(&base(inner)).expect("parse");
3896            let err = m.validate().expect_err("empty field must fail");
3897            assert!(err.contains("must not be empty"), "err: {err}");
3898        }
3899    }
3900
3901    #[test]
3902    fn check_alert_decodes_with_defaults_and_validates() {
3903        let yaml = r#"
3904id: c
3905version: 0.1.0
3906execute:
3907  shell: powershell
3908  script: "echo x"
3909  timeout: 10s
3910check:
3911  name: bitlocker
3912  alert:
3913    notify_user: true
3914    title: "BitLocker 未準拠"
3915"#;
3916        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3917        m.validate().expect("valid alert");
3918        let alert = m.check.unwrap().alert.unwrap();
3919        // Defaults: on = [fail], priority = warn, body = None.
3920        assert_eq!(alert.on, vec![CheckAlertStatus::Fail]);
3921        assert_eq!(
3922            alert.priority,
3923            crate::ipc::notifications::NotificationPriority::Warn
3924        );
3925        assert!(alert.body.is_none());
3926        assert!(alert.notify_user);
3927    }
3928
3929    #[test]
3930    fn check_alert_validation_rejects_bad_configs() {
3931        let base = |alert: &str| {
3932            format!(
3933                "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}"
3934            )
3935        };
3936        let cases = [
3937            // No recipient.
3938            ("    title: t\n", "notify_user and/or notify_groups"),
3939            // Empty title.
3940            (
3941                "    notify_user: true\n    title: \"  \"\n",
3942                "title must not be empty",
3943            ),
3944            // Empty `on`.
3945            (
3946                "    notify_user: true\n    title: t\n    on: []\n",
3947                "on must list at least one status",
3948            ),
3949            // Blank group name.
3950            (
3951                "    notify_groups: [\"  \"]\n    title: t\n",
3952                "notify_groups must not contain blanks",
3953            ),
3954            // alert requires fleet: true.
3955            (
3956                "    notify_user: true\n    title: t\n  fleet: false\n",
3957                "requires fleet: true",
3958            ),
3959            // email opt-in without a group to address.
3960            (
3961                "    notify_user: true\n    email: true\n    title: t\n",
3962                "email requires notify_groups",
3963            ),
3964        ];
3965        for (alert, want) in cases {
3966            let m: Manifest = serde_yaml::from_str(&base(alert)).expect("parse");
3967            let err = m.validate().expect_err("bad alert must fail");
3968            assert!(err.contains(want), "for {alert:?}: got {err}");
3969        }
3970    }
3971
3972    #[test]
3973    fn manifest_client_absent_by_default() {
3974        // A plain operator job (the overwhelming majority) carries no
3975        // `client:` block, so it never surfaces in the end-user
3976        // catalog.
3977        let yaml = r#"
3978id: echo-test
3979version: 0.0.1
3980execute:
3981  shell: powershell
3982  script: "echo 'kanade'"
3983  timeout: 30s
3984"#;
3985        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3986        assert!(m.client.is_none());
3987        m.validate().expect("operator-only job validates");
3988    }
3989
3990    #[test]
3991    fn manifest_client_parses_and_validates() {
3992        // The Client App "困ったとき" remediation job shape: a
3993        // user-invokable troubleshoot job with the end-user fields the
3994        // KLP `jobs.list` wire needs, grouped under `client:`.
3995        let yaml = r#"
3996id: fix-teams-cache
3997version: 1.0.0
3998execute:
3999  shell: powershell
4000  script: "echo clearing"
4001  timeout: 60s
4002client:
4003  name: "Teams のキャッシュをクリア"
4004  description: "Teams が重いときに試してください"
4005  category: troubleshoot
4006  icon: brush-cleaning
4007"#;
4008        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4009        let c = m.client.as_ref().expect("client block present");
4010        assert_eq!(c.name, "Teams のキャッシュをクリア");
4011        assert_eq!(
4012            c.description.as_deref(),
4013            Some("Teams が重いときに試してください")
4014        );
4015        assert_eq!(c.category, "troubleshoot");
4016        assert_eq!(c.icon.as_deref(), Some("brush-cleaning"));
4017        m.validate().expect("user-invokable job validates");
4018    }
4019
4020    #[test]
4021    fn manifest_client_minimal_only_name_and_category() {
4022        // description + icon are optional; name + category are the
4023        // serde-required minimum.
4024        let yaml = r#"
4025id: install-slack
4026version: 1.0.0
4027execute:
4028  shell: powershell
4029  script: "echo install"
4030  timeout: 600s
4031client:
4032  name: Slack
4033  category: catalog
4034"#;
4035        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4036        let c = m.client.as_ref().expect("client present");
4037        assert_eq!(c.category, "catalog");
4038        assert!(c.description.is_none() && c.icon.is_none());
4039        m.validate().expect("minimal client validates");
4040    }
4041
4042    #[test]
4043    fn manifest_client_rejects_blank_name() {
4044        // serde guarantees `name`/`category` are present; the one gap
4045        // is a present-but-blank name → empty catalog row title.
4046        let yaml = r#"
4047id: j
4048version: 1.0.0
4049execute:
4050  shell: powershell
4051  script: "echo x"
4052  timeout: 30s
4053client:
4054  name: "   "
4055  category: catalog
4056"#;
4057        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4058        let err = m.validate().expect_err("blank name must fail");
4059        assert!(err.contains("client.name"), "err: {err}");
4060    }
4061
4062    #[test]
4063    fn manifest_client_rejects_blank_optional_fields() {
4064        // description / icon are optional, but a present-but-blank
4065        // value is a bug (empty subtitle / dangling icon name) — reject
4066        // it, mirroring the check: block's troubleshoot guard.
4067        for (field, line) in [
4068            ("client.description", "  description: \"  \"\n"),
4069            ("client.icon", "  icon: \"\"\n"),
4070            // #792: the new category tab-metadata fields get the same
4071            // present-but-blank guard.
4072            ("client.category_label", "  category_label: \"  \"\n"),
4073            ("client.category_icon", "  category_icon: \"\"\n"),
4074        ] {
4075            let yaml = format!(
4076                "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}"
4077            );
4078            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
4079            let err = m.validate().expect_err("blank optional field must fail");
4080            assert!(err.contains(field), "expected {field} in err: {err}");
4081        }
4082    }
4083
4084    #[test]
4085    fn manifest_client_rejects_blank_category() {
4086        // #792: category is a free-form key now; serde keeps it required,
4087        // but a present-but-blank value would group the job under an empty
4088        // tab — validate() must reject it.
4089        let yaml = r#"
4090id: j
4091version: 1.0.0
4092execute:
4093  shell: powershell
4094  script: "echo x"
4095  timeout: 30s
4096client:
4097  name: "A job"
4098  category: "   "
4099"#;
4100        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4101        let err = m.validate().expect_err("blank category must fail");
4102        assert!(err.contains("client.category"), "err: {err}");
4103    }
4104
4105    #[test]
4106    fn target_matches_pc_group_and_all() {
4107        // #816: pc match, group match, all, and the no-match case.
4108        let by_pc = Target {
4109            pcs: vec!["PC1".into()],
4110            ..Default::default()
4111        };
4112        assert!(by_pc.matches("PC1", &[]));
4113        assert!(!by_pc.matches("PC2", &["g1".into()]));
4114
4115        let by_group = Target {
4116            groups: vec!["g1".into()],
4117            ..Default::default()
4118        };
4119        assert!(by_group.matches("PC2", &["g1".into()]));
4120        assert!(!by_group.matches("PC2", &["g2".into()]));
4121
4122        let all = Target {
4123            all: true,
4124            ..Default::default()
4125        };
4126        assert!(all.matches("anyPC", &[]));
4127    }
4128
4129    #[test]
4130    fn manifest_client_rejects_empty_visible_to() {
4131        // #816: a present-but-empty visible_to (no all/groups/pcs) would
4132        // hide the job from everyone — validate() must reject it.
4133        let yaml = r#"
4134id: j
4135version: 1.0.0
4136execute:
4137  shell: powershell
4138  script: "echo x"
4139  timeout: 30s
4140client:
4141  name: "A job"
4142  category: troubleshoot
4143  visible_to: {}
4144"#;
4145        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4146        let err = m.validate().expect_err("empty visible_to must fail");
4147        assert!(err.contains("client.visible_to"), "err: {err}");
4148    }
4149
4150    #[test]
4151    fn manifest_client_accepts_visible_to_groups() {
4152        let yaml = r#"
4153id: j
4154version: 1.0.0
4155execute:
4156  shell: powershell
4157  script: "echo x"
4158  timeout: 30s
4159client:
4160  name: "A job"
4161  category: settings
4162  visible_to:
4163    groups: [wifi-affected]
4164"#;
4165        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4166        m.validate().expect("visible_to with a group validates");
4167        let vt = m.client.unwrap().visible_to.unwrap();
4168        assert_eq!(vt.groups, vec!["wifi-affected".to_string()]);
4169    }
4170
4171    #[test]
4172    fn manifest_client_show_when_accepts_scalar_and_seq() {
4173        use crate::ipc::state::CheckStatus;
4174        // `is:` accepts a single status (author ergonomics) ...
4175        let scalar = r#"
4176id: office-update
4177version: 1.0.0
4178execute:
4179  shell: powershell
4180  script: "echo x"
4181  timeout: 30s
4182client:
4183  name: "Office を最新に更新"
4184  category: software_update
4185  show_when:
4186    check: office-up-to-date
4187    is: fail
4188"#;
4189        let m: Manifest = serde_yaml::from_str(scalar).expect("parse scalar");
4190        m.validate().expect("scalar show_when validates");
4191        let sw = m.client.unwrap().show_when.unwrap();
4192        assert_eq!(sw.check, "office-up-to-date");
4193        assert_eq!(sw.is, vec![CheckStatus::Fail]);
4194
4195        // ... and a list (e.g. fail-open on a not-yet-run check).
4196        let seq = scalar.replace("is: fail", "is: [fail, unknown]");
4197        let m: Manifest = serde_yaml::from_str(&seq).expect("parse seq");
4198        m.validate().expect("seq show_when validates");
4199        assert_eq!(
4200            m.client.unwrap().show_when.unwrap().is,
4201            vec![CheckStatus::Fail, CheckStatus::Unknown]
4202        );
4203    }
4204
4205    #[test]
4206    fn manifest_client_unlock_round_trips_and_defaults_absent() {
4207        let yaml = r#"
4208id: j
4209version: 1.0.0
4210execute:
4211  shell: powershell
4212  script: "echo x"
4213  timeout: 30s
4214client:
4215  name: "A job"
4216  category: troubleshoot
4217  unlock: support
4218"#;
4219        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4220        m.validate().expect("valid");
4221        assert_eq!(
4222            m.client.as_ref().unwrap().unlock.as_deref(),
4223            Some("support")
4224        );
4225
4226        // Absent ⇒ an ordinary job, and absent from the encoded form too, so
4227        // an older reader sees byte-for-byte what it saw before the field.
4228        let plain = yaml.replace("  unlock: support\n", "");
4229        let m: Manifest = serde_yaml::from_str(&plain).expect("parse");
4230        assert!(m.client.as_ref().unwrap().unlock.is_none());
4231        let v = serde_json::to_value(&m).unwrap();
4232        assert!(v["client"].get("unlock").is_none(), "wire: {v:?}");
4233    }
4234
4235    #[test]
4236    fn manifest_client_unlock_rejects_a_malformed_scope() {
4237        // The scope is compared byte-for-byte with a configured support
4238        // code's scope, and the gate fails closed — so a typo with spaces
4239        // would hide the job forever with no error anywhere. Catch it at
4240        // create time instead.
4241        let yaml = r#"
4242id: j
4243version: 1.0.0
4244execute:
4245  shell: powershell
4246  script: "echo x"
4247  timeout: 30s
4248client:
4249  name: "A job"
4250  category: troubleshoot
4251  unlock: "help desk"
4252"#;
4253        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4254        let err = m.validate().expect_err("malformed unlock scope must fail");
4255        assert!(err.contains("client.unlock"), "err: {err}");
4256
4257        let blank = yaml.replace(r#"unlock: "help desk""#, r#"unlock: "  ""#);
4258        let m: Manifest = serde_yaml::from_str(&blank).expect("parse");
4259        let err = m.validate().expect_err("blank unlock scope must fail");
4260        assert!(err.contains("client.unlock"), "err: {err}");
4261
4262        // The padded-but-otherwise-valid case (Claude review on #1166): the
4263        // charset check runs on the scope EXACTLY AS STORED, so these must
4264        // fail here rather than pass validation and then silently never
4265        // match a support code (whose scope the backend trims before
4266        // storing) — leaving the job hidden forever with no error anywhere.
4267        for padded in [r#"unlock: " support""#, r#"unlock: "support ""#] {
4268            let m: Manifest = serde_yaml::from_str(&yaml.replace(r#"unlock: "help desk""#, padded))
4269                .expect("parse");
4270            let err = m
4271                .validate()
4272                .expect_err("padded unlock scope must fail: {padded}");
4273            assert!(err.contains("client.unlock"), "{padded} err: {err}");
4274        }
4275    }
4276
4277    #[test]
4278    fn manifest_client_show_when_rejects_empty() {
4279        // A malformed check slug (here: internal spaces — a typo that could
4280        // never match a real check name) or an empty status list would
4281        // silently hide the job forever — validate() must reject both.
4282        let bad_check = r#"
4283id: j
4284version: 1.0.0
4285execute:
4286  shell: powershell
4287  script: "echo x"
4288  timeout: 30s
4289client:
4290  name: "A job"
4291  category: software_update
4292  show_when:
4293    check: "office up to date"
4294    is: fail
4295"#;
4296        let m: Manifest = serde_yaml::from_str(bad_check).expect("parse");
4297        let err = m.validate().expect_err("malformed check slug must fail");
4298        assert!(err.contains("client.show_when.check"), "err: {err}");
4299
4300        let empty_is = r#"
4301id: j
4302version: 1.0.0
4303execute:
4304  shell: powershell
4305  script: "echo x"
4306  timeout: 30s
4307client:
4308  name: "A job"
4309  category: software_update
4310  show_when:
4311    check: office-up-to-date
4312    is: []
4313"#;
4314        let m: Manifest = serde_yaml::from_str(empty_is).expect("parse");
4315        let err = m.validate().expect_err("empty is[] must fail");
4316        assert!(err.contains("client.show_when.is"), "err: {err}");
4317    }
4318
4319    #[test]
4320    fn manifest_client_confirm_accepts_bool_and_struct() {
4321        // `confirm:` deserializes from a bare bool or a struct. A bool
4322        // sets `enabled` (message stays default); a struct carries a custom
4323        // message and defaults `enabled` to true.
4324        let base = r#"
4325id: j
4326version: 1.0.0
4327execute:
4328  shell: powershell
4329  script: "echo x"
4330  timeout: 30s
4331client:
4332  name: "Wi-Fi 省電力を切る"
4333  category: settings
4334"#;
4335        // `confirm: false` ⇒ dialog suppressed.
4336        let off: Manifest =
4337            serde_yaml::from_str(&format!("{base}  confirm: false\n")).expect("parse false");
4338        off.validate().expect("confirm: false validates");
4339        let c = off.client.unwrap().confirm.unwrap();
4340        assert!(!c.enabled);
4341        assert!(c.message.is_none());
4342
4343        // `confirm: true` ⇒ same as omitting (dialog shown, default message).
4344        let on: Manifest =
4345            serde_yaml::from_str(&format!("{base}  confirm: true\n")).expect("parse true");
4346        let c = on.client.unwrap().confirm.unwrap();
4347        assert!(c.enabled);
4348        assert!(c.message.is_none());
4349
4350        // Struct with only a message ⇒ enabled defaults true, custom text.
4351        let msg: Manifest = serde_yaml::from_str(&format!(
4352            "{base}  confirm:\n    message: \"再インストールには数分かかります。よろしいですか?\"\n"
4353        ))
4354        .expect("parse struct");
4355        msg.validate().expect("confirm message validates");
4356        let c = msg.client.unwrap().confirm.unwrap();
4357        assert!(c.enabled);
4358        assert_eq!(
4359            c.message.as_deref(),
4360            Some("再インストールには数分かかります。よろしいですか?")
4361        );
4362
4363        // Absent ⇒ None (historical default handled by the client).
4364        let none: Manifest = serde_yaml::from_str(base).expect("parse none");
4365        assert!(none.client.unwrap().confirm.is_none());
4366
4367        // Explicit `confirm: null` is schema-valid (the field is Option) and
4368        // must map to None, not a parse error (Gemini #960).
4369        let null: Manifest =
4370            serde_yaml::from_str(&format!("{base}  confirm: null\n")).expect("parse null");
4371        assert!(null.client.unwrap().confirm.is_none());
4372    }
4373
4374    #[test]
4375    fn manifest_client_confirm_rejects_blank_message() {
4376        // A present-but-blank custom message would render an empty dialog
4377        // title — validate() must reject it, like the other display fields.
4378        let yaml = r#"
4379id: j
4380version: 1.0.0
4381execute:
4382  shell: powershell
4383  script: "echo x"
4384  timeout: 30s
4385client:
4386  name: "A job"
4387  category: settings
4388  confirm:
4389    message: "   "
4390"#;
4391        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4392        let err = m.validate().expect_err("blank confirm.message must fail");
4393        assert!(err.contains("client.confirm.message"), "err: {err}");
4394    }
4395
4396    #[test]
4397    fn manifest_client_requires_category_at_parse() {
4398        // A `client:` block missing `category` is a hard parse error
4399        // (serde required field) — no manual validate() needed.
4400        let yaml = r#"
4401id: j
4402version: 1.0.0
4403execute:
4404  shell: powershell
4405  script: "echo x"
4406  timeout: 30s
4407client:
4408  name: "A job"
4409"#;
4410        let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
4411        assert!(
4412            r.is_err(),
4413            "missing category must be a parse error, got {r:?}"
4414        );
4415    }
4416
4417    #[test]
4418    fn manifest_client_rejects_unknown_field() {
4419        // #492: the strict create boundary catches a fat-fingered
4420        // `displayname:` (with its path) instead of silently
4421        // dropping it; the tolerant read path accepts it.
4422        let yaml = r#"
4423id: j
4424version: 1.0.0
4425execute:
4426  shell: powershell
4427  script: "echo x"
4428  timeout: 30s
4429client:
4430  name: "A job"
4431  category: catalog
4432  displayname: oops
4433"#;
4434        let r = crate::strict::from_yaml_str::<Manifest>(yaml);
4435        let err = r.expect_err("unknown client field must be rejected at the write boundary");
4436        // serde_ignored renders the Option layer as `?`:
4437        // `client.?.displayname`. Assert on the leaf key.
4438        assert!(err.contains("displayname"), "{err}");
4439        // The READ path tolerates the same payload (gradual-upgrade
4440        // contract: an old agent must accept a newer writer's field).
4441        let m: Manifest = serde_yaml::from_str(yaml).expect("tolerant read");
4442        assert_eq!(m.client.as_ref().map(|c| c.name.as_str()), Some("A job"));
4443    }
4444
4445    #[test]
4446    fn manifest_tags_default_empty() {
4447        // The overwhelming majority of jobs carry no tags; the field
4448        // must default to an empty Vec (not fail to parse) and skip
4449        // serialisation so old readers never see the key.
4450        let yaml = r#"
4451id: echo-test
4452version: 0.0.1
4453execute:
4454  shell: powershell
4455  script: "echo 'kanade'"
4456  timeout: 30s
4457"#;
4458        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4459        assert!(m.tags.is_empty());
4460        m.validate().expect("tag-less job validates");
4461        // skip_serializing_if = empty ⇒ the key is absent from JSON.
4462        let json = serde_json::to_string(&m).expect("serialize");
4463        assert!(
4464            !json.contains("tags"),
4465            "empty tags must not serialise: {json}"
4466        );
4467    }
4468
4469    #[test]
4470    fn manifest_parses_and_validates_tags() {
4471        let yaml = r#"
4472id: check-bitlocker
4473version: 0.1.0
4474execute:
4475  shell: powershell
4476  script: "echo x"
4477  timeout: 30s
4478tags: [security, windows, health-check]
4479"#;
4480        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4481        assert_eq!(m.tags, vec!["security", "windows", "health-check"]);
4482        m.validate().expect("tagged job validates");
4483        // Round-trips through JSON (the wire format the SPA reads).
4484        let json = serde_json::to_string(&m).expect("serialize");
4485        assert!(json.contains("\"tags\""), "non-empty tags must serialise");
4486    }
4487
4488    #[test]
4489    fn manifest_rejects_blank_tag() {
4490        // A whitespace-only tag renders an empty filter chip — reject
4491        // it at the write boundary like the other blank display fields.
4492        let yaml = r#"
4493id: j
4494version: 0.1.0
4495execute:
4496  shell: powershell
4497  script: "echo x"
4498  timeout: 30s
4499tags: [ok, "   "]
4500"#;
4501        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4502        let err = m.validate().expect_err("blank tag must fail");
4503        assert!(err.contains("tags must not contain empty"), "err: {err}");
4504    }
4505
4506    #[test]
4507    fn validate_rejects_unknown_tier_and_accepts_known() {
4508        let base =
4509            "id: t\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: x\n  timeout: 30s\n";
4510        // A typo / future tier decodes to Tier::Unknown (#[serde(other)]) and
4511        // must FAIL CLOSED — never fall back to unrestricted endpoint dispatch.
4512        let bogus: Manifest =
4513            serde_yaml::from_str(&format!("{base}tier: controler\n")).expect("parse");
4514        let err = bogus.validate().expect_err("unknown tier must be rejected");
4515        assert!(err.contains("tier"), "err: {err}");
4516        // The two known tiers pass.
4517        serde_yaml::from_str::<Manifest>(&format!("{base}tier: controller\n"))
4518            .unwrap()
4519            .validate()
4520            .expect("controller tier is valid");
4521        serde_yaml::from_str::<Manifest>(&format!("{base}tier: endpoint\n"))
4522            .unwrap()
4523            .validate()
4524            .expect("endpoint tier is valid");
4525    }
4526
4527    #[test]
4528    fn feed_payload_extracts_fenced_block() {
4529        let stdout = "fetched 1500 KEV entries\n\
4530            #KANADE-FEED-BEGIN\n\
4531            {\"vulnerabilities\": []}\n\
4532            #KANADE-FEED-END\n";
4533        assert_eq!(feed_payload(stdout), "{\"vulnerabilities\": []}");
4534    }
4535
4536    #[test]
4537    fn validate_feed_rules() {
4538        let base =
4539            "id: f\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: x\n  timeout: 30s\n";
4540        // A well-formed feed (controller implied; no explicit tier) passes.
4541        serde_yaml::from_str::<Manifest>(&format!(
4542            "{base}feed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4543        ))
4544        .unwrap()
4545        .validate()
4546        .expect("a well-formed feed is valid");
4547
4548        // Empty primary_key is rejected (no item_id → every row dropped).
4549        let err = serde_yaml::from_str::<Manifest>(&format!(
4550            "{base}feed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: []\n"
4551        ))
4552        .unwrap()
4553        .validate()
4554        .expect_err("empty primary_key must be rejected");
4555        assert!(err.contains("primary_key"), "err: {err}");
4556
4557        // A duplicate feed id clobbers a partition — rejected.
4558        let err = serde_yaml::from_str::<Manifest>(&format!(
4559            "{base}feed:\n  - id: dup\n    field: a\n    primary_key: [k]\n  - id: dup\n    field: b\n    primary_key: [k]\n"
4560        ))
4561        .unwrap()
4562        .validate()
4563        .expect_err("duplicate feed id must be rejected");
4564        assert!(err.contains("more than once"), "err: {err}");
4565
4566        // `feed:` + explicit `tier: endpoint` is contradictory — rejected.
4567        let err = serde_yaml::from_str::<Manifest>(&format!(
4568            "{base}tier: endpoint\nfeed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4569        ))
4570        .unwrap()
4571        .validate()
4572        .expect_err("feed + tier: endpoint must be rejected");
4573        assert!(err.contains("controller tier"), "err: {err}");
4574
4575        // `feed:` + `emit:` is incompatible — emit consumes stdout whole, so
4576        // the feed's fence never reaches the projector.
4577        let err = serde_yaml::from_str::<Manifest>(&format!(
4578            "{base}emit:\n  type: events\nfeed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4579        ))
4580        .unwrap()
4581        .validate()
4582        .expect_err("feed + emit must be rejected");
4583        assert!(err.contains("emit"), "err: {err}");
4584    }
4585
4586    // #720 — wrap an `aggregate:` YAML block (already indented as a
4587    // top-level key body) into an otherwise-minimal valid manifest.
4588    fn manifest_with_aggregate(aggregate_block: &str) -> Manifest {
4589        let yaml = format!(
4590            "id: t\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: echo hi\n  timeout: 30s\n{aggregate_block}"
4591        );
4592        serde_yaml::from_str(&yaml).expect("parse aggregate manifest")
4593    }
4594
4595    #[test]
4596    fn aggregate_accepts_full_valid_spec() {
4597        // count+group_by+exclude+sample_minutes, ratio+bool_path,
4598        // timeline+time_bucket, fleet ranking via group_by: pc_id, and a
4599        // bare total stat — alongside emit (composes with every hint).
4600        let m = manifest_with_aggregate(
4601            "emit:\n  type: events\naggregate:\n\
4602             - { placement: { analytics: Utilization }, title: Top apps, kind: app_sample, agg: count, group_by: foreground.app, sample_minutes: 2, exclude: [LockApp], render: bar }\n\
4603             - { placement: { analytics: Utilization }, title: Active ratio, kind: presence, agg: ratio, bool_path: active, sample_minutes: 5, render: gauge }\n\
4604             - { placement: { analytics: Utilization }, title: By hour, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: timeline }\n\
4605             - { placement: { analytics: Reliability }, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
4606             - { placement: { analytics: Reliability }, title: Total crashes, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
4607        );
4608        m.validate().expect("valid aggregate spec");
4609    }
4610
4611    #[test]
4612    fn aggregate_rejects_empty_list() {
4613        let m = manifest_with_aggregate("aggregate: []\n");
4614        let err = m.validate().expect_err("empty list must fail");
4615        assert!(err.contains("at least one widget"), "err: {err}");
4616    }
4617
4618    #[test]
4619    fn aggregate_rejects_ratio_without_bool_path() {
4620        let m = manifest_with_aggregate(
4621            "aggregate:\n- { placement: { analytics: D }, title: T, kind: presence, agg: ratio, render: gauge }\n",
4622        );
4623        let err = m.validate().expect_err("ratio needs bool_path");
4624        assert!(err.contains("agg=ratio requires `bool_path`"), "err: {err}");
4625    }
4626
4627    #[test]
4628    fn aggregate_rejects_sum_without_value_path() {
4629        let m = manifest_with_aggregate(
4630            "aggregate:\n- { placement: { analytics: D }, title: T, kind: io, agg: sum, render: bar }\n",
4631        );
4632        let err = m.validate().expect_err("sum needs value_path");
4633        assert!(err.contains("agg=sum requires `value_path`"), "err: {err}");
4634    }
4635
4636    #[test]
4637    fn aggregate_rejects_pc_id_group_without_fleet() {
4638        let m = manifest_with_aggregate(
4639            "aggregate:\n- { placement: { analytics: D }, title: T, kind: presence, agg: count, group_by: pc_id, render: bar }\n",
4640        );
4641        let err = m.validate().expect_err("pc_id grouping needs fleet");
4642        assert!(
4643            err.contains("pc_id is only valid with scope: fleet"),
4644            "err: {err}"
4645        );
4646    }
4647
4648    #[test]
4649    fn aggregate_rejects_transform_with_pc_id_group() {
4650        let m = manifest_with_aggregate(
4651            "aggregate:\n- { placement: { analytics: D }, title: T, scope: fleet, kind: web_visit, agg: count, group_by: pc_id, transform: host, render: bar }\n",
4652        );
4653        let err = m
4654            .validate()
4655            .expect_err("transform on pc_id grouping must fail");
4656        assert!(
4657            err.contains("transform is not valid with group_by: pc_id"),
4658            "err: {err}"
4659        );
4660    }
4661
4662    #[test]
4663    fn aggregate_rejects_timeline_without_bucket() {
4664        let m = manifest_with_aggregate(
4665            "aggregate:\n- { placement: { analytics: D }, title: T, kind: presence, agg: ratio, bool_path: active, render: timeline }\n",
4666        );
4667        let err = m.validate().expect_err("timeline needs a bucket");
4668        assert!(
4669            err.contains("render=timeline requires `time_bucket`"),
4670            "err: {err}"
4671        );
4672    }
4673
4674    #[test]
4675    fn aggregate_rejects_bucket_on_non_timeline() {
4676        let m = manifest_with_aggregate(
4677            "aggregate:\n- { placement: { analytics: D }, title: T, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: gauge }\n",
4678        );
4679        let err = m.validate().expect_err("bucket only on timeline");
4680        assert!(
4681            err.contains("time_bucket is only valid with render: timeline"),
4682            "err: {err}"
4683        );
4684    }
4685
4686    #[test]
4687    fn aggregate_rejects_unsafe_json_path() {
4688        // A path with characters outside [A-Za-z0-9_.] could break out of
4689        // the `'$.' || ?` bind — reject at create time.
4690        let m = manifest_with_aggregate(
4691            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, group_by: \"foo'; DROP\", render: bar }\n",
4692        );
4693        let err = m.validate().expect_err("unsafe path must fail");
4694        assert!(err.contains("dotted JSON path"), "err: {err}");
4695    }
4696
4697    #[test]
4698    fn aggregate_rejects_blank_title() {
4699        let m = manifest_with_aggregate(
4700            "aggregate:\n- { placement: { analytics: D }, title: \"  \", kind: k, agg: count, render: stat }\n",
4701        );
4702        let err = m.validate().expect_err("blank title must fail");
4703        assert!(err.contains("title must not be empty"), "err: {err}");
4704    }
4705
4706    #[test]
4707    fn aggregate_rejects_blank_kind() {
4708        let m = manifest_with_aggregate(
4709            "aggregate:\n- { placement: { analytics: D }, title: T, kind: \" \", agg: count, render: stat }\n",
4710        );
4711        let err = m.validate().expect_err("blank kind must fail");
4712        assert!(err.contains("kind must not be empty"), "err: {err}");
4713    }
4714
4715    #[test]
4716    fn aggregate_rejects_blank_source_when_set() {
4717        let m = manifest_with_aggregate(
4718            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, source: \"\", agg: count, render: stat }\n",
4719        );
4720        let err = m.validate().expect_err("blank source must fail");
4721        assert!(
4722            err.contains("source must not be empty when set"),
4723            "err: {err}"
4724        );
4725    }
4726
4727    #[test]
4728    fn aggregate_accepts_description_and_rejects_blank() {
4729        let ok = manifest_with_aggregate(
4730            "aggregate:\n- { placement: { analytics: D }, title: T, description: \"samples x 2 min\", kind: k, agg: count, render: stat }\n",
4731        );
4732        ok.validate()
4733            .expect("description is a valid optional field");
4734        assert_eq!(
4735            ok.aggregate.as_ref().unwrap()[0].description.as_deref(),
4736            Some("samples x 2 min")
4737        );
4738        let bad = manifest_with_aggregate(
4739            "aggregate:\n- { placement: { analytics: D }, title: T, description: \"  \", kind: k, agg: count, render: stat }\n",
4740        );
4741        let err = bad.validate().expect_err("blank description must fail");
4742        assert!(
4743            err.contains("description must not be empty when set"),
4744            "err: {err}"
4745        );
4746    }
4747
4748    #[test]
4749    fn aggregate_rejects_count_with_value_path() {
4750        let m = manifest_with_aggregate(
4751            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, value_path: bytes, render: stat }\n",
4752        );
4753        let err = m.validate().expect_err("count must not use value_path");
4754        assert!(
4755            err.contains("agg=count does not use `value_path`"),
4756            "err: {err}"
4757        );
4758    }
4759
4760    #[test]
4761    fn aggregate_rejects_ratio_with_value_path() {
4762        let m = manifest_with_aggregate(
4763            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: ratio, bool_path: active, value_path: bytes, render: gauge }\n",
4764        );
4765        let err = m.validate().expect_err("ratio must not use value_path");
4766        assert!(
4767            err.contains("agg=ratio does not use `value_path`"),
4768            "err: {err}"
4769        );
4770    }
4771
4772    #[test]
4773    fn aggregate_rejects_gauge_without_ratio() {
4774        let m = manifest_with_aggregate(
4775            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, group_by: app, render: gauge }\n",
4776        );
4777        let err = m.validate().expect_err("gauge needs ratio");
4778        assert!(
4779            err.contains("render=gauge is only valid with agg: ratio"),
4780            "err: {err}"
4781        );
4782    }
4783
4784    #[test]
4785    fn aggregate_rejects_limit_without_group_by() {
4786        let m = manifest_with_aggregate(
4787            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, limit: 5, render: stat }\n",
4788        );
4789        let err = m.validate().expect_err("limit needs group_by");
4790        assert!(err.contains("limit requires `group_by`"), "err: {err}");
4791    }
4792
4793    #[test]
4794    fn aggregate_rejects_exclude_without_group_by() {
4795        let m = manifest_with_aggregate(
4796            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, exclude: [x], render: stat }\n",
4797        );
4798        let err = m.validate().expect_err("exclude needs group_by");
4799        assert!(err.contains("exclude requires `group_by`"), "err: {err}");
4800    }
4801
4802    #[test]
4803    fn aggregate_rejects_zero_limit_and_zero_sample_minutes() {
4804        let m = manifest_with_aggregate(
4805            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, group_by: app, limit: 0, render: bar }\n",
4806        );
4807        assert!(m.validate().unwrap_err().contains("limit must be > 0"));
4808        let m = manifest_with_aggregate(
4809            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, group_by: app, sample_minutes: 0, render: bar }\n",
4810        );
4811        assert!(
4812            m.validate()
4813                .unwrap_err()
4814                .contains("sample_minutes must be > 0")
4815        );
4816    }
4817
4818    #[test]
4819    fn aggregate_rejects_empty_exclude_entry() {
4820        let m = manifest_with_aggregate(
4821            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, group_by: app, exclude: [\"  \"], render: bar }\n",
4822        );
4823        let err = m.validate().expect_err("blank exclude entry must fail");
4824        assert!(
4825            err.contains("exclude must not contain empty entries"),
4826            "err: {err}"
4827        );
4828    }
4829
4830    #[test]
4831    fn aggregate_rejects_malformed_dotted_paths() {
4832        for bad in [".foo", "foo.", "foo..bar", "."] {
4833            let m = manifest_with_aggregate(&format!(
4834                "aggregate:\n- {{ placement: {{ analytics: D }}, title: T, kind: k, agg: count, group_by: \"{bad}\", render: bar }}\n"
4835            ));
4836            let err = m.validate().expect_err("malformed path must fail");
4837            assert!(err.contains("dotted JSON path"), "path {bad}: {err}");
4838        }
4839    }
4840
4841    #[test]
4842    fn aggregate_rejects_unknown_enum_value() {
4843        // An unrecognised render string deserialises to the #492 Unknown
4844        // catch-all (so old readers don't choke); validate() rejects it as
4845        // a typo at create time.
4846        let m = manifest_with_aggregate(
4847            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, render: heatmap }\n",
4848        );
4849        let err = m.validate().expect_err("unknown render must fail");
4850        assert!(err.contains("render is not a known value"), "err: {err}");
4851    }
4852
4853    #[test]
4854    fn aggregate_accepts_order_field() {
4855        let m = manifest_with_aggregate(
4856            "aggregate:\n- { placement: { analytics: D }, title: T, order: -5, kind: k, agg: count, render: stat }\n",
4857        );
4858        m.validate().expect("order is a valid optional field");
4859        let w = &m.aggregate.as_ref().unwrap()[0];
4860        assert_eq!(w.order, Some(-5));
4861    }
4862
4863    // #1257 moved aggregate widgets onto the shared `placement:` block, so
4864    // `validate_placement` is now reachable from a second call site
4865    // (`validate_aggregate_widgets`). The SqlWidget side already covers the
4866    // rule; these pin it down where it is new, since a regression there
4867    // would be invisible to those tests.
4868
4869    #[test]
4870    fn aggregate_rejects_widget_that_surfaces_nowhere() {
4871        // No `analytics` tab and not pinned ⇒ the widget renders nowhere.
4872        // Before #1257 this was unrepresentable (`dashboard` was a required
4873        // String), so it's a genuinely new way to write a broken widget.
4874        let err = manifest_with_aggregate(
4875            "aggregate:\n- { placement: {}, title: T, kind: k, agg: count, render: stat }\n",
4876        )
4877        .validate()
4878        .expect_err("a widget with no surface must be rejected");
4879        assert!(err.contains("placement must set"), "err: {err}");
4880
4881        // `pin: false` is a block that pins nowhere — presence of the block
4882        // must not be mistaken for an actual surface.
4883        let err = manifest_with_aggregate(
4884            "aggregate:\n- { placement: { dashboard: { pin: false } }, title: T, kind: k, agg: count, render: stat }\n",
4885        )
4886        .validate()
4887        .expect_err("pin: false surfaces nowhere either");
4888        assert!(err.contains("placement must set"), "err: {err}");
4889    }
4890
4891    #[test]
4892    fn aggregate_accepts_dashboard_only_widget() {
4893        // The capability the refactor unlocks: an aggregate widget that is
4894        // pinned to the Dashboard without also claiming an Analytics tab.
4895        // `tab()` falls back to a label so the grouped widget list still has
4896        // a key to group under.
4897        let m = manifest_with_aggregate(
4898            "aggregate:\n- { placement: { dashboard: { pin: true } }, title: T, scope: fleet, kind: k, agg: count, render: stat }\n",
4899        );
4900        m.validate().expect("dashboard-only placement is valid");
4901        let p = &m.aggregate.as_ref().unwrap()[0].placement;
4902        assert!(p.is_pinned());
4903        assert!(p.analytics.is_none());
4904        assert_eq!(p.tab(), "Dashboard");
4905    }
4906
4907    #[test]
4908    fn analytics_placement_reads_both_shapes_and_serializes_terse() {
4909        // The scalar-or-block contract, and the one-way collapse back to
4910        // the terse form: a block that sets no width is stored as the bare
4911        // string, so resource JSON doesn't grow a wrapper for the ~all
4912        // widgets that never ask for a width.
4913        let bare = manifest_with_aggregate(
4914            "aggregate:\n- { placement: { analytics: Uptime }, title: T, kind: k, agg: count, render: stat }\n",
4915        );
4916        let block = manifest_with_aggregate(
4917            "aggregate:\n- { placement: { analytics: { tab: Uptime } }, title: T, kind: k, agg: count, render: stat }\n",
4918        );
4919        for m in [&bare, &block] {
4920            assert_eq!(m.aggregate.as_ref().unwrap()[0].placement.tab(), "Uptime");
4921        }
4922        let json = serde_json::to_string(&bare.aggregate.as_ref().unwrap()[0].placement)
4923            .expect("serialize placement");
4924        assert!(json.contains(r#""analytics":"Uptime""#), "json: {json}");
4925
4926        // With a width it has to keep the block form, or the width is lost.
4927        let wide = manifest_with_aggregate(
4928            "aggregate:\n- { placement: { analytics: { tab: Uptime, width: half } }, title: T, kind: k, agg: count, render: stat }\n",
4929        );
4930        let p = &wide.aggregate.as_ref().unwrap()[0].placement;
4931        assert_eq!(p.width_for(false), Some(WidgetWidth::Half));
4932        // …and the Dashboard surface is untouched by an Analytics width.
4933        assert_eq!(p.width_for(true), None);
4934        let json = serde_json::to_string(p).expect("serialize placement");
4935        assert!(json.contains(r#""tab":"Uptime""#), "json: {json}");
4936        assert!(json.contains(r#""width":"half""#), "json: {json}");
4937    }
4938
4939    #[test]
4940    fn aggregate_accepts_minimal_op_timeline() {
4941        // op_timeline needs no kind/agg — it reconstructs a fixed multi-kind
4942        // swimlane. A bare per-PC spec is valid, and `kind`/`agg` stay None.
4943        let m = manifest_with_aggregate(
4944            "aggregate:\n- { placement: { analytics: Uptime }, title: Operational state, scope: pc, render: op_timeline }\n",
4945        );
4946        m.validate().expect("minimal op_timeline is valid");
4947        let w = &m.aggregate.as_ref().unwrap()[0];
4948        assert_eq!(w.render, AggregateRender::OpTimeline);
4949        assert!(w.kind.is_none());
4950        assert!(w.agg.is_none());
4951    }
4952
4953    #[test]
4954    fn aggregate_rejects_op_timeline_with_fleet_scope() {
4955        let m = manifest_with_aggregate(
4956            "aggregate:\n- { placement: { analytics: Uptime }, title: T, scope: fleet, render: op_timeline }\n",
4957        );
4958        let err = m.validate().expect_err("op_timeline must be per-PC");
4959        assert!(
4960            err.contains("render=op_timeline requires scope: pc"),
4961            "err: {err}"
4962        );
4963    }
4964
4965    #[test]
4966    fn aggregate_rejects_op_timeline_with_aggregation_fields() {
4967        // Each aggregation knob the operator might paste in is rejected
4968        // (rather than silently ignored), pointing at the field to delete.
4969        for (block, field) in [
4970            ("kind: boot", "kind"),
4971            ("agg: count", "agg"),
4972            ("source: winlog:Security", "source"),
4973            ("group_by: pc_id", "group_by"),
4974            ("bool_path: active", "bool_path"),
4975            ("time_bucket: hour", "time_bucket"),
4976            ("limit: 5", "limit"),
4977        ] {
4978            let m = manifest_with_aggregate(&format!(
4979                "aggregate:\n- {{ placement: {{ analytics: Uptime }}, title: T, scope: pc, {block}, render: op_timeline }}\n"
4980            ));
4981            let err = m
4982                .validate()
4983                .expect_err(&format!("op_timeline must reject {field}"));
4984            assert!(
4985                err.contains(&format!("render=op_timeline does not use `{field}`")),
4986                "field {field}: {err}"
4987            );
4988        }
4989    }
4990
4991    // ── #743 View resource ───────────────────────────────────────────
4992    fn view_from(yaml_body: &str) -> View {
4993        serde_yaml::from_str(&format!("id: v1\n{yaml_body}")).expect("parse view")
4994    }
4995
4996    #[test]
4997    fn view_accepts_valid_widgets() {
4998        let v = view_from(
4999            "widgets:\n\
5000             - { placement: { analytics: Reliability }, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
5001             - { placement: { analytics: Reliability }, title: Total, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
5002        );
5003        v.validate().expect("valid view");
5004    }
5005
5006    #[test]
5007    fn view_rejects_empty_widgets() {
5008        let v = view_from("widgets: []\n");
5009        let err = v.validate().expect_err("empty widgets must fail");
5010        assert!(err.contains("at least one widget"), "err: {err}");
5011    }
5012
5013    #[test]
5014    fn view_rejects_blank_id() {
5015        let v: View = serde_yaml::from_str(
5016            "id: \"  \"\nwidgets:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, render: stat }\n",
5017        )
5018        .expect("parse");
5019        let err = v.validate().expect_err("blank id must fail");
5020        assert!(err.contains("view.id must"), "err: {err}");
5021    }
5022
5023    #[test]
5024    fn view_rejects_unsafe_id() {
5025        // A `/` or `..` in the id would break the KV key and the
5026        // `/api/views/{id}` URL segment — reject at create time.
5027        for bad in ["../etc", "a/b", "has space", "x;y"] {
5028            let v: View = serde_yaml::from_str(&format!(
5029                "id: \"{bad}\"\nwidgets:\n- {{ placement: {{ analytics: D }}, title: T, kind: k, agg: count, render: stat }}\n",
5030            ))
5031            .expect("parse");
5032            let err = v.validate().expect_err("unsafe id must fail");
5033            assert!(err.contains("[A-Za-z0-9._-]"), "id {bad}: {err}");
5034        }
5035        assert!(is_valid_resource_id("dashboards-fleet.v1_2"));
5036    }
5037
5038    #[test]
5039    fn view_rejects_untrimmed_id() {
5040        // A padded id validated-as-trimmed but stored-raw would be a KV key
5041        // (and `/api/views/{id}` segment) nothing matches — reject it outright
5042        // (the id is used verbatim).
5043        let v: View = serde_yaml::from_str(
5044            "id: \" my-view \"\nwidgets:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, render: stat }\n",
5045        )
5046        .expect("parse");
5047        let err = v.validate().expect_err("padded id must fail");
5048        assert!(err.contains("view.id must"), "err: {err}");
5049    }
5050
5051    #[test]
5052    fn view_reuses_shared_widget_validation() {
5053        // The same per-widget rule the job hint enforces (ratio needs
5054        // bool_path), reported under the `widgets[..]` field.
5055        let v = view_from(
5056            "widgets:\n- { placement: { analytics: D }, title: T, kind: presence, agg: ratio, render: gauge }\n",
5057        );
5058        let err = v.validate().expect_err("ratio without bool_path must fail");
5059        assert!(
5060            err.contains("widgets[0].agg=ratio requires `bool_path`"),
5061            "err: {err}"
5062        );
5063    }
5064
5065    // ── #vuln-roadmap PR3 SQL-backed views ───────────────────────────
5066    #[test]
5067    fn view_accepts_pure_sql_widgets() {
5068        // A view with only sql_widgets (no obs_events aggregate widgets) is
5069        // valid — the vulnerability-dashboard shape.
5070        let v = view_from(
5071            "sql_widgets:
5072  - title: KEV-affected hosts
5073    query: \"SELECT pc_id, 1 AS cves FROM inventory_sw_apps\"
5074    refresh: 6h
5075    render: { kind: table, columns: [pc_id, cves], labels: { cves: CVE count } }
5076    placement: { analytics: Security, dashboard: { pin: true } }
5077",
5078        );
5079        v.validate().expect("valid sql view");
5080        // refresh parses; pin/tab helpers read the placement.
5081        let w = &v.sql_widgets[0];
5082        assert_eq!(
5083            w.refresh_interval(),
5084            std::time::Duration::from_secs(6 * 3600)
5085        );
5086        assert!(w.placement.is_pinned());
5087        assert_eq!(w.placement.tab(), "Security");
5088    }
5089
5090    #[test]
5091    fn sql_widget_defaults_and_mix() {
5092        // No refresh ⇒ default; a view can mix aggregate + sql widgets.
5093        let v = view_from(
5094            "widgets:
5095  - { placement: { analytics: D }, title: T, kind: k, agg: count, render: stat }
5096sql_widgets:
5097  - title: N affected
5098    query: \"SELECT count(*) AS n FROM feeds\"
5099    render: { kind: stat, value: n }
5100    placement: { dashboard: { pin: true } }
5101",
5102        );
5103        v.validate().expect("mixed view is valid");
5104        assert_eq!(v.sql_widgets[0].refresh_interval(), DEFAULT_VIEW_REFRESH);
5105        // dashboard-only placement (no analytics tab) falls back to a label.
5106        assert_eq!(v.sql_widgets[0].placement.tab(), "Dashboard");
5107    }
5108
5109    #[test]
5110    fn sql_widget_validation_rules() {
5111        // helper: build a view with one sql_widget from an inline render+placement
5112        let mk = |render: &str, placement: &str| -> Result<(), String> {
5113            view_from(&format!(
5114                "sql_widgets:
5115  - title: W
5116    query: \"SELECT 1 AS a\"
5117    render: {render}
5118    placement: {placement}
5119"
5120            ))
5121            .validate()
5122        };
5123        // bar needs label + value
5124        let err = mk("{ kind: bar, value: a }", "{ analytics: T }").unwrap_err();
5125        assert!(
5126            err.contains("render.label is required for kind=bar"),
5127            "err: {err}"
5128        );
5129        // pie needs value
5130        let err = mk("{ kind: pie, label: a }", "{ analytics: T }").unwrap_err();
5131        assert!(
5132            err.contains("render.value is required for kind=pie"),
5133            "err: {err}"
5134        );
5135        // stat needs value
5136        let err = mk("{ kind: stat }", "{ analytics: T }").unwrap_err();
5137        assert!(
5138            err.contains("render.value is required for kind=stat"),
5139            "err: {err}"
5140        );
5141        // gauge needs value XOR num+den
5142        let err = mk("{ kind: gauge, num: a }", "{ analytics: T }").unwrap_err();
5143        assert!(err.contains("needs either `value`"), "err: {err}");
5144        mk("{ kind: gauge, value: a }", "{ analytics: T }").expect("gauge value ok");
5145        mk("{ kind: gauge, num: a, den: a }", "{ analytics: T }").expect("gauge num/den ok");
5146        // unknown kind rejected
5147        let err = mk("{ kind: sunburst }", "{ analytics: T }").unwrap_err();
5148        assert!(
5149            err.contains("render.kind is not a known value"),
5150            "err: {err}"
5151        );
5152        // placement must surface somewhere
5153        let err = mk("{ kind: table }", "{}").unwrap_err();
5154        assert!(err.contains("placement must set"), "err: {err}");
5155        // a `dashboard: { pin: false }` block still surfaces nowhere.
5156        let err = mk("{ kind: table }", "{ dashboard: { pin: false } }").unwrap_err();
5157        assert!(err.contains("placement must set"), "err: {err}");
5158        mk("{ kind: table }", "{ dashboard: { pin: true } }").expect("pinned dashboard ok");
5159        // limit: 0 on a bar/pie is an invisible widget — rejected.
5160        let err = mk(
5161            "{ kind: bar, label: a, value: a, limit: 0 }",
5162            "{ analytics: T }",
5163        )
5164        .unwrap_err();
5165        assert!(err.contains("limit must be >= 1"), "err: {err}");
5166        // bad refresh duration rejected
5167        let err = view_from(
5168            "sql_widgets:
5169  - { title: W, query: \"SELECT 1\", refresh: \"6 sidereal days\", render: { kind: table }, placement: { analytics: T } }
5170",
5171        )
5172        .validate()
5173        .unwrap_err();
5174        assert!(
5175            err.contains("refresh") && err.contains("not a valid duration"),
5176            "err: {err}"
5177        );
5178        // table is fine with no channels
5179        mk("{ kind: table }", "{ analytics: T }").expect("bare table ok");
5180    }
5181
5182    #[test]
5183    fn rewrite_pc_id_param_is_literal_and_boundary_aware() {
5184        // A real param outside any literal is rewritten + counted.
5185        let (sql, n) = rewrite_pc_id_param("SELECT * FROM t WHERE pc_id = :pc_id");
5186        assert_eq!(n, 1);
5187        assert!(sql.ends_with("pc_id = ?"), "sql: {sql}");
5188        // Appearing twice → two `?`, count 2 (one bind each — the caller binds
5189        // pc_id per occurrence since sqlx-sqlite has no named params).
5190        let (sql, n) = rewrite_pc_id_param("WHERE a = :pc_id AND (:pc_id IS NOT NULL)");
5191        assert_eq!(n, 2);
5192        assert_eq!(sql, "WHERE a = ? AND (? IS NOT NULL)");
5193        // Inside a string literal → copied verbatim, NOT counted (would else be
5194        // a bind-count mismatch → SQLITE_RANGE, and misclassify scope).
5195        let (sql, n) = rewrite_pc_id_param("SELECT 'see :pc_id docs' AS hint");
5196        assert_eq!(n, 0);
5197        assert_eq!(sql, "SELECT 'see :pc_id docs' AS hint");
5198        // Inside a comment → left alone.
5199        let (_, n) = rewrite_pc_id_param("SELECT 1 -- filter by :pc_id\n");
5200        assert_eq!(n, 0);
5201        // A longer identifier prefix (`:pc_idx`) is not our token.
5202        let (sql, n) = rewrite_pc_id_param("WHERE x = :pc_idx");
5203        assert_eq!(n, 0);
5204        assert_eq!(sql, "WHERE x = :pc_idx");
5205    }
5206
5207    #[test]
5208    fn validate_rejects_pinned_per_pc_widget() {
5209        // A per-PC widget (binds :pc_id) that also pins to the Dashboard is a
5210        // create-time contradiction (Dashboard is fleet-scope) — rejected.
5211        let err = view_from(
5212            "sql_widgets:
5213  - title: W
5214    query: \"SELECT count(*) AS n FROM inventory_sw_apps WHERE pc_id = :pc_id\"
5215    render: { kind: stat, value: n }
5216    placement: { analytics: Security, dashboard: { pin: true } }
5217",
5218        )
5219        .validate()
5220        .unwrap_err();
5221        assert!(err.contains("per-PC widget"), "err: {err}");
5222        // The same widget WITHOUT the pin is fine (per-PC, analytics only).
5223        view_from(
5224            "sql_widgets:
5225  - title: W
5226    query: \"SELECT count(*) AS n FROM inventory_sw_apps WHERE pc_id = :pc_id\"
5227    render: { kind: stat, value: n }
5228    placement: { analytics: Security }
5229",
5230        )
5231        .validate()
5232        .expect("per-PC analytics-only widget is valid");
5233    }
5234
5235    fn execute_with(
5236        script: Option<&str>,
5237        script_file: Option<&str>,
5238        script_object: Option<&str>,
5239    ) -> Execute {
5240        Execute {
5241            bypass_local_limit: false,
5242            shell: ExecuteShell::Powershell,
5243            script: script.map(str::to_owned),
5244            script_file: script_file.map(str::to_owned),
5245            script_object: script_object.map(str::to_owned),
5246            timeout: "30s".into(),
5247            run_as: RunAs::default(),
5248            cwd: None,
5249        }
5250    }
5251
5252    #[test]
5253    fn validate_accepts_inline_script() {
5254        let e = execute_with(Some("echo hi"), None, None);
5255        assert!(e.validate_script_source().is_ok());
5256    }
5257
5258    #[test]
5259    fn validate_accepts_script_file_alone() {
5260        let e = execute_with(None, Some("scripts/cleanup.ps1"), None);
5261        assert!(e.validate_script_source().is_ok());
5262    }
5263
5264    #[test]
5265    fn validate_accepts_script_object_alone() {
5266        let e = execute_with(None, None, Some("cleanup/1.0.0"));
5267        assert!(e.validate_script_source().is_ok());
5268    }
5269
5270    #[test]
5271    fn validate_treats_empty_inline_script_as_unset() {
5272        // `script: ""` + `script_object` set is the natural shape
5273        // when an operator comments out the YAML block-scalar body
5274        // but leaves the key. Should pass.
5275        let e = execute_with(Some(""), None, Some("cleanup/1.0.0"));
5276        assert!(e.validate_script_source().is_ok());
5277    }
5278
5279    #[test]
5280    fn validate_rejects_zero_sources() {
5281        let e = execute_with(None, None, None);
5282        let err = e.validate_script_source().unwrap_err();
5283        assert!(err.contains("must be set"), "got: {err}");
5284    }
5285
5286    #[test]
5287    fn validate_rejects_empty_inline_only() {
5288        let e = execute_with(Some(""), None, None);
5289        let err = e.validate_script_source().unwrap_err();
5290        assert!(err.contains("must be set"), "got: {err}");
5291    }
5292
5293    #[test]
5294    fn validate_rejects_inline_plus_file() {
5295        let e = execute_with(Some("echo hi"), Some("scripts/cleanup.ps1"), None);
5296        let err = e.validate_script_source().unwrap_err();
5297        assert!(err.contains("only one of"), "got: {err}");
5298    }
5299
5300    #[test]
5301    fn validate_rejects_inline_plus_object() {
5302        let e = execute_with(Some("echo hi"), None, Some("cleanup/1.0.0"));
5303        let err = e.validate_script_source().unwrap_err();
5304        assert!(err.contains("only one of"), "got: {err}");
5305    }
5306
5307    #[test]
5308    fn validate_rejects_file_plus_object() {
5309        let e = execute_with(None, Some("scripts/cleanup.ps1"), Some("cleanup/1.0.0"));
5310        let err = e.validate_script_source().unwrap_err();
5311        assert!(err.contains("only one of"), "got: {err}");
5312    }
5313
5314    #[test]
5315    fn validate_rejects_all_three() {
5316        let e = execute_with(
5317            Some("echo hi"),
5318            Some("scripts/cleanup.ps1"),
5319            Some("cleanup/1.0.0"),
5320        );
5321        let err = e.validate_script_source().unwrap_err();
5322        assert!(err.contains("only one of"), "got: {err}");
5323    }
5324
5325    #[test]
5326    fn validate_rejects_blank_script_file() {
5327        // #918: a blank `script_file` used to count as "set" and pass
5328        // the exactly-one check, then fail at use time (the CLI reads
5329        // a file named "").
5330        for blank in ["", "   "] {
5331            let e = execute_with(None, Some(blank), None);
5332            let err = e.validate_script_source().unwrap_err();
5333            assert!(err.contains("script_file must not be blank"), "got: {err}");
5334        }
5335    }
5336
5337    #[test]
5338    fn validate_rejects_blank_script_object() {
5339        // #918: same for a blank `script_object` (would 404 every exec).
5340        for blank in ["", "   "] {
5341            let e = execute_with(None, None, Some(blank));
5342            let err = e.validate_script_source().unwrap_err();
5343            assert!(
5344                err.contains("script_object must not be blank"),
5345                "got: {err}"
5346            );
5347        }
5348    }
5349
5350    #[test]
5351    fn validate_treats_whitespace_inline_script_as_unset() {
5352        // #918: a whitespace-only inline body is a commented-out block,
5353        // not a real script — with no other source it's "zero sources".
5354        let e = execute_with(Some("   \n  "), None, None);
5355        let err = e.validate_script_source().unwrap_err();
5356        assert!(err.contains("must be set"), "got: {err}");
5357    }
5358
5359    #[test]
5360    fn validate_rejects_malformed_script_object_ref() {
5361        // #918: the ref must be `<name>/<version>`; a missing slash,
5362        // extra slash, blank half, or whitespace-padded half (the last
5363        // survives a JSON POST body and 404s at exec — gemini/claude
5364        // #943) can never resolve.
5365        for bad in [
5366            "no-slash", "a/b/c", "/1.0.0", "cleanup/", " / ", "foo/bar ", " foo/bar", "foo /bar",
5367        ] {
5368            let e = execute_with(None, None, Some(bad));
5369            let err = e.validate_script_source().unwrap_err();
5370            assert!(
5371                err.contains("must be `<name>/<version>`"),
5372                "for '{bad}', got: {err}"
5373            );
5374        }
5375    }
5376
5377    #[test]
5378    fn manifest_deserialises_script_object_yaml() {
5379        // SPEC §2.4.1 example shape with the Object Store
5380        // reference picked over inline.
5381        let yaml = r#"
5382id: cleanup-disk-temp
5383version: 1.0.1
5384execute:
5385  shell: powershell
5386  script_object: cleanup-disk-temp/1.0.1
5387  timeout: 600s
5388"#;
5389        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
5390        assert_eq!(
5391            m.execute.script_object.as_deref(),
5392            Some("cleanup-disk-temp/1.0.1")
5393        );
5394        assert!(m.execute.script.is_none());
5395        m.validate()
5396            .expect("script_object-only manifest passes validation");
5397    }
5398
5399    #[test]
5400    fn manifest_rejects_typo_in_script_field_name() {
5401        // #492: the strict create boundary catches `script_objectt`
5402        // and similar fat-fingers (with the full path) instead of
5403        // letting them silently fall through to "all three unset".
5404        let yaml = r#"
5405id: typo
5406version: 1.0.0
5407execute:
5408  shell: powershell
5409  script_objectt: oops
5410  timeout: 30s
5411"#;
5412        let err = crate::strict::from_yaml_str::<Manifest>(yaml)
5413            .expect_err("typo'd execute field must be rejected at the write boundary");
5414        assert!(err.contains("execute.script_objectt"), "{err}");
5415    }
5416
5417    #[test]
5418    fn schedule_carries_target_and_rollout() {
5419        let yaml = r#"
5420id: hourly-cleanup-canary
5421when:
5422  per_pc: { every: 1h }
5423job_id: cleanup
5424enabled: true
5425target:
5426  groups: [canary, wave1]
5427jitter: 30s
5428rollout:
5429  strategy: wave
5430  waves:
5431    - { group: canary, delay: 0s }
5432    - { group: wave1,  delay: 5s }
5433"#;
5434        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5435        assert_eq!(s.id, "hourly-cleanup-canary");
5436        assert_eq!(s.job_id, "cleanup");
5437        assert_eq!(s.plan.target.groups, vec!["canary", "wave1"]);
5438        assert_eq!(s.plan.jitter.as_deref(), Some("30s"));
5439        let rollout = s.plan.rollout.expect("rollout present");
5440        assert_eq!(rollout.waves.len(), 2);
5441        assert_eq!(rollout.waves[0].group, "canary");
5442        assert_eq!(rollout.waves[1].delay, "5s");
5443        assert_eq!(rollout.strategy, RolloutStrategy::Wave);
5444    }
5445
5446    #[test]
5447    fn schedule_minimal_target_all() {
5448        let yaml = r#"
5449id: kitting
5450when:
5451  per_pc: once
5452enabled: true
5453job_id: scheduled-echo
5454target: { all: true }
5455"#;
5456        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5457        assert_eq!(s.id, "kitting");
5458        assert_eq!(s.when, When::PerPc(PerPolicy::Once(OnceLiteral::Once)));
5459        assert!(s.enabled);
5460        assert_eq!(s.job_id, "scheduled-echo");
5461        assert!(s.plan.target.all);
5462        assert!(s.plan.rollout.is_none());
5463        assert!(s.plan.jitter.is_none());
5464        assert!(s.active.is_empty());
5465    }
5466
5467    #[test]
5468    fn schedule_enabled_defaults_to_true() {
5469        let yaml = r#"
5470id: x
5471when:
5472  per_pc: once
5473job_id: y
5474target: { all: true }
5475"#;
5476        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5477        assert!(s.enabled);
5478    }
5479
5480    fn once_per_version_yaml(runs_on: &str, per: &str) -> String {
5481        format!(
5482            "id: x\nwhen:\n  {per}\njob_id: install-kanade-client\n\
5483             target: {{ groups: [dejisen] }}\nruns_on: {runs_on}\n"
5484        )
5485    }
5486
5487    #[test]
5488    fn per_pc_once_per_version_parses() {
5489        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5490            "backend",
5491            "per_pc: once_per_version",
5492        ))
5493        .expect("parse");
5494        assert_eq!(
5495            s.when,
5496            When::PerPc(PerPolicy::OncePerVersion(
5497                OncePerVersionLiteral::OncePerVersion
5498            ))
5499        );
5500    }
5501
5502    #[test]
5503    fn per_pc_once_per_version_lowers_to_version_mode_no_cooldown() {
5504        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5505            "backend",
5506            "per_pc: once_per_version",
5507        ))
5508        .expect("parse");
5509        let l = s.lowered();
5510        assert_eq!(l.mode, ExecMode::OncePerPcVersion);
5511        assert_eq!(l.cooldown, None, "version re-arm is not a cooldown");
5512    }
5513
5514    #[test]
5515    fn once_per_version_displays_and_serialises() {
5516        let w = When::PerPc(PerPolicy::OncePerVersion(
5517            OncePerVersionLiteral::OncePerVersion,
5518        ));
5519        assert_eq!(w.to_string(), "per_pc once_per_version");
5520        // serde round-trips through the ergonomic bare string.
5521        let json = serde_json::to_value(&w).unwrap();
5522        assert_eq!(json, serde_json::json!({ "per_pc": "once_per_version" }));
5523    }
5524
5525    #[test]
5526    fn once_per_version_rejects_typo() {
5527        // The distinct literal still catches typos (no free-form String).
5528        let r: Result<Schedule, _> = serde_yaml::from_str(&once_per_version_yaml(
5529            "backend",
5530            "per_pc: once_per_verison",
5531        ));
5532        assert!(r.is_err(), "typo should not parse");
5533    }
5534
5535    #[test]
5536    fn validate_accepts_once_per_version_on_backend() {
5537        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5538            "backend",
5539            "per_pc: once_per_version",
5540        ))
5541        .expect("parse");
5542        assert!(s.validate().is_ok(), "got: {:?}", s.validate());
5543    }
5544
5545    #[test]
5546    fn validate_rejects_once_per_version_on_agent() {
5547        let s: Schedule =
5548            serde_yaml::from_str(&once_per_version_yaml("agent", "per_pc: once_per_version"))
5549                .expect("parse");
5550        let err = s
5551            .validate()
5552            .expect_err("agent + once_per_version must be rejected");
5553        assert!(err.contains("once_per_version"), "got: {err}");
5554        assert!(err.contains("backend"), "got: {err}");
5555    }
5556
5557    #[test]
5558    fn validate_rejects_once_per_version_on_per_target() {
5559        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5560            "backend",
5561            "per_target: once_per_version",
5562        ))
5563        .expect("parse");
5564        let err = s
5565            .validate()
5566            .expect_err("per_target + once_per_version must be rejected");
5567        assert!(err.contains("once_per_version"), "got: {err}");
5568        assert!(err.contains("per_pc"), "got: {err}");
5569    }
5570
5571    #[test]
5572    fn schedule_tags_default_empty_and_skip_serialise() {
5573        let yaml = r#"
5574id: x
5575when:
5576  per_pc: once
5577job_id: y
5578target: { all: true }
5579"#;
5580        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5581        assert!(s.tags.is_empty());
5582        s.validate().expect("tag-less schedule validates");
5583        let json = serde_json::to_string(&s).expect("serialize");
5584        assert!(
5585            !json.contains("tags"),
5586            "empty tags must not serialise: {json}"
5587        );
5588    }
5589
5590    #[test]
5591    fn schedule_parses_and_validates_tags() {
5592        let yaml = r#"
5593id: weekly-cleanup
5594when:
5595  per_pc: { every: 1h }
5596job_id: cleanup
5597target: { all: true }
5598tags: [weekly, maintenance]
5599"#;
5600        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5601        assert_eq!(s.tags, vec!["weekly", "maintenance"]);
5602        s.validate().expect("tagged schedule validates");
5603    }
5604
5605    #[test]
5606    fn schedule_rejects_blank_tag() {
5607        let yaml = r#"
5608id: x
5609when:
5610  per_pc: once
5611job_id: y
5612target: { all: true }
5613tags: [ok, "  "]
5614"#;
5615        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5616        let err = s.validate().expect_err("blank tag must fail");
5617        assert!(err.contains("tags must not contain empty"), "err: {err}");
5618    }
5619
5620    // ---- `when` parsing (#418 Phase 1) ----
5621
5622    fn schedule_yaml_with(when_block: &str) -> String {
5623        format!(
5624            r#"
5625id: x
5626when:
5627{when_block}
5628job_id: y
5629target: {{ all: true }}
5630"#
5631        )
5632    }
5633
5634    #[test]
5635    fn when_per_pc_every_parses_unquoted_humantime() {
5636        // `6h` is digit-led but non-numeric → YAML string, same as
5637        // the old `cooldown: 6h` convention. No quotes needed.
5638        let s: Schedule =
5639            serde_yaml::from_str(&schedule_yaml_with("  per_pc: { every: 6h }")).expect("parse");
5640        assert_eq!(
5641            s.when,
5642            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() }))
5643        );
5644    }
5645
5646    #[test]
5647    fn when_per_target_every_parses() {
5648        let s: Schedule = serde_yaml::from_str(&schedule_yaml_with("  per_target: { every: 24h }"))
5649            .expect("parse");
5650        assert_eq!(
5651            s.when,
5652            When::PerTarget(PerPolicy::Every(EverySpec {
5653                every: "24h".into()
5654            }))
5655        );
5656    }
5657
5658    #[test]
5659    fn when_per_target_once_parses() {
5660        // Falls out of the shared PerPolicy shape and decide_fire
5661        // already implements it ("any one pc succeeds → skip the
5662        // target forever"), so it is allowed, not rejected.
5663        let s: Schedule =
5664            serde_yaml::from_str(&schedule_yaml_with("  per_target: once")).expect("parse");
5665        assert_eq!(s.when, When::PerTarget(PerPolicy::Once(OnceLiteral::Once)));
5666    }
5667
5668    #[test]
5669    fn when_calendar_time_parses() {
5670        let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(
5671            "  calendar:\n    at: \"09:00\"\n    days: [mon-fri]",
5672        ))
5673        .expect("parse");
5674        match &s.when {
5675            When::Calendar(c) => {
5676                assert_eq!(c.at, "09:00");
5677                assert_eq!(c.days, vec!["mon-fri"]);
5678            }
5679            other => panic!("expected calendar, got {other:?}"),
5680        }
5681    }
5682
5683    #[test]
5684    fn when_calendar_days_default_empty() {
5685        let s: Schedule =
5686            serde_yaml::from_str(&schedule_yaml_with("  calendar:\n    at: \"09:00\""))
5687                .expect("parse");
5688        match &s.when {
5689            When::Calendar(c) => assert!(c.days.is_empty(), "days defaults to empty (= daily)"),
5690            other => panic!("expected calendar, got {other:?}"),
5691        }
5692    }
5693
5694    #[test]
5695    fn when_calendar_datetime_parses_all_separators() {
5696        // one-shot: date+time in hyphen / ISO-T / slash forms
5697        for at in ["2026-06-10 09:00", "2026-06-10T09:00", "2026/06/10 09:00"] {
5698            let block = format!("  calendar:\n    at: \"{at}\"");
5699            let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(&block))
5700                .unwrap_or_else(|e| panic!("parse '{at}': {e}"));
5701            match &s.when {
5702                When::Calendar(c) => {
5703                    use chrono::Datelike;
5704                    let p = c.parse_at().expect("parse_at");
5705                    let d = p.date.expect("datetime at carries a date");
5706                    assert_eq!((d.year(), d.month(), d.day()), (2026, 6, 10), "for '{at}'");
5707                }
5708                other => panic!("expected calendar, got {other:?}"),
5709            }
5710        }
5711    }
5712
5713    #[test]
5714    fn when_rejects_bad_once_keyword() {
5715        // `onec` must be a parse error, not a silently-absorbed
5716        // string (OnceLiteral is a single-variant enum for exactly
5717        // this reason).
5718        let r: Result<Schedule, _> = serde_yaml::from_str(&schedule_yaml_with("  per_pc: onec"));
5719        assert!(r.is_err(), "expected parse error, got {r:?}");
5720    }
5721
5722    #[test]
5723    fn when_rejects_unknown_key_in_every() {
5724        // `{ evry: 6h }` still fails on the tolerant read path: the
5725        // required `every` key is missing, so no PerPolicy variant
5726        // matches (#492 removed deny_unknown_fields, but required
5727        // keys keep the untagged disambiguation honest).
5728        let r: Result<Schedule, _> =
5729            serde_yaml::from_str(&schedule_yaml_with("  per_pc: { evry: 6h }"));
5730        assert!(r.is_err(), "expected parse error, got {r:?}");
5731    }
5732
5733    #[test]
5734    fn when_rejects_unknown_variant() {
5735        let r: Result<Schedule, _> =
5736            serde_yaml::from_str(&schedule_yaml_with("  per_galaxy: once"));
5737        assert!(r.is_err(), "expected parse error, got {r:?}");
5738    }
5739
5740    #[test]
5741    fn when_rejects_old_top_level_cron_field() {
5742        // Pre-#418 shape: top-level `cron:` + no `when:`. Must fail
5743        // loudly (missing `when`), which is what turns stale KV
5744        // blobs into warn-skips after the upgrade.
5745        let yaml = r#"
5746id: x
5747cron: "* * * * * *"
5748job_id: y
5749target: { all: true }
5750"#;
5751        let r: Result<Schedule, _> = serde_yaml::from_str(yaml);
5752        assert!(r.is_err(), "expected parse error, got {r:?}");
5753    }
5754
5755    #[test]
5756    fn when_rejects_retired_cron_escape_hatch() {
5757        // #418 Phase 2 retired `when: { cron: "..." }`. A raw cron
5758        // is now an unknown variant → parse error (operators use the
5759        // calendar form instead).
5760        let r: Result<Schedule, _> =
5761            serde_yaml::from_str(&schedule_yaml_with("  cron: \"0 0 9 * * mon-fri\""));
5762        assert!(
5763            r.is_err(),
5764            "expected parse error for retired cron, got {r:?}"
5765        );
5766    }
5767
5768    #[test]
5769    fn when_round_trips_json_and_yaml() {
5770        // Round-trip through the full Schedule: that is the wire
5771        // unit for both stores (JSON catalog KV + YAML mirror), and
5772        // it exercises the singleton_map field attribute that keeps
5773        // serde_yaml on the map shape instead of `!per_pc` tags.
5774        for when in [
5775            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5776            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5777            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5778            When::PerTarget(PerPolicy::Every(EverySpec {
5779                every: "24h".into(),
5780            })),
5781            calendar("09:00", &["mon-fri"]),
5782            calendar("2026-06-10 09:00", &[]),
5783            When::On(vec![OnTrigger::Startup]),
5784            When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
5785            When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
5786            When::On(vec![OnTrigger::NetworkChange]),
5787        ] {
5788            // Event triggers are agent-only; the rest validate on backend.
5789            let runs_on = if matches!(when, When::On(_)) {
5790                RunsOn::Agent
5791            } else {
5792                RunsOn::Backend
5793            };
5794            let s = schedule_with(when.clone(), runs_on);
5795
5796            let json = serde_json::to_string(&s).expect("json serialise");
5797            let back: Schedule = serde_json::from_str(&json).expect("json deserialise");
5798            assert_eq!(back.when, when, "json round-trip for {when}");
5799
5800            let yaml = serde_yaml::to_string(&s).expect("yaml serialise");
5801            assert!(
5802                !yaml.contains('!'),
5803                "yaml must use the map shape, not tags: {yaml}"
5804            );
5805            let back: Schedule = serde_yaml::from_str(&yaml).expect("yaml deserialise");
5806            assert_eq!(back.when, when, "yaml round-trip for {when}");
5807        }
5808    }
5809
5810    #[test]
5811    fn when_once_serialises_as_bare_keyword() {
5812        // The wire shape operators see in the YAML mirror must stay
5813        // the ergonomic `per_pc: once`, not a one-variant map.
5814        let json = serde_json::to_value(When::PerPc(PerPolicy::Once(OnceLiteral::Once)))
5815            .expect("serialise");
5816        assert_eq!(json, serde_json::json!({ "per_pc": "once" }));
5817    }
5818
5819    #[test]
5820    fn when_displays_operator_summary() {
5821        for (when, expected) in [
5822            (
5823                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5824                "per_pc once",
5825            ),
5826            (
5827                When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5828                "per_pc every 6h",
5829            ),
5830            (
5831                When::PerTarget(PerPolicy::Every(EverySpec {
5832                    every: "24h".into(),
5833                })),
5834                "per_target every 24h",
5835            ),
5836            (calendar("09:00", &["mon-fri"]), "at 09:00 [mon-fri]"),
5837            (calendar("2026-06-10 09:00", &[]), "at 2026-06-10 09:00"),
5838            (When::On(vec![OnTrigger::Startup]), "on [startup]"),
5839            (
5840                When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
5841                "on [startup,logon]",
5842            ),
5843            (
5844                When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
5845                "on [lock,unlock]",
5846            ),
5847            (
5848                When::On(vec![OnTrigger::NetworkChange]),
5849                "on [network_change]",
5850            ),
5851        ] {
5852            assert_eq!(when.to_string(), expected);
5853        }
5854    }
5855
5856    // ---- lowering (#418: when → engine vocabulary) ----
5857
5858    fn schedule_with(when: When, runs_on: RunsOn) -> Schedule {
5859        Schedule {
5860            id: "x".into(),
5861            when,
5862            job_id: "y".into(),
5863            // #917: validate() now rejects a target that dispatches
5864            // nothing, so the baseline helper carries the simplest
5865            // specified target.
5866            plan: FanoutPlan {
5867                target: Target {
5868                    all: true,
5869                    ..Target::default()
5870                },
5871                ..FanoutPlan::default()
5872            },
5873            active: Active::default(),
5874            constraints: Constraints::default(),
5875            on_failure: OnFailure::default(),
5876            tz: ScheduleTz::default(),
5877            starting_deadline: None,
5878            runs_on,
5879            enabled: true,
5880            tags: Vec::new(),
5881            origin: None,
5882        }
5883    }
5884
5885    fn calendar(at: &str, days: &[&str]) -> When {
5886        When::Calendar(CalendarSpec {
5887            at: at.into(),
5888            days: days.iter().map(|d| (*d).to_string()).collect(),
5889        })
5890    }
5891
5892    #[test]
5893    fn next_calendar_fire_returns_next_utc_occurrence() {
5894        use chrono::TimeZone;
5895        // Daily 09:00, evaluated in UTC. From 08:00 the same day, the
5896        // next strict occurrence is 09:00 that day.
5897        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5898        s.tz = ScheduleTz::Utc;
5899        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 8, 0, 0).unwrap();
5900        let next = s.next_calendar_fire(now).expect("calendar has a next fire");
5901        assert_eq!(
5902            next,
5903            chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap()
5904        );
5905    }
5906
5907    #[test]
5908    fn next_calendar_fire_is_strictly_after_now() {
5909        use chrono::TimeZone;
5910        // Standing exactly on a fire instant must preview the *next*
5911        // one (inclusive = false), not the one firing right now.
5912        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5913        s.tz = ScheduleTz::Utc;
5914        let on_fire = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap();
5915        let next = s
5916            .next_calendar_fire(on_fire)
5917            .expect("calendar has a next fire");
5918        assert_eq!(
5919            next,
5920            chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()
5921        );
5922    }
5923
5924    #[test]
5925    fn next_calendar_fire_none_for_reconcile_shapes() {
5926        // `per_pc` / `per_target` lower to the every-minute poll cron —
5927        // no discrete upcoming event to preview, so `None`.
5928        let now = chrono::Utc::now();
5929        for when in [
5930            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5931            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5932            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5933            When::PerTarget(PerPolicy::Every(EverySpec {
5934                every: "24h".into(),
5935            })),
5936        ] {
5937            let s = schedule_with(when, RunsOn::Backend);
5938            assert!(
5939                s.next_calendar_fire(now).is_none(),
5940                "reconcile shapes have no calendar fire",
5941            );
5942        }
5943    }
5944
5945    // ---- preview_fires (#418 dry-run / preview) ----
5946
5947    fn cal_utc(at: &str, days: &[&str]) -> Schedule {
5948        let mut s = schedule_with(calendar(at, days), RunsOn::Backend);
5949        s.tz = ScheduleTz::Utc; // host-independent assertions
5950        s
5951    }
5952
5953    #[test]
5954    fn preview_lists_next_calendar_occurrences() {
5955        use chrono::TimeZone;
5956        // Weekday 09:00, from Wed 2026-06-10 00:00 UTC: the next five
5957        // fires skip the weekend (Sat 13 / Sun 14).
5958        let s = cal_utc("09:00", &["mon-fri"]);
5959        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5960        let got = s.preview_fires(now, 5);
5961        let want: Vec<_> = [
5962            (2026, 6, 10), // Wed
5963            (2026, 6, 11), // Thu
5964            (2026, 6, 12), // Fri
5965            (2026, 6, 15), // Mon (skips Sat 13 / Sun 14)
5966            (2026, 6, 16), // Tue
5967        ]
5968        .iter()
5969        .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
5970        .collect();
5971        assert_eq!(got, want);
5972    }
5973
5974    #[test]
5975    fn preview_handles_nth_and_last_weekday() {
5976        use chrono::TimeZone;
5977        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
5978        // 2nd Tuesday (Patch Tuesday): Jun 9, Jul 14 2026.
5979        let nth = cal_utc("09:00", &["tue#2"]).preview_fires(now, 2);
5980        assert_eq!(
5981            nth,
5982            vec![
5983                chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap(),
5984                chrono::Utc.with_ymd_and_hms(2026, 7, 14, 9, 0, 0).unwrap(),
5985            ]
5986        );
5987        // Last Friday of the month: Jun 26, Jul 31 2026.
5988        let last = cal_utc("22:00", &["friL"]).preview_fires(now, 2);
5989        assert_eq!(
5990            last,
5991            vec![
5992                chrono::Utc.with_ymd_and_hms(2026, 6, 26, 22, 0, 0).unwrap(),
5993                chrono::Utc.with_ymd_and_hms(2026, 7, 31, 22, 0, 0).unwrap(),
5994            ]
5995        );
5996    }
5997
5998    #[test]
5999    fn preview_is_empty_for_reconcile_and_zero_count() {
6000        let now = chrono::Utc::now();
6001        // reconcile shapes have no discrete fire times
6002        let recon = schedule_with(
6003            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6004            RunsOn::Backend,
6005        );
6006        assert!(recon.preview_fires(now, 5).is_empty());
6007        // count == 0 yields nothing even for a calendar
6008        assert!(cal_utc("09:00", &[]).preview_fires(now, 0).is_empty());
6009    }
6010
6011    #[test]
6012    fn preview_skips_outside_active_window() {
6013        use chrono::TimeZone;
6014        // Daily 09:00, active only [2026-06-15, 2026-06-17). Occurrences
6015        // before `from` are skipped; `until` is exclusive, so 06-17's
6016        // fire is out — leaving exactly the 15th and 16th.
6017        let mut s = cal_utc("09:00", &[]);
6018        s.active = Active {
6019            from: Some("2026-06-15".into()),
6020            until: Some("2026-06-17".into()),
6021        };
6022        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
6023        let got = s.preview_fires(now, 5);
6024        assert_eq!(
6025            got,
6026            vec![
6027                chrono::Utc.with_ymd_and_hms(2026, 6, 15, 9, 0, 0).unwrap(),
6028                chrono::Utc.with_ymd_and_hms(2026, 6, 16, 9, 0, 0).unwrap(),
6029            ]
6030        );
6031    }
6032
6033    #[test]
6034    fn preview_empty_when_calendar_time_outside_window() {
6035        use chrono::TimeZone;
6036        // Fires at 09:00 but the maintenance window is overnight — it can
6037        // never run, so the preview is empty (matches
6038        // `calendar_outside_window`), and the scan still terminates.
6039        let mut s = cal_utc("09:00", &[]);
6040        s.constraints = Constraints {
6041            window: Some("22:00-05:00".into()),
6042            ..Constraints::default()
6043        };
6044        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
6045        assert!(s.preview_fires(now, 5).is_empty());
6046        // Every candidate tick is rejected, so this also exercises the
6047        // SCAN_CAP bound: a large `count` must still terminate (and
6048        // return empty) rather than spin (claude #578 review).
6049        assert!(s.preview_fires(now, 50).is_empty());
6050    }
6051
6052    #[test]
6053    fn preview_past_one_shot_is_empty() {
6054        use chrono::TimeZone;
6055        // A dated one-shot whose instant has passed never fires again.
6056        let s = cal_utc("2026-06-10 09:00", &[]);
6057        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 0, 0, 0).unwrap();
6058        assert!(s.preview_fires(now, 5).is_empty());
6059        // …but from before it, the single future fire shows up.
6060        let before = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
6061        assert_eq!(
6062            s.preview_fires(before, 5),
6063            vec![chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()]
6064        );
6065    }
6066
6067    #[test]
6068    fn lowering_matches_the_418_table() {
6069        let cases = [
6070            (
6071                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6072                (POLL_CRON, ExecMode::OncePerPc, None),
6073            ),
6074            (
6075                When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6076                (POLL_CRON, ExecMode::OncePerPc, Some("6h")),
6077            ),
6078            (
6079                When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
6080                (POLL_CRON, ExecMode::OncePerTarget, None),
6081            ),
6082            (
6083                When::PerTarget(PerPolicy::Every(EverySpec {
6084                    every: "24h".into(),
6085                })),
6086                (POLL_CRON, ExecMode::OncePerTarget, Some("24h")),
6087            ),
6088            // calendar repeating → 6-field cron
6089            (
6090                calendar("09:00", &["mon-fri"]),
6091                ("0 0 9 * * mon-fri", ExecMode::EveryTick, None),
6092            ),
6093            // calendar daily (no days) → DOW *
6094            (
6095                calendar("18:30", &[]),
6096                ("0 30 18 * * *", ExecMode::EveryTick, None),
6097            ),
6098            // calendar one-shot → 7-field year cron
6099            (
6100                calendar("2026-06-10 09:00", &[]),
6101                ("0 0 9 10 6 * 2026", ExecMode::EveryTick, None),
6102            ),
6103        ];
6104        for (when, (cron, mode, cooldown)) in cases {
6105            let l = schedule_with(when.clone(), RunsOn::Backend).lowered();
6106            assert_eq!(l.cron, cron, "cron for {when}");
6107            assert_eq!(l.mode, mode, "mode for {when}");
6108            assert_eq!(l.cooldown.as_deref(), cooldown, "cooldown for {when}");
6109        }
6110    }
6111
6112    #[test]
6113    fn lowered_carries_schedule_tz() {
6114        for (tz, want) in [
6115            (ScheduleTz::Local, ScheduleTz::Local),
6116            (ScheduleTz::Utc, ScheduleTz::Utc),
6117        ] {
6118            let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
6119            s.tz = tz;
6120            assert_eq!(s.lowered().tz, want, "calendar carries tz");
6121            // reconcile shapes carry tz too (for the active-window check)
6122            let mut s = schedule_with(
6123                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6124                RunsOn::Backend,
6125            );
6126            s.tz = tz;
6127            assert_eq!(s.lowered().tz, want, "reconcile carries tz");
6128        }
6129    }
6130
6131    #[test]
6132    fn poll_cron_is_accepted_by_the_engine_parser() {
6133        // POLL_CRON is system-generated — if the engine's parser
6134        // ever rejected it every reconcile schedule would die at
6135        // register time. Validate it with the same croner config
6136        // (Seconds::Required, dom_and_dow, year optional).
6137        croner::parser::CronParser::builder()
6138            .seconds(croner::parser::Seconds::Required)
6139            .dom_and_dow(true)
6140            .build()
6141            .parse(POLL_CRON)
6142            .expect("POLL_CRON must parse");
6143    }
6144
6145    // ---- Schedule::validate() (#418 decision F) ----
6146
6147    #[test]
6148    fn validate_accepts_reconcile_shapes() {
6149        for when in [
6150            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6151            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6152            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
6153            When::PerTarget(PerPolicy::Every(EverySpec {
6154                every: "24h".into(),
6155            })),
6156        ] {
6157            schedule_with(when.clone(), RunsOn::Backend)
6158                .validate()
6159                .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
6160        }
6161    }
6162
6163    #[test]
6164    fn validate_accepts_per_pc_on_agent() {
6165        schedule_with(
6166            When::PerPc(PerPolicy::Every(EverySpec { every: "1h".into() })),
6167            RunsOn::Agent,
6168        )
6169        .validate()
6170        .expect("per_pc + agent is the offline-inventory shape");
6171    }
6172
6173    // ---- #418 event triggers (when: { on }) ----
6174
6175    #[test]
6176    fn validate_accepts_event_on_agent() {
6177        for triggers in [
6178            vec![OnTrigger::Startup],
6179            vec![OnTrigger::Logon],
6180            vec![OnTrigger::Lock],
6181            vec![OnTrigger::Unlock],
6182            vec![OnTrigger::NetworkChange],
6183            vec![
6184                OnTrigger::Startup,
6185                OnTrigger::Logon,
6186                OnTrigger::Lock,
6187                OnTrigger::Unlock,
6188                OnTrigger::NetworkChange,
6189            ],
6190        ] {
6191            schedule_with(When::On(triggers), RunsOn::Agent)
6192                .validate()
6193                .expect("when.on is valid on runs_on: agent");
6194        }
6195    }
6196
6197    #[test]
6198    fn validate_rejects_event_on_backend() {
6199        let err = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Backend)
6200            .validate()
6201            .unwrap_err();
6202        assert!(err.contains("when.on"), "got: {err}");
6203        assert!(err.contains("runs_on: agent"), "got: {err}");
6204    }
6205
6206    #[test]
6207    fn validate_rejects_empty_event_list() {
6208        let err = schedule_with(When::On(vec![]), RunsOn::Agent)
6209            .validate()
6210            .unwrap_err();
6211        assert!(err.contains("when.on"), "got: {err}");
6212        assert!(err.contains("at least one"), "got: {err}");
6213    }
6214
6215    #[test]
6216    fn event_schedule_lowers_to_event_mode_and_is_event() {
6217        let s = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Agent);
6218        assert!(s.is_event());
6219        assert_eq!(s.lowered().mode, ExecMode::Event);
6220        assert_eq!(s.event_triggers(), &[OnTrigger::Startup]);
6221        // non-event schedules report no triggers.
6222        let cal = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
6223        assert!(!cal.is_event());
6224        assert!(cal.event_triggers().is_empty());
6225    }
6226
6227    // ---- #418 constraints.require (env gates) ----
6228
6229    fn require_schedule(req: Require, runs_on: RunsOn) -> Schedule {
6230        let mut s = schedule_with(
6231            When::PerPc(PerPolicy::Every(EverySpec { every: "1m".into() })),
6232            runs_on,
6233        );
6234        s.constraints.require = Some(req);
6235        s
6236    }
6237
6238    #[test]
6239    fn require_met_combinations() {
6240        use std::time::Duration;
6241        let idle = |m: u64| Some(Duration::from_secs(m * 60));
6242        // Builder for the sensed state: (ac, idle, cpu, network).
6243        let env = |ac, idle, cpu, net| EnvState {
6244            ac_online: ac,
6245            idle,
6246            cpu_pct: cpu,
6247            network_up: net,
6248        };
6249        // Empty require — always met regardless of sensed state.
6250        assert!(require_met(
6251            &Require::default(),
6252            &env(false, None, None, false)
6253        ));
6254        // ac_power: only on AC.
6255        let ac = Require {
6256            ac_power: true,
6257            ..Default::default()
6258        };
6259        assert!(!require_met(&ac, &env(false, None, None, true)));
6260        assert!(require_met(&ac, &env(true, None, None, false)));
6261        // idle: needs >= the configured min; None idle never satisfies.
6262        let idle10 = Require {
6263            idle: Some("10m".into()),
6264            ..Default::default()
6265        };
6266        assert!(!require_met(&idle10, &env(true, None, None, true)));
6267        assert!(!require_met(&idle10, &env(true, idle(5), None, true)));
6268        assert!(require_met(&idle10, &env(true, idle(15), None, true)));
6269        assert!(require_met(&idle10, &env(true, idle(10), None, true))); // boundary inclusive
6270        // cpu_below: needs CPU strictly < threshold; None cpu never satisfies.
6271        let cpu20 = Require {
6272            cpu_below: Some(20.0),
6273            ..Default::default()
6274        };
6275        assert!(!require_met(&cpu20, &env(true, None, None, true))); // no sample → fail-closed
6276        assert!(!require_met(&cpu20, &env(true, None, Some(20.0), true))); // == threshold
6277        assert!(!require_met(&cpu20, &env(true, None, Some(55.0), true))); // busy
6278        assert!(require_met(&cpu20, &env(true, None, Some(5.0), true))); // quiet
6279        // network: only when online.
6280        let net = Require {
6281            network: true,
6282            ..Default::default()
6283        };
6284        assert!(!require_met(&net, &env(true, None, None, false))); // offline
6285        assert!(require_met(&net, &env(true, None, None, true))); // online
6286        // all four: AND.
6287        let all = Require {
6288            ac_power: true,
6289            idle: Some("10m".into()),
6290            cpu_below: Some(20.0),
6291            network: true,
6292        };
6293        assert!(!require_met(&all, &env(false, idle(20), Some(5.0), true))); // on battery
6294        assert!(!require_met(&all, &env(true, idle(1), Some(5.0), true))); // not idle enough
6295        assert!(!require_met(&all, &env(true, idle(20), Some(50.0), true))); // busy
6296        assert!(!require_met(&all, &env(true, idle(20), Some(5.0), false))); // offline
6297        assert!(require_met(&all, &env(true, idle(20), Some(5.0), true)));
6298        // An unparseable idle is treated as no-requirement by require_met
6299        // (validate rejects it at create time, so this only guards a
6300        // hand-edited blob): ac still gates.
6301        let bad = Require {
6302            ac_power: true,
6303            idle: Some("garbage".into()),
6304            ..Default::default()
6305        };
6306        assert!(require_met(&bad, &env(true, None, None, true)));
6307        assert!(!require_met(&bad, &env(false, None, None, true)));
6308    }
6309
6310    #[test]
6311    fn validate_accepts_and_rejects_cpu_below() {
6312        // In-range accepted.
6313        require_schedule(
6314            Require {
6315                cpu_below: Some(20.0),
6316                ..Default::default()
6317            },
6318            RunsOn::Agent,
6319        )
6320        .validate()
6321        .expect("cpu_below 20 is valid");
6322        // Upper boundary: 100.0 is accepted (fires unless CPU is exactly
6323        // 100%). Pins the inclusive upper bound against a future c < 100.0.
6324        require_schedule(
6325            Require {
6326                cpu_below: Some(100.0),
6327                ..Default::default()
6328            },
6329            RunsOn::Agent,
6330        )
6331        .validate()
6332        .expect("cpu_below 100 is valid");
6333        // Out of range rejected (0 and >100).
6334        for bad in [0.0, -5.0, 100.1] {
6335            let err = require_schedule(
6336                Require {
6337                    cpu_below: Some(bad),
6338                    ..Default::default()
6339                },
6340                RunsOn::Agent,
6341            )
6342            .validate()
6343            .unwrap_err();
6344            assert!(
6345                err.contains("constraints.require.cpu_below"),
6346                "cpu_below {bad}: {err}"
6347            );
6348        }
6349    }
6350
6351    #[test]
6352    fn validate_accepts_require_on_agent() {
6353        require_schedule(
6354            Require {
6355                ac_power: true,
6356                idle: Some("10m".into()),
6357                cpu_below: Some(20.0),
6358                network: true,
6359            },
6360            RunsOn::Agent,
6361        )
6362        .validate()
6363        .expect("constraints.require is valid on runs_on: agent");
6364    }
6365
6366    #[test]
6367    fn validate_rejects_require_on_backend() {
6368        let err = require_schedule(
6369            Require {
6370                ac_power: true,
6371                ..Default::default()
6372            },
6373            RunsOn::Backend,
6374        )
6375        .validate()
6376        .unwrap_err();
6377        assert!(err.contains("constraints.require"), "got: {err}");
6378        assert!(err.contains("runs_on: agent"), "got: {err}");
6379
6380        // An idle-only require (ac_power: false) is also non-empty
6381        // (is_empty folds the fields) and must reject on backend too —
6382        // guards against a regression in Require::is_empty.
6383        let err = require_schedule(
6384            Require {
6385                idle: Some("10m".into()),
6386                ..Default::default()
6387            },
6388            RunsOn::Backend,
6389        )
6390        .validate()
6391        .unwrap_err();
6392        assert!(
6393            err.contains("constraints.require"),
6394            "idle-only on backend: {err}"
6395        );
6396    }
6397
6398    #[test]
6399    fn validate_rejects_bad_require_idle() {
6400        let err = require_schedule(
6401            Require {
6402                idle: Some("not-a-duration".into()),
6403                ..Default::default()
6404            },
6405            RunsOn::Agent,
6406        )
6407        .validate()
6408        .unwrap_err();
6409        assert!(err.contains("constraints.require.idle"), "got: {err}");
6410    }
6411
6412    #[test]
6413    fn require_round_trips_and_skips_empty() {
6414        // ac_power: false is skipped; an all-default require nested in
6415        // constraints is omitted (is_empty folds it in).
6416        let yaml = "id: s\nwhen: { per_pc: { every: 1m } }\njob_id: j\nruns_on: agent\n\
6417                    constraints: { require: { ac_power: true, idle: 10m, cpu_below: 20, \
6418                    network: true } }\n";
6419        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6420        let req = s.constraints.require.as_ref().expect("require present");
6421        assert!(req.ac_power);
6422        assert_eq!(req.idle.as_deref(), Some("10m"));
6423        assert_eq!(req.cpu_below, Some(20.0));
6424        assert!(req.network);
6425        // Re-serialize: idle + cpu_below + network present, ac_power true.
6426        let back = serde_json::to_string(&s.constraints).unwrap();
6427        assert!(back.contains("\"idle\":\"10m\""), "got: {back}");
6428        assert!(back.contains("\"cpu_below\":20"), "got: {back}");
6429        assert!(back.contains("\"network\":true"), "got: {back}");
6430        // An empty require is omitted entirely by is_empty.
6431        let mut empty = s.clone();
6432        empty.constraints.require = Some(Require::default());
6433        assert!(empty.constraints.is_empty());
6434    }
6435
6436    #[test]
6437    fn validate_rejects_per_target_on_agent() {
6438        let err = schedule_with(
6439            When::PerTarget(PerPolicy::Every(EverySpec {
6440                every: "24h".into(),
6441            })),
6442            RunsOn::Agent,
6443        )
6444        .validate()
6445        .unwrap_err();
6446        assert!(err.contains("per_target"), "got: {err}");
6447        assert!(err.contains("runs_on: agent"), "got: {err}");
6448
6449        // per_target: once is also backend-only.
6450        let err = schedule_with(
6451            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
6452            RunsOn::Agent,
6453        )
6454        .validate()
6455        .unwrap_err();
6456        assert!(err.contains("per_target"), "got (once): {err}");
6457        assert!(err.contains("runs_on: agent"), "got (once): {err}");
6458    }
6459
6460    #[test]
6461    fn validate_rejects_bad_every_duration() {
6462        let err = schedule_with(
6463            When::PerPc(PerPolicy::Every(EverySpec { every: "6x".into() })),
6464            RunsOn::Backend,
6465        )
6466        .validate()
6467        .unwrap_err();
6468        assert!(err.contains("when.every"), "got: {err}");
6469    }
6470
6471    #[test]
6472    fn validate_rejects_bad_jitter_and_starting_deadline() {
6473        let mut s = schedule_with(
6474            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6475            RunsOn::Backend,
6476        );
6477        s.plan.jitter = Some("5x".into());
6478        let err = s.validate().unwrap_err();
6479        assert!(err.contains("jitter"), "got: {err}");
6480
6481        let mut s = schedule_with(
6482            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6483            RunsOn::Backend,
6484        );
6485        s.starting_deadline = Some("soon".into());
6486        let err = s.validate().unwrap_err();
6487        assert!(err.contains("starting_deadline"), "got: {err}");
6488    }
6489
6490    #[test]
6491    fn validate_rejects_unspecified_target() {
6492        // #917 (1): an all-default target never dispatches anywhere —
6493        // runs_on: agent silently never fires, runs_on: backend
6494        // warn-fails every tick at the exec boundary. Both rejected.
6495        for runs_on in [RunsOn::Backend, RunsOn::Agent] {
6496            let mut s = schedule_with(When::PerPc(PerPolicy::Once(OnceLiteral::Once)), runs_on);
6497            s.plan.target = Target::default();
6498            let err = s.validate().unwrap_err();
6499            assert!(err.contains("target"), "for {runs_on:?}, got: {err}");
6500        }
6501    }
6502
6503    /// A Schedule with every top-level field populated so each one
6504    /// actually serialises (the optional ones are `skip_serializing_if`).
6505    fn fully_populated_schedule() -> Schedule {
6506        let mut s = schedule_with(
6507            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6508            RunsOn::Backend,
6509        );
6510        s.plan.rollout = Some(Rollout {
6511            strategy: RolloutStrategy::Wave,
6512            waves: vec![Wave {
6513                group: "canary".into(),
6514                delay: "0s".into(),
6515            }],
6516        });
6517        s.plan.jitter = Some("5m".into());
6518        s.plan.deadline_at = Some(chrono::Utc::now());
6519        s.active = Active {
6520            from: Some("2026-01-01 00:00".into()),
6521            until: Some("2026-12-31 00:00".into()),
6522        };
6523        s.constraints = Constraints {
6524            window: Some("09:00-17:00".into()),
6525            ..Constraints::default()
6526        };
6527        s.on_failure = OnFailure {
6528            retry: Some(Retry {
6529                max: 1,
6530                backoff: "10s".into(),
6531            }),
6532        };
6533        s.starting_deadline = Some("30m".into());
6534        s.tags = vec!["health".into()];
6535        s.origin = Some(RepoOrigin {
6536            path: "configs/schedules/x.yaml".into(),
6537            repo: None,
6538            script_file: None,
6539        });
6540        s
6541    }
6542
6543    #[test]
6544    fn schedule_top_level_keys_cover_serialized_fields() {
6545        // #924 drift guard: the hand-maintained TOP_LEVEL_KEYS list must
6546        // match exactly what a fully-populated Schedule serialises — so a
6547        // future field added to Schedule or FanoutPlan can't slip past
6548        // the flatten-aware strict guard by being forgotten here.
6549        let s = fully_populated_schedule();
6550        let value = serde_json::to_value(&s).expect("serialize schedule");
6551        let serialized: std::collections::BTreeSet<String> = value
6552            .as_object()
6553            .expect("schedule serialises to an object")
6554            .keys()
6555            .cloned()
6556            .collect();
6557        let listed: std::collections::BTreeSet<String> = Schedule::TOP_LEVEL_KEYS
6558            .iter()
6559            .map(|s| s.to_string())
6560            .collect();
6561        assert_eq!(
6562            serialized, listed,
6563            "TOP_LEVEL_KEYS is out of sync with Schedule's serialized fields \
6564             (flatten-aware strict guard would miss a real field or reject a valid one)"
6565        );
6566    }
6567
6568    #[test]
6569    fn strict_rejects_flatten_hidden_top_level_typo() {
6570        // #924: a top-level typo on a flattening type (jiter / enabledd)
6571        // is buffered into the flatten target by serde and hidden from
6572        // serde_ignored — the top-level guard must catch it. Verified on
6573        // both the YAML and JSON strict boundaries.
6574        let yaml = "\
6575id: s1
6576job_id: j1
6577when:
6578  per_pc: once
6579target:
6580  all: true
6581jiter: 5m
6582";
6583        let err = crate::strict::from_yaml_str::<Schedule>(yaml).unwrap_err();
6584        assert!(err.contains("jiter"), "got: {err}");
6585
6586        let json = serde_json::json!({
6587            "id": "s1",
6588            "job_id": "j1",
6589            "when": { "per_pc": "once" },
6590            "target": { "all": true },
6591            "enabledd": false,
6592        });
6593        let err = crate::strict::from_json_slice::<Schedule>(&serde_json::to_vec(&json).unwrap())
6594            .unwrap_err();
6595        assert!(err.contains("enabledd"), "got: {err}");
6596    }
6597
6598    #[test]
6599    fn strict_accepts_all_valid_schedule_top_level_keys() {
6600        // The guard must not reject any legitimate key — round-trip a
6601        // fully-populated schedule through the strict YAML boundary.
6602        let s = fully_populated_schedule();
6603        let yaml = serde_yaml::to_string(&s).expect("serialize");
6604        crate::strict::from_yaml_str::<Schedule>(&yaml)
6605            .expect("every serialized key must be accepted by the strict guard");
6606    }
6607
6608    #[test]
6609    fn strict_rejects_non_string_top_level_yaml_key() {
6610        // #924 (gemini #945): a YAML key isn't always a string — an
6611        // unquoted `true:` parses as a boolean, `123:` as a number. A
6612        // `filter_map` on `as_str()` would drop these and let them slip
6613        // past the flatten guard; `yaml_key_label` renders them so they
6614        // are still rejected. (serde_yaml is YAML 1.2, so `on:` stays a
6615        // *string* "on" — also rejected, just via the string path.)
6616        let base = "\
6617id: s1
6618job_id: j1
6619when:
6620  per_pc: once
6621target:
6622  all: true
6623";
6624        for (extra, needle) in [
6625            ("true: x\n", "true"),
6626            ("123: x\n", "123"),
6627            ("on: y\n", "on"),
6628        ] {
6629            let yaml = format!("{base}{extra}");
6630            let err = crate::strict::from_yaml_str::<Schedule>(&yaml).unwrap_err();
6631            assert!(err.contains(needle), "for '{extra}', got: {err}");
6632        }
6633    }
6634
6635    #[test]
6636    fn validate_accepts_waves_instead_of_target_on_backend() {
6637        // #917 (1): the exec boundary accepts rollout-only plans
6638        // (target then just labels the audit row) — so does validate.
6639        let mut s = schedule_with(
6640            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6641            RunsOn::Backend,
6642        );
6643        s.plan.target = Target::default();
6644        s.plan.rollout = Some(Rollout {
6645            strategy: RolloutStrategy::Wave,
6646            waves: vec![Wave {
6647                group: "canary".into(),
6648                delay: "0s".into(),
6649            }],
6650        });
6651        s.validate().expect("rollout-only plan should validate");
6652    }
6653
6654    #[test]
6655    fn validate_rejects_rollout_on_agent() {
6656        // #917 (1): rollout waves are backend-published; a runs_on:
6657        // agent schedule never reads them, so the combination is a
6658        // silent no-op — reject like max_concurrent-on-agent.
6659        let mut s = schedule_with(
6660            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6661            RunsOn::Agent,
6662        );
6663        s.plan.rollout = Some(Rollout {
6664            strategy: RolloutStrategy::Wave,
6665            waves: vec![Wave {
6666                group: "canary".into(),
6667                delay: "0s".into(),
6668            }],
6669        });
6670        let err = s.validate().unwrap_err();
6671        assert!(err.contains("rollout"), "got: {err}");
6672    }
6673
6674    #[test]
6675    fn validate_rejects_bad_waves() {
6676        // #917 (2): empty waves, blank group, unparseable delay — all
6677        // previously accepted and failed (or no-opped) at every fire.
6678        let base = || {
6679            schedule_with(
6680                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6681                RunsOn::Backend,
6682            )
6683        };
6684
6685        let mut s = base();
6686        s.plan.rollout = Some(Rollout {
6687            strategy: RolloutStrategy::Wave,
6688            waves: vec![],
6689        });
6690        let err = s.validate().unwrap_err();
6691        assert!(err.contains("at least one wave"), "got: {err}");
6692
6693        let mut s = base();
6694        s.plan.rollout = Some(Rollout {
6695            strategy: RolloutStrategy::Wave,
6696            waves: vec![Wave {
6697                group: "  ".into(),
6698                delay: "0s".into(),
6699            }],
6700        });
6701        let err = s.validate().unwrap_err();
6702        assert!(err.contains("waves[0].group"), "got: {err}");
6703
6704        let mut s = base();
6705        s.plan.rollout = Some(Rollout {
6706            strategy: RolloutStrategy::Wave,
6707            waves: vec![
6708                Wave {
6709                    group: "canary".into(),
6710                    delay: "0s".into(),
6711                },
6712                Wave {
6713                    group: "wave1".into(),
6714                    delay: "5 minuts".into(),
6715                },
6716            ],
6717        });
6718        let err = s.validate().unwrap_err();
6719        assert!(err.contains("waves[1].delay"), "got: {err}");
6720    }
6721
6722    #[test]
6723    fn validate_rejects_wave_delay_at_or_past_starting_deadline() {
6724        // #917 (3): the deadline is stamped once at tick time, so a
6725        // wave sleeping >= starting_deadline publishes already-expired
6726        // Commands — dead on arrival, every fire.
6727        let mut s = schedule_with(
6728            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6729            RunsOn::Backend,
6730        );
6731        s.starting_deadline = Some("30m".into());
6732        s.plan.rollout = Some(Rollout {
6733            strategy: RolloutStrategy::Wave,
6734            waves: vec![
6735                Wave {
6736                    group: "canary".into(),
6737                    delay: "0s".into(),
6738                },
6739                Wave {
6740                    group: "wave1".into(),
6741                    delay: "30m".into(),
6742                },
6743            ],
6744        });
6745        let err = s.validate().unwrap_err();
6746        assert!(
6747            err.contains("waves[1].delay") && err.contains("starting_deadline"),
6748            "got: {err}"
6749        );
6750
6751        // Strictly shorter is fine.
6752        s.plan.rollout.as_mut().unwrap().waves[1].delay = "29m".into();
6753        s.validate().expect("delay < deadline should validate");
6754    }
6755
6756    #[test]
6757    fn validate_rejects_operator_set_deadline_at() {
6758        // #917 (4): machine-stamped field — the scheduler overwrites it
6759        // on every fire, so a hand-set value is silently discarded.
6760        let mut s = schedule_with(
6761            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6762            RunsOn::Backend,
6763        );
6764        s.plan.deadline_at = Some(chrono::Utc::now());
6765        let err = s.validate().unwrap_err();
6766        assert!(
6767            err.contains("deadline_at") && err.contains("starting_deadline"),
6768            "got: {err}"
6769        );
6770    }
6771
6772    #[test]
6773    fn validate_accepts_calendar_shapes() {
6774        for when in [
6775            calendar("09:00", &["mon-fri"]),   // weekday morning
6776            calendar("00:00", &["sun"]),       // weekly
6777            calendar("18:30", &[]),            // daily
6778            calendar("2026-06-10 09:00", &[]), // one-shot
6779            calendar("2026/12/25 00:00", &[]), // one-shot, slash form
6780        ] {
6781            schedule_with(when.clone(), RunsOn::Backend)
6782                .validate()
6783                .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
6784        }
6785    }
6786
6787    #[test]
6788    fn validate_rejects_bad_at() {
6789        for bad in ["25:00", "09:60", "9", "noon", "2026-13-01 09:00"] {
6790            let err = schedule_with(calendar(bad, &[]), RunsOn::Backend)
6791                .validate()
6792                .unwrap_err();
6793            assert!(err.contains("when.at"), "for '{bad}', got: {err}");
6794        }
6795    }
6796
6797    #[test]
6798    fn validate_rejects_datetime_at_with_days() {
6799        // A dated `at` is a one-shot — pairing it with days is a
6800        // contradiction (the date already pins the day).
6801        let err = schedule_with(calendar("2026-06-10 09:00", &["mon"]), RunsOn::Backend)
6802            .validate()
6803            .unwrap_err();
6804        assert!(
6805            err.contains("one-shot") && err.contains("days"),
6806            "got: {err}"
6807        );
6808    }
6809
6810    #[test]
6811    fn validate_rejects_bad_day_name() {
6812        // A garbage DOW token is caught by the days pre-flight and
6813        // reported against `when.days`, not the confusing
6814        // "when.at lowered to invalid cron" (claude #432 review).
6815        let err = schedule_with(calendar("09:00", &["funday"]), RunsOn::Backend)
6816            .validate()
6817            .unwrap_err();
6818        assert!(err.contains("when.days"), "got: {err}");
6819        assert!(err.contains("funday"), "names the bad token: {err}");
6820        // a degenerate range like `mon-` reports the whole token, not
6821        // a cryptic empty part (claude #432 follow-up)
6822        let err = schedule_with(calendar("09:00", &["mon-"]), RunsOn::Backend)
6823            .validate()
6824            .unwrap_err();
6825        assert!(err.contains("'mon-'"), "names the whole token: {err}");
6826        // valid names / ranges / numeric / * all pass
6827        for ok in [
6828            calendar("09:00", &["mon-fri"]),
6829            calendar("09:00", &["mon", "wed", "sun"]),
6830            calendar("09:00", &["1-5"]),
6831        ] {
6832            schedule_with(ok.clone(), RunsOn::Backend)
6833                .validate()
6834                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6835        }
6836    }
6837
6838    #[test]
6839    fn validate_accepts_nth_weekday() {
6840        // #418: nth-weekday (Patch Tuesday). validate() also lowers to
6841        // a cron and parses it with croner, so passing here proves the
6842        // whole chain — token → DOW field → engine-acceptable cron.
6843        for ok in [
6844            calendar("09:00", &["tue#2"]),          // 2nd Tuesday
6845            calendar("09:00", &["fri#1"]),          // 1st Friday
6846            calendar("03:00", &["sun#5"]),          // 5th Sunday
6847            calendar("09:00", &["tue#2", "thu#2"]), // a list of nths
6848            calendar("09:00", &["2#2"]),            // numeric DOW + ordinal
6849            // Case-insensitive both sides: validate lowercases, croner
6850            // upper-cases the whole pattern before aliasing (claude #547).
6851            calendar("09:00", &["TUE#2"]),
6852        ] {
6853            schedule_with(ok.clone(), RunsOn::Backend)
6854                .validate()
6855                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6856        }
6857    }
6858
6859    #[test]
6860    fn validate_rejects_bad_nth_weekday() {
6861        // ordinal out of 1..5, a range with #, and a bad day before #.
6862        for bad in ["tue#0", "tue#6", "tue#x", "mon-fri#2", "funday#2"] {
6863            let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
6864                .validate()
6865                .unwrap_err();
6866            assert!(err.contains("when.days"), "for '{bad}', got: {err}");
6867        }
6868    }
6869
6870    #[test]
6871    fn validate_accepts_last_weekday() {
6872        // #418: last-weekday (`friL` = last Friday). Like the nth case,
6873        // validate() lowers to a cron and round-trips it through croner,
6874        // so passing proves token → DOW field → engine-acceptable cron
6875        // with the verified last-<dow>-of-month semantics.
6876        for ok in [
6877            calendar("09:00", &["friL"]),         // last Friday
6878            calendar("03:00", &["sunL"]),         // last Sunday
6879            calendar("22:00", &["5L"]),           // numeric DOW + last
6880            calendar("00:00", &["0L"]),           // numeric Sunday (0…
6881            calendar("00:00", &["7L"]),           // …and its 7 alias)
6882            calendar("09:00", &["monL", "friL"]), // a list of last-weekdays
6883            // Case-insensitive both the weekday and the `L` suffix:
6884            // validate lowercases the day, croner upper-cases the whole
6885            // pattern before aliasing (claude #547).
6886            calendar("09:00", &["FRIL"]),
6887            calendar("09:00", &["fril"]),
6888        ] {
6889            schedule_with(ok.clone(), RunsOn::Backend)
6890                .validate()
6891                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6892        }
6893    }
6894
6895    #[test]
6896    fn validate_rejects_bad_last_weekday() {
6897        // bare `L` (no weekday — a footgun croner reads as Saturday), a
6898        // range with L, a bad day before L, and an internal space that
6899        // would otherwise leak a malformed cron downstream (gemini #560).
6900        for bad in ["L", "l", "mon-friL", "fundayL", "8L", "*L", "fri L"] {
6901            let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
6902                .validate()
6903                .unwrap_err();
6904            assert!(err.contains("when.days"), "for '{bad}', got: {err}");
6905        }
6906    }
6907
6908    #[test]
6909    fn calendar_oneshot_instant_detects_past() {
6910        use chrono::TimeZone;
6911        // a dated `at` resolves to an absolute instant…
6912        let c = CalendarSpec {
6913            at: "2024-01-01 09:00".into(),
6914            days: vec![],
6915        };
6916        let t = c
6917            .oneshot_instant(ScheduleTz::Utc)
6918            .expect("one-shot instant");
6919        assert_eq!(
6920            t,
6921            chrono::Utc.with_ymd_and_hms(2024, 1, 1, 9, 0, 0).unwrap()
6922        );
6923        assert!(t < chrono::Utc::now(), "2024 is in the past");
6924        // …while a repeating (time-only) calendar has no instant
6925        let rep = CalendarSpec {
6926            at: "09:00".into(),
6927            days: vec!["mon-fri".into()],
6928        };
6929        assert!(rep.oneshot_instant(ScheduleTz::Utc).is_none());
6930    }
6931
6932    fn schedule_with_active(from: Option<&str>, until: Option<&str>) -> Schedule {
6933        let mut s = schedule_with(
6934            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6935            RunsOn::Backend,
6936        );
6937        s.active = Active {
6938            from: from.map(str::to_owned),
6939            until: until.map(str::to_owned),
6940        };
6941        s
6942    }
6943
6944    #[test]
6945    fn validate_accepts_active_window() {
6946        schedule_with_active(Some("2026-07-01"), Some("2026-08-01T12:00:00+09:00"))
6947            .validate()
6948            .expect("date + rfc3339 bounds should validate");
6949    }
6950
6951    #[test]
6952    fn validate_rejects_unparseable_active_bound() {
6953        let err = schedule_with_active(Some("July 1st"), None)
6954            .validate()
6955            .unwrap_err();
6956        assert!(err.contains("active"), "got: {err}");
6957    }
6958
6959    #[test]
6960    fn validate_rejects_from_not_before_until() {
6961        let err = schedule_with_active(Some("2026-08-01"), Some("2026-07-01"))
6962            .validate()
6963            .unwrap_err();
6964        assert!(err.contains("strictly before"), "got: {err}");
6965
6966        let err = schedule_with_active(Some("2026-07-01"), Some("2026-07-01"))
6967            .validate()
6968            .unwrap_err();
6969        assert!(err.contains("strictly before"), "got: {err}");
6970    }
6971
6972    // ---- Active window semantics ----
6973
6974    #[test]
6975    fn active_window_is_half_open() {
6976        use chrono::TimeZone;
6977        let active = Active {
6978            from: Some("2026-07-01".into()),
6979            until: Some("2026-08-01".into()),
6980        };
6981        // UTC tz so the date bounds are UTC midnight.
6982        let at = |y, m, d, h| chrono::Utc.with_ymd_and_hms(y, m, d, h, 0, 0).unwrap();
6983        let c = |t| active.contains(t, ScheduleTz::Utc);
6984        assert!(!c(at(2026, 6, 30, 23)), "before from");
6985        assert!(c(at(2026, 7, 1, 0)), "at from (inclusive)");
6986        assert!(c(at(2026, 7, 15, 12)), "inside");
6987        assert!(!c(at(2026, 8, 1, 0)), "at until (exclusive)");
6988        assert!(!c(at(2026, 8, 2, 0)), "after until");
6989    }
6990
6991    #[test]
6992    fn active_empty_window_is_always_active() {
6993        assert!(Active::default().contains(chrono::Utc::now(), ScheduleTz::Local));
6994    }
6995
6996    #[test]
6997    fn active_rfc3339_bound_honours_offset_regardless_of_tz() {
6998        use chrono::TimeZone;
6999        let active = Active {
7000            from: Some("2026-07-01T09:00:00+09:00".into()),
7001            until: None,
7002        };
7003        // RFC3339 carries its own offset → tz arg is ignored.
7004        // 09:00 JST = 00:00 UTC.
7005        for tz in [ScheduleTz::Utc, ScheduleTz::Local] {
7006            assert!(
7007                !active.contains(
7008                    chrono::Utc
7009                        .with_ymd_and_hms(2026, 6, 30, 23, 59, 0)
7010                        .unwrap(),
7011                    tz
7012                )
7013            );
7014            assert!(active.contains(
7015                chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap(),
7016                tz
7017            ));
7018        }
7019    }
7020
7021    #[test]
7022    fn active_date_bound_respects_tz() {
7023        // A bare `YYYY-MM-DD` bound is midnight *in the schedule's
7024        // tz* (#418 Phase 2). The UTC interpretation is exact and
7025        // host-independent; assert that precisely.
7026        use chrono::TimeZone;
7027        let utc = Active::parse_bound("2026-07-01", ScheduleTz::Utc).expect("utc");
7028        assert_eq!(
7029            utc,
7030            chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap()
7031        );
7032
7033        // The local interpretation must equal what chrono::Local
7034        // computes for the same wall-clock midnight — proves the tz
7035        // path is wired to the host zone (the magnitude vs UTC is
7036        // host-dependent, so we compare against Local directly rather
7037        // than hard-coding the JST offset, keeping CI green on UTC
7038        // runners).
7039        let local = Active::parse_bound("2026-07-01", ScheduleTz::Local).expect("local");
7040        let want = chrono::Local
7041            .with_ymd_and_hms(2026, 7, 1, 0, 0, 0)
7042            .single()
7043            .expect("local midnight is unambiguous")
7044            .with_timezone(&chrono::Utc);
7045        assert_eq!(local, want, "date bound resolved in host-local tz");
7046    }
7047
7048    #[test]
7049    fn active_empty_is_skipped_when_serialising() {
7050        let s = schedule_with(
7051            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7052            RunsOn::Backend,
7053        );
7054        let json = serde_json::to_value(&s).expect("serialise");
7055        assert!(
7056            json.get("active").is_none(),
7057            "empty active must not appear on the wire: {json}"
7058        );
7059    }
7060
7061    // ---- constraints.window (#418 Phase 3) ----
7062
7063    fn with_window(win: &str) -> Schedule {
7064        let mut s = schedule_with(
7065            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
7066            RunsOn::Backend,
7067        );
7068        s.constraints.window = Some(win.into());
7069        s
7070    }
7071
7072    #[test]
7073    fn constraints_window_parses_and_round_trips() {
7074        let yaml = r#"
7075id: x
7076when:
7077  per_pc: { every: 6h }
7078job_id: y
7079target: { all: true }
7080constraints:
7081  window: "22:00-05:00"
7082"#;
7083        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7084        assert_eq!(s.constraints.window.as_deref(), Some("22:00-05:00"));
7085        let back: Schedule =
7086            serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
7087        assert_eq!(back.constraints.window.as_deref(), Some("22:00-05:00"));
7088    }
7089
7090    #[test]
7091    fn constraints_empty_is_skipped_when_serialising() {
7092        let s = schedule_with(
7093            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7094            RunsOn::Backend,
7095        );
7096        let json = serde_json::to_value(&s).expect("serialise");
7097        assert!(
7098            json.get("constraints").is_none(),
7099            "empty constraints must not appear on the wire: {json}"
7100        );
7101    }
7102
7103    #[test]
7104    fn window_no_constraint_always_allows() {
7105        let c = Constraints::default();
7106        assert!(c.allows(chrono::Utc::now(), ScheduleTz::Local));
7107    }
7108
7109    #[test]
7110    fn window_same_day_is_half_open() {
7111        use chrono::TimeZone;
7112        let s = with_window("09:00-17:00");
7113        let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
7114        let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
7115        assert!(!a(at(8, 59)), "before start");
7116        assert!(a(at(9, 0)), "at start (inclusive)");
7117        assert!(a(at(16, 59)), "inside");
7118        assert!(!a(at(17, 0)), "at end (exclusive)");
7119        assert!(!a(at(23, 0)), "after end");
7120    }
7121
7122    #[test]
7123    fn window_crossing_midnight() {
7124        use chrono::TimeZone;
7125        let s = with_window("22:00-05:00");
7126        let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
7127        let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
7128        assert!(a(at(22, 0)), "at start tonight");
7129        assert!(a(at(23, 30)), "late tonight");
7130        assert!(a(at(3, 0)), "early tomorrow");
7131        assert!(!a(at(5, 0)), "at end (exclusive)");
7132        assert!(!a(at(12, 0)), "midday outside");
7133        assert!(!a(at(21, 59)), "just before start");
7134    }
7135
7136    #[test]
7137    fn window_respects_tz() {
7138        // The same instant is inside the window under one tz and may
7139        // be outside under another. Compare UTC vs Local via the
7140        // host's own offset (kept CI-green on UTC runners like the
7141        // active tz test does).
7142        use chrono::TimeZone;
7143        let s = with_window("09:00-17:00");
7144        let noon_utc = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 12, 0, 0).unwrap();
7145        // Under UTC, 12:00 is inside 09:00-17:00.
7146        assert!(s.constraints.allows(noon_utc, ScheduleTz::Utc));
7147        // Under Local, the verdict tracks the host wall-clock time;
7148        // assert it matches a direct wall_time membership check.
7149        let local_t = noon_utc.with_timezone(&chrono::Local).time();
7150        let in_local = local_t >= chrono::NaiveTime::from_hms_opt(9, 0, 0).unwrap()
7151            && local_t < chrono::NaiveTime::from_hms_opt(17, 0, 0).unwrap();
7152        assert_eq!(s.constraints.allows(noon_utc, ScheduleTz::Local), in_local);
7153    }
7154
7155    #[test]
7156    fn validate_accepts_good_window() {
7157        for w in ["09:00-17:00", "22:00-05:00", "00:00-23:59"] {
7158            with_window(w)
7159                .validate()
7160                .unwrap_or_else(|e| panic!("'{w}' should validate: {e}"));
7161        }
7162    }
7163
7164    #[test]
7165    fn validate_rejects_bad_window() {
7166        for bad in ["9-5", "22:00", "22:00-22:00", "25:00-05:00", "09:00_17:00"] {
7167            let err = with_window(bad).validate().unwrap_err();
7168            assert!(
7169                err.contains("constraints.window"),
7170                "for '{bad}', got: {err}"
7171            );
7172        }
7173    }
7174
7175    // ---- constraints.skip_dates (#418 holiday exclusion) ----
7176
7177    fn with_skip_dates(dates: &[&str]) -> Schedule {
7178        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
7179        s.tz = ScheduleTz::Utc; // host-independent date assertions
7180        s.constraints.skip_dates = dates.iter().map(|d| (*d).to_string()).collect();
7181        s
7182    }
7183
7184    #[test]
7185    fn allows_blocks_listed_skip_date() {
7186        use chrono::TimeZone;
7187        let s = with_skip_dates(&["2026-06-10", "2026-12-25"]);
7188        // Any time on a listed date is blocked (whole day).
7189        let on = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap();
7190        assert!(!s.constraints.allows(on, ScheduleTz::Utc));
7191        let on_midnight = chrono::Utc.with_ymd_and_hms(2026, 12, 25, 0, 0, 0).unwrap();
7192        assert!(!s.constraints.allows(on_midnight, ScheduleTz::Utc));
7193        // A date not in the list fires normally.
7194        let off = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
7195        assert!(s.constraints.allows(off, ScheduleTz::Utc));
7196    }
7197
7198    #[test]
7199    fn allows_corrupt_skip_date_fails_closed() {
7200        use chrono::TimeZone;
7201        // A garbled entry (only reachable via hand-edited KV) blocks
7202        // rather than silently re-enabling fires — same posture as a
7203        // corrupt window.
7204        let s = with_skip_dates(&["not-a-date"]);
7205        let any = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
7206        assert!(!s.constraints.allows(any, ScheduleTz::Utc));
7207    }
7208
7209    #[test]
7210    fn validate_accepts_good_skip_dates() {
7211        with_skip_dates(&["2026-01-01", "2026-12-25", "2027-05-03"])
7212            .validate()
7213            .expect("well-formed skip dates should validate");
7214    }
7215
7216    #[test]
7217    fn validate_rejects_bad_skip_date() {
7218        for bad in ["2026-13-01", "01-01-2026", "nope", "2026/01/01"] {
7219            let err = with_skip_dates(&[bad]).validate().unwrap_err();
7220            assert!(
7221                err.contains("constraints.skip_dates"),
7222                "for '{bad}', got: {err}"
7223            );
7224        }
7225    }
7226
7227    #[test]
7228    fn preview_skips_holidays() {
7229        use chrono::TimeZone;
7230        // Daily 09:00 with two of the next five days marked as holidays
7231        // — preview drops exactly those, since it gates on `allows`.
7232        let mut s = cal_utc("09:00", &[]);
7233        s.constraints.skip_dates = vec!["2026-06-11".into(), "2026-06-13".into()];
7234        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
7235        let got = s.preview_fires(now, 4);
7236        let want: Vec<_> = [
7237            (2026, 6, 10),
7238            (2026, 6, 12), // skips 06-11
7239            (2026, 6, 14), // skips 06-13
7240            (2026, 6, 15),
7241        ]
7242        .iter()
7243        .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
7244        .collect();
7245        assert_eq!(got, want);
7246    }
7247
7248    // ---- constraints.max_concurrent (#418) ----
7249
7250    fn with_max_concurrent(max: u32, runs_on: RunsOn) -> Schedule {
7251        let mut s = schedule_with(
7252            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
7253            runs_on,
7254        );
7255        s.constraints.max_concurrent = Some(max);
7256        s
7257    }
7258
7259    #[test]
7260    fn validate_accepts_backend_max_concurrent() {
7261        with_max_concurrent(5, RunsOn::Backend)
7262            .validate()
7263            .expect("backend max_concurrent should validate");
7264    }
7265
7266    #[test]
7267    fn validate_rejects_max_concurrent_on_agent() {
7268        // Decision E: a central running-instance cap needs a central
7269        // counter, which agents don't have.
7270        let err = with_max_concurrent(5, RunsOn::Agent)
7271            .validate()
7272            .unwrap_err();
7273        assert!(err.contains("constraints.max_concurrent"), "got: {err}");
7274        assert!(err.contains("runs_on: agent"), "got: {err}");
7275    }
7276
7277    #[test]
7278    fn validate_rejects_zero_max_concurrent() {
7279        let err = with_max_concurrent(0, RunsOn::Backend)
7280            .validate()
7281            .unwrap_err();
7282        assert!(err.contains("max_concurrent must be >= 1"), "got: {err}");
7283    }
7284
7285    #[test]
7286    fn max_concurrent_round_trips_and_skips_when_absent() {
7287        let s = with_max_concurrent(3, RunsOn::Backend);
7288        let json = serde_json::to_value(&s.constraints).expect("ser");
7289        assert_eq!(json.get("max_concurrent").and_then(|v| v.as_u64()), Some(3));
7290        // A schedule with no constraints omits the whole block.
7291        let bare = schedule_with(
7292            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7293            RunsOn::Backend,
7294        );
7295        assert!(bare.constraints.is_empty());
7296    }
7297
7298    #[test]
7299    fn window_fail_closed_on_corrupt_blob() {
7300        // A malformed window (only reachable via a hand-edited KV
7301        // blob — validate() rejects it at create) must BLOCK, not
7302        // silently allow fires during a change-freeze (gemini #452).
7303        let s = with_window("22:00_05:00");
7304        assert!(
7305            !s.constraints.allows(chrono::Utc::now(), ScheduleTz::Utc),
7306            "corrupt window fails closed"
7307        );
7308        // …and the scheduler can surface why it's stuck.
7309        assert!(
7310            s.bad_window().is_some(),
7311            "bad_window reports the parse error"
7312        );
7313        assert!(with_window("22:00-05:00").bad_window().is_none());
7314    }
7315
7316    #[test]
7317    fn calendar_outside_window_is_flagged() {
7318        // at 09:00 can never fall in 22:00-05:00 → never fires.
7319        let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
7320        s.constraints.window = Some("22:00-05:00".into());
7321        assert!(s.calendar_outside_window(), "09:00 is not in 22:00-05:00");
7322
7323        // at 23:00 IS inside the overnight window → fine.
7324        let mut s = schedule_with(calendar("23:00", &[]), RunsOn::Backend);
7325        s.constraints.window = Some("22:00-05:00".into());
7326        assert!(!s.calendar_outside_window(), "23:00 is in 22:00-05:00");
7327
7328        // reconcile shapes are never flagged (they poll every minute).
7329        let mut s = schedule_with(
7330            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
7331            RunsOn::Backend,
7332        );
7333        s.constraints.window = Some("22:00-05:00".into());
7334        assert!(!s.calendar_outside_window(), "reconcile is unaffected");
7335
7336        // no window → never flagged.
7337        let s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
7338        assert!(!s.calendar_outside_window());
7339    }
7340
7341    // ---- on_failure.retry (#418 Phase 4) ----
7342
7343    fn with_retry(max: u32, backoff: &str) -> Schedule {
7344        let mut s = schedule_with(
7345            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
7346            RunsOn::Backend,
7347        );
7348        s.on_failure.retry = Some(Retry {
7349            max,
7350            backoff: backoff.into(),
7351        });
7352        s
7353    }
7354
7355    #[test]
7356    fn on_failure_parses_and_round_trips() {
7357        let yaml = r#"
7358id: x
7359when:
7360  per_pc: { every: 6h }
7361job_id: y
7362target: { all: true }
7363on_failure:
7364  retry: { max: 3, backoff: 10m }
7365"#;
7366        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7367        let r = s.on_failure.retry.as_ref().expect("retry present");
7368        assert_eq!(r.max, 3);
7369        assert_eq!(r.backoff, "10m");
7370        let back: Schedule =
7371            serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
7372        assert_eq!(back.on_failure, s.on_failure);
7373    }
7374
7375    #[test]
7376    fn on_failure_empty_is_skipped_when_serialising() {
7377        let s = schedule_with(
7378            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7379            RunsOn::Backend,
7380        );
7381        let json = serde_json::to_value(&s).expect("serialise");
7382        assert!(
7383            json.get("on_failure").is_none(),
7384            "empty on_failure must not appear on the wire: {json}"
7385        );
7386    }
7387
7388    #[test]
7389    fn validate_accepts_good_retry() {
7390        for (max, backoff) in [(1, "30s"), (3, "10m"), (10, "1h")] {
7391            with_retry(max, backoff)
7392                .validate()
7393                .unwrap_or_else(|e| panic!("retry {{max:{max}, backoff:{backoff}}}: {e}"));
7394        }
7395    }
7396
7397    #[test]
7398    fn validate_rejects_bad_backoff() {
7399        let err = with_retry(3, "soon").validate().unwrap_err();
7400        assert!(err.contains("on_failure.retry.backoff"), "got: {err}");
7401    }
7402
7403    #[test]
7404    fn validate_rejects_sub_second_backoff() {
7405        // "500ms" parses as humantime but lowers to 0s on the wire —
7406        // reject it so the operator doesn't get a silent no-wait
7407        // (coderabbit #466).
7408        for bad in ["500ms", "0s", "999ms"] {
7409            let err = with_retry(3, bad).validate().unwrap_err();
7410            assert!(
7411                err.contains("on_failure.retry.backoff must be >= 1s"),
7412                "for '{bad}', got: {err}"
7413            );
7414        }
7415    }
7416
7417    #[test]
7418    fn validate_rejects_out_of_range_max() {
7419        for bad in [0u32, 11, 1000] {
7420            let err = with_retry(bad, "10m").validate().unwrap_err();
7421            assert!(
7422                err.contains("on_failure.retry.max"),
7423                "for max={bad}, got: {err}"
7424            );
7425        }
7426    }
7427
7428    #[test]
7429    fn lowered_retry_reduces_backoff_to_seconds() {
7430        let s = with_retry(3, "10m");
7431        let spec = s.on_failure.lowered_retry().expect("a retry policy");
7432        assert_eq!(spec.max, 3);
7433        assert_eq!(spec.backoff_secs, 600);
7434    }
7435
7436    #[test]
7437    fn lowered_retry_is_none_without_policy() {
7438        let s = schedule_with(
7439            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7440            RunsOn::Backend,
7441        );
7442        assert!(s.on_failure.lowered_retry().is_none());
7443    }
7444
7445    // ---- global change-freeze (#418 Phase 5) ----
7446
7447    #[test]
7448    fn freeze_empty_window_is_always_active() {
7449        // The big-red-button shape: no bounds = frozen until cleared.
7450        let f = Freeze::default();
7451        assert!(f.is_active(chrono::Utc::now()));
7452    }
7453
7454    #[test]
7455    fn freeze_window_is_half_open() {
7456        use chrono::TimeZone;
7457        let f = Freeze {
7458            from: Some("2026-12-20T00:00:00+00:00".into()),
7459            until: Some("2027-01-05T00:00:00+00:00".into()),
7460            reason: Some("year-end".into()),
7461            tz: ScheduleTz::Utc,
7462        };
7463        let at = |y, mo, d| chrono::Utc.with_ymd_and_hms(y, mo, d, 0, 0, 0).unwrap();
7464        assert!(!f.is_active(at(2026, 12, 19)), "before from = not frozen");
7465        assert!(f.is_active(at(2026, 12, 20)), "from is inclusive");
7466        assert!(f.is_active(at(2026, 12, 31)), "inside window");
7467        assert!(!f.is_active(at(2027, 1, 5)), "until is exclusive");
7468        assert!(!f.is_active(at(2027, 1, 6)), "after until = not frozen");
7469    }
7470
7471    #[test]
7472    fn freeze_fails_closed_on_corrupt_bound() {
7473        // A freeze is a safety switch: an unparseable bound (only
7474        // reachable via a hand-edited KV blob) must read as FROZEN, not
7475        // "fire normally" (coderabbit #472) — the opposite of `active`,
7476        // which fail-opens.
7477        let f = Freeze {
7478            from: Some("not-a-date".into()),
7479            until: None,
7480            reason: None,
7481            tz: ScheduleTz::Utc,
7482        };
7483        assert!(f.is_active(chrono::Utc::now()), "corrupt bound → frozen");
7484    }
7485
7486    #[test]
7487    fn freeze_validate_accepts_good_bounds() {
7488        Freeze {
7489            from: Some("2026-12-20".into()),
7490            until: Some("2027-01-05T12:00:00+09:00".into()),
7491            reason: None,
7492            tz: ScheduleTz::Local,
7493        }
7494        .validate()
7495        .expect("date + rfc3339 bounds should validate");
7496        // Empty (indefinite) freeze is valid.
7497        Freeze::default().validate().expect("empty freeze is valid");
7498    }
7499
7500    #[test]
7501    fn freeze_validate_rejects_bad_bound_and_inverted_window() {
7502        let err = Freeze {
7503            from: Some("never".into()),
7504            ..Default::default()
7505        }
7506        .validate()
7507        .unwrap_err();
7508        assert!(err.contains("freeze:"), "got: {err}");
7509
7510        let inverted = Freeze {
7511            from: Some("2027-01-05".into()),
7512            until: Some("2026-12-20".into()),
7513            ..Default::default()
7514        }
7515        .validate()
7516        .unwrap_err();
7517        assert!(inverted.contains("freeze.from"), "got: {inverted}");
7518    }
7519
7520    #[test]
7521    fn freeze_round_trips_and_skips_empty_fields() {
7522        let f = Freeze {
7523            from: None,
7524            until: Some("2027-01-05".into()),
7525            reason: Some("INC-1234".into()),
7526            tz: ScheduleTz::Utc,
7527        };
7528        let json = serde_json::to_value(&f).expect("serialise");
7529        assert!(json.get("from").is_none(), "empty from omitted: {json}");
7530        let back: Freeze = serde_json::from_value(json).expect("round-trip");
7531        assert_eq!(back, f);
7532    }
7533
7534    #[test]
7535    fn shipped_schedule_configs_parse_and_validate() {
7536        // Every YAML under configs/schedules/ must parse with the
7537        // current Schedule serde AND pass validate() — keeps the
7538        // shipped examples from drifting out of sync with the model
7539        // (#418 removed back-compat, so drift = broken at create).
7540        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../configs/schedules");
7541        let mut seen = 0;
7542        for entry in std::fs::read_dir(&dir).expect("read configs/schedules") {
7543            let path = entry.expect("dir entry").path();
7544            if path.extension().and_then(|e| e.to_str()) != Some("yaml") {
7545                continue;
7546            }
7547            let body = std::fs::read_to_string(&path).expect("read yaml");
7548            let s: Schedule = serde_yaml::from_str(&body)
7549                .unwrap_or_else(|e| panic!("{} failed to parse: {e}", path.display()));
7550            s.validate()
7551                .unwrap_or_else(|e| panic!("{} failed validate(): {e}", path.display()));
7552            seen += 1;
7553        }
7554        assert!(seen > 0, "no schedule YAMLs found in {}", dir.display());
7555    }
7556
7557    // ---- pre-existing enum wire formats (unchanged by #418) ----
7558
7559    #[test]
7560    fn exec_mode_serialises_snake_case() {
7561        for (mode, expected) in [
7562            (ExecMode::EveryTick, "every_tick"),
7563            (ExecMode::OncePerPc, "once_per_pc"),
7564            (ExecMode::OncePerTarget, "once_per_target"),
7565        ] {
7566            let s = serde_json::to_value(mode).expect("serialise");
7567            assert_eq!(s, serde_json::Value::String(expected.into()));
7568            let back: ExecMode = serde_json::from_value(serde_json::Value::String(expected.into()))
7569                .expect("deserialise");
7570            assert_eq!(back, mode, "round-trip for {expected}");
7571        }
7572    }
7573
7574    #[test]
7575    fn schedule_runs_on_defaults_to_backend() {
7576        let yaml = r#"
7577id: x
7578when:
7579  per_pc: once
7580job_id: y
7581target: { all: true }
7582"#;
7583        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7584        assert_eq!(s.runs_on, RunsOn::Backend);
7585    }
7586
7587    #[test]
7588    fn schedule_runs_on_agent_parses() {
7589        let yaml = r#"
7590id: offline-inv
7591when:
7592  per_pc: { every: 1h }
7593job_id: inventory-hw
7594target: { all: true }
7595runs_on: agent
7596"#;
7597        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7598        assert_eq!(s.runs_on, RunsOn::Agent);
7599        assert_eq!(s.lowered().mode, ExecMode::OncePerPc);
7600    }
7601
7602    #[test]
7603    fn runs_on_serialises_snake_case() {
7604        for (mode, expected) in [(RunsOn::Backend, "backend"), (RunsOn::Agent, "agent")] {
7605            let s = serde_json::to_value(mode).expect("serialise");
7606            assert_eq!(s, serde_json::Value::String(expected.into()));
7607            let back: RunsOn = serde_json::from_value(serde_json::Value::String(expected.into()))
7608                .expect("deserialise");
7609            assert_eq!(back, mode);
7610        }
7611    }
7612
7613    #[test]
7614    fn execute_shell_into_wire_shell() {
7615        assert_eq!(Shell::from(ExecuteShell::Powershell), Shell::Powershell);
7616        assert_eq!(Shell::from(ExecuteShell::Cmd), Shell::Cmd);
7617        assert_eq!(Shell::from(ExecuteShell::Sh), Shell::Sh);
7618        assert_eq!(Shell::from(ExecuteShell::Pwsh), Shell::Pwsh);
7619    }
7620
7621    #[test]
7622    fn execute_shell_parses_sh_and_pwsh() {
7623        // The manifest `execute.shell` accepts the two new lowercase
7624        // tokens end-to-end (serde), so an operator can author a Linux
7625        // job.
7626        for (yaml_shell, want) in [("sh", ExecuteShell::Sh), ("pwsh", ExecuteShell::Pwsh)] {
7627            let yaml = format!(
7628                "id: x\nversion: 1.0.0\nexecute:\n  shell: {yaml_shell}\n  script: \"echo\"\n  timeout: 1s\n"
7629            );
7630            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
7631            assert_eq!(m.execute.shell, want, "shell {yaml_shell}");
7632        }
7633    }
7634
7635    #[test]
7636    fn manifest_staleness_defaults_to_cached() {
7637        let yaml = r#"
7638id: x
7639version: 1.0.0
7640execute:
7641  shell: powershell
7642  script: "echo"
7643  timeout: 1s
7644"#;
7645        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7646        assert_eq!(m.staleness, Staleness::Cached);
7647    }
7648
7649    #[test]
7650    fn manifest_strict_staleness_parses() {
7651        let yaml = r#"
7652id: urgent-patch
7653version: 2.5.1
7654execute:
7655  shell: powershell
7656  script: Install-Hotfix
7657  timeout: 5m
7658staleness:
7659  mode: strict
7660  max_cache_age: 0s
7661"#;
7662        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7663        match m.staleness {
7664            Staleness::Strict { max_cache_age } => assert_eq!(max_cache_age, "0s"),
7665            other => panic!("expected strict, got {other:?}"),
7666        }
7667    }
7668
7669    #[test]
7670    fn manifest_unchecked_staleness_parses() {
7671        let yaml = r#"
7672id: legacy
7673version: 0.1.0
7674execute:
7675  shell: cmd
7676  script: "echo"
7677  timeout: 1s
7678staleness:
7679  mode: unchecked
7680"#;
7681        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7682        assert_eq!(m.staleness, Staleness::Unchecked);
7683    }
7684
7685    #[test]
7686    fn missing_required_field_errors() {
7687        // `id` missing.
7688        let yaml = r#"
7689version: 1.0.0
7690target: { all: true }
7691execute:
7692  shell: powershell
7693  script: "echo"
7694  timeout: 1s
7695"#;
7696        let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
7697        assert!(r.is_err(), "expected error, got {:?}", r);
7698    }
7699
7700    #[test]
7701    fn display_field_table_kind_round_trips_with_nested_columns() {
7702        // #39: `type: table` + `columns:` on a DisplayField gets
7703        // round-tripped through serde so the SPA receives the
7704        // nested schema verbatim. Nested columns themselves are
7705        // DisplayFields so they can carry `type: bytes` /
7706        // `type: number` for cell formatting.
7707        let yaml = r#"
7708id: inv-hw
7709version: 1.0.0
7710execute:
7711  shell: powershell
7712  script: "echo"
7713  timeout: 60s
7714inventory:
7715  display:
7716    - field: hostname
7717      label: Hostname
7718    - field: disks
7719      label: Disks
7720      type: table
7721      columns:
7722        - field: device_id
7723          label: Drive
7724        - field: size_bytes
7725          label: Size
7726          type: bytes
7727        - field: free_bytes
7728          label: Free
7729          type: bytes
7730        - field: file_system
7731          label: FS
7732"#;
7733        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7734        let inv = m.inventory.as_ref().expect("inventory hint");
7735        let disks = inv
7736            .display
7737            .iter()
7738            .find(|d| d.field == "disks")
7739            .expect("disks display row");
7740        assert_eq!(disks.kind.as_deref(), Some("table"));
7741        let cols = disks.columns.as_ref().expect("table needs columns");
7742        assert_eq!(cols.len(), 4);
7743        assert_eq!(cols[1].field, "size_bytes");
7744        assert_eq!(cols[1].kind.as_deref(), Some("bytes"));
7745    }
7746
7747    #[test]
7748    fn display_field_scalar_kind_keeps_columns_none() {
7749        // Defensive: when type is a scalar (`bytes` / `number` /
7750        // `timestamp`) the `columns` field stays None — the SPA
7751        // uses its presence as the "render nested table" signal,
7752        // so it must not leak in via serde defaults.
7753        let yaml = r#"
7754id: x
7755version: 1.0.0
7756execute:
7757  shell: powershell
7758  script: "echo"
7759  timeout: 5s
7760inventory:
7761  display:
7762    - { field: ram_bytes, label: RAM, type: bytes }
7763"#;
7764        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7765        let inv = m.inventory.as_ref().unwrap();
7766        assert!(inv.display[0].columns.is_none());
7767    }
7768
7769    // ---- GroupDef (#1032 dynamic groups) ----
7770
7771    fn group_def(yaml: &str) -> Result<GroupDef, String> {
7772        let g: GroupDef = crate::strict::from_yaml_str(yaml).map_err(|e| e.to_string())?;
7773        g.validate().map(|()| g)
7774    }
7775
7776    #[test]
7777    fn group_def_static_members_valid() {
7778        let g = group_def("id: pilot\nmembers: [PC-A, PC-B]\n").expect("valid static group");
7779        assert_eq!(g.members, vec!["PC-A", "PC-B"]);
7780        assert!(g.dynamic_query().is_none());
7781    }
7782
7783    #[test]
7784    fn group_def_dynamic_query_valid() {
7785        let g = group_def(
7786            "id: clients\nquery: \"SELECT pc_id FROM agents WHERE hostname LIKE 'X%'\"\nrefresh: 30m\n",
7787        )
7788        .expect("valid dynamic group");
7789        assert_eq!(
7790            g.dynamic_query(),
7791            Some("SELECT pc_id FROM agents WHERE hostname LIKE 'X%'")
7792        );
7793        assert_eq!(g.refresh_interval(), std::time::Duration::from_secs(1800));
7794    }
7795
7796    #[test]
7797    fn group_def_refresh_defaults_when_absent() {
7798        let g = group_def("id: c\nquery: \"SELECT pc_id FROM agents\"\n").unwrap();
7799        assert_eq!(g.refresh_interval(), DEFAULT_GROUP_REFRESH);
7800    }
7801
7802    #[test]
7803    fn group_def_rejects_neither_members_nor_query() {
7804        let err = group_def("id: empty\n").unwrap_err();
7805        assert!(err.contains("either"), "err: {err}");
7806    }
7807
7808    #[test]
7809    fn group_def_rejects_both_members_and_query() {
7810        let err = group_def("id: both\nmembers: [PC-A]\nquery: \"SELECT pc_id FROM agents\"\n")
7811            .unwrap_err();
7812        assert!(err.contains("mutually exclusive"), "err: {err}");
7813    }
7814
7815    #[test]
7816    fn group_def_blank_query_is_unset_not_both() {
7817        // An empty-string query reads as unset, so a members group with a
7818        // commented-out (emptied) query is still valid, not a "both set" error.
7819        let g =
7820            group_def("id: pilot\nmembers: [PC-A]\nquery: \"\"\n").expect("blank query = unset");
7821        assert!(g.dynamic_query().is_none());
7822    }
7823
7824    #[test]
7825    fn group_def_rejects_bad_id_charset() {
7826        let err = group_def("id: bad/id\nmembers: [PC-A]\n").unwrap_err();
7827        assert!(err.contains("group.id"), "err: {err}");
7828    }
7829
7830    #[test]
7831    fn group_def_rejects_untrimmed_id() {
7832        // A padded id validated-as-trimmed but stored-raw would be a KV key
7833        // nothing matches — reject it outright (the id is used verbatim).
7834        let err = group_def("id: \" clients \"\nmembers: [PC-A]\n").unwrap_err();
7835        assert!(err.contains("group.id"), "err: {err}");
7836    }
7837
7838    #[test]
7839    fn group_def_rejects_bad_refresh() {
7840        let err =
7841            group_def("id: c\nquery: \"SELECT pc_id FROM agents\"\nrefresh: soon\n").unwrap_err();
7842        assert!(err.contains("refresh"), "err: {err}");
7843    }
7844
7845    #[test]
7846    fn group_def_rejects_unknown_key() {
7847        // Strict parse (#492) — a typo'd key is an operator error, not silently
7848        // dropped.
7849        let err = group_def("id: c\nmembers: [PC-A]\nrlue: x\n").unwrap_err();
7850        assert!(err.to_lowercase().contains("unknown"), "err: {err}");
7851    }
7852
7853    // ---- checked-in JSON Schema freshness (docs/schemas/) ----
7854
7855    /// The JSON Schemas under `docs/schemas/` must match what
7856    /// `schema_for!` produces today — a Cargo.lock-style freshness guard
7857    /// so a `Schedule` / `Manifest` field change can't silently drift
7858    /// the operator-facing schema. The SPA editor, the backend
7859    /// `/api/schemas/*` endpoints, and these files all read the same
7860    /// derived shape; this test fails CI if the checked-in copy lags.
7861    /// Regenerate with:
7862    ///   `UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current`
7863    #[test]
7864    fn schema_files_are_current() {
7865        assert_schema_file("schedule.schema.json", &schemars::schema_for!(Schedule));
7866        assert_schema_file("job.schema.json", &schemars::schema_for!(Manifest));
7867        assert_schema_file("view.schema.json", &schemars::schema_for!(View));
7868        assert_schema_file("group-def.schema.json", &schemars::schema_for!(GroupDef));
7869    }
7870
7871    fn assert_schema_file(name: &str, schema: &schemars::Schema) {
7872        let generated = serde_json::to_string_pretty(schema).expect("serialize schema") + "\n";
7873        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7874            .join("../../docs/schemas")
7875            .join(name);
7876        if std::env::var_os("UPDATE_SCHEMAS").is_some() {
7877            std::fs::create_dir_all(path.parent().unwrap()).expect("mkdir docs/schemas");
7878            std::fs::write(&path, &generated).unwrap_or_else(|e| panic!("write {path:?}: {e}"));
7879            return;
7880        }
7881        // Normalize CRLF→LF before comparing: `.gitattributes` already
7882        // pins these files to `eol=lf`, but a stray CRLF working-tree
7883        // copy (autocrlf, a tool rewrite) shouldn't turn a *content*-
7884        // freshness check into a confusing line-ending failure — that's
7885        // .gitattributes' job, not this test's (gemini #588).
7886        let on_disk = std::fs::read_to_string(&path)
7887            .unwrap_or_else(|e| {
7888                panic!(
7889                    "read {path:?}: {e}\n\
7890                     generate it with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
7891                )
7892            })
7893            .replace("\r\n", "\n");
7894        assert_eq!(
7895            on_disk, generated,
7896            "{name} is stale — a Schedule/Manifest schema change isn't reflected in docs/schemas/. \
7897             Refresh with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
7898        );
7899    }
7900}
7901
7902/// Periodic schedule (spec §2.4.3). v0.18.0 carries the fanout plan
7903/// (target + optional rollout + optional jitter) inline; the
7904/// referenced job (`job_id` → [`BUCKET_JOBS`]) supplies only the
7905/// script body. Two schedules of the same job can target different
7906/// groups on different cadences without copying the manifest.
7907///
7908/// #418 Phase 1: the cadence is the single [`When`] field. The old
7909/// `cron` × `mode` × `cooldown` × `auto_disable_when_done` quartet
7910/// is gone (no back-compat — pre-Phase-1 KV blobs fail to parse and
7911/// are warn-skipped; re-`schedule create` to upgrade them). The
7912/// engine underneath is unchanged: [`Schedule::lowered`] maps `when`
7913/// onto the same (cron, ExecMode, cooldown) trio the scheduler and
7914/// `decide_fire` always ran on.
7915#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
7916pub struct Schedule {
7917    pub id: String,
7918    /// When to fire — a reconcile cadence (`per_pc` / `per_target`)
7919    /// or a calendar time trigger (`at` / `days`). See [`When`].
7920    ///
7921    /// `singleton_map`: serde_yaml 0.9 renders externally-tagged
7922    /// enums as `!per_pc` YAML tags by default; this keeps the
7923    /// operator-facing map shape (`when: { per_pc: once }`). JSON
7924    /// output is identical either way, and the schemars schema
7925    /// (external tagging = oneOf of single-key objects) already
7926    /// matches the singleton-map wire shape.
7927    #[serde(with = "serde_yaml::with::singleton_map")]
7928    #[schemars(with = "When")]
7929    pub when: When,
7930    /// Key into [`crate::kv::BUCKET_JOBS`]. Must equal a registered
7931    /// Manifest's `id`.
7932    pub job_id: String,
7933    /// Who + how-to-phase + when-to-stagger. The Manifest doesn't
7934    /// carry these any more — same job + different fanout = different
7935    /// schedule.
7936    #[serde(flatten)]
7937    pub plan: FanoutPlan,
7938    /// Optional validity window. Outside `[from, until)` the
7939    /// schedule is dormant — still registered, still visible, but
7940    /// every tick is skipped (deleted ≠ dormant: a campaign that
7941    /// ended stays inspectable and can be re-armed by editing the
7942    /// window). Checked at tick time on both the backend scheduler
7943    /// and the agent's local scheduler.
7944    #[serde(default, skip_serializing_if = "Active::is_empty")]
7945    pub active: Active,
7946    /// #418 operational constraints gating *when within an active
7947    /// period* a fire may happen: a maintenance `window`, a fleet
7948    /// `max_concurrent` cap, and `skip_dates` (holiday exclusion). The
7949    /// wall-clock ones are evaluated in the schedule's `tz`; future
7950    /// `require` (env gates) lands in the same namespace. Checked at
7951    /// tick time on both schedulers (and surfaced by `preview`).
7952    #[serde(default, skip_serializing_if = "Constraints::is_empty")]
7953    pub constraints: Constraints,
7954    /// #418 Phase 4: what to do after a fire's script comes back
7955    /// failed. Currently just `retry` (fixed-backoff in-process
7956    /// re-run); future `notify` / `disable` join the same namespace.
7957    /// Applied fire-side in `handle_command` (the retry policy is
7958    /// lowered onto every Command this schedule produces), so it
7959    /// covers both `runs_on` locations.
7960    #[serde(default, skip_serializing_if = "OnFailure::is_empty")]
7961    pub on_failure: OnFailure,
7962    /// #418 Phase 2: the timezone this schedule's wall-clock fields
7963    /// are evaluated in — both the calendar `at` firing time AND the
7964    /// `active.{from,until}` window bounds. `local` (default) = the
7965    /// running host's TZ (the agent's for `runs_on: agent`, the
7966    /// backend server's otherwise); `utc` for TZ-independent
7967    /// schedules. Reconcile shapes (`per_pc`/`per_target`) ignore it
7968    /// for firing (poll cron runs every minute regardless) but still
7969    /// honor it for the `active` window.
7970    #[serde(default)]
7971    pub tz: ScheduleTz,
7972    /// v0.22: optional humantime window after a cron tick during
7973    /// which the Command is still considered "live". The scheduler
7974    /// computes `tick_at + starting_deadline` and stamps it onto
7975    /// each Command as `deadline_at`; agents skip Commands they
7976    /// receive after that absolute time. `None` (default) = no
7977    /// deadline, meaning a Command queued in the broker / stream
7978    /// during agent downtime runs whenever the agent reconnects —
7979    /// good for kitting / inventory / cleanup. Set this for
7980    /// time-of-day notifications, lunch reminders, etc., where
7981    /// "fire 3 hours late" would be wrong.
7982    #[serde(default, skip_serializing_if = "Option::is_none")]
7983    pub starting_deadline: Option<String>,
7984    /// v0.23: where does the cron tick happen? `Backend` (default,
7985    /// historical) = backend's scheduler fires Commands via NATS;
7986    /// agents passively receive. `Agent` = each targeted agent runs
7987    /// its own internal cron and fires locally, so the schedule
7988    /// keeps ticking even when the broker is unreachable (laptop on
7989    /// the train, broker maintenance window, full WAN outage). The
7990    /// two locations are mutually exclusive — when `Agent`, the
7991    /// backend scheduler stays out and just keeps the definition in
7992    /// KV for agents to read.
7993    #[serde(default)]
7994    pub runs_on: RunsOn,
7995    #[serde(default = "default_true")]
7996    pub enabled: bool,
7997    /// Free-form operator taxonomy for the Schedules page — the
7998    /// schedule-side mirror of `Manifest.tags` (added in #640; a plain
7999    /// code ref rather than an intra-doc link, since that field isn't
8000    /// on this branch until #640 merges). Purely a SPA-side
8001    /// organisational aid (search / filter chips alongside the
8002    /// id-prefix grouping); the scheduler never reads it, so any
8003    /// string is allowed and it carries no firing semantics. A
8004    /// schedule's own tags are independent of its job's: the same job
8005    /// may back a `weekly` maintenance schedule and a `canary` rollout
8006    /// schedule. Empty by default and `skip_serializing_if`-elided per
8007    /// the #492 gradual-upgrade wire rule.
8008    #[serde(default, skip_serializing_if = "Vec::is_empty")]
8009    pub tags: Vec<String>,
8010    /// GitOps provenance (#695) — see [`RepoOrigin`]. Stamped by
8011    /// `kanade schedule create` when the source YAML lives inside a Git
8012    /// work tree, so the SPA renders the schedule read-only and points
8013    /// edits back at the repo (SPEC design principle #3: 設定駆動 YAML +
8014    /// Git), parity with a job's [`Manifest::origin`]. `None` for
8015    /// SPA-born schedules and ones applied from outside any repo. Purely
8016    /// informational — the scheduler never reads it. New field ⇒ #492
8017    /// wire rule (`default` + `skip_serializing_if`).
8018    #[serde(default, skip_serializing_if = "Option::is_none")]
8019    pub origin: Option<RepoOrigin>,
8020}
8021
8022impl Schedule {
8023    /// Every valid top-level key on a Schedule YAML/JSON document —
8024    /// this struct's own fields PLUS the fields of the
8025    /// `#[serde(flatten)] plan: FanoutPlan`. The strict create
8026    /// boundary needs this because serde's flatten buffering hides
8027    /// unknown top-level keys from `serde_ignored`, so a typo like
8028    /// `jiter:` or `enabledd:` would otherwise be silently dropped
8029    /// (#924). Kept in sync with the field list by
8030    /// `schedule_top_level_keys_cover_serialized_fields`.
8031    pub const TOP_LEVEL_KEYS: &'static [&'static str] = &[
8032        // Schedule's own fields:
8033        "id",
8034        "when",
8035        "job_id",
8036        "active",
8037        "constraints",
8038        "on_failure",
8039        "tz",
8040        "starting_deadline",
8041        "runs_on",
8042        "enabled",
8043        "tags",
8044        "origin",
8045        // flattened FanoutPlan:
8046        "target",
8047        "rollout",
8048        "jitter",
8049        "deadline_at",
8050    ];
8051}
8052
8053impl crate::strict::StrictSchema for Schedule {
8054    fn strict_top_level_keys() -> Option<&'static [&'static str]> {
8055        Some(Self::TOP_LEVEL_KEYS)
8056    }
8057}
8058
8059/// Manifest has no `#[serde(flatten)]` field, so `serde_ignored`
8060/// already catches every top-level typo — the default (`None`) is
8061/// correct.
8062impl crate::strict::StrictSchema for Manifest {}
8063
8064/// View likewise has no flattened field.
8065impl crate::strict::StrictSchema for View {}
8066
8067/// GroupDef likewise has no flattened field.
8068impl crate::strict::StrictSchema for GroupDef {}
8069
8070/// v0.23 — where the cron tick fires from.
8071#[derive(
8072    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
8073)]
8074#[serde(rename_all = "snake_case")]
8075pub enum RunsOn {
8076    /// Backend's central scheduler ticks and publishes Commands to
8077    /// NATS. Historical default, what every pre-v0.23 schedule
8078    /// uses. Agent offline ⇒ Command queued in STREAM_EXEC; agent
8079    /// reconnects ⇒ catch-up via [`command_replay`](crate)
8080    /// (see kanade-agent's command_replay module).
8081    #[default]
8082    Backend,
8083    /// Each targeted agent runs the cron tick locally. Survives
8084    /// broker / WAN outages. Best for laptops / mobile devices that
8085    /// roam off the corporate network. Agent must be online for the
8086    /// initial schedule + job-catalog pull, but once cached the
8087    /// agent fires the script standalone.
8088    Agent,
8089}
8090
8091/// Per-pc/per-target dedup semantics for a [`Schedule`] (v0.19).
8092#[derive(
8093    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
8094)]
8095#[serde(rename_all = "snake_case")]
8096pub enum ExecMode {
8097    /// Fire on every cron tick at the whole target. Historical
8098    /// (pre-v0.19) behavior; no dedup.
8099    #[default]
8100    EveryTick,
8101    /// Fire at each pc until that pc succeeds; then skip it until
8102    /// the optional cooldown elapses (or forever if no cooldown).
8103    /// Use for kitting / first-boot / per-pc compliance checks.
8104    OncePerPc,
8105    /// Fire at the whole target until **any** pc succeeds; then
8106    /// skip the whole target until the optional cooldown elapses
8107    /// (or forever if no cooldown). Use for "one delegate is
8108    /// enough" tasks like license check-in.
8109    OncePerTarget,
8110    /// Like [`OncePerPc`](ExecMode::OncePerPc), but the "already
8111    /// succeeded ⇒ skip" check is scoped to the CURRENT manifest
8112    /// version: a pc whose only successful run recorded an OLDER
8113    /// manifest version re-fires so the new version reaches it. Bumping
8114    /// the job's YAML `version` is the redistribution trigger. Plain
8115    /// `OncePerPc` (kitting) is version-blind — a pc that ever succeeded
8116    /// is skipped forever; this mode re-arms per version. per_pc only —
8117    /// `Schedule::validate` rejects `per_target: once_per_version`.
8118    OncePerPcVersion,
8119    /// #418 OS-native event trigger (`when: { on: [...] }`). There is
8120    /// no cron — the agent fires it from an OS event source (boot /
8121    /// session-change), not a tick — so the scheduler skips
8122    /// `tokio-cron` registration for it. Each event occurrence fires
8123    /// once, gated by the standard freeze / active / window /
8124    /// skip_dates checks.
8125    Event,
8126}
8127
8128/// #418 Phase 1 — the single "when does this fire" axis.
8129///
8130/// Replaces the old `cron` + `mode` + `cooldown` trio whose
8131/// interactions were implicit (cron doubled as both a real
8132/// time-of-day trigger and a reconcile poll period; contradictory
8133/// combinations silently no-opped). Two shapes:
8134///
8135/// * **reconcile** (`per_pc` / `per_target`) — desired-state: "each
8136///   pc (or one delegate) should have run this within `every`".
8137///   The poll period is system-generated ([`POLL_CRON`], every
8138///   minute) and no longer the operator's concern.
8139/// * **calendar** (`{ at, days }`) — a wall-clock time trigger
8140///   (#418 Phase 2, replacing the old raw-cron escape hatch). Fires
8141///   the whole target at the given time, no dedup. `at: "09:00"` +
8142///   `days` repeats; `at: "2026-06-10 09:00"` (a date+time) fires
8143///   exactly once. Evaluated in the schedule's top-level `tz`.
8144#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8145#[serde(rename_all = "snake_case")]
8146pub enum When {
8147    /// Fire at each targeted pc: `once` (kitting — succeed once,
8148    /// skip forever, forever catching brand-new / re-imaged pcs)
8149    /// or `{ every: <humantime> }` (patrol — re-arm per pc after
8150    /// the interval).
8151    PerPc(PerPolicy),
8152    /// Fire until **any** one pc of the target succeeds, then skip
8153    /// the whole target (`once`) or re-arm after `every`. Needs
8154    /// fleet-wide completion data, so it is backend-only —
8155    /// `runs_on: agent` + `per_target` is rejected by
8156    /// [`Schedule::validate`].
8157    PerTarget(PerPolicy),
8158    /// Calendar time trigger: `{ at: "09:00", days: [mon-fri] }`
8159    /// (repeating) or `{ at: "2026-06-10 09:00" }` (one-shot). Fires
8160    /// the whole target at that wall-clock time in the schedule's
8161    /// `tz` — no dedup, no cooldown.
8162    Calendar(CalendarSpec),
8163    /// #418 OS-native event trigger: `when: { on: [startup, logon] }`.
8164    /// Fires when the agent observes the listed OS event(s) rather than
8165    /// on a clock — there is no cron. `runs_on: agent` only (the agent
8166    /// owns the event source); [`Schedule::validate`] rejects it on
8167    /// `backend` and rejects an empty list. Each event occurrence fires
8168    /// once, gated by the same freeze / active / `constraints.window` /
8169    /// `skip_dates` checks as the cron path. `startup` fires once per OS
8170    /// boot (deduped via the host boot time); a `starting_deadline`, if
8171    /// set, limits it to "agent came up within that long after boot".
8172    /// Only `startup` has an event source on every OS; `logon` / `lock` /
8173    /// `unlock` / `network_change` are Windows-only — on macOS / Linux
8174    /// they never fire, and the agent says so once per schedule / job
8175    /// version (WARN + a synthetic skipped result, exit 122) when it loads it.
8176    On(Vec<OnTrigger>),
8177}
8178
8179/// An OS event the agent can fire a schedule on (#418 `when: { on }`).
8180#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash)]
8181#[serde(rename_all = "snake_case")]
8182pub enum OnTrigger {
8183    /// Once per OS boot (the agent's first run for that boot). Catches
8184    /// freshly-imaged / reinstalled hosts at their next startup.
8185    Startup,
8186    /// On an interactive-session user logon — console, RDP, or
8187    /// auto-logon (Windows `WTS_SESSION_LOGON`; Windows only). Does not fire for
8188    /// service / network / batch logons (no interactive session).
8189    Logon,
8190    /// When the workstation is locked (Win+L / idle lock; Windows
8191    /// `WTS_SESSION_LOCK`; Windows only). Use for step-away compliance / cleanup.
8192    Lock,
8193    /// When the workstation is unlocked — the user returns to a locked
8194    /// session (Windows `WTS_SESSION_UNLOCK`; Windows only). Use to re-check
8195    /// compliance / refresh state when work resumes.
8196    Unlock,
8197    /// When the host's network changes — IP address table change on
8198    /// connect / disconnect / DHCP renew / VPN / Wi-Fi roam (Windows
8199    /// `NotifyAddrChange`; Windows only). Debounced agent-side (a burst of changes
8200    /// from one transition fires once after the network settles), so
8201    /// use it for "re-check connectivity / re-register on network move"
8202    /// rather than expecting one fire per raw adapter event.
8203    ///
8204    /// IPv4 only: `NotifyAddrChange` watches the IPv4 address table, so a
8205    /// transition that touches only IPv6 addresses won't fire. In practice
8206    /// dual-stack networks change both tables together, but a pure-IPv6
8207    /// move (e.g. an IPv6-only Wi-Fi roam) is not detected.
8208    NetworkChange,
8209}
8210
8211/// Calendar time trigger (#418 Phase 2). `at` is either a time of
8212/// day (`"HH:MM"`, repeating — combine with `days`) or a full
8213/// date+time (`"YYYY-MM-DD HH:MM"`, a one-shot that fires once and
8214/// never again). Evaluated in the schedule's top-level `tz`.
8215#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8216pub struct CalendarSpec {
8217    /// `"HH:MM"` (24h) for a repeating trigger, or
8218    /// `"YYYY-MM-DD HH:MM"` (hyphen / slash / `T` separators all
8219    /// accepted) for a one-shot. Parsed lazily —
8220    /// [`Schedule::validate`] rejects garbage at create time.
8221    pub at: String,
8222    /// Day-of-week filter for a time-of-day `at`: `["mon-fri"]`,
8223    /// `["mon","wed","fri"]`, … (passed verbatim to the cron DOW
8224    /// field, so ranges and names both work). An **nth-weekday**
8225    /// `["tue#2"]` fires only on the 2nd Tuesday of each month
8226    /// ("Patch Tuesday"); the ordinal is `1..5`. A **last-weekday**
8227    /// `["friL"]` fires only on the last Friday of each month (handy
8228    /// for monthly maintenance). Empty = every day. Must be empty
8229    /// when `at` carries a date (the date already pins the day).
8230    #[serde(default, skip_serializing_if = "Vec::is_empty")]
8231    pub days: Vec<String>,
8232}
8233
8234/// Parsed `CalendarSpec.at`: the wall-clock minute/hour, plus the
8235/// date for a one-shot (`None` = repeating time-of-day).
8236struct ParsedAt {
8237    minute: u32,
8238    hour: u32,
8239    date: Option<chrono::NaiveDate>,
8240}
8241
8242impl CalendarSpec {
8243    /// Parse `at`: a date+time (`YYYY-MM-DD HH:MM`, hyphen / slash /
8244    /// `T` separators) is a one-shot; a bare `HH:MM` is repeating.
8245    fn parse_at(&self) -> Result<ParsedAt, String> {
8246        use chrono::Timelike;
8247        let s = self.at.trim();
8248        for fmt in ["%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y/%m/%d %H:%M"] {
8249            if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, fmt) {
8250                return Ok(ParsedAt {
8251                    minute: dt.minute(),
8252                    hour: dt.hour(),
8253                    date: Some(dt.date()),
8254                });
8255            }
8256        }
8257        if let Ok(t) = chrono::NaiveTime::parse_from_str(s, "%H:%M") {
8258            return Ok(ParsedAt {
8259                minute: t.minute(),
8260                hour: t.hour(),
8261                date: None,
8262            });
8263        }
8264        Err(format!(
8265            "when.at: unparseable '{}' (want HH:MM or YYYY-MM-DD HH:MM)",
8266            self.at
8267        ))
8268    }
8269
8270    /// Pre-flight check on the `days` tokens so a bad day name gives
8271    /// a `when.days:`-scoped error instead of croner's confusing
8272    /// "when.at lowered to invalid cron" (claude #432 review). Each
8273    /// token is a day name (`mon`..`sun`), a numeric DOW (`0`..`7`),
8274    /// `*`, a `-` range of those, an **nth-weekday** like `tue#2`
8275    /// (2nd Tuesday of the month — "Patch Tuesday"), or a
8276    /// **last-weekday** like `friL` (last Friday of the month).
8277    fn validate_days(&self) -> Result<(), String> {
8278        const NAMES: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
8279        let is_day = |p: &str| NAMES.contains(&p) || p.parse::<u8>().is_ok_and(|n| n <= 7);
8280        for tok in &self.days {
8281            // Report the whole token on a malformed range like `mon-`
8282            // (which would otherwise split to a cryptic empty part —
8283            // claude #432 follow-up).
8284            let invalid = |reason: &str| {
8285                Err(format!(
8286                    "when.days: invalid day token '{tok}' ({reason}; \
8287                     want mon..sun, 0-7, a range like mon-fri, an nth-weekday \
8288                     like tue#2, a last-weekday like friL, or *)"
8289                ))
8290            };
8291            // #418: nth-weekday suffix (`tue#2` = 2nd Tuesday). Croner
8292            // accepts `<dow>#<n>` (n = 1..5) in the DOW field, and
8293            // `to_cron` passes the token through verbatim, so the
8294            // engine fires only on that occurrence. It's a single
8295            // weekday + ordinal — not combinable with a range.
8296            if let Some((day_part, nth_part)) = tok.split_once('#') {
8297                // Normalize once and use `d` consistently (gemini #547);
8298                // the outer `invalid` already echoes the raw `tok`.
8299                let d = day_part.trim().to_ascii_lowercase();
8300                if d.contains('-') || !is_day(&d) {
8301                    return invalid("the part before # must be a single weekday");
8302                }
8303                match nth_part.trim().parse::<u8>() {
8304                    Ok(n) if (1..=5).contains(&n) => {}
8305                    _ => return invalid("the # ordinal must be 1..5 (e.g. tue#2 = 2nd Tuesday)"),
8306                }
8307                continue;
8308            }
8309            // #418: last-weekday suffix (`friL` = last Friday of the
8310            // month — the monthly-maintenance sibling of Patch Tuesday).
8311            // Croner accepts `<dow>L` in the DOW field with verified
8312            // last-<dow>-of-month semantics, and `to_cron` passes it
8313            // through verbatim. A single weekday + `L` — bare `L` and
8314            // ranges are rejected (croner would read bare `L` as
8315            // Saturday, which is a confusing footgun).
8316            if let Some(day_part) = tok.strip_suffix(['L', 'l']) {
8317                // No `.trim()`: a cron DOW token can't carry internal
8318                // whitespace, so `"fri L"` must be *rejected* here (its
8319                // strip leaves `"fri "`, and `is_day` catches the space)
8320                // rather than trimmed into a clean `"fri"` that then
8321                // produces a malformed `fri L` cron downstream and a
8322                // confusing croner error (gemini #560).
8323                let d = day_part.to_ascii_lowercase();
8324                if d.is_empty() {
8325                    return invalid("`L` (last-weekday) needs a weekday before it, e.g. friL");
8326                }
8327                if d.contains('-') || !is_day(&d) {
8328                    return invalid(
8329                        "the part before L must be a single weekday (e.g. friL = last Friday)",
8330                    );
8331                }
8332                continue;
8333            }
8334            for part in tok.split('-') {
8335                let p = part.trim().to_ascii_lowercase();
8336                if p.is_empty() {
8337                    return invalid("empty range bound");
8338                }
8339                if p != "*" && !is_day(&p) {
8340                    return invalid(&format!("'{part}' is not a day"));
8341                }
8342            }
8343        }
8344        Ok(())
8345    }
8346
8347    /// For a one-shot (`at` carries a date), the absolute instant it
8348    /// fires in `tz`. `None` for a repeating calendar. Used to warn
8349    /// about a one-shot whose date is already in the past (it would
8350    /// never fire).
8351    pub fn oneshot_instant(&self, tz: ScheduleTz) -> Option<chrono::DateTime<chrono::Utc>> {
8352        let p = self.parse_at().ok()?;
8353        let date = p.date?;
8354        let naive = date.and_hms_opt(p.hour, p.minute, 0)?;
8355        tz.naive_to_utc(naive)
8356    }
8357
8358    /// The wall-clock time-of-day this calendar fires at (`None` if
8359    /// `at` is unparseable — validate() guards that). Used to detect
8360    /// a calendar whose fire time can never fall inside its
8361    /// `constraints.window` (claude #452 review).
8362    pub fn fire_time(&self) -> Option<chrono::NaiveTime> {
8363        let p = self.parse_at().ok()?;
8364        chrono::NaiveTime::from_hms_opt(p.hour, p.minute, 0)
8365    }
8366
8367    /// Lower to the cron string the scheduler engine runs. Repeating
8368    /// → 6-field `0 {min} {hour} * * {dow}`; one-shot → 7-field
8369    /// `0 {min} {hour} {day} {month} * {year}` (a past year never
8370    /// fires — that's what makes it one-shot).
8371    fn to_cron(&self) -> Result<String, String> {
8372        use chrono::Datelike;
8373        let ParsedAt { minute, hour, date } = self.parse_at()?;
8374        match date {
8375            Some(d) => {
8376                if !self.days.is_empty() {
8377                    return Err(
8378                        "when.at with a date is a one-shot and cannot be combined with days".into(),
8379                    );
8380                }
8381                Ok(format!(
8382                    "0 {minute} {hour} {} {} * {}",
8383                    d.day(),
8384                    d.month(),
8385                    d.year()
8386                ))
8387            }
8388            None => {
8389                let dow = if self.days.is_empty() {
8390                    "*".to_string()
8391                } else {
8392                    self.validate_days()?;
8393                    self.days.join(",")
8394                };
8395                Ok(format!("0 {minute} {hour} * * {dow}"))
8396            }
8397        }
8398    }
8399}
8400
8401/// The timezone a schedule's wall-clock fields (`when.at`,
8402/// `active.{from,until}`) are evaluated in (#418 Phase 2).
8403#[derive(
8404    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
8405)]
8406#[serde(rename_all = "snake_case")]
8407pub enum ScheduleTz {
8408    /// The running host's local timezone — the agent's for
8409    /// `runs_on: agent`, the backend server's otherwise. Default.
8410    #[default]
8411    Local,
8412    /// UTC — for timezone-independent schedules.
8413    Utc,
8414}
8415
8416impl ScheduleTz {
8417    /// Interpret a naive (zoneless) datetime as being in this tz and
8418    /// convert to UTC. On a DST *fold* (the local time occurs twice
8419    /// when clocks go back) we pick `.earliest()` rather than
8420    /// rejecting it; `None` is reserved for a true DST *gap* (a local
8421    /// time that never exists). `Utc` is fixed-offset so neither ever
8422    /// happens; `Local` is whatever timezone the running host is set
8423    /// to and *can* hit a gap/fold on any DST-observing host — not
8424    /// just the JST we run today (gemini + claude #432 review).
8425    fn naive_to_utc(self, naive: chrono::NaiveDateTime) -> Option<chrono::DateTime<chrono::Utc>> {
8426        use chrono::TimeZone;
8427        match self {
8428            ScheduleTz::Utc => Some(chrono::DateTime::from_naive_utc_and_offset(
8429                naive,
8430                chrono::Utc,
8431            )),
8432            ScheduleTz::Local => chrono::Local
8433                .from_local_datetime(&naive)
8434                .earliest()
8435                .map(|dt| dt.with_timezone(&chrono::Utc)),
8436        }
8437    }
8438
8439    /// The wall-clock time-of-day `now` reads as in this tz — used by
8440    /// [`Constraints::allows`] to test a maintenance window
8441    /// (#418 Phase 3). `Utc` is the naive UTC time; `Local` is the
8442    /// running host's local time.
8443    fn wall_time(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveTime {
8444        match self {
8445            ScheduleTz::Utc => now.time(),
8446            ScheduleTz::Local => now.with_timezone(&chrono::Local).time(),
8447        }
8448    }
8449
8450    /// The wall-clock *date* `now` reads as in this tz — used by
8451    /// [`Constraints::allows`] to test `skip_dates` (#418 holiday
8452    /// exclusion). Same tz semantics as [`Self::wall_time`].
8453    fn wall_date(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveDate {
8454        match self {
8455            ScheduleTz::Utc => now.date_naive(),
8456            ScheduleTz::Local => now.with_timezone(&chrono::Local).date_naive(),
8457        }
8458    }
8459
8460    /// Stable lowercase wire/display label (`local` / `utc`) — matches
8461    /// the serde `snake_case` representation. Used for the preview
8462    /// response's `tz` field so the JSON shape isn't coupled to the
8463    /// `Debug` repr (claude #578 review).
8464    pub fn as_str(self) -> &'static str {
8465        match self {
8466            ScheduleTz::Local => "local",
8467            ScheduleTz::Utc => "utc",
8468        }
8469    }
8470}
8471
8472impl std::fmt::Display for ScheduleTz {
8473    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8474        f.write_str(self.as_str())
8475    }
8476}
8477
8478/// `once` / `once_per_version` / `{ every: <humantime> }` — shared by
8479/// `per_pc` / `per_target`. Untagged so the YAML stays the bare keyword
8480/// or a one-key map, nothing more ceremonial. `once_per_version` is
8481/// per_pc + backend only (see the variant doc and `Schedule::validate`).
8482#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8483#[serde(untagged)]
8484pub enum PerPolicy {
8485    /// The bare string `once`: succeed once, then skip permanently
8486    /// (cooldown = infinity), version-blind.
8487    Once(OnceLiteral),
8488    /// The bare string `once_per_version`: succeed once *per manifest
8489    /// version*, then skip until the job's YAML `version` changes. Like
8490    /// `once` but re-arms each pc when the version it succeeded at is no
8491    /// longer current — the version-aware redistribution shape. per_pc
8492    /// only (`Schedule::validate` rejects it on `per_target`).
8493    OncePerVersion(OncePerVersionLiteral),
8494    /// Re-arm after the humantime interval, e.g. `{ every: 6h }`.
8495    Every(EverySpec),
8496}
8497
8498/// Single-variant enum so serde accepts exactly the string `once`
8499/// (a free-form `String` would swallow typos like `onec`).
8500#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
8501#[serde(rename_all = "snake_case")]
8502pub enum OnceLiteral {
8503    Once,
8504}
8505
8506/// Single-variant enum so serde accepts exactly the string
8507/// `once_per_version` (mirrors [`OnceLiteral`]'s typo-catching). The
8508/// distinct literal — rather than a bool field on `once` — keeps the
8509/// ergonomic bare-string surface (`per_pc: once_per_version`).
8510#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
8511#[serde(rename_all = "snake_case")]
8512pub enum OncePerVersionLiteral {
8513    OncePerVersion,
8514}
8515
8516/// `{ every: <humantime> }`. Standalone struct (not an inline
8517/// struct variant). `{ evry: 6h }` still fails to parse (the
8518/// required `every` key is missing), and the create boundaries
8519/// reject the unknown `evry` via [`crate::strict`] with its path —
8520/// while agents reading a future writer's extra fields tolerate
8521/// them (#492).
8522#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8523pub struct EverySpec {
8524    /// Humantime interval (`10m`, `6h`, `1d`...). Parsed lazily —
8525    /// [`Schedule::validate`] rejects garbage at create time.
8526    pub every: String,
8527}
8528
8529impl PerPolicy {
8530    /// The cooldown this policy lowers to: `once` = `None`
8531    /// (permanent skip), `every` = the interval.
8532    fn cooldown(&self) -> Option<String> {
8533        match self {
8534            // Both `once` shapes lower to "no time-based re-arm". The
8535            // version-aware re-arm for `once_per_version` is not a
8536            // cooldown — it is the version filter the scheduler applies
8537            // to the completion set, so the cooldown stays None here.
8538            PerPolicy::Once(_) | PerPolicy::OncePerVersion(_) => None,
8539            PerPolicy::Every(EverySpec { every }) => Some(every.clone()),
8540        }
8541    }
8542}
8543
8544impl std::fmt::Display for When {
8545    /// Operator-facing one-liner (`per_pc once` / `per_pc every 6h`
8546    /// / `at 09:00 [mon-fri]` / `at 2026-06-10 09:00`) for log
8547    /// lines, audit payloads and the API's `ScheduleSummary`.
8548    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8549        let policy = |p: &PerPolicy| match p {
8550            PerPolicy::Once(_) => "once".to_string(),
8551            PerPolicy::OncePerVersion(_) => "once_per_version".to_string(),
8552            PerPolicy::Every(EverySpec { every }) => format!("every {every}"),
8553        };
8554        match self {
8555            When::PerPc(p) => write!(f, "per_pc {}", policy(p)),
8556            When::PerTarget(p) => write!(f, "per_target {}", policy(p)),
8557            When::Calendar(c) if c.days.is_empty() => write!(f, "at {}", c.at),
8558            When::Calendar(c) => write!(f, "at {} [{}]", c.at, c.days.join(",")),
8559            When::On(triggers) => {
8560                let names: Vec<&str> = triggers.iter().map(|t| t.as_str()).collect();
8561                write!(f, "on [{}]", names.join(","))
8562            }
8563        }
8564    }
8565}
8566
8567impl OnTrigger {
8568    /// Lowercase wire/display label (matches the serde `snake_case`).
8569    pub fn as_str(self) -> &'static str {
8570        match self {
8571            OnTrigger::Startup => "startup",
8572            OnTrigger::Logon => "logon",
8573            OnTrigger::Lock => "lock",
8574            OnTrigger::Unlock => "unlock",
8575            OnTrigger::NetworkChange => "network_change",
8576        }
8577    }
8578}
8579
8580/// Optional validity window for a [`Schedule`] (#418 decision G).
8581/// Half-open `[from, until)`; either bound may be omitted. Bounds
8582/// are `YYYY-MM-DD` (= that day's 00:00 in the schedule's `tz`) or
8583/// full RFC3339 (offset is honored as-is, `tz` ignored). Kept as
8584/// strings so the JSON Schema the SPA editor consumes stays two
8585/// plain string fields, mirroring `jitter` / `starting_deadline`.
8586///
8587/// #418 Phase 2: bounds are evaluated in the schedule's top-level
8588/// `tz` (was UTC-only in Phase 1) so `tz: local` makes both the
8589/// calendar `at` AND the `active` window local — one consistent
8590/// timezone per schedule.
8591#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
8592pub struct Active {
8593    /// Dormant before this instant.
8594    #[serde(default, skip_serializing_if = "Option::is_none")]
8595    pub from: Option<String>,
8596    /// Dormant from this instant on (exclusive).
8597    #[serde(default, skip_serializing_if = "Option::is_none")]
8598    pub until: Option<String>,
8599}
8600
8601impl Active {
8602    /// `skip_serializing_if` helper — an empty window means "always
8603    /// active" and is omitted from the wire format entirely.
8604    pub fn is_empty(&self) -> bool {
8605        self.from.is_none() && self.until.is_none()
8606    }
8607
8608    /// Parse one bound: RFC3339 first (offset honored, `tz`
8609    /// ignored), then bare `YYYY-MM-DD` (00:00 in `tz`).
8610    pub fn parse_bound(s: &str, tz: ScheduleTz) -> Result<chrono::DateTime<chrono::Utc>, String> {
8611        if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
8612            return Ok(dt.with_timezone(&chrono::Utc));
8613        }
8614        if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
8615            let midnight = d.and_hms_opt(0, 0, 0).expect("00:00:00 is always valid");
8616            return tz.naive_to_utc(midnight).ok_or_else(|| {
8617                format!("active: bound '{s}' falls in a DST gap for the schedule's tz")
8618            });
8619        }
8620        Err(format!(
8621            "active: unparseable bound '{s}' (want YYYY-MM-DD or RFC3339)"
8622        ))
8623    }
8624
8625    /// Is `now` inside the window? Unparseable bounds are treated
8626    /// as absent here (fail-open) — [`Schedule::validate`] is the
8627    /// place that rejects them loudly; this runs on every tick and
8628    /// must never panic on a stale KV blob.
8629    pub fn contains(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
8630        let bound = |s: &Option<String>| s.as_deref().and_then(|s| Self::parse_bound(s, tz).ok());
8631        if bound(&self.from).is_some_and(|from| now < from) {
8632            return false;
8633        }
8634        if bound(&self.until).is_some_and(|until| now >= until) {
8635            return false;
8636        }
8637        true
8638    }
8639}
8640
8641/// Host-environment gate (#418 `constraints.require`). Fire only when
8642/// the target host is in the required state. Sensed **in-process by the
8643/// agent** (Win32), so it is `runs_on: agent` only — the backend cannot
8644/// read a target host's power/idle state ([`Schedule::validate`]
8645/// rejects it on `runs_on: backend`, symmetric with `when: { on }`).
8646///
8647/// Evaluated at fire time as a skip-this-tick gate (NOT in
8648/// [`Constraints::allows`], which stays pure for `preview`): a reconcile
8649/// cadence re-checks every minute (so it effectively defers until the
8650/// state is met — the intended pairing); a `calendar` fire that lands
8651/// while the state is unmet is simply missed, same as `window`. It is
8652/// therefore a *runtime* gate and does not appear in `preview`.
8653///
8654/// Off Windows only `cpu_below` can be sensed. On macOS / Linux any other
8655/// set gate cannot be evaluated, so the agent fails closed: the job does
8656/// not run, no per-pc completion is recorded (it still runs once the gate
8657/// is supported), and one WARN + one synthetic skipped result (exit 122,
8658/// naming the gate) is published per schedule / job version.
8659// No `Eq`: `cpu_below: Option<f64>` is only `PartialEq` (f64 is not Eq).
8660#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
8661pub struct Require {
8662    /// Fire only while on **AC power** (skip on battery). Reads
8663    /// `GetSystemPowerStatus`; an unknown/unreadable status is treated
8664    /// as not-on-AC (fail-closed — a restrictive gate must not fire
8665    /// when it can't confirm the condition). `false` (default) = no
8666    /// power requirement. Windows only (fail-closed skip elsewhere).
8667    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
8668    pub ac_power: bool,
8669    /// Fire only when the active console session has had **no keyboard /
8670    /// mouse input for at least this long** (humantime, e.g. `"10m"`) —
8671    /// "don't run while the user is actively working". Input-based
8672    /// (simpler than Task Scheduler's CPU/disk-aware idle). A
8673    /// headless / disconnected console (no interactive user) trivially
8674    /// satisfies it. `None` (default) = no idle requirement. Parsed
8675    /// lazily; [`Schedule::validate`] rejects garbage at create time.
8676    /// Windows only (fail-closed skip elsewhere).
8677    #[serde(default, skip_serializing_if = "Option::is_none")]
8678    pub idle: Option<String>,
8679    /// Fire only when the **whole-machine CPU usage is below this
8680    /// percent** (0–100; e.g. `20.0` = "system CPU < 20%") — "don't run
8681    /// while the box is busy". Reuses the agent's `host_perf` system CPU%
8682    /// sample (`sysinfo` mean over cores), so the reading is up to one
8683    /// `host_perf` cadence old (default 60s) — fine as a "generally
8684    /// busy?" proxy, and more accurate than a fresh one-shot read (CPU%
8685    /// needs two samples). An unavailable sample (host_perf not warmed
8686    /// up yet, or stale) is treated as "not below" (fail-closed — a
8687    /// restrictive gate must not fire when it can't confirm). `None`
8688    /// (default) = no CPU requirement. [`Schedule::validate`] rejects an
8689    /// out-of-range value at create time.
8690    #[serde(default, skip_serializing_if = "Option::is_none")]
8691    pub cpu_below: Option<f64>,
8692    /// Fire only when the host has **internet connectivity** (Windows
8693    /// `GetNetworkConnectivityHint` reports InternetAccess) — "don't run
8694    /// until online" for jobs that download / phone home. A captive
8695    /// portal (ConstrainedInternetAccess), LAN-only (LocalAccess), or
8696    /// unknown/unreadable state is treated as offline (fail-closed) — a
8697    /// portal would just fail a download, so we hold the run. For VPN /
8698    /// SASE / app-specific conditions, use a custom script gate (separate
8699    /// slice). `false` (default) = no network requirement. Windows only
8700    /// (fail-closed skip elsewhere).
8701    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
8702    pub network: bool,
8703}
8704
8705impl Require {
8706    /// `skip_serializing_if` helper for an embedded empty `require`.
8707    pub fn is_empty(&self) -> bool {
8708        !self.ac_power && self.idle.is_none() && self.cpu_below.is_none() && !self.network
8709    }
8710
8711    /// Parsed minimum-idle duration (`None` = no idle requirement, or an
8712    /// unparseable value — `validate` rejects the latter at create time).
8713    pub fn min_idle(&self) -> Option<std::time::Duration> {
8714        self.idle
8715            .as_deref()
8716            .and_then(|s| humantime::parse_duration(s.trim()).ok())
8717    }
8718
8719    /// First unparseable field for create-time rejection (mirrors
8720    /// [`Constraints::bad_skip_date`]).
8721    pub fn bad_idle(&self) -> Option<String> {
8722        self.idle.as_deref().and_then(|s| {
8723            humantime::parse_duration(s.trim())
8724                .err()
8725                .map(|e| format!("constraints.require.idle: invalid duration '{s}': {e}"))
8726        })
8727    }
8728}
8729
8730/// Host-environment state sensed by the agent, fed to [`require_met`].
8731/// A named struct (not positional args) so the growing set of sensed
8732/// signals — several of them `bool` — can't be transposed at a call
8733/// site. The Win32 sensing lives in `kanade-agent::env_gate`.
8734#[derive(Debug, Clone, Copy, Default)]
8735pub struct EnvState {
8736    /// Is the host on AC power (`false` if on battery or unreadable).
8737    pub ac_online: bool,
8738    /// How long the console has been idle (`None` = couldn't determine).
8739    pub idle: Option<std::time::Duration>,
8740    /// Whole-machine CPU usage 0–100 (`None` = no sample yet).
8741    pub cpu_pct: Option<f64>,
8742    /// Does the host have internet connectivity (`false` if offline /
8743    /// LAN-only / unreadable).
8744    pub network_up: bool,
8745}
8746
8747/// Pure env-gate decision (#418 `constraints.require`). The Win32
8748/// sensing lives in the agent (`kanade-agent::env_gate`); this is the
8749/// testable core, fed the already-sensed [`EnvState`]. Deliberately a
8750/// free fn (not folded into [`Constraints::allows`]) so `allows` stays
8751/// pure and `preview` never evaluates a runtime gate. Each set
8752/// requirement is a restrictive AND: any unmet (or unknown) gate skips.
8753pub fn require_met(req: &Require, env: &EnvState) -> bool {
8754    if req.ac_power && !env.ac_online {
8755        return false;
8756    }
8757    if let Some(min) = req.min_idle() {
8758        match env.idle {
8759            Some(d) if d >= min => {}
8760            _ => return false,
8761        }
8762    }
8763    if let Some(max) = req.cpu_below {
8764        match env.cpu_pct {
8765            Some(p) if p < max => {}
8766            _ => return false,
8767        }
8768    }
8769    if req.network && !env.network_up {
8770        return false;
8771    }
8772    true
8773}
8774
8775/// [`Active`] decides *over what date range* a schedule is live,
8776/// `Constraints` decides *when, within an active period,* a fire is
8777/// allowed: `window` (a maintenance time-of-day window),
8778/// `max_concurrent` (a fleet-wide running-instance cap), `skip_dates`
8779/// (holiday exclusion) and `require` (host-environment gates, agent-only
8780/// — see [`Require`]).
8781// No `Eq`: contains `require: Option<Require>` which holds an f64.
8782#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
8783pub struct Constraints {
8784    /// `"HH:MM-HH:MM"` wall-clock window (evaluated in the schedule's
8785    /// `tz`). Fires outside it are skipped — mainly for reconcile
8786    /// cadences ("patrol every 6h, but only fire overnight") and
8787    /// daytime change-freezes. `start > end` crosses midnight
8788    /// (`"22:00-05:00"` = 22:00 through 05:00 next morning). Parsed
8789    /// lazily; [`Schedule::validate`] rejects garbage at create time.
8790    #[serde(default, skip_serializing_if = "Option::is_none")]
8791    pub window: Option<String>,
8792    /// Fleet-wide cap on how many instances of this schedule's job may
8793    /// run **at the same time** (#418 "同時実行ハード上限"). The
8794    /// backend scheduler counts the job's still-in-flight runs
8795    /// (`execution_results.finished_at IS NULL`) each tick and only
8796    /// dispatches to as many remaining pcs as there are free slots —
8797    /// a rolling window that refills as runs complete. Useful for
8798    /// disk/CPU/network-heavy jobs you don't want hammering the whole
8799    /// fleet at once.
8800    ///
8801    /// **Backend-only** (it needs a central counter): combining it
8802    /// with `runs_on: agent` is rejected by [`Schedule::validate`]
8803    /// (#418 decision E — "中央上限には中央が要る"). Most meaningful
8804    /// for `per_pc` reconcile cadences, where the poll re-ticks and
8805    /// refills slots. `None` (default) = no cap.
8806    #[serde(default, skip_serializing_if = "Option::is_none")]
8807    pub max_concurrent: Option<u32>,
8808    /// Calendar dates the schedule must **not** fire on — holidays,
8809    /// blackout days, one-off freeze dates (#418 "祝日除外"). Each is
8810    /// `YYYY-MM-DD`, evaluated as a wall-clock date in the schedule's
8811    /// `tz`. Applies to every `when` shape (a reconcile cadence skips
8812    /// the whole day; a calendar fire landing on the date is
8813    /// suppressed) and is honored by both the live scheduler and
8814    /// `preview`, since both gate on [`Constraints::allows`]. Empty
8815    /// (default) = no skips. Operator-supplied: there is no built-in
8816    /// holiday calendar — list the dates you care about. Parsed lazily;
8817    /// [`Schedule::validate`] rejects a malformed date at create time.
8818    #[serde(default, skip_serializing_if = "Vec::is_empty")]
8819    pub skip_dates: Vec<String>,
8820    /// Host-environment gate (#418): fire only when the target host is
8821    /// in the required state (on AC power, idle). Agent-sensed at fire
8822    /// time, `runs_on: agent` only. See [`Require`]. `None` (default) =
8823    /// no environment requirement.
8824    #[serde(default, skip_serializing_if = "Option::is_none")]
8825    pub require: Option<Require>,
8826}
8827
8828impl Constraints {
8829    /// `skip_serializing_if` helper — empty constraints are omitted
8830    /// from the wire format entirely.
8831    pub fn is_empty(&self) -> bool {
8832        self.window.is_none()
8833            && self.max_concurrent.is_none()
8834            && self.skip_dates.is_empty()
8835            && self.require.as_ref().is_none_or(Require::is_empty)
8836    }
8837
8838    /// The first unparseable `skip_dates` entry, if any — the
8839    /// scheduler logs it at register time so a fail-closed
8840    /// (never-firing) schedule from a hand-edited KV blob is
8841    /// diagnosable, mirroring [`Schedule::bad_window`].
8842    pub fn bad_skip_date(&self) -> Option<String> {
8843        self.skip_dates.iter().find_map(|s| {
8844            chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d")
8845                .err()
8846                .map(|e| format!("constraints.skip_dates: invalid date '{s}': {e}"))
8847        })
8848    }
8849
8850    /// Parse `"HH:MM-HH:MM"` into `(start, end)`. Equal bounds are an
8851    /// error (a zero-width or all-day window is ambiguous — write no
8852    /// window for "always").
8853    pub fn parse_window(s: &str) -> Result<(chrono::NaiveTime, chrono::NaiveTime), String> {
8854        let (a, b) = s
8855            .split_once('-')
8856            .ok_or_else(|| format!("constraints.window: '{s}' must be 'HH:MM-HH:MM'"))?;
8857        let parse = |part: &str| {
8858            chrono::NaiveTime::parse_from_str(part.trim(), "%H:%M")
8859                .map_err(|e| format!("constraints.window: invalid time '{}': {e}", part.trim()))
8860        };
8861        let (start, end) = (parse(a)?, parse(b)?);
8862        if start == end {
8863            return Err(format!(
8864                "constraints.window: start and end are equal ('{s}'); omit window for 'always'"
8865            ));
8866        }
8867        Ok((start, end))
8868    }
8869
8870    /// Is a fire allowed at `now` (evaluated in `tz`)? No window =
8871    /// always allowed. Half-open `[start, end)`; `start > end`
8872    /// crosses midnight.
8873    ///
8874    /// **Fail-closed** on an unparseable window (returns `false`,
8875    /// gemini #452 review): a window is a *restrictive* constraint
8876    /// (change-freeze / overnight-only), so a corrupt one must NOT
8877    /// silently allow fires during the restricted hours. Bad windows
8878    /// are rejected at create time by [`Schedule::validate`]; this
8879    /// only bites a hand-edited KV blob, where blocking is the safe
8880    /// direction. The scheduler warns at register time
8881    /// ([`Schedule::bad_window`]) so a stuck schedule is diagnosable.
8882    /// The tick path never panics regardless.
8883    pub fn allows(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
8884        // #418 holiday / blackout dates: never fire on a listed wall
8885        // date (in `tz`). Checked before the window since a skipped day
8886        // overrides any within-window allowance. Fail-closed on a
8887        // corrupt entry (same posture as `window`): a skip date is a
8888        // *restrictive* constraint, so a garbled one must not silently
8889        // re-enable fires — it blocks until fixed (`validate` rejects it
8890        // at create time; `bad_skip_date` lets the scheduler warn).
8891        if !self.skip_dates.is_empty() {
8892            let today = tz.wall_date(now);
8893            let blocked = self.skip_dates.iter().any(|s| {
8894                match chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d") {
8895                    Ok(d) => d == today,
8896                    Err(_) => true, // corrupt entry → fail-closed (block)
8897                }
8898            });
8899            if blocked {
8900                return false;
8901            }
8902        }
8903        match self.window.as_deref() {
8904            // No window → always allowed.
8905            None => true,
8906            // Window set: membership, or fail-closed if unparseable
8907            // (`window_contains` returns None for a corrupt window).
8908            Some(_) => self.window_contains(tz.wall_time(now)).unwrap_or(false),
8909        }
8910    }
8911
8912    /// Membership of a wall-clock time-of-day in the window. `None`
8913    /// when there is no window or it's unparseable (callers decide
8914    /// the failure direction). `start > end` crosses midnight.
8915    fn window_contains(&self, t: chrono::NaiveTime) -> Option<bool> {
8916        let (start, end) = Self::parse_window(self.window.as_deref()?).ok()?;
8917        Some(if start <= end {
8918            start <= t && t < end
8919        } else {
8920            t >= start || t < end
8921        })
8922    }
8923}
8924
8925/// What to do when a fire's script fails (#418 Phase 4 — the "高"
8926/// retry/backoff gap). Where [`Constraints`] gates *whether* a fire
8927/// happens, `OnFailure` decides what happens *after* one ran and
8928/// came back bad. Only `retry` so far; future `notify` / `disable`
8929/// would join the same namespace.
8930#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
8931pub struct OnFailure {
8932    /// Re-run the script in-process when it exits non-zero (or times
8933    /// out), up to a cap, with a fixed backoff between attempts.
8934    /// `None` (default) = no retry: a failed run is published as-is
8935    /// and (for reconcile cadences) simply re-fires on the next poll
8936    /// tick. See [`Retry`].
8937    #[serde(default, skip_serializing_if = "Option::is_none")]
8938    pub retry: Option<Retry>,
8939}
8940
8941impl OnFailure {
8942    /// `skip_serializing_if` helper — an empty policy is omitted from
8943    /// the wire format entirely.
8944    pub fn is_empty(&self) -> bool {
8945        self.retry.is_none()
8946    }
8947
8948    /// Lower the operator-facing `retry` (humantime backoff) onto the
8949    /// engine vocabulary the agent's executor runs on (backoff in
8950    /// whole seconds). Single seam shared by the backend command
8951    /// builder and the agent's local scheduler so the two stamp the
8952    /// same [`crate::wire::RetrySpec`] onto every Command. Returns
8953    /// `None` when there is no retry policy or the backoff is
8954    /// unparseable (validate() rejects the latter at create time;
8955    /// this stays fail-safe = "no retry" for a hand-edited KV blob
8956    /// rather than panicking on the fire path).
8957    pub fn lowered_retry(&self) -> Option<crate::wire::RetrySpec> {
8958        let r = self.retry.as_ref()?;
8959        let backoff_secs = humantime::parse_duration(&r.backoff).ok()?.as_secs();
8960        Some(crate::wire::RetrySpec {
8961            max: r.max,
8962            backoff_secs,
8963        })
8964    }
8965}
8966
8967/// Fixed-backoff retry policy (#418 Phase 4). `max` is the number of
8968/// *additional* attempts after the first run (so `max: 3` = up to 4
8969/// total executions); `backoff` is the humantime delay slept between
8970/// attempts. The retry happens fire-side (inside `kanade fire` /
8971/// `handle_command`) on every OS for the PoC — the Windows-native
8972/// "restart on failure" Task Scheduler path is deferred to the
8973/// native-delegation phase (#418 decision H).
8974#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8975pub struct Retry {
8976    /// Max additional attempts after the first failure. Bounded
8977    /// `1..=10` by [`Schedule::validate`] — a typo'd `max: 1000`
8978    /// with a short backoff would otherwise pin a flapping script in
8979    /// a tight loop for the whole window.
8980    pub max: u32,
8981    /// Humantime delay slept between attempts (`"10m"`, `"30s"`).
8982    pub backoff: String,
8983}
8984
8985/// Fleet-wide change-freeze (#418 Phase 5 — the "メンテナンス窓 /
8986/// 変更凍結" gap's global half). Where [`Constraints::window`] is a
8987/// *per-schedule* time-of-day gate, a `Freeze` is a *single, fleet-
8988/// global* "stop all automated change" switch the operator flips
8989/// during an incident or a year-end change-freeze. It lives in its
8990/// own KV singleton ([`crate::kv::KEY_FREEZE`]); when present and
8991/// active, both the backend scheduler and every agent's local
8992/// scheduler skip *every* fire.
8993///
8994/// Shapes:
8995/// * `{}` (no bounds) — frozen indefinitely until the operator
8996///   clears it (incident "big red button").
8997/// * `{ from, until }` — frozen only within `[from, until)`,
8998///   evaluated in `tz` (planned change-freeze; auto-thaws).
8999///
9000/// The KV key being *absent* means "not frozen" — so clearing the
9001/// freeze is a KV delete, and `is_active` only ever runs on a freeze
9002/// the operator actually set.
9003#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
9004pub struct Freeze {
9005    /// Frozen from this instant (RFC3339 or bare `YYYY-MM-DD` in
9006    /// `tz`). `None` ⇒ frozen from the beginning of time.
9007    #[serde(default, skip_serializing_if = "Option::is_none")]
9008    pub from: Option<String>,
9009    /// Thawed from this instant on, exclusive. `None` ⇒ frozen with
9010    /// no scheduled end (manual clear required).
9011    #[serde(default, skip_serializing_if = "Option::is_none")]
9012    pub until: Option<String>,
9013    /// Operator-supplied note surfaced on the freeze-skip log and the
9014    /// SPA banner ("year-end change freeze", "INC-1234"). Advisory.
9015    #[serde(default, skip_serializing_if = "Option::is_none")]
9016    pub reason: Option<String>,
9017    /// Timezone the bare-date bounds are evaluated in (RFC3339 bounds
9018    /// carry their own offset). Defaults to host-local like a
9019    /// schedule's `tz`.
9020    #[serde(default)]
9021    pub tz: ScheduleTz,
9022}
9023
9024impl Freeze {
9025    /// Is the fleet frozen at `now`? An empty window (`from`/`until`
9026    /// both absent) is frozen unconditionally; otherwise membership of
9027    /// `[from, until)` in `tz`. Half-open like [`Active::contains`],
9028    /// but **fails CLOSED** on an unparseable bound — a freeze is a
9029    /// safety switch, so a corrupt window (only reachable via a
9030    /// hand-edited KV blob; `validate` rejects it at set time) must
9031    /// mean "frozen", not "fire normally" (coderabbit #472). This is
9032    /// the one deliberate divergence from `active`'s fail-OPEN
9033    /// behaviour, where an unparseable bound dormant-skips a schedule.
9034    pub fn is_active(&self, now: chrono::DateTime<chrono::Utc>) -> bool {
9035        // Parse a bound; an unparseable one short-circuits the whole
9036        // check to `true` (frozen) via the closure's `None` sentinel
9037        // handled below.
9038        let bound = |s: &Option<String>| -> Result<Option<chrono::DateTime<chrono::Utc>>, ()> {
9039            match s.as_deref() {
9040                None => Ok(None),
9041                Some(raw) => Active::parse_bound(raw, self.tz).map(Some).map_err(|_| ()),
9042            }
9043        };
9044        let (from, until) = match (bound(&self.from), bound(&self.until)) {
9045            (Ok(f), Ok(u)) => (f, u),
9046            // Any corrupt bound → fail closed (frozen).
9047            _ => return true,
9048        };
9049        if from.is_some_and(|f| now < f) {
9050            return false;
9051        }
9052        if until.is_some_and(|u| now >= u) {
9053            return false;
9054        }
9055        true
9056    }
9057
9058    /// Reject unparseable bounds / `from >= until` at set time (the
9059    /// API + CLI counterpart to [`Schedule::validate`]).
9060    pub fn validate(&self) -> Result<(), String> {
9061        let from = self
9062            .from
9063            .as_deref()
9064            .map(|s| Active::parse_bound(s, self.tz))
9065            .transpose()
9066            .map_err(|e| e.replace("active:", "freeze:"))?;
9067        let until = self
9068            .until
9069            .as_deref()
9070            .map(|s| Active::parse_bound(s, self.tz))
9071            .transpose()
9072            .map_err(|e| e.replace("active:", "freeze:"))?;
9073        if let (Some(f), Some(u)) = (from, until) {
9074            if f >= u {
9075                return Err(format!(
9076                    "freeze.from ({}) must be strictly before freeze.until ({})",
9077                    self.from.as_deref().unwrap_or_default(),
9078                    self.until.as_deref().unwrap_or_default(),
9079                ));
9080            }
9081        }
9082        Ok(())
9083    }
9084}
9085
9086/// The system-generated poll cadence every reconcile-shaped `when`
9087/// lowers to. Operators never write this: the real inter-run
9088/// spacing is the `every` cooldown; this only bounds "how soon do
9089/// we notice somebody is due" (#418 decision B took the poll
9090/// period away from the operator).
9091pub const POLL_CRON: &str = "0 * * * * *";
9092
9093/// What a [`When`] lowers to — the exact (cron, mode, cooldown)
9094/// trio the pre-#418 engine ran on. Keeping the engine vocabulary
9095/// unchanged is what lets Phase 1 swap the operator surface without
9096/// touching the tick / dedup machinery.
9097pub struct Lowered {
9098    /// Cron handed to `tokio-cron-scheduler` — [`POLL_CRON`] for
9099    /// reconcile shapes, a 6/7-field cron for calendar shapes.
9100    pub cron: String,
9101    /// Dedup semantics for `decide_fire`.
9102    pub mode: ExecMode,
9103    /// Humantime re-arm interval (`None` = succeed once, skip
9104    /// forever).
9105    pub cooldown: Option<String>,
9106    /// Timezone to evaluate `cron` in (#418 Phase 2). The scheduler
9107    /// passes this to `Job::new_async_tz`. Reconcile shapes carry
9108    /// the schedule's tz too even though POLL_CRON is tz-agnostic,
9109    /// so the same value drives the `active`-window check.
9110    pub tz: ScheduleTz,
9111}
9112
9113impl Schedule {
9114    /// The error message if this schedule's `constraints.window` is
9115    /// set but unparseable, else `None`. The scheduler logs this at
9116    /// register time so a fail-closed (never-firing) schedule from a
9117    /// hand-edited KV blob is diagnosable (gemini #452 review).
9118    pub fn bad_window(&self) -> Option<String> {
9119        let w = self.constraints.window.as_deref()?;
9120        Constraints::parse_window(w).err()
9121    }
9122
9123    /// True when this is a `calendar` schedule whose fire time can
9124    /// never fall inside its `constraints.window` — the cron fires,
9125    /// the window check rejects it, and (firing only at that
9126    /// time-of-day) it effectively never runs. An easy misconfig to
9127    /// set up by accident; the scheduler warns at register time
9128    /// (claude #452 review). Reconcile shapes poll every minute, so
9129    /// they always catch the window opening and aren't affected.
9130    pub fn calendar_outside_window(&self) -> bool {
9131        let When::Calendar(c) = &self.when else {
9132            return false;
9133        };
9134        let Some(t) = c.fire_time() else {
9135            return false;
9136        };
9137        matches!(self.constraints.window_contains(t), Some(false))
9138    }
9139
9140    /// Up to `count` future instants this schedule will fire, as
9141    /// absolute UTC, strictly after `now` — the dry-run / preview
9142    /// surface (#418 "ドライラン / プレビュー"). Only **calendar**
9143    /// schedules have discrete fire times; reconcile shapes
9144    /// (`per_pc`/`per_target`) poll every minute gated by cooldown, so
9145    /// they return an empty vec and the caller describes the cadence
9146    /// instead. Occurrences outside the `active.{from,until}` window or
9147    /// the `constraints.window` are **skipped**, so the list reflects
9148    /// when the schedule will ACTUALLY run, not the raw cron ticks.
9149    /// Evaluated in the schedule's `tz`, exactly like the scheduler's
9150    /// `Job::new_async_tz`, and with the same croner config the
9151    /// scheduler / [`Schedule::validate`] use, so a preview can never
9152    /// disagree with a real fire. A schedule that can never fire (a
9153    /// calendar time wholly outside its window, a past one-shot,
9154    /// `enabled: false` is *not* considered here — callers gate on
9155    /// `enabled` separately) yields an empty vec.
9156    pub fn preview_fires(
9157        &self,
9158        now: chrono::DateTime<chrono::Utc>,
9159        count: usize,
9160    ) -> Vec<chrono::DateTime<chrono::Utc>> {
9161        use croner::parser::{CronParser, Seconds};
9162        if !matches!(self.when, When::Calendar(_)) {
9163            return Vec::new();
9164        }
9165        // Same lowering + croner config as `next_calendar_fire` and the
9166        // live scheduler, so a preview can never disagree with a real
9167        // fire. `preview_fires` adds the N-occurrence walk and the
9168        // active / window filtering on top of that single seam.
9169        let lowered = self.lowered();
9170        let Ok(cron) = CronParser::builder()
9171            .seconds(Seconds::Required)
9172            .dom_and_dow(true)
9173            .build()
9174            .parse(&lowered.cron)
9175        else {
9176            return Vec::new();
9177        };
9178        let accept = |utc: chrono::DateTime<chrono::Utc>| {
9179            self.active.contains(utc, self.tz) && self.constraints.allows(utc, self.tz)
9180        };
9181        match self.tz {
9182            ScheduleTz::Utc => Self::next_occurrences(&cron, now, count, accept),
9183            ScheduleTz::Local => {
9184                Self::next_occurrences(&cron, now.with_timezone(&chrono::Local), count, accept)
9185            }
9186        }
9187    }
9188
9189    /// Walk croner forward from `after` collecting up to `count`
9190    /// accepted occurrences (converted to UTC). Generic over the tz the
9191    /// cron is evaluated in so `preview_fires` can run it in either
9192    /// `Utc` or `Local` without duplicating the loop.
9193    fn next_occurrences<Tz>(
9194        cron: &croner::Cron,
9195        after: chrono::DateTime<Tz>,
9196        count: usize,
9197        accept: impl Fn(chrono::DateTime<chrono::Utc>) -> bool,
9198    ) -> Vec<chrono::DateTime<chrono::Utc>>
9199    where
9200        Tz: chrono::TimeZone,
9201    {
9202        // Bound the scan so an `active`/window dead-end (every future
9203        // tick rejected) can't spin forever: ~4096 raw ticks covers
9204        // >10y of a daily calendar while staying instant for croner.
9205        const SCAN_CAP: usize = 4096;
9206        let mut out = Vec::with_capacity(count.min(SCAN_CAP));
9207        let mut cursor = after;
9208        let mut scanned = 0usize;
9209        while out.len() < count && scanned < SCAN_CAP {
9210            scanned += 1;
9211            let Ok(next) = cron.find_next_occurrence(&cursor, false) else {
9212                break;
9213            };
9214            let utc = next.with_timezone(&chrono::Utc);
9215            if accept(utc) {
9216                out.push(utc);
9217            }
9218            // `find_next_occurrence(.., inclusive = false)` already
9219            // advances strictly past `cursor`, so handing it `next`
9220            // verbatim gets the following occurrence — no manual +1s
9221            // nudge (and `DateTime<Tz>` is `Copy`, so no clone).
9222            cursor = next;
9223        }
9224        out
9225    }
9226
9227    /// Lower the operator-facing `when` onto the engine vocabulary.
9228    /// Single seam shared by the backend scheduler and the agent's
9229    /// local scheduler so the two can never drift.
9230    pub fn lowered(&self) -> Lowered {
9231        let tz = self.tz;
9232        match &self.when {
9233            When::PerPc(p) => Lowered {
9234                cron: POLL_CRON.into(),
9235                // `once_per_version` re-arms each pc when the manifest
9236                // version changes; the scheduler keys that dedup on
9237                // `execution_results.version`. Plain `once` / `every`
9238                // stay version-blind.
9239                mode: match p {
9240                    PerPolicy::OncePerVersion(_) => ExecMode::OncePerPcVersion,
9241                    PerPolicy::Once(_) | PerPolicy::Every(_) => ExecMode::OncePerPc,
9242                },
9243                cooldown: p.cooldown(),
9244                tz,
9245            },
9246            When::PerTarget(p) => Lowered {
9247                cron: POLL_CRON.into(),
9248                mode: ExecMode::OncePerTarget,
9249                cooldown: p.cooldown(),
9250                tz,
9251            },
9252            // `to_cron` only fails on a malformed `at` (rejected by
9253            // validate() at create time). For a hand-edited KV blob
9254            // that slipped past, emit a deliberately-invalid cron so
9255            // register()'s Job::new_async_tz fails → warn+skip,
9256            // rather than firing at the wrong time.
9257            When::Calendar(c) => Lowered {
9258                cron: c
9259                    .to_cron()
9260                    .unwrap_or_else(|_| "# invalid calendar at".into()),
9261                mode: ExecMode::EveryTick,
9262                cooldown: None,
9263                tz,
9264            },
9265            // Event triggers have no cron — the agent fires them from an
9266            // OS event source. The `# event-trigger` cron is never
9267            // registered (the scheduler branches on `is_event()` first),
9268            // but keep it deliberately-invalid as a belt-and-suspenders
9269            // so a stray registration would fail rather than misfire.
9270            When::On(_) => Lowered {
9271                cron: "# event-trigger (no cron)".into(),
9272                mode: ExecMode::Event,
9273                cooldown: None,
9274                tz,
9275            },
9276        }
9277    }
9278
9279    /// True when this schedule fires from an OS event (`when: { on }`)
9280    /// rather than a clock — the agent skips `tokio-cron` registration
9281    /// for these and drives them from boot / session-change instead.
9282    pub fn is_event(&self) -> bool {
9283        matches!(self.when, When::On(_))
9284    }
9285
9286    /// The OS event triggers this schedule listens for, or `&[]` when it
9287    /// is not an event schedule.
9288    pub fn event_triggers(&self) -> &[OnTrigger] {
9289        match &self.when {
9290            When::On(t) => t,
9291            _ => &[],
9292        }
9293    }
9294
9295    /// The next absolute (UTC) time this schedule fires, or `None` when
9296    /// it has no discrete upcoming fire to preview.
9297    ///
9298    /// Used by the KLP `maintenance.list` preview ("what's about to
9299    /// happen on my PC", SPEC §2.1). Returns `None` for:
9300    ///
9301    /// - reconcile shapes (`per_pc` / `per_target`) — they lower to the
9302    ///   every-minute [`POLL_CRON`] and re-converge state continuously,
9303    ///   so "next fire" is always ~60s away and means nothing to a user
9304    ///   previewing upcoming maintenance;
9305    /// - a calendar schedule whose lowered cron won't parse (a
9306    ///   hand-edited KV blob that slipped past [`Schedule::validate`]);
9307    /// - a cron with no future occurrence.
9308    ///
9309    /// The wall-clock fire is evaluated in the schedule's own `tz`
9310    /// (matching the live tick's `Job::new_async_tz`) then normalised
9311    /// to UTC for the wire. `inclusive = false`: strictly the *next*
9312    /// fire after `now`, never one matching the current instant.
9313    pub fn next_calendar_fire(
9314        &self,
9315        now: chrono::DateTime<chrono::Utc>,
9316    ) -> Option<chrono::DateTime<chrono::Utc>> {
9317        if !matches!(self.when, When::Calendar(_)) {
9318            return None;
9319        }
9320        let lowered = self.lowered();
9321        // Same parser configuration tokio-cron-scheduler 0.15 uses
9322        // internally, so this can never compute a fire the live
9323        // scheduler wouldn't (seconds required, DOM-and-DOW honored).
9324        let cron = croner::parser::CronParser::builder()
9325            .seconds(croner::parser::Seconds::Required)
9326            .dom_and_dow(true)
9327            .build()
9328            .parse(&lowered.cron)
9329            .ok()?;
9330        match lowered.tz {
9331            ScheduleTz::Utc => cron.find_next_occurrence(&now, false).ok(),
9332            ScheduleTz::Local => {
9333                let now_local = now.with_timezone(&chrono::Local);
9334                cron.find_next_occurrence(&now_local, false)
9335                    .ok()
9336                    .map(|t| t.with_timezone(&chrono::Utc))
9337            }
9338        }
9339    }
9340
9341    /// Cross-field semantic checks that don't fit pure serde derive
9342    /// — the [`Manifest::validate`] counterpart (#418 decision F;
9343    /// pre-Phase-1 a broken schedule was accepted at create time
9344    /// and silently warn-skipped at tick time). Run at every create
9345    /// site: `kanade schedule create` (client-side) and
9346    /// `POST /api/schedules`. The job_id-exists check lives in the
9347    /// API handler instead — it needs the JOBS KV.
9348    pub fn validate(&self) -> Result<(), String> {
9349        if matches!(self.runs_on, RunsOn::Agent) && matches!(self.when, When::PerTarget(_)) {
9350            return Err(
9351                "when.per_target needs fleet-wide completion data and is backend-only; \
9352                 it cannot be combined with runs_on: agent (each agent self-schedules, \
9353                 so per-target dedup would be deduping across a target of 1)"
9354                    .into(),
9355            );
9356        }
9357        // `once_per_version` is a per_pc-only shape: it re-arms an
9358        // individual pc when the manifest version it succeeded at is no
9359        // longer current. "One delegate per version" for a whole target
9360        // has no clear meaning, so reject it rather than silently
9361        // lowering to plain per_target (version-blind).
9362        if matches!(self.when, When::PerTarget(PerPolicy::OncePerVersion(_))) {
9363            return Err(
9364                "when.per_target: once_per_version is not supported — once_per_version \
9365                 re-arms per pc per manifest version, which only makes sense for per_pc. \
9366                 Use `per_pc: once_per_version`."
9367                    .into(),
9368            );
9369        }
9370        // `once_per_version` keys its dedup on the backend's
9371        // `execution_results.version` history. A runs_on: agent schedule
9372        // self-schedules from the agent's local completion map, which has
9373        // no per-version record, so it is backend-only (symmetric with
9374        // per_target). Reject it rather than silently degrade to
9375        // version-blind kitting-once on the agent.
9376        if matches!(self.runs_on, RunsOn::Agent)
9377            && matches!(self.when, When::PerPc(PerPolicy::OncePerVersion(_)))
9378        {
9379            return Err(
9380                "when.per_pc: once_per_version keys its dedup on the backend's per-version \
9381                 completion history and is backend-only; it cannot be combined with \
9382                 runs_on: agent (the agent self-schedules with no per-version record). \
9383                 Use runs_on: backend."
9384                    .into(),
9385            );
9386        }
9387        // #418 event triggers: the agent owns the OS event source
9388        // (boot / session-change), so `when: { on }` is agent-only and
9389        // needs at least one trigger.
9390        if let When::On(triggers) = &self.when {
9391            if !matches!(self.runs_on, RunsOn::Agent) {
9392                return Err(
9393                    "when.on (OS event trigger) is fired by the agent's own event \
9394                     source, so it requires runs_on: agent"
9395                        .into(),
9396                );
9397            }
9398            if triggers.is_empty() {
9399                return Err(
9400                    "when.on must list at least one trigger (e.g. [startup, logon])".into(),
9401                );
9402            }
9403        }
9404        if let Some(cd) = self.lowered().cooldown.as_deref() {
9405            humantime::parse_duration(cd)
9406                .map_err(|e| format!("when.every: invalid duration '{cd}': {e}"))?;
9407        }
9408        if let When::Calendar(c) = &self.when {
9409            // Lower the calendar form to its cron (catches a bad `at`
9410            // and the date+days conflict), then validate that cron
9411            // with the same parser configuration tokio-cron-scheduler
9412            // 0.15 uses internally (croner, seconds required,
9413            // DOM-and-DOW both honored, year optional) — create-time
9414            // validation can never accept what register() rejects.
9415            let cron = c.to_cron()?;
9416            croner::parser::CronParser::builder()
9417                .seconds(croner::parser::Seconds::Required)
9418                .dom_and_dow(true)
9419                .build()
9420                .parse(&cron)
9421                .map_err(|e| format!("when.at lowered to invalid cron '{cron}': {e}"))?;
9422        }
9423        // The other humantime strings on the schedule (claude #419
9424        // review): runtime degrades gracefully on both (bad jitter →
9425        // silent no-op, bad starting_deadline → warn + skipped tick),
9426        // but "rejected at create time" should cover every field the
9427        // operator can typo, not just `when`.
9428        if let Some(j) = &self.plan.jitter {
9429            humantime::parse_duration(j)
9430                .map_err(|e| format!("jitter: invalid duration '{j}': {e}"))?;
9431        }
9432        if let Some(sd) = &self.starting_deadline {
9433            humantime::parse_duration(sd)
9434                .map_err(|e| format!("starting_deadline: invalid duration '{sd}': {e}"))?;
9435        }
9436        // #917: the plan side got almost no create-time checks, so
9437        // several never-fires / fails-every-tick shapes were accepted
9438        // and only surfaced at dispatch time — or never:
9439        //
9440        // (1) a target that dispatches nothing. A runs_on: agent
9441        // schedule matches each agent against `target` (rollout waves
9442        // are backend-published and never reach that path), so an
9443        // unspecified target silently never fires; a runs_on: backend
9444        // one warn-fails every tick at the exec boundary, which
9445        // rejects the same shape with the same message.
9446        let has_waves = self
9447            .plan
9448            .rollout
9449            .as_ref()
9450            .is_some_and(|r| !r.waves.is_empty());
9451        if matches!(self.runs_on, RunsOn::Agent) {
9452            if !self.plan.target.is_specified() {
9453                return Err(
9454                    "target must specify at least one of `all` / `groups` / `pcs` — a \
9455                     runs_on: agent schedule matches each agent against `target`, so an \
9456                     unspecified target never fires anywhere"
9457                        .into(),
9458                );
9459            }
9460            if self.plan.rollout.is_some() {
9461                return Err(
9462                    "rollout waves are published by the backend and are ignored by \
9463                     runs_on: agent schedules (each agent self-schedules from `target`); \
9464                     drop `rollout:` or use runs_on: backend"
9465                        .into(),
9466                );
9467            }
9468        } else if !has_waves && !self.plan.target.is_specified() {
9469            return Err(
9470                "target must specify at least one of `all` / `groups` / `pcs` \
9471                 (or set `rollout.waves`) — the exec boundary rejects an \
9472                 unspecified target, so the schedule would fail every tick"
9473                    .into(),
9474            );
9475        }
9476        // (2) rollout waves were never validated: a blank group or an
9477        // unparseable delay failed at EVERY fire (the CLI doesn't even
9478        // expose waves, so the failure was always deferred to dispatch)
9479        // and an empty list dispatched nothing. (3) A wave delayed to
9480        // or past starting_deadline is dead on arrival: the deadline is
9481        // stamped once at tick time and the Command is serialised
9482        // before the wave sleep, so agents receive it already expired
9483        // (a synthetic exit-125 skip on every fire).
9484        if let Some(rollout) = &self.plan.rollout {
9485            if rollout.waves.is_empty() {
9486                return Err(
9487                    "rollout.waves must list at least one wave; omit `rollout:` for a \
9488                     one-shot fan-out of `target`"
9489                        .into(),
9490                );
9491            }
9492            let deadline = self
9493                .starting_deadline
9494                .as_deref()
9495                .and_then(|sd| humantime::parse_duration(sd).ok());
9496            for (i, wave) in rollout.waves.iter().enumerate() {
9497                if wave.group.trim().is_empty() {
9498                    return Err(format!("rollout.waves[{i}].group must not be blank"));
9499                }
9500                let delay = humantime::parse_duration(&wave.delay).map_err(|e| {
9501                    format!(
9502                        "rollout.waves[{i}].delay: invalid duration '{}': {e}",
9503                        wave.delay
9504                    )
9505                })?;
9506                if let Some(deadline) = deadline
9507                    && delay >= deadline
9508                {
9509                    return Err(format!(
9510                        "rollout.waves[{i}].delay ('{}') must be shorter than \
9511                         starting_deadline ('{}'): the deadline is stamped at tick time, \
9512                         so this wave's Commands would already be expired when published \
9513                         (skipped by every agent, every fire)",
9514                        wave.delay,
9515                        self.starting_deadline.as_deref().unwrap_or_default(),
9516                    ));
9517                }
9518            }
9519        }
9520        // (4) deadline_at is machine-stamped: the scheduler overwrites
9521        // it from `tick + starting_deadline` on every fire, so an
9522        // operator-set value is silently discarded — reject it and
9523        // point at the knob that does what they meant. (Ad-hoc POST
9524        // /api/exec bodies are a different write path and may still
9525        // carry it.)
9526        if self.plan.deadline_at.is_some() {
9527            return Err(
9528                "deadline_at is computed by the scheduler (tick time + starting_deadline) \
9529                 and overwritten on every fire — set `starting_deadline` instead"
9530                    .into(),
9531            );
9532        }
9533        let from = self
9534            .active
9535            .from
9536            .as_deref()
9537            .map(|s| Active::parse_bound(s, self.tz))
9538            .transpose()?;
9539        let until = self
9540            .active
9541            .until
9542            .as_deref()
9543            .map(|s| Active::parse_bound(s, self.tz))
9544            .transpose()?;
9545        if let (Some(f), Some(u)) = (from, until) {
9546            if f >= u {
9547                return Err(format!(
9548                    "active.from ({}) must be strictly before active.until ({})",
9549                    self.active.from.as_deref().unwrap_or_default(),
9550                    self.active.until.as_deref().unwrap_or_default(),
9551                ));
9552            }
9553        }
9554        // #418 Phase 3: a bad maintenance window is rejected at create
9555        // time (parse_window also catches equal bounds).
9556        if let Some(w) = self.constraints.window.as_deref() {
9557            Constraints::parse_window(w)?;
9558        }
9559        // #418 holiday exclusion: reject a malformed skip date at create
9560        // time so the fail-closed `allows` path only ever bites a
9561        // hand-edited KV blob, not a fresh `kanade schedule create`.
9562        if let Some(err) = self.constraints.bad_skip_date() {
9563            return Err(err);
9564        }
9565        // #418: constraints.max_concurrent is a central running-instance
9566        // cap, so it needs the backend's counter — reject it on
9567        // runs_on: agent (decision E), and reject a meaningless 0.
9568        if let Some(mc) = self.constraints.max_concurrent {
9569            // Check the structural incompatibility (agent has no central
9570            // counter) before the value range, so a `max_concurrent: 0`
9571            // + `runs_on: agent` combo reports the more fundamental
9572            // problem first (claude #542).
9573            if matches!(self.runs_on, RunsOn::Agent) {
9574                return Err(
9575                    "constraints.max_concurrent needs a central counter and is backend-only; \
9576                     it cannot be combined with runs_on: agent (each agent self-schedules, \
9577                     so there is no fleet-wide count to cap against)"
9578                        .into(),
9579                );
9580            }
9581            if mc == 0 {
9582                return Err(
9583                    "constraints.max_concurrent must be >= 1 (0 would never fire; \
9584                     omit it for no cap)"
9585                        .into(),
9586                );
9587            }
9588        }
9589        // #418: constraints.require (host-state env gates: ac_power /
9590        // idle / cpu_below / network) is sensed in-process by the agent,
9591        // so it needs runs_on: agent — the backend can't read a target
9592        // host's power / idle / cpu / connectivity state. Symmetric with
9593        // `when: { on }` (also agent-only); inverse of max_concurrent
9594        // (backend-only).
9595        if let Some(req) = &self.constraints.require {
9596            if !req.is_empty() && matches!(self.runs_on, RunsOn::Backend) {
9597                return Err(
9598                    "constraints.require (host-state env gates: ac_power / idle / cpu_below / \
9599                     network) is sensed in-process by the agent and needs runs_on: agent; the \
9600                     backend cannot read a target host's power / idle / cpu / connectivity state"
9601                        .into(),
9602                );
9603            }
9604            // Reject a malformed idle duration at create time so the
9605            // fail-closed runtime path only ever bites a hand-edited
9606            // KV blob (mirror skip_dates / on_failure.retry).
9607            if let Some(err) = req.bad_idle() {
9608                return Err(err);
9609            }
9610            // cpu_below is a percent — reject out-of-range so a typo
9611            // can't make a schedule that never (>=100 is always-busy?
9612            // no — <0 never matches) or trivially fires.
9613            if let Some(c) = req.cpu_below
9614                && !(c > 0.0 && c <= 100.0)
9615            {
9616                return Err(format!(
9617                    "constraints.require.cpu_below must be in (0, 100] percent (got {c}); \
9618                     omit it for no CPU requirement"
9619                ));
9620            }
9621        }
9622        // #418 Phase 4: a bad on_failure.retry is rejected at create
9623        // time — backoff must be valid humantime, and max is bounded
9624        // so a typo can't pin a flapping script in a tight loop.
9625        if let Some(r) = &self.on_failure.retry {
9626            let backoff = humantime::parse_duration(&r.backoff).map_err(|e| {
9627                format!(
9628                    "on_failure.retry.backoff: invalid duration '{}': {e}",
9629                    r.backoff
9630                )
9631            })?;
9632            // The wire form lowers backoff to whole seconds, so a
9633            // sub-second value would silently become a 0s no-wait
9634            // (coderabbit #466). Reject it rather than honour a backoff
9635            // the operator can't actually get.
9636            if backoff.as_secs() < 1 {
9637                return Err(format!(
9638                    "on_failure.retry.backoff must be >= 1s (got '{}'); sub-second backoffs \
9639                     round to 0 on the wire",
9640                    r.backoff
9641                ));
9642            }
9643            if !(1..=10).contains(&r.max) {
9644                return Err(format!(
9645                    "on_failure.retry.max must be 1..=10 (got {}); it counts additional \
9646                     attempts after the first run",
9647                    r.max
9648                ));
9649            }
9650        }
9651        // A blank / whitespace-only tag renders an empty filter chip on
9652        // the Schedules page — reject it at create time, mirroring the
9653        // Manifest::validate tag guard.
9654        for tag in &self.tags {
9655            if tag.trim().is_empty() {
9656                return Err("tags must not contain empty entries".to_string());
9657            }
9658        }
9659        Ok(())
9660    }
9661}
9662
9663/// Shared `serde(default)` for `bool` fields that default to `true`
9664/// (e.g. `CheckHint::fleet` / `CheckHint::health`). Generic name so it
9665/// doesn't read as "fleet" when reused for `health`.
9666fn default_true() -> bool {
9667    true
9668}