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) — matches pre-v0.21 behavior.
2420    #[serde(default)]
2421    pub run_as: RunAs,
2422    /// Working directory for the spawned child (v0.21.1). When
2423    /// unset, the child inherits the agent's cwd — on Windows that
2424    /// means `%SystemRoot%\System32` for the prod service, which is
2425    /// almost never what operators actually want. Use an absolute
2426    /// path; relative paths are passed through to the OS verbatim.
2427    /// `%PROGRAMDATA%` works for `run_as: system`; for `run_as: user`
2428    /// you'd want `%USERPROFILE%` (but expansion happens in the
2429    /// shell, so write `$env:USERPROFILE` for PowerShell, or set
2430    /// it via teravars before `kanade job create`).
2431    #[serde(default, skip_serializing_if = "Option::is_none")]
2432    pub cwd: Option<String>,
2433}
2434
2435impl Execute {
2436    /// Treat an empty — or whitespace-only (#918) — `script:` body as
2437    /// "intentionally unset". Operators commenting out a block-scalar
2438    /// tend to leave the key behind, and failing the validator on
2439    /// `script: ""` would surprise them; a body of blank lines can't
2440    /// be a real script either, only a commented-out one, and letting
2441    /// it count as "set" shipped a validated do-nothing job.
2442    fn has_inline_script(&self) -> bool {
2443        matches!(&self.script, Some(s) if !s.trim().is_empty())
2444    }
2445
2446    /// Enforce that exactly one of `script` / `script_file` /
2447    /// `script_object` is set. Called at the write-side parse
2448    /// boundaries (CLI `kanade job create` + backend
2449    /// `POST /api/jobs`) so ambiguous YAML is rejected before it
2450    /// reaches the JOBS KV. Read paths (projector, agent
2451    /// scheduler, list endpoints) skip this check — they only ever
2452    /// see what the write path already validated.
2453    pub fn validate_script_source(&self) -> Result<(), String> {
2454        // #918: a blank-but-present alternate source is a typo, not a
2455        // choice — `script_file: ""` used to count as "set", pass the
2456        // exactly-one check, and only fail at use time (the CLI reads
2457        // a file named ""; a stored blank script_object 404s on every
2458        // exec). Reject it with the field named. Inline `script` keeps
2459        // its documented empty-means-unset semantics instead — see
2460        // `has_inline_script`.
2461        if matches!(&self.script_file, Some(s) if s.trim().is_empty()) {
2462            return Err(
2463                "execute.script_file must not be blank when set (drop the key to use \
2464                 another source)"
2465                    .into(),
2466            );
2467        }
2468        if matches!(&self.script_object, Some(s) if s.trim().is_empty()) {
2469            return Err(
2470                "execute.script_object must not be blank when set (drop the key to use \
2471                 another source)"
2472                    .into(),
2473            );
2474        }
2475        let inline = self.has_inline_script();
2476        let file = self.script_file.is_some();
2477        let obj = self.script_object.is_some();
2478        let set = [inline, file, obj].into_iter().filter(|b| *b).count();
2479        match set {
2480            1 => {}
2481            0 => {
2482                return Err(
2483                    "execute: one of `script`, `script_file`, `script_object` must be set".into(),
2484                );
2485            }
2486            _ => {
2487                return Err(format!(
2488                    "execute: only one of `script` / `script_file` / `script_object` may be set \
2489                     (got script={inline}, script_file={file}, script_object={obj})"
2490                ));
2491            }
2492        }
2493        // #918: a script_object ref is `<name>/<version>` — the agent
2494        // fetches the body via `/api/script-objects/{name}/{version}`
2495        // and the backend uses the ref *verbatim* as the Object Store
2496        // key (`resolve_script_source`), so each half must be a
2497        // well-formed resource id: exactly one slash, and both halves
2498        // [A-Za-z0-9._-]. `is_valid_resource_id` also rejects a half
2499        // that's blank OR merely whitespace-padded (`"foo/bar "`) —
2500        // padding survives a JSON POST body (unlike a YAML plain
2501        // scalar) and would 404 on every exec (gemini/claude #943).
2502        if let Some(obj_ref) = self.script_object.as_deref() {
2503            let parts: Vec<&str> = obj_ref.split('/').collect();
2504            if parts.len() != 2 || parts.iter().any(|p| !is_valid_resource_id(p)) {
2505                return Err(format!(
2506                    "execute.script_object must be `<name>/<version>` with each half \
2507                     [A-Za-z0-9._-] (got '{obj_ref}'); publish bodies with \
2508                     `kanade script publish <name> <version>`"
2509                ));
2510            }
2511        }
2512        Ok(())
2513    }
2514}
2515
2516/// Job-generic post-step hook (see [`Manifest::finalize`]). Runs after
2517/// the main `execute:` script (and the collect upload) on a clean exit,
2518/// with the step's structured result injected via an environment
2519/// variable. P1 supports an inline `script:` only — `script_file:` /
2520/// `script_object:` are follow-ups.
2521#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2522pub struct FinalizeSpec {
2523    pub shell: ExecuteShell,
2524    /// Inline script body (required; inline-only in P1).
2525    pub script: String,
2526    /// humantime duration string (e.g. `"60s"`, `"5m"`). Defaults to
2527    /// `60s` when unset.
2528    #[serde(default = "default_finalize_timeout")]
2529    pub timeout: String,
2530    /// Token + session combination, like [`Execute::run_as`]. Defaults
2531    /// to [`RunAs::System`].
2532    #[serde(default)]
2533    pub run_as: RunAs,
2534    /// Working directory for the hook child, like [`Execute::cwd`].
2535    #[serde(default, skip_serializing_if = "Option::is_none")]
2536    pub cwd: Option<String>,
2537    /// #965: for a `collect:` job, run this hook once per uploaded
2538    /// bundle (with a single-bundle `KANADE_COLLECT_RESULT`) as each
2539    /// bundle uploads, instead of once after the whole set. Lets an
2540    /// interrupted collect still clean up the days it managed to
2541    /// upload (partial progress sticks), breaking the
2542    /// offline-before-finalize backlog spiral.
2543    ///
2544    /// **Opt-in** (default `false` = one call after all bundles, the
2545    /// established contract) because per-bundle changes the hook's
2546    /// payload (all → one) and invocation count (1 → N), which would
2547    /// break a hook written for the all-at-once assumption (cross-bundle
2548    /// aggregation, once-only side effects, all-or-nothing). Only valid
2549    /// with a `collect:` hint — [`Manifest::validate`] rejects it
2550    /// otherwise, since a non-collect finalize has no bundles to iterate.
2551    #[serde(default)]
2552    pub on_each_bundle: bool,
2553}
2554
2555/// Default `finalize.timeout` when the operator omits it.
2556fn default_finalize_timeout() -> String {
2557    "60s".to_string()
2558}
2559
2560impl FinalizeSpec {
2561    /// Lower to the wire form forwarded onto a [`Command`]. The timeout
2562    /// parse falls back to 60s — [`Manifest::validate`] already rejects
2563    /// an unparseable value at create time, so the fire path uses a safe
2564    /// default rather than failing (mirrors
2565    /// [`CollectHint::max_size_bytes`]). A sub-second timeout floors at
2566    /// 1s for the same reason `build_command` does.
2567    pub fn lower(&self) -> FinalizeCommand {
2568        let timeout_secs = humantime::parse_duration(&self.timeout)
2569            .map(|d| d.as_secs().max(1))
2570            .unwrap_or(60);
2571        FinalizeCommand {
2572            shell: self.shell.into(),
2573            script: self.script.clone(),
2574            timeout_secs,
2575            run_as: self.run_as,
2576            cwd: self.cwd.clone(),
2577            on_each_bundle: self.on_each_bundle,
2578        }
2579    }
2580}
2581
2582impl Manifest {
2583    /// Cross-field semantic checks that don't fit into pure serde
2584    /// derive. Currently delegates to
2585    /// [`Execute::validate_script_source`] — see that method's
2586    /// docs for the rationale on which call sites should run this.
2587    pub fn validate(&self) -> Result<(), String> {
2588        self.execute.validate_script_source()?;
2589        // Fail CLOSED on an unrecognised execution tier. `#[serde(other)]`
2590        // turns a typo (`tier: controler`) or a future tier into
2591        // `Tier::Unknown`; without this check the controller gate would
2592        // fall back to normal endpoint dispatch, so an operator who *meant*
2593        // to confine a job to the controller tier would silently get
2594        // fleet-wide dispatch (CodeRabbit #905). Rejecting it at the write
2595        // boundary surfaces the typo at `job create`, and — since
2596        // `exec_manifest` re-validates — a hand-poked KV manifest can't slip
2597        // a controller-tier job onto endpoints either.
2598        if matches!(self.tier, Some(Tier::Unknown)) {
2599            return Err(
2600                "tier: unrecognised execution tier — use `endpoint` or `controller` \
2601                 (this is a typo, or a tier a newer kanade supports that this backend does not)"
2602                    .to_string(),
2603            );
2604        }
2605        // #vuln-roadmap: a `feed:` spec drives the global `feeds`
2606        // projection. id / item_id are stored as *values* (the `feeds`
2607        // table is fixed-schema — no identifier splicing), but blank
2608        // values are silent projection bugs: a blank id collides every
2609        // feed under "", a blank field never matches the payload array,
2610        // and an empty primary_key yields no item_id (every row dropped).
2611        // Reject them at the write boundary so `kanade job create` surfaces
2612        // the typo instead of producing an empty/garbled feed at run time.
2613        let mut seen_feed_ids: Vec<&str> = Vec::new();
2614        for spec in &self.feed {
2615            let id = spec.id.trim();
2616            if id.is_empty() {
2617                return Err("feed.id must not be empty".to_string());
2618            }
2619            if spec.field.trim().is_empty() {
2620                return Err(format!("feed '{id}' field must not be empty"));
2621            }
2622            if spec.primary_key.is_empty() {
2623                return Err(format!("feed '{id}' needs at least one primary_key field"));
2624            }
2625            if spec.primary_key.iter().any(|k| k.trim().is_empty()) {
2626                return Err(format!(
2627                    "feed '{id}' primary_key must not contain blank entries"
2628                ));
2629            }
2630            // Two specs sharing an id both target the same `feeds`
2631            // partition and would clobber each other on every run —
2632            // reject the ambiguity rather than let last-write-wins.
2633            if seen_feed_ids.contains(&id) {
2634                return Err(format!("feed id '{id}' is declared more than once"));
2635            }
2636            seen_feed_ids.push(id);
2637        }
2638        // A `feed:` job fetches external data and MUST run on the trusted
2639        // controller tier — the dispatch guard (`requires_controller`) treats
2640        // a non-empty `feed:` as implying `controller`. An explicit
2641        // `tier: endpoint` contradicts that intent; reject it rather than
2642        // silently overriding, so the operator can't believe a feed runs on
2643        // endpoints. Omitting `tier:` (the default) is fine — the implication
2644        // confines it; `tier: controller` is the redundant-but-explicit form.
2645        if !self.feed.is_empty() && matches!(self.tier, Some(Tier::Endpoint)) {
2646            return Err(
2647                "feed: requires the controller tier — remove `tier: endpoint` (a feed: job \
2648                 fetches external data and is confined to the controller_group)"
2649                    .to_string(),
2650            );
2651        }
2652        // A present-but-empty finalize script is an invisible no-op
2653        // (the hook would run an empty body); reject it at the write
2654        // boundary. Inline-only in P1, so `script` is the sole source.
2655        if let Some(finalize) = &self.finalize {
2656            if finalize.script.trim().is_empty() {
2657                return Err("finalize.script must not be empty".to_string());
2658            }
2659            // Reject an unparseable timeout at the write boundary so the
2660            // operator sees the error at `job create` rather than getting
2661            // a silent fire-time fallback (`FinalizeSpec::lower` floors to
2662            // 60s, which would otherwise mask a typo).
2663            if humantime::parse_duration(&finalize.timeout).is_err() {
2664                return Err(format!(
2665                    "finalize.timeout '{}' is not a valid duration",
2666                    finalize.timeout
2667                ));
2668            }
2669            // Disallow cmd for finalize: the agent injects the result JSON
2670            // into the hook's environment, and cmd.exe quoting doesn't
2671            // nest — JSON's `"` plus shell metacharacters in a collected
2672            // path/key could break out into command injection at the
2673            // agent's (often LocalSystem) privilege. PowerShell's
2674            // single-quote escaping is safe, and finalize hooks are
2675            // PowerShell by convention anyway.
2676            // `sh` is rejected for the same injection reason (its
2677            // single-word quoting doesn't nest around the JSON result
2678            // either), and additionally because the injected prelude is
2679            // PowerShell syntax (`$env:KANADE_COLLECT_RESULT = '...'`) —
2680            // it would be malformed in a POSIX shell. `pwsh` IS allowed:
2681            // it's PowerShell, so the prelude + single-quote escaping are
2682            // valid and safe.
2683            if matches!(finalize.shell, ExecuteShell::Cmd | ExecuteShell::Sh) {
2684                return Err(
2685                    "finalize.shell: cmd and sh are not supported for finalize hooks \
2686                     (shell-injection risk when the result JSON is injected, and the injected \
2687                     prelude is PowerShell syntax); use powershell or pwsh"
2688                        .to_string(),
2689                );
2690            }
2691            // #965: per-bundle finalize only means anything for a
2692            // collect: job — a non-collect finalize has no bundles to
2693            // iterate (it runs once after the script). Reject the
2694            // combination at the write boundary so a confused operator
2695            // is told rather than silently getting a no-op.
2696            if finalize.on_each_bundle && self.collect.is_none() {
2697                return Err(
2698                    "finalize.on_each_bundle: true requires a collect: hint — a non-collect \
2699                     finalize has no bundles to iterate (it runs once after the script)"
2700                        .to_string(),
2701                );
2702            }
2703        }
2704        // Stdout-format compatibility (#821). `inventory:` / `check:` /
2705        // `collect:` now COMPOSE: each reads its own `#KANADE-<KIND>-
2706        // BEGIN/END`-fenced JSON block from stdout, so a single job can
2707        // project inventory facts, drive a Health-tab check, AND collect
2708        // files in one run. (A single-hint job may still skip the fence;
2709        // a multi-hint job must fence each block.)
2710        //
2711        // `emit:` remains the exception — its stdout is line-delimited
2712        // NDJSON consumed whole and then omitted from the result — so it
2713        // can't share stdout with any fenced hint. `feed:` is another fenced
2714        // stdout consumer (`#KANADE-FEED`), so it belongs in this exclusion
2715        // too: with `emit:` present the projector never sees the feed's fence
2716        // (CodeRabbit).
2717        if self.emit.is_some()
2718            && (self.inventory.is_some()
2719                || self.check.is_some()
2720                || self.collect.is_some()
2721                || !self.feed.is_empty())
2722        {
2723            return Err(
2724                "`emit:` is incompatible with `inventory:` / `check:` / `collect:` / `feed:` — \
2725                 emit's stdout is NDJSON timeline events (consumed whole and omitted from the \
2726                 result), while the others read fenced JSON blocks from stdout"
2727                    .to_string(),
2728            );
2729        }
2730        // A check's `name` is the Health-tab row id (React key); the
2731        // field names tell the agent where to read status/detail.
2732        // An empty value is an invisible runtime bug, and the serde
2733        // defaults don't guard an operator who writes `status_field:
2734        // ""` explicitly — reject all three here.
2735        if let Some(check) = &self.check {
2736            for (label, value) in [
2737                ("check.name", &check.name),
2738                ("check.status_field", &check.status_field),
2739                ("check.detail_field", &check.detail_field),
2740            ] {
2741                if value.trim().is_empty() {
2742                    return Err(format!("{label} must not be empty"));
2743                }
2744            }
2745            // A present-but-blank `troubleshoot` is a broken
2746            // remediation job id (the "修復する" button would target
2747            // an empty manifest id) — reject it too.
2748            if let Some(troubleshoot) = &check.troubleshoot {
2749                if troubleshoot.trim().is_empty() {
2750                    return Err("check.troubleshoot must not be empty when set".to_string());
2751                }
2752            }
2753            // A present-but-blank `label` would render an empty row
2754            // title on the Health tab / Compliance page — reject it so
2755            // the slug fallback only ever kicks in when label is absent.
2756            if let Some(label) = &check.label {
2757                if label.trim().is_empty() {
2758                    return Err("check.label must not be empty when set".to_string());
2759                }
2760            }
2761            if let Some(alert) = &check.alert {
2762                // An alert that names no recipient is a silent no-op.
2763                if !alert.notify_user && alert.notify_groups.is_empty() {
2764                    return Err("check.alert must set notify_user and/or notify_groups".to_string());
2765                }
2766                if alert.title.trim().is_empty() {
2767                    return Err("check.alert.title must not be empty".to_string());
2768                }
2769                // `on: []` would never fire; an empty group name resolves to
2770                // a malformed `notifications.group.` subject.
2771                if alert.on.is_empty() {
2772                    return Err("check.alert.on must list at least one status".to_string());
2773                }
2774                if alert.notify_groups.iter().any(|g| g.trim().is_empty()) {
2775                    return Err("check.alert.notify_groups must not contain blanks".to_string());
2776                }
2777                // Email is addressed via group_contacts (group → email), so
2778                // there must be a group to map. notify_user has no email.
2779                if alert.email && alert.notify_groups.is_empty() {
2780                    return Err(
2781                        "check.alert.email requires notify_groups (email is addressed per group, not per user)"
2782                            .to_string(),
2783                    );
2784                }
2785                // The alert rides the `check_status` projection, which only
2786                // runs for `fleet: true`.
2787                if !check.fleet {
2788                    return Err(
2789                        "check.alert requires fleet: true (the alert rides the compliance projection)"
2790                            .to_string(),
2791                    );
2792                }
2793            }
2794        }
2795        // #291: a `client:` job is rendered in the Client App's
2796        // catalog (`jobs.list` → `jobs.execute`). serde already makes
2797        // `name` + `category` required at parse time; the only gap is
2798        // a present-but-blank `name`, which would render an empty row
2799        // title — reject it like the other display-id fields.
2800        if let Some(client) = &self.client {
2801            if client.name.trim().is_empty() {
2802                return Err("client.name must not be empty".to_string());
2803            }
2804            // #792: category is a free-form key now, so a blank one would
2805            // group the job under an empty tab — reject it like `name`.
2806            if client.category.trim().is_empty() {
2807                return Err("client.category must not be empty".to_string());
2808            }
2809            // Optional display fields, when present, must be
2810            // meaningful: a blank `description` renders an empty
2811            // subtitle and a blank `icon` is a dangling lucide name.
2812            // Same present-but-blank guard the `check:` block applies
2813            // to its optional `troubleshoot` id.
2814            for (label, value) in [
2815                ("client.description", &client.description),
2816                ("client.icon", &client.icon),
2817                ("client.category_label", &client.category_label),
2818                ("client.category_icon", &client.category_icon),
2819            ] {
2820                if let Some(v) = value {
2821                    if v.trim().is_empty() {
2822                        return Err(format!("{label} must not be empty when set"));
2823                    }
2824                }
2825            }
2826            // #816: a present-but-empty `visible_to` (no all/groups/pcs)
2827            // would hide the job from everyone in the Client App — almost
2828            // certainly a mistake. Require at least one selector; omit the
2829            // whole block to mean "visible to all".
2830            if let Some(t) = &client.visible_to {
2831                if !t.is_specified() {
2832                    return Err(
2833                        "client.visible_to must set at least one of all / groups / pcs (omit it for all PCs)"
2834                            .to_string(),
2835                    );
2836                }
2837            }
2838            // show_when: a dynamic display gate keyed on a check result. A
2839            // malformed check slug matches nothing and an empty status list
2840            // matches nothing — both would silently hide the job forever,
2841            // so reject them at create time rather than at a confused
2842            // "why isn't my job showing?" later. The slug must be a clean
2843            // resource id (same charset checks/jobs use): a typo with spaces
2844            // or punctuation can never match a real check name, so catch it
2845            // here instead of failing closed at runtime. (Whether the slug
2846            // names a check that actually EXISTS can't be checked here —
2847            // checks are keyed by name across manifests — so a valid-but-
2848            // unknown slug stays a runtime miss = hidden, the documented
2849            // fail-closed behavior.)
2850            if let Some(sw) = &client.show_when {
2851                if !is_valid_resource_id(sw.check.trim()) {
2852                    return Err(
2853                        "client.show_when.check must be a non-empty check slug ([A-Za-z0-9._-])"
2854                            .to_string(),
2855                    );
2856                }
2857                if sw.is.is_empty() {
2858                    return Err(
2859                        "client.show_when.is must list at least one check status".to_string()
2860                    );
2861                }
2862            }
2863            // confirm: a present-but-blank custom message would render an
2864            // empty dialog title — reject it like the other display fields.
2865            // (A `confirm: false` / `enabled: false` with no message is fine:
2866            // the dialog is suppressed, so there's nothing to render.)
2867            if let Some(c) = &client.confirm {
2868                if let Some(msg) = &c.message {
2869                    if msg.trim().is_empty() {
2870                        return Err("client.confirm.message must not be empty when set".to_string());
2871                    }
2872                }
2873            }
2874            // unlock: the scope slug is matched byte-for-byte against the
2875            // operator's configured `support_codes[].scope`, so a slug with
2876            // stray whitespace / punctuation can never match one — and
2877            // because the gate fails closed, the job would simply be
2878            // invisible forever with no error anywhere. Reject it at create
2879            // time. (Whether a code is actually CONFIGURED for the scope
2880            // can't be checked here — that lives in server settings, not the
2881            // manifest — so an unconfigured scope stays a runtime miss =
2882            // hidden.)
2883            //
2884            // Validated EXACTLY AS STORED — no `.trim()`, the same no-trim
2885            // rule `View::validate` / `AgentGroup::validate` spell out. The
2886            // backend trims a support code's scope before storing it, so a
2887            // padded manifest scope that validated as its trimmed form but
2888            // was stored raw would pass this check and then never match a
2889            // code — precisely the silent-forever-hidden failure this guard
2890            // exists to prevent.
2891            if let Some(scope) = &client.unlock {
2892                if !is_valid_resource_id(scope) {
2893                    return Err(
2894                        "client.unlock must be a non-empty unlock scope slug ([A-Za-z0-9._-]) \
2895                         with no surrounding whitespace"
2896                            .to_string(),
2897                    );
2898                }
2899            }
2900        }
2901        // #219: a `collect:` job's `name` heads the bundle on the SPA
2902        // Collect page (and the Client App row when paired with
2903        // `client:`), `files_field` tells the agent where to read the
2904        // path list, and `max_size` must be a parseable size so a typo
2905        // is caught at create time rather than silently capping the
2906        // bundle at the default on the fire path.
2907        if let Some(collect) = &self.collect {
2908            if collect.name.trim().is_empty() {
2909                return Err("collect.name must not be empty".to_string());
2910            }
2911            if collect.files_field.trim().is_empty() {
2912                return Err("collect.files_field must not be empty".to_string());
2913            }
2914            if let Some(description) = &collect.description {
2915                if description.trim().is_empty() {
2916                    return Err("collect.description must not be empty when set".to_string());
2917                }
2918            }
2919            if let Some(max_size) = &collect.max_size {
2920                parse_size_bytes(max_size).map_err(|e| format!("collect.max_size: {e}"))?;
2921            }
2922        }
2923        // #720/#743: `aggregate:` is a pure read-spec (it never touches
2924        // stdout and is never sent to an agent), so it composes with every
2925        // other hint. The per-widget rules are shared with the standalone
2926        // `view` resource — see [`validate_aggregate_widgets`].
2927        if let Some(widgets) = &self.aggregate {
2928            validate_aggregate_widgets(widgets, "aggregate")?;
2929        }
2930        // A blank / whitespace-only tag is an invisible operator typo
2931        // that would render an empty filter chip on the Jobs page —
2932        // reject it like the other present-but-blank display fields.
2933        for tag in &self.tags {
2934            if tag.trim().is_empty() {
2935                return Err("tags must not contain empty entries".to_string());
2936            }
2937        }
2938        Ok(())
2939    }
2940}
2941
2942#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
2943#[serde(rename_all = "lowercase")]
2944pub enum ExecuteShell {
2945    /// Windows PowerShell 5.1 (`powershell`).
2946    Powershell,
2947    /// `cmd.exe` (`cmd /C`). Windows only.
2948    Cmd,
2949    /// POSIX shell (`sh -c`). Linux/macOS.
2950    Sh,
2951    /// PowerShell 7, cross-platform (`pwsh`).
2952    Pwsh,
2953}
2954
2955impl From<ExecuteShell> for Shell {
2956    fn from(s: ExecuteShell) -> Self {
2957        match s {
2958            ExecuteShell::Powershell => Shell::Powershell,
2959            ExecuteShell::Cmd => Shell::Cmd,
2960            ExecuteShell::Sh => Shell::Sh,
2961            ExecuteShell::Pwsh => Shell::Pwsh,
2962        }
2963    }
2964}
2965
2966#[cfg(test)]
2967mod tests {
2968    use super::*;
2969
2970    #[test]
2971    fn inventory_payload_extracts_fenced_block() {
2972        // Readable message + fenced JSON → only the JSON, trimmed.
2973        let stdout = "Wi-Fi 設定を適用しました。\n\
2974            #KANADE-INVENTORY-BEGIN\n\
2975            {\"applied\": true}\n\
2976            #KANADE-INVENTORY-END\n";
2977        assert_eq!(inventory_payload(stdout), "{\"applied\": true}");
2978    }
2979
2980    #[test]
2981    fn inventory_payload_falls_back_to_whole_stdout() {
2982        // No fence (a plain inventory job) → whole stdout, trimmed.
2983        assert_eq!(
2984            inventory_payload("  {\"ram_gb\": 16}\n"),
2985            "{\"ram_gb\": 16}"
2986        );
2987    }
2988
2989    #[test]
2990    fn inventory_payload_handles_unterminated_fence() {
2991        // Closing marker missing (e.g. truncated) → everything after the
2992        // opener, trimmed.
2993        let stdout = "msg\n#KANADE-INVENTORY-BEGIN\n{\"a\": 1}";
2994        assert_eq!(inventory_payload(stdout), "{\"a\": 1}");
2995    }
2996
2997    #[test]
2998    fn inventory_payload_ignores_mid_line_sentinel() {
2999        // The marker echoed mid-line (not at a line start) must NOT be
3000        // treated as a fence — fall back to the whole stdout.
3001        let stdout = "see #KANADE-INVENTORY-BEGIN in the docs\nnot json";
3002        assert_eq!(inventory_payload(stdout), stdout.trim());
3003    }
3004
3005    #[test]
3006    fn fenced_payload_extracts_each_hint_block_independently() {
3007        // #821: one stdout carrying a user message + all three fenced
3008        // blocks — every consumer pulls only its own.
3009        let stdout = "\
3010done!
3011#KANADE-INVENTORY-BEGIN
3012{\"os\":\"win\"}
3013#KANADE-INVENTORY-END
3014#KANADE-CHECK-BEGIN
3015{\"status\":\"ok\"}
3016#KANADE-CHECK-END
3017#KANADE-COLLECT-BEGIN
3018{\"files\":[\"a\"]}
3019#KANADE-COLLECT-END
3020";
3021        assert_eq!(
3022            fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
3023            "{\"os\":\"win\"}"
3024        );
3025        assert_eq!(
3026            fenced_payload(stdout, CHECK_BLOCK_BEGIN, CHECK_BLOCK_END),
3027            "{\"status\":\"ok\"}"
3028        );
3029        assert_eq!(
3030            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
3031            "{\"files\":[\"a\"]}"
3032        );
3033    }
3034
3035    #[test]
3036    fn fenced_payload_falls_back_to_whole_stdout_without_fence() {
3037        // A single-hint job needs no fence — the whole (trimmed) stdout is
3038        // the payload.
3039        let stdout = "  {\"files\":[\"a\"]}  ";
3040        assert_eq!(
3041            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
3042            "{\"files\":[\"a\"]}"
3043        );
3044    }
3045
3046    #[test]
3047    fn fenced_payload_returns_empty_when_other_fences_present_but_mine_missing() {
3048        // Multi-hint output (inventory + check fenced) but the COLLECT
3049        // fence is missing — collect must NOT fall back to the whole
3050        // stdout (which holds the inventory/check blocks) and cross-parse
3051        // a sibling block; it gets "" → its JSON parse fails → no data.
3052        let stdout = "\
3053#KANADE-INVENTORY-BEGIN
3054{\"os\":\"win\"}
3055#KANADE-INVENTORY-END
3056#KANADE-CHECK-BEGIN
3057{\"status\":\"ok\"}
3058#KANADE-CHECK-END
3059";
3060        assert_eq!(
3061            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
3062            ""
3063        );
3064        // ...while the hints that DID fence still extract correctly.
3065        assert_eq!(
3066            fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
3067            "{\"os\":\"win\"}"
3068        );
3069    }
3070
3071    /// The example check-job + schedule YAMLs shipped under `configs/`
3072    /// must stay valid as the schema evolves (#290 PR-C). `include_str!`
3073    /// pins them at compile time so a breaking edit fails `cargo test`
3074    /// rather than only `kanade job create` at deploy time.
3075    #[test]
3076    fn example_check_job_yamls_parse_and_validate() {
3077        let jobs = [
3078            (
3079                "check-bitlocker",
3080                include_str!("../../../configs/jobs/check-bitlocker.yaml"),
3081            ),
3082            (
3083                "check-av-signature",
3084                include_str!("../../../configs/jobs/check-av-signature.yaml"),
3085            ),
3086            (
3087                "check-cert-expiry",
3088                include_str!("../../../configs/jobs/check-cert-expiry.yaml"),
3089            ),
3090            (
3091                "check-disk-space",
3092                include_str!("../../../configs/jobs/check-disk-space.yaml"),
3093            ),
3094            (
3095                "check-pending-reboot",
3096                include_str!("../../../configs/jobs/check-pending-reboot.yaml"),
3097            ),
3098            (
3099                "check-defender-rtp",
3100                include_str!("../../../configs/jobs/check-defender-rtp.yaml"),
3101            ),
3102            (
3103                "check-firewall",
3104                include_str!("../../../configs/jobs/check-firewall.yaml"),
3105            ),
3106        ];
3107        for (name, yaml) in jobs {
3108            let m: Manifest =
3109                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} parse: {e}"));
3110            m.validate()
3111                .unwrap_or_else(|e| panic!("{name} validate: {e}"));
3112            let check = m
3113                .check
3114                .as_ref()
3115                .unwrap_or_else(|| panic!("{name} must carry a check: hint"));
3116            assert!(!check.name.trim().is_empty(), "{name} check.name empty");
3117            // These examples all read admin-only WMI / registry / netsh
3118            // state, so they run_as system. NOTE: that's a property of
3119            // these particular checks, NOT of the `check:` contract — a
3120            // check probing user-session state could run_as user.
3121            assert_eq!(
3122                m.execute.run_as,
3123                RunAs::System,
3124                "{name} should run_as system"
3125            );
3126        }
3127    }
3128
3129    /// The example user-invokable job YAMLs (#291) shipped under
3130    /// `configs/jobs/` must stay valid as the `client:` schema
3131    /// evolves. `include_str!` pins them at compile time so a breaking
3132    /// edit fails `cargo test`, not `kanade job create` at deploy.
3133    #[test]
3134    fn example_client_job_yamls_parse_and_validate() {
3135        let jobs = [
3136            (
3137                "fix-teams-cache",
3138                "troubleshoot",
3139                include_str!("../../../configs/jobs/fix-teams-cache.yaml"),
3140            ),
3141            (
3142                "chrome-update",
3143                "software_update",
3144                include_str!("../../../configs/jobs/chrome-update.yaml"),
3145            ),
3146            (
3147                "install-slack",
3148                "catalog",
3149                include_str!("../../../configs/jobs/install-slack.yaml"),
3150            ),
3151            (
3152                "fix-defender-rtp",
3153                "troubleshoot",
3154                include_str!("../../../configs/jobs/fix-defender-rtp.yaml"),
3155            ),
3156            // #792 custom category ("settings") + #809 message/inventory.
3157            (
3158                "example-power-plan",
3159                "settings",
3160                include_str!("../../../configs/jobs/example-power-plan.yaml"),
3161            ),
3162            // #792: diagnostics moved to its own "support" tab.
3163            (
3164                "collect-diagnostics",
3165                "support",
3166                include_str!("../../../configs/jobs/collect-diagnostics.yaml"),
3167            ),
3168        ];
3169        for (id, category, yaml) in jobs {
3170            let m: Manifest =
3171                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
3172            m.validate()
3173                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
3174            assert_eq!(m.id, id, "{id} id mismatch");
3175            let client = m
3176                .client
3177                .as_ref()
3178                .unwrap_or_else(|| panic!("{id} must carry a client: block"));
3179            assert!(!client.name.trim().is_empty(), "{id} client.name empty");
3180            assert_eq!(client.category, category, "{id} category");
3181        }
3182    }
3183
3184    /// #219: the shipped `collect:` example must stay valid as the
3185    /// schema evolves. `include_str!` pins it at compile time so a
3186    /// breaking edit (or a YAML typo in the PowerShell block) fails
3187    /// `cargo test` rather than `kanade job create` at deploy. It carries
3188    /// both `collect:` and `client:` (end-user-triggerable), which must
3189    /// compose.
3190    #[test]
3191    fn example_collect_job_yaml_parses_and_validates() {
3192        let yaml = include_str!("../../../configs/jobs/collect-diagnostics.yaml");
3193        let m: Manifest = serde_yaml::from_str(yaml).expect("collect-diagnostics parse");
3194        m.validate().expect("collect-diagnostics validate");
3195        assert_eq!(m.id, "collect-diagnostics");
3196        let collect = m.collect.as_ref().expect("collect: block present");
3197        assert!(!collect.name.trim().is_empty());
3198        assert_eq!(collect.files_field, "files");
3199        assert_eq!(collect.max_size_bytes(), 50_000_000);
3200        // collect + client compose — the Client App can trigger it.
3201        assert!(
3202            m.client.is_some(),
3203            "collect-diagnostics also carries client:"
3204        );
3205    }
3206
3207    /// The `emit: { type: events }` collector jobs under
3208    /// `configs/jobs/` feed the obs_events timeline. `include_str!`
3209    /// pins them at compile time so a breaking edit (e.g. an `emit:`
3210    /// paired with `check:`/`inventory:`, a bad watermark field, or a
3211    /// YAML typo in the PowerShell block) fails `cargo test` rather
3212    /// than `kanade job create` at deploy. Every one must carry an
3213    /// `emit.type=events` block and NO check/inventory (validate()
3214    /// rejects the pairing).
3215    #[test]
3216    fn example_event_collector_job_yamls_parse_and_validate() {
3217        let jobs = [
3218            // collect-winlog-events was retired in #841 PR2 — the scheduled
3219            // human-session / power timeline is now read natively by the
3220            // agent (kanade-agent `winlog` module via EvtQuery), no
3221            // PowerShell job. collect-winlog-logons-all stays as the
3222            // on-demand forensic all-token-logons companion.
3223            (
3224                "collect-winlog-logons-all",
3225                include_str!("../../../configs/jobs/collect-winlog-logons-all.yaml"),
3226            ),
3227            (
3228                "collect-wlan-events",
3229                include_str!("../../../configs/jobs/collect-wlan-events.yaml"),
3230            ),
3231        ];
3232        for (id, yaml) in jobs {
3233            // Strict parse so an unknown-key typo in these fixtures fails
3234            // here (not silently at deploy) — the runtime Manifest is
3235            // unknown-key-tolerant, so the lenient serde_yaml::from_str
3236            // wouldn't catch fixture drift (CodeRabbit #689).
3237            let m: Manifest =
3238                crate::strict::from_yaml_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
3239            m.validate()
3240                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
3241            assert_eq!(m.id, id, "{id} id mismatch");
3242            let emit = m
3243                .emit
3244                .as_ref()
3245                .unwrap_or_else(|| panic!("{id} must carry an emit: block"));
3246            assert_eq!(emit.kind, EmitKind::Events, "{id} emit.type");
3247            assert!(
3248                m.check.is_none() && m.inventory.is_none(),
3249                "{id}: emit jobs must not pair with check/inventory"
3250            );
3251        }
3252    }
3253
3254    /// The `inventory:` snapshot jobs under `configs/jobs/` project
3255    /// facts into `inventory_facts` + exploded tables. `include_str!`
3256    /// pins them at compile time so a breaking edit (bad explode
3257    /// schema, a YAML typo in the PowerShell block, an `inventory:`
3258    /// accidentally paired with `emit:`) fails `cargo test` rather
3259    /// than the projector at deploy. Each must carry an `inventory:`
3260    /// block and NO emit (validate() rejects the pairing).
3261    #[test]
3262    fn example_inventory_job_yamls_parse_and_validate() {
3263        let jobs = [
3264            (
3265                "inventory-hw",
3266                include_str!("../../../configs/jobs/inventory-hw.yaml"),
3267            ),
3268            (
3269                "inventory-sw",
3270                include_str!("../../../configs/jobs/inventory-sw.yaml"),
3271            ),
3272            (
3273                "inventory-driver",
3274                include_str!("../../../configs/jobs/inventory-driver.yaml"),
3275            ),
3276        ];
3277        for (id, yaml) in jobs {
3278            let m: Manifest =
3279                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
3280            m.validate()
3281                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
3282            assert_eq!(m.id, id, "{id} id mismatch");
3283            assert!(m.inventory.is_some(), "{id} must carry an inventory: block");
3284            assert!(m.emit.is_none(), "{id}: inventory jobs must not set emit:");
3285        }
3286    }
3287
3288    #[test]
3289    fn example_check_schedule_yamls_parse_and_validate() {
3290        let schedules = [
3291            (
3292                "check-bitlocker",
3293                include_str!("../../../configs/schedules/check-bitlocker.yaml"),
3294            ),
3295            (
3296                "check-av-signature",
3297                include_str!("../../../configs/schedules/check-av-signature.yaml"),
3298            ),
3299            (
3300                "check-cert-expiry",
3301                include_str!("../../../configs/schedules/check-cert-expiry.yaml"),
3302            ),
3303            (
3304                "check-disk-space",
3305                include_str!("../../../configs/schedules/check-disk-space.yaml"),
3306            ),
3307            (
3308                "check-pending-reboot",
3309                include_str!("../../../configs/schedules/check-pending-reboot.yaml"),
3310            ),
3311            (
3312                "check-defender-rtp",
3313                include_str!("../../../configs/schedules/check-defender-rtp.yaml"),
3314            ),
3315            (
3316                "check-firewall",
3317                include_str!("../../../configs/schedules/check-firewall.yaml"),
3318            ),
3319        ];
3320        for (name, yaml) in schedules {
3321            let s: Schedule =
3322                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
3323            s.validate()
3324                .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
3325            assert_eq!(s.job_id, name, "{name} schedule must reference its job");
3326        }
3327    }
3328
3329    /// Inventory schedule wrappers (`per_pc` cadence) must stay valid
3330    /// alongside the schedule schema. `include_str!` pins them so a
3331    /// breaking edit fails `cargo test`, not `kanade schedule create`.
3332    #[test]
3333    fn example_inventory_schedule_yamls_parse_and_validate() {
3334        let schedules = [
3335            (
3336                "inventory-hw",
3337                include_str!("../../../configs/schedules/inventory-hw.yaml"),
3338            ),
3339            (
3340                "inventory-sw",
3341                include_str!("../../../configs/schedules/inventory-sw.yaml"),
3342            ),
3343            (
3344                "inventory-driver",
3345                include_str!("../../../configs/schedules/inventory-driver.yaml"),
3346            ),
3347        ];
3348        for (name, yaml) in schedules {
3349            let s: Schedule =
3350                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
3351            s.validate()
3352                .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
3353            assert_eq!(s.job_id, name, "{name} schedule must reference its job");
3354        }
3355    }
3356
3357    #[test]
3358    fn target_is_specified_requires_at_least_one_field() {
3359        let empty = Target::default();
3360        assert!(!empty.is_specified());
3361
3362        let with_all = Target {
3363            all: true,
3364            ..Target::default()
3365        };
3366        assert!(with_all.is_specified());
3367
3368        let with_groups = Target {
3369            groups: vec!["canary".into()],
3370            ..Target::default()
3371        };
3372        assert!(with_groups.is_specified());
3373
3374        let with_pcs = Target {
3375            pcs: vec!["pc-01".into()],
3376            ..Target::default()
3377        };
3378        assert!(with_pcs.is_specified());
3379    }
3380
3381    #[test]
3382    fn manifest_deserialises_minimal_yaml() {
3383        // Matches jobs/echo-test.yaml. v0.18: no target/rollout/jitter
3384        // — those live on the schedule / exec request now.
3385        let yaml = r#"
3386id: echo-test
3387version: 0.0.1
3388execute:
3389  shell: powershell
3390  script: "echo 'kanade'"
3391  timeout: 30s
3392"#;
3393        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3394        assert_eq!(m.id, "echo-test");
3395        assert_eq!(m.version, "0.0.1");
3396        assert!(matches!(m.execute.shell, ExecuteShell::Powershell));
3397        assert_eq!(
3398            m.execute.script.as_deref().map(str::trim),
3399            Some("echo 'kanade'")
3400        );
3401        assert!(m.execute.script_file.is_none());
3402        assert!(m.execute.script_object.is_none());
3403        assert_eq!(m.execute.timeout, "30s");
3404        assert!(!m.require_approval);
3405        m.validate()
3406            .expect("inline-script manifest passes validation");
3407    }
3408
3409    #[test]
3410    fn manifest_parses_check_job_and_validates() {
3411        // An operator-defined health check (#290): a `check:` hint +
3412        // a PowerShell script that prints {status, detail}.
3413        let yaml = r#"
3414id: check-bitlocker
3415version: 0.1.0
3416execute:
3417  shell: powershell
3418  run_as: system
3419  timeout: 15s
3420  script: |
3421    [pscustomobject]@{ status = 'ok'; detail = 'all volumes protected' } | ConvertTo-Json -Compress
3422check:
3423  name: bitlocker
3424  troubleshoot: fix-bitlocker
3425"#;
3426        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3427        let check = m.check.as_ref().expect("check hint present");
3428        assert_eq!(check.name, "bitlocker");
3429        assert_eq!(check.troubleshoot.as_deref(), Some("fix-bitlocker"));
3430        // Field names default to the conventional "status" / "detail".
3431        assert_eq!(check.status_field, "status");
3432        assert_eq!(check.detail_field, "detail");
3433        assert!(m.inventory.is_none() && m.emit.is_none());
3434        m.validate().expect("check-only manifest passes validation");
3435    }
3436
3437    #[test]
3438    fn manifest_check_defaults_and_custom_fields() {
3439        // Minimal: only `name`; status/detail fields default.
3440        let m: Manifest = serde_yaml::from_str(
3441            r#"
3442id: check-disk
3443version: 0.1.0
3444execute:
3445  shell: powershell
3446  script: "[pscustomobject]@{ status = 'ok' } | ConvertTo-Json -Compress"
3447  timeout: 10s
3448check:
3449  name: disk_free
3450"#,
3451        )
3452        .expect("parse");
3453        let c = m.check.as_ref().unwrap();
3454        assert_eq!(c.name, "disk_free");
3455        assert_eq!(c.status_field, "status");
3456        assert_eq!(c.detail_field, "detail");
3457        assert!(c.troubleshoot.is_none());
3458        m.validate().expect("validates");
3459
3460        // The operator can point status/detail at any field of their
3461        // free-form inventory object.
3462        let m2: Manifest = serde_yaml::from_str(
3463            r#"
3464id: check-custom
3465version: 0.1.0
3466execute:
3467  shell: powershell
3468  script: "echo x"
3469  timeout: 10s
3470check:
3471  name: patch_level
3472  status_field: compliance
3473  detail_field: summary
3474"#,
3475        )
3476        .expect("parse");
3477        let c2 = m2.check.as_ref().unwrap();
3478        assert_eq!(c2.status_field, "compliance");
3479        assert_eq!(c2.detail_field, "summary");
3480    }
3481
3482    #[test]
3483    fn manifest_allows_check_composed_with_inventory() {
3484        // `check:` + `inventory:` COMPOSE on the same stdout object:
3485        // status/detail → Health tab, the rest → SPA projection +
3486        // explode sub-tables. Must pass validation.
3487        let yaml = r#"
3488id: check-bitlocker-detailed
3489version: 0.1.0
3490execute:
3491  shell: powershell
3492  script: "echo x"
3493  timeout: 10s
3494check:
3495  name: bitlocker
3496inventory:
3497  display:
3498    - { field: status, label: Status }
3499"#;
3500        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3501        assert!(m.check.is_some() && m.inventory.is_some());
3502        m.validate().expect("check + inventory compose");
3503    }
3504
3505    #[test]
3506    fn manifest_parses_collect_job_and_validates() {
3507        // #219: a `collect:` hint + a script that lists files on stdout.
3508        let yaml = r#"
3509id: collect-diagnostics
3510version: 0.1.0
3511execute:
3512  shell: powershell
3513  run_as: system
3514  timeout: 120s
3515  script: |
3516    @{ files = @("$env:KANADE_COLLECT_DIR/system.csv") } | ConvertTo-Json
3517collect:
3518  name: "Full diagnostics"
3519  description: "Event logs + process"
3520  max_size: 50MB
3521"#;
3522        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3523        let c = m.collect.as_ref().expect("collect hint present");
3524        assert_eq!(c.name, "Full diagnostics");
3525        assert_eq!(c.files_field, "files"); // default
3526        assert_eq!(c.max_size_bytes(), 50_000_000);
3527        m.validate().expect("collect-only manifest validates");
3528    }
3529
3530    #[test]
3531    fn manifest_finalize_powershell_validates_and_lowers() {
3532        let yaml = r#"
3533id: collect-fin
3534version: 0.1.0
3535execute:
3536  shell: powershell
3537  timeout: 120s
3538  script: |
3539    @{ files = @() } | ConvertTo-Json
3540collect:
3541  name: "diag"
3542  max_size: 50MB
3543finalize:
3544  shell: powershell
3545  timeout: 30s
3546  run_as: system
3547  script: |
3548    Write-Output "cleanup"
3549"#;
3550        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3551        m.validate().expect("powershell finalize validates");
3552        let lowered = m.finalize.as_ref().expect("finalize present").lower();
3553        assert_eq!(lowered.timeout_secs, 30);
3554        assert!(matches!(lowered.shell, Shell::Powershell));
3555        // #965: default is the one-call-after-all contract.
3556        assert!(!lowered.on_each_bundle);
3557    }
3558
3559    #[test]
3560    fn manifest_finalize_on_each_bundle_validates_with_collect_and_lowers() {
3561        // #965: on_each_bundle + a collect hint is the intended
3562        // combination — validates, and the flag survives lowering.
3563        let yaml = r#"
3564id: collect-fin-each
3565version: 0.1.0
3566execute:
3567  shell: powershell
3568  timeout: 120s
3569  script: |
3570    @{ files = @() } | ConvertTo-Json
3571collect:
3572  name: "diag"
3573  max_size: 50MB
3574finalize:
3575  shell: powershell
3576  on_each_bundle: true
3577  script: |
3578    Write-Output "cleanup"
3579"#;
3580        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3581        m.validate().expect("on_each_bundle + collect validates");
3582        let lowered = m.finalize.as_ref().expect("finalize present").lower();
3583        assert!(lowered.on_each_bundle, "flag survives lowering");
3584    }
3585
3586    #[test]
3587    fn manifest_finalize_on_each_bundle_without_collect_rejected() {
3588        // #965: a non-collect finalize has no bundles to iterate, so
3589        // on_each_bundle is a no-op — reject it at the write boundary so
3590        // the operator is told rather than silently getting nothing.
3591        let yaml = r#"
3592id: fin-each-no-collect
3593version: 0.1.0
3594execute:
3595  shell: powershell
3596  timeout: 120s
3597  script: |
3598    Write-Output "hi"
3599finalize:
3600  shell: powershell
3601  on_each_bundle: true
3602  script: |
3603    Write-Output "cleanup"
3604"#;
3605        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3606        let err = m
3607            .validate()
3608            .expect_err("on_each_bundle without collect rejected");
3609        assert!(err.contains("on_each_bundle"), "got: {err}");
3610        assert!(err.contains("collect"), "got: {err}");
3611    }
3612
3613    #[test]
3614    fn manifest_finalize_rejects_cmd_shell() {
3615        // cmd finalize is an injection risk (the agent injects JSON into
3616        // the hook's env; cmd.exe quoting doesn't nest) — validate must
3617        // reject it.
3618        let yaml = r#"
3619id: collect-fin-cmd
3620version: 0.1.0
3621execute:
3622  shell: powershell
3623  timeout: 120s
3624  script: |
3625    @{ files = @() } | ConvertTo-Json
3626finalize:
3627  shell: cmd
3628  script: |
3629    echo hi
3630"#;
3631        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3632        let err = m.validate().expect_err("cmd finalize rejected");
3633        assert!(err.contains("finalize.shell"), "got: {err}");
3634    }
3635
3636    #[test]
3637    fn manifest_finalize_rejects_sh_shell() {
3638        // sh finalize is rejected for the same reason as cmd: the agent
3639        // injects the result JSON, and the injected prelude is PowerShell
3640        // syntax that a POSIX shell can't run.
3641        let yaml = r#"
3642id: collect-fin-sh
3643version: 0.1.0
3644execute:
3645  shell: powershell
3646  timeout: 120s
3647  script: |
3648    @{ files = @() } | ConvertTo-Json
3649finalize:
3650  shell: sh
3651  script: |
3652    echo hi
3653"#;
3654        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3655        let err = m.validate().expect_err("sh finalize rejected");
3656        assert!(err.contains("finalize.shell"), "got: {err}");
3657    }
3658
3659    #[test]
3660    fn manifest_finalize_accepts_pwsh_shell() {
3661        // pwsh IS PowerShell, so the injected prelude + single-quote
3662        // escaping are valid and safe — a pwsh finalize must validate.
3663        let yaml = r#"
3664id: collect-fin-pwsh
3665version: 0.1.0
3666execute:
3667  shell: pwsh
3668  timeout: 120s
3669  script: |
3670    @{ files = @() } | ConvertTo-Json
3671finalize:
3672  shell: pwsh
3673  script: |
3674    Write-Output hi
3675"#;
3676        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3677        m.validate().expect("pwsh finalize accepted");
3678    }
3679
3680    #[test]
3681    fn manifest_finalize_rejects_empty_script() {
3682        let yaml = r#"
3683id: collect-fin-empty
3684version: 0.1.0
3685execute:
3686  shell: powershell
3687  timeout: 120s
3688  script: |
3689    @{ files = @() } | ConvertTo-Json
3690finalize:
3691  shell: powershell
3692  script: "   "
3693"#;
3694        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3695        let err = m.validate().expect_err("empty finalize script rejected");
3696        assert!(err.contains("finalize.script"), "got: {err}");
3697    }
3698
3699    #[test]
3700    fn manifest_collect_max_size_defaults_when_unset() {
3701        let m: Manifest = serde_yaml::from_str(
3702            r#"
3703id: collect-min
3704version: 0.1.0
3705execute:
3706  shell: powershell
3707  script: "echo x"
3708  timeout: 10s
3709collect:
3710  name: minimal
3711"#,
3712        )
3713        .expect("parse");
3714        let c = m.collect.as_ref().unwrap();
3715        assert!(c.max_size.is_none());
3716        assert_eq!(c.max_size_bytes(), DEFAULT_COLLECT_MAX_SIZE);
3717        m.validate().expect("validates");
3718    }
3719
3720    #[test]
3721    fn manifest_allows_collect_with_client() {
3722        // collect composes with client (client doesn't touch stdout):
3723        // an end user can trigger a collection from the Client App.
3724        let yaml = r#"
3725id: collect-diag-client
3726version: 0.1.0
3727execute:
3728  shell: powershell
3729  script: "echo x"
3730  timeout: 10s
3731collect:
3732  name: diagnostics
3733client:
3734  name: "Send diagnostics"
3735  category: troubleshoot
3736"#;
3737        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3738        assert!(m.collect.is_some() && m.client.is_some());
3739        m.validate().expect("collect + client compose");
3740    }
3741
3742    #[test]
3743    fn manifest_allows_inventory_check_collect_coexistence() {
3744        // #821: the three fenced hints now COMPOSE — each reads its own
3745        // `#KANADE-<KIND>` stdout block, so one job can do all three.
3746        let yaml = r#"
3747id: multi-hint
3748version: 0.1.0
3749execute:
3750  shell: powershell
3751  script: "echo x"
3752  timeout: 10s
3753inventory:
3754  display:
3755    - { field: status, label: Status }
3756check:
3757  name: health
3758collect:
3759  name: diag
3760"#;
3761        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3762        m.validate()
3763            .expect("inventory + check + collect coexist after #821");
3764    }
3765
3766    #[test]
3767    fn manifest_rejects_emit_combined_with_fenced_hints() {
3768        // `emit:` consumes stdout as NDJSON (and blanks it), so it still
3769        // can't share with any fenced hint — inventory, check, OR collect.
3770        for extra in [
3771            "inventory:\n  display:\n    - { field: s, label: S }\n",
3772            "check:\n  name: health\n",
3773            "collect:\n  name: diag\n",
3774        ] {
3775            let yaml = format!(
3776                "id: bad-emit-mix\nversion: 0.1.0\nexecute:\n  shell: powershell\n  \
3777                 script: \"echo x\"\n  timeout: 10s\nemit:\n  type: events\n{extra}"
3778            );
3779            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
3780            let err = m
3781                .validate()
3782                .expect_err("emit + fenced hint must be rejected");
3783            assert!(err.contains("emit"), "error mentions emit: {err}");
3784        }
3785    }
3786
3787    #[test]
3788    fn manifest_rejects_collect_empty_name_and_bad_size() {
3789        let empty_name: Manifest = serde_yaml::from_str(
3790            r#"
3791id: c
3792version: 0.1.0
3793execute: { shell: powershell, script: "echo x", timeout: 10s }
3794collect: { name: "  " }
3795"#,
3796        )
3797        .expect("parse");
3798        assert!(
3799            empty_name.validate().is_err(),
3800            "blank collect.name rejected"
3801        );
3802
3803        let bad_size: Manifest = serde_yaml::from_str(
3804            r#"
3805id: c
3806version: 0.1.0
3807execute: { shell: powershell, script: "echo x", timeout: 10s }
3808collect: { name: diag, max_size: "50 quux" }
3809"#,
3810        )
3811        .expect("parse");
3812        let err = bad_size.validate().expect_err("bad max_size rejected");
3813        assert!(err.contains("max_size"), "error mentions max_size: {err}");
3814    }
3815
3816    #[test]
3817    fn parse_size_bytes_units() {
3818        assert_eq!(parse_size_bytes("1024").unwrap(), 1024);
3819        assert_eq!(parse_size_bytes("1B").unwrap(), 1);
3820        assert_eq!(parse_size_bytes("50MB").unwrap(), 50_000_000);
3821        assert_eq!(parse_size_bytes("500 KB").unwrap(), 500_000);
3822        assert_eq!(parse_size_bytes("1GiB").unwrap(), 1024 * 1024 * 1024);
3823        assert_eq!(parse_size_bytes("2mib").unwrap(), 2 * 1024 * 1024);
3824        assert!(parse_size_bytes("").is_err());
3825        assert!(parse_size_bytes("MB").is_err());
3826        assert!(parse_size_bytes("12 zonks").is_err());
3827    }
3828
3829    #[test]
3830    fn manifest_rejects_check_combined_with_emit() {
3831        // `emit:` stdout is NDJSON (and omitted from the result), so
3832        // it can't pair with `check:` (which needs a single JSON
3833        // object on stdout).
3834        let yaml = r#"
3835id: bad-mix
3836version: 0.1.0
3837execute:
3838  shell: powershell
3839  script: "echo x"
3840  timeout: 10s
3841check:
3842  name: bitlocker
3843emit:
3844  type: events
3845"#;
3846        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3847        let err = m.validate().expect_err("emit + check must fail");
3848        assert!(err.contains("incompatible"), "err: {err}");
3849    }
3850
3851    #[test]
3852    fn manifest_rejects_emit_combined_with_inventory() {
3853        // The other half of the emit-incompatibility condition.
3854        let yaml = r#"
3855id: bad-mix-2
3856version: 0.1.0
3857execute:
3858  shell: powershell
3859  script: "echo x"
3860  timeout: 10s
3861emit:
3862  type: events
3863inventory:
3864  display:
3865    - { field: status, label: Status }
3866"#;
3867        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3868        let err = m.validate().expect_err("emit + inventory must fail");
3869        assert!(err.contains("incompatible"), "err: {err}");
3870    }
3871
3872    #[test]
3873    fn manifest_rejects_empty_check_field_names() {
3874        // Empty name / status_field / detail_field are invisible
3875        // runtime bugs (empty React key, agent reads the wrong field)
3876        // — reject them even though serde supplies non-empty defaults.
3877        let base = |inner: &str| {
3878            format!(
3879                "id: c\nversion: 0.1.0\nexecute:\n  shell: powershell\n  script: \"echo x\"\n  timeout: 10s\ncheck:\n{inner}"
3880            )
3881        };
3882        for inner in [
3883            "  name: \"\"\n",
3884            "  name: ok\n  status_field: \"\"\n",
3885            "  name: ok\n  detail_field: \"   \"\n",
3886            // present-but-blank troubleshoot → broken remediation id.
3887            "  name: ok\n  troubleshoot: \"  \"\n",
3888        ] {
3889            let m: Manifest = serde_yaml::from_str(&base(inner)).expect("parse");
3890            let err = m.validate().expect_err("empty field must fail");
3891            assert!(err.contains("must not be empty"), "err: {err}");
3892        }
3893    }
3894
3895    #[test]
3896    fn check_alert_decodes_with_defaults_and_validates() {
3897        let yaml = r#"
3898id: c
3899version: 0.1.0
3900execute:
3901  shell: powershell
3902  script: "echo x"
3903  timeout: 10s
3904check:
3905  name: bitlocker
3906  alert:
3907    notify_user: true
3908    title: "BitLocker 未準拠"
3909"#;
3910        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3911        m.validate().expect("valid alert");
3912        let alert = m.check.unwrap().alert.unwrap();
3913        // Defaults: on = [fail], priority = warn, body = None.
3914        assert_eq!(alert.on, vec![CheckAlertStatus::Fail]);
3915        assert_eq!(
3916            alert.priority,
3917            crate::ipc::notifications::NotificationPriority::Warn
3918        );
3919        assert!(alert.body.is_none());
3920        assert!(alert.notify_user);
3921    }
3922
3923    #[test]
3924    fn check_alert_validation_rejects_bad_configs() {
3925        let base = |alert: &str| {
3926            format!(
3927                "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}"
3928            )
3929        };
3930        let cases = [
3931            // No recipient.
3932            ("    title: t\n", "notify_user and/or notify_groups"),
3933            // Empty title.
3934            (
3935                "    notify_user: true\n    title: \"  \"\n",
3936                "title must not be empty",
3937            ),
3938            // Empty `on`.
3939            (
3940                "    notify_user: true\n    title: t\n    on: []\n",
3941                "on must list at least one status",
3942            ),
3943            // Blank group name.
3944            (
3945                "    notify_groups: [\"  \"]\n    title: t\n",
3946                "notify_groups must not contain blanks",
3947            ),
3948            // alert requires fleet: true.
3949            (
3950                "    notify_user: true\n    title: t\n  fleet: false\n",
3951                "requires fleet: true",
3952            ),
3953            // email opt-in without a group to address.
3954            (
3955                "    notify_user: true\n    email: true\n    title: t\n",
3956                "email requires notify_groups",
3957            ),
3958        ];
3959        for (alert, want) in cases {
3960            let m: Manifest = serde_yaml::from_str(&base(alert)).expect("parse");
3961            let err = m.validate().expect_err("bad alert must fail");
3962            assert!(err.contains(want), "for {alert:?}: got {err}");
3963        }
3964    }
3965
3966    #[test]
3967    fn manifest_client_absent_by_default() {
3968        // A plain operator job (the overwhelming majority) carries no
3969        // `client:` block, so it never surfaces in the end-user
3970        // catalog.
3971        let yaml = r#"
3972id: echo-test
3973version: 0.0.1
3974execute:
3975  shell: powershell
3976  script: "echo 'kanade'"
3977  timeout: 30s
3978"#;
3979        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3980        assert!(m.client.is_none());
3981        m.validate().expect("operator-only job validates");
3982    }
3983
3984    #[test]
3985    fn manifest_client_parses_and_validates() {
3986        // The Client App "困ったとき" remediation job shape: a
3987        // user-invokable troubleshoot job with the end-user fields the
3988        // KLP `jobs.list` wire needs, grouped under `client:`.
3989        let yaml = r#"
3990id: fix-teams-cache
3991version: 1.0.0
3992execute:
3993  shell: powershell
3994  script: "echo clearing"
3995  timeout: 60s
3996client:
3997  name: "Teams のキャッシュをクリア"
3998  description: "Teams が重いときに試してください"
3999  category: troubleshoot
4000  icon: brush-cleaning
4001"#;
4002        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4003        let c = m.client.as_ref().expect("client block present");
4004        assert_eq!(c.name, "Teams のキャッシュをクリア");
4005        assert_eq!(
4006            c.description.as_deref(),
4007            Some("Teams が重いときに試してください")
4008        );
4009        assert_eq!(c.category, "troubleshoot");
4010        assert_eq!(c.icon.as_deref(), Some("brush-cleaning"));
4011        m.validate().expect("user-invokable job validates");
4012    }
4013
4014    #[test]
4015    fn manifest_client_minimal_only_name_and_category() {
4016        // description + icon are optional; name + category are the
4017        // serde-required minimum.
4018        let yaml = r#"
4019id: install-slack
4020version: 1.0.0
4021execute:
4022  shell: powershell
4023  script: "echo install"
4024  timeout: 600s
4025client:
4026  name: Slack
4027  category: catalog
4028"#;
4029        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4030        let c = m.client.as_ref().expect("client present");
4031        assert_eq!(c.category, "catalog");
4032        assert!(c.description.is_none() && c.icon.is_none());
4033        m.validate().expect("minimal client validates");
4034    }
4035
4036    #[test]
4037    fn manifest_client_rejects_blank_name() {
4038        // serde guarantees `name`/`category` are present; the one gap
4039        // is a present-but-blank name → empty catalog row title.
4040        let yaml = r#"
4041id: j
4042version: 1.0.0
4043execute:
4044  shell: powershell
4045  script: "echo x"
4046  timeout: 30s
4047client:
4048  name: "   "
4049  category: catalog
4050"#;
4051        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4052        let err = m.validate().expect_err("blank name must fail");
4053        assert!(err.contains("client.name"), "err: {err}");
4054    }
4055
4056    #[test]
4057    fn manifest_client_rejects_blank_optional_fields() {
4058        // description / icon are optional, but a present-but-blank
4059        // value is a bug (empty subtitle / dangling icon name) — reject
4060        // it, mirroring the check: block's troubleshoot guard.
4061        for (field, line) in [
4062            ("client.description", "  description: \"  \"\n"),
4063            ("client.icon", "  icon: \"\"\n"),
4064            // #792: the new category tab-metadata fields get the same
4065            // present-but-blank guard.
4066            ("client.category_label", "  category_label: \"  \"\n"),
4067            ("client.category_icon", "  category_icon: \"\"\n"),
4068        ] {
4069            let yaml = format!(
4070                "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}"
4071            );
4072            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
4073            let err = m.validate().expect_err("blank optional field must fail");
4074            assert!(err.contains(field), "expected {field} in err: {err}");
4075        }
4076    }
4077
4078    #[test]
4079    fn manifest_client_rejects_blank_category() {
4080        // #792: category is a free-form key now; serde keeps it required,
4081        // but a present-but-blank value would group the job under an empty
4082        // tab — validate() must reject it.
4083        let yaml = r#"
4084id: j
4085version: 1.0.0
4086execute:
4087  shell: powershell
4088  script: "echo x"
4089  timeout: 30s
4090client:
4091  name: "A job"
4092  category: "   "
4093"#;
4094        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4095        let err = m.validate().expect_err("blank category must fail");
4096        assert!(err.contains("client.category"), "err: {err}");
4097    }
4098
4099    #[test]
4100    fn target_matches_pc_group_and_all() {
4101        // #816: pc match, group match, all, and the no-match case.
4102        let by_pc = Target {
4103            pcs: vec!["PC1".into()],
4104            ..Default::default()
4105        };
4106        assert!(by_pc.matches("PC1", &[]));
4107        assert!(!by_pc.matches("PC2", &["g1".into()]));
4108
4109        let by_group = Target {
4110            groups: vec!["g1".into()],
4111            ..Default::default()
4112        };
4113        assert!(by_group.matches("PC2", &["g1".into()]));
4114        assert!(!by_group.matches("PC2", &["g2".into()]));
4115
4116        let all = Target {
4117            all: true,
4118            ..Default::default()
4119        };
4120        assert!(all.matches("anyPC", &[]));
4121    }
4122
4123    #[test]
4124    fn manifest_client_rejects_empty_visible_to() {
4125        // #816: a present-but-empty visible_to (no all/groups/pcs) would
4126        // hide the job from everyone — validate() must reject it.
4127        let yaml = r#"
4128id: j
4129version: 1.0.0
4130execute:
4131  shell: powershell
4132  script: "echo x"
4133  timeout: 30s
4134client:
4135  name: "A job"
4136  category: troubleshoot
4137  visible_to: {}
4138"#;
4139        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4140        let err = m.validate().expect_err("empty visible_to must fail");
4141        assert!(err.contains("client.visible_to"), "err: {err}");
4142    }
4143
4144    #[test]
4145    fn manifest_client_accepts_visible_to_groups() {
4146        let yaml = r#"
4147id: j
4148version: 1.0.0
4149execute:
4150  shell: powershell
4151  script: "echo x"
4152  timeout: 30s
4153client:
4154  name: "A job"
4155  category: settings
4156  visible_to:
4157    groups: [wifi-affected]
4158"#;
4159        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4160        m.validate().expect("visible_to with a group validates");
4161        let vt = m.client.unwrap().visible_to.unwrap();
4162        assert_eq!(vt.groups, vec!["wifi-affected".to_string()]);
4163    }
4164
4165    #[test]
4166    fn manifest_client_show_when_accepts_scalar_and_seq() {
4167        use crate::ipc::state::CheckStatus;
4168        // `is:` accepts a single status (author ergonomics) ...
4169        let scalar = r#"
4170id: office-update
4171version: 1.0.0
4172execute:
4173  shell: powershell
4174  script: "echo x"
4175  timeout: 30s
4176client:
4177  name: "Office を最新に更新"
4178  category: software_update
4179  show_when:
4180    check: office-up-to-date
4181    is: fail
4182"#;
4183        let m: Manifest = serde_yaml::from_str(scalar).expect("parse scalar");
4184        m.validate().expect("scalar show_when validates");
4185        let sw = m.client.unwrap().show_when.unwrap();
4186        assert_eq!(sw.check, "office-up-to-date");
4187        assert_eq!(sw.is, vec![CheckStatus::Fail]);
4188
4189        // ... and a list (e.g. fail-open on a not-yet-run check).
4190        let seq = scalar.replace("is: fail", "is: [fail, unknown]");
4191        let m: Manifest = serde_yaml::from_str(&seq).expect("parse seq");
4192        m.validate().expect("seq show_when validates");
4193        assert_eq!(
4194            m.client.unwrap().show_when.unwrap().is,
4195            vec![CheckStatus::Fail, CheckStatus::Unknown]
4196        );
4197    }
4198
4199    #[test]
4200    fn manifest_client_unlock_round_trips_and_defaults_absent() {
4201        let yaml = r#"
4202id: j
4203version: 1.0.0
4204execute:
4205  shell: powershell
4206  script: "echo x"
4207  timeout: 30s
4208client:
4209  name: "A job"
4210  category: troubleshoot
4211  unlock: support
4212"#;
4213        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4214        m.validate().expect("valid");
4215        assert_eq!(
4216            m.client.as_ref().unwrap().unlock.as_deref(),
4217            Some("support")
4218        );
4219
4220        // Absent ⇒ an ordinary job, and absent from the encoded form too, so
4221        // an older reader sees byte-for-byte what it saw before the field.
4222        let plain = yaml.replace("  unlock: support\n", "");
4223        let m: Manifest = serde_yaml::from_str(&plain).expect("parse");
4224        assert!(m.client.as_ref().unwrap().unlock.is_none());
4225        let v = serde_json::to_value(&m).unwrap();
4226        assert!(v["client"].get("unlock").is_none(), "wire: {v:?}");
4227    }
4228
4229    #[test]
4230    fn manifest_client_unlock_rejects_a_malformed_scope() {
4231        // The scope is compared byte-for-byte with a configured support
4232        // code's scope, and the gate fails closed — so a typo with spaces
4233        // would hide the job forever with no error anywhere. Catch it at
4234        // create time instead.
4235        let yaml = r#"
4236id: j
4237version: 1.0.0
4238execute:
4239  shell: powershell
4240  script: "echo x"
4241  timeout: 30s
4242client:
4243  name: "A job"
4244  category: troubleshoot
4245  unlock: "help desk"
4246"#;
4247        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4248        let err = m.validate().expect_err("malformed unlock scope must fail");
4249        assert!(err.contains("client.unlock"), "err: {err}");
4250
4251        let blank = yaml.replace(r#"unlock: "help desk""#, r#"unlock: "  ""#);
4252        let m: Manifest = serde_yaml::from_str(&blank).expect("parse");
4253        let err = m.validate().expect_err("blank unlock scope must fail");
4254        assert!(err.contains("client.unlock"), "err: {err}");
4255
4256        // The padded-but-otherwise-valid case (Claude review on #1166): the
4257        // charset check runs on the scope EXACTLY AS STORED, so these must
4258        // fail here rather than pass validation and then silently never
4259        // match a support code (whose scope the backend trims before
4260        // storing) — leaving the job hidden forever with no error anywhere.
4261        for padded in [r#"unlock: " support""#, r#"unlock: "support ""#] {
4262            let m: Manifest = serde_yaml::from_str(&yaml.replace(r#"unlock: "help desk""#, padded))
4263                .expect("parse");
4264            let err = m
4265                .validate()
4266                .expect_err("padded unlock scope must fail: {padded}");
4267            assert!(err.contains("client.unlock"), "{padded} err: {err}");
4268        }
4269    }
4270
4271    #[test]
4272    fn manifest_client_show_when_rejects_empty() {
4273        // A malformed check slug (here: internal spaces — a typo that could
4274        // never match a real check name) or an empty status list would
4275        // silently hide the job forever — validate() must reject both.
4276        let bad_check = r#"
4277id: j
4278version: 1.0.0
4279execute:
4280  shell: powershell
4281  script: "echo x"
4282  timeout: 30s
4283client:
4284  name: "A job"
4285  category: software_update
4286  show_when:
4287    check: "office up to date"
4288    is: fail
4289"#;
4290        let m: Manifest = serde_yaml::from_str(bad_check).expect("parse");
4291        let err = m.validate().expect_err("malformed check slug must fail");
4292        assert!(err.contains("client.show_when.check"), "err: {err}");
4293
4294        let empty_is = r#"
4295id: j
4296version: 1.0.0
4297execute:
4298  shell: powershell
4299  script: "echo x"
4300  timeout: 30s
4301client:
4302  name: "A job"
4303  category: software_update
4304  show_when:
4305    check: office-up-to-date
4306    is: []
4307"#;
4308        let m: Manifest = serde_yaml::from_str(empty_is).expect("parse");
4309        let err = m.validate().expect_err("empty is[] must fail");
4310        assert!(err.contains("client.show_when.is"), "err: {err}");
4311    }
4312
4313    #[test]
4314    fn manifest_client_confirm_accepts_bool_and_struct() {
4315        // `confirm:` deserializes from a bare bool or a struct. A bool
4316        // sets `enabled` (message stays default); a struct carries a custom
4317        // message and defaults `enabled` to true.
4318        let base = r#"
4319id: j
4320version: 1.0.0
4321execute:
4322  shell: powershell
4323  script: "echo x"
4324  timeout: 30s
4325client:
4326  name: "Wi-Fi 省電力を切る"
4327  category: settings
4328"#;
4329        // `confirm: false` ⇒ dialog suppressed.
4330        let off: Manifest =
4331            serde_yaml::from_str(&format!("{base}  confirm: false\n")).expect("parse false");
4332        off.validate().expect("confirm: false validates");
4333        let c = off.client.unwrap().confirm.unwrap();
4334        assert!(!c.enabled);
4335        assert!(c.message.is_none());
4336
4337        // `confirm: true` ⇒ same as omitting (dialog shown, default message).
4338        let on: Manifest =
4339            serde_yaml::from_str(&format!("{base}  confirm: true\n")).expect("parse true");
4340        let c = on.client.unwrap().confirm.unwrap();
4341        assert!(c.enabled);
4342        assert!(c.message.is_none());
4343
4344        // Struct with only a message ⇒ enabled defaults true, custom text.
4345        let msg: Manifest = serde_yaml::from_str(&format!(
4346            "{base}  confirm:\n    message: \"再インストールには数分かかります。よろしいですか?\"\n"
4347        ))
4348        .expect("parse struct");
4349        msg.validate().expect("confirm message validates");
4350        let c = msg.client.unwrap().confirm.unwrap();
4351        assert!(c.enabled);
4352        assert_eq!(
4353            c.message.as_deref(),
4354            Some("再インストールには数分かかります。よろしいですか?")
4355        );
4356
4357        // Absent ⇒ None (historical default handled by the client).
4358        let none: Manifest = serde_yaml::from_str(base).expect("parse none");
4359        assert!(none.client.unwrap().confirm.is_none());
4360
4361        // Explicit `confirm: null` is schema-valid (the field is Option) and
4362        // must map to None, not a parse error (Gemini #960).
4363        let null: Manifest =
4364            serde_yaml::from_str(&format!("{base}  confirm: null\n")).expect("parse null");
4365        assert!(null.client.unwrap().confirm.is_none());
4366    }
4367
4368    #[test]
4369    fn manifest_client_confirm_rejects_blank_message() {
4370        // A present-but-blank custom message would render an empty dialog
4371        // title — validate() must reject it, like the other display fields.
4372        let yaml = r#"
4373id: j
4374version: 1.0.0
4375execute:
4376  shell: powershell
4377  script: "echo x"
4378  timeout: 30s
4379client:
4380  name: "A job"
4381  category: settings
4382  confirm:
4383    message: "   "
4384"#;
4385        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4386        let err = m.validate().expect_err("blank confirm.message must fail");
4387        assert!(err.contains("client.confirm.message"), "err: {err}");
4388    }
4389
4390    #[test]
4391    fn manifest_client_requires_category_at_parse() {
4392        // A `client:` block missing `category` is a hard parse error
4393        // (serde required field) — no manual validate() needed.
4394        let yaml = r#"
4395id: j
4396version: 1.0.0
4397execute:
4398  shell: powershell
4399  script: "echo x"
4400  timeout: 30s
4401client:
4402  name: "A job"
4403"#;
4404        let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
4405        assert!(
4406            r.is_err(),
4407            "missing category must be a parse error, got {r:?}"
4408        );
4409    }
4410
4411    #[test]
4412    fn manifest_client_rejects_unknown_field() {
4413        // #492: the strict create boundary catches a fat-fingered
4414        // `displayname:` (with its path) instead of silently
4415        // dropping it; the tolerant read path accepts it.
4416        let yaml = r#"
4417id: j
4418version: 1.0.0
4419execute:
4420  shell: powershell
4421  script: "echo x"
4422  timeout: 30s
4423client:
4424  name: "A job"
4425  category: catalog
4426  displayname: oops
4427"#;
4428        let r = crate::strict::from_yaml_str::<Manifest>(yaml);
4429        let err = r.expect_err("unknown client field must be rejected at the write boundary");
4430        // serde_ignored renders the Option layer as `?`:
4431        // `client.?.displayname`. Assert on the leaf key.
4432        assert!(err.contains("displayname"), "{err}");
4433        // The READ path tolerates the same payload (gradual-upgrade
4434        // contract: an old agent must accept a newer writer's field).
4435        let m: Manifest = serde_yaml::from_str(yaml).expect("tolerant read");
4436        assert_eq!(m.client.as_ref().map(|c| c.name.as_str()), Some("A job"));
4437    }
4438
4439    #[test]
4440    fn manifest_tags_default_empty() {
4441        // The overwhelming majority of jobs carry no tags; the field
4442        // must default to an empty Vec (not fail to parse) and skip
4443        // serialisation so old readers never see the key.
4444        let yaml = r#"
4445id: echo-test
4446version: 0.0.1
4447execute:
4448  shell: powershell
4449  script: "echo 'kanade'"
4450  timeout: 30s
4451"#;
4452        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4453        assert!(m.tags.is_empty());
4454        m.validate().expect("tag-less job validates");
4455        // skip_serializing_if = empty ⇒ the key is absent from JSON.
4456        let json = serde_json::to_string(&m).expect("serialize");
4457        assert!(
4458            !json.contains("tags"),
4459            "empty tags must not serialise: {json}"
4460        );
4461    }
4462
4463    #[test]
4464    fn manifest_parses_and_validates_tags() {
4465        let yaml = r#"
4466id: check-bitlocker
4467version: 0.1.0
4468execute:
4469  shell: powershell
4470  script: "echo x"
4471  timeout: 30s
4472tags: [security, windows, health-check]
4473"#;
4474        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4475        assert_eq!(m.tags, vec!["security", "windows", "health-check"]);
4476        m.validate().expect("tagged job validates");
4477        // Round-trips through JSON (the wire format the SPA reads).
4478        let json = serde_json::to_string(&m).expect("serialize");
4479        assert!(json.contains("\"tags\""), "non-empty tags must serialise");
4480    }
4481
4482    #[test]
4483    fn manifest_rejects_blank_tag() {
4484        // A whitespace-only tag renders an empty filter chip — reject
4485        // it at the write boundary like the other blank display fields.
4486        let yaml = r#"
4487id: j
4488version: 0.1.0
4489execute:
4490  shell: powershell
4491  script: "echo x"
4492  timeout: 30s
4493tags: [ok, "   "]
4494"#;
4495        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4496        let err = m.validate().expect_err("blank tag must fail");
4497        assert!(err.contains("tags must not contain empty"), "err: {err}");
4498    }
4499
4500    #[test]
4501    fn validate_rejects_unknown_tier_and_accepts_known() {
4502        let base =
4503            "id: t\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: x\n  timeout: 30s\n";
4504        // A typo / future tier decodes to Tier::Unknown (#[serde(other)]) and
4505        // must FAIL CLOSED — never fall back to unrestricted endpoint dispatch.
4506        let bogus: Manifest =
4507            serde_yaml::from_str(&format!("{base}tier: controler\n")).expect("parse");
4508        let err = bogus.validate().expect_err("unknown tier must be rejected");
4509        assert!(err.contains("tier"), "err: {err}");
4510        // The two known tiers pass.
4511        serde_yaml::from_str::<Manifest>(&format!("{base}tier: controller\n"))
4512            .unwrap()
4513            .validate()
4514            .expect("controller tier is valid");
4515        serde_yaml::from_str::<Manifest>(&format!("{base}tier: endpoint\n"))
4516            .unwrap()
4517            .validate()
4518            .expect("endpoint tier is valid");
4519    }
4520
4521    #[test]
4522    fn feed_payload_extracts_fenced_block() {
4523        let stdout = "fetched 1500 KEV entries\n\
4524            #KANADE-FEED-BEGIN\n\
4525            {\"vulnerabilities\": []}\n\
4526            #KANADE-FEED-END\n";
4527        assert_eq!(feed_payload(stdout), "{\"vulnerabilities\": []}");
4528    }
4529
4530    #[test]
4531    fn validate_feed_rules() {
4532        let base =
4533            "id: f\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: x\n  timeout: 30s\n";
4534        // A well-formed feed (controller implied; no explicit tier) passes.
4535        serde_yaml::from_str::<Manifest>(&format!(
4536            "{base}feed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4537        ))
4538        .unwrap()
4539        .validate()
4540        .expect("a well-formed feed is valid");
4541
4542        // Empty primary_key is rejected (no item_id → every row dropped).
4543        let err = serde_yaml::from_str::<Manifest>(&format!(
4544            "{base}feed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: []\n"
4545        ))
4546        .unwrap()
4547        .validate()
4548        .expect_err("empty primary_key must be rejected");
4549        assert!(err.contains("primary_key"), "err: {err}");
4550
4551        // A duplicate feed id clobbers a partition — rejected.
4552        let err = serde_yaml::from_str::<Manifest>(&format!(
4553            "{base}feed:\n  - id: dup\n    field: a\n    primary_key: [k]\n  - id: dup\n    field: b\n    primary_key: [k]\n"
4554        ))
4555        .unwrap()
4556        .validate()
4557        .expect_err("duplicate feed id must be rejected");
4558        assert!(err.contains("more than once"), "err: {err}");
4559
4560        // `feed:` + explicit `tier: endpoint` is contradictory — rejected.
4561        let err = serde_yaml::from_str::<Manifest>(&format!(
4562            "{base}tier: endpoint\nfeed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4563        ))
4564        .unwrap()
4565        .validate()
4566        .expect_err("feed + tier: endpoint must be rejected");
4567        assert!(err.contains("controller tier"), "err: {err}");
4568
4569        // `feed:` + `emit:` is incompatible — emit consumes stdout whole, so
4570        // the feed's fence never reaches the projector.
4571        let err = serde_yaml::from_str::<Manifest>(&format!(
4572            "{base}emit:\n  type: events\nfeed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4573        ))
4574        .unwrap()
4575        .validate()
4576        .expect_err("feed + emit must be rejected");
4577        assert!(err.contains("emit"), "err: {err}");
4578    }
4579
4580    // #720 — wrap an `aggregate:` YAML block (already indented as a
4581    // top-level key body) into an otherwise-minimal valid manifest.
4582    fn manifest_with_aggregate(aggregate_block: &str) -> Manifest {
4583        let yaml = format!(
4584            "id: t\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: echo hi\n  timeout: 30s\n{aggregate_block}"
4585        );
4586        serde_yaml::from_str(&yaml).expect("parse aggregate manifest")
4587    }
4588
4589    #[test]
4590    fn aggregate_accepts_full_valid_spec() {
4591        // count+group_by+exclude+sample_minutes, ratio+bool_path,
4592        // timeline+time_bucket, fleet ranking via group_by: pc_id, and a
4593        // bare total stat — alongside emit (composes with every hint).
4594        let m = manifest_with_aggregate(
4595            "emit:\n  type: events\naggregate:\n\
4596             - { placement: { analytics: Utilization }, title: Top apps, kind: app_sample, agg: count, group_by: foreground.app, sample_minutes: 2, exclude: [LockApp], render: bar }\n\
4597             - { placement: { analytics: Utilization }, title: Active ratio, kind: presence, agg: ratio, bool_path: active, sample_minutes: 5, render: gauge }\n\
4598             - { placement: { analytics: Utilization }, title: By hour, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: timeline }\n\
4599             - { placement: { analytics: Reliability }, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
4600             - { placement: { analytics: Reliability }, title: Total crashes, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
4601        );
4602        m.validate().expect("valid aggregate spec");
4603    }
4604
4605    #[test]
4606    fn aggregate_rejects_empty_list() {
4607        let m = manifest_with_aggregate("aggregate: []\n");
4608        let err = m.validate().expect_err("empty list must fail");
4609        assert!(err.contains("at least one widget"), "err: {err}");
4610    }
4611
4612    #[test]
4613    fn aggregate_rejects_ratio_without_bool_path() {
4614        let m = manifest_with_aggregate(
4615            "aggregate:\n- { placement: { analytics: D }, title: T, kind: presence, agg: ratio, render: gauge }\n",
4616        );
4617        let err = m.validate().expect_err("ratio needs bool_path");
4618        assert!(err.contains("agg=ratio requires `bool_path`"), "err: {err}");
4619    }
4620
4621    #[test]
4622    fn aggregate_rejects_sum_without_value_path() {
4623        let m = manifest_with_aggregate(
4624            "aggregate:\n- { placement: { analytics: D }, title: T, kind: io, agg: sum, render: bar }\n",
4625        );
4626        let err = m.validate().expect_err("sum needs value_path");
4627        assert!(err.contains("agg=sum requires `value_path`"), "err: {err}");
4628    }
4629
4630    #[test]
4631    fn aggregate_rejects_pc_id_group_without_fleet() {
4632        let m = manifest_with_aggregate(
4633            "aggregate:\n- { placement: { analytics: D }, title: T, kind: presence, agg: count, group_by: pc_id, render: bar }\n",
4634        );
4635        let err = m.validate().expect_err("pc_id grouping needs fleet");
4636        assert!(
4637            err.contains("pc_id is only valid with scope: fleet"),
4638            "err: {err}"
4639        );
4640    }
4641
4642    #[test]
4643    fn aggregate_rejects_transform_with_pc_id_group() {
4644        let m = manifest_with_aggregate(
4645            "aggregate:\n- { placement: { analytics: D }, title: T, scope: fleet, kind: web_visit, agg: count, group_by: pc_id, transform: host, render: bar }\n",
4646        );
4647        let err = m
4648            .validate()
4649            .expect_err("transform on pc_id grouping must fail");
4650        assert!(
4651            err.contains("transform is not valid with group_by: pc_id"),
4652            "err: {err}"
4653        );
4654    }
4655
4656    #[test]
4657    fn aggregate_rejects_timeline_without_bucket() {
4658        let m = manifest_with_aggregate(
4659            "aggregate:\n- { placement: { analytics: D }, title: T, kind: presence, agg: ratio, bool_path: active, render: timeline }\n",
4660        );
4661        let err = m.validate().expect_err("timeline needs a bucket");
4662        assert!(
4663            err.contains("render=timeline requires `time_bucket`"),
4664            "err: {err}"
4665        );
4666    }
4667
4668    #[test]
4669    fn aggregate_rejects_bucket_on_non_timeline() {
4670        let m = manifest_with_aggregate(
4671            "aggregate:\n- { placement: { analytics: D }, title: T, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: gauge }\n",
4672        );
4673        let err = m.validate().expect_err("bucket only on timeline");
4674        assert!(
4675            err.contains("time_bucket is only valid with render: timeline"),
4676            "err: {err}"
4677        );
4678    }
4679
4680    #[test]
4681    fn aggregate_rejects_unsafe_json_path() {
4682        // A path with characters outside [A-Za-z0-9_.] could break out of
4683        // the `'$.' || ?` bind — reject at create time.
4684        let m = manifest_with_aggregate(
4685            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, group_by: \"foo'; DROP\", render: bar }\n",
4686        );
4687        let err = m.validate().expect_err("unsafe path must fail");
4688        assert!(err.contains("dotted JSON path"), "err: {err}");
4689    }
4690
4691    #[test]
4692    fn aggregate_rejects_blank_title() {
4693        let m = manifest_with_aggregate(
4694            "aggregate:\n- { placement: { analytics: D }, title: \"  \", kind: k, agg: count, render: stat }\n",
4695        );
4696        let err = m.validate().expect_err("blank title must fail");
4697        assert!(err.contains("title must not be empty"), "err: {err}");
4698    }
4699
4700    #[test]
4701    fn aggregate_rejects_blank_kind() {
4702        let m = manifest_with_aggregate(
4703            "aggregate:\n- { placement: { analytics: D }, title: T, kind: \" \", agg: count, render: stat }\n",
4704        );
4705        let err = m.validate().expect_err("blank kind must fail");
4706        assert!(err.contains("kind must not be empty"), "err: {err}");
4707    }
4708
4709    #[test]
4710    fn aggregate_rejects_blank_source_when_set() {
4711        let m = manifest_with_aggregate(
4712            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, source: \"\", agg: count, render: stat }\n",
4713        );
4714        let err = m.validate().expect_err("blank source must fail");
4715        assert!(
4716            err.contains("source must not be empty when set"),
4717            "err: {err}"
4718        );
4719    }
4720
4721    #[test]
4722    fn aggregate_accepts_description_and_rejects_blank() {
4723        let ok = manifest_with_aggregate(
4724            "aggregate:\n- { placement: { analytics: D }, title: T, description: \"samples x 2 min\", kind: k, agg: count, render: stat }\n",
4725        );
4726        ok.validate()
4727            .expect("description is a valid optional field");
4728        assert_eq!(
4729            ok.aggregate.as_ref().unwrap()[0].description.as_deref(),
4730            Some("samples x 2 min")
4731        );
4732        let bad = manifest_with_aggregate(
4733            "aggregate:\n- { placement: { analytics: D }, title: T, description: \"  \", kind: k, agg: count, render: stat }\n",
4734        );
4735        let err = bad.validate().expect_err("blank description must fail");
4736        assert!(
4737            err.contains("description must not be empty when set"),
4738            "err: {err}"
4739        );
4740    }
4741
4742    #[test]
4743    fn aggregate_rejects_count_with_value_path() {
4744        let m = manifest_with_aggregate(
4745            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, value_path: bytes, render: stat }\n",
4746        );
4747        let err = m.validate().expect_err("count must not use value_path");
4748        assert!(
4749            err.contains("agg=count does not use `value_path`"),
4750            "err: {err}"
4751        );
4752    }
4753
4754    #[test]
4755    fn aggregate_rejects_ratio_with_value_path() {
4756        let m = manifest_with_aggregate(
4757            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: ratio, bool_path: active, value_path: bytes, render: gauge }\n",
4758        );
4759        let err = m.validate().expect_err("ratio must not use value_path");
4760        assert!(
4761            err.contains("agg=ratio does not use `value_path`"),
4762            "err: {err}"
4763        );
4764    }
4765
4766    #[test]
4767    fn aggregate_rejects_gauge_without_ratio() {
4768        let m = manifest_with_aggregate(
4769            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, group_by: app, render: gauge }\n",
4770        );
4771        let err = m.validate().expect_err("gauge needs ratio");
4772        assert!(
4773            err.contains("render=gauge is only valid with agg: ratio"),
4774            "err: {err}"
4775        );
4776    }
4777
4778    #[test]
4779    fn aggregate_rejects_limit_without_group_by() {
4780        let m = manifest_with_aggregate(
4781            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, limit: 5, render: stat }\n",
4782        );
4783        let err = m.validate().expect_err("limit needs group_by");
4784        assert!(err.contains("limit requires `group_by`"), "err: {err}");
4785    }
4786
4787    #[test]
4788    fn aggregate_rejects_exclude_without_group_by() {
4789        let m = manifest_with_aggregate(
4790            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, exclude: [x], render: stat }\n",
4791        );
4792        let err = m.validate().expect_err("exclude needs group_by");
4793        assert!(err.contains("exclude requires `group_by`"), "err: {err}");
4794    }
4795
4796    #[test]
4797    fn aggregate_rejects_zero_limit_and_zero_sample_minutes() {
4798        let m = manifest_with_aggregate(
4799            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, group_by: app, limit: 0, render: bar }\n",
4800        );
4801        assert!(m.validate().unwrap_err().contains("limit must be > 0"));
4802        let m = manifest_with_aggregate(
4803            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, group_by: app, sample_minutes: 0, render: bar }\n",
4804        );
4805        assert!(
4806            m.validate()
4807                .unwrap_err()
4808                .contains("sample_minutes must be > 0")
4809        );
4810    }
4811
4812    #[test]
4813    fn aggregate_rejects_empty_exclude_entry() {
4814        let m = manifest_with_aggregate(
4815            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, group_by: app, exclude: [\"  \"], render: bar }\n",
4816        );
4817        let err = m.validate().expect_err("blank exclude entry must fail");
4818        assert!(
4819            err.contains("exclude must not contain empty entries"),
4820            "err: {err}"
4821        );
4822    }
4823
4824    #[test]
4825    fn aggregate_rejects_malformed_dotted_paths() {
4826        for bad in [".foo", "foo.", "foo..bar", "."] {
4827            let m = manifest_with_aggregate(&format!(
4828                "aggregate:\n- {{ placement: {{ analytics: D }}, title: T, kind: k, agg: count, group_by: \"{bad}\", render: bar }}\n"
4829            ));
4830            let err = m.validate().expect_err("malformed path must fail");
4831            assert!(err.contains("dotted JSON path"), "path {bad}: {err}");
4832        }
4833    }
4834
4835    #[test]
4836    fn aggregate_rejects_unknown_enum_value() {
4837        // An unrecognised render string deserialises to the #492 Unknown
4838        // catch-all (so old readers don't choke); validate() rejects it as
4839        // a typo at create time.
4840        let m = manifest_with_aggregate(
4841            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, render: heatmap }\n",
4842        );
4843        let err = m.validate().expect_err("unknown render must fail");
4844        assert!(err.contains("render is not a known value"), "err: {err}");
4845    }
4846
4847    #[test]
4848    fn aggregate_accepts_order_field() {
4849        let m = manifest_with_aggregate(
4850            "aggregate:\n- { placement: { analytics: D }, title: T, order: -5, kind: k, agg: count, render: stat }\n",
4851        );
4852        m.validate().expect("order is a valid optional field");
4853        let w = &m.aggregate.as_ref().unwrap()[0];
4854        assert_eq!(w.order, Some(-5));
4855    }
4856
4857    // #1257 moved aggregate widgets onto the shared `placement:` block, so
4858    // `validate_placement` is now reachable from a second call site
4859    // (`validate_aggregate_widgets`). The SqlWidget side already covers the
4860    // rule; these pin it down where it is new, since a regression there
4861    // would be invisible to those tests.
4862
4863    #[test]
4864    fn aggregate_rejects_widget_that_surfaces_nowhere() {
4865        // No `analytics` tab and not pinned ⇒ the widget renders nowhere.
4866        // Before #1257 this was unrepresentable (`dashboard` was a required
4867        // String), so it's a genuinely new way to write a broken widget.
4868        let err = manifest_with_aggregate(
4869            "aggregate:\n- { placement: {}, title: T, kind: k, agg: count, render: stat }\n",
4870        )
4871        .validate()
4872        .expect_err("a widget with no surface must be rejected");
4873        assert!(err.contains("placement must set"), "err: {err}");
4874
4875        // `pin: false` is a block that pins nowhere — presence of the block
4876        // must not be mistaken for an actual surface.
4877        let err = manifest_with_aggregate(
4878            "aggregate:\n- { placement: { dashboard: { pin: false } }, title: T, kind: k, agg: count, render: stat }\n",
4879        )
4880        .validate()
4881        .expect_err("pin: false surfaces nowhere either");
4882        assert!(err.contains("placement must set"), "err: {err}");
4883    }
4884
4885    #[test]
4886    fn aggregate_accepts_dashboard_only_widget() {
4887        // The capability the refactor unlocks: an aggregate widget that is
4888        // pinned to the Dashboard without also claiming an Analytics tab.
4889        // `tab()` falls back to a label so the grouped widget list still has
4890        // a key to group under.
4891        let m = manifest_with_aggregate(
4892            "aggregate:\n- { placement: { dashboard: { pin: true } }, title: T, scope: fleet, kind: k, agg: count, render: stat }\n",
4893        );
4894        m.validate().expect("dashboard-only placement is valid");
4895        let p = &m.aggregate.as_ref().unwrap()[0].placement;
4896        assert!(p.is_pinned());
4897        assert!(p.analytics.is_none());
4898        assert_eq!(p.tab(), "Dashboard");
4899    }
4900
4901    #[test]
4902    fn analytics_placement_reads_both_shapes_and_serializes_terse() {
4903        // The scalar-or-block contract, and the one-way collapse back to
4904        // the terse form: a block that sets no width is stored as the bare
4905        // string, so resource JSON doesn't grow a wrapper for the ~all
4906        // widgets that never ask for a width.
4907        let bare = manifest_with_aggregate(
4908            "aggregate:\n- { placement: { analytics: Uptime }, title: T, kind: k, agg: count, render: stat }\n",
4909        );
4910        let block = manifest_with_aggregate(
4911            "aggregate:\n- { placement: { analytics: { tab: Uptime } }, title: T, kind: k, agg: count, render: stat }\n",
4912        );
4913        for m in [&bare, &block] {
4914            assert_eq!(m.aggregate.as_ref().unwrap()[0].placement.tab(), "Uptime");
4915        }
4916        let json = serde_json::to_string(&bare.aggregate.as_ref().unwrap()[0].placement)
4917            .expect("serialize placement");
4918        assert!(json.contains(r#""analytics":"Uptime""#), "json: {json}");
4919
4920        // With a width it has to keep the block form, or the width is lost.
4921        let wide = manifest_with_aggregate(
4922            "aggregate:\n- { placement: { analytics: { tab: Uptime, width: half } }, title: T, kind: k, agg: count, render: stat }\n",
4923        );
4924        let p = &wide.aggregate.as_ref().unwrap()[0].placement;
4925        assert_eq!(p.width_for(false), Some(WidgetWidth::Half));
4926        // …and the Dashboard surface is untouched by an Analytics width.
4927        assert_eq!(p.width_for(true), None);
4928        let json = serde_json::to_string(p).expect("serialize placement");
4929        assert!(json.contains(r#""tab":"Uptime""#), "json: {json}");
4930        assert!(json.contains(r#""width":"half""#), "json: {json}");
4931    }
4932
4933    #[test]
4934    fn aggregate_accepts_minimal_op_timeline() {
4935        // op_timeline needs no kind/agg — it reconstructs a fixed multi-kind
4936        // swimlane. A bare per-PC spec is valid, and `kind`/`agg` stay None.
4937        let m = manifest_with_aggregate(
4938            "aggregate:\n- { placement: { analytics: Uptime }, title: Operational state, scope: pc, render: op_timeline }\n",
4939        );
4940        m.validate().expect("minimal op_timeline is valid");
4941        let w = &m.aggregate.as_ref().unwrap()[0];
4942        assert_eq!(w.render, AggregateRender::OpTimeline);
4943        assert!(w.kind.is_none());
4944        assert!(w.agg.is_none());
4945    }
4946
4947    #[test]
4948    fn aggregate_rejects_op_timeline_with_fleet_scope() {
4949        let m = manifest_with_aggregate(
4950            "aggregate:\n- { placement: { analytics: Uptime }, title: T, scope: fleet, render: op_timeline }\n",
4951        );
4952        let err = m.validate().expect_err("op_timeline must be per-PC");
4953        assert!(
4954            err.contains("render=op_timeline requires scope: pc"),
4955            "err: {err}"
4956        );
4957    }
4958
4959    #[test]
4960    fn aggregate_rejects_op_timeline_with_aggregation_fields() {
4961        // Each aggregation knob the operator might paste in is rejected
4962        // (rather than silently ignored), pointing at the field to delete.
4963        for (block, field) in [
4964            ("kind: boot", "kind"),
4965            ("agg: count", "agg"),
4966            ("source: winlog:Security", "source"),
4967            ("group_by: pc_id", "group_by"),
4968            ("bool_path: active", "bool_path"),
4969            ("time_bucket: hour", "time_bucket"),
4970            ("limit: 5", "limit"),
4971        ] {
4972            let m = manifest_with_aggregate(&format!(
4973                "aggregate:\n- {{ placement: {{ analytics: Uptime }}, title: T, scope: pc, {block}, render: op_timeline }}\n"
4974            ));
4975            let err = m
4976                .validate()
4977                .expect_err(&format!("op_timeline must reject {field}"));
4978            assert!(
4979                err.contains(&format!("render=op_timeline does not use `{field}`")),
4980                "field {field}: {err}"
4981            );
4982        }
4983    }
4984
4985    // ── #743 View resource ───────────────────────────────────────────
4986    fn view_from(yaml_body: &str) -> View {
4987        serde_yaml::from_str(&format!("id: v1\n{yaml_body}")).expect("parse view")
4988    }
4989
4990    #[test]
4991    fn view_accepts_valid_widgets() {
4992        let v = view_from(
4993            "widgets:\n\
4994             - { placement: { analytics: Reliability }, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
4995             - { placement: { analytics: Reliability }, title: Total, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
4996        );
4997        v.validate().expect("valid view");
4998    }
4999
5000    #[test]
5001    fn view_rejects_empty_widgets() {
5002        let v = view_from("widgets: []\n");
5003        let err = v.validate().expect_err("empty widgets must fail");
5004        assert!(err.contains("at least one widget"), "err: {err}");
5005    }
5006
5007    #[test]
5008    fn view_rejects_blank_id() {
5009        let v: View = serde_yaml::from_str(
5010            "id: \"  \"\nwidgets:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, render: stat }\n",
5011        )
5012        .expect("parse");
5013        let err = v.validate().expect_err("blank id must fail");
5014        assert!(err.contains("view.id must"), "err: {err}");
5015    }
5016
5017    #[test]
5018    fn view_rejects_unsafe_id() {
5019        // A `/` or `..` in the id would break the KV key and the
5020        // `/api/views/{id}` URL segment — reject at create time.
5021        for bad in ["../etc", "a/b", "has space", "x;y"] {
5022            let v: View = serde_yaml::from_str(&format!(
5023                "id: \"{bad}\"\nwidgets:\n- {{ placement: {{ analytics: D }}, title: T, kind: k, agg: count, render: stat }}\n",
5024            ))
5025            .expect("parse");
5026            let err = v.validate().expect_err("unsafe id must fail");
5027            assert!(err.contains("[A-Za-z0-9._-]"), "id {bad}: {err}");
5028        }
5029        assert!(is_valid_resource_id("dashboards-fleet.v1_2"));
5030    }
5031
5032    #[test]
5033    fn view_rejects_untrimmed_id() {
5034        // A padded id validated-as-trimmed but stored-raw would be a KV key
5035        // (and `/api/views/{id}` segment) nothing matches — reject it outright
5036        // (the id is used verbatim).
5037        let v: View = serde_yaml::from_str(
5038            "id: \" my-view \"\nwidgets:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, render: stat }\n",
5039        )
5040        .expect("parse");
5041        let err = v.validate().expect_err("padded id must fail");
5042        assert!(err.contains("view.id must"), "err: {err}");
5043    }
5044
5045    #[test]
5046    fn view_reuses_shared_widget_validation() {
5047        // The same per-widget rule the job hint enforces (ratio needs
5048        // bool_path), reported under the `widgets[..]` field.
5049        let v = view_from(
5050            "widgets:\n- { placement: { analytics: D }, title: T, kind: presence, agg: ratio, render: gauge }\n",
5051        );
5052        let err = v.validate().expect_err("ratio without bool_path must fail");
5053        assert!(
5054            err.contains("widgets[0].agg=ratio requires `bool_path`"),
5055            "err: {err}"
5056        );
5057    }
5058
5059    // ── #vuln-roadmap PR3 SQL-backed views ───────────────────────────
5060    #[test]
5061    fn view_accepts_pure_sql_widgets() {
5062        // A view with only sql_widgets (no obs_events aggregate widgets) is
5063        // valid — the vulnerability-dashboard shape.
5064        let v = view_from(
5065            "sql_widgets:
5066  - title: KEV-affected hosts
5067    query: \"SELECT pc_id, 1 AS cves FROM inventory_sw_apps\"
5068    refresh: 6h
5069    render: { kind: table, columns: [pc_id, cves], labels: { cves: CVE count } }
5070    placement: { analytics: Security, dashboard: { pin: true } }
5071",
5072        );
5073        v.validate().expect("valid sql view");
5074        // refresh parses; pin/tab helpers read the placement.
5075        let w = &v.sql_widgets[0];
5076        assert_eq!(
5077            w.refresh_interval(),
5078            std::time::Duration::from_secs(6 * 3600)
5079        );
5080        assert!(w.placement.is_pinned());
5081        assert_eq!(w.placement.tab(), "Security");
5082    }
5083
5084    #[test]
5085    fn sql_widget_defaults_and_mix() {
5086        // No refresh ⇒ default; a view can mix aggregate + sql widgets.
5087        let v = view_from(
5088            "widgets:
5089  - { placement: { analytics: D }, title: T, kind: k, agg: count, render: stat }
5090sql_widgets:
5091  - title: N affected
5092    query: \"SELECT count(*) AS n FROM feeds\"
5093    render: { kind: stat, value: n }
5094    placement: { dashboard: { pin: true } }
5095",
5096        );
5097        v.validate().expect("mixed view is valid");
5098        assert_eq!(v.sql_widgets[0].refresh_interval(), DEFAULT_VIEW_REFRESH);
5099        // dashboard-only placement (no analytics tab) falls back to a label.
5100        assert_eq!(v.sql_widgets[0].placement.tab(), "Dashboard");
5101    }
5102
5103    #[test]
5104    fn sql_widget_validation_rules() {
5105        // helper: build a view with one sql_widget from an inline render+placement
5106        let mk = |render: &str, placement: &str| -> Result<(), String> {
5107            view_from(&format!(
5108                "sql_widgets:
5109  - title: W
5110    query: \"SELECT 1 AS a\"
5111    render: {render}
5112    placement: {placement}
5113"
5114            ))
5115            .validate()
5116        };
5117        // bar needs label + value
5118        let err = mk("{ kind: bar, value: a }", "{ analytics: T }").unwrap_err();
5119        assert!(
5120            err.contains("render.label is required for kind=bar"),
5121            "err: {err}"
5122        );
5123        // pie needs value
5124        let err = mk("{ kind: pie, label: a }", "{ analytics: T }").unwrap_err();
5125        assert!(
5126            err.contains("render.value is required for kind=pie"),
5127            "err: {err}"
5128        );
5129        // stat needs value
5130        let err = mk("{ kind: stat }", "{ analytics: T }").unwrap_err();
5131        assert!(
5132            err.contains("render.value is required for kind=stat"),
5133            "err: {err}"
5134        );
5135        // gauge needs value XOR num+den
5136        let err = mk("{ kind: gauge, num: a }", "{ analytics: T }").unwrap_err();
5137        assert!(err.contains("needs either `value`"), "err: {err}");
5138        mk("{ kind: gauge, value: a }", "{ analytics: T }").expect("gauge value ok");
5139        mk("{ kind: gauge, num: a, den: a }", "{ analytics: T }").expect("gauge num/den ok");
5140        // unknown kind rejected
5141        let err = mk("{ kind: sunburst }", "{ analytics: T }").unwrap_err();
5142        assert!(
5143            err.contains("render.kind is not a known value"),
5144            "err: {err}"
5145        );
5146        // placement must surface somewhere
5147        let err = mk("{ kind: table }", "{}").unwrap_err();
5148        assert!(err.contains("placement must set"), "err: {err}");
5149        // a `dashboard: { pin: false }` block still surfaces nowhere.
5150        let err = mk("{ kind: table }", "{ dashboard: { pin: false } }").unwrap_err();
5151        assert!(err.contains("placement must set"), "err: {err}");
5152        mk("{ kind: table }", "{ dashboard: { pin: true } }").expect("pinned dashboard ok");
5153        // limit: 0 on a bar/pie is an invisible widget — rejected.
5154        let err = mk(
5155            "{ kind: bar, label: a, value: a, limit: 0 }",
5156            "{ analytics: T }",
5157        )
5158        .unwrap_err();
5159        assert!(err.contains("limit must be >= 1"), "err: {err}");
5160        // bad refresh duration rejected
5161        let err = view_from(
5162            "sql_widgets:
5163  - { title: W, query: \"SELECT 1\", refresh: \"6 sidereal days\", render: { kind: table }, placement: { analytics: T } }
5164",
5165        )
5166        .validate()
5167        .unwrap_err();
5168        assert!(
5169            err.contains("refresh") && err.contains("not a valid duration"),
5170            "err: {err}"
5171        );
5172        // table is fine with no channels
5173        mk("{ kind: table }", "{ analytics: T }").expect("bare table ok");
5174    }
5175
5176    #[test]
5177    fn rewrite_pc_id_param_is_literal_and_boundary_aware() {
5178        // A real param outside any literal is rewritten + counted.
5179        let (sql, n) = rewrite_pc_id_param("SELECT * FROM t WHERE pc_id = :pc_id");
5180        assert_eq!(n, 1);
5181        assert!(sql.ends_with("pc_id = ?"), "sql: {sql}");
5182        // Appearing twice → two `?`, count 2 (one bind each — the caller binds
5183        // pc_id per occurrence since sqlx-sqlite has no named params).
5184        let (sql, n) = rewrite_pc_id_param("WHERE a = :pc_id AND (:pc_id IS NOT NULL)");
5185        assert_eq!(n, 2);
5186        assert_eq!(sql, "WHERE a = ? AND (? IS NOT NULL)");
5187        // Inside a string literal → copied verbatim, NOT counted (would else be
5188        // a bind-count mismatch → SQLITE_RANGE, and misclassify scope).
5189        let (sql, n) = rewrite_pc_id_param("SELECT 'see :pc_id docs' AS hint");
5190        assert_eq!(n, 0);
5191        assert_eq!(sql, "SELECT 'see :pc_id docs' AS hint");
5192        // Inside a comment → left alone.
5193        let (_, n) = rewrite_pc_id_param("SELECT 1 -- filter by :pc_id\n");
5194        assert_eq!(n, 0);
5195        // A longer identifier prefix (`:pc_idx`) is not our token.
5196        let (sql, n) = rewrite_pc_id_param("WHERE x = :pc_idx");
5197        assert_eq!(n, 0);
5198        assert_eq!(sql, "WHERE x = :pc_idx");
5199    }
5200
5201    #[test]
5202    fn validate_rejects_pinned_per_pc_widget() {
5203        // A per-PC widget (binds :pc_id) that also pins to the Dashboard is a
5204        // create-time contradiction (Dashboard is fleet-scope) — rejected.
5205        let err = view_from(
5206            "sql_widgets:
5207  - title: W
5208    query: \"SELECT count(*) AS n FROM inventory_sw_apps WHERE pc_id = :pc_id\"
5209    render: { kind: stat, value: n }
5210    placement: { analytics: Security, dashboard: { pin: true } }
5211",
5212        )
5213        .validate()
5214        .unwrap_err();
5215        assert!(err.contains("per-PC widget"), "err: {err}");
5216        // The same widget WITHOUT the pin is fine (per-PC, analytics only).
5217        view_from(
5218            "sql_widgets:
5219  - title: W
5220    query: \"SELECT count(*) AS n FROM inventory_sw_apps WHERE pc_id = :pc_id\"
5221    render: { kind: stat, value: n }
5222    placement: { analytics: Security }
5223",
5224        )
5225        .validate()
5226        .expect("per-PC analytics-only widget is valid");
5227    }
5228
5229    fn execute_with(
5230        script: Option<&str>,
5231        script_file: Option<&str>,
5232        script_object: Option<&str>,
5233    ) -> Execute {
5234        Execute {
5235            bypass_local_limit: false,
5236            shell: ExecuteShell::Powershell,
5237            script: script.map(str::to_owned),
5238            script_file: script_file.map(str::to_owned),
5239            script_object: script_object.map(str::to_owned),
5240            timeout: "30s".into(),
5241            run_as: RunAs::default(),
5242            cwd: None,
5243        }
5244    }
5245
5246    #[test]
5247    fn validate_accepts_inline_script() {
5248        let e = execute_with(Some("echo hi"), None, None);
5249        assert!(e.validate_script_source().is_ok());
5250    }
5251
5252    #[test]
5253    fn validate_accepts_script_file_alone() {
5254        let e = execute_with(None, Some("scripts/cleanup.ps1"), None);
5255        assert!(e.validate_script_source().is_ok());
5256    }
5257
5258    #[test]
5259    fn validate_accepts_script_object_alone() {
5260        let e = execute_with(None, None, Some("cleanup/1.0.0"));
5261        assert!(e.validate_script_source().is_ok());
5262    }
5263
5264    #[test]
5265    fn validate_treats_empty_inline_script_as_unset() {
5266        // `script: ""` + `script_object` set is the natural shape
5267        // when an operator comments out the YAML block-scalar body
5268        // but leaves the key. Should pass.
5269        let e = execute_with(Some(""), None, Some("cleanup/1.0.0"));
5270        assert!(e.validate_script_source().is_ok());
5271    }
5272
5273    #[test]
5274    fn validate_rejects_zero_sources() {
5275        let e = execute_with(None, None, None);
5276        let err = e.validate_script_source().unwrap_err();
5277        assert!(err.contains("must be set"), "got: {err}");
5278    }
5279
5280    #[test]
5281    fn validate_rejects_empty_inline_only() {
5282        let e = execute_with(Some(""), None, None);
5283        let err = e.validate_script_source().unwrap_err();
5284        assert!(err.contains("must be set"), "got: {err}");
5285    }
5286
5287    #[test]
5288    fn validate_rejects_inline_plus_file() {
5289        let e = execute_with(Some("echo hi"), Some("scripts/cleanup.ps1"), None);
5290        let err = e.validate_script_source().unwrap_err();
5291        assert!(err.contains("only one of"), "got: {err}");
5292    }
5293
5294    #[test]
5295    fn validate_rejects_inline_plus_object() {
5296        let e = execute_with(Some("echo hi"), None, Some("cleanup/1.0.0"));
5297        let err = e.validate_script_source().unwrap_err();
5298        assert!(err.contains("only one of"), "got: {err}");
5299    }
5300
5301    #[test]
5302    fn validate_rejects_file_plus_object() {
5303        let e = execute_with(None, Some("scripts/cleanup.ps1"), Some("cleanup/1.0.0"));
5304        let err = e.validate_script_source().unwrap_err();
5305        assert!(err.contains("only one of"), "got: {err}");
5306    }
5307
5308    #[test]
5309    fn validate_rejects_all_three() {
5310        let e = execute_with(
5311            Some("echo hi"),
5312            Some("scripts/cleanup.ps1"),
5313            Some("cleanup/1.0.0"),
5314        );
5315        let err = e.validate_script_source().unwrap_err();
5316        assert!(err.contains("only one of"), "got: {err}");
5317    }
5318
5319    #[test]
5320    fn validate_rejects_blank_script_file() {
5321        // #918: a blank `script_file` used to count as "set" and pass
5322        // the exactly-one check, then fail at use time (the CLI reads
5323        // a file named "").
5324        for blank in ["", "   "] {
5325            let e = execute_with(None, Some(blank), None);
5326            let err = e.validate_script_source().unwrap_err();
5327            assert!(err.contains("script_file must not be blank"), "got: {err}");
5328        }
5329    }
5330
5331    #[test]
5332    fn validate_rejects_blank_script_object() {
5333        // #918: same for a blank `script_object` (would 404 every exec).
5334        for blank in ["", "   "] {
5335            let e = execute_with(None, None, Some(blank));
5336            let err = e.validate_script_source().unwrap_err();
5337            assert!(
5338                err.contains("script_object must not be blank"),
5339                "got: {err}"
5340            );
5341        }
5342    }
5343
5344    #[test]
5345    fn validate_treats_whitespace_inline_script_as_unset() {
5346        // #918: a whitespace-only inline body is a commented-out block,
5347        // not a real script — with no other source it's "zero sources".
5348        let e = execute_with(Some("   \n  "), None, None);
5349        let err = e.validate_script_source().unwrap_err();
5350        assert!(err.contains("must be set"), "got: {err}");
5351    }
5352
5353    #[test]
5354    fn validate_rejects_malformed_script_object_ref() {
5355        // #918: the ref must be `<name>/<version>`; a missing slash,
5356        // extra slash, blank half, or whitespace-padded half (the last
5357        // survives a JSON POST body and 404s at exec — gemini/claude
5358        // #943) can never resolve.
5359        for bad in [
5360            "no-slash", "a/b/c", "/1.0.0", "cleanup/", " / ", "foo/bar ", " foo/bar", "foo /bar",
5361        ] {
5362            let e = execute_with(None, None, Some(bad));
5363            let err = e.validate_script_source().unwrap_err();
5364            assert!(
5365                err.contains("must be `<name>/<version>`"),
5366                "for '{bad}', got: {err}"
5367            );
5368        }
5369    }
5370
5371    #[test]
5372    fn manifest_deserialises_script_object_yaml() {
5373        // SPEC §2.4.1 example shape with the Object Store
5374        // reference picked over inline.
5375        let yaml = r#"
5376id: cleanup-disk-temp
5377version: 1.0.1
5378execute:
5379  shell: powershell
5380  script_object: cleanup-disk-temp/1.0.1
5381  timeout: 600s
5382"#;
5383        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
5384        assert_eq!(
5385            m.execute.script_object.as_deref(),
5386            Some("cleanup-disk-temp/1.0.1")
5387        );
5388        assert!(m.execute.script.is_none());
5389        m.validate()
5390            .expect("script_object-only manifest passes validation");
5391    }
5392
5393    #[test]
5394    fn manifest_rejects_typo_in_script_field_name() {
5395        // #492: the strict create boundary catches `script_objectt`
5396        // and similar fat-fingers (with the full path) instead of
5397        // letting them silently fall through to "all three unset".
5398        let yaml = r#"
5399id: typo
5400version: 1.0.0
5401execute:
5402  shell: powershell
5403  script_objectt: oops
5404  timeout: 30s
5405"#;
5406        let err = crate::strict::from_yaml_str::<Manifest>(yaml)
5407            .expect_err("typo'd execute field must be rejected at the write boundary");
5408        assert!(err.contains("execute.script_objectt"), "{err}");
5409    }
5410
5411    #[test]
5412    fn schedule_carries_target_and_rollout() {
5413        let yaml = r#"
5414id: hourly-cleanup-canary
5415when:
5416  per_pc: { every: 1h }
5417job_id: cleanup
5418enabled: true
5419target:
5420  groups: [canary, wave1]
5421jitter: 30s
5422rollout:
5423  strategy: wave
5424  waves:
5425    - { group: canary, delay: 0s }
5426    - { group: wave1,  delay: 5s }
5427"#;
5428        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5429        assert_eq!(s.id, "hourly-cleanup-canary");
5430        assert_eq!(s.job_id, "cleanup");
5431        assert_eq!(s.plan.target.groups, vec!["canary", "wave1"]);
5432        assert_eq!(s.plan.jitter.as_deref(), Some("30s"));
5433        let rollout = s.plan.rollout.expect("rollout present");
5434        assert_eq!(rollout.waves.len(), 2);
5435        assert_eq!(rollout.waves[0].group, "canary");
5436        assert_eq!(rollout.waves[1].delay, "5s");
5437        assert_eq!(rollout.strategy, RolloutStrategy::Wave);
5438    }
5439
5440    #[test]
5441    fn schedule_minimal_target_all() {
5442        let yaml = r#"
5443id: kitting
5444when:
5445  per_pc: once
5446enabled: true
5447job_id: scheduled-echo
5448target: { all: true }
5449"#;
5450        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5451        assert_eq!(s.id, "kitting");
5452        assert_eq!(s.when, When::PerPc(PerPolicy::Once(OnceLiteral::Once)));
5453        assert!(s.enabled);
5454        assert_eq!(s.job_id, "scheduled-echo");
5455        assert!(s.plan.target.all);
5456        assert!(s.plan.rollout.is_none());
5457        assert!(s.plan.jitter.is_none());
5458        assert!(s.active.is_empty());
5459    }
5460
5461    #[test]
5462    fn schedule_enabled_defaults_to_true() {
5463        let yaml = r#"
5464id: x
5465when:
5466  per_pc: once
5467job_id: y
5468target: { all: true }
5469"#;
5470        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5471        assert!(s.enabled);
5472    }
5473
5474    fn once_per_version_yaml(runs_on: &str, per: &str) -> String {
5475        format!(
5476            "id: x\nwhen:\n  {per}\njob_id: install-kanade-client\n\
5477             target: {{ groups: [dejisen] }}\nruns_on: {runs_on}\n"
5478        )
5479    }
5480
5481    #[test]
5482    fn per_pc_once_per_version_parses() {
5483        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5484            "backend",
5485            "per_pc: once_per_version",
5486        ))
5487        .expect("parse");
5488        assert_eq!(
5489            s.when,
5490            When::PerPc(PerPolicy::OncePerVersion(
5491                OncePerVersionLiteral::OncePerVersion
5492            ))
5493        );
5494    }
5495
5496    #[test]
5497    fn per_pc_once_per_version_lowers_to_version_mode_no_cooldown() {
5498        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5499            "backend",
5500            "per_pc: once_per_version",
5501        ))
5502        .expect("parse");
5503        let l = s.lowered();
5504        assert_eq!(l.mode, ExecMode::OncePerPcVersion);
5505        assert_eq!(l.cooldown, None, "version re-arm is not a cooldown");
5506    }
5507
5508    #[test]
5509    fn once_per_version_displays_and_serialises() {
5510        let w = When::PerPc(PerPolicy::OncePerVersion(
5511            OncePerVersionLiteral::OncePerVersion,
5512        ));
5513        assert_eq!(w.to_string(), "per_pc once_per_version");
5514        // serde round-trips through the ergonomic bare string.
5515        let json = serde_json::to_value(&w).unwrap();
5516        assert_eq!(json, serde_json::json!({ "per_pc": "once_per_version" }));
5517    }
5518
5519    #[test]
5520    fn once_per_version_rejects_typo() {
5521        // The distinct literal still catches typos (no free-form String).
5522        let r: Result<Schedule, _> = serde_yaml::from_str(&once_per_version_yaml(
5523            "backend",
5524            "per_pc: once_per_verison",
5525        ));
5526        assert!(r.is_err(), "typo should not parse");
5527    }
5528
5529    #[test]
5530    fn validate_accepts_once_per_version_on_backend() {
5531        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5532            "backend",
5533            "per_pc: once_per_version",
5534        ))
5535        .expect("parse");
5536        assert!(s.validate().is_ok(), "got: {:?}", s.validate());
5537    }
5538
5539    #[test]
5540    fn validate_rejects_once_per_version_on_agent() {
5541        let s: Schedule =
5542            serde_yaml::from_str(&once_per_version_yaml("agent", "per_pc: once_per_version"))
5543                .expect("parse");
5544        let err = s
5545            .validate()
5546            .expect_err("agent + once_per_version must be rejected");
5547        assert!(err.contains("once_per_version"), "got: {err}");
5548        assert!(err.contains("backend"), "got: {err}");
5549    }
5550
5551    #[test]
5552    fn validate_rejects_once_per_version_on_per_target() {
5553        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5554            "backend",
5555            "per_target: once_per_version",
5556        ))
5557        .expect("parse");
5558        let err = s
5559            .validate()
5560            .expect_err("per_target + once_per_version must be rejected");
5561        assert!(err.contains("once_per_version"), "got: {err}");
5562        assert!(err.contains("per_pc"), "got: {err}");
5563    }
5564
5565    #[test]
5566    fn schedule_tags_default_empty_and_skip_serialise() {
5567        let yaml = r#"
5568id: x
5569when:
5570  per_pc: once
5571job_id: y
5572target: { all: true }
5573"#;
5574        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5575        assert!(s.tags.is_empty());
5576        s.validate().expect("tag-less schedule validates");
5577        let json = serde_json::to_string(&s).expect("serialize");
5578        assert!(
5579            !json.contains("tags"),
5580            "empty tags must not serialise: {json}"
5581        );
5582    }
5583
5584    #[test]
5585    fn schedule_parses_and_validates_tags() {
5586        let yaml = r#"
5587id: weekly-cleanup
5588when:
5589  per_pc: { every: 1h }
5590job_id: cleanup
5591target: { all: true }
5592tags: [weekly, maintenance]
5593"#;
5594        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5595        assert_eq!(s.tags, vec!["weekly", "maintenance"]);
5596        s.validate().expect("tagged schedule validates");
5597    }
5598
5599    #[test]
5600    fn schedule_rejects_blank_tag() {
5601        let yaml = r#"
5602id: x
5603when:
5604  per_pc: once
5605job_id: y
5606target: { all: true }
5607tags: [ok, "  "]
5608"#;
5609        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5610        let err = s.validate().expect_err("blank tag must fail");
5611        assert!(err.contains("tags must not contain empty"), "err: {err}");
5612    }
5613
5614    // ---- `when` parsing (#418 Phase 1) ----
5615
5616    fn schedule_yaml_with(when_block: &str) -> String {
5617        format!(
5618            r#"
5619id: x
5620when:
5621{when_block}
5622job_id: y
5623target: {{ all: true }}
5624"#
5625        )
5626    }
5627
5628    #[test]
5629    fn when_per_pc_every_parses_unquoted_humantime() {
5630        // `6h` is digit-led but non-numeric → YAML string, same as
5631        // the old `cooldown: 6h` convention. No quotes needed.
5632        let s: Schedule =
5633            serde_yaml::from_str(&schedule_yaml_with("  per_pc: { every: 6h }")).expect("parse");
5634        assert_eq!(
5635            s.when,
5636            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() }))
5637        );
5638    }
5639
5640    #[test]
5641    fn when_per_target_every_parses() {
5642        let s: Schedule = serde_yaml::from_str(&schedule_yaml_with("  per_target: { every: 24h }"))
5643            .expect("parse");
5644        assert_eq!(
5645            s.when,
5646            When::PerTarget(PerPolicy::Every(EverySpec {
5647                every: "24h".into()
5648            }))
5649        );
5650    }
5651
5652    #[test]
5653    fn when_per_target_once_parses() {
5654        // Falls out of the shared PerPolicy shape and decide_fire
5655        // already implements it ("any one pc succeeds → skip the
5656        // target forever"), so it is allowed, not rejected.
5657        let s: Schedule =
5658            serde_yaml::from_str(&schedule_yaml_with("  per_target: once")).expect("parse");
5659        assert_eq!(s.when, When::PerTarget(PerPolicy::Once(OnceLiteral::Once)));
5660    }
5661
5662    #[test]
5663    fn when_calendar_time_parses() {
5664        let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(
5665            "  calendar:\n    at: \"09:00\"\n    days: [mon-fri]",
5666        ))
5667        .expect("parse");
5668        match &s.when {
5669            When::Calendar(c) => {
5670                assert_eq!(c.at, "09:00");
5671                assert_eq!(c.days, vec!["mon-fri"]);
5672            }
5673            other => panic!("expected calendar, got {other:?}"),
5674        }
5675    }
5676
5677    #[test]
5678    fn when_calendar_days_default_empty() {
5679        let s: Schedule =
5680            serde_yaml::from_str(&schedule_yaml_with("  calendar:\n    at: \"09:00\""))
5681                .expect("parse");
5682        match &s.when {
5683            When::Calendar(c) => assert!(c.days.is_empty(), "days defaults to empty (= daily)"),
5684            other => panic!("expected calendar, got {other:?}"),
5685        }
5686    }
5687
5688    #[test]
5689    fn when_calendar_datetime_parses_all_separators() {
5690        // one-shot: date+time in hyphen / ISO-T / slash forms
5691        for at in ["2026-06-10 09:00", "2026-06-10T09:00", "2026/06/10 09:00"] {
5692            let block = format!("  calendar:\n    at: \"{at}\"");
5693            let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(&block))
5694                .unwrap_or_else(|e| panic!("parse '{at}': {e}"));
5695            match &s.when {
5696                When::Calendar(c) => {
5697                    use chrono::Datelike;
5698                    let p = c.parse_at().expect("parse_at");
5699                    let d = p.date.expect("datetime at carries a date");
5700                    assert_eq!((d.year(), d.month(), d.day()), (2026, 6, 10), "for '{at}'");
5701                }
5702                other => panic!("expected calendar, got {other:?}"),
5703            }
5704        }
5705    }
5706
5707    #[test]
5708    fn when_rejects_bad_once_keyword() {
5709        // `onec` must be a parse error, not a silently-absorbed
5710        // string (OnceLiteral is a single-variant enum for exactly
5711        // this reason).
5712        let r: Result<Schedule, _> = serde_yaml::from_str(&schedule_yaml_with("  per_pc: onec"));
5713        assert!(r.is_err(), "expected parse error, got {r:?}");
5714    }
5715
5716    #[test]
5717    fn when_rejects_unknown_key_in_every() {
5718        // `{ evry: 6h }` still fails on the tolerant read path: the
5719        // required `every` key is missing, so no PerPolicy variant
5720        // matches (#492 removed deny_unknown_fields, but required
5721        // keys keep the untagged disambiguation honest).
5722        let r: Result<Schedule, _> =
5723            serde_yaml::from_str(&schedule_yaml_with("  per_pc: { evry: 6h }"));
5724        assert!(r.is_err(), "expected parse error, got {r:?}");
5725    }
5726
5727    #[test]
5728    fn when_rejects_unknown_variant() {
5729        let r: Result<Schedule, _> =
5730            serde_yaml::from_str(&schedule_yaml_with("  per_galaxy: once"));
5731        assert!(r.is_err(), "expected parse error, got {r:?}");
5732    }
5733
5734    #[test]
5735    fn when_rejects_old_top_level_cron_field() {
5736        // Pre-#418 shape: top-level `cron:` + no `when:`. Must fail
5737        // loudly (missing `when`), which is what turns stale KV
5738        // blobs into warn-skips after the upgrade.
5739        let yaml = r#"
5740id: x
5741cron: "* * * * * *"
5742job_id: y
5743target: { all: true }
5744"#;
5745        let r: Result<Schedule, _> = serde_yaml::from_str(yaml);
5746        assert!(r.is_err(), "expected parse error, got {r:?}");
5747    }
5748
5749    #[test]
5750    fn when_rejects_retired_cron_escape_hatch() {
5751        // #418 Phase 2 retired `when: { cron: "..." }`. A raw cron
5752        // is now an unknown variant → parse error (operators use the
5753        // calendar form instead).
5754        let r: Result<Schedule, _> =
5755            serde_yaml::from_str(&schedule_yaml_with("  cron: \"0 0 9 * * mon-fri\""));
5756        assert!(
5757            r.is_err(),
5758            "expected parse error for retired cron, got {r:?}"
5759        );
5760    }
5761
5762    #[test]
5763    fn when_round_trips_json_and_yaml() {
5764        // Round-trip through the full Schedule: that is the wire
5765        // unit for both stores (JSON catalog KV + YAML mirror), and
5766        // it exercises the singleton_map field attribute that keeps
5767        // serde_yaml on the map shape instead of `!per_pc` tags.
5768        for when in [
5769            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5770            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5771            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5772            When::PerTarget(PerPolicy::Every(EverySpec {
5773                every: "24h".into(),
5774            })),
5775            calendar("09:00", &["mon-fri"]),
5776            calendar("2026-06-10 09:00", &[]),
5777            When::On(vec![OnTrigger::Startup]),
5778            When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
5779            When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
5780            When::On(vec![OnTrigger::NetworkChange]),
5781        ] {
5782            // Event triggers are agent-only; the rest validate on backend.
5783            let runs_on = if matches!(when, When::On(_)) {
5784                RunsOn::Agent
5785            } else {
5786                RunsOn::Backend
5787            };
5788            let s = schedule_with(when.clone(), runs_on);
5789
5790            let json = serde_json::to_string(&s).expect("json serialise");
5791            let back: Schedule = serde_json::from_str(&json).expect("json deserialise");
5792            assert_eq!(back.when, when, "json round-trip for {when}");
5793
5794            let yaml = serde_yaml::to_string(&s).expect("yaml serialise");
5795            assert!(
5796                !yaml.contains('!'),
5797                "yaml must use the map shape, not tags: {yaml}"
5798            );
5799            let back: Schedule = serde_yaml::from_str(&yaml).expect("yaml deserialise");
5800            assert_eq!(back.when, when, "yaml round-trip for {when}");
5801        }
5802    }
5803
5804    #[test]
5805    fn when_once_serialises_as_bare_keyword() {
5806        // The wire shape operators see in the YAML mirror must stay
5807        // the ergonomic `per_pc: once`, not a one-variant map.
5808        let json = serde_json::to_value(When::PerPc(PerPolicy::Once(OnceLiteral::Once)))
5809            .expect("serialise");
5810        assert_eq!(json, serde_json::json!({ "per_pc": "once" }));
5811    }
5812
5813    #[test]
5814    fn when_displays_operator_summary() {
5815        for (when, expected) in [
5816            (
5817                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5818                "per_pc once",
5819            ),
5820            (
5821                When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5822                "per_pc every 6h",
5823            ),
5824            (
5825                When::PerTarget(PerPolicy::Every(EverySpec {
5826                    every: "24h".into(),
5827                })),
5828                "per_target every 24h",
5829            ),
5830            (calendar("09:00", &["mon-fri"]), "at 09:00 [mon-fri]"),
5831            (calendar("2026-06-10 09:00", &[]), "at 2026-06-10 09:00"),
5832            (When::On(vec![OnTrigger::Startup]), "on [startup]"),
5833            (
5834                When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
5835                "on [startup,logon]",
5836            ),
5837            (
5838                When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
5839                "on [lock,unlock]",
5840            ),
5841            (
5842                When::On(vec![OnTrigger::NetworkChange]),
5843                "on [network_change]",
5844            ),
5845        ] {
5846            assert_eq!(when.to_string(), expected);
5847        }
5848    }
5849
5850    // ---- lowering (#418: when → engine vocabulary) ----
5851
5852    fn schedule_with(when: When, runs_on: RunsOn) -> Schedule {
5853        Schedule {
5854            id: "x".into(),
5855            when,
5856            job_id: "y".into(),
5857            // #917: validate() now rejects a target that dispatches
5858            // nothing, so the baseline helper carries the simplest
5859            // specified target.
5860            plan: FanoutPlan {
5861                target: Target {
5862                    all: true,
5863                    ..Target::default()
5864                },
5865                ..FanoutPlan::default()
5866            },
5867            active: Active::default(),
5868            constraints: Constraints::default(),
5869            on_failure: OnFailure::default(),
5870            tz: ScheduleTz::default(),
5871            starting_deadline: None,
5872            runs_on,
5873            enabled: true,
5874            tags: Vec::new(),
5875            origin: None,
5876        }
5877    }
5878
5879    fn calendar(at: &str, days: &[&str]) -> When {
5880        When::Calendar(CalendarSpec {
5881            at: at.into(),
5882            days: days.iter().map(|d| (*d).to_string()).collect(),
5883        })
5884    }
5885
5886    #[test]
5887    fn next_calendar_fire_returns_next_utc_occurrence() {
5888        use chrono::TimeZone;
5889        // Daily 09:00, evaluated in UTC. From 08:00 the same day, the
5890        // next strict occurrence is 09:00 that day.
5891        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5892        s.tz = ScheduleTz::Utc;
5893        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 8, 0, 0).unwrap();
5894        let next = s.next_calendar_fire(now).expect("calendar has a next fire");
5895        assert_eq!(
5896            next,
5897            chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap()
5898        );
5899    }
5900
5901    #[test]
5902    fn next_calendar_fire_is_strictly_after_now() {
5903        use chrono::TimeZone;
5904        // Standing exactly on a fire instant must preview the *next*
5905        // one (inclusive = false), not the one firing right now.
5906        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5907        s.tz = ScheduleTz::Utc;
5908        let on_fire = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap();
5909        let next = s
5910            .next_calendar_fire(on_fire)
5911            .expect("calendar has a next fire");
5912        assert_eq!(
5913            next,
5914            chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()
5915        );
5916    }
5917
5918    #[test]
5919    fn next_calendar_fire_none_for_reconcile_shapes() {
5920        // `per_pc` / `per_target` lower to the every-minute poll cron —
5921        // no discrete upcoming event to preview, so `None`.
5922        let now = chrono::Utc::now();
5923        for when in [
5924            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5925            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5926            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5927            When::PerTarget(PerPolicy::Every(EverySpec {
5928                every: "24h".into(),
5929            })),
5930        ] {
5931            let s = schedule_with(when, RunsOn::Backend);
5932            assert!(
5933                s.next_calendar_fire(now).is_none(),
5934                "reconcile shapes have no calendar fire",
5935            );
5936        }
5937    }
5938
5939    // ---- preview_fires (#418 dry-run / preview) ----
5940
5941    fn cal_utc(at: &str, days: &[&str]) -> Schedule {
5942        let mut s = schedule_with(calendar(at, days), RunsOn::Backend);
5943        s.tz = ScheduleTz::Utc; // host-independent assertions
5944        s
5945    }
5946
5947    #[test]
5948    fn preview_lists_next_calendar_occurrences() {
5949        use chrono::TimeZone;
5950        // Weekday 09:00, from Wed 2026-06-10 00:00 UTC: the next five
5951        // fires skip the weekend (Sat 13 / Sun 14).
5952        let s = cal_utc("09:00", &["mon-fri"]);
5953        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5954        let got = s.preview_fires(now, 5);
5955        let want: Vec<_> = [
5956            (2026, 6, 10), // Wed
5957            (2026, 6, 11), // Thu
5958            (2026, 6, 12), // Fri
5959            (2026, 6, 15), // Mon (skips Sat 13 / Sun 14)
5960            (2026, 6, 16), // Tue
5961        ]
5962        .iter()
5963        .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
5964        .collect();
5965        assert_eq!(got, want);
5966    }
5967
5968    #[test]
5969    fn preview_handles_nth_and_last_weekday() {
5970        use chrono::TimeZone;
5971        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
5972        // 2nd Tuesday (Patch Tuesday): Jun 9, Jul 14 2026.
5973        let nth = cal_utc("09:00", &["tue#2"]).preview_fires(now, 2);
5974        assert_eq!(
5975            nth,
5976            vec![
5977                chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap(),
5978                chrono::Utc.with_ymd_and_hms(2026, 7, 14, 9, 0, 0).unwrap(),
5979            ]
5980        );
5981        // Last Friday of the month: Jun 26, Jul 31 2026.
5982        let last = cal_utc("22:00", &["friL"]).preview_fires(now, 2);
5983        assert_eq!(
5984            last,
5985            vec![
5986                chrono::Utc.with_ymd_and_hms(2026, 6, 26, 22, 0, 0).unwrap(),
5987                chrono::Utc.with_ymd_and_hms(2026, 7, 31, 22, 0, 0).unwrap(),
5988            ]
5989        );
5990    }
5991
5992    #[test]
5993    fn preview_is_empty_for_reconcile_and_zero_count() {
5994        let now = chrono::Utc::now();
5995        // reconcile shapes have no discrete fire times
5996        let recon = schedule_with(
5997            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5998            RunsOn::Backend,
5999        );
6000        assert!(recon.preview_fires(now, 5).is_empty());
6001        // count == 0 yields nothing even for a calendar
6002        assert!(cal_utc("09:00", &[]).preview_fires(now, 0).is_empty());
6003    }
6004
6005    #[test]
6006    fn preview_skips_outside_active_window() {
6007        use chrono::TimeZone;
6008        // Daily 09:00, active only [2026-06-15, 2026-06-17). Occurrences
6009        // before `from` are skipped; `until` is exclusive, so 06-17's
6010        // fire is out — leaving exactly the 15th and 16th.
6011        let mut s = cal_utc("09:00", &[]);
6012        s.active = Active {
6013            from: Some("2026-06-15".into()),
6014            until: Some("2026-06-17".into()),
6015        };
6016        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
6017        let got = s.preview_fires(now, 5);
6018        assert_eq!(
6019            got,
6020            vec![
6021                chrono::Utc.with_ymd_and_hms(2026, 6, 15, 9, 0, 0).unwrap(),
6022                chrono::Utc.with_ymd_and_hms(2026, 6, 16, 9, 0, 0).unwrap(),
6023            ]
6024        );
6025    }
6026
6027    #[test]
6028    fn preview_empty_when_calendar_time_outside_window() {
6029        use chrono::TimeZone;
6030        // Fires at 09:00 but the maintenance window is overnight — it can
6031        // never run, so the preview is empty (matches
6032        // `calendar_outside_window`), and the scan still terminates.
6033        let mut s = cal_utc("09:00", &[]);
6034        s.constraints = Constraints {
6035            window: Some("22:00-05:00".into()),
6036            ..Constraints::default()
6037        };
6038        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
6039        assert!(s.preview_fires(now, 5).is_empty());
6040        // Every candidate tick is rejected, so this also exercises the
6041        // SCAN_CAP bound: a large `count` must still terminate (and
6042        // return empty) rather than spin (claude #578 review).
6043        assert!(s.preview_fires(now, 50).is_empty());
6044    }
6045
6046    #[test]
6047    fn preview_past_one_shot_is_empty() {
6048        use chrono::TimeZone;
6049        // A dated one-shot whose instant has passed never fires again.
6050        let s = cal_utc("2026-06-10 09:00", &[]);
6051        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 0, 0, 0).unwrap();
6052        assert!(s.preview_fires(now, 5).is_empty());
6053        // …but from before it, the single future fire shows up.
6054        let before = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
6055        assert_eq!(
6056            s.preview_fires(before, 5),
6057            vec![chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()]
6058        );
6059    }
6060
6061    #[test]
6062    fn lowering_matches_the_418_table() {
6063        let cases = [
6064            (
6065                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6066                (POLL_CRON, ExecMode::OncePerPc, None),
6067            ),
6068            (
6069                When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6070                (POLL_CRON, ExecMode::OncePerPc, Some("6h")),
6071            ),
6072            (
6073                When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
6074                (POLL_CRON, ExecMode::OncePerTarget, None),
6075            ),
6076            (
6077                When::PerTarget(PerPolicy::Every(EverySpec {
6078                    every: "24h".into(),
6079                })),
6080                (POLL_CRON, ExecMode::OncePerTarget, Some("24h")),
6081            ),
6082            // calendar repeating → 6-field cron
6083            (
6084                calendar("09:00", &["mon-fri"]),
6085                ("0 0 9 * * mon-fri", ExecMode::EveryTick, None),
6086            ),
6087            // calendar daily (no days) → DOW *
6088            (
6089                calendar("18:30", &[]),
6090                ("0 30 18 * * *", ExecMode::EveryTick, None),
6091            ),
6092            // calendar one-shot → 7-field year cron
6093            (
6094                calendar("2026-06-10 09:00", &[]),
6095                ("0 0 9 10 6 * 2026", ExecMode::EveryTick, None),
6096            ),
6097        ];
6098        for (when, (cron, mode, cooldown)) in cases {
6099            let l = schedule_with(when.clone(), RunsOn::Backend).lowered();
6100            assert_eq!(l.cron, cron, "cron for {when}");
6101            assert_eq!(l.mode, mode, "mode for {when}");
6102            assert_eq!(l.cooldown.as_deref(), cooldown, "cooldown for {when}");
6103        }
6104    }
6105
6106    #[test]
6107    fn lowered_carries_schedule_tz() {
6108        for (tz, want) in [
6109            (ScheduleTz::Local, ScheduleTz::Local),
6110            (ScheduleTz::Utc, ScheduleTz::Utc),
6111        ] {
6112            let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
6113            s.tz = tz;
6114            assert_eq!(s.lowered().tz, want, "calendar carries tz");
6115            // reconcile shapes carry tz too (for the active-window check)
6116            let mut s = schedule_with(
6117                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6118                RunsOn::Backend,
6119            );
6120            s.tz = tz;
6121            assert_eq!(s.lowered().tz, want, "reconcile carries tz");
6122        }
6123    }
6124
6125    #[test]
6126    fn poll_cron_is_accepted_by_the_engine_parser() {
6127        // POLL_CRON is system-generated — if the engine's parser
6128        // ever rejected it every reconcile schedule would die at
6129        // register time. Validate it with the same croner config
6130        // (Seconds::Required, dom_and_dow, year optional).
6131        croner::parser::CronParser::builder()
6132            .seconds(croner::parser::Seconds::Required)
6133            .dom_and_dow(true)
6134            .build()
6135            .parse(POLL_CRON)
6136            .expect("POLL_CRON must parse");
6137    }
6138
6139    // ---- Schedule::validate() (#418 decision F) ----
6140
6141    #[test]
6142    fn validate_accepts_reconcile_shapes() {
6143        for when in [
6144            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6145            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6146            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
6147            When::PerTarget(PerPolicy::Every(EverySpec {
6148                every: "24h".into(),
6149            })),
6150        ] {
6151            schedule_with(when.clone(), RunsOn::Backend)
6152                .validate()
6153                .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
6154        }
6155    }
6156
6157    #[test]
6158    fn validate_accepts_per_pc_on_agent() {
6159        schedule_with(
6160            When::PerPc(PerPolicy::Every(EverySpec { every: "1h".into() })),
6161            RunsOn::Agent,
6162        )
6163        .validate()
6164        .expect("per_pc + agent is the offline-inventory shape");
6165    }
6166
6167    // ---- #418 event triggers (when: { on }) ----
6168
6169    #[test]
6170    fn validate_accepts_event_on_agent() {
6171        for triggers in [
6172            vec![OnTrigger::Startup],
6173            vec![OnTrigger::Logon],
6174            vec![OnTrigger::Lock],
6175            vec![OnTrigger::Unlock],
6176            vec![OnTrigger::NetworkChange],
6177            vec![
6178                OnTrigger::Startup,
6179                OnTrigger::Logon,
6180                OnTrigger::Lock,
6181                OnTrigger::Unlock,
6182                OnTrigger::NetworkChange,
6183            ],
6184        ] {
6185            schedule_with(When::On(triggers), RunsOn::Agent)
6186                .validate()
6187                .expect("when.on is valid on runs_on: agent");
6188        }
6189    }
6190
6191    #[test]
6192    fn validate_rejects_event_on_backend() {
6193        let err = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Backend)
6194            .validate()
6195            .unwrap_err();
6196        assert!(err.contains("when.on"), "got: {err}");
6197        assert!(err.contains("runs_on: agent"), "got: {err}");
6198    }
6199
6200    #[test]
6201    fn validate_rejects_empty_event_list() {
6202        let err = schedule_with(When::On(vec![]), RunsOn::Agent)
6203            .validate()
6204            .unwrap_err();
6205        assert!(err.contains("when.on"), "got: {err}");
6206        assert!(err.contains("at least one"), "got: {err}");
6207    }
6208
6209    #[test]
6210    fn event_schedule_lowers_to_event_mode_and_is_event() {
6211        let s = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Agent);
6212        assert!(s.is_event());
6213        assert_eq!(s.lowered().mode, ExecMode::Event);
6214        assert_eq!(s.event_triggers(), &[OnTrigger::Startup]);
6215        // non-event schedules report no triggers.
6216        let cal = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
6217        assert!(!cal.is_event());
6218        assert!(cal.event_triggers().is_empty());
6219    }
6220
6221    // ---- #418 constraints.require (env gates) ----
6222
6223    fn require_schedule(req: Require, runs_on: RunsOn) -> Schedule {
6224        let mut s = schedule_with(
6225            When::PerPc(PerPolicy::Every(EverySpec { every: "1m".into() })),
6226            runs_on,
6227        );
6228        s.constraints.require = Some(req);
6229        s
6230    }
6231
6232    #[test]
6233    fn require_met_combinations() {
6234        use std::time::Duration;
6235        let idle = |m: u64| Some(Duration::from_secs(m * 60));
6236        // Builder for the sensed state: (ac, idle, cpu, network).
6237        let env = |ac, idle, cpu, net| EnvState {
6238            ac_online: ac,
6239            idle,
6240            cpu_pct: cpu,
6241            network_up: net,
6242        };
6243        // Empty require — always met regardless of sensed state.
6244        assert!(require_met(
6245            &Require::default(),
6246            &env(false, None, None, false)
6247        ));
6248        // ac_power: only on AC.
6249        let ac = Require {
6250            ac_power: true,
6251            ..Default::default()
6252        };
6253        assert!(!require_met(&ac, &env(false, None, None, true)));
6254        assert!(require_met(&ac, &env(true, None, None, false)));
6255        // idle: needs >= the configured min; None idle never satisfies.
6256        let idle10 = Require {
6257            idle: Some("10m".into()),
6258            ..Default::default()
6259        };
6260        assert!(!require_met(&idle10, &env(true, None, None, true)));
6261        assert!(!require_met(&idle10, &env(true, idle(5), None, true)));
6262        assert!(require_met(&idle10, &env(true, idle(15), None, true)));
6263        assert!(require_met(&idle10, &env(true, idle(10), None, true))); // boundary inclusive
6264        // cpu_below: needs CPU strictly < threshold; None cpu never satisfies.
6265        let cpu20 = Require {
6266            cpu_below: Some(20.0),
6267            ..Default::default()
6268        };
6269        assert!(!require_met(&cpu20, &env(true, None, None, true))); // no sample → fail-closed
6270        assert!(!require_met(&cpu20, &env(true, None, Some(20.0), true))); // == threshold
6271        assert!(!require_met(&cpu20, &env(true, None, Some(55.0), true))); // busy
6272        assert!(require_met(&cpu20, &env(true, None, Some(5.0), true))); // quiet
6273        // network: only when online.
6274        let net = Require {
6275            network: true,
6276            ..Default::default()
6277        };
6278        assert!(!require_met(&net, &env(true, None, None, false))); // offline
6279        assert!(require_met(&net, &env(true, None, None, true))); // online
6280        // all four: AND.
6281        let all = Require {
6282            ac_power: true,
6283            idle: Some("10m".into()),
6284            cpu_below: Some(20.0),
6285            network: true,
6286        };
6287        assert!(!require_met(&all, &env(false, idle(20), Some(5.0), true))); // on battery
6288        assert!(!require_met(&all, &env(true, idle(1), Some(5.0), true))); // not idle enough
6289        assert!(!require_met(&all, &env(true, idle(20), Some(50.0), true))); // busy
6290        assert!(!require_met(&all, &env(true, idle(20), Some(5.0), false))); // offline
6291        assert!(require_met(&all, &env(true, idle(20), Some(5.0), true)));
6292        // An unparseable idle is treated as no-requirement by require_met
6293        // (validate rejects it at create time, so this only guards a
6294        // hand-edited blob): ac still gates.
6295        let bad = Require {
6296            ac_power: true,
6297            idle: Some("garbage".into()),
6298            ..Default::default()
6299        };
6300        assert!(require_met(&bad, &env(true, None, None, true)));
6301        assert!(!require_met(&bad, &env(false, None, None, true)));
6302    }
6303
6304    #[test]
6305    fn validate_accepts_and_rejects_cpu_below() {
6306        // In-range accepted.
6307        require_schedule(
6308            Require {
6309                cpu_below: Some(20.0),
6310                ..Default::default()
6311            },
6312            RunsOn::Agent,
6313        )
6314        .validate()
6315        .expect("cpu_below 20 is valid");
6316        // Upper boundary: 100.0 is accepted (fires unless CPU is exactly
6317        // 100%). Pins the inclusive upper bound against a future c < 100.0.
6318        require_schedule(
6319            Require {
6320                cpu_below: Some(100.0),
6321                ..Default::default()
6322            },
6323            RunsOn::Agent,
6324        )
6325        .validate()
6326        .expect("cpu_below 100 is valid");
6327        // Out of range rejected (0 and >100).
6328        for bad in [0.0, -5.0, 100.1] {
6329            let err = require_schedule(
6330                Require {
6331                    cpu_below: Some(bad),
6332                    ..Default::default()
6333                },
6334                RunsOn::Agent,
6335            )
6336            .validate()
6337            .unwrap_err();
6338            assert!(
6339                err.contains("constraints.require.cpu_below"),
6340                "cpu_below {bad}: {err}"
6341            );
6342        }
6343    }
6344
6345    #[test]
6346    fn validate_accepts_require_on_agent() {
6347        require_schedule(
6348            Require {
6349                ac_power: true,
6350                idle: Some("10m".into()),
6351                cpu_below: Some(20.0),
6352                network: true,
6353            },
6354            RunsOn::Agent,
6355        )
6356        .validate()
6357        .expect("constraints.require is valid on runs_on: agent");
6358    }
6359
6360    #[test]
6361    fn validate_rejects_require_on_backend() {
6362        let err = require_schedule(
6363            Require {
6364                ac_power: true,
6365                ..Default::default()
6366            },
6367            RunsOn::Backend,
6368        )
6369        .validate()
6370        .unwrap_err();
6371        assert!(err.contains("constraints.require"), "got: {err}");
6372        assert!(err.contains("runs_on: agent"), "got: {err}");
6373
6374        // An idle-only require (ac_power: false) is also non-empty
6375        // (is_empty folds the fields) and must reject on backend too —
6376        // guards against a regression in Require::is_empty.
6377        let err = require_schedule(
6378            Require {
6379                idle: Some("10m".into()),
6380                ..Default::default()
6381            },
6382            RunsOn::Backend,
6383        )
6384        .validate()
6385        .unwrap_err();
6386        assert!(
6387            err.contains("constraints.require"),
6388            "idle-only on backend: {err}"
6389        );
6390    }
6391
6392    #[test]
6393    fn validate_rejects_bad_require_idle() {
6394        let err = require_schedule(
6395            Require {
6396                idle: Some("not-a-duration".into()),
6397                ..Default::default()
6398            },
6399            RunsOn::Agent,
6400        )
6401        .validate()
6402        .unwrap_err();
6403        assert!(err.contains("constraints.require.idle"), "got: {err}");
6404    }
6405
6406    #[test]
6407    fn require_round_trips_and_skips_empty() {
6408        // ac_power: false is skipped; an all-default require nested in
6409        // constraints is omitted (is_empty folds it in).
6410        let yaml = "id: s\nwhen: { per_pc: { every: 1m } }\njob_id: j\nruns_on: agent\n\
6411                    constraints: { require: { ac_power: true, idle: 10m, cpu_below: 20, \
6412                    network: true } }\n";
6413        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6414        let req = s.constraints.require.as_ref().expect("require present");
6415        assert!(req.ac_power);
6416        assert_eq!(req.idle.as_deref(), Some("10m"));
6417        assert_eq!(req.cpu_below, Some(20.0));
6418        assert!(req.network);
6419        // Re-serialize: idle + cpu_below + network present, ac_power true.
6420        let back = serde_json::to_string(&s.constraints).unwrap();
6421        assert!(back.contains("\"idle\":\"10m\""), "got: {back}");
6422        assert!(back.contains("\"cpu_below\":20"), "got: {back}");
6423        assert!(back.contains("\"network\":true"), "got: {back}");
6424        // An empty require is omitted entirely by is_empty.
6425        let mut empty = s.clone();
6426        empty.constraints.require = Some(Require::default());
6427        assert!(empty.constraints.is_empty());
6428    }
6429
6430    #[test]
6431    fn validate_rejects_per_target_on_agent() {
6432        let err = schedule_with(
6433            When::PerTarget(PerPolicy::Every(EverySpec {
6434                every: "24h".into(),
6435            })),
6436            RunsOn::Agent,
6437        )
6438        .validate()
6439        .unwrap_err();
6440        assert!(err.contains("per_target"), "got: {err}");
6441        assert!(err.contains("runs_on: agent"), "got: {err}");
6442
6443        // per_target: once is also backend-only.
6444        let err = schedule_with(
6445            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
6446            RunsOn::Agent,
6447        )
6448        .validate()
6449        .unwrap_err();
6450        assert!(err.contains("per_target"), "got (once): {err}");
6451        assert!(err.contains("runs_on: agent"), "got (once): {err}");
6452    }
6453
6454    #[test]
6455    fn validate_rejects_bad_every_duration() {
6456        let err = schedule_with(
6457            When::PerPc(PerPolicy::Every(EverySpec { every: "6x".into() })),
6458            RunsOn::Backend,
6459        )
6460        .validate()
6461        .unwrap_err();
6462        assert!(err.contains("when.every"), "got: {err}");
6463    }
6464
6465    #[test]
6466    fn validate_rejects_bad_jitter_and_starting_deadline() {
6467        let mut s = schedule_with(
6468            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6469            RunsOn::Backend,
6470        );
6471        s.plan.jitter = Some("5x".into());
6472        let err = s.validate().unwrap_err();
6473        assert!(err.contains("jitter"), "got: {err}");
6474
6475        let mut s = schedule_with(
6476            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6477            RunsOn::Backend,
6478        );
6479        s.starting_deadline = Some("soon".into());
6480        let err = s.validate().unwrap_err();
6481        assert!(err.contains("starting_deadline"), "got: {err}");
6482    }
6483
6484    #[test]
6485    fn validate_rejects_unspecified_target() {
6486        // #917 (1): an all-default target never dispatches anywhere —
6487        // runs_on: agent silently never fires, runs_on: backend
6488        // warn-fails every tick at the exec boundary. Both rejected.
6489        for runs_on in [RunsOn::Backend, RunsOn::Agent] {
6490            let mut s = schedule_with(When::PerPc(PerPolicy::Once(OnceLiteral::Once)), runs_on);
6491            s.plan.target = Target::default();
6492            let err = s.validate().unwrap_err();
6493            assert!(err.contains("target"), "for {runs_on:?}, got: {err}");
6494        }
6495    }
6496
6497    /// A Schedule with every top-level field populated so each one
6498    /// actually serialises (the optional ones are `skip_serializing_if`).
6499    fn fully_populated_schedule() -> Schedule {
6500        let mut s = schedule_with(
6501            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6502            RunsOn::Backend,
6503        );
6504        s.plan.rollout = Some(Rollout {
6505            strategy: RolloutStrategy::Wave,
6506            waves: vec![Wave {
6507                group: "canary".into(),
6508                delay: "0s".into(),
6509            }],
6510        });
6511        s.plan.jitter = Some("5m".into());
6512        s.plan.deadline_at = Some(chrono::Utc::now());
6513        s.active = Active {
6514            from: Some("2026-01-01 00:00".into()),
6515            until: Some("2026-12-31 00:00".into()),
6516        };
6517        s.constraints = Constraints {
6518            window: Some("09:00-17:00".into()),
6519            ..Constraints::default()
6520        };
6521        s.on_failure = OnFailure {
6522            retry: Some(Retry {
6523                max: 1,
6524                backoff: "10s".into(),
6525            }),
6526        };
6527        s.starting_deadline = Some("30m".into());
6528        s.tags = vec!["health".into()];
6529        s.origin = Some(RepoOrigin {
6530            path: "configs/schedules/x.yaml".into(),
6531            repo: None,
6532            script_file: None,
6533        });
6534        s
6535    }
6536
6537    #[test]
6538    fn schedule_top_level_keys_cover_serialized_fields() {
6539        // #924 drift guard: the hand-maintained TOP_LEVEL_KEYS list must
6540        // match exactly what a fully-populated Schedule serialises — so a
6541        // future field added to Schedule or FanoutPlan can't slip past
6542        // the flatten-aware strict guard by being forgotten here.
6543        let s = fully_populated_schedule();
6544        let value = serde_json::to_value(&s).expect("serialize schedule");
6545        let serialized: std::collections::BTreeSet<String> = value
6546            .as_object()
6547            .expect("schedule serialises to an object")
6548            .keys()
6549            .cloned()
6550            .collect();
6551        let listed: std::collections::BTreeSet<String> = Schedule::TOP_LEVEL_KEYS
6552            .iter()
6553            .map(|s| s.to_string())
6554            .collect();
6555        assert_eq!(
6556            serialized, listed,
6557            "TOP_LEVEL_KEYS is out of sync with Schedule's serialized fields \
6558             (flatten-aware strict guard would miss a real field or reject a valid one)"
6559        );
6560    }
6561
6562    #[test]
6563    fn strict_rejects_flatten_hidden_top_level_typo() {
6564        // #924: a top-level typo on a flattening type (jiter / enabledd)
6565        // is buffered into the flatten target by serde and hidden from
6566        // serde_ignored — the top-level guard must catch it. Verified on
6567        // both the YAML and JSON strict boundaries.
6568        let yaml = "\
6569id: s1
6570job_id: j1
6571when:
6572  per_pc: once
6573target:
6574  all: true
6575jiter: 5m
6576";
6577        let err = crate::strict::from_yaml_str::<Schedule>(yaml).unwrap_err();
6578        assert!(err.contains("jiter"), "got: {err}");
6579
6580        let json = serde_json::json!({
6581            "id": "s1",
6582            "job_id": "j1",
6583            "when": { "per_pc": "once" },
6584            "target": { "all": true },
6585            "enabledd": false,
6586        });
6587        let err = crate::strict::from_json_slice::<Schedule>(&serde_json::to_vec(&json).unwrap())
6588            .unwrap_err();
6589        assert!(err.contains("enabledd"), "got: {err}");
6590    }
6591
6592    #[test]
6593    fn strict_accepts_all_valid_schedule_top_level_keys() {
6594        // The guard must not reject any legitimate key — round-trip a
6595        // fully-populated schedule through the strict YAML boundary.
6596        let s = fully_populated_schedule();
6597        let yaml = serde_yaml::to_string(&s).expect("serialize");
6598        crate::strict::from_yaml_str::<Schedule>(&yaml)
6599            .expect("every serialized key must be accepted by the strict guard");
6600    }
6601
6602    #[test]
6603    fn strict_rejects_non_string_top_level_yaml_key() {
6604        // #924 (gemini #945): a YAML key isn't always a string — an
6605        // unquoted `true:` parses as a boolean, `123:` as a number. A
6606        // `filter_map` on `as_str()` would drop these and let them slip
6607        // past the flatten guard; `yaml_key_label` renders them so they
6608        // are still rejected. (serde_yaml is YAML 1.2, so `on:` stays a
6609        // *string* "on" — also rejected, just via the string path.)
6610        let base = "\
6611id: s1
6612job_id: j1
6613when:
6614  per_pc: once
6615target:
6616  all: true
6617";
6618        for (extra, needle) in [
6619            ("true: x\n", "true"),
6620            ("123: x\n", "123"),
6621            ("on: y\n", "on"),
6622        ] {
6623            let yaml = format!("{base}{extra}");
6624            let err = crate::strict::from_yaml_str::<Schedule>(&yaml).unwrap_err();
6625            assert!(err.contains(needle), "for '{extra}', got: {err}");
6626        }
6627    }
6628
6629    #[test]
6630    fn validate_accepts_waves_instead_of_target_on_backend() {
6631        // #917 (1): the exec boundary accepts rollout-only plans
6632        // (target then just labels the audit row) — so does validate.
6633        let mut s = schedule_with(
6634            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6635            RunsOn::Backend,
6636        );
6637        s.plan.target = Target::default();
6638        s.plan.rollout = Some(Rollout {
6639            strategy: RolloutStrategy::Wave,
6640            waves: vec![Wave {
6641                group: "canary".into(),
6642                delay: "0s".into(),
6643            }],
6644        });
6645        s.validate().expect("rollout-only plan should validate");
6646    }
6647
6648    #[test]
6649    fn validate_rejects_rollout_on_agent() {
6650        // #917 (1): rollout waves are backend-published; a runs_on:
6651        // agent schedule never reads them, so the combination is a
6652        // silent no-op — reject like max_concurrent-on-agent.
6653        let mut s = schedule_with(
6654            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6655            RunsOn::Agent,
6656        );
6657        s.plan.rollout = Some(Rollout {
6658            strategy: RolloutStrategy::Wave,
6659            waves: vec![Wave {
6660                group: "canary".into(),
6661                delay: "0s".into(),
6662            }],
6663        });
6664        let err = s.validate().unwrap_err();
6665        assert!(err.contains("rollout"), "got: {err}");
6666    }
6667
6668    #[test]
6669    fn validate_rejects_bad_waves() {
6670        // #917 (2): empty waves, blank group, unparseable delay — all
6671        // previously accepted and failed (or no-opped) at every fire.
6672        let base = || {
6673            schedule_with(
6674                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6675                RunsOn::Backend,
6676            )
6677        };
6678
6679        let mut s = base();
6680        s.plan.rollout = Some(Rollout {
6681            strategy: RolloutStrategy::Wave,
6682            waves: vec![],
6683        });
6684        let err = s.validate().unwrap_err();
6685        assert!(err.contains("at least one wave"), "got: {err}");
6686
6687        let mut s = base();
6688        s.plan.rollout = Some(Rollout {
6689            strategy: RolloutStrategy::Wave,
6690            waves: vec![Wave {
6691                group: "  ".into(),
6692                delay: "0s".into(),
6693            }],
6694        });
6695        let err = s.validate().unwrap_err();
6696        assert!(err.contains("waves[0].group"), "got: {err}");
6697
6698        let mut s = base();
6699        s.plan.rollout = Some(Rollout {
6700            strategy: RolloutStrategy::Wave,
6701            waves: vec![
6702                Wave {
6703                    group: "canary".into(),
6704                    delay: "0s".into(),
6705                },
6706                Wave {
6707                    group: "wave1".into(),
6708                    delay: "5 minuts".into(),
6709                },
6710            ],
6711        });
6712        let err = s.validate().unwrap_err();
6713        assert!(err.contains("waves[1].delay"), "got: {err}");
6714    }
6715
6716    #[test]
6717    fn validate_rejects_wave_delay_at_or_past_starting_deadline() {
6718        // #917 (3): the deadline is stamped once at tick time, so a
6719        // wave sleeping >= starting_deadline publishes already-expired
6720        // Commands — dead on arrival, every fire.
6721        let mut s = schedule_with(
6722            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6723            RunsOn::Backend,
6724        );
6725        s.starting_deadline = Some("30m".into());
6726        s.plan.rollout = Some(Rollout {
6727            strategy: RolloutStrategy::Wave,
6728            waves: vec![
6729                Wave {
6730                    group: "canary".into(),
6731                    delay: "0s".into(),
6732                },
6733                Wave {
6734                    group: "wave1".into(),
6735                    delay: "30m".into(),
6736                },
6737            ],
6738        });
6739        let err = s.validate().unwrap_err();
6740        assert!(
6741            err.contains("waves[1].delay") && err.contains("starting_deadline"),
6742            "got: {err}"
6743        );
6744
6745        // Strictly shorter is fine.
6746        s.plan.rollout.as_mut().unwrap().waves[1].delay = "29m".into();
6747        s.validate().expect("delay < deadline should validate");
6748    }
6749
6750    #[test]
6751    fn validate_rejects_operator_set_deadline_at() {
6752        // #917 (4): machine-stamped field — the scheduler overwrites it
6753        // on every fire, so a hand-set value is silently discarded.
6754        let mut s = schedule_with(
6755            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6756            RunsOn::Backend,
6757        );
6758        s.plan.deadline_at = Some(chrono::Utc::now());
6759        let err = s.validate().unwrap_err();
6760        assert!(
6761            err.contains("deadline_at") && err.contains("starting_deadline"),
6762            "got: {err}"
6763        );
6764    }
6765
6766    #[test]
6767    fn validate_accepts_calendar_shapes() {
6768        for when in [
6769            calendar("09:00", &["mon-fri"]),   // weekday morning
6770            calendar("00:00", &["sun"]),       // weekly
6771            calendar("18:30", &[]),            // daily
6772            calendar("2026-06-10 09:00", &[]), // one-shot
6773            calendar("2026/12/25 00:00", &[]), // one-shot, slash form
6774        ] {
6775            schedule_with(when.clone(), RunsOn::Backend)
6776                .validate()
6777                .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
6778        }
6779    }
6780
6781    #[test]
6782    fn validate_rejects_bad_at() {
6783        for bad in ["25:00", "09:60", "9", "noon", "2026-13-01 09:00"] {
6784            let err = schedule_with(calendar(bad, &[]), RunsOn::Backend)
6785                .validate()
6786                .unwrap_err();
6787            assert!(err.contains("when.at"), "for '{bad}', got: {err}");
6788        }
6789    }
6790
6791    #[test]
6792    fn validate_rejects_datetime_at_with_days() {
6793        // A dated `at` is a one-shot — pairing it with days is a
6794        // contradiction (the date already pins the day).
6795        let err = schedule_with(calendar("2026-06-10 09:00", &["mon"]), RunsOn::Backend)
6796            .validate()
6797            .unwrap_err();
6798        assert!(
6799            err.contains("one-shot") && err.contains("days"),
6800            "got: {err}"
6801        );
6802    }
6803
6804    #[test]
6805    fn validate_rejects_bad_day_name() {
6806        // A garbage DOW token is caught by the days pre-flight and
6807        // reported against `when.days`, not the confusing
6808        // "when.at lowered to invalid cron" (claude #432 review).
6809        let err = schedule_with(calendar("09:00", &["funday"]), RunsOn::Backend)
6810            .validate()
6811            .unwrap_err();
6812        assert!(err.contains("when.days"), "got: {err}");
6813        assert!(err.contains("funday"), "names the bad token: {err}");
6814        // a degenerate range like `mon-` reports the whole token, not
6815        // a cryptic empty part (claude #432 follow-up)
6816        let err = schedule_with(calendar("09:00", &["mon-"]), RunsOn::Backend)
6817            .validate()
6818            .unwrap_err();
6819        assert!(err.contains("'mon-'"), "names the whole token: {err}");
6820        // valid names / ranges / numeric / * all pass
6821        for ok in [
6822            calendar("09:00", &["mon-fri"]),
6823            calendar("09:00", &["mon", "wed", "sun"]),
6824            calendar("09:00", &["1-5"]),
6825        ] {
6826            schedule_with(ok.clone(), RunsOn::Backend)
6827                .validate()
6828                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6829        }
6830    }
6831
6832    #[test]
6833    fn validate_accepts_nth_weekday() {
6834        // #418: nth-weekday (Patch Tuesday). validate() also lowers to
6835        // a cron and parses it with croner, so passing here proves the
6836        // whole chain — token → DOW field → engine-acceptable cron.
6837        for ok in [
6838            calendar("09:00", &["tue#2"]),          // 2nd Tuesday
6839            calendar("09:00", &["fri#1"]),          // 1st Friday
6840            calendar("03:00", &["sun#5"]),          // 5th Sunday
6841            calendar("09:00", &["tue#2", "thu#2"]), // a list of nths
6842            calendar("09:00", &["2#2"]),            // numeric DOW + ordinal
6843            // Case-insensitive both sides: validate lowercases, croner
6844            // upper-cases the whole pattern before aliasing (claude #547).
6845            calendar("09:00", &["TUE#2"]),
6846        ] {
6847            schedule_with(ok.clone(), RunsOn::Backend)
6848                .validate()
6849                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6850        }
6851    }
6852
6853    #[test]
6854    fn validate_rejects_bad_nth_weekday() {
6855        // ordinal out of 1..5, a range with #, and a bad day before #.
6856        for bad in ["tue#0", "tue#6", "tue#x", "mon-fri#2", "funday#2"] {
6857            let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
6858                .validate()
6859                .unwrap_err();
6860            assert!(err.contains("when.days"), "for '{bad}', got: {err}");
6861        }
6862    }
6863
6864    #[test]
6865    fn validate_accepts_last_weekday() {
6866        // #418: last-weekday (`friL` = last Friday). Like the nth case,
6867        // validate() lowers to a cron and round-trips it through croner,
6868        // so passing proves token → DOW field → engine-acceptable cron
6869        // with the verified last-<dow>-of-month semantics.
6870        for ok in [
6871            calendar("09:00", &["friL"]),         // last Friday
6872            calendar("03:00", &["sunL"]),         // last Sunday
6873            calendar("22:00", &["5L"]),           // numeric DOW + last
6874            calendar("00:00", &["0L"]),           // numeric Sunday (0…
6875            calendar("00:00", &["7L"]),           // …and its 7 alias)
6876            calendar("09:00", &["monL", "friL"]), // a list of last-weekdays
6877            // Case-insensitive both the weekday and the `L` suffix:
6878            // validate lowercases the day, croner upper-cases the whole
6879            // pattern before aliasing (claude #547).
6880            calendar("09:00", &["FRIL"]),
6881            calendar("09:00", &["fril"]),
6882        ] {
6883            schedule_with(ok.clone(), RunsOn::Backend)
6884                .validate()
6885                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6886        }
6887    }
6888
6889    #[test]
6890    fn validate_rejects_bad_last_weekday() {
6891        // bare `L` (no weekday — a footgun croner reads as Saturday), a
6892        // range with L, a bad day before L, and an internal space that
6893        // would otherwise leak a malformed cron downstream (gemini #560).
6894        for bad in ["L", "l", "mon-friL", "fundayL", "8L", "*L", "fri L"] {
6895            let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
6896                .validate()
6897                .unwrap_err();
6898            assert!(err.contains("when.days"), "for '{bad}', got: {err}");
6899        }
6900    }
6901
6902    #[test]
6903    fn calendar_oneshot_instant_detects_past() {
6904        use chrono::TimeZone;
6905        // a dated `at` resolves to an absolute instant…
6906        let c = CalendarSpec {
6907            at: "2024-01-01 09:00".into(),
6908            days: vec![],
6909        };
6910        let t = c
6911            .oneshot_instant(ScheduleTz::Utc)
6912            .expect("one-shot instant");
6913        assert_eq!(
6914            t,
6915            chrono::Utc.with_ymd_and_hms(2024, 1, 1, 9, 0, 0).unwrap()
6916        );
6917        assert!(t < chrono::Utc::now(), "2024 is in the past");
6918        // …while a repeating (time-only) calendar has no instant
6919        let rep = CalendarSpec {
6920            at: "09:00".into(),
6921            days: vec!["mon-fri".into()],
6922        };
6923        assert!(rep.oneshot_instant(ScheduleTz::Utc).is_none());
6924    }
6925
6926    fn schedule_with_active(from: Option<&str>, until: Option<&str>) -> Schedule {
6927        let mut s = schedule_with(
6928            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6929            RunsOn::Backend,
6930        );
6931        s.active = Active {
6932            from: from.map(str::to_owned),
6933            until: until.map(str::to_owned),
6934        };
6935        s
6936    }
6937
6938    #[test]
6939    fn validate_accepts_active_window() {
6940        schedule_with_active(Some("2026-07-01"), Some("2026-08-01T12:00:00+09:00"))
6941            .validate()
6942            .expect("date + rfc3339 bounds should validate");
6943    }
6944
6945    #[test]
6946    fn validate_rejects_unparseable_active_bound() {
6947        let err = schedule_with_active(Some("July 1st"), None)
6948            .validate()
6949            .unwrap_err();
6950        assert!(err.contains("active"), "got: {err}");
6951    }
6952
6953    #[test]
6954    fn validate_rejects_from_not_before_until() {
6955        let err = schedule_with_active(Some("2026-08-01"), Some("2026-07-01"))
6956            .validate()
6957            .unwrap_err();
6958        assert!(err.contains("strictly before"), "got: {err}");
6959
6960        let err = schedule_with_active(Some("2026-07-01"), Some("2026-07-01"))
6961            .validate()
6962            .unwrap_err();
6963        assert!(err.contains("strictly before"), "got: {err}");
6964    }
6965
6966    // ---- Active window semantics ----
6967
6968    #[test]
6969    fn active_window_is_half_open() {
6970        use chrono::TimeZone;
6971        let active = Active {
6972            from: Some("2026-07-01".into()),
6973            until: Some("2026-08-01".into()),
6974        };
6975        // UTC tz so the date bounds are UTC midnight.
6976        let at = |y, m, d, h| chrono::Utc.with_ymd_and_hms(y, m, d, h, 0, 0).unwrap();
6977        let c = |t| active.contains(t, ScheduleTz::Utc);
6978        assert!(!c(at(2026, 6, 30, 23)), "before from");
6979        assert!(c(at(2026, 7, 1, 0)), "at from (inclusive)");
6980        assert!(c(at(2026, 7, 15, 12)), "inside");
6981        assert!(!c(at(2026, 8, 1, 0)), "at until (exclusive)");
6982        assert!(!c(at(2026, 8, 2, 0)), "after until");
6983    }
6984
6985    #[test]
6986    fn active_empty_window_is_always_active() {
6987        assert!(Active::default().contains(chrono::Utc::now(), ScheduleTz::Local));
6988    }
6989
6990    #[test]
6991    fn active_rfc3339_bound_honours_offset_regardless_of_tz() {
6992        use chrono::TimeZone;
6993        let active = Active {
6994            from: Some("2026-07-01T09:00:00+09:00".into()),
6995            until: None,
6996        };
6997        // RFC3339 carries its own offset → tz arg is ignored.
6998        // 09:00 JST = 00:00 UTC.
6999        for tz in [ScheduleTz::Utc, ScheduleTz::Local] {
7000            assert!(
7001                !active.contains(
7002                    chrono::Utc
7003                        .with_ymd_and_hms(2026, 6, 30, 23, 59, 0)
7004                        .unwrap(),
7005                    tz
7006                )
7007            );
7008            assert!(active.contains(
7009                chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap(),
7010                tz
7011            ));
7012        }
7013    }
7014
7015    #[test]
7016    fn active_date_bound_respects_tz() {
7017        // A bare `YYYY-MM-DD` bound is midnight *in the schedule's
7018        // tz* (#418 Phase 2). The UTC interpretation is exact and
7019        // host-independent; assert that precisely.
7020        use chrono::TimeZone;
7021        let utc = Active::parse_bound("2026-07-01", ScheduleTz::Utc).expect("utc");
7022        assert_eq!(
7023            utc,
7024            chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap()
7025        );
7026
7027        // The local interpretation must equal what chrono::Local
7028        // computes for the same wall-clock midnight — proves the tz
7029        // path is wired to the host zone (the magnitude vs UTC is
7030        // host-dependent, so we compare against Local directly rather
7031        // than hard-coding the JST offset, keeping CI green on UTC
7032        // runners).
7033        let local = Active::parse_bound("2026-07-01", ScheduleTz::Local).expect("local");
7034        let want = chrono::Local
7035            .with_ymd_and_hms(2026, 7, 1, 0, 0, 0)
7036            .single()
7037            .expect("local midnight is unambiguous")
7038            .with_timezone(&chrono::Utc);
7039        assert_eq!(local, want, "date bound resolved in host-local tz");
7040    }
7041
7042    #[test]
7043    fn active_empty_is_skipped_when_serialising() {
7044        let s = schedule_with(
7045            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7046            RunsOn::Backend,
7047        );
7048        let json = serde_json::to_value(&s).expect("serialise");
7049        assert!(
7050            json.get("active").is_none(),
7051            "empty active must not appear on the wire: {json}"
7052        );
7053    }
7054
7055    // ---- constraints.window (#418 Phase 3) ----
7056
7057    fn with_window(win: &str) -> Schedule {
7058        let mut s = schedule_with(
7059            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
7060            RunsOn::Backend,
7061        );
7062        s.constraints.window = Some(win.into());
7063        s
7064    }
7065
7066    #[test]
7067    fn constraints_window_parses_and_round_trips() {
7068        let yaml = r#"
7069id: x
7070when:
7071  per_pc: { every: 6h }
7072job_id: y
7073target: { all: true }
7074constraints:
7075  window: "22:00-05:00"
7076"#;
7077        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7078        assert_eq!(s.constraints.window.as_deref(), Some("22:00-05:00"));
7079        let back: Schedule =
7080            serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
7081        assert_eq!(back.constraints.window.as_deref(), Some("22:00-05:00"));
7082    }
7083
7084    #[test]
7085    fn constraints_empty_is_skipped_when_serialising() {
7086        let s = schedule_with(
7087            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7088            RunsOn::Backend,
7089        );
7090        let json = serde_json::to_value(&s).expect("serialise");
7091        assert!(
7092            json.get("constraints").is_none(),
7093            "empty constraints must not appear on the wire: {json}"
7094        );
7095    }
7096
7097    #[test]
7098    fn window_no_constraint_always_allows() {
7099        let c = Constraints::default();
7100        assert!(c.allows(chrono::Utc::now(), ScheduleTz::Local));
7101    }
7102
7103    #[test]
7104    fn window_same_day_is_half_open() {
7105        use chrono::TimeZone;
7106        let s = with_window("09:00-17:00");
7107        let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
7108        let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
7109        assert!(!a(at(8, 59)), "before start");
7110        assert!(a(at(9, 0)), "at start (inclusive)");
7111        assert!(a(at(16, 59)), "inside");
7112        assert!(!a(at(17, 0)), "at end (exclusive)");
7113        assert!(!a(at(23, 0)), "after end");
7114    }
7115
7116    #[test]
7117    fn window_crossing_midnight() {
7118        use chrono::TimeZone;
7119        let s = with_window("22:00-05:00");
7120        let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
7121        let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
7122        assert!(a(at(22, 0)), "at start tonight");
7123        assert!(a(at(23, 30)), "late tonight");
7124        assert!(a(at(3, 0)), "early tomorrow");
7125        assert!(!a(at(5, 0)), "at end (exclusive)");
7126        assert!(!a(at(12, 0)), "midday outside");
7127        assert!(!a(at(21, 59)), "just before start");
7128    }
7129
7130    #[test]
7131    fn window_respects_tz() {
7132        // The same instant is inside the window under one tz and may
7133        // be outside under another. Compare UTC vs Local via the
7134        // host's own offset (kept CI-green on UTC runners like the
7135        // active tz test does).
7136        use chrono::TimeZone;
7137        let s = with_window("09:00-17:00");
7138        let noon_utc = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 12, 0, 0).unwrap();
7139        // Under UTC, 12:00 is inside 09:00-17:00.
7140        assert!(s.constraints.allows(noon_utc, ScheduleTz::Utc));
7141        // Under Local, the verdict tracks the host wall-clock time;
7142        // assert it matches a direct wall_time membership check.
7143        let local_t = noon_utc.with_timezone(&chrono::Local).time();
7144        let in_local = local_t >= chrono::NaiveTime::from_hms_opt(9, 0, 0).unwrap()
7145            && local_t < chrono::NaiveTime::from_hms_opt(17, 0, 0).unwrap();
7146        assert_eq!(s.constraints.allows(noon_utc, ScheduleTz::Local), in_local);
7147    }
7148
7149    #[test]
7150    fn validate_accepts_good_window() {
7151        for w in ["09:00-17:00", "22:00-05:00", "00:00-23:59"] {
7152            with_window(w)
7153                .validate()
7154                .unwrap_or_else(|e| panic!("'{w}' should validate: {e}"));
7155        }
7156    }
7157
7158    #[test]
7159    fn validate_rejects_bad_window() {
7160        for bad in ["9-5", "22:00", "22:00-22:00", "25:00-05:00", "09:00_17:00"] {
7161            let err = with_window(bad).validate().unwrap_err();
7162            assert!(
7163                err.contains("constraints.window"),
7164                "for '{bad}', got: {err}"
7165            );
7166        }
7167    }
7168
7169    // ---- constraints.skip_dates (#418 holiday exclusion) ----
7170
7171    fn with_skip_dates(dates: &[&str]) -> Schedule {
7172        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
7173        s.tz = ScheduleTz::Utc; // host-independent date assertions
7174        s.constraints.skip_dates = dates.iter().map(|d| (*d).to_string()).collect();
7175        s
7176    }
7177
7178    #[test]
7179    fn allows_blocks_listed_skip_date() {
7180        use chrono::TimeZone;
7181        let s = with_skip_dates(&["2026-06-10", "2026-12-25"]);
7182        // Any time on a listed date is blocked (whole day).
7183        let on = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap();
7184        assert!(!s.constraints.allows(on, ScheduleTz::Utc));
7185        let on_midnight = chrono::Utc.with_ymd_and_hms(2026, 12, 25, 0, 0, 0).unwrap();
7186        assert!(!s.constraints.allows(on_midnight, ScheduleTz::Utc));
7187        // A date not in the list fires normally.
7188        let off = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
7189        assert!(s.constraints.allows(off, ScheduleTz::Utc));
7190    }
7191
7192    #[test]
7193    fn allows_corrupt_skip_date_fails_closed() {
7194        use chrono::TimeZone;
7195        // A garbled entry (only reachable via hand-edited KV) blocks
7196        // rather than silently re-enabling fires — same posture as a
7197        // corrupt window.
7198        let s = with_skip_dates(&["not-a-date"]);
7199        let any = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
7200        assert!(!s.constraints.allows(any, ScheduleTz::Utc));
7201    }
7202
7203    #[test]
7204    fn validate_accepts_good_skip_dates() {
7205        with_skip_dates(&["2026-01-01", "2026-12-25", "2027-05-03"])
7206            .validate()
7207            .expect("well-formed skip dates should validate");
7208    }
7209
7210    #[test]
7211    fn validate_rejects_bad_skip_date() {
7212        for bad in ["2026-13-01", "01-01-2026", "nope", "2026/01/01"] {
7213            let err = with_skip_dates(&[bad]).validate().unwrap_err();
7214            assert!(
7215                err.contains("constraints.skip_dates"),
7216                "for '{bad}', got: {err}"
7217            );
7218        }
7219    }
7220
7221    #[test]
7222    fn preview_skips_holidays() {
7223        use chrono::TimeZone;
7224        // Daily 09:00 with two of the next five days marked as holidays
7225        // — preview drops exactly those, since it gates on `allows`.
7226        let mut s = cal_utc("09:00", &[]);
7227        s.constraints.skip_dates = vec!["2026-06-11".into(), "2026-06-13".into()];
7228        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
7229        let got = s.preview_fires(now, 4);
7230        let want: Vec<_> = [
7231            (2026, 6, 10),
7232            (2026, 6, 12), // skips 06-11
7233            (2026, 6, 14), // skips 06-13
7234            (2026, 6, 15),
7235        ]
7236        .iter()
7237        .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
7238        .collect();
7239        assert_eq!(got, want);
7240    }
7241
7242    // ---- constraints.max_concurrent (#418) ----
7243
7244    fn with_max_concurrent(max: u32, runs_on: RunsOn) -> Schedule {
7245        let mut s = schedule_with(
7246            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
7247            runs_on,
7248        );
7249        s.constraints.max_concurrent = Some(max);
7250        s
7251    }
7252
7253    #[test]
7254    fn validate_accepts_backend_max_concurrent() {
7255        with_max_concurrent(5, RunsOn::Backend)
7256            .validate()
7257            .expect("backend max_concurrent should validate");
7258    }
7259
7260    #[test]
7261    fn validate_rejects_max_concurrent_on_agent() {
7262        // Decision E: a central running-instance cap needs a central
7263        // counter, which agents don't have.
7264        let err = with_max_concurrent(5, RunsOn::Agent)
7265            .validate()
7266            .unwrap_err();
7267        assert!(err.contains("constraints.max_concurrent"), "got: {err}");
7268        assert!(err.contains("runs_on: agent"), "got: {err}");
7269    }
7270
7271    #[test]
7272    fn validate_rejects_zero_max_concurrent() {
7273        let err = with_max_concurrent(0, RunsOn::Backend)
7274            .validate()
7275            .unwrap_err();
7276        assert!(err.contains("max_concurrent must be >= 1"), "got: {err}");
7277    }
7278
7279    #[test]
7280    fn max_concurrent_round_trips_and_skips_when_absent() {
7281        let s = with_max_concurrent(3, RunsOn::Backend);
7282        let json = serde_json::to_value(&s.constraints).expect("ser");
7283        assert_eq!(json.get("max_concurrent").and_then(|v| v.as_u64()), Some(3));
7284        // A schedule with no constraints omits the whole block.
7285        let bare = schedule_with(
7286            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7287            RunsOn::Backend,
7288        );
7289        assert!(bare.constraints.is_empty());
7290    }
7291
7292    #[test]
7293    fn window_fail_closed_on_corrupt_blob() {
7294        // A malformed window (only reachable via a hand-edited KV
7295        // blob — validate() rejects it at create) must BLOCK, not
7296        // silently allow fires during a change-freeze (gemini #452).
7297        let s = with_window("22:00_05:00");
7298        assert!(
7299            !s.constraints.allows(chrono::Utc::now(), ScheduleTz::Utc),
7300            "corrupt window fails closed"
7301        );
7302        // …and the scheduler can surface why it's stuck.
7303        assert!(
7304            s.bad_window().is_some(),
7305            "bad_window reports the parse error"
7306        );
7307        assert!(with_window("22:00-05:00").bad_window().is_none());
7308    }
7309
7310    #[test]
7311    fn calendar_outside_window_is_flagged() {
7312        // at 09:00 can never fall in 22:00-05:00 → never fires.
7313        let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
7314        s.constraints.window = Some("22:00-05:00".into());
7315        assert!(s.calendar_outside_window(), "09:00 is not in 22:00-05:00");
7316
7317        // at 23:00 IS inside the overnight window → fine.
7318        let mut s = schedule_with(calendar("23:00", &[]), RunsOn::Backend);
7319        s.constraints.window = Some("22:00-05:00".into());
7320        assert!(!s.calendar_outside_window(), "23:00 is in 22:00-05:00");
7321
7322        // reconcile shapes are never flagged (they poll every minute).
7323        let mut s = schedule_with(
7324            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
7325            RunsOn::Backend,
7326        );
7327        s.constraints.window = Some("22:00-05:00".into());
7328        assert!(!s.calendar_outside_window(), "reconcile is unaffected");
7329
7330        // no window → never flagged.
7331        let s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
7332        assert!(!s.calendar_outside_window());
7333    }
7334
7335    // ---- on_failure.retry (#418 Phase 4) ----
7336
7337    fn with_retry(max: u32, backoff: &str) -> Schedule {
7338        let mut s = schedule_with(
7339            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
7340            RunsOn::Backend,
7341        );
7342        s.on_failure.retry = Some(Retry {
7343            max,
7344            backoff: backoff.into(),
7345        });
7346        s
7347    }
7348
7349    #[test]
7350    fn on_failure_parses_and_round_trips() {
7351        let yaml = r#"
7352id: x
7353when:
7354  per_pc: { every: 6h }
7355job_id: y
7356target: { all: true }
7357on_failure:
7358  retry: { max: 3, backoff: 10m }
7359"#;
7360        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7361        let r = s.on_failure.retry.as_ref().expect("retry present");
7362        assert_eq!(r.max, 3);
7363        assert_eq!(r.backoff, "10m");
7364        let back: Schedule =
7365            serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
7366        assert_eq!(back.on_failure, s.on_failure);
7367    }
7368
7369    #[test]
7370    fn on_failure_empty_is_skipped_when_serialising() {
7371        let s = schedule_with(
7372            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7373            RunsOn::Backend,
7374        );
7375        let json = serde_json::to_value(&s).expect("serialise");
7376        assert!(
7377            json.get("on_failure").is_none(),
7378            "empty on_failure must not appear on the wire: {json}"
7379        );
7380    }
7381
7382    #[test]
7383    fn validate_accepts_good_retry() {
7384        for (max, backoff) in [(1, "30s"), (3, "10m"), (10, "1h")] {
7385            with_retry(max, backoff)
7386                .validate()
7387                .unwrap_or_else(|e| panic!("retry {{max:{max}, backoff:{backoff}}}: {e}"));
7388        }
7389    }
7390
7391    #[test]
7392    fn validate_rejects_bad_backoff() {
7393        let err = with_retry(3, "soon").validate().unwrap_err();
7394        assert!(err.contains("on_failure.retry.backoff"), "got: {err}");
7395    }
7396
7397    #[test]
7398    fn validate_rejects_sub_second_backoff() {
7399        // "500ms" parses as humantime but lowers to 0s on the wire —
7400        // reject it so the operator doesn't get a silent no-wait
7401        // (coderabbit #466).
7402        for bad in ["500ms", "0s", "999ms"] {
7403            let err = with_retry(3, bad).validate().unwrap_err();
7404            assert!(
7405                err.contains("on_failure.retry.backoff must be >= 1s"),
7406                "for '{bad}', got: {err}"
7407            );
7408        }
7409    }
7410
7411    #[test]
7412    fn validate_rejects_out_of_range_max() {
7413        for bad in [0u32, 11, 1000] {
7414            let err = with_retry(bad, "10m").validate().unwrap_err();
7415            assert!(
7416                err.contains("on_failure.retry.max"),
7417                "for max={bad}, got: {err}"
7418            );
7419        }
7420    }
7421
7422    #[test]
7423    fn lowered_retry_reduces_backoff_to_seconds() {
7424        let s = with_retry(3, "10m");
7425        let spec = s.on_failure.lowered_retry().expect("a retry policy");
7426        assert_eq!(spec.max, 3);
7427        assert_eq!(spec.backoff_secs, 600);
7428    }
7429
7430    #[test]
7431    fn lowered_retry_is_none_without_policy() {
7432        let s = schedule_with(
7433            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7434            RunsOn::Backend,
7435        );
7436        assert!(s.on_failure.lowered_retry().is_none());
7437    }
7438
7439    // ---- global change-freeze (#418 Phase 5) ----
7440
7441    #[test]
7442    fn freeze_empty_window_is_always_active() {
7443        // The big-red-button shape: no bounds = frozen until cleared.
7444        let f = Freeze::default();
7445        assert!(f.is_active(chrono::Utc::now()));
7446    }
7447
7448    #[test]
7449    fn freeze_window_is_half_open() {
7450        use chrono::TimeZone;
7451        let f = Freeze {
7452            from: Some("2026-12-20T00:00:00+00:00".into()),
7453            until: Some("2027-01-05T00:00:00+00:00".into()),
7454            reason: Some("year-end".into()),
7455            tz: ScheduleTz::Utc,
7456        };
7457        let at = |y, mo, d| chrono::Utc.with_ymd_and_hms(y, mo, d, 0, 0, 0).unwrap();
7458        assert!(!f.is_active(at(2026, 12, 19)), "before from = not frozen");
7459        assert!(f.is_active(at(2026, 12, 20)), "from is inclusive");
7460        assert!(f.is_active(at(2026, 12, 31)), "inside window");
7461        assert!(!f.is_active(at(2027, 1, 5)), "until is exclusive");
7462        assert!(!f.is_active(at(2027, 1, 6)), "after until = not frozen");
7463    }
7464
7465    #[test]
7466    fn freeze_fails_closed_on_corrupt_bound() {
7467        // A freeze is a safety switch: an unparseable bound (only
7468        // reachable via a hand-edited KV blob) must read as FROZEN, not
7469        // "fire normally" (coderabbit #472) — the opposite of `active`,
7470        // which fail-opens.
7471        let f = Freeze {
7472            from: Some("not-a-date".into()),
7473            until: None,
7474            reason: None,
7475            tz: ScheduleTz::Utc,
7476        };
7477        assert!(f.is_active(chrono::Utc::now()), "corrupt bound → frozen");
7478    }
7479
7480    #[test]
7481    fn freeze_validate_accepts_good_bounds() {
7482        Freeze {
7483            from: Some("2026-12-20".into()),
7484            until: Some("2027-01-05T12:00:00+09:00".into()),
7485            reason: None,
7486            tz: ScheduleTz::Local,
7487        }
7488        .validate()
7489        .expect("date + rfc3339 bounds should validate");
7490        // Empty (indefinite) freeze is valid.
7491        Freeze::default().validate().expect("empty freeze is valid");
7492    }
7493
7494    #[test]
7495    fn freeze_validate_rejects_bad_bound_and_inverted_window() {
7496        let err = Freeze {
7497            from: Some("never".into()),
7498            ..Default::default()
7499        }
7500        .validate()
7501        .unwrap_err();
7502        assert!(err.contains("freeze:"), "got: {err}");
7503
7504        let inverted = Freeze {
7505            from: Some("2027-01-05".into()),
7506            until: Some("2026-12-20".into()),
7507            ..Default::default()
7508        }
7509        .validate()
7510        .unwrap_err();
7511        assert!(inverted.contains("freeze.from"), "got: {inverted}");
7512    }
7513
7514    #[test]
7515    fn freeze_round_trips_and_skips_empty_fields() {
7516        let f = Freeze {
7517            from: None,
7518            until: Some("2027-01-05".into()),
7519            reason: Some("INC-1234".into()),
7520            tz: ScheduleTz::Utc,
7521        };
7522        let json = serde_json::to_value(&f).expect("serialise");
7523        assert!(json.get("from").is_none(), "empty from omitted: {json}");
7524        let back: Freeze = serde_json::from_value(json).expect("round-trip");
7525        assert_eq!(back, f);
7526    }
7527
7528    #[test]
7529    fn shipped_schedule_configs_parse_and_validate() {
7530        // Every YAML under configs/schedules/ must parse with the
7531        // current Schedule serde AND pass validate() — keeps the
7532        // shipped examples from drifting out of sync with the model
7533        // (#418 removed back-compat, so drift = broken at create).
7534        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../configs/schedules");
7535        let mut seen = 0;
7536        for entry in std::fs::read_dir(&dir).expect("read configs/schedules") {
7537            let path = entry.expect("dir entry").path();
7538            if path.extension().and_then(|e| e.to_str()) != Some("yaml") {
7539                continue;
7540            }
7541            let body = std::fs::read_to_string(&path).expect("read yaml");
7542            let s: Schedule = serde_yaml::from_str(&body)
7543                .unwrap_or_else(|e| panic!("{} failed to parse: {e}", path.display()));
7544            s.validate()
7545                .unwrap_or_else(|e| panic!("{} failed validate(): {e}", path.display()));
7546            seen += 1;
7547        }
7548        assert!(seen > 0, "no schedule YAMLs found in {}", dir.display());
7549    }
7550
7551    // ---- pre-existing enum wire formats (unchanged by #418) ----
7552
7553    #[test]
7554    fn exec_mode_serialises_snake_case() {
7555        for (mode, expected) in [
7556            (ExecMode::EveryTick, "every_tick"),
7557            (ExecMode::OncePerPc, "once_per_pc"),
7558            (ExecMode::OncePerTarget, "once_per_target"),
7559        ] {
7560            let s = serde_json::to_value(mode).expect("serialise");
7561            assert_eq!(s, serde_json::Value::String(expected.into()));
7562            let back: ExecMode = serde_json::from_value(serde_json::Value::String(expected.into()))
7563                .expect("deserialise");
7564            assert_eq!(back, mode, "round-trip for {expected}");
7565        }
7566    }
7567
7568    #[test]
7569    fn schedule_runs_on_defaults_to_backend() {
7570        let yaml = r#"
7571id: x
7572when:
7573  per_pc: once
7574job_id: y
7575target: { all: true }
7576"#;
7577        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7578        assert_eq!(s.runs_on, RunsOn::Backend);
7579    }
7580
7581    #[test]
7582    fn schedule_runs_on_agent_parses() {
7583        let yaml = r#"
7584id: offline-inv
7585when:
7586  per_pc: { every: 1h }
7587job_id: inventory-hw
7588target: { all: true }
7589runs_on: agent
7590"#;
7591        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7592        assert_eq!(s.runs_on, RunsOn::Agent);
7593        assert_eq!(s.lowered().mode, ExecMode::OncePerPc);
7594    }
7595
7596    #[test]
7597    fn runs_on_serialises_snake_case() {
7598        for (mode, expected) in [(RunsOn::Backend, "backend"), (RunsOn::Agent, "agent")] {
7599            let s = serde_json::to_value(mode).expect("serialise");
7600            assert_eq!(s, serde_json::Value::String(expected.into()));
7601            let back: RunsOn = serde_json::from_value(serde_json::Value::String(expected.into()))
7602                .expect("deserialise");
7603            assert_eq!(back, mode);
7604        }
7605    }
7606
7607    #[test]
7608    fn execute_shell_into_wire_shell() {
7609        assert_eq!(Shell::from(ExecuteShell::Powershell), Shell::Powershell);
7610        assert_eq!(Shell::from(ExecuteShell::Cmd), Shell::Cmd);
7611        assert_eq!(Shell::from(ExecuteShell::Sh), Shell::Sh);
7612        assert_eq!(Shell::from(ExecuteShell::Pwsh), Shell::Pwsh);
7613    }
7614
7615    #[test]
7616    fn execute_shell_parses_sh_and_pwsh() {
7617        // The manifest `execute.shell` accepts the two new lowercase
7618        // tokens end-to-end (serde), so an operator can author a Linux
7619        // job.
7620        for (yaml_shell, want) in [("sh", ExecuteShell::Sh), ("pwsh", ExecuteShell::Pwsh)] {
7621            let yaml = format!(
7622                "id: x\nversion: 1.0.0\nexecute:\n  shell: {yaml_shell}\n  script: \"echo\"\n  timeout: 1s\n"
7623            );
7624            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
7625            assert_eq!(m.execute.shell, want, "shell {yaml_shell}");
7626        }
7627    }
7628
7629    #[test]
7630    fn manifest_staleness_defaults_to_cached() {
7631        let yaml = r#"
7632id: x
7633version: 1.0.0
7634execute:
7635  shell: powershell
7636  script: "echo"
7637  timeout: 1s
7638"#;
7639        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7640        assert_eq!(m.staleness, Staleness::Cached);
7641    }
7642
7643    #[test]
7644    fn manifest_strict_staleness_parses() {
7645        let yaml = r#"
7646id: urgent-patch
7647version: 2.5.1
7648execute:
7649  shell: powershell
7650  script: Install-Hotfix
7651  timeout: 5m
7652staleness:
7653  mode: strict
7654  max_cache_age: 0s
7655"#;
7656        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7657        match m.staleness {
7658            Staleness::Strict { max_cache_age } => assert_eq!(max_cache_age, "0s"),
7659            other => panic!("expected strict, got {other:?}"),
7660        }
7661    }
7662
7663    #[test]
7664    fn manifest_unchecked_staleness_parses() {
7665        let yaml = r#"
7666id: legacy
7667version: 0.1.0
7668execute:
7669  shell: cmd
7670  script: "echo"
7671  timeout: 1s
7672staleness:
7673  mode: unchecked
7674"#;
7675        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7676        assert_eq!(m.staleness, Staleness::Unchecked);
7677    }
7678
7679    #[test]
7680    fn missing_required_field_errors() {
7681        // `id` missing.
7682        let yaml = r#"
7683version: 1.0.0
7684target: { all: true }
7685execute:
7686  shell: powershell
7687  script: "echo"
7688  timeout: 1s
7689"#;
7690        let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
7691        assert!(r.is_err(), "expected error, got {:?}", r);
7692    }
7693
7694    #[test]
7695    fn display_field_table_kind_round_trips_with_nested_columns() {
7696        // #39: `type: table` + `columns:` on a DisplayField gets
7697        // round-tripped through serde so the SPA receives the
7698        // nested schema verbatim. Nested columns themselves are
7699        // DisplayFields so they can carry `type: bytes` /
7700        // `type: number` for cell formatting.
7701        let yaml = r#"
7702id: inv-hw
7703version: 1.0.0
7704execute:
7705  shell: powershell
7706  script: "echo"
7707  timeout: 60s
7708inventory:
7709  display:
7710    - field: hostname
7711      label: Hostname
7712    - field: disks
7713      label: Disks
7714      type: table
7715      columns:
7716        - field: device_id
7717          label: Drive
7718        - field: size_bytes
7719          label: Size
7720          type: bytes
7721        - field: free_bytes
7722          label: Free
7723          type: bytes
7724        - field: file_system
7725          label: FS
7726"#;
7727        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7728        let inv = m.inventory.as_ref().expect("inventory hint");
7729        let disks = inv
7730            .display
7731            .iter()
7732            .find(|d| d.field == "disks")
7733            .expect("disks display row");
7734        assert_eq!(disks.kind.as_deref(), Some("table"));
7735        let cols = disks.columns.as_ref().expect("table needs columns");
7736        assert_eq!(cols.len(), 4);
7737        assert_eq!(cols[1].field, "size_bytes");
7738        assert_eq!(cols[1].kind.as_deref(), Some("bytes"));
7739    }
7740
7741    #[test]
7742    fn display_field_scalar_kind_keeps_columns_none() {
7743        // Defensive: when type is a scalar (`bytes` / `number` /
7744        // `timestamp`) the `columns` field stays None — the SPA
7745        // uses its presence as the "render nested table" signal,
7746        // so it must not leak in via serde defaults.
7747        let yaml = r#"
7748id: x
7749version: 1.0.0
7750execute:
7751  shell: powershell
7752  script: "echo"
7753  timeout: 5s
7754inventory:
7755  display:
7756    - { field: ram_bytes, label: RAM, type: bytes }
7757"#;
7758        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7759        let inv = m.inventory.as_ref().unwrap();
7760        assert!(inv.display[0].columns.is_none());
7761    }
7762
7763    // ---- GroupDef (#1032 dynamic groups) ----
7764
7765    fn group_def(yaml: &str) -> Result<GroupDef, String> {
7766        let g: GroupDef = crate::strict::from_yaml_str(yaml).map_err(|e| e.to_string())?;
7767        g.validate().map(|()| g)
7768    }
7769
7770    #[test]
7771    fn group_def_static_members_valid() {
7772        let g = group_def("id: pilot\nmembers: [PC-A, PC-B]\n").expect("valid static group");
7773        assert_eq!(g.members, vec!["PC-A", "PC-B"]);
7774        assert!(g.dynamic_query().is_none());
7775    }
7776
7777    #[test]
7778    fn group_def_dynamic_query_valid() {
7779        let g = group_def(
7780            "id: clients\nquery: \"SELECT pc_id FROM agents WHERE hostname LIKE 'X%'\"\nrefresh: 30m\n",
7781        )
7782        .expect("valid dynamic group");
7783        assert_eq!(
7784            g.dynamic_query(),
7785            Some("SELECT pc_id FROM agents WHERE hostname LIKE 'X%'")
7786        );
7787        assert_eq!(g.refresh_interval(), std::time::Duration::from_secs(1800));
7788    }
7789
7790    #[test]
7791    fn group_def_refresh_defaults_when_absent() {
7792        let g = group_def("id: c\nquery: \"SELECT pc_id FROM agents\"\n").unwrap();
7793        assert_eq!(g.refresh_interval(), DEFAULT_GROUP_REFRESH);
7794    }
7795
7796    #[test]
7797    fn group_def_rejects_neither_members_nor_query() {
7798        let err = group_def("id: empty\n").unwrap_err();
7799        assert!(err.contains("either"), "err: {err}");
7800    }
7801
7802    #[test]
7803    fn group_def_rejects_both_members_and_query() {
7804        let err = group_def("id: both\nmembers: [PC-A]\nquery: \"SELECT pc_id FROM agents\"\n")
7805            .unwrap_err();
7806        assert!(err.contains("mutually exclusive"), "err: {err}");
7807    }
7808
7809    #[test]
7810    fn group_def_blank_query_is_unset_not_both() {
7811        // An empty-string query reads as unset, so a members group with a
7812        // commented-out (emptied) query is still valid, not a "both set" error.
7813        let g =
7814            group_def("id: pilot\nmembers: [PC-A]\nquery: \"\"\n").expect("blank query = unset");
7815        assert!(g.dynamic_query().is_none());
7816    }
7817
7818    #[test]
7819    fn group_def_rejects_bad_id_charset() {
7820        let err = group_def("id: bad/id\nmembers: [PC-A]\n").unwrap_err();
7821        assert!(err.contains("group.id"), "err: {err}");
7822    }
7823
7824    #[test]
7825    fn group_def_rejects_untrimmed_id() {
7826        // A padded id validated-as-trimmed but stored-raw would be a KV key
7827        // nothing matches — reject it outright (the id is used verbatim).
7828        let err = group_def("id: \" clients \"\nmembers: [PC-A]\n").unwrap_err();
7829        assert!(err.contains("group.id"), "err: {err}");
7830    }
7831
7832    #[test]
7833    fn group_def_rejects_bad_refresh() {
7834        let err =
7835            group_def("id: c\nquery: \"SELECT pc_id FROM agents\"\nrefresh: soon\n").unwrap_err();
7836        assert!(err.contains("refresh"), "err: {err}");
7837    }
7838
7839    #[test]
7840    fn group_def_rejects_unknown_key() {
7841        // Strict parse (#492) — a typo'd key is an operator error, not silently
7842        // dropped.
7843        let err = group_def("id: c\nmembers: [PC-A]\nrlue: x\n").unwrap_err();
7844        assert!(err.to_lowercase().contains("unknown"), "err: {err}");
7845    }
7846
7847    // ---- checked-in JSON Schema freshness (docs/schemas/) ----
7848
7849    /// The JSON Schemas under `docs/schemas/` must match what
7850    /// `schema_for!` produces today — a Cargo.lock-style freshness guard
7851    /// so a `Schedule` / `Manifest` field change can't silently drift
7852    /// the operator-facing schema. The SPA editor, the backend
7853    /// `/api/schemas/*` endpoints, and these files all read the same
7854    /// derived shape; this test fails CI if the checked-in copy lags.
7855    /// Regenerate with:
7856    ///   `UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current`
7857    #[test]
7858    fn schema_files_are_current() {
7859        assert_schema_file("schedule.schema.json", &schemars::schema_for!(Schedule));
7860        assert_schema_file("job.schema.json", &schemars::schema_for!(Manifest));
7861        assert_schema_file("view.schema.json", &schemars::schema_for!(View));
7862        assert_schema_file("group-def.schema.json", &schemars::schema_for!(GroupDef));
7863    }
7864
7865    fn assert_schema_file(name: &str, schema: &schemars::Schema) {
7866        let generated = serde_json::to_string_pretty(schema).expect("serialize schema") + "\n";
7867        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7868            .join("../../docs/schemas")
7869            .join(name);
7870        if std::env::var_os("UPDATE_SCHEMAS").is_some() {
7871            std::fs::create_dir_all(path.parent().unwrap()).expect("mkdir docs/schemas");
7872            std::fs::write(&path, &generated).unwrap_or_else(|e| panic!("write {path:?}: {e}"));
7873            return;
7874        }
7875        // Normalize CRLF→LF before comparing: `.gitattributes` already
7876        // pins these files to `eol=lf`, but a stray CRLF working-tree
7877        // copy (autocrlf, a tool rewrite) shouldn't turn a *content*-
7878        // freshness check into a confusing line-ending failure — that's
7879        // .gitattributes' job, not this test's (gemini #588).
7880        let on_disk = std::fs::read_to_string(&path)
7881            .unwrap_or_else(|e| {
7882                panic!(
7883                    "read {path:?}: {e}\n\
7884                     generate it with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
7885                )
7886            })
7887            .replace("\r\n", "\n");
7888        assert_eq!(
7889            on_disk, generated,
7890            "{name} is stale — a Schedule/Manifest schema change isn't reflected in docs/schemas/. \
7891             Refresh with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
7892        );
7893    }
7894}
7895
7896/// Periodic schedule (spec §2.4.3). v0.18.0 carries the fanout plan
7897/// (target + optional rollout + optional jitter) inline; the
7898/// referenced job (`job_id` → [`BUCKET_JOBS`]) supplies only the
7899/// script body. Two schedules of the same job can target different
7900/// groups on different cadences without copying the manifest.
7901///
7902/// #418 Phase 1: the cadence is the single [`When`] field. The old
7903/// `cron` × `mode` × `cooldown` × `auto_disable_when_done` quartet
7904/// is gone (no back-compat — pre-Phase-1 KV blobs fail to parse and
7905/// are warn-skipped; re-`schedule create` to upgrade them). The
7906/// engine underneath is unchanged: [`Schedule::lowered`] maps `when`
7907/// onto the same (cron, ExecMode, cooldown) trio the scheduler and
7908/// `decide_fire` always ran on.
7909#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
7910pub struct Schedule {
7911    pub id: String,
7912    /// When to fire — a reconcile cadence (`per_pc` / `per_target`)
7913    /// or a calendar time trigger (`at` / `days`). See [`When`].
7914    ///
7915    /// `singleton_map`: serde_yaml 0.9 renders externally-tagged
7916    /// enums as `!per_pc` YAML tags by default; this keeps the
7917    /// operator-facing map shape (`when: { per_pc: once }`). JSON
7918    /// output is identical either way, and the schemars schema
7919    /// (external tagging = oneOf of single-key objects) already
7920    /// matches the singleton-map wire shape.
7921    #[serde(with = "serde_yaml::with::singleton_map")]
7922    #[schemars(with = "When")]
7923    pub when: When,
7924    /// Key into [`crate::kv::BUCKET_JOBS`]. Must equal a registered
7925    /// Manifest's `id`.
7926    pub job_id: String,
7927    /// Who + how-to-phase + when-to-stagger. The Manifest doesn't
7928    /// carry these any more — same job + different fanout = different
7929    /// schedule.
7930    #[serde(flatten)]
7931    pub plan: FanoutPlan,
7932    /// Optional validity window. Outside `[from, until)` the
7933    /// schedule is dormant — still registered, still visible, but
7934    /// every tick is skipped (deleted ≠ dormant: a campaign that
7935    /// ended stays inspectable and can be re-armed by editing the
7936    /// window). Checked at tick time on both the backend scheduler
7937    /// and the agent's local scheduler.
7938    #[serde(default, skip_serializing_if = "Active::is_empty")]
7939    pub active: Active,
7940    /// #418 operational constraints gating *when within an active
7941    /// period* a fire may happen: a maintenance `window`, a fleet
7942    /// `max_concurrent` cap, and `skip_dates` (holiday exclusion). The
7943    /// wall-clock ones are evaluated in the schedule's `tz`; future
7944    /// `require` (env gates) lands in the same namespace. Checked at
7945    /// tick time on both schedulers (and surfaced by `preview`).
7946    #[serde(default, skip_serializing_if = "Constraints::is_empty")]
7947    pub constraints: Constraints,
7948    /// #418 Phase 4: what to do after a fire's script comes back
7949    /// failed. Currently just `retry` (fixed-backoff in-process
7950    /// re-run); future `notify` / `disable` join the same namespace.
7951    /// Applied fire-side in `handle_command` (the retry policy is
7952    /// lowered onto every Command this schedule produces), so it
7953    /// covers both `runs_on` locations.
7954    #[serde(default, skip_serializing_if = "OnFailure::is_empty")]
7955    pub on_failure: OnFailure,
7956    /// #418 Phase 2: the timezone this schedule's wall-clock fields
7957    /// are evaluated in — both the calendar `at` firing time AND the
7958    /// `active.{from,until}` window bounds. `local` (default) = the
7959    /// running host's TZ (the agent's for `runs_on: agent`, the
7960    /// backend server's otherwise); `utc` for TZ-independent
7961    /// schedules. Reconcile shapes (`per_pc`/`per_target`) ignore it
7962    /// for firing (poll cron runs every minute regardless) but still
7963    /// honor it for the `active` window.
7964    #[serde(default)]
7965    pub tz: ScheduleTz,
7966    /// v0.22: optional humantime window after a cron tick during
7967    /// which the Command is still considered "live". The scheduler
7968    /// computes `tick_at + starting_deadline` and stamps it onto
7969    /// each Command as `deadline_at`; agents skip Commands they
7970    /// receive after that absolute time. `None` (default) = no
7971    /// deadline, meaning a Command queued in the broker / stream
7972    /// during agent downtime runs whenever the agent reconnects —
7973    /// good for kitting / inventory / cleanup. Set this for
7974    /// time-of-day notifications, lunch reminders, etc., where
7975    /// "fire 3 hours late" would be wrong.
7976    #[serde(default, skip_serializing_if = "Option::is_none")]
7977    pub starting_deadline: Option<String>,
7978    /// v0.23: where does the cron tick happen? `Backend` (default,
7979    /// historical) = backend's scheduler fires Commands via NATS;
7980    /// agents passively receive. `Agent` = each targeted agent runs
7981    /// its own internal cron and fires locally, so the schedule
7982    /// keeps ticking even when the broker is unreachable (laptop on
7983    /// the train, broker maintenance window, full WAN outage). The
7984    /// two locations are mutually exclusive — when `Agent`, the
7985    /// backend scheduler stays out and just keeps the definition in
7986    /// KV for agents to read.
7987    #[serde(default)]
7988    pub runs_on: RunsOn,
7989    #[serde(default = "default_true")]
7990    pub enabled: bool,
7991    /// Free-form operator taxonomy for the Schedules page — the
7992    /// schedule-side mirror of `Manifest.tags` (added in #640; a plain
7993    /// code ref rather than an intra-doc link, since that field isn't
7994    /// on this branch until #640 merges). Purely a SPA-side
7995    /// organisational aid (search / filter chips alongside the
7996    /// id-prefix grouping); the scheduler never reads it, so any
7997    /// string is allowed and it carries no firing semantics. A
7998    /// schedule's own tags are independent of its job's: the same job
7999    /// may back a `weekly` maintenance schedule and a `canary` rollout
8000    /// schedule. Empty by default and `skip_serializing_if`-elided per
8001    /// the #492 gradual-upgrade wire rule.
8002    #[serde(default, skip_serializing_if = "Vec::is_empty")]
8003    pub tags: Vec<String>,
8004    /// GitOps provenance (#695) — see [`RepoOrigin`]. Stamped by
8005    /// `kanade schedule create` when the source YAML lives inside a Git
8006    /// work tree, so the SPA renders the schedule read-only and points
8007    /// edits back at the repo (SPEC design principle #3: 設定駆動 YAML +
8008    /// Git), parity with a job's [`Manifest::origin`]. `None` for
8009    /// SPA-born schedules and ones applied from outside any repo. Purely
8010    /// informational — the scheduler never reads it. New field ⇒ #492
8011    /// wire rule (`default` + `skip_serializing_if`).
8012    #[serde(default, skip_serializing_if = "Option::is_none")]
8013    pub origin: Option<RepoOrigin>,
8014}
8015
8016impl Schedule {
8017    /// Every valid top-level key on a Schedule YAML/JSON document —
8018    /// this struct's own fields PLUS the fields of the
8019    /// `#[serde(flatten)] plan: FanoutPlan`. The strict create
8020    /// boundary needs this because serde's flatten buffering hides
8021    /// unknown top-level keys from `serde_ignored`, so a typo like
8022    /// `jiter:` or `enabledd:` would otherwise be silently dropped
8023    /// (#924). Kept in sync with the field list by
8024    /// `schedule_top_level_keys_cover_serialized_fields`.
8025    pub const TOP_LEVEL_KEYS: &'static [&'static str] = &[
8026        // Schedule's own fields:
8027        "id",
8028        "when",
8029        "job_id",
8030        "active",
8031        "constraints",
8032        "on_failure",
8033        "tz",
8034        "starting_deadline",
8035        "runs_on",
8036        "enabled",
8037        "tags",
8038        "origin",
8039        // flattened FanoutPlan:
8040        "target",
8041        "rollout",
8042        "jitter",
8043        "deadline_at",
8044    ];
8045}
8046
8047impl crate::strict::StrictSchema for Schedule {
8048    fn strict_top_level_keys() -> Option<&'static [&'static str]> {
8049        Some(Self::TOP_LEVEL_KEYS)
8050    }
8051}
8052
8053/// Manifest has no `#[serde(flatten)]` field, so `serde_ignored`
8054/// already catches every top-level typo — the default (`None`) is
8055/// correct.
8056impl crate::strict::StrictSchema for Manifest {}
8057
8058/// View likewise has no flattened field.
8059impl crate::strict::StrictSchema for View {}
8060
8061/// GroupDef likewise has no flattened field.
8062impl crate::strict::StrictSchema for GroupDef {}
8063
8064/// v0.23 — where the cron tick fires from.
8065#[derive(
8066    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
8067)]
8068#[serde(rename_all = "snake_case")]
8069pub enum RunsOn {
8070    /// Backend's central scheduler ticks and publishes Commands to
8071    /// NATS. Historical default, what every pre-v0.23 schedule
8072    /// uses. Agent offline ⇒ Command queued in STREAM_EXEC; agent
8073    /// reconnects ⇒ catch-up via [`command_replay`](crate)
8074    /// (see kanade-agent's command_replay module).
8075    #[default]
8076    Backend,
8077    /// Each targeted agent runs the cron tick locally. Survives
8078    /// broker / WAN outages. Best for laptops / mobile devices that
8079    /// roam off the corporate network. Agent must be online for the
8080    /// initial schedule + job-catalog pull, but once cached the
8081    /// agent fires the script standalone.
8082    Agent,
8083}
8084
8085/// Per-pc/per-target dedup semantics for a [`Schedule`] (v0.19).
8086#[derive(
8087    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
8088)]
8089#[serde(rename_all = "snake_case")]
8090pub enum ExecMode {
8091    /// Fire on every cron tick at the whole target. Historical
8092    /// (pre-v0.19) behavior; no dedup.
8093    #[default]
8094    EveryTick,
8095    /// Fire at each pc until that pc succeeds; then skip it until
8096    /// the optional cooldown elapses (or forever if no cooldown).
8097    /// Use for kitting / first-boot / per-pc compliance checks.
8098    OncePerPc,
8099    /// Fire at the whole target until **any** pc succeeds; then
8100    /// skip the whole target until the optional cooldown elapses
8101    /// (or forever if no cooldown). Use for "one delegate is
8102    /// enough" tasks like license check-in.
8103    OncePerTarget,
8104    /// Like [`OncePerPc`](ExecMode::OncePerPc), but the "already
8105    /// succeeded ⇒ skip" check is scoped to the CURRENT manifest
8106    /// version: a pc whose only successful run recorded an OLDER
8107    /// manifest version re-fires so the new version reaches it. Bumping
8108    /// the job's YAML `version` is the redistribution trigger. Plain
8109    /// `OncePerPc` (kitting) is version-blind — a pc that ever succeeded
8110    /// is skipped forever; this mode re-arms per version. per_pc only —
8111    /// `Schedule::validate` rejects `per_target: once_per_version`.
8112    OncePerPcVersion,
8113    /// #418 OS-native event trigger (`when: { on: [...] }`). There is
8114    /// no cron — the agent fires it from an OS event source (boot /
8115    /// session-change), not a tick — so the scheduler skips
8116    /// `tokio-cron` registration for it. Each event occurrence fires
8117    /// once, gated by the standard freeze / active / window /
8118    /// skip_dates checks.
8119    Event,
8120}
8121
8122/// #418 Phase 1 — the single "when does this fire" axis.
8123///
8124/// Replaces the old `cron` + `mode` + `cooldown` trio whose
8125/// interactions were implicit (cron doubled as both a real
8126/// time-of-day trigger and a reconcile poll period; contradictory
8127/// combinations silently no-opped). Two shapes:
8128///
8129/// * **reconcile** (`per_pc` / `per_target`) — desired-state: "each
8130///   pc (or one delegate) should have run this within `every`".
8131///   The poll period is system-generated ([`POLL_CRON`], every
8132///   minute) and no longer the operator's concern.
8133/// * **calendar** (`{ at, days }`) — a wall-clock time trigger
8134///   (#418 Phase 2, replacing the old raw-cron escape hatch). Fires
8135///   the whole target at the given time, no dedup. `at: "09:00"` +
8136///   `days` repeats; `at: "2026-06-10 09:00"` (a date+time) fires
8137///   exactly once. Evaluated in the schedule's top-level `tz`.
8138#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8139#[serde(rename_all = "snake_case")]
8140pub enum When {
8141    /// Fire at each targeted pc: `once` (kitting — succeed once,
8142    /// skip forever, forever catching brand-new / re-imaged pcs)
8143    /// or `{ every: <humantime> }` (patrol — re-arm per pc after
8144    /// the interval).
8145    PerPc(PerPolicy),
8146    /// Fire until **any** one pc of the target succeeds, then skip
8147    /// the whole target (`once`) or re-arm after `every`. Needs
8148    /// fleet-wide completion data, so it is backend-only —
8149    /// `runs_on: agent` + `per_target` is rejected by
8150    /// [`Schedule::validate`].
8151    PerTarget(PerPolicy),
8152    /// Calendar time trigger: `{ at: "09:00", days: [mon-fri] }`
8153    /// (repeating) or `{ at: "2026-06-10 09:00" }` (one-shot). Fires
8154    /// the whole target at that wall-clock time in the schedule's
8155    /// `tz` — no dedup, no cooldown.
8156    Calendar(CalendarSpec),
8157    /// #418 OS-native event trigger: `when: { on: [startup, logon] }`.
8158    /// Fires when the agent observes the listed OS event(s) rather than
8159    /// on a clock — there is no cron. `runs_on: agent` only (the agent
8160    /// owns the event source); [`Schedule::validate`] rejects it on
8161    /// `backend` and rejects an empty list. Each event occurrence fires
8162    /// once, gated by the same freeze / active / `constraints.window` /
8163    /// `skip_dates` checks as the cron path. `startup` fires once per OS
8164    /// boot (deduped via the host boot time); a `starting_deadline`, if
8165    /// set, limits it to "agent came up within that long after boot".
8166    On(Vec<OnTrigger>),
8167}
8168
8169/// An OS event the agent can fire a schedule on (#418 `when: { on }`).
8170#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash)]
8171#[serde(rename_all = "snake_case")]
8172pub enum OnTrigger {
8173    /// Once per OS boot (the agent's first run for that boot). Catches
8174    /// freshly-imaged / reinstalled hosts at their next startup.
8175    Startup,
8176    /// On an interactive-session user logon — console, RDP, or
8177    /// auto-logon (Windows `WTS_SESSION_LOGON`). Does not fire for
8178    /// service / network / batch logons (no interactive session).
8179    Logon,
8180    /// When the workstation is locked (Win+L / idle lock; Windows
8181    /// `WTS_SESSION_LOCK`). Use for step-away compliance / cleanup.
8182    Lock,
8183    /// When the workstation is unlocked — the user returns to a locked
8184    /// session (Windows `WTS_SESSION_UNLOCK`). Use to re-check
8185    /// compliance / refresh state when work resumes.
8186    Unlock,
8187    /// When the host's network changes — IP address table change on
8188    /// connect / disconnect / DHCP renew / VPN / Wi-Fi roam (Windows
8189    /// `NotifyAddrChange`). Debounced agent-side (a burst of changes
8190    /// from one transition fires once after the network settles), so
8191    /// use it for "re-check connectivity / re-register on network move"
8192    /// rather than expecting one fire per raw adapter event.
8193    ///
8194    /// IPv4 only: `NotifyAddrChange` watches the IPv4 address table, so a
8195    /// transition that touches only IPv6 addresses won't fire. In practice
8196    /// dual-stack networks change both tables together, but a pure-IPv6
8197    /// move (e.g. an IPv6-only Wi-Fi roam) is not detected.
8198    NetworkChange,
8199}
8200
8201/// Calendar time trigger (#418 Phase 2). `at` is either a time of
8202/// day (`"HH:MM"`, repeating — combine with `days`) or a full
8203/// date+time (`"YYYY-MM-DD HH:MM"`, a one-shot that fires once and
8204/// never again). Evaluated in the schedule's top-level `tz`.
8205#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8206pub struct CalendarSpec {
8207    /// `"HH:MM"` (24h) for a repeating trigger, or
8208    /// `"YYYY-MM-DD HH:MM"` (hyphen / slash / `T` separators all
8209    /// accepted) for a one-shot. Parsed lazily —
8210    /// [`Schedule::validate`] rejects garbage at create time.
8211    pub at: String,
8212    /// Day-of-week filter for a time-of-day `at`: `["mon-fri"]`,
8213    /// `["mon","wed","fri"]`, … (passed verbatim to the cron DOW
8214    /// field, so ranges and names both work). An **nth-weekday**
8215    /// `["tue#2"]` fires only on the 2nd Tuesday of each month
8216    /// ("Patch Tuesday"); the ordinal is `1..5`. A **last-weekday**
8217    /// `["friL"]` fires only on the last Friday of each month (handy
8218    /// for monthly maintenance). Empty = every day. Must be empty
8219    /// when `at` carries a date (the date already pins the day).
8220    #[serde(default, skip_serializing_if = "Vec::is_empty")]
8221    pub days: Vec<String>,
8222}
8223
8224/// Parsed `CalendarSpec.at`: the wall-clock minute/hour, plus the
8225/// date for a one-shot (`None` = repeating time-of-day).
8226struct ParsedAt {
8227    minute: u32,
8228    hour: u32,
8229    date: Option<chrono::NaiveDate>,
8230}
8231
8232impl CalendarSpec {
8233    /// Parse `at`: a date+time (`YYYY-MM-DD HH:MM`, hyphen / slash /
8234    /// `T` separators) is a one-shot; a bare `HH:MM` is repeating.
8235    fn parse_at(&self) -> Result<ParsedAt, String> {
8236        use chrono::Timelike;
8237        let s = self.at.trim();
8238        for fmt in ["%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y/%m/%d %H:%M"] {
8239            if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, fmt) {
8240                return Ok(ParsedAt {
8241                    minute: dt.minute(),
8242                    hour: dt.hour(),
8243                    date: Some(dt.date()),
8244                });
8245            }
8246        }
8247        if let Ok(t) = chrono::NaiveTime::parse_from_str(s, "%H:%M") {
8248            return Ok(ParsedAt {
8249                minute: t.minute(),
8250                hour: t.hour(),
8251                date: None,
8252            });
8253        }
8254        Err(format!(
8255            "when.at: unparseable '{}' (want HH:MM or YYYY-MM-DD HH:MM)",
8256            self.at
8257        ))
8258    }
8259
8260    /// Pre-flight check on the `days` tokens so a bad day name gives
8261    /// a `when.days:`-scoped error instead of croner's confusing
8262    /// "when.at lowered to invalid cron" (claude #432 review). Each
8263    /// token is a day name (`mon`..`sun`), a numeric DOW (`0`..`7`),
8264    /// `*`, a `-` range of those, an **nth-weekday** like `tue#2`
8265    /// (2nd Tuesday of the month — "Patch Tuesday"), or a
8266    /// **last-weekday** like `friL` (last Friday of the month).
8267    fn validate_days(&self) -> Result<(), String> {
8268        const NAMES: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
8269        let is_day = |p: &str| NAMES.contains(&p) || p.parse::<u8>().is_ok_and(|n| n <= 7);
8270        for tok in &self.days {
8271            // Report the whole token on a malformed range like `mon-`
8272            // (which would otherwise split to a cryptic empty part —
8273            // claude #432 follow-up).
8274            let invalid = |reason: &str| {
8275                Err(format!(
8276                    "when.days: invalid day token '{tok}' ({reason}; \
8277                     want mon..sun, 0-7, a range like mon-fri, an nth-weekday \
8278                     like tue#2, a last-weekday like friL, or *)"
8279                ))
8280            };
8281            // #418: nth-weekday suffix (`tue#2` = 2nd Tuesday). Croner
8282            // accepts `<dow>#<n>` (n = 1..5) in the DOW field, and
8283            // `to_cron` passes the token through verbatim, so the
8284            // engine fires only on that occurrence. It's a single
8285            // weekday + ordinal — not combinable with a range.
8286            if let Some((day_part, nth_part)) = tok.split_once('#') {
8287                // Normalize once and use `d` consistently (gemini #547);
8288                // the outer `invalid` already echoes the raw `tok`.
8289                let d = day_part.trim().to_ascii_lowercase();
8290                if d.contains('-') || !is_day(&d) {
8291                    return invalid("the part before # must be a single weekday");
8292                }
8293                match nth_part.trim().parse::<u8>() {
8294                    Ok(n) if (1..=5).contains(&n) => {}
8295                    _ => return invalid("the # ordinal must be 1..5 (e.g. tue#2 = 2nd Tuesday)"),
8296                }
8297                continue;
8298            }
8299            // #418: last-weekday suffix (`friL` = last Friday of the
8300            // month — the monthly-maintenance sibling of Patch Tuesday).
8301            // Croner accepts `<dow>L` in the DOW field with verified
8302            // last-<dow>-of-month semantics, and `to_cron` passes it
8303            // through verbatim. A single weekday + `L` — bare `L` and
8304            // ranges are rejected (croner would read bare `L` as
8305            // Saturday, which is a confusing footgun).
8306            if let Some(day_part) = tok.strip_suffix(['L', 'l']) {
8307                // No `.trim()`: a cron DOW token can't carry internal
8308                // whitespace, so `"fri L"` must be *rejected* here (its
8309                // strip leaves `"fri "`, and `is_day` catches the space)
8310                // rather than trimmed into a clean `"fri"` that then
8311                // produces a malformed `fri L` cron downstream and a
8312                // confusing croner error (gemini #560).
8313                let d = day_part.to_ascii_lowercase();
8314                if d.is_empty() {
8315                    return invalid("`L` (last-weekday) needs a weekday before it, e.g. friL");
8316                }
8317                if d.contains('-') || !is_day(&d) {
8318                    return invalid(
8319                        "the part before L must be a single weekday (e.g. friL = last Friday)",
8320                    );
8321                }
8322                continue;
8323            }
8324            for part in tok.split('-') {
8325                let p = part.trim().to_ascii_lowercase();
8326                if p.is_empty() {
8327                    return invalid("empty range bound");
8328                }
8329                if p != "*" && !is_day(&p) {
8330                    return invalid(&format!("'{part}' is not a day"));
8331                }
8332            }
8333        }
8334        Ok(())
8335    }
8336
8337    /// For a one-shot (`at` carries a date), the absolute instant it
8338    /// fires in `tz`. `None` for a repeating calendar. Used to warn
8339    /// about a one-shot whose date is already in the past (it would
8340    /// never fire).
8341    pub fn oneshot_instant(&self, tz: ScheduleTz) -> Option<chrono::DateTime<chrono::Utc>> {
8342        let p = self.parse_at().ok()?;
8343        let date = p.date?;
8344        let naive = date.and_hms_opt(p.hour, p.minute, 0)?;
8345        tz.naive_to_utc(naive)
8346    }
8347
8348    /// The wall-clock time-of-day this calendar fires at (`None` if
8349    /// `at` is unparseable — validate() guards that). Used to detect
8350    /// a calendar whose fire time can never fall inside its
8351    /// `constraints.window` (claude #452 review).
8352    pub fn fire_time(&self) -> Option<chrono::NaiveTime> {
8353        let p = self.parse_at().ok()?;
8354        chrono::NaiveTime::from_hms_opt(p.hour, p.minute, 0)
8355    }
8356
8357    /// Lower to the cron string the scheduler engine runs. Repeating
8358    /// → 6-field `0 {min} {hour} * * {dow}`; one-shot → 7-field
8359    /// `0 {min} {hour} {day} {month} * {year}` (a past year never
8360    /// fires — that's what makes it one-shot).
8361    fn to_cron(&self) -> Result<String, String> {
8362        use chrono::Datelike;
8363        let ParsedAt { minute, hour, date } = self.parse_at()?;
8364        match date {
8365            Some(d) => {
8366                if !self.days.is_empty() {
8367                    return Err(
8368                        "when.at with a date is a one-shot and cannot be combined with days".into(),
8369                    );
8370                }
8371                Ok(format!(
8372                    "0 {minute} {hour} {} {} * {}",
8373                    d.day(),
8374                    d.month(),
8375                    d.year()
8376                ))
8377            }
8378            None => {
8379                let dow = if self.days.is_empty() {
8380                    "*".to_string()
8381                } else {
8382                    self.validate_days()?;
8383                    self.days.join(",")
8384                };
8385                Ok(format!("0 {minute} {hour} * * {dow}"))
8386            }
8387        }
8388    }
8389}
8390
8391/// The timezone a schedule's wall-clock fields (`when.at`,
8392/// `active.{from,until}`) are evaluated in (#418 Phase 2).
8393#[derive(
8394    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
8395)]
8396#[serde(rename_all = "snake_case")]
8397pub enum ScheduleTz {
8398    /// The running host's local timezone — the agent's for
8399    /// `runs_on: agent`, the backend server's otherwise. Default.
8400    #[default]
8401    Local,
8402    /// UTC — for timezone-independent schedules.
8403    Utc,
8404}
8405
8406impl ScheduleTz {
8407    /// Interpret a naive (zoneless) datetime as being in this tz and
8408    /// convert to UTC. On a DST *fold* (the local time occurs twice
8409    /// when clocks go back) we pick `.earliest()` rather than
8410    /// rejecting it; `None` is reserved for a true DST *gap* (a local
8411    /// time that never exists). `Utc` is fixed-offset so neither ever
8412    /// happens; `Local` is whatever timezone the running host is set
8413    /// to and *can* hit a gap/fold on any DST-observing host — not
8414    /// just the JST we run today (gemini + claude #432 review).
8415    fn naive_to_utc(self, naive: chrono::NaiveDateTime) -> Option<chrono::DateTime<chrono::Utc>> {
8416        use chrono::TimeZone;
8417        match self {
8418            ScheduleTz::Utc => Some(chrono::DateTime::from_naive_utc_and_offset(
8419                naive,
8420                chrono::Utc,
8421            )),
8422            ScheduleTz::Local => chrono::Local
8423                .from_local_datetime(&naive)
8424                .earliest()
8425                .map(|dt| dt.with_timezone(&chrono::Utc)),
8426        }
8427    }
8428
8429    /// The wall-clock time-of-day `now` reads as in this tz — used by
8430    /// [`Constraints::allows`] to test a maintenance window
8431    /// (#418 Phase 3). `Utc` is the naive UTC time; `Local` is the
8432    /// running host's local time.
8433    fn wall_time(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveTime {
8434        match self {
8435            ScheduleTz::Utc => now.time(),
8436            ScheduleTz::Local => now.with_timezone(&chrono::Local).time(),
8437        }
8438    }
8439
8440    /// The wall-clock *date* `now` reads as in this tz — used by
8441    /// [`Constraints::allows`] to test `skip_dates` (#418 holiday
8442    /// exclusion). Same tz semantics as [`Self::wall_time`].
8443    fn wall_date(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveDate {
8444        match self {
8445            ScheduleTz::Utc => now.date_naive(),
8446            ScheduleTz::Local => now.with_timezone(&chrono::Local).date_naive(),
8447        }
8448    }
8449
8450    /// Stable lowercase wire/display label (`local` / `utc`) — matches
8451    /// the serde `snake_case` representation. Used for the preview
8452    /// response's `tz` field so the JSON shape isn't coupled to the
8453    /// `Debug` repr (claude #578 review).
8454    pub fn as_str(self) -> &'static str {
8455        match self {
8456            ScheduleTz::Local => "local",
8457            ScheduleTz::Utc => "utc",
8458        }
8459    }
8460}
8461
8462impl std::fmt::Display for ScheduleTz {
8463    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8464        f.write_str(self.as_str())
8465    }
8466}
8467
8468/// `once` / `once_per_version` / `{ every: <humantime> }` — shared by
8469/// `per_pc` / `per_target`. Untagged so the YAML stays the bare keyword
8470/// or a one-key map, nothing more ceremonial. `once_per_version` is
8471/// per_pc + backend only (see the variant doc and `Schedule::validate`).
8472#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8473#[serde(untagged)]
8474pub enum PerPolicy {
8475    /// The bare string `once`: succeed once, then skip permanently
8476    /// (cooldown = infinity), version-blind.
8477    Once(OnceLiteral),
8478    /// The bare string `once_per_version`: succeed once *per manifest
8479    /// version*, then skip until the job's YAML `version` changes. Like
8480    /// `once` but re-arms each pc when the version it succeeded at is no
8481    /// longer current — the version-aware redistribution shape. per_pc
8482    /// only (`Schedule::validate` rejects it on `per_target`).
8483    OncePerVersion(OncePerVersionLiteral),
8484    /// Re-arm after the humantime interval, e.g. `{ every: 6h }`.
8485    Every(EverySpec),
8486}
8487
8488/// Single-variant enum so serde accepts exactly the string `once`
8489/// (a free-form `String` would swallow typos like `onec`).
8490#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
8491#[serde(rename_all = "snake_case")]
8492pub enum OnceLiteral {
8493    Once,
8494}
8495
8496/// Single-variant enum so serde accepts exactly the string
8497/// `once_per_version` (mirrors [`OnceLiteral`]'s typo-catching). The
8498/// distinct literal — rather than a bool field on `once` — keeps the
8499/// ergonomic bare-string surface (`per_pc: once_per_version`).
8500#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
8501#[serde(rename_all = "snake_case")]
8502pub enum OncePerVersionLiteral {
8503    OncePerVersion,
8504}
8505
8506/// `{ every: <humantime> }`. Standalone struct (not an inline
8507/// struct variant). `{ evry: 6h }` still fails to parse (the
8508/// required `every` key is missing), and the create boundaries
8509/// reject the unknown `evry` via [`crate::strict`] with its path —
8510/// while agents reading a future writer's extra fields tolerate
8511/// them (#492).
8512#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8513pub struct EverySpec {
8514    /// Humantime interval (`10m`, `6h`, `1d`...). Parsed lazily —
8515    /// [`Schedule::validate`] rejects garbage at create time.
8516    pub every: String,
8517}
8518
8519impl PerPolicy {
8520    /// The cooldown this policy lowers to: `once` = `None`
8521    /// (permanent skip), `every` = the interval.
8522    fn cooldown(&self) -> Option<String> {
8523        match self {
8524            // Both `once` shapes lower to "no time-based re-arm". The
8525            // version-aware re-arm for `once_per_version` is not a
8526            // cooldown — it is the version filter the scheduler applies
8527            // to the completion set, so the cooldown stays None here.
8528            PerPolicy::Once(_) | PerPolicy::OncePerVersion(_) => None,
8529            PerPolicy::Every(EverySpec { every }) => Some(every.clone()),
8530        }
8531    }
8532}
8533
8534impl std::fmt::Display for When {
8535    /// Operator-facing one-liner (`per_pc once` / `per_pc every 6h`
8536    /// / `at 09:00 [mon-fri]` / `at 2026-06-10 09:00`) for log
8537    /// lines, audit payloads and the API's `ScheduleSummary`.
8538    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8539        let policy = |p: &PerPolicy| match p {
8540            PerPolicy::Once(_) => "once".to_string(),
8541            PerPolicy::OncePerVersion(_) => "once_per_version".to_string(),
8542            PerPolicy::Every(EverySpec { every }) => format!("every {every}"),
8543        };
8544        match self {
8545            When::PerPc(p) => write!(f, "per_pc {}", policy(p)),
8546            When::PerTarget(p) => write!(f, "per_target {}", policy(p)),
8547            When::Calendar(c) if c.days.is_empty() => write!(f, "at {}", c.at),
8548            When::Calendar(c) => write!(f, "at {} [{}]", c.at, c.days.join(",")),
8549            When::On(triggers) => {
8550                let names: Vec<&str> = triggers.iter().map(|t| t.as_str()).collect();
8551                write!(f, "on [{}]", names.join(","))
8552            }
8553        }
8554    }
8555}
8556
8557impl OnTrigger {
8558    /// Lowercase wire/display label (matches the serde `snake_case`).
8559    pub fn as_str(self) -> &'static str {
8560        match self {
8561            OnTrigger::Startup => "startup",
8562            OnTrigger::Logon => "logon",
8563            OnTrigger::Lock => "lock",
8564            OnTrigger::Unlock => "unlock",
8565            OnTrigger::NetworkChange => "network_change",
8566        }
8567    }
8568}
8569
8570/// Optional validity window for a [`Schedule`] (#418 decision G).
8571/// Half-open `[from, until)`; either bound may be omitted. Bounds
8572/// are `YYYY-MM-DD` (= that day's 00:00 in the schedule's `tz`) or
8573/// full RFC3339 (offset is honored as-is, `tz` ignored). Kept as
8574/// strings so the JSON Schema the SPA editor consumes stays two
8575/// plain string fields, mirroring `jitter` / `starting_deadline`.
8576///
8577/// #418 Phase 2: bounds are evaluated in the schedule's top-level
8578/// `tz` (was UTC-only in Phase 1) so `tz: local` makes both the
8579/// calendar `at` AND the `active` window local — one consistent
8580/// timezone per schedule.
8581#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
8582pub struct Active {
8583    /// Dormant before this instant.
8584    #[serde(default, skip_serializing_if = "Option::is_none")]
8585    pub from: Option<String>,
8586    /// Dormant from this instant on (exclusive).
8587    #[serde(default, skip_serializing_if = "Option::is_none")]
8588    pub until: Option<String>,
8589}
8590
8591impl Active {
8592    /// `skip_serializing_if` helper — an empty window means "always
8593    /// active" and is omitted from the wire format entirely.
8594    pub fn is_empty(&self) -> bool {
8595        self.from.is_none() && self.until.is_none()
8596    }
8597
8598    /// Parse one bound: RFC3339 first (offset honored, `tz`
8599    /// ignored), then bare `YYYY-MM-DD` (00:00 in `tz`).
8600    pub fn parse_bound(s: &str, tz: ScheduleTz) -> Result<chrono::DateTime<chrono::Utc>, String> {
8601        if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
8602            return Ok(dt.with_timezone(&chrono::Utc));
8603        }
8604        if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
8605            let midnight = d.and_hms_opt(0, 0, 0).expect("00:00:00 is always valid");
8606            return tz.naive_to_utc(midnight).ok_or_else(|| {
8607                format!("active: bound '{s}' falls in a DST gap for the schedule's tz")
8608            });
8609        }
8610        Err(format!(
8611            "active: unparseable bound '{s}' (want YYYY-MM-DD or RFC3339)"
8612        ))
8613    }
8614
8615    /// Is `now` inside the window? Unparseable bounds are treated
8616    /// as absent here (fail-open) — [`Schedule::validate`] is the
8617    /// place that rejects them loudly; this runs on every tick and
8618    /// must never panic on a stale KV blob.
8619    pub fn contains(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
8620        let bound = |s: &Option<String>| s.as_deref().and_then(|s| Self::parse_bound(s, tz).ok());
8621        if bound(&self.from).is_some_and(|from| now < from) {
8622            return false;
8623        }
8624        if bound(&self.until).is_some_and(|until| now >= until) {
8625            return false;
8626        }
8627        true
8628    }
8629}
8630
8631/// Host-environment gate (#418 `constraints.require`). Fire only when
8632/// the target host is in the required state. Sensed **in-process by the
8633/// agent** (Win32), so it is `runs_on: agent` only — the backend cannot
8634/// read a target host's power/idle state ([`Schedule::validate`]
8635/// rejects it on `runs_on: backend`, symmetric with `when: { on }`).
8636///
8637/// Evaluated at fire time as a skip-this-tick gate (NOT in
8638/// [`Constraints::allows`], which stays pure for `preview`): a reconcile
8639/// cadence re-checks every minute (so it effectively defers until the
8640/// state is met — the intended pairing); a `calendar` fire that lands
8641/// while the state is unmet is simply missed, same as `window`. It is
8642/// therefore a *runtime* gate and does not appear in `preview`.
8643// No `Eq`: `cpu_below: Option<f64>` is only `PartialEq` (f64 is not Eq).
8644#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
8645pub struct Require {
8646    /// Fire only while on **AC power** (skip on battery). Reads
8647    /// `GetSystemPowerStatus`; an unknown/unreadable status is treated
8648    /// as not-on-AC (fail-closed — a restrictive gate must not fire
8649    /// when it can't confirm the condition). `false` (default) = no
8650    /// power requirement.
8651    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
8652    pub ac_power: bool,
8653    /// Fire only when the active console session has had **no keyboard /
8654    /// mouse input for at least this long** (humantime, e.g. `"10m"`) —
8655    /// "don't run while the user is actively working". Input-based
8656    /// (simpler than Task Scheduler's CPU/disk-aware idle). A
8657    /// headless / disconnected console (no interactive user) trivially
8658    /// satisfies it. `None` (default) = no idle requirement. Parsed
8659    /// lazily; [`Schedule::validate`] rejects garbage at create time.
8660    #[serde(default, skip_serializing_if = "Option::is_none")]
8661    pub idle: Option<String>,
8662    /// Fire only when the **whole-machine CPU usage is below this
8663    /// percent** (0–100; e.g. `20.0` = "system CPU < 20%") — "don't run
8664    /// while the box is busy". Reuses the agent's `host_perf` system CPU%
8665    /// sample (`sysinfo` mean over cores), so the reading is up to one
8666    /// `host_perf` cadence old (default 60s) — fine as a "generally
8667    /// busy?" proxy, and more accurate than a fresh one-shot read (CPU%
8668    /// needs two samples). An unavailable sample (host_perf not warmed
8669    /// up yet, or stale) is treated as "not below" (fail-closed — a
8670    /// restrictive gate must not fire when it can't confirm). `None`
8671    /// (default) = no CPU requirement. [`Schedule::validate`] rejects an
8672    /// out-of-range value at create time.
8673    #[serde(default, skip_serializing_if = "Option::is_none")]
8674    pub cpu_below: Option<f64>,
8675    /// Fire only when the host has **internet connectivity** (Windows
8676    /// `GetNetworkConnectivityHint` reports InternetAccess) — "don't run
8677    /// until online" for jobs that download / phone home. A captive
8678    /// portal (ConstrainedInternetAccess), LAN-only (LocalAccess), or
8679    /// unknown/unreadable state is treated as offline (fail-closed) — a
8680    /// portal would just fail a download, so we hold the run. For VPN /
8681    /// SASE / app-specific conditions, use a custom script gate (separate
8682    /// slice). `false` (default) = no network requirement.
8683    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
8684    pub network: bool,
8685}
8686
8687impl Require {
8688    /// `skip_serializing_if` helper for an embedded empty `require`.
8689    pub fn is_empty(&self) -> bool {
8690        !self.ac_power && self.idle.is_none() && self.cpu_below.is_none() && !self.network
8691    }
8692
8693    /// Parsed minimum-idle duration (`None` = no idle requirement, or an
8694    /// unparseable value — `validate` rejects the latter at create time).
8695    pub fn min_idle(&self) -> Option<std::time::Duration> {
8696        self.idle
8697            .as_deref()
8698            .and_then(|s| humantime::parse_duration(s.trim()).ok())
8699    }
8700
8701    /// First unparseable field for create-time rejection (mirrors
8702    /// [`Constraints::bad_skip_date`]).
8703    pub fn bad_idle(&self) -> Option<String> {
8704        self.idle.as_deref().and_then(|s| {
8705            humantime::parse_duration(s.trim())
8706                .err()
8707                .map(|e| format!("constraints.require.idle: invalid duration '{s}': {e}"))
8708        })
8709    }
8710}
8711
8712/// Host-environment state sensed by the agent, fed to [`require_met`].
8713/// A named struct (not positional args) so the growing set of sensed
8714/// signals — several of them `bool` — can't be transposed at a call
8715/// site. The Win32 sensing lives in `kanade-agent::env_gate`.
8716#[derive(Debug, Clone, Copy, Default)]
8717pub struct EnvState {
8718    /// Is the host on AC power (`false` if on battery or unreadable).
8719    pub ac_online: bool,
8720    /// How long the console has been idle (`None` = couldn't determine).
8721    pub idle: Option<std::time::Duration>,
8722    /// Whole-machine CPU usage 0–100 (`None` = no sample yet).
8723    pub cpu_pct: Option<f64>,
8724    /// Does the host have internet connectivity (`false` if offline /
8725    /// LAN-only / unreadable).
8726    pub network_up: bool,
8727}
8728
8729/// Pure env-gate decision (#418 `constraints.require`). The Win32
8730/// sensing lives in the agent (`kanade-agent::env_gate`); this is the
8731/// testable core, fed the already-sensed [`EnvState`]. Deliberately a
8732/// free fn (not folded into [`Constraints::allows`]) so `allows` stays
8733/// pure and `preview` never evaluates a runtime gate. Each set
8734/// requirement is a restrictive AND: any unmet (or unknown) gate skips.
8735pub fn require_met(req: &Require, env: &EnvState) -> bool {
8736    if req.ac_power && !env.ac_online {
8737        return false;
8738    }
8739    if let Some(min) = req.min_idle() {
8740        match env.idle {
8741            Some(d) if d >= min => {}
8742            _ => return false,
8743        }
8744    }
8745    if let Some(max) = req.cpu_below {
8746        match env.cpu_pct {
8747            Some(p) if p < max => {}
8748            _ => return false,
8749        }
8750    }
8751    if req.network && !env.network_up {
8752        return false;
8753    }
8754    true
8755}
8756
8757/// [`Active`] decides *over what date range* a schedule is live,
8758/// `Constraints` decides *when, within an active period,* a fire is
8759/// allowed: `window` (a maintenance time-of-day window),
8760/// `max_concurrent` (a fleet-wide running-instance cap), `skip_dates`
8761/// (holiday exclusion) and `require` (host-environment gates, agent-only
8762/// — see [`Require`]).
8763// No `Eq`: contains `require: Option<Require>` which holds an f64.
8764#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
8765pub struct Constraints {
8766    /// `"HH:MM-HH:MM"` wall-clock window (evaluated in the schedule's
8767    /// `tz`). Fires outside it are skipped — mainly for reconcile
8768    /// cadences ("patrol every 6h, but only fire overnight") and
8769    /// daytime change-freezes. `start > end` crosses midnight
8770    /// (`"22:00-05:00"` = 22:00 through 05:00 next morning). Parsed
8771    /// lazily; [`Schedule::validate`] rejects garbage at create time.
8772    #[serde(default, skip_serializing_if = "Option::is_none")]
8773    pub window: Option<String>,
8774    /// Fleet-wide cap on how many instances of this schedule's job may
8775    /// run **at the same time** (#418 "同時実行ハード上限"). The
8776    /// backend scheduler counts the job's still-in-flight runs
8777    /// (`execution_results.finished_at IS NULL`) each tick and only
8778    /// dispatches to as many remaining pcs as there are free slots —
8779    /// a rolling window that refills as runs complete. Useful for
8780    /// disk/CPU/network-heavy jobs you don't want hammering the whole
8781    /// fleet at once.
8782    ///
8783    /// **Backend-only** (it needs a central counter): combining it
8784    /// with `runs_on: agent` is rejected by [`Schedule::validate`]
8785    /// (#418 decision E — "中央上限には中央が要る"). Most meaningful
8786    /// for `per_pc` reconcile cadences, where the poll re-ticks and
8787    /// refills slots. `None` (default) = no cap.
8788    #[serde(default, skip_serializing_if = "Option::is_none")]
8789    pub max_concurrent: Option<u32>,
8790    /// Calendar dates the schedule must **not** fire on — holidays,
8791    /// blackout days, one-off freeze dates (#418 "祝日除外"). Each is
8792    /// `YYYY-MM-DD`, evaluated as a wall-clock date in the schedule's
8793    /// `tz`. Applies to every `when` shape (a reconcile cadence skips
8794    /// the whole day; a calendar fire landing on the date is
8795    /// suppressed) and is honored by both the live scheduler and
8796    /// `preview`, since both gate on [`Constraints::allows`]. Empty
8797    /// (default) = no skips. Operator-supplied: there is no built-in
8798    /// holiday calendar — list the dates you care about. Parsed lazily;
8799    /// [`Schedule::validate`] rejects a malformed date at create time.
8800    #[serde(default, skip_serializing_if = "Vec::is_empty")]
8801    pub skip_dates: Vec<String>,
8802    /// Host-environment gate (#418): fire only when the target host is
8803    /// in the required state (on AC power, idle). Agent-sensed at fire
8804    /// time, `runs_on: agent` only. See [`Require`]. `None` (default) =
8805    /// no environment requirement.
8806    #[serde(default, skip_serializing_if = "Option::is_none")]
8807    pub require: Option<Require>,
8808}
8809
8810impl Constraints {
8811    /// `skip_serializing_if` helper — empty constraints are omitted
8812    /// from the wire format entirely.
8813    pub fn is_empty(&self) -> bool {
8814        self.window.is_none()
8815            && self.max_concurrent.is_none()
8816            && self.skip_dates.is_empty()
8817            && self.require.as_ref().is_none_or(Require::is_empty)
8818    }
8819
8820    /// The first unparseable `skip_dates` entry, if any — the
8821    /// scheduler logs it at register time so a fail-closed
8822    /// (never-firing) schedule from a hand-edited KV blob is
8823    /// diagnosable, mirroring [`Schedule::bad_window`].
8824    pub fn bad_skip_date(&self) -> Option<String> {
8825        self.skip_dates.iter().find_map(|s| {
8826            chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d")
8827                .err()
8828                .map(|e| format!("constraints.skip_dates: invalid date '{s}': {e}"))
8829        })
8830    }
8831
8832    /// Parse `"HH:MM-HH:MM"` into `(start, end)`. Equal bounds are an
8833    /// error (a zero-width or all-day window is ambiguous — write no
8834    /// window for "always").
8835    pub fn parse_window(s: &str) -> Result<(chrono::NaiveTime, chrono::NaiveTime), String> {
8836        let (a, b) = s
8837            .split_once('-')
8838            .ok_or_else(|| format!("constraints.window: '{s}' must be 'HH:MM-HH:MM'"))?;
8839        let parse = |part: &str| {
8840            chrono::NaiveTime::parse_from_str(part.trim(), "%H:%M")
8841                .map_err(|e| format!("constraints.window: invalid time '{}': {e}", part.trim()))
8842        };
8843        let (start, end) = (parse(a)?, parse(b)?);
8844        if start == end {
8845            return Err(format!(
8846                "constraints.window: start and end are equal ('{s}'); omit window for 'always'"
8847            ));
8848        }
8849        Ok((start, end))
8850    }
8851
8852    /// Is a fire allowed at `now` (evaluated in `tz`)? No window =
8853    /// always allowed. Half-open `[start, end)`; `start > end`
8854    /// crosses midnight.
8855    ///
8856    /// **Fail-closed** on an unparseable window (returns `false`,
8857    /// gemini #452 review): a window is a *restrictive* constraint
8858    /// (change-freeze / overnight-only), so a corrupt one must NOT
8859    /// silently allow fires during the restricted hours. Bad windows
8860    /// are rejected at create time by [`Schedule::validate`]; this
8861    /// only bites a hand-edited KV blob, where blocking is the safe
8862    /// direction. The scheduler warns at register time
8863    /// ([`Schedule::bad_window`]) so a stuck schedule is diagnosable.
8864    /// The tick path never panics regardless.
8865    pub fn allows(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
8866        // #418 holiday / blackout dates: never fire on a listed wall
8867        // date (in `tz`). Checked before the window since a skipped day
8868        // overrides any within-window allowance. Fail-closed on a
8869        // corrupt entry (same posture as `window`): a skip date is a
8870        // *restrictive* constraint, so a garbled one must not silently
8871        // re-enable fires — it blocks until fixed (`validate` rejects it
8872        // at create time; `bad_skip_date` lets the scheduler warn).
8873        if !self.skip_dates.is_empty() {
8874            let today = tz.wall_date(now);
8875            let blocked = self.skip_dates.iter().any(|s| {
8876                match chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d") {
8877                    Ok(d) => d == today,
8878                    Err(_) => true, // corrupt entry → fail-closed (block)
8879                }
8880            });
8881            if blocked {
8882                return false;
8883            }
8884        }
8885        match self.window.as_deref() {
8886            // No window → always allowed.
8887            None => true,
8888            // Window set: membership, or fail-closed if unparseable
8889            // (`window_contains` returns None for a corrupt window).
8890            Some(_) => self.window_contains(tz.wall_time(now)).unwrap_or(false),
8891        }
8892    }
8893
8894    /// Membership of a wall-clock time-of-day in the window. `None`
8895    /// when there is no window or it's unparseable (callers decide
8896    /// the failure direction). `start > end` crosses midnight.
8897    fn window_contains(&self, t: chrono::NaiveTime) -> Option<bool> {
8898        let (start, end) = Self::parse_window(self.window.as_deref()?).ok()?;
8899        Some(if start <= end {
8900            start <= t && t < end
8901        } else {
8902            t >= start || t < end
8903        })
8904    }
8905}
8906
8907/// What to do when a fire's script fails (#418 Phase 4 — the "高"
8908/// retry/backoff gap). Where [`Constraints`] gates *whether* a fire
8909/// happens, `OnFailure` decides what happens *after* one ran and
8910/// came back bad. Only `retry` so far; future `notify` / `disable`
8911/// would join the same namespace.
8912#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
8913pub struct OnFailure {
8914    /// Re-run the script in-process when it exits non-zero (or times
8915    /// out), up to a cap, with a fixed backoff between attempts.
8916    /// `None` (default) = no retry: a failed run is published as-is
8917    /// and (for reconcile cadences) simply re-fires on the next poll
8918    /// tick. See [`Retry`].
8919    #[serde(default, skip_serializing_if = "Option::is_none")]
8920    pub retry: Option<Retry>,
8921}
8922
8923impl OnFailure {
8924    /// `skip_serializing_if` helper — an empty policy is omitted from
8925    /// the wire format entirely.
8926    pub fn is_empty(&self) -> bool {
8927        self.retry.is_none()
8928    }
8929
8930    /// Lower the operator-facing `retry` (humantime backoff) onto the
8931    /// engine vocabulary the agent's executor runs on (backoff in
8932    /// whole seconds). Single seam shared by the backend command
8933    /// builder and the agent's local scheduler so the two stamp the
8934    /// same [`crate::wire::RetrySpec`] onto every Command. Returns
8935    /// `None` when there is no retry policy or the backoff is
8936    /// unparseable (validate() rejects the latter at create time;
8937    /// this stays fail-safe = "no retry" for a hand-edited KV blob
8938    /// rather than panicking on the fire path).
8939    pub fn lowered_retry(&self) -> Option<crate::wire::RetrySpec> {
8940        let r = self.retry.as_ref()?;
8941        let backoff_secs = humantime::parse_duration(&r.backoff).ok()?.as_secs();
8942        Some(crate::wire::RetrySpec {
8943            max: r.max,
8944            backoff_secs,
8945        })
8946    }
8947}
8948
8949/// Fixed-backoff retry policy (#418 Phase 4). `max` is the number of
8950/// *additional* attempts after the first run (so `max: 3` = up to 4
8951/// total executions); `backoff` is the humantime delay slept between
8952/// attempts. The retry happens fire-side (inside `kanade fire` /
8953/// `handle_command`) on every OS for the PoC — the Windows-native
8954/// "restart on failure" Task Scheduler path is deferred to the
8955/// native-delegation phase (#418 decision H).
8956#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8957pub struct Retry {
8958    /// Max additional attempts after the first failure. Bounded
8959    /// `1..=10` by [`Schedule::validate`] — a typo'd `max: 1000`
8960    /// with a short backoff would otherwise pin a flapping script in
8961    /// a tight loop for the whole window.
8962    pub max: u32,
8963    /// Humantime delay slept between attempts (`"10m"`, `"30s"`).
8964    pub backoff: String,
8965}
8966
8967/// Fleet-wide change-freeze (#418 Phase 5 — the "メンテナンス窓 /
8968/// 変更凍結" gap's global half). Where [`Constraints::window`] is a
8969/// *per-schedule* time-of-day gate, a `Freeze` is a *single, fleet-
8970/// global* "stop all automated change" switch the operator flips
8971/// during an incident or a year-end change-freeze. It lives in its
8972/// own KV singleton ([`crate::kv::KEY_FREEZE`]); when present and
8973/// active, both the backend scheduler and every agent's local
8974/// scheduler skip *every* fire.
8975///
8976/// Shapes:
8977/// * `{}` (no bounds) — frozen indefinitely until the operator
8978///   clears it (incident "big red button").
8979/// * `{ from, until }` — frozen only within `[from, until)`,
8980///   evaluated in `tz` (planned change-freeze; auto-thaws).
8981///
8982/// The KV key being *absent* means "not frozen" — so clearing the
8983/// freeze is a KV delete, and `is_active` only ever runs on a freeze
8984/// the operator actually set.
8985#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
8986pub struct Freeze {
8987    /// Frozen from this instant (RFC3339 or bare `YYYY-MM-DD` in
8988    /// `tz`). `None` ⇒ frozen from the beginning of time.
8989    #[serde(default, skip_serializing_if = "Option::is_none")]
8990    pub from: Option<String>,
8991    /// Thawed from this instant on, exclusive. `None` ⇒ frozen with
8992    /// no scheduled end (manual clear required).
8993    #[serde(default, skip_serializing_if = "Option::is_none")]
8994    pub until: Option<String>,
8995    /// Operator-supplied note surfaced on the freeze-skip log and the
8996    /// SPA banner ("year-end change freeze", "INC-1234"). Advisory.
8997    #[serde(default, skip_serializing_if = "Option::is_none")]
8998    pub reason: Option<String>,
8999    /// Timezone the bare-date bounds are evaluated in (RFC3339 bounds
9000    /// carry their own offset). Defaults to host-local like a
9001    /// schedule's `tz`.
9002    #[serde(default)]
9003    pub tz: ScheduleTz,
9004}
9005
9006impl Freeze {
9007    /// Is the fleet frozen at `now`? An empty window (`from`/`until`
9008    /// both absent) is frozen unconditionally; otherwise membership of
9009    /// `[from, until)` in `tz`. Half-open like [`Active::contains`],
9010    /// but **fails CLOSED** on an unparseable bound — a freeze is a
9011    /// safety switch, so a corrupt window (only reachable via a
9012    /// hand-edited KV blob; `validate` rejects it at set time) must
9013    /// mean "frozen", not "fire normally" (coderabbit #472). This is
9014    /// the one deliberate divergence from `active`'s fail-OPEN
9015    /// behaviour, where an unparseable bound dormant-skips a schedule.
9016    pub fn is_active(&self, now: chrono::DateTime<chrono::Utc>) -> bool {
9017        // Parse a bound; an unparseable one short-circuits the whole
9018        // check to `true` (frozen) via the closure's `None` sentinel
9019        // handled below.
9020        let bound = |s: &Option<String>| -> Result<Option<chrono::DateTime<chrono::Utc>>, ()> {
9021            match s.as_deref() {
9022                None => Ok(None),
9023                Some(raw) => Active::parse_bound(raw, self.tz).map(Some).map_err(|_| ()),
9024            }
9025        };
9026        let (from, until) = match (bound(&self.from), bound(&self.until)) {
9027            (Ok(f), Ok(u)) => (f, u),
9028            // Any corrupt bound → fail closed (frozen).
9029            _ => return true,
9030        };
9031        if from.is_some_and(|f| now < f) {
9032            return false;
9033        }
9034        if until.is_some_and(|u| now >= u) {
9035            return false;
9036        }
9037        true
9038    }
9039
9040    /// Reject unparseable bounds / `from >= until` at set time (the
9041    /// API + CLI counterpart to [`Schedule::validate`]).
9042    pub fn validate(&self) -> Result<(), String> {
9043        let from = self
9044            .from
9045            .as_deref()
9046            .map(|s| Active::parse_bound(s, self.tz))
9047            .transpose()
9048            .map_err(|e| e.replace("active:", "freeze:"))?;
9049        let until = self
9050            .until
9051            .as_deref()
9052            .map(|s| Active::parse_bound(s, self.tz))
9053            .transpose()
9054            .map_err(|e| e.replace("active:", "freeze:"))?;
9055        if let (Some(f), Some(u)) = (from, until) {
9056            if f >= u {
9057                return Err(format!(
9058                    "freeze.from ({}) must be strictly before freeze.until ({})",
9059                    self.from.as_deref().unwrap_or_default(),
9060                    self.until.as_deref().unwrap_or_default(),
9061                ));
9062            }
9063        }
9064        Ok(())
9065    }
9066}
9067
9068/// The system-generated poll cadence every reconcile-shaped `when`
9069/// lowers to. Operators never write this: the real inter-run
9070/// spacing is the `every` cooldown; this only bounds "how soon do
9071/// we notice somebody is due" (#418 decision B took the poll
9072/// period away from the operator).
9073pub const POLL_CRON: &str = "0 * * * * *";
9074
9075/// What a [`When`] lowers to — the exact (cron, mode, cooldown)
9076/// trio the pre-#418 engine ran on. Keeping the engine vocabulary
9077/// unchanged is what lets Phase 1 swap the operator surface without
9078/// touching the tick / dedup machinery.
9079pub struct Lowered {
9080    /// Cron handed to `tokio-cron-scheduler` — [`POLL_CRON`] for
9081    /// reconcile shapes, a 6/7-field cron for calendar shapes.
9082    pub cron: String,
9083    /// Dedup semantics for `decide_fire`.
9084    pub mode: ExecMode,
9085    /// Humantime re-arm interval (`None` = succeed once, skip
9086    /// forever).
9087    pub cooldown: Option<String>,
9088    /// Timezone to evaluate `cron` in (#418 Phase 2). The scheduler
9089    /// passes this to `Job::new_async_tz`. Reconcile shapes carry
9090    /// the schedule's tz too even though POLL_CRON is tz-agnostic,
9091    /// so the same value drives the `active`-window check.
9092    pub tz: ScheduleTz,
9093}
9094
9095impl Schedule {
9096    /// The error message if this schedule's `constraints.window` is
9097    /// set but unparseable, else `None`. The scheduler logs this at
9098    /// register time so a fail-closed (never-firing) schedule from a
9099    /// hand-edited KV blob is diagnosable (gemini #452 review).
9100    pub fn bad_window(&self) -> Option<String> {
9101        let w = self.constraints.window.as_deref()?;
9102        Constraints::parse_window(w).err()
9103    }
9104
9105    /// True when this is a `calendar` schedule whose fire time can
9106    /// never fall inside its `constraints.window` — the cron fires,
9107    /// the window check rejects it, and (firing only at that
9108    /// time-of-day) it effectively never runs. An easy misconfig to
9109    /// set up by accident; the scheduler warns at register time
9110    /// (claude #452 review). Reconcile shapes poll every minute, so
9111    /// they always catch the window opening and aren't affected.
9112    pub fn calendar_outside_window(&self) -> bool {
9113        let When::Calendar(c) = &self.when else {
9114            return false;
9115        };
9116        let Some(t) = c.fire_time() else {
9117            return false;
9118        };
9119        matches!(self.constraints.window_contains(t), Some(false))
9120    }
9121
9122    /// Up to `count` future instants this schedule will fire, as
9123    /// absolute UTC, strictly after `now` — the dry-run / preview
9124    /// surface (#418 "ドライラン / プレビュー"). Only **calendar**
9125    /// schedules have discrete fire times; reconcile shapes
9126    /// (`per_pc`/`per_target`) poll every minute gated by cooldown, so
9127    /// they return an empty vec and the caller describes the cadence
9128    /// instead. Occurrences outside the `active.{from,until}` window or
9129    /// the `constraints.window` are **skipped**, so the list reflects
9130    /// when the schedule will ACTUALLY run, not the raw cron ticks.
9131    /// Evaluated in the schedule's `tz`, exactly like the scheduler's
9132    /// `Job::new_async_tz`, and with the same croner config the
9133    /// scheduler / [`Schedule::validate`] use, so a preview can never
9134    /// disagree with a real fire. A schedule that can never fire (a
9135    /// calendar time wholly outside its window, a past one-shot,
9136    /// `enabled: false` is *not* considered here — callers gate on
9137    /// `enabled` separately) yields an empty vec.
9138    pub fn preview_fires(
9139        &self,
9140        now: chrono::DateTime<chrono::Utc>,
9141        count: usize,
9142    ) -> Vec<chrono::DateTime<chrono::Utc>> {
9143        use croner::parser::{CronParser, Seconds};
9144        if !matches!(self.when, When::Calendar(_)) {
9145            return Vec::new();
9146        }
9147        // Same lowering + croner config as `next_calendar_fire` and the
9148        // live scheduler, so a preview can never disagree with a real
9149        // fire. `preview_fires` adds the N-occurrence walk and the
9150        // active / window filtering on top of that single seam.
9151        let lowered = self.lowered();
9152        let Ok(cron) = CronParser::builder()
9153            .seconds(Seconds::Required)
9154            .dom_and_dow(true)
9155            .build()
9156            .parse(&lowered.cron)
9157        else {
9158            return Vec::new();
9159        };
9160        let accept = |utc: chrono::DateTime<chrono::Utc>| {
9161            self.active.contains(utc, self.tz) && self.constraints.allows(utc, self.tz)
9162        };
9163        match self.tz {
9164            ScheduleTz::Utc => Self::next_occurrences(&cron, now, count, accept),
9165            ScheduleTz::Local => {
9166                Self::next_occurrences(&cron, now.with_timezone(&chrono::Local), count, accept)
9167            }
9168        }
9169    }
9170
9171    /// Walk croner forward from `after` collecting up to `count`
9172    /// accepted occurrences (converted to UTC). Generic over the tz the
9173    /// cron is evaluated in so `preview_fires` can run it in either
9174    /// `Utc` or `Local` without duplicating the loop.
9175    fn next_occurrences<Tz>(
9176        cron: &croner::Cron,
9177        after: chrono::DateTime<Tz>,
9178        count: usize,
9179        accept: impl Fn(chrono::DateTime<chrono::Utc>) -> bool,
9180    ) -> Vec<chrono::DateTime<chrono::Utc>>
9181    where
9182        Tz: chrono::TimeZone,
9183    {
9184        // Bound the scan so an `active`/window dead-end (every future
9185        // tick rejected) can't spin forever: ~4096 raw ticks covers
9186        // >10y of a daily calendar while staying instant for croner.
9187        const SCAN_CAP: usize = 4096;
9188        let mut out = Vec::with_capacity(count.min(SCAN_CAP));
9189        let mut cursor = after;
9190        let mut scanned = 0usize;
9191        while out.len() < count && scanned < SCAN_CAP {
9192            scanned += 1;
9193            let Ok(next) = cron.find_next_occurrence(&cursor, false) else {
9194                break;
9195            };
9196            let utc = next.with_timezone(&chrono::Utc);
9197            if accept(utc) {
9198                out.push(utc);
9199            }
9200            // `find_next_occurrence(.., inclusive = false)` already
9201            // advances strictly past `cursor`, so handing it `next`
9202            // verbatim gets the following occurrence — no manual +1s
9203            // nudge (and `DateTime<Tz>` is `Copy`, so no clone).
9204            cursor = next;
9205        }
9206        out
9207    }
9208
9209    /// Lower the operator-facing `when` onto the engine vocabulary.
9210    /// Single seam shared by the backend scheduler and the agent's
9211    /// local scheduler so the two can never drift.
9212    pub fn lowered(&self) -> Lowered {
9213        let tz = self.tz;
9214        match &self.when {
9215            When::PerPc(p) => Lowered {
9216                cron: POLL_CRON.into(),
9217                // `once_per_version` re-arms each pc when the manifest
9218                // version changes; the scheduler keys that dedup on
9219                // `execution_results.version`. Plain `once` / `every`
9220                // stay version-blind.
9221                mode: match p {
9222                    PerPolicy::OncePerVersion(_) => ExecMode::OncePerPcVersion,
9223                    PerPolicy::Once(_) | PerPolicy::Every(_) => ExecMode::OncePerPc,
9224                },
9225                cooldown: p.cooldown(),
9226                tz,
9227            },
9228            When::PerTarget(p) => Lowered {
9229                cron: POLL_CRON.into(),
9230                mode: ExecMode::OncePerTarget,
9231                cooldown: p.cooldown(),
9232                tz,
9233            },
9234            // `to_cron` only fails on a malformed `at` (rejected by
9235            // validate() at create time). For a hand-edited KV blob
9236            // that slipped past, emit a deliberately-invalid cron so
9237            // register()'s Job::new_async_tz fails → warn+skip,
9238            // rather than firing at the wrong time.
9239            When::Calendar(c) => Lowered {
9240                cron: c
9241                    .to_cron()
9242                    .unwrap_or_else(|_| "# invalid calendar at".into()),
9243                mode: ExecMode::EveryTick,
9244                cooldown: None,
9245                tz,
9246            },
9247            // Event triggers have no cron — the agent fires them from an
9248            // OS event source. The `# event-trigger` cron is never
9249            // registered (the scheduler branches on `is_event()` first),
9250            // but keep it deliberately-invalid as a belt-and-suspenders
9251            // so a stray registration would fail rather than misfire.
9252            When::On(_) => Lowered {
9253                cron: "# event-trigger (no cron)".into(),
9254                mode: ExecMode::Event,
9255                cooldown: None,
9256                tz,
9257            },
9258        }
9259    }
9260
9261    /// True when this schedule fires from an OS event (`when: { on }`)
9262    /// rather than a clock — the agent skips `tokio-cron` registration
9263    /// for these and drives them from boot / session-change instead.
9264    pub fn is_event(&self) -> bool {
9265        matches!(self.when, When::On(_))
9266    }
9267
9268    /// The OS event triggers this schedule listens for, or `&[]` when it
9269    /// is not an event schedule.
9270    pub fn event_triggers(&self) -> &[OnTrigger] {
9271        match &self.when {
9272            When::On(t) => t,
9273            _ => &[],
9274        }
9275    }
9276
9277    /// The next absolute (UTC) time this schedule fires, or `None` when
9278    /// it has no discrete upcoming fire to preview.
9279    ///
9280    /// Used by the KLP `maintenance.list` preview ("what's about to
9281    /// happen on my PC", SPEC §2.1). Returns `None` for:
9282    ///
9283    /// - reconcile shapes (`per_pc` / `per_target`) — they lower to the
9284    ///   every-minute [`POLL_CRON`] and re-converge state continuously,
9285    ///   so "next fire" is always ~60s away and means nothing to a user
9286    ///   previewing upcoming maintenance;
9287    /// - a calendar schedule whose lowered cron won't parse (a
9288    ///   hand-edited KV blob that slipped past [`Schedule::validate`]);
9289    /// - a cron with no future occurrence.
9290    ///
9291    /// The wall-clock fire is evaluated in the schedule's own `tz`
9292    /// (matching the live tick's `Job::new_async_tz`) then normalised
9293    /// to UTC for the wire. `inclusive = false`: strictly the *next*
9294    /// fire after `now`, never one matching the current instant.
9295    pub fn next_calendar_fire(
9296        &self,
9297        now: chrono::DateTime<chrono::Utc>,
9298    ) -> Option<chrono::DateTime<chrono::Utc>> {
9299        if !matches!(self.when, When::Calendar(_)) {
9300            return None;
9301        }
9302        let lowered = self.lowered();
9303        // Same parser configuration tokio-cron-scheduler 0.15 uses
9304        // internally, so this can never compute a fire the live
9305        // scheduler wouldn't (seconds required, DOM-and-DOW honored).
9306        let cron = croner::parser::CronParser::builder()
9307            .seconds(croner::parser::Seconds::Required)
9308            .dom_and_dow(true)
9309            .build()
9310            .parse(&lowered.cron)
9311            .ok()?;
9312        match lowered.tz {
9313            ScheduleTz::Utc => cron.find_next_occurrence(&now, false).ok(),
9314            ScheduleTz::Local => {
9315                let now_local = now.with_timezone(&chrono::Local);
9316                cron.find_next_occurrence(&now_local, false)
9317                    .ok()
9318                    .map(|t| t.with_timezone(&chrono::Utc))
9319            }
9320        }
9321    }
9322
9323    /// Cross-field semantic checks that don't fit pure serde derive
9324    /// — the [`Manifest::validate`] counterpart (#418 decision F;
9325    /// pre-Phase-1 a broken schedule was accepted at create time
9326    /// and silently warn-skipped at tick time). Run at every create
9327    /// site: `kanade schedule create` (client-side) and
9328    /// `POST /api/schedules`. The job_id-exists check lives in the
9329    /// API handler instead — it needs the JOBS KV.
9330    pub fn validate(&self) -> Result<(), String> {
9331        if matches!(self.runs_on, RunsOn::Agent) && matches!(self.when, When::PerTarget(_)) {
9332            return Err(
9333                "when.per_target needs fleet-wide completion data and is backend-only; \
9334                 it cannot be combined with runs_on: agent (each agent self-schedules, \
9335                 so per-target dedup would be deduping across a target of 1)"
9336                    .into(),
9337            );
9338        }
9339        // `once_per_version` is a per_pc-only shape: it re-arms an
9340        // individual pc when the manifest version it succeeded at is no
9341        // longer current. "One delegate per version" for a whole target
9342        // has no clear meaning, so reject it rather than silently
9343        // lowering to plain per_target (version-blind).
9344        if matches!(self.when, When::PerTarget(PerPolicy::OncePerVersion(_))) {
9345            return Err(
9346                "when.per_target: once_per_version is not supported — once_per_version \
9347                 re-arms per pc per manifest version, which only makes sense for per_pc. \
9348                 Use `per_pc: once_per_version`."
9349                    .into(),
9350            );
9351        }
9352        // `once_per_version` keys its dedup on the backend's
9353        // `execution_results.version` history. A runs_on: agent schedule
9354        // self-schedules from the agent's local completion map, which has
9355        // no per-version record, so it is backend-only (symmetric with
9356        // per_target). Reject it rather than silently degrade to
9357        // version-blind kitting-once on the agent.
9358        if matches!(self.runs_on, RunsOn::Agent)
9359            && matches!(self.when, When::PerPc(PerPolicy::OncePerVersion(_)))
9360        {
9361            return Err(
9362                "when.per_pc: once_per_version keys its dedup on the backend's per-version \
9363                 completion history and is backend-only; it cannot be combined with \
9364                 runs_on: agent (the agent self-schedules with no per-version record). \
9365                 Use runs_on: backend."
9366                    .into(),
9367            );
9368        }
9369        // #418 event triggers: the agent owns the OS event source
9370        // (boot / session-change), so `when: { on }` is agent-only and
9371        // needs at least one trigger.
9372        if let When::On(triggers) = &self.when {
9373            if !matches!(self.runs_on, RunsOn::Agent) {
9374                return Err(
9375                    "when.on (OS event trigger) is fired by the agent's own event \
9376                     source, so it requires runs_on: agent"
9377                        .into(),
9378                );
9379            }
9380            if triggers.is_empty() {
9381                return Err(
9382                    "when.on must list at least one trigger (e.g. [startup, logon])".into(),
9383                );
9384            }
9385        }
9386        if let Some(cd) = self.lowered().cooldown.as_deref() {
9387            humantime::parse_duration(cd)
9388                .map_err(|e| format!("when.every: invalid duration '{cd}': {e}"))?;
9389        }
9390        if let When::Calendar(c) = &self.when {
9391            // Lower the calendar form to its cron (catches a bad `at`
9392            // and the date+days conflict), then validate that cron
9393            // with the same parser configuration tokio-cron-scheduler
9394            // 0.15 uses internally (croner, seconds required,
9395            // DOM-and-DOW both honored, year optional) — create-time
9396            // validation can never accept what register() rejects.
9397            let cron = c.to_cron()?;
9398            croner::parser::CronParser::builder()
9399                .seconds(croner::parser::Seconds::Required)
9400                .dom_and_dow(true)
9401                .build()
9402                .parse(&cron)
9403                .map_err(|e| format!("when.at lowered to invalid cron '{cron}': {e}"))?;
9404        }
9405        // The other humantime strings on the schedule (claude #419
9406        // review): runtime degrades gracefully on both (bad jitter →
9407        // silent no-op, bad starting_deadline → warn + skipped tick),
9408        // but "rejected at create time" should cover every field the
9409        // operator can typo, not just `when`.
9410        if let Some(j) = &self.plan.jitter {
9411            humantime::parse_duration(j)
9412                .map_err(|e| format!("jitter: invalid duration '{j}': {e}"))?;
9413        }
9414        if let Some(sd) = &self.starting_deadline {
9415            humantime::parse_duration(sd)
9416                .map_err(|e| format!("starting_deadline: invalid duration '{sd}': {e}"))?;
9417        }
9418        // #917: the plan side got almost no create-time checks, so
9419        // several never-fires / fails-every-tick shapes were accepted
9420        // and only surfaced at dispatch time — or never:
9421        //
9422        // (1) a target that dispatches nothing. A runs_on: agent
9423        // schedule matches each agent against `target` (rollout waves
9424        // are backend-published and never reach that path), so an
9425        // unspecified target silently never fires; a runs_on: backend
9426        // one warn-fails every tick at the exec boundary, which
9427        // rejects the same shape with the same message.
9428        let has_waves = self
9429            .plan
9430            .rollout
9431            .as_ref()
9432            .is_some_and(|r| !r.waves.is_empty());
9433        if matches!(self.runs_on, RunsOn::Agent) {
9434            if !self.plan.target.is_specified() {
9435                return Err(
9436                    "target must specify at least one of `all` / `groups` / `pcs` — a \
9437                     runs_on: agent schedule matches each agent against `target`, so an \
9438                     unspecified target never fires anywhere"
9439                        .into(),
9440                );
9441            }
9442            if self.plan.rollout.is_some() {
9443                return Err(
9444                    "rollout waves are published by the backend and are ignored by \
9445                     runs_on: agent schedules (each agent self-schedules from `target`); \
9446                     drop `rollout:` or use runs_on: backend"
9447                        .into(),
9448                );
9449            }
9450        } else if !has_waves && !self.plan.target.is_specified() {
9451            return Err(
9452                "target must specify at least one of `all` / `groups` / `pcs` \
9453                 (or set `rollout.waves`) — the exec boundary rejects an \
9454                 unspecified target, so the schedule would fail every tick"
9455                    .into(),
9456            );
9457        }
9458        // (2) rollout waves were never validated: a blank group or an
9459        // unparseable delay failed at EVERY fire (the CLI doesn't even
9460        // expose waves, so the failure was always deferred to dispatch)
9461        // and an empty list dispatched nothing. (3) A wave delayed to
9462        // or past starting_deadline is dead on arrival: the deadline is
9463        // stamped once at tick time and the Command is serialised
9464        // before the wave sleep, so agents receive it already expired
9465        // (a synthetic exit-125 skip on every fire).
9466        if let Some(rollout) = &self.plan.rollout {
9467            if rollout.waves.is_empty() {
9468                return Err(
9469                    "rollout.waves must list at least one wave; omit `rollout:` for a \
9470                     one-shot fan-out of `target`"
9471                        .into(),
9472                );
9473            }
9474            let deadline = self
9475                .starting_deadline
9476                .as_deref()
9477                .and_then(|sd| humantime::parse_duration(sd).ok());
9478            for (i, wave) in rollout.waves.iter().enumerate() {
9479                if wave.group.trim().is_empty() {
9480                    return Err(format!("rollout.waves[{i}].group must not be blank"));
9481                }
9482                let delay = humantime::parse_duration(&wave.delay).map_err(|e| {
9483                    format!(
9484                        "rollout.waves[{i}].delay: invalid duration '{}': {e}",
9485                        wave.delay
9486                    )
9487                })?;
9488                if let Some(deadline) = deadline
9489                    && delay >= deadline
9490                {
9491                    return Err(format!(
9492                        "rollout.waves[{i}].delay ('{}') must be shorter than \
9493                         starting_deadline ('{}'): the deadline is stamped at tick time, \
9494                         so this wave's Commands would already be expired when published \
9495                         (skipped by every agent, every fire)",
9496                        wave.delay,
9497                        self.starting_deadline.as_deref().unwrap_or_default(),
9498                    ));
9499                }
9500            }
9501        }
9502        // (4) deadline_at is machine-stamped: the scheduler overwrites
9503        // it from `tick + starting_deadline` on every fire, so an
9504        // operator-set value is silently discarded — reject it and
9505        // point at the knob that does what they meant. (Ad-hoc POST
9506        // /api/exec bodies are a different write path and may still
9507        // carry it.)
9508        if self.plan.deadline_at.is_some() {
9509            return Err(
9510                "deadline_at is computed by the scheduler (tick time + starting_deadline) \
9511                 and overwritten on every fire — set `starting_deadline` instead"
9512                    .into(),
9513            );
9514        }
9515        let from = self
9516            .active
9517            .from
9518            .as_deref()
9519            .map(|s| Active::parse_bound(s, self.tz))
9520            .transpose()?;
9521        let until = self
9522            .active
9523            .until
9524            .as_deref()
9525            .map(|s| Active::parse_bound(s, self.tz))
9526            .transpose()?;
9527        if let (Some(f), Some(u)) = (from, until) {
9528            if f >= u {
9529                return Err(format!(
9530                    "active.from ({}) must be strictly before active.until ({})",
9531                    self.active.from.as_deref().unwrap_or_default(),
9532                    self.active.until.as_deref().unwrap_or_default(),
9533                ));
9534            }
9535        }
9536        // #418 Phase 3: a bad maintenance window is rejected at create
9537        // time (parse_window also catches equal bounds).
9538        if let Some(w) = self.constraints.window.as_deref() {
9539            Constraints::parse_window(w)?;
9540        }
9541        // #418 holiday exclusion: reject a malformed skip date at create
9542        // time so the fail-closed `allows` path only ever bites a
9543        // hand-edited KV blob, not a fresh `kanade schedule create`.
9544        if let Some(err) = self.constraints.bad_skip_date() {
9545            return Err(err);
9546        }
9547        // #418: constraints.max_concurrent is a central running-instance
9548        // cap, so it needs the backend's counter — reject it on
9549        // runs_on: agent (decision E), and reject a meaningless 0.
9550        if let Some(mc) = self.constraints.max_concurrent {
9551            // Check the structural incompatibility (agent has no central
9552            // counter) before the value range, so a `max_concurrent: 0`
9553            // + `runs_on: agent` combo reports the more fundamental
9554            // problem first (claude #542).
9555            if matches!(self.runs_on, RunsOn::Agent) {
9556                return Err(
9557                    "constraints.max_concurrent needs a central counter and is backend-only; \
9558                     it cannot be combined with runs_on: agent (each agent self-schedules, \
9559                     so there is no fleet-wide count to cap against)"
9560                        .into(),
9561                );
9562            }
9563            if mc == 0 {
9564                return Err(
9565                    "constraints.max_concurrent must be >= 1 (0 would never fire; \
9566                     omit it for no cap)"
9567                        .into(),
9568                );
9569            }
9570        }
9571        // #418: constraints.require (host-state env gates: ac_power /
9572        // idle / cpu_below / network) is sensed in-process by the agent,
9573        // so it needs runs_on: agent — the backend can't read a target
9574        // host's power / idle / cpu / connectivity state. Symmetric with
9575        // `when: { on }` (also agent-only); inverse of max_concurrent
9576        // (backend-only).
9577        if let Some(req) = &self.constraints.require {
9578            if !req.is_empty() && matches!(self.runs_on, RunsOn::Backend) {
9579                return Err(
9580                    "constraints.require (host-state env gates: ac_power / idle / cpu_below / \
9581                     network) is sensed in-process by the agent and needs runs_on: agent; the \
9582                     backend cannot read a target host's power / idle / cpu / connectivity state"
9583                        .into(),
9584                );
9585            }
9586            // Reject a malformed idle duration at create time so the
9587            // fail-closed runtime path only ever bites a hand-edited
9588            // KV blob (mirror skip_dates / on_failure.retry).
9589            if let Some(err) = req.bad_idle() {
9590                return Err(err);
9591            }
9592            // cpu_below is a percent — reject out-of-range so a typo
9593            // can't make a schedule that never (>=100 is always-busy?
9594            // no — <0 never matches) or trivially fires.
9595            if let Some(c) = req.cpu_below
9596                && !(c > 0.0 && c <= 100.0)
9597            {
9598                return Err(format!(
9599                    "constraints.require.cpu_below must be in (0, 100] percent (got {c}); \
9600                     omit it for no CPU requirement"
9601                ));
9602            }
9603        }
9604        // #418 Phase 4: a bad on_failure.retry is rejected at create
9605        // time — backoff must be valid humantime, and max is bounded
9606        // so a typo can't pin a flapping script in a tight loop.
9607        if let Some(r) = &self.on_failure.retry {
9608            let backoff = humantime::parse_duration(&r.backoff).map_err(|e| {
9609                format!(
9610                    "on_failure.retry.backoff: invalid duration '{}': {e}",
9611                    r.backoff
9612                )
9613            })?;
9614            // The wire form lowers backoff to whole seconds, so a
9615            // sub-second value would silently become a 0s no-wait
9616            // (coderabbit #466). Reject it rather than honour a backoff
9617            // the operator can't actually get.
9618            if backoff.as_secs() < 1 {
9619                return Err(format!(
9620                    "on_failure.retry.backoff must be >= 1s (got '{}'); sub-second backoffs \
9621                     round to 0 on the wire",
9622                    r.backoff
9623                ));
9624            }
9625            if !(1..=10).contains(&r.max) {
9626                return Err(format!(
9627                    "on_failure.retry.max must be 1..=10 (got {}); it counts additional \
9628                     attempts after the first run",
9629                    r.max
9630                ));
9631            }
9632        }
9633        // A blank / whitespace-only tag renders an empty filter chip on
9634        // the Schedules page — reject it at create time, mirroring the
9635        // Manifest::validate tag guard.
9636        for tag in &self.tags {
9637            if tag.trim().is_empty() {
9638                return Err("tags must not contain empty entries".to_string());
9639            }
9640        }
9641        Ok(())
9642    }
9643}
9644
9645/// Shared `serde(default)` for `bool` fields that default to `true`
9646/// (e.g. `CheckHint::fleet` / `CheckHint::health`). Generic name so it
9647/// doesn't read as "fleet" when reused for `health`.
9648fn default_true() -> bool {
9649    true
9650}