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