Skip to main content

kanade_shared/
manifest.rs

1use serde::{Deserialize, Serialize};
2
3use crate::wire::{FinalizeCommand, RunAs, Shell, Staleness};
4
5/// YAML job manifest (= registered "what to run", v0.18.0+).
6///
7/// Owns only script-intrinsic fields. **Who** (`target`), **how to
8/// phase fanout** (`rollout`), and **when to stagger start**
9/// (`jitter`) all moved to the Schedule / exec request side — same
10/// script can now be fired against different targets / rollouts
11/// without copying the script body.
12///
13/// #492: these types are READ fleet-wide (agents decode them from
14/// BUCKET_JOBS / BUCKET_SCHEDULES and inside live Commands), so they
15/// must tolerate unknown fields — `deny_unknown_fields` here made a
16/// gradually-upgrading fleet's OLD agents reject the whole object
17/// the moment a newer backend added any field. Operator typo
18/// protection (the old reason for the attribute) lives at the WRITE
19/// boundaries instead: `kanade job/schedule create` and the backend
20/// POST extractor parse via [`crate::strict`], which rejects unknown
21/// keys with their full paths. The wire rule: new fields always get
22/// `#[serde(default)]` (+ `skip_serializing_if` while old readers
23/// may still be strict).
24#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
25pub struct Manifest {
26    pub id: String,
27    pub version: String,
28    #[serde(default)]
29    pub description: Option<String>,
30    pub execute: Execute,
31    #[serde(default)]
32    pub require_approval: bool,
33    /// Opt-in marker that this job produces a JSON inventory fact
34    /// payload on stdout. When present, the backend's results
35    /// projector parses `ExecResult.stdout` as JSON and upserts an
36    /// `inventory_facts` row keyed by `(pc_id, manifest.id)`. The
37    /// `display` sub-config drives the SPA's Inventory page render.
38    #[serde(default)]
39    pub inventory: Option<InventoryHint>,
40    /// Issue #246: opt-in marker that this job emits per-line
41    /// observability events on stdout (one JSON `ObsEvent` per
42    /// newline). When present, the agent — after the script exits
43    /// successfully — parses each non-empty stdout line as an
44    /// `ObsEvent`, publishes it on `obs.<pc_id>` via the
45    /// `obs_outbox`, and (intentionally) **omits the stdout from
46    /// the `ExecResult`** so the timeline data doesn't double up
47    /// in `execution_results.stdout` (which would multiply rows
48    /// by ~50/day/PC of noise).
49    ///
50    /// Distinct from `inventory:` (single JSON object → projector
51    /// upsert) — events are append-only timeline points consumed
52    /// by the dedicated `obs_events` table.
53    #[serde(default)]
54    pub emit: Option<EmitConfig>,
55    /// #290: opt-in marker that this job is an operator-defined
56    /// **health check** whose result feeds the Client App's Health
57    /// tab over KLP (`StateSnapshot.checks`). The script prints a
58    /// free-form JSON object on stdout (like any inventory job); the
59    /// agent reads the [`CheckHint::status_field`] value dynamically
60    /// into a [`crate::ipc::state::Check`] named `check.name`.
61    /// Cadence / windows / conditions come from
62    /// the job's Schedule (exactly like inventory) — there is
63    /// deliberately no interval here. **Composes with `inventory:` and
64    /// `collect:`** (#821): each reads its own `#KANADE-<KIND>`-fenced
65    /// stdout block, so one job can drive a check, project inventory
66    /// facts, and collect files in a single run. Only `emit:` (NDJSON
67    /// stdout) is incompatible. A check-only job may skip the fence
68    /// (whole stdout is the JSON); a multi-hint job fences each block.
69    #[serde(default)]
70    pub check: Option<CheckHint>,
71    /// #219: opt-in marker that this job COLLECTS files into a bundle.
72    /// The script does the collection work and prints a single JSON
73    /// object on stdout carrying a `files` array of paths (the field
74    /// name is [`CollectHint::files_field`], default `"files"`); the
75    /// agent — after the script exits successfully — zips those files,
76    /// uploads the archive to the `OBJECT_COLLECTIONS` Object Store
77    /// bucket (key `<pc_id>/<job_id>/<timestamp>.zip`), and records the
78    /// key in [`crate::wire::ExecResult::collect_object`]. The operator
79    /// downloads bundles from the SPA Collect page.
80    ///
81    /// Like `inventory:` / `check:` this reads a JSON object from stdout.
82    /// #821: it reads its own `#KANADE-COLLECT-BEGIN/END`-fenced block,
83    /// so it **composes with `inventory:` / `check:`** (and a user
84    /// message) on one stdout — only `emit:` (NDJSON) is incompatible
85    /// (enforced in [`Manifest::validate`]). A collect-only job may skip
86    /// the fence. It also composes with `client:` — a `collect:` +
87    /// `client:` job lets an end user trigger a collection from the
88    /// Client App (the same-host agent runs it).
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub collect: Option<CollectHint>,
91    /// #720: opt-in declarative aggregation over `obs_events` that drives
92    /// the SPA **Analytics** page. Unlike the other hints this one never
93    /// touches stdout and is never delivered to the agent — it's a pure
94    /// *read spec* the backend reads from `BUCKET_JOBS` at query time and
95    /// turns into `json_extract` aggregation SQL. Each entry is one widget
96    /// (a `dashboard:` tab groups them); `scope:` selects per-PC vs
97    /// fleet-wide rollup. Because it consumes nothing at run time it
98    /// composes with every other hint (typically paired with `emit:`,
99    /// which produces the events it reads). See [`AggregateWidget`].
100    ///
101    /// New field ⇒ #492 wire rule (`default` + `skip_serializing_if`).
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub aggregate: Option<Vec<AggregateWidget>>,
104    /// v0.26: Layer 2 staleness policy (SPEC.md §2.6.2). Controls
105    /// what the agent does at fire time when it can't verify the
106    /// `script_current` / `script_status` KV values are fresh —
107    /// especially relevant for `runs_on: agent` schedules where
108    /// the agent may fire from cache while offline. Defaults to
109    /// `Staleness::Cached` (silently use cached values), which
110    /// matches every pre-v0.26 Manifest.
111    #[serde(default)]
112    pub staleness: Staleness,
113    /// #291: opt-in marker that this job is offered to **end users**
114    /// in the Client App's job tabs over KLP (`jobs.list` →
115    /// `jobs.execute`). Parallel to [`inventory`] / [`check`] /
116    /// [`emit`]: the block's mere presence is the opt-in, and it
117    /// groups the end-user presentation fields (name / category /
118    /// icon) that only make sense for a user-facing job. `None`
119    /// (the default) ⇒ an operator-only job — inventory, checks,
120    /// scheduled maintenance — that never surfaces in the catalog.
121    ///
122    /// The agent re-reads this at every `jobs.list` / `jobs.execute`
123    /// (SPEC §2.1), so removing the block takes a job out of a
124    /// running client on its next action.
125    ///
126    /// [`inventory`]: Manifest::inventory
127    /// [`check`]: Manifest::check
128    /// [`emit`]: Manifest::emit
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub client: Option<ClientHint>,
131    /// Free-form operator taxonomy for the Jobs catalog. Purely a
132    /// SPA-side organisational aid — agents / scheduler / projector
133    /// never read it — so it carries no runtime semantics and any
134    /// string is allowed (`security`, `weekly`, `windows`, …). Jobs
135    /// cross-cut (a `check-bitlocker` is at once a health-check, a
136    /// security control, and Windows-specific), which is why this is
137    /// a multi-valued list rather than the single closed-enum
138    /// [`ClientHint::category`] (whose values are the end-user Client
139    /// App's tabs, a different concern). The operator Jobs page groups
140    /// rows by id-prefix for free; tags add the orthogonal filter axis
141    /// prefixes can't express.
142    ///
143    /// Empty by default (the overwhelming majority of jobs), and a
144    /// new field, so it follows the #492 wire rule: `serde(default)`
145    /// plus `skip_serializing_if` keep gradually-upgrading old readers
146    /// from tripping over its absence / presence.
147    #[serde(default, skip_serializing_if = "Vec::is_empty")]
148    pub tags: Vec<String>,
149    /// GitOps provenance (#678) — see [`RepoOrigin`]. Stamped by
150    /// `kanade job create` when the source YAML lives inside a Git work
151    /// tree, so the SPA can render the job read-only and point edits
152    /// back at the repo instead of letting a ClickOps edit silently
153    /// diverge from Git (SPEC design principle #3: 設定駆動 YAML + Git).
154    /// `None` for SPA-born jobs and for manifests applied from outside
155    /// any Git repo. Purely informational: agents / scheduler /
156    /// projector never read it, and it survives `script_file:` inlining
157    /// (it's orthogonal to the exactly-one-of script-source rule). New
158    /// field ⇒ #492 wire rule (`default` + `skip_serializing_if`).
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub origin: Option<RepoOrigin>,
161    /// Job-generic post-step hook. When set, the agent runs this script
162    /// AFTER the main `execute:` script exits cleanly (and, for a
163    /// `collect:` job, after the bundle finishes uploading), so the
164    /// operator can delete / move / notify based on what the step
165    /// produced. Best-effort: a finalize failure is logged but never
166    /// fails the run — the upload (if any) already succeeded.
167    ///
168    /// For `collect:` jobs the agent injects the environment variable
169    /// `KANADE_COLLECT_RESULT` — a JSON object
170    /// `{ "ok": true, "bundles": [ { "key", "uploaded", "files": [...] } ] }`
171    /// — so the hook acts on exactly the files that were bundled and
172    /// uploaded (e.g. deletes only the `uploaded` ones). Composes with
173    /// every hint. New field ⇒ #492 wire rule (`default` +
174    /// `skip_serializing_if`).
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub finalize: Option<FinalizeSpec>,
177    /// #vuln-roadmap: declarative **external-data feeds**. Each entry fetches
178    /// global reference data (a vulnerability catalog, an EOL table, a license
179    /// roster) and projects it into the shared `feeds` table keyed
180    /// `(feed_id, item_id)` — fleet-wide, with no `pc_id`, unlike the per-PC
181    /// inventory [`ExplodeSpec`]. The job's script (run on the trusted
182    /// controller tier) fetches + shapes the data and prints the array under
183    /// each spec's [`field`](FeedSpec::field) inside a
184    /// `#KANADE-FEED-BEGIN/END` fence; the projector replaces that feed's rows
185    /// wholesale. A non-empty `feed:` **implies** `tier: controller` (the
186    /// dispatch guard treats it as such), so an external fetch never lands on
187    /// an employee endpoint. Composes with the other fenced hints. New field ⇒
188    /// #492 wire rule (`default` + `skip_serializing_if`). See [`FeedSpec`].
189    #[serde(default, skip_serializing_if = "Vec::is_empty")]
190    pub feed: Vec<FeedSpec>,
191    /// Execution tier (#vuln-roadmap). `None` / `endpoint` (default) ⇒ the
192    /// job dispatches to the targeted fleet agents like any job. `controller`
193    /// ⇒ it may run ONLY on trusted infra hosts — the backend constrains
194    /// dispatch to members of the operator-configured `controller_group`
195    /// (`server_settings` KV), and refuses to run anywhere if that group is
196    /// unset (fail-safe). This keeps `feed:` (external-fetch) and future
197    /// privileged hints off employee endpoints. The `feed:` hint implies
198    /// `controller`; it can also be set explicitly. New field ⇒ #492 wire
199    /// rule (`default` + `skip_serializing_if`).
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub tier: Option<Tier>,
202}
203
204/// Execution tier for a [`Manifest`] — see [`Manifest::tier`]. `endpoint`
205/// is the default (a normal fleet job); `controller` restricts dispatch to
206/// the trusted `controller_group`. `Unknown` is the #492 forward-compat
207/// catch-all: an older reader still *decodes* a job that names a future
208/// tier (so it doesn't fail the whole document), but `Manifest::validate()`
209/// **rejects** it — for a security field we fail closed rather than fall
210/// back to unrestricted `endpoint` dispatch (a future tier is presumably
211/// *more* restrictive, and a typo'd `controller` must not silently widen).
212#[derive(
213    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
214)]
215#[serde(rename_all = "snake_case")]
216#[non_exhaustive]
217pub enum Tier {
218    /// Dispatch to the targeted fleet agents (the default).
219    #[default]
220    Endpoint,
221    /// Dispatch only to members of the configured `controller_group`.
222    Controller,
223    /// #492 forward-compat catch-all (a future tier this build can't act on).
224    #[serde(other)]
225    Unknown,
226}
227
228/// GitOps provenance for a repo-managed YAML artifact — a [`Manifest`]
229/// (#678) or a [`Schedule`] (#695). Populated by `kanade job create` /
230/// `kanade schedule create` from the Git context of the source YAML;
231/// the SPA reads it to render Git-managed entries read-only and link
232/// the operator back at the repo. Never consulted by the runtime.
233#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
234pub struct RepoOrigin {
235    /// Repo-relative path of the source YAML — the primary edit target
236    /// the SPA surfaces (e.g. `configs/jobs/foo.yaml`). Forward slashes
237    /// regardless of the authoring OS.
238    pub path: String,
239    /// `origin` remote URL, when the repo has one. Lets the SPA turn
240    /// `path` into a clickable link; `None` for remote-less repos.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub repo: Option<String>,
243    /// Repo-relative path of the `script_file:` a job manifest inlined,
244    /// when it used one — a secondary pointer shown beneath `path`.
245    /// Always `None` for schedules (they carry no script).
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    pub script_file: Option<String>,
248}
249
250/// "Who + how + when-to-stagger" — the fanout-plan side of an exec.
251/// Used both as the POST `/api/exec/{job_id}` body and as the embedded
252/// `target` / `rollout` / `jitter` slot on [`Schedule`]. Centralising
253/// here keeps the validation + serialisation logic in one place.
254#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default)]
255pub struct FanoutPlan {
256    #[serde(default)]
257    pub target: Target,
258    /// Optional wave rollout — when present, the backend publishes
259    /// each wave's group subject on its own delay schedule instead
260    /// of fanning out the `target` block in one go. `target` then
261    /// only labels the deploy for the audit log.
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub rollout: Option<Rollout>,
264    /// Optional humantime jitter; agent uses it to randomise
265    /// execution start. Lives here (not on the script) so different
266    /// schedules / ad-hoc fires of the same job can pick different
267    /// stagger windows.
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub jitter: Option<String>,
270    /// Absolute time the scheduler stamps on each emitted Command
271    /// when this exec was driven by a [`Schedule`] with
272    /// `starting_deadline`. Agents receiving a Command after this
273    /// instant publish a synthetic skipped-result instead of
274    /// running the script. `None` (default) = no deadline / catch
275    /// up whenever delivered. Computed by the scheduler from
276    /// `tick_at + starting_deadline` and overwritten on every fire —
277    /// on a Schedule, setting it by hand is rejected at create time
278    /// (#917, use `starting_deadline`); it remains settable on an
279    /// ad-hoc POST /api/exec body.
280    #[serde(default, skip_serializing_if = "Option::is_none")]
281    pub deadline_at: Option<chrono::DateTime<chrono::Utc>>,
282}
283
284/// Sentinel lines that fence a hint's structured JSON payload inside an
285/// otherwise human-readable job stdout. Each stdout-reading hint
286/// (`inventory:` / `check:` / `collect:`) has its OWN `#KANADE-<KIND>-
287/// BEGIN`/`-END` pair, so one job can carry several of them at once
288/// (and/or a user-facing message) on its single stdout stream — every
289/// consumer extracts only its own block via [`fenced_payload`].
290///
291/// Originated for inventory (#793): a `client:` job couldn't put both a
292/// friendly message and a JSON object on one stdout (the Client App
293/// renders stdout verbatim, the projector needs JSON). #821 generalised
294/// it so inventory / check / collect can coexist. `emit:` is the
295/// exception — its stdout is line-delimited NDJSON consumed whole, so it
296/// never fences and never coexists with the others.
297///
298/// A job carrying a SINGLE hint may still skip the fence —
299/// [`fenced_payload`] falls back to the whole stdout — but a job
300/// COMBINING hints must fence each block (else every consumer would try
301/// to parse the same whole stdout).
302pub const INVENTORY_BLOCK_BEGIN: &str = "#KANADE-INVENTORY-BEGIN";
303/// Closing marker — see [`INVENTORY_BLOCK_BEGIN`].
304pub const INVENTORY_BLOCK_END: &str = "#KANADE-INVENTORY-END";
305/// Check-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
306pub const CHECK_BLOCK_BEGIN: &str = "#KANADE-CHECK-BEGIN";
307/// Check-payload closing marker.
308pub const CHECK_BLOCK_END: &str = "#KANADE-CHECK-END";
309/// Collect-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
310pub const COLLECT_BLOCK_BEGIN: &str = "#KANADE-COLLECT-BEGIN";
311/// Collect-payload closing marker.
312pub const COLLECT_BLOCK_END: &str = "#KANADE-COLLECT-END";
313/// Feed-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
314pub const FEED_BLOCK_BEGIN: &str = "#KANADE-FEED-BEGIN";
315/// Feed-payload closing marker.
316pub const FEED_BLOCK_END: &str = "#KANADE-FEED-END";
317
318/// Extract a hint's fenced block when the `begin` marker is present, else
319/// `None`. An unterminated fence (closing marker missing, e.g. truncated
320/// output) takes everything after the opener. Trimmed so surrounding
321/// message text / whitespace never reaches the JSON parser.
322pub fn fenced_payload_if_present<'a>(stdout: &'a str, begin: &str, end: &str) -> Option<&'a str> {
323    let b = find_line_marker(stdout, begin)?;
324    let after = &stdout[b + begin.len()..];
325    let inner = match find_line_marker(after, end) {
326        Some(e) => &after[..e],
327        None => after,
328    };
329    Some(inner.trim())
330}
331
332/// True if stdout carries ANY `#KANADE-<KIND>-BEGIN` fence at a line
333/// start — i.e. the script opted into fenced output. Used to decide
334/// whether a missing fence means "single-hint, use the whole stdout" or
335/// "multi-hint author error / truncation, this hint just has no block".
336pub fn has_any_hint_fence(stdout: &str) -> bool {
337    [
338        INVENTORY_BLOCK_BEGIN,
339        CHECK_BLOCK_BEGIN,
340        COLLECT_BLOCK_BEGIN,
341        FEED_BLOCK_BEGIN,
342    ]
343    .iter()
344    .any(|m| find_line_marker(stdout, m).is_some())
345}
346
347/// Extract one hint's JSON payload from a job's stdout. When the hint's
348/// own `#KANADE-<KIND>` fence is present, return that block. When it's
349/// absent, fall back to the WHOLE stdout only for an unfenced (single-
350/// hint) job; if any OTHER hint's fence is present (#821 multi-hint
351/// output) return `""` instead — the script opted into fences but this
352/// block is missing (author error or truncation), so this consumer must
353/// NOT grab a sibling hint's block. An empty payload fails the consumer's
354/// JSON parse and degrades to "no data for this hint", never cross-parse.
355pub fn fenced_payload<'a>(stdout: &'a str, begin: &str, end: &str) -> &'a str {
356    if let Some(p) = fenced_payload_if_present(stdout, begin, end) {
357        return p;
358    }
359    if has_any_hint_fence(stdout) {
360        ""
361    } else {
362        stdout.trim()
363    }
364}
365
366/// Inventory's fenced payload — [`fenced_payload`] with the inventory
367/// markers. Kept as a named helper for the projector call site.
368pub fn inventory_payload(stdout: &str) -> &str {
369    fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END)
370}
371
372/// Feed's fenced payload — [`fenced_payload`] with the feed markers. Kept as
373/// a named helper for the projector call site.
374pub fn feed_payload(stdout: &str) -> &str {
375    fenced_payload(stdout, FEED_BLOCK_BEGIN, FEED_BLOCK_END)
376}
377
378/// Find `needle` only where it begins a line (start of `hay` or right
379/// after a `\n`). Anchoring to line start means a script echoing the
380/// literal sentinel mid-message (e.g. printing a command name) can't
381/// false-trigger the fence (Claude #793).
382fn find_line_marker(hay: &str, needle: &str) -> Option<usize> {
383    if hay.starts_with(needle) {
384        return Some(0);
385    }
386    hay.find(&format!("\n{needle}")).map(|p| p + 1)
387}
388
389/// Manifest sub-section: how the SPA should render the inventory
390/// facts this job produces. Each field name (`field`) is a top-level
391/// key in the stdout JSON, e.g. `hostname`, `ram_gb`.
392///
393/// Two render modes:
394///   * `display` — vertical "field / value" per PC, used by the
395///     `/inventory?pc=<id>` detail view. ALL columns the operator
396///     wants visible on the detail page.
397///   * `summary` — horizontal table across the fleet (row = PC,
398///     column = field) on `/inventory`. Optional; when omitted the
399///     SPA falls back to `display`, but operators usually want a
400///     trimmer "hostname / OS / CPU / RAM" set for the fleet view.
401#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
402pub struct InventoryHint {
403    /// Detail-view columns, in order.
404    pub display: Vec<DisplayField>,
405    /// Optional fleet-list columns (row = PC). Defaults to `display`
406    /// when omitted, but operators usually pick a 3-5 column subset.
407    #[serde(default, skip_serializing_if = "Option::is_none")]
408    pub summary: Option<Vec<DisplayField>>,
409    /// v0.31 / #40: payload arrays that should be exploded into
410    /// per-element rows of a derived SQLite table. Lets operators
411    /// answer cross-PC questions ("which PCs still have Chrome <
412    /// 120?", "C: >90% full") with normal SQL filters + indexes
413    /// instead of grepping JSON. The projector creates the derived
414    /// table on register and replaces this PC's rows on each result
415    /// (DELETE WHERE pc_id=? AND job_id=? + bulk INSERT). See
416    /// [`ExplodeSpec`] for the per-spec schema.
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub explode: Option<Vec<ExplodeSpec>>,
419    /// v0.35 / #93: top-level scalar fields whose changes the
420    /// projector logs to `inventory_history` (one event per
421    /// changed field per scan). Pairs with `explode[].track_history`
422    /// — that covers array elements; this covers single-valued
423    /// fields like `ram_bytes` / `os_version` / `cpu_model` /
424    /// `os_build` that operators want to track for "did the RAM
425    /// get upgraded?" / "when did Win 11 land on this PC?" /
426    /// "BIOS / firmware bumped?" questions. Field name = `field_path`
427    /// in the history row, `identity_json` is NULL, `before_json`
428    /// / `after_json` each carry `{"value": <prior or new value>}`.
429    /// First-ever observation of a scalar (no prior facts row)
430    /// emits `added`; subsequent value changes emit `changed`. No
431    /// `removed` events — a scalar disappearing from the payload
432    /// is rare and the operator can still see the last value via
433    /// the `before_json` of the most recent change.
434    #[serde(default, skip_serializing_if = "Option::is_none")]
435    pub history_scalars: Option<Vec<String>>,
436}
437
438/// Manifest sub-section (#290): marks a job as an operator-defined
439/// **health check**. Parallel to [`InventoryHint`] / `EmitConfig`.
440/// The stdout contract is a free-form JSON object (same as any
441/// inventory job) from which the agent reads `status_field` /
442/// `detail_field` to build the KLP [`crate::ipc::state::Check`] shown
443/// on the Client App's Health tab.
444///
445/// There is deliberately **no timing field** — when / how often /
446/// in which window a check runs is driven by the job's Schedule,
447/// exactly like inventory jobs, so operators get the full `when:` /
448/// rollout / `runs_on` expressiveness for free.
449///
450/// A check's stdout is a **free-form inventory object** (arbitrary
451/// key/value pairs + arrays) — same as any inventory job — that also
452/// carries a status field. `check:` adds only the health semantics on
453/// top: which field is the ok/warn/fail/unknown status, an optional
454/// one-line summary field, and a remediation job. Everything else
455/// (rich per-PC detail, `explode` sub-tables like a software list) is
456/// driven by a co-present [`InventoryHint`] and rendered with the
457/// SAME display logic the SPA Inventory page uses — on the Client App
458/// too. This keeps checks maximally expressive without a bespoke
459/// payload type.
460#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
461pub struct CheckHint {
462    /// Stable check id → [`Check.name`](crate::ipc::state::Check),
463    /// the SPA/Client React key + analytics label. Unique within the
464    /// fleet's check set. Machine-friendly slug (`disk_space`,
465    /// `defender_rtp`); for the human-facing row title see [`label`].
466    ///
467    /// [`label`]: CheckHint::label
468    pub name: String,
469    /// Optional human-facing display title →
470    /// [`Check.label`](crate::ipc::state::Check). The Client App's
471    /// Health tab and the operator SPA's Compliance page render this
472    /// instead of the [`name`](CheckHint::name) slug when set
473    /// (`"ウイルス対策のリアルタイム保護"` reads better than
474    /// `defender_rtp`). Falls back to the slug when absent, so it's
475    /// purely additive. Author it in the check's language — there's no
476    /// per-locale variant; checks are operator-defined per fleet.
477    #[serde(default, skip_serializing_if = "Option::is_none")]
478    pub label: Option<String>,
479    /// Top-level stdout field whose string value
480    /// (`ok`/`warn`/`fail`/`unknown`) becomes the Health-tab light
481    /// ([`CheckStatus`](crate::ipc::state::CheckStatus)). Defaults to
482    /// `"status"`; a missing / unparseable value → `unknown`.
483    #[serde(default = "default_status_field")]
484    pub status_field: String,
485    /// Top-level stdout field used as the Health-tab row's one-line
486    /// summary. Defaults to `"detail"`; absent in the payload → no
487    /// detail line (the rich breakdown lives in the inventory view).
488    #[serde(default = "default_detail_field")]
489    pub detail_field: String,
490    /// Optional remediation job id →
491    /// [`Check.troubleshoot`](crate::ipc::state::Check). The Client
492    /// App shows a "修復する" button when present; that job must be
493    /// `user_invokable`.
494    #[serde(default, skip_serializing_if = "Option::is_none")]
495    pub troubleshoot: Option<String>,
496    /// #290 PR-E: when `true` (default), the backend also projects this
497    /// check's `status` / `detail` into the `check_status` table so the
498    /// operator SPA gets a fleet-wide compliance view for free — no
499    /// `inventory:` block needed. Set `fleet: false` for a client-only
500    /// check the operator doesn't want surfaced across the fleet.
501    #[serde(default = "default_true")]
502    pub fleet: bool,
503    /// When `true` (default), this check is shown on the Client App's
504    /// Health tab (the end user sees its ok/warn/fail row). Set
505    /// `health: false` for a **gate-only** check — one that exists purely
506    /// to drive a `client.show_when` display gate (e.g. `myapp-up-to-date`)
507    /// and would just be noise as a Health row. The agent still records it
508    /// into `StateSnapshot.checks` (so `show_when` can read it and the gate
509    /// keeps working); only the Client App's Health *rendering* skips it,
510    /// via the [`Check.health_hidden`](crate::ipc::state::Check::health_hidden)
511    /// wire flag. Orthogonal to [`fleet`](CheckHint::fleet): `fleet` gates
512    /// the operator SPA fleet view, `health` gates the end-user Health tab,
513    /// so a pure gate detector typically sets neither (`fleet: false` +
514    /// `health: false`) to stay invisible everywhere while still driving
515    /// the gate.
516    #[serde(default = "default_true")]
517    pub health: bool,
518    /// Optional auto-notification on a compliance transition. When set, the
519    /// backend publishes an end-user notification the moment this check
520    /// transitions *into* one of [`CheckAlert::on`] (e.g. ok → fail) — to
521    /// the failing PC's user and/or operator groups. Fired once per
522    /// transition (not on every poll). Requires `fleet: true` (the alert
523    /// rides the same projection that fills `check_status`).
524    #[serde(default, skip_serializing_if = "Option::is_none")]
525    pub alert: Option<CheckAlert>,
526}
527
528/// Auto-notification rule for a [`CheckHint`] (compliance alerting). When a
529/// check's status transitions into one of [`on`](Self::on), the backend
530/// publishes a notification to the failing PC's user
531/// ([`notify_user`](Self::notify_user)) and/or operator groups
532/// ([`notify_groups`](Self::notify_groups)). Deliberately config-driven:
533/// who gets told, how loud, and the wording all live in the manifest, not
534/// hardcoded in the backend.
535#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
536pub struct CheckAlert {
537    /// Statuses that fire the alert on *transition into* them (a check that
538    /// stays failing doesn't re-alert every poll). Defaults to `[fail]`.
539    /// `ok` is not representable — [`CheckAlertStatus`] has no `Ok` variant,
540    /// so a YAML `on: [ok]` fails to deserialize (before `validate()` is
541    /// even reached); "recovered" notifications are out of scope.
542    #[serde(default = "default_alert_on")]
543    pub on: Vec<CheckAlertStatus>,
544    /// Notify the user(s) on the failing PC (`notifications.pc.<pc_id>`).
545    #[serde(default)]
546    pub notify_user: bool,
547    /// Notify these operator groups (`notifications.group.<name>`).
548    #[serde(default, skip_serializing_if = "Vec::is_empty")]
549    pub notify_groups: Vec<String>,
550    /// Notification priority (colour/label only — toasting is the separate
551    /// `toast` flag). Defaults to `warn`.
552    #[serde(default = "default_alert_priority")]
553    pub priority: crate::ipc::notifications::NotificationPriority,
554    /// Require the recipient to click 確認 to dismiss.
555    #[serde(default)]
556    pub require_ack: bool,
557    /// Surface an OS toast (launches a closed Client App, Action Center
558    /// while locked). Recommended `true` for `notify_user` so a
559    /// non-emergency "your PC is non-compliant" nudge still reaches a user
560    /// whose app is closed.
561    #[serde(default)]
562    pub toast: bool,
563    /// Also send the alert by email, to every address mapped to the
564    /// `notify_groups` (via the `group_contacts` KV, edited on the SPA
565    /// Groups page). Opt-in: defaults to `false`, so an existing alert
566    /// never starts emailing on its own. Requires `notify_groups` to be
567    /// non-empty (there is no per-PC user email) and the backend's
568    /// `[mail]` config to be present; otherwise the email is a logged
569    /// no-op while the in-app/toast notification still fires.
570    #[serde(default)]
571    pub email: bool,
572    /// Notification title (required). May use the same `{…}` placeholders
573    /// as [`body`](Self::body).
574    pub title: String,
575    /// Notification body template. Placeholders: `{pc_id}`, `{name}` (check
576    /// slug), `{label}` (check label, falls back to slug), `{status}`,
577    /// `{detail}` (the check's one-line summary), `{last_logon}` (the PC's
578    /// last sign-in account). Absent → empty body.
579    #[serde(default, skip_serializing_if = "Option::is_none")]
580    pub body: Option<String>,
581}
582
583/// A check status that can trigger a [`CheckAlert`]. Mirrors the
584/// projected `check_status.status` values minus `ok` (alerting on `ok` is
585/// rejected at validation).
586#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash)]
587#[serde(rename_all = "snake_case")]
588pub enum CheckAlertStatus {
589    Warn,
590    Fail,
591    Unknown,
592}
593
594impl CheckAlertStatus {
595    /// The wire string, matching the projected `check_status.status`.
596    pub fn as_str(self) -> &'static str {
597        match self {
598            Self::Warn => "warn",
599            Self::Fail => "fail",
600            Self::Unknown => "unknown",
601        }
602    }
603}
604
605fn default_alert_on() -> Vec<CheckAlertStatus> {
606    vec![CheckAlertStatus::Fail]
607}
608
609fn default_alert_priority() -> crate::ipc::notifications::NotificationPriority {
610    crate::ipc::notifications::NotificationPriority::Warn
611}
612
613fn default_status_field() -> String {
614    "status".to_string()
615}
616
617fn default_detail_field() -> String {
618    "detail".to_string()
619}
620
621fn default_files_field() -> String {
622    "files".to_string()
623}
624
625/// Fallback cap on a collect bundle's total input size when the
626/// manifest's `collect.max_size` is unset. 50 MB (decimal).
627pub const DEFAULT_COLLECT_MAX_SIZE: u64 = 50 * 1_000_000;
628
629/// Manifest sub-section (#219): marks a job as a **file collector** and
630/// carries how the collected bundle presents in the SPA. Parallel to
631/// [`InventoryHint`] / [`CheckHint`] — the block's presence is the
632/// opt-in. The script prints a single JSON object on stdout whose
633/// [`files_field`](CollectHint::files_field) key holds an array of file
634/// paths to bundle (env vars are expanded); the agent zips them and
635/// uploads to `OBJECT_COLLECTIONS`. See [`Manifest::collect`].
636#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
637pub struct CollectHint {
638    /// Operator/end-user-facing title for the collection, shown as the
639    /// bundle's heading on the SPA Collect page (and the Client App row
640    /// when paired with `client:`). Required; validated non-empty.
641    pub name: String,
642    /// Optional one-line description of what the bundle contains.
643    #[serde(default, skip_serializing_if = "Option::is_none")]
644    pub description: Option<String>,
645    /// Human-readable cap on the bundle's total input size
646    /// (`"50MB"`, `"500KB"`, `"1GiB"`). The agent refuses to build a
647    /// bundle whose listed files exceed this. `None` ⇒
648    /// [`DEFAULT_COLLECT_MAX_SIZE`]. Parsed by [`parse_size_bytes`];
649    /// [`Manifest::validate`] rejects an unparseable value at create
650    /// time.
651    ///
652    /// Note: this bounds the **uncompressed** bytes the agent reads off
653    /// disk, not the resulting zip. Text logs compress well, so the
654    /// download is usually much smaller; many tiny files add a little
655    /// per-entry zip overhead. Read it as "how much the agent reads +
656    /// packs", not "the exact download size".
657    #[serde(default, skip_serializing_if = "Option::is_none")]
658    pub max_size: Option<String>,
659    /// Top-level stdout JSON key holding the array of file paths to
660    /// bundle. Defaults to `"files"`.
661    #[serde(default = "default_files_field")]
662    pub files_field: String,
663}
664
665impl CollectHint {
666    /// The effective size cap in bytes — the parsed `max_size` or
667    /// [`DEFAULT_COLLECT_MAX_SIZE`] when unset. Assumes `max_size` (if
668    /// present) already passed [`Manifest::validate`]; falls back to the
669    /// default on a parse error rather than panicking on the fire path.
670    pub fn max_size_bytes(&self) -> u64 {
671        match &self.max_size {
672            Some(s) => parse_size_bytes(s).unwrap_or(DEFAULT_COLLECT_MAX_SIZE),
673            None => DEFAULT_COLLECT_MAX_SIZE,
674        }
675    }
676}
677
678/// Parse a human-readable byte size (`"50MB"`, `"500 KB"`, `"1GiB"`,
679/// `"1024"`). Decimal units (KB/MB/GB) are 1000-based; binary units
680/// (KiB/MiB/GiB) are 1024-based; a bare number (or `B`) is bytes.
681/// Case-insensitive. Shared by `collect.max_size` validation and the
682/// agent's bundle-size enforcement.
683pub fn parse_size_bytes(s: &str) -> Result<u64, String> {
684    let t = s.trim();
685    if t.is_empty() {
686        return Err("size must not be empty".to_string());
687    }
688    let split = t.find(|c: char| !c.is_ascii_digit()).unwrap_or(t.len());
689    let (num_str, unit_raw) = t.split_at(split);
690    if num_str.is_empty() {
691        return Err(format!("size '{s}': missing leading number"));
692    }
693    let num: u64 = num_str
694        .parse()
695        .map_err(|_| format!("size '{s}': bad number '{num_str}'"))?;
696    let mult: u64 = match unit_raw.trim().to_ascii_lowercase().as_str() {
697        "" | "b" => 1,
698        "kb" => 1_000,
699        "mb" => 1_000_000,
700        "gb" => 1_000_000_000,
701        "kib" => 1024,
702        "mib" => 1024 * 1024,
703        "gib" => 1024 * 1024 * 1024,
704        other => {
705            return Err(format!(
706                "size '{s}': unknown unit '{other}' (use B/KB/MB/GB/KiB/MiB/GiB)"
707            ));
708        }
709    };
710    num.checked_mul(mult)
711        .ok_or_else(|| format!("size '{s}': overflow"))
712}
713
714/// Manifest sub-section (#291): marks a job as **user-invokable**
715/// from the Client App and carries how it presents to the end user.
716/// Parallel to [`InventoryHint`] / [`CheckHint`] / `EmitConfig` —
717/// the block's presence is the opt-in (no separate boolean), and its
718/// required fields (`name`, `category`) are enforced by serde at
719/// parse time, so a half-filled catalog entry fails
720/// `kanade job create` instead of rendering a nameless / tab-less row.
721///
722/// The agent maps this 1:1 into the KLP
723/// [`UserInvokableJob`](crate::ipc::jobs::UserInvokableJob) wire shape
724/// that `jobs.list` returns; the Client App renders one row per job in
725/// the tab named by `category`.
726#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
727pub struct ClientHint {
728    /// End-user-facing title for the job row. The operator-internal
729    /// `Manifest::id` slug is rarely what an end user should read, so
730    /// this is required (and validated non-empty by
731    /// [`Manifest::validate`]). Maps to `UserInvokableJob::display_name`.
732    pub name: String,
733    /// Optional one-line subtitle under `name` in the Client App.
734    /// Distinct from the operator-facing top-level
735    /// [`Manifest::description`] — this one is written for the end
736    /// user. Maps to `UserInvokableJob::display_description`.
737    #[serde(default, skip_serializing_if = "Option::is_none")]
738    pub description: Option<String>,
739    /// Which Client App tab the job lives in — a **free-form category
740    /// key** (#792). The Client App renders one tab per distinct key.
741    /// Well-known keys (`software_update`, `troubleshoot`, `catalog`)
742    /// carry built-in tab labels/icons; any other key defines a new tab
743    /// (style it with `category_label` / `category_icon`). Required and
744    /// validated non-empty — without it the agent can't place the job.
745    /// Note: the `software_update` key also drives the agent's
746    /// maintenance / auto-reboot grouping.
747    pub category: String,
748    /// Optional display name for the category's TAB. Set it on (at least
749    /// one of) a custom category's jobs to name the tab; `None` ⇒ a
750    /// built-in default for a well-known key, else the key itself.
751    #[serde(default, skip_serializing_if = "Option::is_none")]
752    pub category_label: Option<String>,
753    /// Optional icon for the category's TAB (lucide name or `data:` URL).
754    /// `None` ⇒ Client App default for the key.
755    #[serde(default, skip_serializing_if = "Option::is_none")]
756    pub category_icon: Option<String>,
757    /// Optional sort order for the TAB; lower sorts first. `None` ⇒
758    /// default (well-known keys keep their familiar order; custom keys
759    /// sort after, then by label).
760    #[serde(default, skip_serializing_if = "Option::is_none")]
761    pub category_order: Option<i64>,
762    /// Optional icon hint for the job ROW — a lucide-react icon name
763    /// or a `data:` URL. `None` ⇒ the Client App falls back to the
764    /// category's icon. Surfaced verbatim in `jobs.list[].icon`.
765    #[serde(default, skip_serializing_if = "Option::is_none")]
766    pub icon: Option<String>,
767    /// Optional visibility scope for the end-user Client App (#816).
768    ///
769    /// `None` ⇒ visible to every PC (current behavior). When set, only
770    /// agents whose `pc_id` / group membership match the [`Target`] list
771    /// the job in `jobs.list` and may run it via KLP `jobs.execute`.
772    ///
773    /// This gates the END-USER surface ONLY. Operators are unaffected:
774    /// `POST /api/exec/{job_id}` (SPA / `kanade exec`) is a separate path
775    /// that never consults `client:`, so an operator can still run the
776    /// job on any PC regardless of `visible_to`. Reuses the schedule
777    /// `Target` shape (`all` / `groups` / `pcs`); a present-but-empty
778    /// target is rejected by [`Manifest::validate`].
779    #[serde(default, skip_serializing_if = "Option::is_none")]
780    pub visible_to: Option<Target>,
781    /// Optional **dynamic display gate** keyed on a health check's result.
782    ///
783    /// `None` ⇒ always listed (current behavior). When set, the agent
784    /// lists the job in `jobs.list` ONLY while the named [`check:`] slug's
785    /// latest result is one of [`ShowWhen::is`]. The canonical use is an
786    /// update action that hides itself once the machine is already current:
787    /// pair the update job with a `check:` that reports `ok` when up to
788    /// date and gate on `is: [fail]`.
789    ///
790    /// Evaluated agent-side at `jobs.list` time against the live
791    /// `StateSnapshot.checks`, which is **keyed by check name** — so the
792    /// detector `check:` and this job may live in *different* manifests and
793    /// still share one slug. Distinct from [`visible_to`](ClientHint::visible_to):
794    /// that gates BOTH listing and `jobs.execute` (an authorization
795    /// boundary); `show_when` gates listing ONLY (a UX hint), so it can't
796    /// cause a list/execute race. New field ⇒ #492 wire rule.
797    ///
798    /// [`check:`]: crate::manifest::CheckHint
799    #[serde(default, skip_serializing_if = "Option::is_none")]
800    pub show_when: Option<ShowWhen>,
801}
802
803/// Dynamic display gate for a [`ClientHint`] — see
804/// [`ClientHint::show_when`]. Shows the job only while the named check's
805/// latest status is one of [`is`](ShowWhen::is).
806#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
807pub struct ShowWhen {
808    /// The `check:` slug (a [`CheckHint::name`](crate::manifest::CheckHint::name))
809    /// whose latest status gates this job. May be defined by a *different*
810    /// manifest: checks are keyed by name in the agent's snapshot, so a
811    /// standalone detector job and this one can share a slug. A check that
812    /// has never run (absent from the snapshot) does NOT match — the job
813    /// stays hidden until the detector first reports (fails closed, like
814    /// `visible_to`).
815    pub check: String,
816    /// The check status(es) in which the job is SHOWN. Accepts a single
817    /// status (`is: fail`) or a list (`is: [fail, unknown]`); both
818    /// deserialize to a `Vec`. The `length(min = 1)` schema constraint +
819    /// [`Manifest::validate`] both reject an empty set (it would match
820    /// nothing and silently hide the job) so schema-driven tooling and the
821    /// write path agree.
822    #[serde(deserialize_with = "de_one_or_many_check_status")]
823    #[schemars(length(min = 1))]
824    pub is: Vec<crate::ipc::state::CheckStatus>,
825}
826
827/// Accept either a single `CheckStatus` (`is: fail`) or a sequence
828/// (`is: [fail, unknown]`) for [`ShowWhen::is`], normalising to a `Vec`.
829/// The scalar form is purely author ergonomics; the JSON schema advertises
830/// the canonical array form (`#[schemars(with = ...)]`).
831fn de_one_or_many_check_status<'de, D>(
832    d: D,
833) -> Result<Vec<crate::ipc::state::CheckStatus>, D::Error>
834where
835    D: serde::Deserializer<'de>,
836{
837    use crate::ipc::state::CheckStatus;
838    #[derive(Deserialize)]
839    #[serde(untagged)]
840    enum OneOrMany {
841        One(CheckStatus),
842        Many(Vec<CheckStatus>),
843    }
844    Ok(match OneOrMany::deserialize(d)? {
845        OneOrMany::One(c) => vec![c],
846        OneOrMany::Many(v) => v,
847    })
848}
849
850/// #720 — one widget on the SPA **Analytics** page: a declarative
851/// aggregation over the `obs_events` table. The backend reads these off
852/// `Manifest::aggregate` (from `BUCKET_JOBS`) at query time and builds
853/// the `json_extract` GROUP BY / time-bucket SQL from these generic
854/// primitives, so an operator can chart any emitted event without a Rust
855/// change. The reference shapes are the attendance dashboards
856/// (presence / app_sample / web_visit), but the same DSL covers logon /
857/// reboot / agent-health trends, etc.
858#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
859pub struct AggregateWidget {
860    /// Tab this widget lives under on the Analytics page. Widgets from
861    /// every job are collected and grouped by this label, so the same
862    /// string across jobs builds one multi-source dashboard. Required.
863    pub dashboard: String,
864    /// Widget heading. Required, validated non-empty.
865    pub title: String,
866    /// Optional one-line subtitle shown muted under the `title` on the
867    /// Analytics page — room for a unit, a caveat, or what the number
868    /// means ("samples × 2 min", "Security 4624 only"). Rejected if
869    /// present-but-blank.
870    #[serde(default, skip_serializing_if = "Option::is_none")]
871    pub description: Option<String>,
872    /// Optional sort weight (#743). Once the order-aware sort lands (PR2)
873    /// widgets render in `(order, dashboard, title)` order, so a lower
874    /// `order` pulls a widget — and its tab — earlier; equal/absent `order`
875    /// falls back to the alphabetical `(dashboard, title)` ordering. Treated
876    /// as `0` when unset, so a fleet with no `order` anywhere stays purely
877    /// alphabetical (today's behaviour); negatives are allowed to pin
878    /// something first. (This field only carries the value; the backend
879    /// applies it.)
880    #[serde(default, skip_serializing_if = "Option::is_none")]
881    pub order: Option<i32>,
882    /// Promote this widget to the main Dashboard, not just the Analytics
883    /// page (#vuln-roadmap PR3). The Dashboard fetches the pinned subset
884    /// (`/api/analytics?pinned=true`, fleet scope) and renders it with the
885    /// same widget components. Operator-controlled, so any config-driven
886    /// view (e.g. a future vulnerability rollup) can surface up front
887    /// without a bespoke card. Defaults to `false`. Pin a `scope: fleet`
888    /// widget — a `pc`-scoped one needs a selected PC and won't render on
889    /// the fleet Dashboard.
890    // `Not::not` is `!self`, so this skips serializing the field when it's
891    // `false` — keeps `pin_dashboard: false` out of the stored job/view JSON,
892    // matching how the optional fields above omit their defaults.
893    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
894    pub pin_dashboard: bool,
895    /// `pc` rolls up a single selected PC; `fleet` rolls up all PCs
896    /// (and unlocks `group_by: pc_id` to rank PCs against each other).
897    /// Defaults to `pc`.
898    #[serde(default)]
899    pub scope: AggregateScope,
900    /// `obs_events.kind` this widget reads (e.g. `app_sample`,
901    /// `presence`, `unexpected_shutdown`). Required for every aggregation
902    /// render (`bar`/`gauge`/`timeline`/`stat`); rejected for
903    /// `op_timeline`, which reconstructs a fixed multi-kind operational
904    /// swimlane (power/session/sleep) baked into the SPA and so reads no
905    /// single `kind`.
906    #[serde(default, skip_serializing_if = "Option::is_none")]
907    pub kind: Option<String>,
908    /// Optional `obs_events.source` filter, when one `kind` is emitted by
909    /// more than one collector.
910    #[serde(default, skip_serializing_if = "Option::is_none")]
911    pub source: Option<String>,
912    /// How to roll the matching events up. See [`AggregateAgg`]. Required
913    /// for every aggregation render; rejected for `op_timeline` (which
914    /// performs no rollup — it returns the raw operational events and the
915    /// SPA folds them into lane spans).
916    #[serde(default, skip_serializing_if = "Option::is_none")]
917    pub agg: Option<AggregateAgg>,
918    /// Dotted JSON path (no `$.` prefix) to group by for `agg: count` /
919    /// `sum` — e.g. `foreground.app`. The literal `pc_id` is special:
920    /// it groups by the `pc_id` column (fleet ranking), not a payload
921    /// field. Omit for a single total. Required when `agg: sum` needs a
922    /// breakdown; for `agg: count` omitting it yields the grand total.
923    #[serde(default, skip_serializing_if = "Option::is_none")]
924    pub group_by: Option<String>,
925    /// Dotted JSON path to a boolean for `agg: ratio` (e.g. `active`):
926    /// the widget reports `true_count / total`. Required when `agg: ratio`.
927    #[serde(default, skip_serializing_if = "Option::is_none")]
928    pub bool_path: Option<String>,
929    /// Dotted JSON path to a number for `agg: sum`. Required when `agg: sum`.
930    #[serde(default, skip_serializing_if = "Option::is_none")]
931    pub value_path: Option<String>,
932    /// Optional value transform applied before grouping. Currently only
933    /// `host` (parse a URL down to its host) — used by the top-sites
934    /// widget, where SQLite can't parse a URL so the backend does it in
935    /// Rust. See [`AggregateTransform`].
936    #[serde(default, skip_serializing_if = "Option::is_none")]
937    pub transform: Option<AggregateTransform>,
938    /// Optional sampling cadence in minutes. When set, a `count` is also
939    /// reported as estimated time (`count × sample_minutes`) — e.g. a
940    /// 2-minute app sampler turns 11 samples into ~22 minutes. Must be ≥ 1.
941    #[serde(default, skip_serializing_if = "Option::is_none")]
942    #[schemars(range(min = 1))]
943    pub sample_minutes: Option<u32>,
944    /// Grouped values to drop from the rollup (e.g. `["LockApp"]` so the
945    /// lock screen doesn't top the app ranking). Empty by default.
946    #[serde(default, skip_serializing_if = "Vec::is_empty")]
947    pub exclude: Vec<String>,
948    /// Optional time bucketing — `hour` buckets events by local
949    /// hour-of-day for a `timeline` render. See [`AggregateTimeBucket`].
950    #[serde(default, skip_serializing_if = "Option::is_none")]
951    pub time_bucket: Option<AggregateTimeBucket>,
952    /// Top-N cap for grouped renders (`bar`). Defaults to 10 when unset.
953    #[serde(default, skip_serializing_if = "Option::is_none")]
954    #[schemars(range(min = 1))]
955    pub limit: Option<u32>,
956    /// Which widget the SPA draws. See [`AggregateRender`].
957    pub render: AggregateRender,
958}
959
960/// Per-PC vs fleet-wide rollup for an [`AggregateWidget`].
961#[derive(
962    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
963)]
964#[serde(rename_all = "lowercase")]
965#[non_exhaustive]
966pub enum AggregateScope {
967    /// Roll up the single PC the operator selected. The default.
968    #[default]
969    Pc,
970    /// Roll up across every PC. Unlocks `group_by: pc_id`.
971    Fleet,
972    /// #492 forward-compat catch-all — a Manifest is read fleet-wide, so
973    /// an older reader must tolerate a future variant rather than failing
974    /// to decode the whole job. The backend skips an `Unknown` widget.
975    #[serde(other)]
976    Unknown,
977}
978
979/// The rollup function for an [`AggregateWidget`].
980#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
981#[serde(rename_all = "lowercase")]
982#[non_exhaustive]
983pub enum AggregateAgg {
984    /// Row count, optionally grouped (`group_by`) and time-estimated
985    /// (`sample_minutes`).
986    Count,
987    /// `true_count / total` over `bool_path`.
988    Ratio,
989    /// Sum of `value_path`, optionally grouped.
990    Sum,
991    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
992    #[serde(other)]
993    Unknown,
994}
995
996/// Optional pre-grouping value transform for an [`AggregateWidget`].
997#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
998#[serde(rename_all = "lowercase")]
999#[non_exhaustive]
1000pub enum AggregateTransform {
1001    /// Parse the grouped value as a URL and keep only its host.
1002    Host,
1003    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1004    #[serde(other)]
1005    Unknown,
1006}
1007
1008/// Time bucketing for an [`AggregateWidget`] (drives a `timeline`).
1009#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1010#[serde(rename_all = "lowercase")]
1011#[non_exhaustive]
1012pub enum AggregateTimeBucket {
1013    /// Bucket by local hour-of-day (0–23), summed over the window.
1014    Hour,
1015    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1016    #[serde(other)]
1017    Unknown,
1018}
1019
1020/// Which visual the SPA renders an [`AggregateWidget`] as.
1021#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1022#[serde(rename_all = "lowercase")]
1023#[non_exhaustive]
1024pub enum AggregateRender {
1025    /// Ranked horizontal bars (a grouped `count` / `sum`).
1026    Bar,
1027    /// A single ratio dial (`agg: ratio`).
1028    Gauge,
1029    /// 24-hour activity strip (`time_bucket: hour`).
1030    Timeline,
1031    /// A single headline number (an ungrouped total).
1032    Stat,
1033    /// Per-PC operational swimlane (power / session / sleep) reconstructed
1034    /// from a fixed multi-kind event set. Unlike the aggregation renders it
1035    /// reads no single `kind`/`agg`: the backend returns the raw events in
1036    /// the window and the SPA folds them into lane spans (shared with the
1037    /// Events page strip). Per-PC only (`scope: pc`).
1038    #[serde(rename = "op_timeline")]
1039    OpTimeline,
1040    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1041    #[serde(other)]
1042    Unknown,
1043}
1044
1045/// True if `p` is a well-formed dotted JSON path of `[A-Za-z0-9_]`
1046/// segments joined by single dots — the shape safe to bind into
1047/// `json_extract(payload, '$.' || ?)`. The charset blocks injection; the
1048/// segment check additionally rejects `"."`, `".foo"`, `"foo."`,
1049/// `"foo..bar"`, which would pass the charset but produce a malformed
1050/// `$.` path that errors at query time. Accepts `pc_id`, `foreground.app`,
1051/// `active`, etc.
1052fn is_valid_json_path(p: &str) -> bool {
1053    !p.is_empty()
1054        && p.split('.').all(|seg| {
1055            !seg.is_empty() && seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
1056        })
1057}
1058
1059/// Per-widget validation for a list of [`AggregateWidget`]s — shared by
1060/// the `aggregate:` job hint ([`Manifest::validate`]) and the standalone
1061/// [`View`] resource (#743) so the two can't diverge. `field` names the
1062/// containing key for error messages (`"aggregate"` or `"widgets"`).
1063///
1064/// Enforces: non-empty list; non-empty dashboard/title (and `kind`/`agg`
1065/// for every aggregation render); a blank-when-set `source`; rejection of
1066/// any #492 `Unknown` enum (an operator typo at create time); safe dotted
1067/// JSON paths; the value path each `agg` needs (and rejection of mis-paired
1068/// ones); `pc_id` grouping only in `fleet` scope; `transform`/`limit`/
1069/// `exclude` only with a `group_by`; positive `limit`/`sample_minutes`;
1070/// `gauge`⇔`ratio`; and `timeline`⇔`time_bucket`. A `render: op_timeline`
1071/// widget is validated separately (per-PC, no aggregation knobs) — see
1072/// [`validate_op_timeline_widget`].
1073pub fn validate_aggregate_widgets(widgets: &[AggregateWidget], field: &str) -> Result<(), String> {
1074    if widgets.is_empty() {
1075        return Err(format!(
1076            "`{field}:` must list at least one widget when present"
1077        ));
1078    }
1079    for (i, w) in widgets.iter().enumerate() {
1080        let at = format!("{field}[{i}]");
1081        for (label, value) in [("dashboard", &w.dashboard), ("title", &w.title)] {
1082            if value.trim().is_empty() {
1083                return Err(format!("{at}.{label} must not be empty"));
1084            }
1085        }
1086        // A present-but-blank `description` renders an empty muted line —
1087        // reject it so the subtitle only shows when it says something.
1088        if let Some(description) = &w.description {
1089            if description.trim().is_empty() {
1090                return Err(format!("{at}.description must not be empty when set"));
1091            }
1092        }
1093        // Reject values that fell through to the #492 `Unknown` catch-all:
1094        // at create time on the current version that's an operator typo. (A
1095        // genuinely-future variant only reaches an older reader via a stored
1096        // resource, which is never re-validated, so forward-compat holds.)
1097        if w.scope == AggregateScope::Unknown {
1098            return Err(format!("{at}.scope is not a known value (pc | fleet)"));
1099        }
1100        if w.render == AggregateRender::Unknown {
1101            return Err(format!(
1102                "{at}.render is not a known value (bar | gauge | timeline | stat | op_timeline)"
1103            ));
1104        }
1105        // `op_timeline` reconstructs a fixed per-PC operational swimlane
1106        // (power/session/sleep) from a baked-in multi-kind set — it uses none
1107        // of the aggregation knobs, so validate it on its own terms (per-PC,
1108        // no `kind`/`agg`/grouping) and skip the rollup rules below.
1109        if w.render == AggregateRender::OpTimeline {
1110            validate_op_timeline_widget(w, &at)?;
1111            continue;
1112        }
1113        // Every other render is an aggregation over a single `kind`.
1114        if w.kind.as_deref().map(str::trim).unwrap_or("").is_empty() {
1115            return Err(format!("{at}.kind must not be empty"));
1116        }
1117        let agg = match w.agg {
1118            Some(AggregateAgg::Unknown) => {
1119                return Err(format!(
1120                    "{at}.agg is not a known value (count | ratio | sum)"
1121                ));
1122            }
1123            Some(agg) => agg,
1124            None => return Err(format!("{at}.agg is required")),
1125        };
1126        // A present-but-blank `source` is a no-op filter — reject like the
1127        // other blank-when-set guards.
1128        if let Some(source) = &w.source {
1129            if source.trim().is_empty() {
1130                return Err(format!("{at}.source must not be empty when set"));
1131            }
1132        }
1133        if w.transform == Some(AggregateTransform::Unknown) {
1134            return Err(format!("{at}.transform is not a known value (host)"));
1135        }
1136        if w.time_bucket == Some(AggregateTimeBucket::Unknown) {
1137            return Err(format!("{at}.time_bucket is not a known value (hour)"));
1138        }
1139        for (label, path) in [
1140            ("group_by", &w.group_by),
1141            ("bool_path", &w.bool_path),
1142            ("value_path", &w.value_path),
1143        ] {
1144            if let Some(p) = path {
1145                if !is_valid_json_path(p) {
1146                    return Err(format!(
1147                        "{at}.{label} '{p}' must be a dotted JSON path of [A-Za-z0-9_] segments"
1148                    ));
1149                }
1150            }
1151        }
1152        // Each agg uses exactly one value path; reject a mis-paired path so
1153        // a typo fails at create rather than being ignored.
1154        match agg {
1155            // count: grouped → ranking, ungrouped → grand total.
1156            AggregateAgg::Count => {
1157                for (label, path) in [("bool_path", &w.bool_path), ("value_path", &w.value_path)] {
1158                    if path.is_some() {
1159                        return Err(format!("{at}.agg=count does not use `{label}`"));
1160                    }
1161                }
1162            }
1163            AggregateAgg::Ratio => {
1164                if w.bool_path.is_none() {
1165                    return Err(format!("{at}.agg=ratio requires `bool_path`"));
1166                }
1167                if w.value_path.is_some() {
1168                    return Err(format!("{at}.agg=ratio does not use `value_path`"));
1169                }
1170            }
1171            AggregateAgg::Sum => {
1172                if w.value_path.is_none() {
1173                    return Err(format!("{at}.agg=sum requires `value_path`"));
1174                }
1175                if w.bool_path.is_some() {
1176                    return Err(format!("{at}.agg=sum does not use `bool_path`"));
1177                }
1178            }
1179            // Rejected above; arm exists only for exhaustiveness.
1180            AggregateAgg::Unknown => {}
1181        }
1182        // Ranking PCs against each other only means something across the
1183        // fleet — within one PC it's a single bar.
1184        if w.group_by.as_deref() == Some("pc_id") && w.scope != AggregateScope::Fleet {
1185            return Err(format!(
1186                "{at}.group_by: pc_id is only valid with scope: fleet"
1187            ));
1188        }
1189        // `transform` rewrites the grouped PAYLOAD value (URL→host); it's
1190        // meaningless on a `pc_id` grouping (the pc_id column, not a payload
1191        // field), so reject the combo at create time.
1192        if w.transform.is_some() && w.group_by.as_deref() == Some("pc_id") {
1193            return Err(format!("{at}.transform is not valid with group_by: pc_id"));
1194        }
1195        // limit / transform / exclude all operate on grouped values, so
1196        // without a `group_by` they're silent no-ops — reject.
1197        if w.group_by.is_none() {
1198            if w.limit.is_some() {
1199                return Err(format!("{at}.limit requires `group_by`"));
1200            }
1201            if w.transform.is_some() {
1202                return Err(format!("{at}.transform requires `group_by`"));
1203            }
1204            if !w.exclude.is_empty() {
1205                return Err(format!("{at}.exclude requires `group_by`"));
1206            }
1207        }
1208        if w.limit == Some(0) {
1209            return Err(format!("{at}.limit must be > 0"));
1210        }
1211        if w.sample_minutes == Some(0) {
1212            return Err(format!("{at}.sample_minutes must be > 0"));
1213        }
1214        for ex in &w.exclude {
1215            if ex.trim().is_empty() {
1216                return Err(format!("{at}.exclude must not contain empty entries"));
1217            }
1218        }
1219        // A gauge draws a single ratio dial — only meaningful for agg: ratio.
1220        if w.render == AggregateRender::Gauge && agg != AggregateAgg::Ratio {
1221            return Err(format!("{at}.render=gauge is only valid with agg: ratio"));
1222        }
1223        // A timeline needs a bucket; a bucket on any other render is a no-op
1224        // that signals operator confusion — reject both.
1225        match (w.render, &w.time_bucket) {
1226            (AggregateRender::Timeline, None) => {
1227                return Err(format!("{at}.render=timeline requires `time_bucket`"));
1228            }
1229            (r, Some(_)) if r != AggregateRender::Timeline => {
1230                return Err(format!(
1231                    "{at}.time_bucket is only valid with render: timeline"
1232                ));
1233            }
1234            _ => {}
1235        }
1236    }
1237    Ok(())
1238}
1239
1240/// Validate a `render: op_timeline` widget. It draws a fixed per-PC
1241/// operational swimlane (power / session / sleep) reconstructed by the SPA
1242/// from a baked-in multi-kind event set, so it uses none of the aggregation
1243/// knobs: require `scope: pc` and reject every field that only makes sense
1244/// for a rollup (`kind`/`source`/`agg`/`group_by`/`bool_path`/`value_path`/
1245/// `transform`/`sample_minutes`/`exclude`/`time_bucket`/`limit`). Rejecting
1246/// the unused fields (rather than ignoring them) keeps an operator typo from
1247/// silently doing nothing, matching the rest of this validator.
1248fn validate_op_timeline_widget(w: &AggregateWidget, at: &str) -> Result<(), String> {
1249    // Per-PC only: a fleet-wide swimlane of every PC's spans is unbounded
1250    // and unreadable, and the backend only computes it in per-PC scope.
1251    if w.scope != AggregateScope::Pc {
1252        return Err(format!("{at}.render=op_timeline requires scope: pc"));
1253    }
1254    // Each unused field, with the name the operator wrote, so the error
1255    // points at exactly what to delete.
1256    if w.kind.is_some() {
1257        return Err(format!("{at}.render=op_timeline does not use `kind`"));
1258    }
1259    if w.source.is_some() {
1260        return Err(format!("{at}.render=op_timeline does not use `source`"));
1261    }
1262    if w.agg.is_some() {
1263        return Err(format!("{at}.render=op_timeline does not use `agg`"));
1264    }
1265    for (label, set) in [
1266        ("group_by", w.group_by.is_some()),
1267        ("bool_path", w.bool_path.is_some()),
1268        ("value_path", w.value_path.is_some()),
1269        ("transform", w.transform.is_some()),
1270        ("sample_minutes", w.sample_minutes.is_some()),
1271        ("time_bucket", w.time_bucket.is_some()),
1272        ("limit", w.limit.is_some()),
1273        ("exclude", !w.exclude.is_empty()),
1274    ] {
1275        if set {
1276            return Err(format!("{at}.render=op_timeline does not use `{label}`"));
1277        }
1278    }
1279    Ok(())
1280}
1281
1282/// Default materialization cadence for a [`SqlWidget`] whose `refresh` is
1283/// unset — 1 hour. A view over feed/inventory tables changes only as fast as
1284/// its underlying feed refresh (often daily), so an hour is fresh enough while
1285/// keeping an expensive correlation join off the ~30s Dashboard poll path.
1286pub const DEFAULT_VIEW_REFRESH: std::time::Duration = std::time::Duration::from_secs(3600);
1287
1288/// #vuln-roadmap PR3: a **SQL-backed, materialized** widget on a [`View`].
1289///
1290/// Where an [`AggregateWidget`] encodes an `obs_events` rollup in structured
1291/// YAML fields, a `SqlWidget` carries a raw read-only `SELECT`/`WITH` over the
1292/// projector's tables (inventory `explode:` tables, `feeds`, `check_status`,
1293/// …) — the correlation that powers a vulnerability / EOL / license dashboard
1294/// is just a `JOIN`, far more expressive than a YAML DSL. The backend runs the
1295/// query in the read-only sandbox (`api::query`), caches the result on the
1296/// `refresh` cadence, and maps it to the same render-ready shape the existing
1297/// widget components consume, via [`RenderSpec`]. See [`View::sql_widgets`].
1298#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1299pub struct SqlWidget {
1300    /// Widget heading. Required, validated non-empty.
1301    pub title: String,
1302    /// Optional muted subtitle (a unit, a caveat). Rejected if present-blank.
1303    #[serde(default, skip_serializing_if = "Option::is_none")]
1304    pub description: Option<String>,
1305    /// The read-only SQL. Executed in the `api::query` sandbox: a single
1306    /// `SELECT`/`WITH` on a `SQLITE_OPEN_READONLY` connection, row-capped and
1307    /// time-bounded. The backend validates it read-only at `view create` and
1308    /// again at run time; a write verb / stacked statement is rejected.
1309    pub query: String,
1310    /// How the query's result columns map to a visual — see [`RenderSpec`].
1311    pub render: RenderSpec,
1312    /// Materialization cadence as a humantime duration (`"6h"`, `"30m"`).
1313    /// Absent ⇒ [`DEFAULT_VIEW_REFRESH`]. The backend re-runs the query at
1314    /// most this often; reads in between hit the cache.
1315    #[serde(default, skip_serializing_if = "Option::is_none")]
1316    pub refresh: Option<String>,
1317    /// Where the widget surfaces — an Analytics tab and/or a pinned Dashboard
1318    /// card. At least one must be set (else it renders nowhere).
1319    pub placement: Placement,
1320}
1321
1322impl SqlWidget {
1323    /// The effective refresh cadence — the parsed `refresh` or
1324    /// [`DEFAULT_VIEW_REFRESH`]. Falls back to the default on an unparseable
1325    /// value rather than panicking on the read path (validation already
1326    /// rejected a bad value at `view create`).
1327    pub fn refresh_interval(&self) -> std::time::Duration {
1328        self.refresh
1329            .as_deref()
1330            .and_then(|s| humantime::parse_duration(s).ok())
1331            .unwrap_or(DEFAULT_VIEW_REFRESH)
1332    }
1333}
1334
1335/// How a [`SqlWidget`]'s SQL result columns map onto a visual. A `kind` names
1336/// the chart; the channel fields (`value`, `label`, `columns`, …) name which
1337/// result columns feed it. Only the channels a `kind` uses are read; the
1338/// backend validates the named columns exist in the result. New chart types
1339/// are "one renderer + the same mapping", so this stays a flat, additive shape.
1340#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Hash)]
1341pub struct RenderSpec {
1342    /// Which visual to render the result as.
1343    pub kind: RenderKind,
1344    /// `table` only: the columns to show, in order. Absent ⇒ every result
1345    /// column (the universal default).
1346    #[serde(default, skip_serializing_if = "Option::is_none")]
1347    pub columns: Option<Vec<String>>,
1348    /// `table` only: optional per-column header relabelling (result column →
1349    /// display name). Columns not listed keep their SQL name.
1350    #[serde(default, skip_serializing_if = "Option::is_none")]
1351    pub labels: Option<std::collections::BTreeMap<String, String>>,
1352    /// `stat` / `bar` / `pie` / `gauge`: the result column holding the numeric
1353    /// value (`stat`/`gauge` read the first row; `bar`/`pie` read every row).
1354    #[serde(default, skip_serializing_if = "Option::is_none")]
1355    pub value: Option<String>,
1356    /// `bar` / `pie`: the result column holding each row's category label.
1357    #[serde(default, skip_serializing_if = "Option::is_none")]
1358    pub label: Option<String>,
1359    /// `bar` / `pie`: keep only the top-N rows (by value). Absent ⇒ all rows.
1360    #[serde(default, skip_serializing_if = "Option::is_none")]
1361    pub limit: Option<u32>,
1362    /// `pie` only: render as a donut (a hole with the total in the centre).
1363    #[serde(default, skip_serializing_if = "Option::is_none")]
1364    pub donut: Option<bool>,
1365    /// `gauge` only: the numerator column (paired with `den`). Alternative to
1366    /// a precomputed `value` ratio.
1367    #[serde(default, skip_serializing_if = "Option::is_none")]
1368    pub num: Option<String>,
1369    /// `gauge` only: the denominator column (paired with `num`).
1370    #[serde(default, skip_serializing_if = "Option::is_none")]
1371    pub den: Option<String>,
1372}
1373
1374/// The chart kind for a [`RenderSpec`]. `table` and `pie` are new in PR3; the
1375/// rest reuse the existing `obs_events` widget renderers.
1376#[derive(
1377    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash, Default,
1378)]
1379#[serde(rename_all = "lowercase")]
1380pub enum RenderKind {
1381    /// The full result grid (new renderer). The universal default.
1382    #[default]
1383    Table,
1384    /// A single headline number from the first row's `value` cell.
1385    Stat,
1386    /// Ranked horizontal bars — `label` + `value` per row, optional top-N.
1387    Bar,
1388    /// Parts-of-a-whole (new renderer) — `label` + `value` per row.
1389    Pie,
1390    /// A ratio dial — a `value` ratio, or a `num`/`den` pair.
1391    Gauge,
1392    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1393    #[serde(other)]
1394    Unknown,
1395}
1396
1397/// Where a [`SqlWidget`] surfaces in the SPA. Mirrors the placement an
1398/// [`AggregateWidget`] expresses via `dashboard` + `pin_dashboard`, but as an
1399/// explicit block since a SQL widget lives on a standalone view.
1400#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1401pub struct Placement {
1402    /// The Analytics tab this widget groups under (the `AggregateWidget`
1403    /// `dashboard` analogue). Absent ⇒ not shown on the Analytics page.
1404    #[serde(default, skip_serializing_if = "Option::is_none")]
1405    pub analytics: Option<String>,
1406    /// Promote to the main Dashboard (reuses #900's pinned section). Absent ⇒
1407    /// not pinned.
1408    #[serde(default, skip_serializing_if = "Option::is_none")]
1409    pub dashboard: Option<DashboardPlacement>,
1410}
1411
1412impl Placement {
1413    /// True when the widget is pinned to the main Dashboard.
1414    pub fn is_pinned(&self) -> bool {
1415        self.dashboard.as_ref().is_some_and(|d| d.pin)
1416    }
1417    /// The Analytics tab name, or a fallback so a dashboard-only widget still
1418    /// carries a group label for the shared widget list.
1419    pub fn tab(&self) -> &str {
1420        self.analytics.as_deref().unwrap_or("Dashboard")
1421    }
1422}
1423
1424/// The `placement.dashboard` block — see [`Placement::dashboard`].
1425#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1426pub struct DashboardPlacement {
1427    /// Pin this widget to the main Dashboard's promoted section.
1428    #[serde(default)]
1429    pub pin: bool,
1430}
1431
1432/// Per-widget validation for a list of [`SqlWidget`]s — shared by the
1433/// [`View`] resource so authoring errors surface at `view create`. `field`
1434/// names the containing key for error messages. The read-only SQL check is
1435/// NOT here (it lives in the backend `api::query` sandbox, which kanade-shared
1436/// can't depend on) — this validates structure: non-empty title/query, a
1437/// known `kind`, the channels each `kind` needs, a real placement, and a
1438/// parseable `refresh`.
1439pub fn validate_sql_widgets(widgets: &[SqlWidget], field: &str) -> Result<(), String> {
1440    for (i, w) in widgets.iter().enumerate() {
1441        let at = format!("{field}[{i}]");
1442        if w.title.trim().is_empty() {
1443            return Err(format!("{at}.title must not be empty"));
1444        }
1445        if w.query.trim().is_empty() {
1446            return Err(format!("{at}.query must not be empty"));
1447        }
1448        if let Some(description) = &w.description {
1449            if description.trim().is_empty() {
1450                return Err(format!("{at}.description must not be empty when set"));
1451            }
1452        }
1453        if let Some(refresh) = &w.refresh {
1454            humantime::parse_duration(refresh)
1455                .map_err(|e| format!("{at}.refresh '{refresh}' is not a valid duration: {e}"))?;
1456        }
1457        // A widget that surfaces nowhere is an invisible no-op. A
1458        // `dashboard:` block with `pin: false` doesn't count — it pins
1459        // nowhere — so gate on the effective pin, not the block's presence
1460        // (Gemini / CodeRabbit).
1461        if w.placement.analytics.is_none() && !w.placement.is_pinned() {
1462            return Err(format!(
1463                "{at}.placement must set `analytics` and/or pin to `dashboard` (else the widget renders nowhere)"
1464            ));
1465        }
1466        if let Some(tab) = &w.placement.analytics {
1467            if tab.trim().is_empty() {
1468                return Err(format!(
1469                    "{at}.placement.analytics must not be empty when set"
1470                ));
1471            }
1472        }
1473        // A per-PC widget (its query binds `:pc_id`) renders only in the
1474        // per-PC Analytics scope, bound to the selected PC. The Dashboard's
1475        // pinned section is fleet-scope and never sends a PC, so a pinned
1476        // per-PC widget would be silently dropped on every request — reject
1477        // the contradiction at create time rather than let it vanish (claude
1478        // review). Literal-aware so a `:pc_id` inside a string literal doesn't
1479        // trip it (see [`rewrite_pc_id_param`]).
1480        if w.placement.is_pinned() && rewrite_pc_id_param(&w.query).1 > 0 {
1481            return Err(format!(
1482                "{at}: a per-PC widget (its query binds `:pc_id`) cannot pin to the Dashboard \
1483                 (the Dashboard is fleet-scope, it never selects a PC) — use `analytics` placement only"
1484            ));
1485        }
1486        validate_render_spec(&w.render, &at)?;
1487    }
1488    Ok(())
1489}
1490
1491/// The named parameter a per-PC [`SqlWidget`] binds to the selected PC. Its
1492/// presence in a widget's query is what makes the widget per-PC.
1493pub const PC_ID_PARAM: &str = ":pc_id";
1494
1495/// Rewrite every *real* `:pc_id` parameter in a widget query to a positional
1496/// `?`, returning `(rewritten_sql, count)`. "Real" = OUTSIDE string literals,
1497/// quoted identifiers and comments, and a whole token (the char after `:pc_id`
1498/// isn't a word char, so `:pc_idx` is left alone). One scanner shared by three
1499/// call sites so they can't disagree on how many `?` SQLite will actually see:
1500///   * per-PC scope detection (`count > 0` ⇒ the widget is per-PC),
1501///   * the backend's bind path (sqlx-sqlite binds POSITIONAL `?` only, not
1502///     `:name`, so the token must be rewritten and bound once per occurrence),
1503///   * and `validate_sql_widgets`' pinned-per-PC rejection above.
1504///
1505/// The literal/comment skipping mirrors the read-only sandbox's
1506/// `strip_sql_noise`, so a `:pc_id` inside `SELECT 'see :pc_id docs'` is copied
1507/// verbatim and NOT counted — it would otherwise be miscounted (a bind-count
1508/// mismatch → `SQLITE_RANGE`) and misclassify the widget's scope (Gemini /
1509/// claude review).
1510pub fn rewrite_pc_id_param(sql: &str) -> (String, usize) {
1511    let mut out = String::with_capacity(sql.len());
1512    let mut count = 0usize;
1513    let mut chars = sql.char_indices().peekable();
1514    while let Some((idx, c)) = chars.next() {
1515        match c {
1516            // String literal / quoted identifier — copy verbatim, honouring the
1517            // doubled-quote escape (`''` / `""` stays inside).
1518            '\'' | '"' => {
1519                out.push(c);
1520                let quote = c;
1521                while let Some((_, d)) = chars.next() {
1522                    out.push(d);
1523                    if d == quote {
1524                        if chars.peek().map(|&(_, e)| e) == Some(quote) {
1525                            let (_, e) = chars.next().unwrap();
1526                            out.push(e);
1527                        } else {
1528                            break;
1529                        }
1530                    }
1531                }
1532            }
1533            // Line comment — copy to end of line.
1534            '-' if chars.peek().map(|&(_, e)| e) == Some('-') => {
1535                out.push(c);
1536                for (_, d) in chars.by_ref() {
1537                    out.push(d);
1538                    if d == '\n' {
1539                        break;
1540                    }
1541                }
1542            }
1543            // Block comment — copy to `*/`.
1544            '/' if chars.peek().map(|&(_, e)| e) == Some('*') => {
1545                out.push(c);
1546                let (_, star) = chars.next().unwrap();
1547                out.push(star);
1548                let mut prev = ' ';
1549                for (_, d) in chars.by_ref() {
1550                    out.push(d);
1551                    if prev == '*' && d == '/' {
1552                        break;
1553                    }
1554                    prev = d;
1555                }
1556            }
1557            // A `:pc_id` token outside any literal/comment — rewrite if it's a
1558            // whole token (not the prefix of `:pc_idx`).
1559            ':' if sql[idx..].starts_with(PC_ID_PARAM) => {
1560                let after = idx + PC_ID_PARAM.len();
1561                let next_is_word = sql[after..]
1562                    .chars()
1563                    .next()
1564                    .is_some_and(|w| w.is_alphanumeric() || w == '_');
1565                if next_is_word {
1566                    out.push(c);
1567                } else {
1568                    out.push('?');
1569                    count += 1;
1570                    for _ in 0..PC_ID_PARAM.chars().count() - 1 {
1571                        chars.next();
1572                    }
1573                }
1574            }
1575            _ => out.push(c),
1576        }
1577    }
1578    (out, count)
1579}
1580
1581/// Validate a [`RenderSpec`]: reject the #492 `Unknown` catch-all (an operator
1582/// typo at create time) and require the channel columns each `kind` reads.
1583fn validate_render_spec(r: &RenderSpec, at: &str) -> Result<(), String> {
1584    // A channel column is "given" when present and non-blank.
1585    let given = |v: &Option<String>| v.as_deref().map(str::trim).is_some_and(|s| !s.is_empty());
1586    match r.kind {
1587        RenderKind::Unknown => {
1588            return Err(format!(
1589                "{at}.render.kind is not a known value (table | stat | bar | pie | gauge)"
1590            ));
1591        }
1592        RenderKind::Table => {
1593            // `columns` optional; if given, each name must be non-blank.
1594            if let Some(cols) = &r.columns {
1595                if cols.iter().any(|c| c.trim().is_empty()) {
1596                    return Err(format!("{at}.render.columns must not contain blank names"));
1597                }
1598            }
1599            if let Some(labels) = &r.labels {
1600                for (k, v) in labels {
1601                    if k.trim().is_empty() || v.trim().is_empty() {
1602                        return Err(format!(
1603                            "{at}.render.labels keys and values must be non-empty"
1604                        ));
1605                    }
1606                }
1607            }
1608        }
1609        RenderKind::Stat => {
1610            if !given(&r.value) {
1611                return Err(format!("{at}.render.value is required for kind=stat"));
1612            }
1613        }
1614        RenderKind::Bar | RenderKind::Pie => {
1615            let kind = if r.kind == RenderKind::Bar {
1616                "bar"
1617            } else {
1618                "pie"
1619            };
1620            if !given(&r.label) {
1621                return Err(format!("{at}.render.label is required for kind={kind}"));
1622            }
1623            if !given(&r.value) {
1624                return Err(format!("{at}.render.value is required for kind={kind}"));
1625            }
1626            // `limit: 0` truncates to no rows — an invisible widget, almost
1627            // certainly a typo. Omit `limit` for "all rows" (CodeRabbit).
1628            if r.limit == Some(0) {
1629                return Err(format!(
1630                    "{at}.render.limit must be >= 1 (omit it to keep all rows)"
1631                ));
1632            }
1633        }
1634        RenderKind::Gauge => {
1635            // Either a precomputed `value` ratio, or a `num`/`den` pair —
1636            // exactly one of the two forms.
1637            match (given(&r.value), given(&r.num), given(&r.den)) {
1638                (true, false, false) => {}
1639                (false, true, true) => {}
1640                _ => {
1641                    return Err(format!(
1642                        "{at}.render for kind=gauge needs either `value` (a ratio) or both `num` and `den`"
1643                    ));
1644                }
1645            }
1646        }
1647    }
1648    Ok(())
1649}
1650
1651/// A standalone declarative read/aggregation for the Analytics page (#743).
1652///
1653/// A **view** aggregates stored fleet data (`obs_events`, …) without an
1654/// `execute` or a schedule — unlike a [`Manifest`] it only declares
1655/// [`AggregateWidget`]s. (The first line is concise on purpose: `schemars`
1656/// uses it as the generated schema's `title`.) The backend reads views from
1657/// `BUCKET_VIEWS` at
1658/// query time and merges their widgets with the co-located `aggregate:`
1659/// hints on jobs, so a cross-cutting dashboard (one that charts events
1660/// emitted by several other jobs / the agent) has a home that doesn't need
1661/// a noop job carrier. Stored JSON in `BUCKET_VIEWS`, keyed by `id`.
1662#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1663pub struct View {
1664    /// Stable identifier (the KV key). Required, validated non-empty.
1665    pub id: String,
1666    /// Optional human description shown on the Views admin page.
1667    #[serde(default, skip_serializing_if = "Option::is_none")]
1668    pub description: Option<String>,
1669    /// The `obs_events` aggregate widgets this view contributes to the
1670    /// Analytics page. Optional since PR3 — a view may instead (or also)
1671    /// carry [`sql_widgets`](View::sql_widgets); a view must have at least one
1672    /// widget across the two lists.
1673    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1674    pub widgets: Vec<AggregateWidget>,
1675    /// #vuln-roadmap PR3: SQL-backed, materialized widgets — raw read-only SQL
1676    /// over the projector tables (inventory/feeds/…) mapped to a visual. This
1677    /// is how a correlation dashboard (vulnerability / EOL / license) is
1678    /// expressed as config. See [`SqlWidget`].
1679    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1680    pub sql_widgets: Vec<SqlWidget>,
1681    /// Free-form operator taxonomy (same role as [`Manifest::tags`]).
1682    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1683    pub tags: Vec<String>,
1684    /// GitOps provenance (#678), stamped by `kanade view create` from the
1685    /// source YAML's Git context — same as [`Manifest::origin`].
1686    #[serde(default, skip_serializing_if = "Option::is_none")]
1687    pub origin: Option<RepoOrigin>,
1688}
1689
1690/// True if `id` is a safe resource identifier — non-empty and only
1691/// `[A-Za-z0-9._-]`. A view `id` becomes a NATS KV key *and* a URL path
1692/// segment (`/api/views/{id}`), so this blocks `/`, `..`, whitespace and
1693/// other characters that would break the KV key or let a CLI arg wander
1694/// the URL space. (#743 / #744 follow-up — a deliberately small charset
1695/// rather than the looser set NATS technically allows.)
1696pub fn is_valid_resource_id(id: &str) -> bool {
1697    !id.is_empty()
1698        && id
1699            .chars()
1700            .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-')
1701}
1702
1703impl View {
1704    pub fn validate(&self) -> Result<(), String> {
1705        if !is_valid_resource_id(self.id.trim()) {
1706            return Err(
1707                "view.id must be non-empty and only [A-Za-z0-9._-] (it's a KV key + URL segment)"
1708                    .to_string(),
1709            );
1710        }
1711        // A view must contribute at least one widget across the two lists;
1712        // `validate_aggregate_widgets` rejects an empty `widgets` on its own,
1713        // so only call it when that list is non-empty (a pure-SQL view is
1714        // valid with an empty `widgets`).
1715        if self.widgets.is_empty() && self.sql_widgets.is_empty() {
1716            return Err(
1717                "view must declare at least one widget (`widgets:` and/or `sql_widgets:`)"
1718                    .to_string(),
1719            );
1720        }
1721        if !self.widgets.is_empty() {
1722            validate_aggregate_widgets(&self.widgets, "widgets")?;
1723        }
1724        validate_sql_widgets(&self.sql_widgets, "sql_widgets")?;
1725        for tag in &self.tags {
1726            if tag.trim().is_empty() {
1727                return Err("tags must not contain empty entries".to_string());
1728            }
1729        }
1730        Ok(())
1731    }
1732}
1733
1734/// Issue #246 — `emit:` manifest block for jobs whose stdout is
1735/// NDJSON observability events (one `ObsEvent` per line). Parallel
1736/// to `inventory:` but for the append-only timeline pipeline; see
1737/// `Manifest::emit` for the full contract.
1738#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1739pub struct EmitConfig {
1740    /// What kind of payload the agent should expect on stdout. Only
1741    /// `events` is defined today (parses each non-empty line as
1742    /// `ObsEvent` and publishes on `obs.<pc_id>`); future variants
1743    /// (e.g. metrics streams, structured trace events) plug in here.
1744    #[serde(rename = "type")]
1745    pub kind: EmitKind,
1746    /// Operator hint for where the script keeps its own state — the
1747    /// watermark file the PowerShell / sh body reads + writes
1748    /// between runs so it only emits NEW events since the last
1749    /// poll. The agent doesn't read this; it's documentation that
1750    /// the SPA (and `kanade job edit`) can surface to operators
1751    /// reviewing the manifest. Optional; the script is allowed to
1752    /// keep state anywhere (registry, env, etc.) — the field's
1753    /// presence makes the convention discoverable.
1754    #[serde(default, skip_serializing_if = "Option::is_none")]
1755    pub watermark_path: Option<String>,
1756}
1757
1758/// `emit.type` enum. Lowercase serde so manifests read
1759/// `type: events` rather than `Events`.
1760#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1761#[serde(rename_all = "lowercase")]
1762pub enum EmitKind {
1763    /// Per-line `ObsEvent` JSON. Agent parses + publishes on
1764    /// `obs.<pc_id>`, drops the stdout from the resulting
1765    /// `ExecResult`.
1766    Events,
1767}
1768
1769/// v0.31 / #40: declarative "flatten this JSON array into a real
1770/// SQLite table" spec on an inventory manifest. The projector
1771/// creates the table on first registration (CREATE TABLE IF NOT
1772/// EXISTS + indexes) and writes a row per element of
1773/// `payload[field]` on every result, scoped by (pc_id, job_id) so
1774/// each PC's rows replace cleanly without a per-PC schema.
1775#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1776pub struct ExplodeSpec {
1777    /// JSON array key under the payload to explode. E.g. `"apps"`
1778    /// for `payload: { apps: [{...}, {...}] }`.
1779    pub field: String,
1780    /// Derived SQLite table name. Operators choose this — pick
1781    /// something namespaced + stable (`inventory_sw_apps`, not
1782    /// `apps`) so multiple inventory manifests don't collide on a
1783    /// generic name.
1784    pub table: String,
1785    /// Element-level fields that uniquely identify a row inside one
1786    /// PC's payload. The full PK is `(pc_id, job_id) + these
1787    /// columns`. Required — operators must think about uniqueness
1788    /// (e.g. `["name", "source"]` for installed apps because the
1789    /// same name appears in multiple uninstall hives).
1790    ///
1791    /// v0.31 / #41: same tuple drives history identity. When
1792    /// `track_history` is on, the projector serialises these
1793    /// fields' values into `inventory_history.identity_json` for
1794    /// every change event, so queries like "every PC that ever
1795    /// installed Chrome (any source)" filter on identity_json
1796    /// content without a per-manifest schema.
1797    pub primary_key: Vec<String>,
1798    /// Per-element fields that become columns in the derived table.
1799    pub columns: Vec<ExplodeColumn>,
1800    /// v0.31 / #41: when true (default false), the projector
1801    /// diffs each PC's incoming payload against the prior rows
1802    /// for the same (pc_id, job_id) BEFORE the DELETE-then-INSERT
1803    /// replace, and writes added / removed / changed events into
1804    /// `inventory_history`. Lets operators answer time-dimension
1805    /// questions ("when did Chrome 120 first appear on PC X?",
1806    /// "what's the Win 11 23H2 rollout curve") without storing
1807    /// per-scan snapshots. Off by default so operators opt in
1808    /// per-spec — history has a real storage cost on long-lived
1809    /// deployments (mitigated by the 90-day default retention
1810    /// sweeper, see `cleanup` module).
1811    #[serde(default)]
1812    pub track_history: bool,
1813}
1814
1815/// One column in an [`ExplodeSpec`]'s derived table.
1816#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1817pub struct ExplodeColumn {
1818    /// JSON key under each array element. Becomes the column name
1819    /// in the derived SQLite table — we don't rename.
1820    pub field: String,
1821    /// SQLite affinity: `"text"` (default), `"integer"`, `"real"`.
1822    /// Storage maps directly via `sqlx::query.bind(...)`; type
1823    /// mismatches at INSERT-time fail loudly rather than silently
1824    /// dropping the row.
1825    #[serde(default, skip_serializing_if = "Option::is_none")]
1826    #[serde(rename = "type")]
1827    pub kind: Option<String>,
1828    /// When true, the projector creates a `CREATE INDEX` on this
1829    /// column at table-creation time. Boost for the common-filter
1830    /// columns (`name`, `version`) — operators mark them
1831    /// explicitly, the projector won't guess.
1832    #[serde(default)]
1833    pub index: bool,
1834}
1835
1836/// #vuln-roadmap: one declarative **external-data feed** on a `feed:`
1837/// manifest — see [`Manifest::feed`]. Unlike inventory [`ExplodeSpec`]
1838/// (keyed per `(pc_id, job_id)`), a feed is GLOBAL fleet-wide reference
1839/// data: the controller-tier job's script fetches + shapes it, prints the
1840/// array under [`field`](FeedSpec::field) inside a `#KANADE-FEED-BEGIN/END`
1841/// fence, and the projector REPLACES that feed's rows wholesale in the
1842/// shared `feeds` table keyed `(feed_id, item_id)`. The full element JSON
1843/// lands in a `data` column, so a `view:` SQL `json_extract`s whatever
1844/// shape the feed carries — no per-feed schema, no dynamic DDL. One
1845/// manifest may declare several feeds.
1846#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1847pub struct FeedSpec {
1848    /// Stable feed identifier — the `feed_id` partition in the shared
1849    /// `feeds` table. Operators choose this; namespace it (`cisa-kev`,
1850    /// `endoflife-windows`) so feeds don't collide. A new result for the
1851    /// same id replaces that partition wholesale.
1852    pub id: String,
1853    /// JSON array key under the (fenced) payload to ingest. E.g.
1854    /// `"vulnerabilities"` for `{ vulnerabilities: [{...}, {...}] }`.
1855    pub field: String,
1856    /// Element-level field(s) whose values uniquely identify an item
1857    /// within the feed — they form the `item_id` key (joined for a
1858    /// composite key). Required: operators must think about uniqueness
1859    /// (e.g. `["cveID"]` for CISA KEV). An element missing any of these is
1860    /// skipped (it has no stable identity).
1861    pub primary_key: Vec<String>,
1862}
1863
1864#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1865pub struct DisplayField {
1866    /// Top-level key in the stdout JSON.
1867    pub field: String,
1868    /// Human-readable column header.
1869    pub label: String,
1870    /// Optional render hint — `"number"`, `"bytes"`, `"timestamp"`,
1871    /// or `"table"` (#39). Defaults to plain text rendering on the
1872    /// SPA side. `"table"` expects the field's value to be a JSON
1873    /// array of objects and renders a nested sub-table on the
1874    /// per-PC detail page using `columns` as the schema; the fleet
1875    /// summary view falls back to showing the row count for
1876    /// `"table"` cells so the wide list stays compact.
1877    #[serde(default, skip_serializing_if = "Option::is_none")]
1878    #[serde(rename = "type")]
1879    pub kind: Option<String>,
1880    /// v0.30 / #39: when `kind == "table"`, the SPA renders the
1881    /// field's value (an array of objects like
1882    /// `disks: [{ device_id, size_bytes, ... }]`) as a nested
1883    /// sub-table using these columns. Each column is itself a
1884    /// `DisplayField`, so the nested cells reuse the same render
1885    /// hints (`bytes`, `number`, `timestamp`) — no parallel format
1886    /// pipeline. Ignored for any other `kind`.
1887    #[serde(default, skip_serializing_if = "Option::is_none")]
1888    pub columns: Option<Vec<DisplayField>>,
1889}
1890
1891#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1892pub struct Rollout {
1893    #[serde(default)]
1894    pub strategy: RolloutStrategy,
1895    pub waves: Vec<Wave>,
1896}
1897
1898#[derive(
1899    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
1900)]
1901#[serde(rename_all = "lowercase")]
1902pub enum RolloutStrategy {
1903    #[default]
1904    Wave,
1905}
1906
1907#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1908pub struct Wave {
1909    pub group: String,
1910    /// humantime delay measured from the deploy's publish time. wave[0]
1911    /// typically has "0s"; subsequent waves use minutes / hours.
1912    pub delay: String,
1913}
1914
1915#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default)]
1916pub struct Target {
1917    #[serde(default)]
1918    pub groups: Vec<String>,
1919    #[serde(default)]
1920    pub pcs: Vec<String>,
1921    #[serde(default)]
1922    pub all: bool,
1923}
1924
1925impl Target {
1926    /// At least one of all / groups / pcs is set.
1927    pub fn is_specified(&self) -> bool {
1928        self.all || !self.groups.is_empty() || !self.pcs.is_empty()
1929    }
1930
1931    /// Whether a PC (its `pc_id` + group membership) falls in this target:
1932    /// `all`, or the pc is listed, or it belongs to a listed group. Used
1933    /// by the agent to scope `client.visible_to` (#816). An unspecified
1934    /// target matches nobody (callers should treat "no target" as
1935    /// "visible to all" before calling this).
1936    pub fn matches(&self, pc_id: &str, groups: &[String]) -> bool {
1937        self.all
1938            || self.pcs.iter().any(|p| p == pc_id)
1939            || self.groups.iter().any(|g| groups.contains(g))
1940    }
1941}
1942
1943#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1944pub struct Execute {
1945    pub shell: ExecuteShell,
1946    /// Inline script body. Mutually exclusive with [`script_file`]
1947    /// and [`script_object`]; exactly one of the three must be set
1948    /// (enforced by [`Execute::validate_script_source`] at the
1949    /// write-side parse boundaries — `kanade job create` and
1950    /// `POST /api/jobs`).
1951    ///
1952    /// Empty string is treated as **unset** so operators can swap
1953    /// to a `script_file:` / `script_object:` alternative just by
1954    /// commenting out the body, without having to also drop the
1955    /// `script:` key entirely.
1956    ///
1957    /// [`script_file`]: Self::script_file
1958    /// [`script_object`]: Self::script_object
1959    #[serde(default, skip_serializing_if = "Option::is_none")]
1960    pub script: Option<String>,
1961    /// Repo-local file path resolved by the operator-side CLI at
1962    /// `kanade job create` time. The CLI reads the file, slots its
1963    /// contents into `script`, and clears this field before
1964    /// POSTing — so the backend / agents never see `script_file`
1965    /// in stored manifests. SPEC §2.4.1.
1966    ///
1967    /// The resolver shipped with #210: `kanade job create` /
1968    /// `kanade job validate` inline this field end-to-end. Because
1969    /// resolution is CLI-side (it needs the operator's filesystem),
1970    /// `POST /api/jobs` rejects a manifest that still carries it
1971    /// (#918) — a stored `script_file` job would 400 at every exec.
1972    /// Inline the script or use `script_object` when writing through
1973    /// the API / SPA editor.
1974    #[serde(default, skip_serializing_if = "Option::is_none")]
1975    pub script_file: Option<String>,
1976    /// Object Store reference (`<name>/<version>`) into the
1977    /// `scripts` bucket (`OBJECT_SCRIPTS`). Agents fetch the body
1978    /// at Execute time via `/api/script-objects/{name}/{version}`
1979    /// and cache it locally. SPEC §2.4.1.
1980    ///
1981    /// Fully wired (#210/#211): the backend resolves the digest at
1982    /// exec submission (`api::exec::resolve_script_source`), the agent
1983    /// fetches + sha-verifies + caches the body (`script_cache`), and
1984    /// `kanade script` CRUDs the store. Unlike `script_file:` (inlined
1985    /// CLI-side, git-managed), this keeps the body in versioned,
1986    /// digest-pinned object storage — the ops-managed counterpart.
1987    #[serde(default, skip_serializing_if = "Option::is_none")]
1988    pub script_object: Option<String>,
1989    /// humantime duration string (e.g. "30s", "10m"). Script-intrinsic
1990    /// — represents how long this script reasonably takes to run.
1991    pub timeout: String,
1992    /// Token + session combination the agent uses to launch the
1993    /// script (v0.21). Default = [`RunAs::System`] (Session 0,
1994    /// LocalSystem privileges, no GUI) — matches pre-v0.21 behavior.
1995    #[serde(default)]
1996    pub run_as: RunAs,
1997    /// Working directory for the spawned child (v0.21.1). When
1998    /// unset, the child inherits the agent's cwd — on Windows that
1999    /// means `%SystemRoot%\System32` for the prod service, which is
2000    /// almost never what operators actually want. Use an absolute
2001    /// path; relative paths are passed through to the OS verbatim.
2002    /// `%PROGRAMDATA%` works for `run_as: system`; for `run_as: user`
2003    /// you'd want `%USERPROFILE%` (but expansion happens in the
2004    /// shell, so write `$env:USERPROFILE` for PowerShell, or set
2005    /// it via teravars before `kanade job create`).
2006    #[serde(default, skip_serializing_if = "Option::is_none")]
2007    pub cwd: Option<String>,
2008}
2009
2010impl Execute {
2011    /// Treat an empty — or whitespace-only (#918) — `script:` body as
2012    /// "intentionally unset". Operators commenting out a block-scalar
2013    /// tend to leave the key behind, and failing the validator on
2014    /// `script: ""` would surprise them; a body of blank lines can't
2015    /// be a real script either, only a commented-out one, and letting
2016    /// it count as "set" shipped a validated do-nothing job.
2017    fn has_inline_script(&self) -> bool {
2018        matches!(&self.script, Some(s) if !s.trim().is_empty())
2019    }
2020
2021    /// Enforce that exactly one of `script` / `script_file` /
2022    /// `script_object` is set. Called at the write-side parse
2023    /// boundaries (CLI `kanade job create` + backend
2024    /// `POST /api/jobs`) so ambiguous YAML is rejected before it
2025    /// reaches the JOBS KV. Read paths (projector, agent
2026    /// scheduler, list endpoints) skip this check — they only ever
2027    /// see what the write path already validated.
2028    pub fn validate_script_source(&self) -> Result<(), String> {
2029        // #918: a blank-but-present alternate source is a typo, not a
2030        // choice — `script_file: ""` used to count as "set", pass the
2031        // exactly-one check, and only fail at use time (the CLI reads
2032        // a file named ""; a stored blank script_object 404s on every
2033        // exec). Reject it with the field named. Inline `script` keeps
2034        // its documented empty-means-unset semantics instead — see
2035        // `has_inline_script`.
2036        if matches!(&self.script_file, Some(s) if s.trim().is_empty()) {
2037            return Err(
2038                "execute.script_file must not be blank when set (drop the key to use \
2039                 another source)"
2040                    .into(),
2041            );
2042        }
2043        if matches!(&self.script_object, Some(s) if s.trim().is_empty()) {
2044            return Err(
2045                "execute.script_object must not be blank when set (drop the key to use \
2046                 another source)"
2047                    .into(),
2048            );
2049        }
2050        let inline = self.has_inline_script();
2051        let file = self.script_file.is_some();
2052        let obj = self.script_object.is_some();
2053        let set = [inline, file, obj].into_iter().filter(|b| *b).count();
2054        match set {
2055            1 => {}
2056            0 => {
2057                return Err(
2058                    "execute: one of `script`, `script_file`, `script_object` must be set".into(),
2059                );
2060            }
2061            _ => {
2062                return Err(format!(
2063                    "execute: only one of `script` / `script_file` / `script_object` may be set \
2064                     (got script={inline}, script_file={file}, script_object={obj})"
2065                ));
2066            }
2067        }
2068        // #918: a script_object ref is `<name>/<version>` — the agent
2069        // fetches the body via `/api/script-objects/{name}/{version}`
2070        // and the backend uses the ref *verbatim* as the Object Store
2071        // key (`resolve_script_source`), so each half must be a
2072        // well-formed resource id: exactly one slash, and both halves
2073        // [A-Za-z0-9._-]. `is_valid_resource_id` also rejects a half
2074        // that's blank OR merely whitespace-padded (`"foo/bar "`) —
2075        // padding survives a JSON POST body (unlike a YAML plain
2076        // scalar) and would 404 on every exec (gemini/claude #943).
2077        if let Some(obj_ref) = self.script_object.as_deref() {
2078            let parts: Vec<&str> = obj_ref.split('/').collect();
2079            if parts.len() != 2 || parts.iter().any(|p| !is_valid_resource_id(p)) {
2080                return Err(format!(
2081                    "execute.script_object must be `<name>/<version>` with each half \
2082                     [A-Za-z0-9._-] (got '{obj_ref}'); publish bodies with \
2083                     `kanade script publish <name> <version>`"
2084                ));
2085            }
2086        }
2087        Ok(())
2088    }
2089}
2090
2091/// Job-generic post-step hook (see [`Manifest::finalize`]). Runs after
2092/// the main `execute:` script (and the collect upload) on a clean exit,
2093/// with the step's structured result injected via an environment
2094/// variable. P1 supports an inline `script:` only — `script_file:` /
2095/// `script_object:` are follow-ups.
2096#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2097pub struct FinalizeSpec {
2098    pub shell: ExecuteShell,
2099    /// Inline script body (required; inline-only in P1).
2100    pub script: String,
2101    /// humantime duration string (e.g. `"60s"`, `"5m"`). Defaults to
2102    /// `60s` when unset.
2103    #[serde(default = "default_finalize_timeout")]
2104    pub timeout: String,
2105    /// Token + session combination, like [`Execute::run_as`]. Defaults
2106    /// to [`RunAs::System`].
2107    #[serde(default)]
2108    pub run_as: RunAs,
2109    /// Working directory for the hook child, like [`Execute::cwd`].
2110    #[serde(default, skip_serializing_if = "Option::is_none")]
2111    pub cwd: Option<String>,
2112}
2113
2114/// Default `finalize.timeout` when the operator omits it.
2115fn default_finalize_timeout() -> String {
2116    "60s".to_string()
2117}
2118
2119impl FinalizeSpec {
2120    /// Lower to the wire form forwarded onto a [`Command`]. The timeout
2121    /// parse falls back to 60s — [`Manifest::validate`] already rejects
2122    /// an unparseable value at create time, so the fire path uses a safe
2123    /// default rather than failing (mirrors
2124    /// [`CollectHint::max_size_bytes`]). A sub-second timeout floors at
2125    /// 1s for the same reason `build_command` does.
2126    pub fn lower(&self) -> FinalizeCommand {
2127        let timeout_secs = humantime::parse_duration(&self.timeout)
2128            .map(|d| d.as_secs().max(1))
2129            .unwrap_or(60);
2130        FinalizeCommand {
2131            shell: self.shell.into(),
2132            script: self.script.clone(),
2133            timeout_secs,
2134            run_as: self.run_as,
2135            cwd: self.cwd.clone(),
2136        }
2137    }
2138}
2139
2140impl Manifest {
2141    /// Cross-field semantic checks that don't fit into pure serde
2142    /// derive. Currently delegates to
2143    /// [`Execute::validate_script_source`] — see that method's
2144    /// docs for the rationale on which call sites should run this.
2145    pub fn validate(&self) -> Result<(), String> {
2146        self.execute.validate_script_source()?;
2147        // Fail CLOSED on an unrecognised execution tier. `#[serde(other)]`
2148        // turns a typo (`tier: controler`) or a future tier into
2149        // `Tier::Unknown`; without this check the controller gate would
2150        // fall back to normal endpoint dispatch, so an operator who *meant*
2151        // to confine a job to the controller tier would silently get
2152        // fleet-wide dispatch (CodeRabbit #905). Rejecting it at the write
2153        // boundary surfaces the typo at `job create`, and — since
2154        // `exec_manifest` re-validates — a hand-poked KV manifest can't slip
2155        // a controller-tier job onto endpoints either.
2156        if matches!(self.tier, Some(Tier::Unknown)) {
2157            return Err(
2158                "tier: unrecognised execution tier — use `endpoint` or `controller` \
2159                 (this is a typo, or a tier a newer kanade supports that this backend does not)"
2160                    .to_string(),
2161            );
2162        }
2163        // #vuln-roadmap: a `feed:` spec drives the global `feeds`
2164        // projection. id / item_id are stored as *values* (the `feeds`
2165        // table is fixed-schema — no identifier splicing), but blank
2166        // values are silent projection bugs: a blank id collides every
2167        // feed under "", a blank field never matches the payload array,
2168        // and an empty primary_key yields no item_id (every row dropped).
2169        // Reject them at the write boundary so `kanade job create` surfaces
2170        // the typo instead of producing an empty/garbled feed at run time.
2171        let mut seen_feed_ids: Vec<&str> = Vec::new();
2172        for spec in &self.feed {
2173            let id = spec.id.trim();
2174            if id.is_empty() {
2175                return Err("feed.id must not be empty".to_string());
2176            }
2177            if spec.field.trim().is_empty() {
2178                return Err(format!("feed '{id}' field must not be empty"));
2179            }
2180            if spec.primary_key.is_empty() {
2181                return Err(format!("feed '{id}' needs at least one primary_key field"));
2182            }
2183            if spec.primary_key.iter().any(|k| k.trim().is_empty()) {
2184                return Err(format!(
2185                    "feed '{id}' primary_key must not contain blank entries"
2186                ));
2187            }
2188            // Two specs sharing an id both target the same `feeds`
2189            // partition and would clobber each other on every run —
2190            // reject the ambiguity rather than let last-write-wins.
2191            if seen_feed_ids.contains(&id) {
2192                return Err(format!("feed id '{id}' is declared more than once"));
2193            }
2194            seen_feed_ids.push(id);
2195        }
2196        // A `feed:` job fetches external data and MUST run on the trusted
2197        // controller tier — the dispatch guard (`requires_controller`) treats
2198        // a non-empty `feed:` as implying `controller`. An explicit
2199        // `tier: endpoint` contradicts that intent; reject it rather than
2200        // silently overriding, so the operator can't believe a feed runs on
2201        // endpoints. Omitting `tier:` (the default) is fine — the implication
2202        // confines it; `tier: controller` is the redundant-but-explicit form.
2203        if !self.feed.is_empty() && matches!(self.tier, Some(Tier::Endpoint)) {
2204            return Err(
2205                "feed: requires the controller tier — remove `tier: endpoint` (a feed: job \
2206                 fetches external data and is confined to the controller_group)"
2207                    .to_string(),
2208            );
2209        }
2210        // A present-but-empty finalize script is an invisible no-op
2211        // (the hook would run an empty body); reject it at the write
2212        // boundary. Inline-only in P1, so `script` is the sole source.
2213        if let Some(finalize) = &self.finalize {
2214            if finalize.script.trim().is_empty() {
2215                return Err("finalize.script must not be empty".to_string());
2216            }
2217            // Reject an unparseable timeout at the write boundary so the
2218            // operator sees the error at `job create` rather than getting
2219            // a silent fire-time fallback (`FinalizeSpec::lower` floors to
2220            // 60s, which would otherwise mask a typo).
2221            if humantime::parse_duration(&finalize.timeout).is_err() {
2222                return Err(format!(
2223                    "finalize.timeout '{}' is not a valid duration",
2224                    finalize.timeout
2225                ));
2226            }
2227            // Disallow cmd for finalize: the agent injects the result JSON
2228            // into the hook's environment, and cmd.exe quoting doesn't
2229            // nest — JSON's `"` plus shell metacharacters in a collected
2230            // path/key could break out into command injection at the
2231            // agent's (often LocalSystem) privilege. PowerShell's
2232            // single-quote escaping is safe, and finalize hooks are
2233            // PowerShell by convention anyway.
2234            if finalize.shell == ExecuteShell::Cmd {
2235                return Err(
2236                    "finalize.shell: cmd is not supported for finalize hooks (shell-injection \
2237                     risk when the result JSON is injected into the environment); use powershell"
2238                        .to_string(),
2239                );
2240            }
2241        }
2242        // Stdout-format compatibility (#821). `inventory:` / `check:` /
2243        // `collect:` now COMPOSE: each reads its own `#KANADE-<KIND>-
2244        // BEGIN/END`-fenced JSON block from stdout, so a single job can
2245        // project inventory facts, drive a Health-tab check, AND collect
2246        // files in one run. (A single-hint job may still skip the fence;
2247        // a multi-hint job must fence each block.)
2248        //
2249        // `emit:` remains the exception — its stdout is line-delimited
2250        // NDJSON consumed whole and then omitted from the result — so it
2251        // can't share stdout with any fenced hint. `feed:` is another fenced
2252        // stdout consumer (`#KANADE-FEED`), so it belongs in this exclusion
2253        // too: with `emit:` present the projector never sees the feed's fence
2254        // (CodeRabbit).
2255        if self.emit.is_some()
2256            && (self.inventory.is_some()
2257                || self.check.is_some()
2258                || self.collect.is_some()
2259                || !self.feed.is_empty())
2260        {
2261            return Err(
2262                "`emit:` is incompatible with `inventory:` / `check:` / `collect:` / `feed:` — \
2263                 emit's stdout is NDJSON timeline events (consumed whole and omitted from the \
2264                 result), while the others read fenced JSON blocks from stdout"
2265                    .to_string(),
2266            );
2267        }
2268        // A check's `name` is the Health-tab row id (React key); the
2269        // field names tell the agent where to read status/detail.
2270        // An empty value is an invisible runtime bug, and the serde
2271        // defaults don't guard an operator who writes `status_field:
2272        // ""` explicitly — reject all three here.
2273        if let Some(check) = &self.check {
2274            for (label, value) in [
2275                ("check.name", &check.name),
2276                ("check.status_field", &check.status_field),
2277                ("check.detail_field", &check.detail_field),
2278            ] {
2279                if value.trim().is_empty() {
2280                    return Err(format!("{label} must not be empty"));
2281                }
2282            }
2283            // A present-but-blank `troubleshoot` is a broken
2284            // remediation job id (the "修復する" button would target
2285            // an empty manifest id) — reject it too.
2286            if let Some(troubleshoot) = &check.troubleshoot {
2287                if troubleshoot.trim().is_empty() {
2288                    return Err("check.troubleshoot must not be empty when set".to_string());
2289                }
2290            }
2291            // A present-but-blank `label` would render an empty row
2292            // title on the Health tab / Compliance page — reject it so
2293            // the slug fallback only ever kicks in when label is absent.
2294            if let Some(label) = &check.label {
2295                if label.trim().is_empty() {
2296                    return Err("check.label must not be empty when set".to_string());
2297                }
2298            }
2299            if let Some(alert) = &check.alert {
2300                // An alert that names no recipient is a silent no-op.
2301                if !alert.notify_user && alert.notify_groups.is_empty() {
2302                    return Err("check.alert must set notify_user and/or notify_groups".to_string());
2303                }
2304                if alert.title.trim().is_empty() {
2305                    return Err("check.alert.title must not be empty".to_string());
2306                }
2307                // `on: []` would never fire; an empty group name resolves to
2308                // a malformed `notifications.group.` subject.
2309                if alert.on.is_empty() {
2310                    return Err("check.alert.on must list at least one status".to_string());
2311                }
2312                if alert.notify_groups.iter().any(|g| g.trim().is_empty()) {
2313                    return Err("check.alert.notify_groups must not contain blanks".to_string());
2314                }
2315                // Email is addressed via group_contacts (group → email), so
2316                // there must be a group to map. notify_user has no email.
2317                if alert.email && alert.notify_groups.is_empty() {
2318                    return Err(
2319                        "check.alert.email requires notify_groups (email is addressed per group, not per user)"
2320                            .to_string(),
2321                    );
2322                }
2323                // The alert rides the `check_status` projection, which only
2324                // runs for `fleet: true`.
2325                if !check.fleet {
2326                    return Err(
2327                        "check.alert requires fleet: true (the alert rides the compliance projection)"
2328                            .to_string(),
2329                    );
2330                }
2331            }
2332        }
2333        // #291: a `client:` job is rendered in the Client App's
2334        // catalog (`jobs.list` → `jobs.execute`). serde already makes
2335        // `name` + `category` required at parse time; the only gap is
2336        // a present-but-blank `name`, which would render an empty row
2337        // title — reject it like the other display-id fields.
2338        if let Some(client) = &self.client {
2339            if client.name.trim().is_empty() {
2340                return Err("client.name must not be empty".to_string());
2341            }
2342            // #792: category is a free-form key now, so a blank one would
2343            // group the job under an empty tab — reject it like `name`.
2344            if client.category.trim().is_empty() {
2345                return Err("client.category must not be empty".to_string());
2346            }
2347            // Optional display fields, when present, must be
2348            // meaningful: a blank `description` renders an empty
2349            // subtitle and a blank `icon` is a dangling lucide name.
2350            // Same present-but-blank guard the `check:` block applies
2351            // to its optional `troubleshoot` id.
2352            for (label, value) in [
2353                ("client.description", &client.description),
2354                ("client.icon", &client.icon),
2355                ("client.category_label", &client.category_label),
2356                ("client.category_icon", &client.category_icon),
2357            ] {
2358                if let Some(v) = value {
2359                    if v.trim().is_empty() {
2360                        return Err(format!("{label} must not be empty when set"));
2361                    }
2362                }
2363            }
2364            // #816: a present-but-empty `visible_to` (no all/groups/pcs)
2365            // would hide the job from everyone in the Client App — almost
2366            // certainly a mistake. Require at least one selector; omit the
2367            // whole block to mean "visible to all".
2368            if let Some(t) = &client.visible_to {
2369                if !t.is_specified() {
2370                    return Err(
2371                        "client.visible_to must set at least one of all / groups / pcs (omit it for all PCs)"
2372                            .to_string(),
2373                    );
2374                }
2375            }
2376            // show_when: a dynamic display gate keyed on a check result. A
2377            // malformed check slug matches nothing and an empty status list
2378            // matches nothing — both would silently hide the job forever,
2379            // so reject them at create time rather than at a confused
2380            // "why isn't my job showing?" later. The slug must be a clean
2381            // resource id (same charset checks/jobs use): a typo with spaces
2382            // or punctuation can never match a real check name, so catch it
2383            // here instead of failing closed at runtime. (Whether the slug
2384            // names a check that actually EXISTS can't be checked here —
2385            // checks are keyed by name across manifests — so a valid-but-
2386            // unknown slug stays a runtime miss = hidden, the documented
2387            // fail-closed behavior.)
2388            if let Some(sw) = &client.show_when {
2389                if !is_valid_resource_id(sw.check.trim()) {
2390                    return Err(
2391                        "client.show_when.check must be a non-empty check slug ([A-Za-z0-9._-])"
2392                            .to_string(),
2393                    );
2394                }
2395                if sw.is.is_empty() {
2396                    return Err(
2397                        "client.show_when.is must list at least one check status".to_string()
2398                    );
2399                }
2400            }
2401        }
2402        // #219: a `collect:` job's `name` heads the bundle on the SPA
2403        // Collect page (and the Client App row when paired with
2404        // `client:`), `files_field` tells the agent where to read the
2405        // path list, and `max_size` must be a parseable size so a typo
2406        // is caught at create time rather than silently capping the
2407        // bundle at the default on the fire path.
2408        if let Some(collect) = &self.collect {
2409            if collect.name.trim().is_empty() {
2410                return Err("collect.name must not be empty".to_string());
2411            }
2412            if collect.files_field.trim().is_empty() {
2413                return Err("collect.files_field must not be empty".to_string());
2414            }
2415            if let Some(description) = &collect.description {
2416                if description.trim().is_empty() {
2417                    return Err("collect.description must not be empty when set".to_string());
2418                }
2419            }
2420            if let Some(max_size) = &collect.max_size {
2421                parse_size_bytes(max_size).map_err(|e| format!("collect.max_size: {e}"))?;
2422            }
2423        }
2424        // #720/#743: `aggregate:` is a pure read-spec (it never touches
2425        // stdout and is never sent to an agent), so it composes with every
2426        // other hint. The per-widget rules are shared with the standalone
2427        // `view` resource — see [`validate_aggregate_widgets`].
2428        if let Some(widgets) = &self.aggregate {
2429            validate_aggregate_widgets(widgets, "aggregate")?;
2430        }
2431        // A blank / whitespace-only tag is an invisible operator typo
2432        // that would render an empty filter chip on the Jobs page —
2433        // reject it like the other present-but-blank display fields.
2434        for tag in &self.tags {
2435            if tag.trim().is_empty() {
2436                return Err("tags must not contain empty entries".to_string());
2437            }
2438        }
2439        Ok(())
2440    }
2441}
2442
2443#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
2444#[serde(rename_all = "lowercase")]
2445pub enum ExecuteShell {
2446    Powershell,
2447    Cmd,
2448}
2449
2450impl From<ExecuteShell> for Shell {
2451    fn from(s: ExecuteShell) -> Self {
2452        match s {
2453            ExecuteShell::Powershell => Shell::Powershell,
2454            ExecuteShell::Cmd => Shell::Cmd,
2455        }
2456    }
2457}
2458
2459#[cfg(test)]
2460mod tests {
2461    use super::*;
2462
2463    #[test]
2464    fn inventory_payload_extracts_fenced_block() {
2465        // Readable message + fenced JSON → only the JSON, trimmed.
2466        let stdout = "Wi-Fi 設定を適用しました。\n\
2467            #KANADE-INVENTORY-BEGIN\n\
2468            {\"applied\": true}\n\
2469            #KANADE-INVENTORY-END\n";
2470        assert_eq!(inventory_payload(stdout), "{\"applied\": true}");
2471    }
2472
2473    #[test]
2474    fn inventory_payload_falls_back_to_whole_stdout() {
2475        // No fence (a plain inventory job) → whole stdout, trimmed.
2476        assert_eq!(
2477            inventory_payload("  {\"ram_gb\": 16}\n"),
2478            "{\"ram_gb\": 16}"
2479        );
2480    }
2481
2482    #[test]
2483    fn inventory_payload_handles_unterminated_fence() {
2484        // Closing marker missing (e.g. truncated) → everything after the
2485        // opener, trimmed.
2486        let stdout = "msg\n#KANADE-INVENTORY-BEGIN\n{\"a\": 1}";
2487        assert_eq!(inventory_payload(stdout), "{\"a\": 1}");
2488    }
2489
2490    #[test]
2491    fn inventory_payload_ignores_mid_line_sentinel() {
2492        // The marker echoed mid-line (not at a line start) must NOT be
2493        // treated as a fence — fall back to the whole stdout.
2494        let stdout = "see #KANADE-INVENTORY-BEGIN in the docs\nnot json";
2495        assert_eq!(inventory_payload(stdout), stdout.trim());
2496    }
2497
2498    #[test]
2499    fn fenced_payload_extracts_each_hint_block_independently() {
2500        // #821: one stdout carrying a user message + all three fenced
2501        // blocks — every consumer pulls only its own.
2502        let stdout = "\
2503done!
2504#KANADE-INVENTORY-BEGIN
2505{\"os\":\"win\"}
2506#KANADE-INVENTORY-END
2507#KANADE-CHECK-BEGIN
2508{\"status\":\"ok\"}
2509#KANADE-CHECK-END
2510#KANADE-COLLECT-BEGIN
2511{\"files\":[\"a\"]}
2512#KANADE-COLLECT-END
2513";
2514        assert_eq!(
2515            fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
2516            "{\"os\":\"win\"}"
2517        );
2518        assert_eq!(
2519            fenced_payload(stdout, CHECK_BLOCK_BEGIN, CHECK_BLOCK_END),
2520            "{\"status\":\"ok\"}"
2521        );
2522        assert_eq!(
2523            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2524            "{\"files\":[\"a\"]}"
2525        );
2526    }
2527
2528    #[test]
2529    fn fenced_payload_falls_back_to_whole_stdout_without_fence() {
2530        // A single-hint job needs no fence — the whole (trimmed) stdout is
2531        // the payload.
2532        let stdout = "  {\"files\":[\"a\"]}  ";
2533        assert_eq!(
2534            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2535            "{\"files\":[\"a\"]}"
2536        );
2537    }
2538
2539    #[test]
2540    fn fenced_payload_returns_empty_when_other_fences_present_but_mine_missing() {
2541        // Multi-hint output (inventory + check fenced) but the COLLECT
2542        // fence is missing — collect must NOT fall back to the whole
2543        // stdout (which holds the inventory/check blocks) and cross-parse
2544        // a sibling block; it gets "" → its JSON parse fails → no data.
2545        let stdout = "\
2546#KANADE-INVENTORY-BEGIN
2547{\"os\":\"win\"}
2548#KANADE-INVENTORY-END
2549#KANADE-CHECK-BEGIN
2550{\"status\":\"ok\"}
2551#KANADE-CHECK-END
2552";
2553        assert_eq!(
2554            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
2555            ""
2556        );
2557        // ...while the hints that DID fence still extract correctly.
2558        assert_eq!(
2559            fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
2560            "{\"os\":\"win\"}"
2561        );
2562    }
2563
2564    /// The example check-job + schedule YAMLs shipped under `configs/`
2565    /// must stay valid as the schema evolves (#290 PR-C). `include_str!`
2566    /// pins them at compile time so a breaking edit fails `cargo test`
2567    /// rather than only `kanade job create` at deploy time.
2568    #[test]
2569    fn example_check_job_yamls_parse_and_validate() {
2570        let jobs = [
2571            (
2572                "check-bitlocker",
2573                include_str!("../../../configs/jobs/check-bitlocker.yaml"),
2574            ),
2575            (
2576                "check-av-signature",
2577                include_str!("../../../configs/jobs/check-av-signature.yaml"),
2578            ),
2579            (
2580                "check-cert-expiry",
2581                include_str!("../../../configs/jobs/check-cert-expiry.yaml"),
2582            ),
2583            (
2584                "check-disk-space",
2585                include_str!("../../../configs/jobs/check-disk-space.yaml"),
2586            ),
2587            (
2588                "check-pending-reboot",
2589                include_str!("../../../configs/jobs/check-pending-reboot.yaml"),
2590            ),
2591            (
2592                "check-defender-rtp",
2593                include_str!("../../../configs/jobs/check-defender-rtp.yaml"),
2594            ),
2595            (
2596                "check-firewall",
2597                include_str!("../../../configs/jobs/check-firewall.yaml"),
2598            ),
2599        ];
2600        for (name, yaml) in jobs {
2601            let m: Manifest =
2602                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} parse: {e}"));
2603            m.validate()
2604                .unwrap_or_else(|e| panic!("{name} validate: {e}"));
2605            let check = m
2606                .check
2607                .as_ref()
2608                .unwrap_or_else(|| panic!("{name} must carry a check: hint"));
2609            assert!(!check.name.trim().is_empty(), "{name} check.name empty");
2610            // These examples all read admin-only WMI / registry / netsh
2611            // state, so they run_as system. NOTE: that's a property of
2612            // these particular checks, NOT of the `check:` contract — a
2613            // check probing user-session state could run_as user.
2614            assert_eq!(
2615                m.execute.run_as,
2616                RunAs::System,
2617                "{name} should run_as system"
2618            );
2619        }
2620    }
2621
2622    /// The example user-invokable job YAMLs (#291) shipped under
2623    /// `configs/jobs/` must stay valid as the `client:` schema
2624    /// evolves. `include_str!` pins them at compile time so a breaking
2625    /// edit fails `cargo test`, not `kanade job create` at deploy.
2626    #[test]
2627    fn example_client_job_yamls_parse_and_validate() {
2628        let jobs = [
2629            (
2630                "fix-teams-cache",
2631                "troubleshoot",
2632                include_str!("../../../configs/jobs/fix-teams-cache.yaml"),
2633            ),
2634            (
2635                "chrome-update",
2636                "software_update",
2637                include_str!("../../../configs/jobs/chrome-update.yaml"),
2638            ),
2639            (
2640                "install-slack",
2641                "catalog",
2642                include_str!("../../../configs/jobs/install-slack.yaml"),
2643            ),
2644            (
2645                "fix-defender-rtp",
2646                "troubleshoot",
2647                include_str!("../../../configs/jobs/fix-defender-rtp.yaml"),
2648            ),
2649            // #792 custom category ("settings") + #809 message/inventory.
2650            (
2651                "example-power-plan",
2652                "settings",
2653                include_str!("../../../configs/jobs/example-power-plan.yaml"),
2654            ),
2655            // #792: diagnostics moved to its own "support" tab.
2656            (
2657                "collect-diagnostics",
2658                "support",
2659                include_str!("../../../configs/jobs/collect-diagnostics.yaml"),
2660            ),
2661        ];
2662        for (id, category, yaml) in jobs {
2663            let m: Manifest =
2664                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
2665            m.validate()
2666                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
2667            assert_eq!(m.id, id, "{id} id mismatch");
2668            let client = m
2669                .client
2670                .as_ref()
2671                .unwrap_or_else(|| panic!("{id} must carry a client: block"));
2672            assert!(!client.name.trim().is_empty(), "{id} client.name empty");
2673            assert_eq!(client.category, category, "{id} category");
2674        }
2675    }
2676
2677    /// #219: the shipped `collect:` example must stay valid as the
2678    /// schema evolves. `include_str!` pins it at compile time so a
2679    /// breaking edit (or a YAML typo in the PowerShell block) fails
2680    /// `cargo test` rather than `kanade job create` at deploy. It carries
2681    /// both `collect:` and `client:` (end-user-triggerable), which must
2682    /// compose.
2683    #[test]
2684    fn example_collect_job_yaml_parses_and_validates() {
2685        let yaml = include_str!("../../../configs/jobs/collect-diagnostics.yaml");
2686        let m: Manifest = serde_yaml::from_str(yaml).expect("collect-diagnostics parse");
2687        m.validate().expect("collect-diagnostics validate");
2688        assert_eq!(m.id, "collect-diagnostics");
2689        let collect = m.collect.as_ref().expect("collect: block present");
2690        assert!(!collect.name.trim().is_empty());
2691        assert_eq!(collect.files_field, "files");
2692        assert_eq!(collect.max_size_bytes(), 50_000_000);
2693        // collect + client compose — the Client App can trigger it.
2694        assert!(
2695            m.client.is_some(),
2696            "collect-diagnostics also carries client:"
2697        );
2698    }
2699
2700    /// The `emit: { type: events }` collector jobs under
2701    /// `configs/jobs/` feed the obs_events timeline. `include_str!`
2702    /// pins them at compile time so a breaking edit (e.g. an `emit:`
2703    /// paired with `check:`/`inventory:`, a bad watermark field, or a
2704    /// YAML typo in the PowerShell block) fails `cargo test` rather
2705    /// than `kanade job create` at deploy. Every one must carry an
2706    /// `emit.type=events` block and NO check/inventory (validate()
2707    /// rejects the pairing).
2708    #[test]
2709    fn example_event_collector_job_yamls_parse_and_validate() {
2710        let jobs = [
2711            // collect-winlog-events was retired in #841 PR2 — the scheduled
2712            // human-session / power timeline is now read natively by the
2713            // agent (kanade-agent `winlog` module via EvtQuery), no
2714            // PowerShell job. collect-winlog-logons-all stays as the
2715            // on-demand forensic all-token-logons companion.
2716            (
2717                "collect-winlog-logons-all",
2718                include_str!("../../../configs/jobs/collect-winlog-logons-all.yaml"),
2719            ),
2720            (
2721                "collect-wlan-events",
2722                include_str!("../../../configs/jobs/collect-wlan-events.yaml"),
2723            ),
2724        ];
2725        for (id, yaml) in jobs {
2726            // Strict parse so an unknown-key typo in these fixtures fails
2727            // here (not silently at deploy) — the runtime Manifest is
2728            // unknown-key-tolerant, so the lenient serde_yaml::from_str
2729            // wouldn't catch fixture drift (CodeRabbit #689).
2730            let m: Manifest =
2731                crate::strict::from_yaml_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
2732            m.validate()
2733                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
2734            assert_eq!(m.id, id, "{id} id mismatch");
2735            let emit = m
2736                .emit
2737                .as_ref()
2738                .unwrap_or_else(|| panic!("{id} must carry an emit: block"));
2739            assert_eq!(emit.kind, EmitKind::Events, "{id} emit.type");
2740            assert!(
2741                m.check.is_none() && m.inventory.is_none(),
2742                "{id}: emit jobs must not pair with check/inventory"
2743            );
2744        }
2745    }
2746
2747    /// The `inventory:` snapshot jobs under `configs/jobs/` project
2748    /// facts into `inventory_facts` + exploded tables. `include_str!`
2749    /// pins them at compile time so a breaking edit (bad explode
2750    /// schema, a YAML typo in the PowerShell block, an `inventory:`
2751    /// accidentally paired with `emit:`) fails `cargo test` rather
2752    /// than the projector at deploy. Each must carry an `inventory:`
2753    /// block and NO emit (validate() rejects the pairing).
2754    #[test]
2755    fn example_inventory_job_yamls_parse_and_validate() {
2756        let jobs = [
2757            (
2758                "inventory-hw",
2759                include_str!("../../../configs/jobs/inventory-hw.yaml"),
2760            ),
2761            (
2762                "inventory-sw",
2763                include_str!("../../../configs/jobs/inventory-sw.yaml"),
2764            ),
2765            (
2766                "inventory-driver",
2767                include_str!("../../../configs/jobs/inventory-driver.yaml"),
2768            ),
2769        ];
2770        for (id, yaml) in jobs {
2771            let m: Manifest =
2772                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
2773            m.validate()
2774                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
2775            assert_eq!(m.id, id, "{id} id mismatch");
2776            assert!(m.inventory.is_some(), "{id} must carry an inventory: block");
2777            assert!(m.emit.is_none(), "{id}: inventory jobs must not set emit:");
2778        }
2779    }
2780
2781    #[test]
2782    fn example_check_schedule_yamls_parse_and_validate() {
2783        let schedules = [
2784            (
2785                "check-bitlocker",
2786                include_str!("../../../configs/schedules/check-bitlocker.yaml"),
2787            ),
2788            (
2789                "check-av-signature",
2790                include_str!("../../../configs/schedules/check-av-signature.yaml"),
2791            ),
2792            (
2793                "check-cert-expiry",
2794                include_str!("../../../configs/schedules/check-cert-expiry.yaml"),
2795            ),
2796            (
2797                "check-disk-space",
2798                include_str!("../../../configs/schedules/check-disk-space.yaml"),
2799            ),
2800            (
2801                "check-pending-reboot",
2802                include_str!("../../../configs/schedules/check-pending-reboot.yaml"),
2803            ),
2804            (
2805                "check-defender-rtp",
2806                include_str!("../../../configs/schedules/check-defender-rtp.yaml"),
2807            ),
2808            (
2809                "check-firewall",
2810                include_str!("../../../configs/schedules/check-firewall.yaml"),
2811            ),
2812        ];
2813        for (name, yaml) in schedules {
2814            let s: Schedule =
2815                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
2816            s.validate()
2817                .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
2818            assert_eq!(s.job_id, name, "{name} schedule must reference its job");
2819        }
2820    }
2821
2822    /// Inventory schedule wrappers (`per_pc` cadence) must stay valid
2823    /// alongside the schedule schema. `include_str!` pins them so a
2824    /// breaking edit fails `cargo test`, not `kanade schedule create`.
2825    #[test]
2826    fn example_inventory_schedule_yamls_parse_and_validate() {
2827        let schedules = [
2828            (
2829                "inventory-hw",
2830                include_str!("../../../configs/schedules/inventory-hw.yaml"),
2831            ),
2832            (
2833                "inventory-sw",
2834                include_str!("../../../configs/schedules/inventory-sw.yaml"),
2835            ),
2836            (
2837                "inventory-driver",
2838                include_str!("../../../configs/schedules/inventory-driver.yaml"),
2839            ),
2840        ];
2841        for (name, yaml) in schedules {
2842            let s: Schedule =
2843                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
2844            s.validate()
2845                .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
2846            assert_eq!(s.job_id, name, "{name} schedule must reference its job");
2847        }
2848    }
2849
2850    #[test]
2851    fn target_is_specified_requires_at_least_one_field() {
2852        let empty = Target::default();
2853        assert!(!empty.is_specified());
2854
2855        let with_all = Target {
2856            all: true,
2857            ..Target::default()
2858        };
2859        assert!(with_all.is_specified());
2860
2861        let with_groups = Target {
2862            groups: vec!["canary".into()],
2863            ..Target::default()
2864        };
2865        assert!(with_groups.is_specified());
2866
2867        let with_pcs = Target {
2868            pcs: vec!["pc-01".into()],
2869            ..Target::default()
2870        };
2871        assert!(with_pcs.is_specified());
2872    }
2873
2874    #[test]
2875    fn manifest_deserialises_minimal_yaml() {
2876        // Matches jobs/echo-test.yaml. v0.18: no target/rollout/jitter
2877        // — those live on the schedule / exec request now.
2878        let yaml = r#"
2879id: echo-test
2880version: 0.0.1
2881execute:
2882  shell: powershell
2883  script: "echo 'kanade'"
2884  timeout: 30s
2885"#;
2886        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2887        assert_eq!(m.id, "echo-test");
2888        assert_eq!(m.version, "0.0.1");
2889        assert!(matches!(m.execute.shell, ExecuteShell::Powershell));
2890        assert_eq!(
2891            m.execute.script.as_deref().map(str::trim),
2892            Some("echo 'kanade'")
2893        );
2894        assert!(m.execute.script_file.is_none());
2895        assert!(m.execute.script_object.is_none());
2896        assert_eq!(m.execute.timeout, "30s");
2897        assert!(!m.require_approval);
2898        m.validate()
2899            .expect("inline-script manifest passes validation");
2900    }
2901
2902    #[test]
2903    fn manifest_parses_check_job_and_validates() {
2904        // An operator-defined health check (#290): a `check:` hint +
2905        // a PowerShell script that prints {status, detail}.
2906        let yaml = r#"
2907id: check-bitlocker
2908version: 0.1.0
2909execute:
2910  shell: powershell
2911  run_as: system
2912  timeout: 15s
2913  script: |
2914    [pscustomobject]@{ status = 'ok'; detail = 'all volumes protected' } | ConvertTo-Json -Compress
2915check:
2916  name: bitlocker
2917  troubleshoot: fix-bitlocker
2918"#;
2919        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2920        let check = m.check.as_ref().expect("check hint present");
2921        assert_eq!(check.name, "bitlocker");
2922        assert_eq!(check.troubleshoot.as_deref(), Some("fix-bitlocker"));
2923        // Field names default to the conventional "status" / "detail".
2924        assert_eq!(check.status_field, "status");
2925        assert_eq!(check.detail_field, "detail");
2926        assert!(m.inventory.is_none() && m.emit.is_none());
2927        m.validate().expect("check-only manifest passes validation");
2928    }
2929
2930    #[test]
2931    fn manifest_check_defaults_and_custom_fields() {
2932        // Minimal: only `name`; status/detail fields default.
2933        let m: Manifest = serde_yaml::from_str(
2934            r#"
2935id: check-disk
2936version: 0.1.0
2937execute:
2938  shell: powershell
2939  script: "[pscustomobject]@{ status = 'ok' } | ConvertTo-Json -Compress"
2940  timeout: 10s
2941check:
2942  name: disk_free
2943"#,
2944        )
2945        .expect("parse");
2946        let c = m.check.as_ref().unwrap();
2947        assert_eq!(c.name, "disk_free");
2948        assert_eq!(c.status_field, "status");
2949        assert_eq!(c.detail_field, "detail");
2950        assert!(c.troubleshoot.is_none());
2951        m.validate().expect("validates");
2952
2953        // The operator can point status/detail at any field of their
2954        // free-form inventory object.
2955        let m2: Manifest = serde_yaml::from_str(
2956            r#"
2957id: check-custom
2958version: 0.1.0
2959execute:
2960  shell: powershell
2961  script: "echo x"
2962  timeout: 10s
2963check:
2964  name: patch_level
2965  status_field: compliance
2966  detail_field: summary
2967"#,
2968        )
2969        .expect("parse");
2970        let c2 = m2.check.as_ref().unwrap();
2971        assert_eq!(c2.status_field, "compliance");
2972        assert_eq!(c2.detail_field, "summary");
2973    }
2974
2975    #[test]
2976    fn manifest_allows_check_composed_with_inventory() {
2977        // `check:` + `inventory:` COMPOSE on the same stdout object:
2978        // status/detail → Health tab, the rest → SPA projection +
2979        // explode sub-tables. Must pass validation.
2980        let yaml = r#"
2981id: check-bitlocker-detailed
2982version: 0.1.0
2983execute:
2984  shell: powershell
2985  script: "echo x"
2986  timeout: 10s
2987check:
2988  name: bitlocker
2989inventory:
2990  display:
2991    - { field: status, label: Status }
2992"#;
2993        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
2994        assert!(m.check.is_some() && m.inventory.is_some());
2995        m.validate().expect("check + inventory compose");
2996    }
2997
2998    #[test]
2999    fn manifest_parses_collect_job_and_validates() {
3000        // #219: a `collect:` hint + a script that lists files on stdout.
3001        let yaml = r#"
3002id: collect-diagnostics
3003version: 0.1.0
3004execute:
3005  shell: powershell
3006  run_as: system
3007  timeout: 120s
3008  script: |
3009    @{ files = @("$env:KANADE_COLLECT_DIR/system.csv") } | ConvertTo-Json
3010collect:
3011  name: "Full diagnostics"
3012  description: "Event logs + process"
3013  max_size: 50MB
3014"#;
3015        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3016        let c = m.collect.as_ref().expect("collect hint present");
3017        assert_eq!(c.name, "Full diagnostics");
3018        assert_eq!(c.files_field, "files"); // default
3019        assert_eq!(c.max_size_bytes(), 50_000_000);
3020        m.validate().expect("collect-only manifest validates");
3021    }
3022
3023    #[test]
3024    fn manifest_finalize_powershell_validates_and_lowers() {
3025        let yaml = r#"
3026id: collect-fin
3027version: 0.1.0
3028execute:
3029  shell: powershell
3030  timeout: 120s
3031  script: |
3032    @{ files = @() } | ConvertTo-Json
3033collect:
3034  name: "diag"
3035  max_size: 50MB
3036finalize:
3037  shell: powershell
3038  timeout: 30s
3039  run_as: system
3040  script: |
3041    Write-Output "cleanup"
3042"#;
3043        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3044        m.validate().expect("powershell finalize validates");
3045        let lowered = m.finalize.as_ref().expect("finalize present").lower();
3046        assert_eq!(lowered.timeout_secs, 30);
3047        assert!(matches!(lowered.shell, Shell::Powershell));
3048    }
3049
3050    #[test]
3051    fn manifest_finalize_rejects_cmd_shell() {
3052        // cmd finalize is an injection risk (the agent injects JSON into
3053        // the hook's env; cmd.exe quoting doesn't nest) — validate must
3054        // reject it.
3055        let yaml = r#"
3056id: collect-fin-cmd
3057version: 0.1.0
3058execute:
3059  shell: powershell
3060  timeout: 120s
3061  script: |
3062    @{ files = @() } | ConvertTo-Json
3063finalize:
3064  shell: cmd
3065  script: |
3066    echo hi
3067"#;
3068        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3069        let err = m.validate().expect_err("cmd finalize rejected");
3070        assert!(err.contains("finalize.shell"), "got: {err}");
3071    }
3072
3073    #[test]
3074    fn manifest_finalize_rejects_empty_script() {
3075        let yaml = r#"
3076id: collect-fin-empty
3077version: 0.1.0
3078execute:
3079  shell: powershell
3080  timeout: 120s
3081  script: |
3082    @{ files = @() } | ConvertTo-Json
3083finalize:
3084  shell: powershell
3085  script: "   "
3086"#;
3087        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3088        let err = m.validate().expect_err("empty finalize script rejected");
3089        assert!(err.contains("finalize.script"), "got: {err}");
3090    }
3091
3092    #[test]
3093    fn manifest_collect_max_size_defaults_when_unset() {
3094        let m: Manifest = serde_yaml::from_str(
3095            r#"
3096id: collect-min
3097version: 0.1.0
3098execute:
3099  shell: powershell
3100  script: "echo x"
3101  timeout: 10s
3102collect:
3103  name: minimal
3104"#,
3105        )
3106        .expect("parse");
3107        let c = m.collect.as_ref().unwrap();
3108        assert!(c.max_size.is_none());
3109        assert_eq!(c.max_size_bytes(), DEFAULT_COLLECT_MAX_SIZE);
3110        m.validate().expect("validates");
3111    }
3112
3113    #[test]
3114    fn manifest_allows_collect_with_client() {
3115        // collect composes with client (client doesn't touch stdout):
3116        // an end user can trigger a collection from the Client App.
3117        let yaml = r#"
3118id: collect-diag-client
3119version: 0.1.0
3120execute:
3121  shell: powershell
3122  script: "echo x"
3123  timeout: 10s
3124collect:
3125  name: diagnostics
3126client:
3127  name: "Send diagnostics"
3128  category: troubleshoot
3129"#;
3130        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3131        assert!(m.collect.is_some() && m.client.is_some());
3132        m.validate().expect("collect + client compose");
3133    }
3134
3135    #[test]
3136    fn manifest_allows_inventory_check_collect_coexistence() {
3137        // #821: the three fenced hints now COMPOSE — each reads its own
3138        // `#KANADE-<KIND>` stdout block, so one job can do all three.
3139        let yaml = r#"
3140id: multi-hint
3141version: 0.1.0
3142execute:
3143  shell: powershell
3144  script: "echo x"
3145  timeout: 10s
3146inventory:
3147  display:
3148    - { field: status, label: Status }
3149check:
3150  name: health
3151collect:
3152  name: diag
3153"#;
3154        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3155        m.validate()
3156            .expect("inventory + check + collect coexist after #821");
3157    }
3158
3159    #[test]
3160    fn manifest_rejects_emit_combined_with_fenced_hints() {
3161        // `emit:` consumes stdout as NDJSON (and blanks it), so it still
3162        // can't share with any fenced hint — inventory, check, OR collect.
3163        for extra in [
3164            "inventory:\n  display:\n    - { field: s, label: S }\n",
3165            "check:\n  name: health\n",
3166            "collect:\n  name: diag\n",
3167        ] {
3168            let yaml = format!(
3169                "id: bad-emit-mix\nversion: 0.1.0\nexecute:\n  shell: powershell\n  \
3170                 script: \"echo x\"\n  timeout: 10s\nemit:\n  type: events\n{extra}"
3171            );
3172            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
3173            let err = m
3174                .validate()
3175                .expect_err("emit + fenced hint must be rejected");
3176            assert!(err.contains("emit"), "error mentions emit: {err}");
3177        }
3178    }
3179
3180    #[test]
3181    fn manifest_rejects_collect_empty_name_and_bad_size() {
3182        let empty_name: Manifest = serde_yaml::from_str(
3183            r#"
3184id: c
3185version: 0.1.0
3186execute: { shell: powershell, script: "echo x", timeout: 10s }
3187collect: { name: "  " }
3188"#,
3189        )
3190        .expect("parse");
3191        assert!(
3192            empty_name.validate().is_err(),
3193            "blank collect.name rejected"
3194        );
3195
3196        let bad_size: Manifest = serde_yaml::from_str(
3197            r#"
3198id: c
3199version: 0.1.0
3200execute: { shell: powershell, script: "echo x", timeout: 10s }
3201collect: { name: diag, max_size: "50 quux" }
3202"#,
3203        )
3204        .expect("parse");
3205        let err = bad_size.validate().expect_err("bad max_size rejected");
3206        assert!(err.contains("max_size"), "error mentions max_size: {err}");
3207    }
3208
3209    #[test]
3210    fn parse_size_bytes_units() {
3211        assert_eq!(parse_size_bytes("1024").unwrap(), 1024);
3212        assert_eq!(parse_size_bytes("1B").unwrap(), 1);
3213        assert_eq!(parse_size_bytes("50MB").unwrap(), 50_000_000);
3214        assert_eq!(parse_size_bytes("500 KB").unwrap(), 500_000);
3215        assert_eq!(parse_size_bytes("1GiB").unwrap(), 1024 * 1024 * 1024);
3216        assert_eq!(parse_size_bytes("2mib").unwrap(), 2 * 1024 * 1024);
3217        assert!(parse_size_bytes("").is_err());
3218        assert!(parse_size_bytes("MB").is_err());
3219        assert!(parse_size_bytes("12 zonks").is_err());
3220    }
3221
3222    #[test]
3223    fn manifest_rejects_check_combined_with_emit() {
3224        // `emit:` stdout is NDJSON (and omitted from the result), so
3225        // it can't pair with `check:` (which needs a single JSON
3226        // object on stdout).
3227        let yaml = r#"
3228id: bad-mix
3229version: 0.1.0
3230execute:
3231  shell: powershell
3232  script: "echo x"
3233  timeout: 10s
3234check:
3235  name: bitlocker
3236emit:
3237  type: events
3238"#;
3239        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3240        let err = m.validate().expect_err("emit + check must fail");
3241        assert!(err.contains("incompatible"), "err: {err}");
3242    }
3243
3244    #[test]
3245    fn manifest_rejects_emit_combined_with_inventory() {
3246        // The other half of the emit-incompatibility condition.
3247        let yaml = r#"
3248id: bad-mix-2
3249version: 0.1.0
3250execute:
3251  shell: powershell
3252  script: "echo x"
3253  timeout: 10s
3254emit:
3255  type: events
3256inventory:
3257  display:
3258    - { field: status, label: Status }
3259"#;
3260        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3261        let err = m.validate().expect_err("emit + inventory must fail");
3262        assert!(err.contains("incompatible"), "err: {err}");
3263    }
3264
3265    #[test]
3266    fn manifest_rejects_empty_check_field_names() {
3267        // Empty name / status_field / detail_field are invisible
3268        // runtime bugs (empty React key, agent reads the wrong field)
3269        // — reject them even though serde supplies non-empty defaults.
3270        let base = |inner: &str| {
3271            format!(
3272                "id: c\nversion: 0.1.0\nexecute:\n  shell: powershell\n  script: \"echo x\"\n  timeout: 10s\ncheck:\n{inner}"
3273            )
3274        };
3275        for inner in [
3276            "  name: \"\"\n",
3277            "  name: ok\n  status_field: \"\"\n",
3278            "  name: ok\n  detail_field: \"   \"\n",
3279            // present-but-blank troubleshoot → broken remediation id.
3280            "  name: ok\n  troubleshoot: \"  \"\n",
3281        ] {
3282            let m: Manifest = serde_yaml::from_str(&base(inner)).expect("parse");
3283            let err = m.validate().expect_err("empty field must fail");
3284            assert!(err.contains("must not be empty"), "err: {err}");
3285        }
3286    }
3287
3288    #[test]
3289    fn check_alert_decodes_with_defaults_and_validates() {
3290        let yaml = r#"
3291id: c
3292version: 0.1.0
3293execute:
3294  shell: powershell
3295  script: "echo x"
3296  timeout: 10s
3297check:
3298  name: bitlocker
3299  alert:
3300    notify_user: true
3301    title: "BitLocker 未準拠"
3302"#;
3303        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3304        m.validate().expect("valid alert");
3305        let alert = m.check.unwrap().alert.unwrap();
3306        // Defaults: on = [fail], priority = warn, body = None.
3307        assert_eq!(alert.on, vec![CheckAlertStatus::Fail]);
3308        assert_eq!(
3309            alert.priority,
3310            crate::ipc::notifications::NotificationPriority::Warn
3311        );
3312        assert!(alert.body.is_none());
3313        assert!(alert.notify_user);
3314    }
3315
3316    #[test]
3317    fn check_alert_validation_rejects_bad_configs() {
3318        let base = |alert: &str| {
3319            format!(
3320                "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}"
3321            )
3322        };
3323        let cases = [
3324            // No recipient.
3325            ("    title: t\n", "notify_user and/or notify_groups"),
3326            // Empty title.
3327            (
3328                "    notify_user: true\n    title: \"  \"\n",
3329                "title must not be empty",
3330            ),
3331            // Empty `on`.
3332            (
3333                "    notify_user: true\n    title: t\n    on: []\n",
3334                "on must list at least one status",
3335            ),
3336            // Blank group name.
3337            (
3338                "    notify_groups: [\"  \"]\n    title: t\n",
3339                "notify_groups must not contain blanks",
3340            ),
3341            // alert requires fleet: true.
3342            (
3343                "    notify_user: true\n    title: t\n  fleet: false\n",
3344                "requires fleet: true",
3345            ),
3346            // email opt-in without a group to address.
3347            (
3348                "    notify_user: true\n    email: true\n    title: t\n",
3349                "email requires notify_groups",
3350            ),
3351        ];
3352        for (alert, want) in cases {
3353            let m: Manifest = serde_yaml::from_str(&base(alert)).expect("parse");
3354            let err = m.validate().expect_err("bad alert must fail");
3355            assert!(err.contains(want), "for {alert:?}: got {err}");
3356        }
3357    }
3358
3359    #[test]
3360    fn manifest_client_absent_by_default() {
3361        // A plain operator job (the overwhelming majority) carries no
3362        // `client:` block, so it never surfaces in the end-user
3363        // catalog.
3364        let yaml = r#"
3365id: echo-test
3366version: 0.0.1
3367execute:
3368  shell: powershell
3369  script: "echo 'kanade'"
3370  timeout: 30s
3371"#;
3372        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3373        assert!(m.client.is_none());
3374        m.validate().expect("operator-only job validates");
3375    }
3376
3377    #[test]
3378    fn manifest_client_parses_and_validates() {
3379        // The Client App "困ったとき" remediation job shape: a
3380        // user-invokable troubleshoot job with the end-user fields the
3381        // KLP `jobs.list` wire needs, grouped under `client:`.
3382        let yaml = r#"
3383id: fix-teams-cache
3384version: 1.0.0
3385execute:
3386  shell: powershell
3387  script: "echo clearing"
3388  timeout: 60s
3389client:
3390  name: "Teams のキャッシュをクリア"
3391  description: "Teams が重いときに試してください"
3392  category: troubleshoot
3393  icon: brush-cleaning
3394"#;
3395        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3396        let c = m.client.as_ref().expect("client block present");
3397        assert_eq!(c.name, "Teams のキャッシュをクリア");
3398        assert_eq!(
3399            c.description.as_deref(),
3400            Some("Teams が重いときに試してください")
3401        );
3402        assert_eq!(c.category, "troubleshoot");
3403        assert_eq!(c.icon.as_deref(), Some("brush-cleaning"));
3404        m.validate().expect("user-invokable job validates");
3405    }
3406
3407    #[test]
3408    fn manifest_client_minimal_only_name_and_category() {
3409        // description + icon are optional; name + category are the
3410        // serde-required minimum.
3411        let yaml = r#"
3412id: install-slack
3413version: 1.0.0
3414execute:
3415  shell: powershell
3416  script: "echo install"
3417  timeout: 600s
3418client:
3419  name: Slack
3420  category: catalog
3421"#;
3422        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3423        let c = m.client.as_ref().expect("client present");
3424        assert_eq!(c.category, "catalog");
3425        assert!(c.description.is_none() && c.icon.is_none());
3426        m.validate().expect("minimal client validates");
3427    }
3428
3429    #[test]
3430    fn manifest_client_rejects_blank_name() {
3431        // serde guarantees `name`/`category` are present; the one gap
3432        // is a present-but-blank name → empty catalog row title.
3433        let yaml = r#"
3434id: j
3435version: 1.0.0
3436execute:
3437  shell: powershell
3438  script: "echo x"
3439  timeout: 30s
3440client:
3441  name: "   "
3442  category: catalog
3443"#;
3444        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3445        let err = m.validate().expect_err("blank name must fail");
3446        assert!(err.contains("client.name"), "err: {err}");
3447    }
3448
3449    #[test]
3450    fn manifest_client_rejects_blank_optional_fields() {
3451        // description / icon are optional, but a present-but-blank
3452        // value is a bug (empty subtitle / dangling icon name) — reject
3453        // it, mirroring the check: block's troubleshoot guard.
3454        for (field, line) in [
3455            ("client.description", "  description: \"  \"\n"),
3456            ("client.icon", "  icon: \"\"\n"),
3457            // #792: the new category tab-metadata fields get the same
3458            // present-but-blank guard.
3459            ("client.category_label", "  category_label: \"  \"\n"),
3460            ("client.category_icon", "  category_icon: \"\"\n"),
3461        ] {
3462            let yaml = format!(
3463                "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}"
3464            );
3465            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
3466            let err = m.validate().expect_err("blank optional field must fail");
3467            assert!(err.contains(field), "expected {field} in err: {err}");
3468        }
3469    }
3470
3471    #[test]
3472    fn manifest_client_rejects_blank_category() {
3473        // #792: category is a free-form key now; serde keeps it required,
3474        // but a present-but-blank value would group the job under an empty
3475        // tab — validate() must reject it.
3476        let yaml = r#"
3477id: j
3478version: 1.0.0
3479execute:
3480  shell: powershell
3481  script: "echo x"
3482  timeout: 30s
3483client:
3484  name: "A job"
3485  category: "   "
3486"#;
3487        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3488        let err = m.validate().expect_err("blank category must fail");
3489        assert!(err.contains("client.category"), "err: {err}");
3490    }
3491
3492    #[test]
3493    fn target_matches_pc_group_and_all() {
3494        // #816: pc match, group match, all, and the no-match case.
3495        let by_pc = Target {
3496            pcs: vec!["PC1".into()],
3497            ..Default::default()
3498        };
3499        assert!(by_pc.matches("PC1", &[]));
3500        assert!(!by_pc.matches("PC2", &["g1".into()]));
3501
3502        let by_group = Target {
3503            groups: vec!["g1".into()],
3504            ..Default::default()
3505        };
3506        assert!(by_group.matches("PC2", &["g1".into()]));
3507        assert!(!by_group.matches("PC2", &["g2".into()]));
3508
3509        let all = Target {
3510            all: true,
3511            ..Default::default()
3512        };
3513        assert!(all.matches("anyPC", &[]));
3514    }
3515
3516    #[test]
3517    fn manifest_client_rejects_empty_visible_to() {
3518        // #816: a present-but-empty visible_to (no all/groups/pcs) would
3519        // hide the job from everyone — validate() must reject it.
3520        let yaml = r#"
3521id: j
3522version: 1.0.0
3523execute:
3524  shell: powershell
3525  script: "echo x"
3526  timeout: 30s
3527client:
3528  name: "A job"
3529  category: troubleshoot
3530  visible_to: {}
3531"#;
3532        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3533        let err = m.validate().expect_err("empty visible_to must fail");
3534        assert!(err.contains("client.visible_to"), "err: {err}");
3535    }
3536
3537    #[test]
3538    fn manifest_client_accepts_visible_to_groups() {
3539        let yaml = r#"
3540id: j
3541version: 1.0.0
3542execute:
3543  shell: powershell
3544  script: "echo x"
3545  timeout: 30s
3546client:
3547  name: "A job"
3548  category: settings
3549  visible_to:
3550    groups: [wifi-affected]
3551"#;
3552        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3553        m.validate().expect("visible_to with a group validates");
3554        let vt = m.client.unwrap().visible_to.unwrap();
3555        assert_eq!(vt.groups, vec!["wifi-affected".to_string()]);
3556    }
3557
3558    #[test]
3559    fn manifest_client_show_when_accepts_scalar_and_seq() {
3560        use crate::ipc::state::CheckStatus;
3561        // `is:` accepts a single status (author ergonomics) ...
3562        let scalar = r#"
3563id: office-update
3564version: 1.0.0
3565execute:
3566  shell: powershell
3567  script: "echo x"
3568  timeout: 30s
3569client:
3570  name: "Office を最新に更新"
3571  category: software_update
3572  show_when:
3573    check: office-up-to-date
3574    is: fail
3575"#;
3576        let m: Manifest = serde_yaml::from_str(scalar).expect("parse scalar");
3577        m.validate().expect("scalar show_when validates");
3578        let sw = m.client.unwrap().show_when.unwrap();
3579        assert_eq!(sw.check, "office-up-to-date");
3580        assert_eq!(sw.is, vec![CheckStatus::Fail]);
3581
3582        // ... and a list (e.g. fail-open on a not-yet-run check).
3583        let seq = scalar.replace("is: fail", "is: [fail, unknown]");
3584        let m: Manifest = serde_yaml::from_str(&seq).expect("parse seq");
3585        m.validate().expect("seq show_when validates");
3586        assert_eq!(
3587            m.client.unwrap().show_when.unwrap().is,
3588            vec![CheckStatus::Fail, CheckStatus::Unknown]
3589        );
3590    }
3591
3592    #[test]
3593    fn manifest_client_show_when_rejects_empty() {
3594        // A malformed check slug (here: internal spaces — a typo that could
3595        // never match a real check name) or an empty status list would
3596        // silently hide the job forever — validate() must reject both.
3597        let bad_check = r#"
3598id: j
3599version: 1.0.0
3600execute:
3601  shell: powershell
3602  script: "echo x"
3603  timeout: 30s
3604client:
3605  name: "A job"
3606  category: software_update
3607  show_when:
3608    check: "office up to date"
3609    is: fail
3610"#;
3611        let m: Manifest = serde_yaml::from_str(bad_check).expect("parse");
3612        let err = m.validate().expect_err("malformed check slug must fail");
3613        assert!(err.contains("client.show_when.check"), "err: {err}");
3614
3615        let empty_is = r#"
3616id: j
3617version: 1.0.0
3618execute:
3619  shell: powershell
3620  script: "echo x"
3621  timeout: 30s
3622client:
3623  name: "A job"
3624  category: software_update
3625  show_when:
3626    check: office-up-to-date
3627    is: []
3628"#;
3629        let m: Manifest = serde_yaml::from_str(empty_is).expect("parse");
3630        let err = m.validate().expect_err("empty is[] must fail");
3631        assert!(err.contains("client.show_when.is"), "err: {err}");
3632    }
3633
3634    #[test]
3635    fn manifest_client_requires_category_at_parse() {
3636        // A `client:` block missing `category` is a hard parse error
3637        // (serde required field) — no manual validate() needed.
3638        let yaml = r#"
3639id: j
3640version: 1.0.0
3641execute:
3642  shell: powershell
3643  script: "echo x"
3644  timeout: 30s
3645client:
3646  name: "A job"
3647"#;
3648        let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
3649        assert!(
3650            r.is_err(),
3651            "missing category must be a parse error, got {r:?}"
3652        );
3653    }
3654
3655    #[test]
3656    fn manifest_client_rejects_unknown_field() {
3657        // #492: the strict create boundary catches a fat-fingered
3658        // `displayname:` (with its path) instead of silently
3659        // dropping it; the tolerant read path accepts it.
3660        let yaml = r#"
3661id: j
3662version: 1.0.0
3663execute:
3664  shell: powershell
3665  script: "echo x"
3666  timeout: 30s
3667client:
3668  name: "A job"
3669  category: catalog
3670  displayname: oops
3671"#;
3672        let r = crate::strict::from_yaml_str::<Manifest>(yaml);
3673        let err = r.expect_err("unknown client field must be rejected at the write boundary");
3674        // serde_ignored renders the Option layer as `?`:
3675        // `client.?.displayname`. Assert on the leaf key.
3676        assert!(err.contains("displayname"), "{err}");
3677        // The READ path tolerates the same payload (gradual-upgrade
3678        // contract: an old agent must accept a newer writer's field).
3679        let m: Manifest = serde_yaml::from_str(yaml).expect("tolerant read");
3680        assert_eq!(m.client.as_ref().map(|c| c.name.as_str()), Some("A job"));
3681    }
3682
3683    #[test]
3684    fn manifest_tags_default_empty() {
3685        // The overwhelming majority of jobs carry no tags; the field
3686        // must default to an empty Vec (not fail to parse) and skip
3687        // serialisation so old readers never see the key.
3688        let yaml = r#"
3689id: echo-test
3690version: 0.0.1
3691execute:
3692  shell: powershell
3693  script: "echo 'kanade'"
3694  timeout: 30s
3695"#;
3696        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3697        assert!(m.tags.is_empty());
3698        m.validate().expect("tag-less job validates");
3699        // skip_serializing_if = empty ⇒ the key is absent from JSON.
3700        let json = serde_json::to_string(&m).expect("serialize");
3701        assert!(
3702            !json.contains("tags"),
3703            "empty tags must not serialise: {json}"
3704        );
3705    }
3706
3707    #[test]
3708    fn manifest_parses_and_validates_tags() {
3709        let yaml = r#"
3710id: check-bitlocker
3711version: 0.1.0
3712execute:
3713  shell: powershell
3714  script: "echo x"
3715  timeout: 30s
3716tags: [security, windows, health-check]
3717"#;
3718        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3719        assert_eq!(m.tags, vec!["security", "windows", "health-check"]);
3720        m.validate().expect("tagged job validates");
3721        // Round-trips through JSON (the wire format the SPA reads).
3722        let json = serde_json::to_string(&m).expect("serialize");
3723        assert!(json.contains("\"tags\""), "non-empty tags must serialise");
3724    }
3725
3726    #[test]
3727    fn manifest_rejects_blank_tag() {
3728        // A whitespace-only tag renders an empty filter chip — reject
3729        // it at the write boundary like the other blank display fields.
3730        let yaml = r#"
3731id: j
3732version: 0.1.0
3733execute:
3734  shell: powershell
3735  script: "echo x"
3736  timeout: 30s
3737tags: [ok, "   "]
3738"#;
3739        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3740        let err = m.validate().expect_err("blank tag must fail");
3741        assert!(err.contains("tags must not contain empty"), "err: {err}");
3742    }
3743
3744    #[test]
3745    fn validate_rejects_unknown_tier_and_accepts_known() {
3746        let base =
3747            "id: t\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: x\n  timeout: 30s\n";
3748        // A typo / future tier decodes to Tier::Unknown (#[serde(other)]) and
3749        // must FAIL CLOSED — never fall back to unrestricted endpoint dispatch.
3750        let bogus: Manifest =
3751            serde_yaml::from_str(&format!("{base}tier: controler\n")).expect("parse");
3752        let err = bogus.validate().expect_err("unknown tier must be rejected");
3753        assert!(err.contains("tier"), "err: {err}");
3754        // The two known tiers pass.
3755        serde_yaml::from_str::<Manifest>(&format!("{base}tier: controller\n"))
3756            .unwrap()
3757            .validate()
3758            .expect("controller tier is valid");
3759        serde_yaml::from_str::<Manifest>(&format!("{base}tier: endpoint\n"))
3760            .unwrap()
3761            .validate()
3762            .expect("endpoint tier is valid");
3763    }
3764
3765    #[test]
3766    fn feed_payload_extracts_fenced_block() {
3767        let stdout = "fetched 1500 KEV entries\n\
3768            #KANADE-FEED-BEGIN\n\
3769            {\"vulnerabilities\": []}\n\
3770            #KANADE-FEED-END\n";
3771        assert_eq!(feed_payload(stdout), "{\"vulnerabilities\": []}");
3772    }
3773
3774    #[test]
3775    fn validate_feed_rules() {
3776        let base =
3777            "id: f\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: x\n  timeout: 30s\n";
3778        // A well-formed feed (controller implied; no explicit tier) passes.
3779        serde_yaml::from_str::<Manifest>(&format!(
3780            "{base}feed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
3781        ))
3782        .unwrap()
3783        .validate()
3784        .expect("a well-formed feed is valid");
3785
3786        // Empty primary_key is rejected (no item_id → every row dropped).
3787        let err = serde_yaml::from_str::<Manifest>(&format!(
3788            "{base}feed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: []\n"
3789        ))
3790        .unwrap()
3791        .validate()
3792        .expect_err("empty primary_key must be rejected");
3793        assert!(err.contains("primary_key"), "err: {err}");
3794
3795        // A duplicate feed id clobbers a partition — rejected.
3796        let err = serde_yaml::from_str::<Manifest>(&format!(
3797            "{base}feed:\n  - id: dup\n    field: a\n    primary_key: [k]\n  - id: dup\n    field: b\n    primary_key: [k]\n"
3798        ))
3799        .unwrap()
3800        .validate()
3801        .expect_err("duplicate feed id must be rejected");
3802        assert!(err.contains("more than once"), "err: {err}");
3803
3804        // `feed:` + explicit `tier: endpoint` is contradictory — rejected.
3805        let err = serde_yaml::from_str::<Manifest>(&format!(
3806            "{base}tier: endpoint\nfeed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
3807        ))
3808        .unwrap()
3809        .validate()
3810        .expect_err("feed + tier: endpoint must be rejected");
3811        assert!(err.contains("controller tier"), "err: {err}");
3812
3813        // `feed:` + `emit:` is incompatible — emit consumes stdout whole, so
3814        // the feed's fence never reaches the projector.
3815        let err = serde_yaml::from_str::<Manifest>(&format!(
3816            "{base}emit:\n  type: events\nfeed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
3817        ))
3818        .unwrap()
3819        .validate()
3820        .expect_err("feed + emit must be rejected");
3821        assert!(err.contains("emit"), "err: {err}");
3822    }
3823
3824    // #720 — wrap an `aggregate:` YAML block (already indented as a
3825    // top-level key body) into an otherwise-minimal valid manifest.
3826    fn manifest_with_aggregate(aggregate_block: &str) -> Manifest {
3827        let yaml = format!(
3828            "id: t\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: echo hi\n  timeout: 30s\n{aggregate_block}"
3829        );
3830        serde_yaml::from_str(&yaml).expect("parse aggregate manifest")
3831    }
3832
3833    #[test]
3834    fn aggregate_accepts_full_valid_spec() {
3835        // count+group_by+exclude+sample_minutes, ratio+bool_path,
3836        // timeline+time_bucket, fleet ranking via group_by: pc_id, and a
3837        // bare total stat — alongside emit (composes with every hint).
3838        let m = manifest_with_aggregate(
3839            "emit:\n  type: events\naggregate:\n\
3840             - { dashboard: Utilization, title: Top apps, kind: app_sample, agg: count, group_by: foreground.app, sample_minutes: 2, exclude: [LockApp], render: bar }\n\
3841             - { dashboard: Utilization, title: Active ratio, kind: presence, agg: ratio, bool_path: active, sample_minutes: 5, render: gauge }\n\
3842             - { dashboard: Utilization, title: By hour, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: timeline }\n\
3843             - { dashboard: Reliability, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
3844             - { dashboard: Reliability, title: Total crashes, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
3845        );
3846        m.validate().expect("valid aggregate spec");
3847    }
3848
3849    #[test]
3850    fn aggregate_rejects_empty_list() {
3851        let m = manifest_with_aggregate("aggregate: []\n");
3852        let err = m.validate().expect_err("empty list must fail");
3853        assert!(err.contains("at least one widget"), "err: {err}");
3854    }
3855
3856    #[test]
3857    fn aggregate_rejects_ratio_without_bool_path() {
3858        let m = manifest_with_aggregate(
3859            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, render: gauge }\n",
3860        );
3861        let err = m.validate().expect_err("ratio needs bool_path");
3862        assert!(err.contains("agg=ratio requires `bool_path`"), "err: {err}");
3863    }
3864
3865    #[test]
3866    fn aggregate_rejects_sum_without_value_path() {
3867        let m = manifest_with_aggregate(
3868            "aggregate:\n- { dashboard: D, title: T, kind: io, agg: sum, render: bar }\n",
3869        );
3870        let err = m.validate().expect_err("sum needs value_path");
3871        assert!(err.contains("agg=sum requires `value_path`"), "err: {err}");
3872    }
3873
3874    #[test]
3875    fn aggregate_rejects_pc_id_group_without_fleet() {
3876        let m = manifest_with_aggregate(
3877            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: count, group_by: pc_id, render: bar }\n",
3878        );
3879        let err = m.validate().expect_err("pc_id grouping needs fleet");
3880        assert!(
3881            err.contains("pc_id is only valid with scope: fleet"),
3882            "err: {err}"
3883        );
3884    }
3885
3886    #[test]
3887    fn aggregate_rejects_transform_with_pc_id_group() {
3888        let m = manifest_with_aggregate(
3889            "aggregate:\n- { dashboard: D, title: T, scope: fleet, kind: web_visit, agg: count, group_by: pc_id, transform: host, render: bar }\n",
3890        );
3891        let err = m
3892            .validate()
3893            .expect_err("transform on pc_id grouping must fail");
3894        assert!(
3895            err.contains("transform is not valid with group_by: pc_id"),
3896            "err: {err}"
3897        );
3898    }
3899
3900    #[test]
3901    fn aggregate_rejects_timeline_without_bucket() {
3902        let m = manifest_with_aggregate(
3903            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, bool_path: active, render: timeline }\n",
3904        );
3905        let err = m.validate().expect_err("timeline needs a bucket");
3906        assert!(
3907            err.contains("render=timeline requires `time_bucket`"),
3908            "err: {err}"
3909        );
3910    }
3911
3912    #[test]
3913    fn aggregate_rejects_bucket_on_non_timeline() {
3914        let m = manifest_with_aggregate(
3915            "aggregate:\n- { dashboard: D, title: T, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: gauge }\n",
3916        );
3917        let err = m.validate().expect_err("bucket only on timeline");
3918        assert!(
3919            err.contains("time_bucket is only valid with render: timeline"),
3920            "err: {err}"
3921        );
3922    }
3923
3924    #[test]
3925    fn aggregate_rejects_unsafe_json_path() {
3926        // A path with characters outside [A-Za-z0-9_.] could break out of
3927        // the `'$.' || ?` bind — reject at create time.
3928        let m = manifest_with_aggregate(
3929            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: \"foo'; DROP\", render: bar }\n",
3930        );
3931        let err = m.validate().expect_err("unsafe path must fail");
3932        assert!(err.contains("dotted JSON path"), "err: {err}");
3933    }
3934
3935    #[test]
3936    fn aggregate_rejects_blank_title() {
3937        let m = manifest_with_aggregate(
3938            "aggregate:\n- { dashboard: D, title: \"  \", kind: k, agg: count, render: stat }\n",
3939        );
3940        let err = m.validate().expect_err("blank title must fail");
3941        assert!(err.contains("title must not be empty"), "err: {err}");
3942    }
3943
3944    #[test]
3945    fn aggregate_rejects_blank_kind() {
3946        let m = manifest_with_aggregate(
3947            "aggregate:\n- { dashboard: D, title: T, kind: \" \", agg: count, render: stat }\n",
3948        );
3949        let err = m.validate().expect_err("blank kind must fail");
3950        assert!(err.contains("kind must not be empty"), "err: {err}");
3951    }
3952
3953    #[test]
3954    fn aggregate_rejects_blank_source_when_set() {
3955        let m = manifest_with_aggregate(
3956            "aggregate:\n- { dashboard: D, title: T, kind: k, source: \"\", agg: count, render: stat }\n",
3957        );
3958        let err = m.validate().expect_err("blank source must fail");
3959        assert!(
3960            err.contains("source must not be empty when set"),
3961            "err: {err}"
3962        );
3963    }
3964
3965    #[test]
3966    fn aggregate_accepts_description_and_rejects_blank() {
3967        let ok = manifest_with_aggregate(
3968            "aggregate:\n- { dashboard: D, title: T, description: \"samples x 2 min\", kind: k, agg: count, render: stat }\n",
3969        );
3970        ok.validate()
3971            .expect("description is a valid optional field");
3972        assert_eq!(
3973            ok.aggregate.as_ref().unwrap()[0].description.as_deref(),
3974            Some("samples x 2 min")
3975        );
3976        let bad = manifest_with_aggregate(
3977            "aggregate:\n- { dashboard: D, title: T, description: \"  \", kind: k, agg: count, render: stat }\n",
3978        );
3979        let err = bad.validate().expect_err("blank description must fail");
3980        assert!(
3981            err.contains("description must not be empty when set"),
3982            "err: {err}"
3983        );
3984    }
3985
3986    #[test]
3987    fn aggregate_rejects_count_with_value_path() {
3988        let m = manifest_with_aggregate(
3989            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, value_path: bytes, render: stat }\n",
3990        );
3991        let err = m.validate().expect_err("count must not use value_path");
3992        assert!(
3993            err.contains("agg=count does not use `value_path`"),
3994            "err: {err}"
3995        );
3996    }
3997
3998    #[test]
3999    fn aggregate_rejects_ratio_with_value_path() {
4000        let m = manifest_with_aggregate(
4001            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: ratio, bool_path: active, value_path: bytes, render: gauge }\n",
4002        );
4003        let err = m.validate().expect_err("ratio must not use value_path");
4004        assert!(
4005            err.contains("agg=ratio does not use `value_path`"),
4006            "err: {err}"
4007        );
4008    }
4009
4010    #[test]
4011    fn aggregate_rejects_gauge_without_ratio() {
4012        let m = manifest_with_aggregate(
4013            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, render: gauge }\n",
4014        );
4015        let err = m.validate().expect_err("gauge needs ratio");
4016        assert!(
4017            err.contains("render=gauge is only valid with agg: ratio"),
4018            "err: {err}"
4019        );
4020    }
4021
4022    #[test]
4023    fn aggregate_rejects_limit_without_group_by() {
4024        let m = manifest_with_aggregate(
4025            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, limit: 5, render: stat }\n",
4026        );
4027        let err = m.validate().expect_err("limit needs group_by");
4028        assert!(err.contains("limit requires `group_by`"), "err: {err}");
4029    }
4030
4031    #[test]
4032    fn aggregate_rejects_exclude_without_group_by() {
4033        let m = manifest_with_aggregate(
4034            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, exclude: [x], render: stat }\n",
4035        );
4036        let err = m.validate().expect_err("exclude needs group_by");
4037        assert!(err.contains("exclude requires `group_by`"), "err: {err}");
4038    }
4039
4040    #[test]
4041    fn aggregate_rejects_zero_limit_and_zero_sample_minutes() {
4042        let m = manifest_with_aggregate(
4043            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, limit: 0, render: bar }\n",
4044        );
4045        assert!(m.validate().unwrap_err().contains("limit must be > 0"));
4046        let m = manifest_with_aggregate(
4047            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, sample_minutes: 0, render: bar }\n",
4048        );
4049        assert!(
4050            m.validate()
4051                .unwrap_err()
4052                .contains("sample_minutes must be > 0")
4053        );
4054    }
4055
4056    #[test]
4057    fn aggregate_rejects_empty_exclude_entry() {
4058        let m = manifest_with_aggregate(
4059            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, group_by: app, exclude: [\"  \"], render: bar }\n",
4060        );
4061        let err = m.validate().expect_err("blank exclude entry must fail");
4062        assert!(
4063            err.contains("exclude must not contain empty entries"),
4064            "err: {err}"
4065        );
4066    }
4067
4068    #[test]
4069    fn aggregate_rejects_malformed_dotted_paths() {
4070        for bad in [".foo", "foo.", "foo..bar", "."] {
4071            let m = manifest_with_aggregate(&format!(
4072                "aggregate:\n- {{ dashboard: D, title: T, kind: k, agg: count, group_by: \"{bad}\", render: bar }}\n"
4073            ));
4074            let err = m.validate().expect_err("malformed path must fail");
4075            assert!(err.contains("dotted JSON path"), "path {bad}: {err}");
4076        }
4077    }
4078
4079    #[test]
4080    fn aggregate_rejects_unknown_enum_value() {
4081        // An unrecognised render string deserialises to the #492 Unknown
4082        // catch-all (so old readers don't choke); validate() rejects it as
4083        // a typo at create time.
4084        let m = manifest_with_aggregate(
4085            "aggregate:\n- { dashboard: D, title: T, kind: k, agg: count, render: heatmap }\n",
4086        );
4087        let err = m.validate().expect_err("unknown render must fail");
4088        assert!(err.contains("render is not a known value"), "err: {err}");
4089    }
4090
4091    #[test]
4092    fn aggregate_accepts_order_field() {
4093        let m = manifest_with_aggregate(
4094            "aggregate:\n- { dashboard: D, title: T, order: -5, kind: k, agg: count, render: stat }\n",
4095        );
4096        m.validate().expect("order is a valid optional field");
4097        let w = &m.aggregate.as_ref().unwrap()[0];
4098        assert_eq!(w.order, Some(-5));
4099    }
4100
4101    #[test]
4102    fn aggregate_accepts_minimal_op_timeline() {
4103        // op_timeline needs no kind/agg — it reconstructs a fixed multi-kind
4104        // swimlane. A bare per-PC spec is valid, and `kind`/`agg` stay None.
4105        let m = manifest_with_aggregate(
4106            "aggregate:\n- { dashboard: Uptime, title: Operational state, scope: pc, render: op_timeline }\n",
4107        );
4108        m.validate().expect("minimal op_timeline is valid");
4109        let w = &m.aggregate.as_ref().unwrap()[0];
4110        assert_eq!(w.render, AggregateRender::OpTimeline);
4111        assert!(w.kind.is_none());
4112        assert!(w.agg.is_none());
4113    }
4114
4115    #[test]
4116    fn aggregate_rejects_op_timeline_with_fleet_scope() {
4117        let m = manifest_with_aggregate(
4118            "aggregate:\n- { dashboard: Uptime, title: T, scope: fleet, render: op_timeline }\n",
4119        );
4120        let err = m.validate().expect_err("op_timeline must be per-PC");
4121        assert!(
4122            err.contains("render=op_timeline requires scope: pc"),
4123            "err: {err}"
4124        );
4125    }
4126
4127    #[test]
4128    fn aggregate_rejects_op_timeline_with_aggregation_fields() {
4129        // Each aggregation knob the operator might paste in is rejected
4130        // (rather than silently ignored), pointing at the field to delete.
4131        for (block, field) in [
4132            ("kind: boot", "kind"),
4133            ("agg: count", "agg"),
4134            ("source: winlog:Security", "source"),
4135            ("group_by: pc_id", "group_by"),
4136            ("bool_path: active", "bool_path"),
4137            ("time_bucket: hour", "time_bucket"),
4138            ("limit: 5", "limit"),
4139        ] {
4140            let m = manifest_with_aggregate(&format!(
4141                "aggregate:\n- {{ dashboard: Uptime, title: T, scope: pc, {block}, render: op_timeline }}\n"
4142            ));
4143            let err = m
4144                .validate()
4145                .expect_err(&format!("op_timeline must reject {field}"));
4146            assert!(
4147                err.contains(&format!("render=op_timeline does not use `{field}`")),
4148                "field {field}: {err}"
4149            );
4150        }
4151    }
4152
4153    // ── #743 View resource ───────────────────────────────────────────
4154    fn view_from(yaml_body: &str) -> View {
4155        serde_yaml::from_str(&format!("id: v1\n{yaml_body}")).expect("parse view")
4156    }
4157
4158    #[test]
4159    fn view_accepts_valid_widgets() {
4160        let v = view_from(
4161            "widgets:\n\
4162             - { dashboard: Reliability, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
4163             - { dashboard: Reliability, title: Total, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
4164        );
4165        v.validate().expect("valid view");
4166    }
4167
4168    #[test]
4169    fn view_rejects_empty_widgets() {
4170        let v = view_from("widgets: []\n");
4171        let err = v.validate().expect_err("empty widgets must fail");
4172        assert!(err.contains("at least one widget"), "err: {err}");
4173    }
4174
4175    #[test]
4176    fn view_rejects_blank_id() {
4177        let v: View = serde_yaml::from_str(
4178            "id: \"  \"\nwidgets:\n- { dashboard: D, title: T, kind: k, agg: count, render: stat }\n",
4179        )
4180        .expect("parse");
4181        let err = v.validate().expect_err("blank id must fail");
4182        assert!(err.contains("view.id must"), "err: {err}");
4183    }
4184
4185    #[test]
4186    fn view_rejects_unsafe_id() {
4187        // A `/` or `..` in the id would break the KV key and the
4188        // `/api/views/{id}` URL segment — reject at create time.
4189        for bad in ["../etc", "a/b", "has space", "x;y"] {
4190            let v: View = serde_yaml::from_str(&format!(
4191                "id: \"{bad}\"\nwidgets:\n- {{ dashboard: D, title: T, kind: k, agg: count, render: stat }}\n",
4192            ))
4193            .expect("parse");
4194            let err = v.validate().expect_err("unsafe id must fail");
4195            assert!(err.contains("[A-Za-z0-9._-]"), "id {bad}: {err}");
4196        }
4197        assert!(is_valid_resource_id("dashboards-fleet.v1_2"));
4198    }
4199
4200    #[test]
4201    fn view_reuses_shared_widget_validation() {
4202        // The same per-widget rule the job hint enforces (ratio needs
4203        // bool_path), reported under the `widgets[..]` field.
4204        let v = view_from(
4205            "widgets:\n- { dashboard: D, title: T, kind: presence, agg: ratio, render: gauge }\n",
4206        );
4207        let err = v.validate().expect_err("ratio without bool_path must fail");
4208        assert!(
4209            err.contains("widgets[0].agg=ratio requires `bool_path`"),
4210            "err: {err}"
4211        );
4212    }
4213
4214    // ── #vuln-roadmap PR3 SQL-backed views ───────────────────────────
4215    #[test]
4216    fn view_accepts_pure_sql_widgets() {
4217        // A view with only sql_widgets (no obs_events aggregate widgets) is
4218        // valid — the vulnerability-dashboard shape.
4219        let v = view_from(
4220            "sql_widgets:
4221  - title: KEV-affected hosts
4222    query: \"SELECT pc_id, 1 AS cves FROM inventory_sw_apps\"
4223    refresh: 6h
4224    render: { kind: table, columns: [pc_id, cves], labels: { cves: CVE count } }
4225    placement: { analytics: Security, dashboard: { pin: true } }
4226",
4227        );
4228        v.validate().expect("valid sql view");
4229        // refresh parses; pin/tab helpers read the placement.
4230        let w = &v.sql_widgets[0];
4231        assert_eq!(
4232            w.refresh_interval(),
4233            std::time::Duration::from_secs(6 * 3600)
4234        );
4235        assert!(w.placement.is_pinned());
4236        assert_eq!(w.placement.tab(), "Security");
4237    }
4238
4239    #[test]
4240    fn sql_widget_defaults_and_mix() {
4241        // No refresh ⇒ default; a view can mix aggregate + sql widgets.
4242        let v = view_from(
4243            "widgets:
4244  - { dashboard: D, title: T, kind: k, agg: count, render: stat }
4245sql_widgets:
4246  - title: N affected
4247    query: \"SELECT count(*) AS n FROM feeds\"
4248    render: { kind: stat, value: n }
4249    placement: { dashboard: { pin: true } }
4250",
4251        );
4252        v.validate().expect("mixed view is valid");
4253        assert_eq!(v.sql_widgets[0].refresh_interval(), DEFAULT_VIEW_REFRESH);
4254        // dashboard-only placement (no analytics tab) falls back to a label.
4255        assert_eq!(v.sql_widgets[0].placement.tab(), "Dashboard");
4256    }
4257
4258    #[test]
4259    fn sql_widget_validation_rules() {
4260        // helper: build a view with one sql_widget from an inline render+placement
4261        let mk = |render: &str, placement: &str| -> Result<(), String> {
4262            view_from(&format!(
4263                "sql_widgets:
4264  - title: W
4265    query: \"SELECT 1 AS a\"
4266    render: {render}
4267    placement: {placement}
4268"
4269            ))
4270            .validate()
4271        };
4272        // bar needs label + value
4273        let err = mk("{ kind: bar, value: a }", "{ analytics: T }").unwrap_err();
4274        assert!(
4275            err.contains("render.label is required for kind=bar"),
4276            "err: {err}"
4277        );
4278        // pie needs value
4279        let err = mk("{ kind: pie, label: a }", "{ analytics: T }").unwrap_err();
4280        assert!(
4281            err.contains("render.value is required for kind=pie"),
4282            "err: {err}"
4283        );
4284        // stat needs value
4285        let err = mk("{ kind: stat }", "{ analytics: T }").unwrap_err();
4286        assert!(
4287            err.contains("render.value is required for kind=stat"),
4288            "err: {err}"
4289        );
4290        // gauge needs value XOR num+den
4291        let err = mk("{ kind: gauge, num: a }", "{ analytics: T }").unwrap_err();
4292        assert!(err.contains("needs either `value`"), "err: {err}");
4293        mk("{ kind: gauge, value: a }", "{ analytics: T }").expect("gauge value ok");
4294        mk("{ kind: gauge, num: a, den: a }", "{ analytics: T }").expect("gauge num/den ok");
4295        // unknown kind rejected
4296        let err = mk("{ kind: sunburst }", "{ analytics: T }").unwrap_err();
4297        assert!(
4298            err.contains("render.kind is not a known value"),
4299            "err: {err}"
4300        );
4301        // placement must surface somewhere
4302        let err = mk("{ kind: table }", "{}").unwrap_err();
4303        assert!(err.contains("placement must set"), "err: {err}");
4304        // a `dashboard: { pin: false }` block still surfaces nowhere.
4305        let err = mk("{ kind: table }", "{ dashboard: { pin: false } }").unwrap_err();
4306        assert!(err.contains("placement must set"), "err: {err}");
4307        mk("{ kind: table }", "{ dashboard: { pin: true } }").expect("pinned dashboard ok");
4308        // limit: 0 on a bar/pie is an invisible widget — rejected.
4309        let err = mk(
4310            "{ kind: bar, label: a, value: a, limit: 0 }",
4311            "{ analytics: T }",
4312        )
4313        .unwrap_err();
4314        assert!(err.contains("limit must be >= 1"), "err: {err}");
4315        // bad refresh duration rejected
4316        let err = view_from(
4317            "sql_widgets:
4318  - { title: W, query: \"SELECT 1\", refresh: \"6 sidereal days\", render: { kind: table }, placement: { analytics: T } }
4319",
4320        )
4321        .validate()
4322        .unwrap_err();
4323        assert!(
4324            err.contains("refresh") && err.contains("not a valid duration"),
4325            "err: {err}"
4326        );
4327        // table is fine with no channels
4328        mk("{ kind: table }", "{ analytics: T }").expect("bare table ok");
4329    }
4330
4331    #[test]
4332    fn rewrite_pc_id_param_is_literal_and_boundary_aware() {
4333        // A real param outside any literal is rewritten + counted.
4334        let (sql, n) = rewrite_pc_id_param("SELECT * FROM t WHERE pc_id = :pc_id");
4335        assert_eq!(n, 1);
4336        assert!(sql.ends_with("pc_id = ?"), "sql: {sql}");
4337        // Appearing twice → two `?`, count 2 (one bind each — the caller binds
4338        // pc_id per occurrence since sqlx-sqlite has no named params).
4339        let (sql, n) = rewrite_pc_id_param("WHERE a = :pc_id AND (:pc_id IS NOT NULL)");
4340        assert_eq!(n, 2);
4341        assert_eq!(sql, "WHERE a = ? AND (? IS NOT NULL)");
4342        // Inside a string literal → copied verbatim, NOT counted (would else be
4343        // a bind-count mismatch → SQLITE_RANGE, and misclassify scope).
4344        let (sql, n) = rewrite_pc_id_param("SELECT 'see :pc_id docs' AS hint");
4345        assert_eq!(n, 0);
4346        assert_eq!(sql, "SELECT 'see :pc_id docs' AS hint");
4347        // Inside a comment → left alone.
4348        let (_, n) = rewrite_pc_id_param("SELECT 1 -- filter by :pc_id\n");
4349        assert_eq!(n, 0);
4350        // A longer identifier prefix (`:pc_idx`) is not our token.
4351        let (sql, n) = rewrite_pc_id_param("WHERE x = :pc_idx");
4352        assert_eq!(n, 0);
4353        assert_eq!(sql, "WHERE x = :pc_idx");
4354    }
4355
4356    #[test]
4357    fn validate_rejects_pinned_per_pc_widget() {
4358        // A per-PC widget (binds :pc_id) that also pins to the Dashboard is a
4359        // create-time contradiction (Dashboard is fleet-scope) — rejected.
4360        let err = view_from(
4361            "sql_widgets:
4362  - title: W
4363    query: \"SELECT count(*) AS n FROM inventory_sw_apps WHERE pc_id = :pc_id\"
4364    render: { kind: stat, value: n }
4365    placement: { analytics: Security, dashboard: { pin: true } }
4366",
4367        )
4368        .validate()
4369        .unwrap_err();
4370        assert!(err.contains("per-PC widget"), "err: {err}");
4371        // The same widget WITHOUT the pin is fine (per-PC, analytics only).
4372        view_from(
4373            "sql_widgets:
4374  - title: W
4375    query: \"SELECT count(*) AS n FROM inventory_sw_apps WHERE pc_id = :pc_id\"
4376    render: { kind: stat, value: n }
4377    placement: { analytics: Security }
4378",
4379        )
4380        .validate()
4381        .expect("per-PC analytics-only widget is valid");
4382    }
4383
4384    fn execute_with(
4385        script: Option<&str>,
4386        script_file: Option<&str>,
4387        script_object: Option<&str>,
4388    ) -> Execute {
4389        Execute {
4390            shell: ExecuteShell::Powershell,
4391            script: script.map(str::to_owned),
4392            script_file: script_file.map(str::to_owned),
4393            script_object: script_object.map(str::to_owned),
4394            timeout: "30s".into(),
4395            run_as: RunAs::default(),
4396            cwd: None,
4397        }
4398    }
4399
4400    #[test]
4401    fn validate_accepts_inline_script() {
4402        let e = execute_with(Some("echo hi"), None, None);
4403        assert!(e.validate_script_source().is_ok());
4404    }
4405
4406    #[test]
4407    fn validate_accepts_script_file_alone() {
4408        let e = execute_with(None, Some("scripts/cleanup.ps1"), None);
4409        assert!(e.validate_script_source().is_ok());
4410    }
4411
4412    #[test]
4413    fn validate_accepts_script_object_alone() {
4414        let e = execute_with(None, None, Some("cleanup/1.0.0"));
4415        assert!(e.validate_script_source().is_ok());
4416    }
4417
4418    #[test]
4419    fn validate_treats_empty_inline_script_as_unset() {
4420        // `script: ""` + `script_object` set is the natural shape
4421        // when an operator comments out the YAML block-scalar body
4422        // but leaves the key. Should pass.
4423        let e = execute_with(Some(""), None, Some("cleanup/1.0.0"));
4424        assert!(e.validate_script_source().is_ok());
4425    }
4426
4427    #[test]
4428    fn validate_rejects_zero_sources() {
4429        let e = execute_with(None, None, None);
4430        let err = e.validate_script_source().unwrap_err();
4431        assert!(err.contains("must be set"), "got: {err}");
4432    }
4433
4434    #[test]
4435    fn validate_rejects_empty_inline_only() {
4436        let e = execute_with(Some(""), None, None);
4437        let err = e.validate_script_source().unwrap_err();
4438        assert!(err.contains("must be set"), "got: {err}");
4439    }
4440
4441    #[test]
4442    fn validate_rejects_inline_plus_file() {
4443        let e = execute_with(Some("echo hi"), Some("scripts/cleanup.ps1"), None);
4444        let err = e.validate_script_source().unwrap_err();
4445        assert!(err.contains("only one of"), "got: {err}");
4446    }
4447
4448    #[test]
4449    fn validate_rejects_inline_plus_object() {
4450        let e = execute_with(Some("echo hi"), None, Some("cleanup/1.0.0"));
4451        let err = e.validate_script_source().unwrap_err();
4452        assert!(err.contains("only one of"), "got: {err}");
4453    }
4454
4455    #[test]
4456    fn validate_rejects_file_plus_object() {
4457        let e = execute_with(None, Some("scripts/cleanup.ps1"), Some("cleanup/1.0.0"));
4458        let err = e.validate_script_source().unwrap_err();
4459        assert!(err.contains("only one of"), "got: {err}");
4460    }
4461
4462    #[test]
4463    fn validate_rejects_all_three() {
4464        let e = execute_with(
4465            Some("echo hi"),
4466            Some("scripts/cleanup.ps1"),
4467            Some("cleanup/1.0.0"),
4468        );
4469        let err = e.validate_script_source().unwrap_err();
4470        assert!(err.contains("only one of"), "got: {err}");
4471    }
4472
4473    #[test]
4474    fn validate_rejects_blank_script_file() {
4475        // #918: a blank `script_file` used to count as "set" and pass
4476        // the exactly-one check, then fail at use time (the CLI reads
4477        // a file named "").
4478        for blank in ["", "   "] {
4479            let e = execute_with(None, Some(blank), None);
4480            let err = e.validate_script_source().unwrap_err();
4481            assert!(err.contains("script_file must not be blank"), "got: {err}");
4482        }
4483    }
4484
4485    #[test]
4486    fn validate_rejects_blank_script_object() {
4487        // #918: same for a blank `script_object` (would 404 every exec).
4488        for blank in ["", "   "] {
4489            let e = execute_with(None, None, Some(blank));
4490            let err = e.validate_script_source().unwrap_err();
4491            assert!(
4492                err.contains("script_object must not be blank"),
4493                "got: {err}"
4494            );
4495        }
4496    }
4497
4498    #[test]
4499    fn validate_treats_whitespace_inline_script_as_unset() {
4500        // #918: a whitespace-only inline body is a commented-out block,
4501        // not a real script — with no other source it's "zero sources".
4502        let e = execute_with(Some("   \n  "), None, None);
4503        let err = e.validate_script_source().unwrap_err();
4504        assert!(err.contains("must be set"), "got: {err}");
4505    }
4506
4507    #[test]
4508    fn validate_rejects_malformed_script_object_ref() {
4509        // #918: the ref must be `<name>/<version>`; a missing slash,
4510        // extra slash, blank half, or whitespace-padded half (the last
4511        // survives a JSON POST body and 404s at exec — gemini/claude
4512        // #943) can never resolve.
4513        for bad in [
4514            "no-slash", "a/b/c", "/1.0.0", "cleanup/", " / ", "foo/bar ", " foo/bar", "foo /bar",
4515        ] {
4516            let e = execute_with(None, None, Some(bad));
4517            let err = e.validate_script_source().unwrap_err();
4518            assert!(
4519                err.contains("must be `<name>/<version>`"),
4520                "for '{bad}', got: {err}"
4521            );
4522        }
4523    }
4524
4525    #[test]
4526    fn manifest_deserialises_script_object_yaml() {
4527        // SPEC §2.4.1 example shape with the Object Store
4528        // reference picked over inline.
4529        let yaml = r#"
4530id: cleanup-disk-temp
4531version: 1.0.1
4532execute:
4533  shell: powershell
4534  script_object: cleanup-disk-temp/1.0.1
4535  timeout: 600s
4536"#;
4537        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4538        assert_eq!(
4539            m.execute.script_object.as_deref(),
4540            Some("cleanup-disk-temp/1.0.1")
4541        );
4542        assert!(m.execute.script.is_none());
4543        m.validate()
4544            .expect("script_object-only manifest passes validation");
4545    }
4546
4547    #[test]
4548    fn manifest_rejects_typo_in_script_field_name() {
4549        // #492: the strict create boundary catches `script_objectt`
4550        // and similar fat-fingers (with the full path) instead of
4551        // letting them silently fall through to "all three unset".
4552        let yaml = r#"
4553id: typo
4554version: 1.0.0
4555execute:
4556  shell: powershell
4557  script_objectt: oops
4558  timeout: 30s
4559"#;
4560        let err = crate::strict::from_yaml_str::<Manifest>(yaml)
4561            .expect_err("typo'd execute field must be rejected at the write boundary");
4562        assert!(err.contains("execute.script_objectt"), "{err}");
4563    }
4564
4565    #[test]
4566    fn schedule_carries_target_and_rollout() {
4567        let yaml = r#"
4568id: hourly-cleanup-canary
4569when:
4570  per_pc: { every: 1h }
4571job_id: cleanup
4572enabled: true
4573target:
4574  groups: [canary, wave1]
4575jitter: 30s
4576rollout:
4577  strategy: wave
4578  waves:
4579    - { group: canary, delay: 0s }
4580    - { group: wave1,  delay: 5s }
4581"#;
4582        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4583        assert_eq!(s.id, "hourly-cleanup-canary");
4584        assert_eq!(s.job_id, "cleanup");
4585        assert_eq!(s.plan.target.groups, vec!["canary", "wave1"]);
4586        assert_eq!(s.plan.jitter.as_deref(), Some("30s"));
4587        let rollout = s.plan.rollout.expect("rollout present");
4588        assert_eq!(rollout.waves.len(), 2);
4589        assert_eq!(rollout.waves[0].group, "canary");
4590        assert_eq!(rollout.waves[1].delay, "5s");
4591        assert_eq!(rollout.strategy, RolloutStrategy::Wave);
4592    }
4593
4594    #[test]
4595    fn schedule_minimal_target_all() {
4596        let yaml = r#"
4597id: kitting
4598when:
4599  per_pc: once
4600enabled: true
4601job_id: scheduled-echo
4602target: { all: true }
4603"#;
4604        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4605        assert_eq!(s.id, "kitting");
4606        assert_eq!(s.when, When::PerPc(PerPolicy::Once(OnceLiteral::Once)));
4607        assert!(s.enabled);
4608        assert_eq!(s.job_id, "scheduled-echo");
4609        assert!(s.plan.target.all);
4610        assert!(s.plan.rollout.is_none());
4611        assert!(s.plan.jitter.is_none());
4612        assert!(s.active.is_empty());
4613    }
4614
4615    #[test]
4616    fn schedule_enabled_defaults_to_true() {
4617        let yaml = r#"
4618id: x
4619when:
4620  per_pc: once
4621job_id: y
4622target: { all: true }
4623"#;
4624        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4625        assert!(s.enabled);
4626    }
4627
4628    #[test]
4629    fn schedule_tags_default_empty_and_skip_serialise() {
4630        let yaml = r#"
4631id: x
4632when:
4633  per_pc: once
4634job_id: y
4635target: { all: true }
4636"#;
4637        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4638        assert!(s.tags.is_empty());
4639        s.validate().expect("tag-less schedule validates");
4640        let json = serde_json::to_string(&s).expect("serialize");
4641        assert!(
4642            !json.contains("tags"),
4643            "empty tags must not serialise: {json}"
4644        );
4645    }
4646
4647    #[test]
4648    fn schedule_parses_and_validates_tags() {
4649        let yaml = r#"
4650id: weekly-cleanup
4651when:
4652  per_pc: { every: 1h }
4653job_id: cleanup
4654target: { all: true }
4655tags: [weekly, maintenance]
4656"#;
4657        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4658        assert_eq!(s.tags, vec!["weekly", "maintenance"]);
4659        s.validate().expect("tagged schedule validates");
4660    }
4661
4662    #[test]
4663    fn schedule_rejects_blank_tag() {
4664        let yaml = r#"
4665id: x
4666when:
4667  per_pc: once
4668job_id: y
4669target: { all: true }
4670tags: [ok, "  "]
4671"#;
4672        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
4673        let err = s.validate().expect_err("blank tag must fail");
4674        assert!(err.contains("tags must not contain empty"), "err: {err}");
4675    }
4676
4677    // ---- `when` parsing (#418 Phase 1) ----
4678
4679    fn schedule_yaml_with(when_block: &str) -> String {
4680        format!(
4681            r#"
4682id: x
4683when:
4684{when_block}
4685job_id: y
4686target: {{ all: true }}
4687"#
4688        )
4689    }
4690
4691    #[test]
4692    fn when_per_pc_every_parses_unquoted_humantime() {
4693        // `6h` is digit-led but non-numeric → YAML string, same as
4694        // the old `cooldown: 6h` convention. No quotes needed.
4695        let s: Schedule =
4696            serde_yaml::from_str(&schedule_yaml_with("  per_pc: { every: 6h }")).expect("parse");
4697        assert_eq!(
4698            s.when,
4699            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() }))
4700        );
4701    }
4702
4703    #[test]
4704    fn when_per_target_every_parses() {
4705        let s: Schedule = serde_yaml::from_str(&schedule_yaml_with("  per_target: { every: 24h }"))
4706            .expect("parse");
4707        assert_eq!(
4708            s.when,
4709            When::PerTarget(PerPolicy::Every(EverySpec {
4710                every: "24h".into()
4711            }))
4712        );
4713    }
4714
4715    #[test]
4716    fn when_per_target_once_parses() {
4717        // Falls out of the shared PerPolicy shape and decide_fire
4718        // already implements it ("any one pc succeeds → skip the
4719        // target forever"), so it is allowed, not rejected.
4720        let s: Schedule =
4721            serde_yaml::from_str(&schedule_yaml_with("  per_target: once")).expect("parse");
4722        assert_eq!(s.when, When::PerTarget(PerPolicy::Once(OnceLiteral::Once)));
4723    }
4724
4725    #[test]
4726    fn when_calendar_time_parses() {
4727        let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(
4728            "  calendar:\n    at: \"09:00\"\n    days: [mon-fri]",
4729        ))
4730        .expect("parse");
4731        match &s.when {
4732            When::Calendar(c) => {
4733                assert_eq!(c.at, "09:00");
4734                assert_eq!(c.days, vec!["mon-fri"]);
4735            }
4736            other => panic!("expected calendar, got {other:?}"),
4737        }
4738    }
4739
4740    #[test]
4741    fn when_calendar_days_default_empty() {
4742        let s: Schedule =
4743            serde_yaml::from_str(&schedule_yaml_with("  calendar:\n    at: \"09:00\""))
4744                .expect("parse");
4745        match &s.when {
4746            When::Calendar(c) => assert!(c.days.is_empty(), "days defaults to empty (= daily)"),
4747            other => panic!("expected calendar, got {other:?}"),
4748        }
4749    }
4750
4751    #[test]
4752    fn when_calendar_datetime_parses_all_separators() {
4753        // one-shot: date+time in hyphen / ISO-T / slash forms
4754        for at in ["2026-06-10 09:00", "2026-06-10T09:00", "2026/06/10 09:00"] {
4755            let block = format!("  calendar:\n    at: \"{at}\"");
4756            let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(&block))
4757                .unwrap_or_else(|e| panic!("parse '{at}': {e}"));
4758            match &s.when {
4759                When::Calendar(c) => {
4760                    use chrono::Datelike;
4761                    let p = c.parse_at().expect("parse_at");
4762                    let d = p.date.expect("datetime at carries a date");
4763                    assert_eq!((d.year(), d.month(), d.day()), (2026, 6, 10), "for '{at}'");
4764                }
4765                other => panic!("expected calendar, got {other:?}"),
4766            }
4767        }
4768    }
4769
4770    #[test]
4771    fn when_rejects_bad_once_keyword() {
4772        // `onec` must be a parse error, not a silently-absorbed
4773        // string (OnceLiteral is a single-variant enum for exactly
4774        // this reason).
4775        let r: Result<Schedule, _> = serde_yaml::from_str(&schedule_yaml_with("  per_pc: onec"));
4776        assert!(r.is_err(), "expected parse error, got {r:?}");
4777    }
4778
4779    #[test]
4780    fn when_rejects_unknown_key_in_every() {
4781        // `{ evry: 6h }` still fails on the tolerant read path: the
4782        // required `every` key is missing, so no PerPolicy variant
4783        // matches (#492 removed deny_unknown_fields, but required
4784        // keys keep the untagged disambiguation honest).
4785        let r: Result<Schedule, _> =
4786            serde_yaml::from_str(&schedule_yaml_with("  per_pc: { evry: 6h }"));
4787        assert!(r.is_err(), "expected parse error, got {r:?}");
4788    }
4789
4790    #[test]
4791    fn when_rejects_unknown_variant() {
4792        let r: Result<Schedule, _> =
4793            serde_yaml::from_str(&schedule_yaml_with("  per_galaxy: once"));
4794        assert!(r.is_err(), "expected parse error, got {r:?}");
4795    }
4796
4797    #[test]
4798    fn when_rejects_old_top_level_cron_field() {
4799        // Pre-#418 shape: top-level `cron:` + no `when:`. Must fail
4800        // loudly (missing `when`), which is what turns stale KV
4801        // blobs into warn-skips after the upgrade.
4802        let yaml = r#"
4803id: x
4804cron: "* * * * * *"
4805job_id: y
4806target: { all: true }
4807"#;
4808        let r: Result<Schedule, _> = serde_yaml::from_str(yaml);
4809        assert!(r.is_err(), "expected parse error, got {r:?}");
4810    }
4811
4812    #[test]
4813    fn when_rejects_retired_cron_escape_hatch() {
4814        // #418 Phase 2 retired `when: { cron: "..." }`. A raw cron
4815        // is now an unknown variant → parse error (operators use the
4816        // calendar form instead).
4817        let r: Result<Schedule, _> =
4818            serde_yaml::from_str(&schedule_yaml_with("  cron: \"0 0 9 * * mon-fri\""));
4819        assert!(
4820            r.is_err(),
4821            "expected parse error for retired cron, got {r:?}"
4822        );
4823    }
4824
4825    #[test]
4826    fn when_round_trips_json_and_yaml() {
4827        // Round-trip through the full Schedule: that is the wire
4828        // unit for both stores (JSON catalog KV + YAML mirror), and
4829        // it exercises the singleton_map field attribute that keeps
4830        // serde_yaml on the map shape instead of `!per_pc` tags.
4831        for when in [
4832            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
4833            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
4834            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
4835            When::PerTarget(PerPolicy::Every(EverySpec {
4836                every: "24h".into(),
4837            })),
4838            calendar("09:00", &["mon-fri"]),
4839            calendar("2026-06-10 09:00", &[]),
4840            When::On(vec![OnTrigger::Startup]),
4841            When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
4842            When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
4843            When::On(vec![OnTrigger::NetworkChange]),
4844        ] {
4845            // Event triggers are agent-only; the rest validate on backend.
4846            let runs_on = if matches!(when, When::On(_)) {
4847                RunsOn::Agent
4848            } else {
4849                RunsOn::Backend
4850            };
4851            let s = schedule_with(when.clone(), runs_on);
4852
4853            let json = serde_json::to_string(&s).expect("json serialise");
4854            let back: Schedule = serde_json::from_str(&json).expect("json deserialise");
4855            assert_eq!(back.when, when, "json round-trip for {when}");
4856
4857            let yaml = serde_yaml::to_string(&s).expect("yaml serialise");
4858            assert!(
4859                !yaml.contains('!'),
4860                "yaml must use the map shape, not tags: {yaml}"
4861            );
4862            let back: Schedule = serde_yaml::from_str(&yaml).expect("yaml deserialise");
4863            assert_eq!(back.when, when, "yaml round-trip for {when}");
4864        }
4865    }
4866
4867    #[test]
4868    fn when_once_serialises_as_bare_keyword() {
4869        // The wire shape operators see in the YAML mirror must stay
4870        // the ergonomic `per_pc: once`, not a one-variant map.
4871        let json = serde_json::to_value(When::PerPc(PerPolicy::Once(OnceLiteral::Once)))
4872            .expect("serialise");
4873        assert_eq!(json, serde_json::json!({ "per_pc": "once" }));
4874    }
4875
4876    #[test]
4877    fn when_displays_operator_summary() {
4878        for (when, expected) in [
4879            (
4880                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
4881                "per_pc once",
4882            ),
4883            (
4884                When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
4885                "per_pc every 6h",
4886            ),
4887            (
4888                When::PerTarget(PerPolicy::Every(EverySpec {
4889                    every: "24h".into(),
4890                })),
4891                "per_target every 24h",
4892            ),
4893            (calendar("09:00", &["mon-fri"]), "at 09:00 [mon-fri]"),
4894            (calendar("2026-06-10 09:00", &[]), "at 2026-06-10 09:00"),
4895            (When::On(vec![OnTrigger::Startup]), "on [startup]"),
4896            (
4897                When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
4898                "on [startup,logon]",
4899            ),
4900            (
4901                When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
4902                "on [lock,unlock]",
4903            ),
4904            (
4905                When::On(vec![OnTrigger::NetworkChange]),
4906                "on [network_change]",
4907            ),
4908        ] {
4909            assert_eq!(when.to_string(), expected);
4910        }
4911    }
4912
4913    // ---- lowering (#418: when → engine vocabulary) ----
4914
4915    fn schedule_with(when: When, runs_on: RunsOn) -> Schedule {
4916        Schedule {
4917            id: "x".into(),
4918            when,
4919            job_id: "y".into(),
4920            // #917: validate() now rejects a target that dispatches
4921            // nothing, so the baseline helper carries the simplest
4922            // specified target.
4923            plan: FanoutPlan {
4924                target: Target {
4925                    all: true,
4926                    ..Target::default()
4927                },
4928                ..FanoutPlan::default()
4929            },
4930            active: Active::default(),
4931            constraints: Constraints::default(),
4932            on_failure: OnFailure::default(),
4933            tz: ScheduleTz::default(),
4934            starting_deadline: None,
4935            runs_on,
4936            enabled: true,
4937            tags: Vec::new(),
4938            origin: None,
4939        }
4940    }
4941
4942    fn calendar(at: &str, days: &[&str]) -> When {
4943        When::Calendar(CalendarSpec {
4944            at: at.into(),
4945            days: days.iter().map(|d| (*d).to_string()).collect(),
4946        })
4947    }
4948
4949    #[test]
4950    fn next_calendar_fire_returns_next_utc_occurrence() {
4951        use chrono::TimeZone;
4952        // Daily 09:00, evaluated in UTC. From 08:00 the same day, the
4953        // next strict occurrence is 09:00 that day.
4954        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
4955        s.tz = ScheduleTz::Utc;
4956        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 8, 0, 0).unwrap();
4957        let next = s.next_calendar_fire(now).expect("calendar has a next fire");
4958        assert_eq!(
4959            next,
4960            chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap()
4961        );
4962    }
4963
4964    #[test]
4965    fn next_calendar_fire_is_strictly_after_now() {
4966        use chrono::TimeZone;
4967        // Standing exactly on a fire instant must preview the *next*
4968        // one (inclusive = false), not the one firing right now.
4969        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
4970        s.tz = ScheduleTz::Utc;
4971        let on_fire = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap();
4972        let next = s
4973            .next_calendar_fire(on_fire)
4974            .expect("calendar has a next fire");
4975        assert_eq!(
4976            next,
4977            chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()
4978        );
4979    }
4980
4981    #[test]
4982    fn next_calendar_fire_none_for_reconcile_shapes() {
4983        // `per_pc` / `per_target` lower to the every-minute poll cron —
4984        // no discrete upcoming event to preview, so `None`.
4985        let now = chrono::Utc::now();
4986        for when in [
4987            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
4988            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
4989            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
4990            When::PerTarget(PerPolicy::Every(EverySpec {
4991                every: "24h".into(),
4992            })),
4993        ] {
4994            let s = schedule_with(when, RunsOn::Backend);
4995            assert!(
4996                s.next_calendar_fire(now).is_none(),
4997                "reconcile shapes have no calendar fire",
4998            );
4999        }
5000    }
5001
5002    // ---- preview_fires (#418 dry-run / preview) ----
5003
5004    fn cal_utc(at: &str, days: &[&str]) -> Schedule {
5005        let mut s = schedule_with(calendar(at, days), RunsOn::Backend);
5006        s.tz = ScheduleTz::Utc; // host-independent assertions
5007        s
5008    }
5009
5010    #[test]
5011    fn preview_lists_next_calendar_occurrences() {
5012        use chrono::TimeZone;
5013        // Weekday 09:00, from Wed 2026-06-10 00:00 UTC: the next five
5014        // fires skip the weekend (Sat 13 / Sun 14).
5015        let s = cal_utc("09:00", &["mon-fri"]);
5016        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5017        let got = s.preview_fires(now, 5);
5018        let want: Vec<_> = [
5019            (2026, 6, 10), // Wed
5020            (2026, 6, 11), // Thu
5021            (2026, 6, 12), // Fri
5022            (2026, 6, 15), // Mon (skips Sat 13 / Sun 14)
5023            (2026, 6, 16), // Tue
5024        ]
5025        .iter()
5026        .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
5027        .collect();
5028        assert_eq!(got, want);
5029    }
5030
5031    #[test]
5032    fn preview_handles_nth_and_last_weekday() {
5033        use chrono::TimeZone;
5034        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
5035        // 2nd Tuesday (Patch Tuesday): Jun 9, Jul 14 2026.
5036        let nth = cal_utc("09:00", &["tue#2"]).preview_fires(now, 2);
5037        assert_eq!(
5038            nth,
5039            vec![
5040                chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap(),
5041                chrono::Utc.with_ymd_and_hms(2026, 7, 14, 9, 0, 0).unwrap(),
5042            ]
5043        );
5044        // Last Friday of the month: Jun 26, Jul 31 2026.
5045        let last = cal_utc("22:00", &["friL"]).preview_fires(now, 2);
5046        assert_eq!(
5047            last,
5048            vec![
5049                chrono::Utc.with_ymd_and_hms(2026, 6, 26, 22, 0, 0).unwrap(),
5050                chrono::Utc.with_ymd_and_hms(2026, 7, 31, 22, 0, 0).unwrap(),
5051            ]
5052        );
5053    }
5054
5055    #[test]
5056    fn preview_is_empty_for_reconcile_and_zero_count() {
5057        let now = chrono::Utc::now();
5058        // reconcile shapes have no discrete fire times
5059        let recon = schedule_with(
5060            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5061            RunsOn::Backend,
5062        );
5063        assert!(recon.preview_fires(now, 5).is_empty());
5064        // count == 0 yields nothing even for a calendar
5065        assert!(cal_utc("09:00", &[]).preview_fires(now, 0).is_empty());
5066    }
5067
5068    #[test]
5069    fn preview_skips_outside_active_window() {
5070        use chrono::TimeZone;
5071        // Daily 09:00, active only [2026-06-15, 2026-06-17). Occurrences
5072        // before `from` are skipped; `until` is exclusive, so 06-17's
5073        // fire is out — leaving exactly the 15th and 16th.
5074        let mut s = cal_utc("09:00", &[]);
5075        s.active = Active {
5076            from: Some("2026-06-15".into()),
5077            until: Some("2026-06-17".into()),
5078        };
5079        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5080        let got = s.preview_fires(now, 5);
5081        assert_eq!(
5082            got,
5083            vec![
5084                chrono::Utc.with_ymd_and_hms(2026, 6, 15, 9, 0, 0).unwrap(),
5085                chrono::Utc.with_ymd_and_hms(2026, 6, 16, 9, 0, 0).unwrap(),
5086            ]
5087        );
5088    }
5089
5090    #[test]
5091    fn preview_empty_when_calendar_time_outside_window() {
5092        use chrono::TimeZone;
5093        // Fires at 09:00 but the maintenance window is overnight — it can
5094        // never run, so the preview is empty (matches
5095        // `calendar_outside_window`), and the scan still terminates.
5096        let mut s = cal_utc("09:00", &[]);
5097        s.constraints = Constraints {
5098            window: Some("22:00-05:00".into()),
5099            ..Constraints::default()
5100        };
5101        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5102        assert!(s.preview_fires(now, 5).is_empty());
5103        // Every candidate tick is rejected, so this also exercises the
5104        // SCAN_CAP bound: a large `count` must still terminate (and
5105        // return empty) rather than spin (claude #578 review).
5106        assert!(s.preview_fires(now, 50).is_empty());
5107    }
5108
5109    #[test]
5110    fn preview_past_one_shot_is_empty() {
5111        use chrono::TimeZone;
5112        // A dated one-shot whose instant has passed never fires again.
5113        let s = cal_utc("2026-06-10 09:00", &[]);
5114        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 0, 0, 0).unwrap();
5115        assert!(s.preview_fires(now, 5).is_empty());
5116        // …but from before it, the single future fire shows up.
5117        let before = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
5118        assert_eq!(
5119            s.preview_fires(before, 5),
5120            vec![chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()]
5121        );
5122    }
5123
5124    #[test]
5125    fn lowering_matches_the_418_table() {
5126        let cases = [
5127            (
5128                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5129                (POLL_CRON, ExecMode::OncePerPc, None),
5130            ),
5131            (
5132                When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5133                (POLL_CRON, ExecMode::OncePerPc, Some("6h")),
5134            ),
5135            (
5136                When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5137                (POLL_CRON, ExecMode::OncePerTarget, None),
5138            ),
5139            (
5140                When::PerTarget(PerPolicy::Every(EverySpec {
5141                    every: "24h".into(),
5142                })),
5143                (POLL_CRON, ExecMode::OncePerTarget, Some("24h")),
5144            ),
5145            // calendar repeating → 6-field cron
5146            (
5147                calendar("09:00", &["mon-fri"]),
5148                ("0 0 9 * * mon-fri", ExecMode::EveryTick, None),
5149            ),
5150            // calendar daily (no days) → DOW *
5151            (
5152                calendar("18:30", &[]),
5153                ("0 30 18 * * *", ExecMode::EveryTick, None),
5154            ),
5155            // calendar one-shot → 7-field year cron
5156            (
5157                calendar("2026-06-10 09:00", &[]),
5158                ("0 0 9 10 6 * 2026", ExecMode::EveryTick, None),
5159            ),
5160        ];
5161        for (when, (cron, mode, cooldown)) in cases {
5162            let l = schedule_with(when.clone(), RunsOn::Backend).lowered();
5163            assert_eq!(l.cron, cron, "cron for {when}");
5164            assert_eq!(l.mode, mode, "mode for {when}");
5165            assert_eq!(l.cooldown.as_deref(), cooldown, "cooldown for {when}");
5166        }
5167    }
5168
5169    #[test]
5170    fn lowered_carries_schedule_tz() {
5171        for (tz, want) in [
5172            (ScheduleTz::Local, ScheduleTz::Local),
5173            (ScheduleTz::Utc, ScheduleTz::Utc),
5174        ] {
5175            let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
5176            s.tz = tz;
5177            assert_eq!(s.lowered().tz, want, "calendar carries tz");
5178            // reconcile shapes carry tz too (for the active-window check)
5179            let mut s = schedule_with(
5180                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5181                RunsOn::Backend,
5182            );
5183            s.tz = tz;
5184            assert_eq!(s.lowered().tz, want, "reconcile carries tz");
5185        }
5186    }
5187
5188    #[test]
5189    fn poll_cron_is_accepted_by_the_engine_parser() {
5190        // POLL_CRON is system-generated — if the engine's parser
5191        // ever rejected it every reconcile schedule would die at
5192        // register time. Validate it with the same croner config
5193        // (Seconds::Required, dom_and_dow, year optional).
5194        croner::parser::CronParser::builder()
5195            .seconds(croner::parser::Seconds::Required)
5196            .dom_and_dow(true)
5197            .build()
5198            .parse(POLL_CRON)
5199            .expect("POLL_CRON must parse");
5200    }
5201
5202    // ---- Schedule::validate() (#418 decision F) ----
5203
5204    #[test]
5205    fn validate_accepts_reconcile_shapes() {
5206        for when in [
5207            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5208            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5209            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5210            When::PerTarget(PerPolicy::Every(EverySpec {
5211                every: "24h".into(),
5212            })),
5213        ] {
5214            schedule_with(when.clone(), RunsOn::Backend)
5215                .validate()
5216                .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
5217        }
5218    }
5219
5220    #[test]
5221    fn validate_accepts_per_pc_on_agent() {
5222        schedule_with(
5223            When::PerPc(PerPolicy::Every(EverySpec { every: "1h".into() })),
5224            RunsOn::Agent,
5225        )
5226        .validate()
5227        .expect("per_pc + agent is the offline-inventory shape");
5228    }
5229
5230    // ---- #418 event triggers (when: { on }) ----
5231
5232    #[test]
5233    fn validate_accepts_event_on_agent() {
5234        for triggers in [
5235            vec![OnTrigger::Startup],
5236            vec![OnTrigger::Logon],
5237            vec![OnTrigger::Lock],
5238            vec![OnTrigger::Unlock],
5239            vec![OnTrigger::NetworkChange],
5240            vec![
5241                OnTrigger::Startup,
5242                OnTrigger::Logon,
5243                OnTrigger::Lock,
5244                OnTrigger::Unlock,
5245                OnTrigger::NetworkChange,
5246            ],
5247        ] {
5248            schedule_with(When::On(triggers), RunsOn::Agent)
5249                .validate()
5250                .expect("when.on is valid on runs_on: agent");
5251        }
5252    }
5253
5254    #[test]
5255    fn validate_rejects_event_on_backend() {
5256        let err = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Backend)
5257            .validate()
5258            .unwrap_err();
5259        assert!(err.contains("when.on"), "got: {err}");
5260        assert!(err.contains("runs_on: agent"), "got: {err}");
5261    }
5262
5263    #[test]
5264    fn validate_rejects_empty_event_list() {
5265        let err = schedule_with(When::On(vec![]), RunsOn::Agent)
5266            .validate()
5267            .unwrap_err();
5268        assert!(err.contains("when.on"), "got: {err}");
5269        assert!(err.contains("at least one"), "got: {err}");
5270    }
5271
5272    #[test]
5273    fn event_schedule_lowers_to_event_mode_and_is_event() {
5274        let s = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Agent);
5275        assert!(s.is_event());
5276        assert_eq!(s.lowered().mode, ExecMode::Event);
5277        assert_eq!(s.event_triggers(), &[OnTrigger::Startup]);
5278        // non-event schedules report no triggers.
5279        let cal = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5280        assert!(!cal.is_event());
5281        assert!(cal.event_triggers().is_empty());
5282    }
5283
5284    // ---- #418 constraints.require (env gates) ----
5285
5286    fn require_schedule(req: Require, runs_on: RunsOn) -> Schedule {
5287        let mut s = schedule_with(
5288            When::PerPc(PerPolicy::Every(EverySpec { every: "1m".into() })),
5289            runs_on,
5290        );
5291        s.constraints.require = Some(req);
5292        s
5293    }
5294
5295    #[test]
5296    fn require_met_combinations() {
5297        use std::time::Duration;
5298        let idle = |m: u64| Some(Duration::from_secs(m * 60));
5299        // Builder for the sensed state: (ac, idle, cpu, network).
5300        let env = |ac, idle, cpu, net| EnvState {
5301            ac_online: ac,
5302            idle,
5303            cpu_pct: cpu,
5304            network_up: net,
5305        };
5306        // Empty require — always met regardless of sensed state.
5307        assert!(require_met(
5308            &Require::default(),
5309            &env(false, None, None, false)
5310        ));
5311        // ac_power: only on AC.
5312        let ac = Require {
5313            ac_power: true,
5314            ..Default::default()
5315        };
5316        assert!(!require_met(&ac, &env(false, None, None, true)));
5317        assert!(require_met(&ac, &env(true, None, None, false)));
5318        // idle: needs >= the configured min; None idle never satisfies.
5319        let idle10 = Require {
5320            idle: Some("10m".into()),
5321            ..Default::default()
5322        };
5323        assert!(!require_met(&idle10, &env(true, None, None, true)));
5324        assert!(!require_met(&idle10, &env(true, idle(5), None, true)));
5325        assert!(require_met(&idle10, &env(true, idle(15), None, true)));
5326        assert!(require_met(&idle10, &env(true, idle(10), None, true))); // boundary inclusive
5327        // cpu_below: needs CPU strictly < threshold; None cpu never satisfies.
5328        let cpu20 = Require {
5329            cpu_below: Some(20.0),
5330            ..Default::default()
5331        };
5332        assert!(!require_met(&cpu20, &env(true, None, None, true))); // no sample → fail-closed
5333        assert!(!require_met(&cpu20, &env(true, None, Some(20.0), true))); // == threshold
5334        assert!(!require_met(&cpu20, &env(true, None, Some(55.0), true))); // busy
5335        assert!(require_met(&cpu20, &env(true, None, Some(5.0), true))); // quiet
5336        // network: only when online.
5337        let net = Require {
5338            network: true,
5339            ..Default::default()
5340        };
5341        assert!(!require_met(&net, &env(true, None, None, false))); // offline
5342        assert!(require_met(&net, &env(true, None, None, true))); // online
5343        // all four: AND.
5344        let all = Require {
5345            ac_power: true,
5346            idle: Some("10m".into()),
5347            cpu_below: Some(20.0),
5348            network: true,
5349        };
5350        assert!(!require_met(&all, &env(false, idle(20), Some(5.0), true))); // on battery
5351        assert!(!require_met(&all, &env(true, idle(1), Some(5.0), true))); // not idle enough
5352        assert!(!require_met(&all, &env(true, idle(20), Some(50.0), true))); // busy
5353        assert!(!require_met(&all, &env(true, idle(20), Some(5.0), false))); // offline
5354        assert!(require_met(&all, &env(true, idle(20), Some(5.0), true)));
5355        // An unparseable idle is treated as no-requirement by require_met
5356        // (validate rejects it at create time, so this only guards a
5357        // hand-edited blob): ac still gates.
5358        let bad = Require {
5359            ac_power: true,
5360            idle: Some("garbage".into()),
5361            ..Default::default()
5362        };
5363        assert!(require_met(&bad, &env(true, None, None, true)));
5364        assert!(!require_met(&bad, &env(false, None, None, true)));
5365    }
5366
5367    #[test]
5368    fn validate_accepts_and_rejects_cpu_below() {
5369        // In-range accepted.
5370        require_schedule(
5371            Require {
5372                cpu_below: Some(20.0),
5373                ..Default::default()
5374            },
5375            RunsOn::Agent,
5376        )
5377        .validate()
5378        .expect("cpu_below 20 is valid");
5379        // Upper boundary: 100.0 is accepted (fires unless CPU is exactly
5380        // 100%). Pins the inclusive upper bound against a future c < 100.0.
5381        require_schedule(
5382            Require {
5383                cpu_below: Some(100.0),
5384                ..Default::default()
5385            },
5386            RunsOn::Agent,
5387        )
5388        .validate()
5389        .expect("cpu_below 100 is valid");
5390        // Out of range rejected (0 and >100).
5391        for bad in [0.0, -5.0, 100.1] {
5392            let err = require_schedule(
5393                Require {
5394                    cpu_below: Some(bad),
5395                    ..Default::default()
5396                },
5397                RunsOn::Agent,
5398            )
5399            .validate()
5400            .unwrap_err();
5401            assert!(
5402                err.contains("constraints.require.cpu_below"),
5403                "cpu_below {bad}: {err}"
5404            );
5405        }
5406    }
5407
5408    #[test]
5409    fn validate_accepts_require_on_agent() {
5410        require_schedule(
5411            Require {
5412                ac_power: true,
5413                idle: Some("10m".into()),
5414                cpu_below: Some(20.0),
5415                network: true,
5416            },
5417            RunsOn::Agent,
5418        )
5419        .validate()
5420        .expect("constraints.require is valid on runs_on: agent");
5421    }
5422
5423    #[test]
5424    fn validate_rejects_require_on_backend() {
5425        let err = require_schedule(
5426            Require {
5427                ac_power: true,
5428                ..Default::default()
5429            },
5430            RunsOn::Backend,
5431        )
5432        .validate()
5433        .unwrap_err();
5434        assert!(err.contains("constraints.require"), "got: {err}");
5435        assert!(err.contains("runs_on: agent"), "got: {err}");
5436
5437        // An idle-only require (ac_power: false) is also non-empty
5438        // (is_empty folds the fields) and must reject on backend too —
5439        // guards against a regression in Require::is_empty.
5440        let err = require_schedule(
5441            Require {
5442                idle: Some("10m".into()),
5443                ..Default::default()
5444            },
5445            RunsOn::Backend,
5446        )
5447        .validate()
5448        .unwrap_err();
5449        assert!(
5450            err.contains("constraints.require"),
5451            "idle-only on backend: {err}"
5452        );
5453    }
5454
5455    #[test]
5456    fn validate_rejects_bad_require_idle() {
5457        let err = require_schedule(
5458            Require {
5459                idle: Some("not-a-duration".into()),
5460                ..Default::default()
5461            },
5462            RunsOn::Agent,
5463        )
5464        .validate()
5465        .unwrap_err();
5466        assert!(err.contains("constraints.require.idle"), "got: {err}");
5467    }
5468
5469    #[test]
5470    fn require_round_trips_and_skips_empty() {
5471        // ac_power: false is skipped; an all-default require nested in
5472        // constraints is omitted (is_empty folds it in).
5473        let yaml = "id: s\nwhen: { per_pc: { every: 1m } }\njob_id: j\nruns_on: agent\n\
5474                    constraints: { require: { ac_power: true, idle: 10m, cpu_below: 20, \
5475                    network: true } }\n";
5476        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5477        let req = s.constraints.require.as_ref().expect("require present");
5478        assert!(req.ac_power);
5479        assert_eq!(req.idle.as_deref(), Some("10m"));
5480        assert_eq!(req.cpu_below, Some(20.0));
5481        assert!(req.network);
5482        // Re-serialize: idle + cpu_below + network present, ac_power true.
5483        let back = serde_json::to_string(&s.constraints).unwrap();
5484        assert!(back.contains("\"idle\":\"10m\""), "got: {back}");
5485        assert!(back.contains("\"cpu_below\":20"), "got: {back}");
5486        assert!(back.contains("\"network\":true"), "got: {back}");
5487        // An empty require is omitted entirely by is_empty.
5488        let mut empty = s.clone();
5489        empty.constraints.require = Some(Require::default());
5490        assert!(empty.constraints.is_empty());
5491    }
5492
5493    #[test]
5494    fn validate_rejects_per_target_on_agent() {
5495        let err = schedule_with(
5496            When::PerTarget(PerPolicy::Every(EverySpec {
5497                every: "24h".into(),
5498            })),
5499            RunsOn::Agent,
5500        )
5501        .validate()
5502        .unwrap_err();
5503        assert!(err.contains("per_target"), "got: {err}");
5504        assert!(err.contains("runs_on: agent"), "got: {err}");
5505
5506        // per_target: once is also backend-only.
5507        let err = schedule_with(
5508            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5509            RunsOn::Agent,
5510        )
5511        .validate()
5512        .unwrap_err();
5513        assert!(err.contains("per_target"), "got (once): {err}");
5514        assert!(err.contains("runs_on: agent"), "got (once): {err}");
5515    }
5516
5517    #[test]
5518    fn validate_rejects_bad_every_duration() {
5519        let err = schedule_with(
5520            When::PerPc(PerPolicy::Every(EverySpec { every: "6x".into() })),
5521            RunsOn::Backend,
5522        )
5523        .validate()
5524        .unwrap_err();
5525        assert!(err.contains("when.every"), "got: {err}");
5526    }
5527
5528    #[test]
5529    fn validate_rejects_bad_jitter_and_starting_deadline() {
5530        let mut s = schedule_with(
5531            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5532            RunsOn::Backend,
5533        );
5534        s.plan.jitter = Some("5x".into());
5535        let err = s.validate().unwrap_err();
5536        assert!(err.contains("jitter"), "got: {err}");
5537
5538        let mut s = schedule_with(
5539            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5540            RunsOn::Backend,
5541        );
5542        s.starting_deadline = Some("soon".into());
5543        let err = s.validate().unwrap_err();
5544        assert!(err.contains("starting_deadline"), "got: {err}");
5545    }
5546
5547    #[test]
5548    fn validate_rejects_unspecified_target() {
5549        // #917 (1): an all-default target never dispatches anywhere —
5550        // runs_on: agent silently never fires, runs_on: backend
5551        // warn-fails every tick at the exec boundary. Both rejected.
5552        for runs_on in [RunsOn::Backend, RunsOn::Agent] {
5553            let mut s = schedule_with(When::PerPc(PerPolicy::Once(OnceLiteral::Once)), runs_on);
5554            s.plan.target = Target::default();
5555            let err = s.validate().unwrap_err();
5556            assert!(err.contains("target"), "for {runs_on:?}, got: {err}");
5557        }
5558    }
5559
5560    /// A Schedule with every top-level field populated so each one
5561    /// actually serialises (the optional ones are `skip_serializing_if`).
5562    fn fully_populated_schedule() -> Schedule {
5563        let mut s = schedule_with(
5564            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5565            RunsOn::Backend,
5566        );
5567        s.plan.rollout = Some(Rollout {
5568            strategy: RolloutStrategy::Wave,
5569            waves: vec![Wave {
5570                group: "canary".into(),
5571                delay: "0s".into(),
5572            }],
5573        });
5574        s.plan.jitter = Some("5m".into());
5575        s.plan.deadline_at = Some(chrono::Utc::now());
5576        s.active = Active {
5577            from: Some("2026-01-01 00:00".into()),
5578            until: Some("2026-12-31 00:00".into()),
5579        };
5580        s.constraints = Constraints {
5581            window: Some("09:00-17:00".into()),
5582            ..Constraints::default()
5583        };
5584        s.on_failure = OnFailure {
5585            retry: Some(Retry {
5586                max: 1,
5587                backoff: "10s".into(),
5588            }),
5589        };
5590        s.starting_deadline = Some("30m".into());
5591        s.tags = vec!["health".into()];
5592        s.origin = Some(RepoOrigin {
5593            path: "configs/schedules/x.yaml".into(),
5594            repo: None,
5595            script_file: None,
5596        });
5597        s
5598    }
5599
5600    #[test]
5601    fn schedule_top_level_keys_cover_serialized_fields() {
5602        // #924 drift guard: the hand-maintained TOP_LEVEL_KEYS list must
5603        // match exactly what a fully-populated Schedule serialises — so a
5604        // future field added to Schedule or FanoutPlan can't slip past
5605        // the flatten-aware strict guard by being forgotten here.
5606        let s = fully_populated_schedule();
5607        let value = serde_json::to_value(&s).expect("serialize schedule");
5608        let serialized: std::collections::BTreeSet<String> = value
5609            .as_object()
5610            .expect("schedule serialises to an object")
5611            .keys()
5612            .cloned()
5613            .collect();
5614        let listed: std::collections::BTreeSet<String> = Schedule::TOP_LEVEL_KEYS
5615            .iter()
5616            .map(|s| s.to_string())
5617            .collect();
5618        assert_eq!(
5619            serialized, listed,
5620            "TOP_LEVEL_KEYS is out of sync with Schedule's serialized fields \
5621             (flatten-aware strict guard would miss a real field or reject a valid one)"
5622        );
5623    }
5624
5625    #[test]
5626    fn strict_rejects_flatten_hidden_top_level_typo() {
5627        // #924: a top-level typo on a flattening type (jiter / enabledd)
5628        // is buffered into the flatten target by serde and hidden from
5629        // serde_ignored — the top-level guard must catch it. Verified on
5630        // both the YAML and JSON strict boundaries.
5631        let yaml = "\
5632id: s1
5633job_id: j1
5634when:
5635  per_pc: once
5636target:
5637  all: true
5638jiter: 5m
5639";
5640        let err = crate::strict::from_yaml_str::<Schedule>(yaml).unwrap_err();
5641        assert!(err.contains("jiter"), "got: {err}");
5642
5643        let json = serde_json::json!({
5644            "id": "s1",
5645            "job_id": "j1",
5646            "when": { "per_pc": "once" },
5647            "target": { "all": true },
5648            "enabledd": false,
5649        });
5650        let err = crate::strict::from_json_slice::<Schedule>(&serde_json::to_vec(&json).unwrap())
5651            .unwrap_err();
5652        assert!(err.contains("enabledd"), "got: {err}");
5653    }
5654
5655    #[test]
5656    fn strict_accepts_all_valid_schedule_top_level_keys() {
5657        // The guard must not reject any legitimate key — round-trip a
5658        // fully-populated schedule through the strict YAML boundary.
5659        let s = fully_populated_schedule();
5660        let yaml = serde_yaml::to_string(&s).expect("serialize");
5661        crate::strict::from_yaml_str::<Schedule>(&yaml)
5662            .expect("every serialized key must be accepted by the strict guard");
5663    }
5664
5665    #[test]
5666    fn strict_rejects_non_string_top_level_yaml_key() {
5667        // #924 (gemini #945): a YAML key isn't always a string — an
5668        // unquoted `true:` parses as a boolean, `123:` as a number. A
5669        // `filter_map` on `as_str()` would drop these and let them slip
5670        // past the flatten guard; `yaml_key_label` renders them so they
5671        // are still rejected. (serde_yaml is YAML 1.2, so `on:` stays a
5672        // *string* "on" — also rejected, just via the string path.)
5673        let base = "\
5674id: s1
5675job_id: j1
5676when:
5677  per_pc: once
5678target:
5679  all: true
5680";
5681        for (extra, needle) in [
5682            ("true: x\n", "true"),
5683            ("123: x\n", "123"),
5684            ("on: y\n", "on"),
5685        ] {
5686            let yaml = format!("{base}{extra}");
5687            let err = crate::strict::from_yaml_str::<Schedule>(&yaml).unwrap_err();
5688            assert!(err.contains(needle), "for '{extra}', got: {err}");
5689        }
5690    }
5691
5692    #[test]
5693    fn validate_accepts_waves_instead_of_target_on_backend() {
5694        // #917 (1): the exec boundary accepts rollout-only plans
5695        // (target then just labels the audit row) — so does validate.
5696        let mut s = schedule_with(
5697            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5698            RunsOn::Backend,
5699        );
5700        s.plan.target = Target::default();
5701        s.plan.rollout = Some(Rollout {
5702            strategy: RolloutStrategy::Wave,
5703            waves: vec![Wave {
5704                group: "canary".into(),
5705                delay: "0s".into(),
5706            }],
5707        });
5708        s.validate().expect("rollout-only plan should validate");
5709    }
5710
5711    #[test]
5712    fn validate_rejects_rollout_on_agent() {
5713        // #917 (1): rollout waves are backend-published; a runs_on:
5714        // agent schedule never reads them, so the combination is a
5715        // silent no-op — reject like max_concurrent-on-agent.
5716        let mut s = schedule_with(
5717            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5718            RunsOn::Agent,
5719        );
5720        s.plan.rollout = Some(Rollout {
5721            strategy: RolloutStrategy::Wave,
5722            waves: vec![Wave {
5723                group: "canary".into(),
5724                delay: "0s".into(),
5725            }],
5726        });
5727        let err = s.validate().unwrap_err();
5728        assert!(err.contains("rollout"), "got: {err}");
5729    }
5730
5731    #[test]
5732    fn validate_rejects_bad_waves() {
5733        // #917 (2): empty waves, blank group, unparseable delay — all
5734        // previously accepted and failed (or no-opped) at every fire.
5735        let base = || {
5736            schedule_with(
5737                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5738                RunsOn::Backend,
5739            )
5740        };
5741
5742        let mut s = base();
5743        s.plan.rollout = Some(Rollout {
5744            strategy: RolloutStrategy::Wave,
5745            waves: vec![],
5746        });
5747        let err = s.validate().unwrap_err();
5748        assert!(err.contains("at least one wave"), "got: {err}");
5749
5750        let mut s = base();
5751        s.plan.rollout = Some(Rollout {
5752            strategy: RolloutStrategy::Wave,
5753            waves: vec![Wave {
5754                group: "  ".into(),
5755                delay: "0s".into(),
5756            }],
5757        });
5758        let err = s.validate().unwrap_err();
5759        assert!(err.contains("waves[0].group"), "got: {err}");
5760
5761        let mut s = base();
5762        s.plan.rollout = Some(Rollout {
5763            strategy: RolloutStrategy::Wave,
5764            waves: vec![
5765                Wave {
5766                    group: "canary".into(),
5767                    delay: "0s".into(),
5768                },
5769                Wave {
5770                    group: "wave1".into(),
5771                    delay: "5 minuts".into(),
5772                },
5773            ],
5774        });
5775        let err = s.validate().unwrap_err();
5776        assert!(err.contains("waves[1].delay"), "got: {err}");
5777    }
5778
5779    #[test]
5780    fn validate_rejects_wave_delay_at_or_past_starting_deadline() {
5781        // #917 (3): the deadline is stamped once at tick time, so a
5782        // wave sleeping >= starting_deadline publishes already-expired
5783        // Commands — dead on arrival, every fire.
5784        let mut s = schedule_with(
5785            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5786            RunsOn::Backend,
5787        );
5788        s.starting_deadline = Some("30m".into());
5789        s.plan.rollout = Some(Rollout {
5790            strategy: RolloutStrategy::Wave,
5791            waves: vec![
5792                Wave {
5793                    group: "canary".into(),
5794                    delay: "0s".into(),
5795                },
5796                Wave {
5797                    group: "wave1".into(),
5798                    delay: "30m".into(),
5799                },
5800            ],
5801        });
5802        let err = s.validate().unwrap_err();
5803        assert!(
5804            err.contains("waves[1].delay") && err.contains("starting_deadline"),
5805            "got: {err}"
5806        );
5807
5808        // Strictly shorter is fine.
5809        s.plan.rollout.as_mut().unwrap().waves[1].delay = "29m".into();
5810        s.validate().expect("delay < deadline should validate");
5811    }
5812
5813    #[test]
5814    fn validate_rejects_operator_set_deadline_at() {
5815        // #917 (4): machine-stamped field — the scheduler overwrites it
5816        // on every fire, so a hand-set value is silently discarded.
5817        let mut s = schedule_with(
5818            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5819            RunsOn::Backend,
5820        );
5821        s.plan.deadline_at = Some(chrono::Utc::now());
5822        let err = s.validate().unwrap_err();
5823        assert!(
5824            err.contains("deadline_at") && err.contains("starting_deadline"),
5825            "got: {err}"
5826        );
5827    }
5828
5829    #[test]
5830    fn validate_accepts_calendar_shapes() {
5831        for when in [
5832            calendar("09:00", &["mon-fri"]),   // weekday morning
5833            calendar("00:00", &["sun"]),       // weekly
5834            calendar("18:30", &[]),            // daily
5835            calendar("2026-06-10 09:00", &[]), // one-shot
5836            calendar("2026/12/25 00:00", &[]), // one-shot, slash form
5837        ] {
5838            schedule_with(when.clone(), RunsOn::Backend)
5839                .validate()
5840                .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
5841        }
5842    }
5843
5844    #[test]
5845    fn validate_rejects_bad_at() {
5846        for bad in ["25:00", "09:60", "9", "noon", "2026-13-01 09:00"] {
5847            let err = schedule_with(calendar(bad, &[]), RunsOn::Backend)
5848                .validate()
5849                .unwrap_err();
5850            assert!(err.contains("when.at"), "for '{bad}', got: {err}");
5851        }
5852    }
5853
5854    #[test]
5855    fn validate_rejects_datetime_at_with_days() {
5856        // A dated `at` is a one-shot — pairing it with days is a
5857        // contradiction (the date already pins the day).
5858        let err = schedule_with(calendar("2026-06-10 09:00", &["mon"]), RunsOn::Backend)
5859            .validate()
5860            .unwrap_err();
5861        assert!(
5862            err.contains("one-shot") && err.contains("days"),
5863            "got: {err}"
5864        );
5865    }
5866
5867    #[test]
5868    fn validate_rejects_bad_day_name() {
5869        // A garbage DOW token is caught by the days pre-flight and
5870        // reported against `when.days`, not the confusing
5871        // "when.at lowered to invalid cron" (claude #432 review).
5872        let err = schedule_with(calendar("09:00", &["funday"]), RunsOn::Backend)
5873            .validate()
5874            .unwrap_err();
5875        assert!(err.contains("when.days"), "got: {err}");
5876        assert!(err.contains("funday"), "names the bad token: {err}");
5877        // a degenerate range like `mon-` reports the whole token, not
5878        // a cryptic empty part (claude #432 follow-up)
5879        let err = schedule_with(calendar("09:00", &["mon-"]), RunsOn::Backend)
5880            .validate()
5881            .unwrap_err();
5882        assert!(err.contains("'mon-'"), "names the whole token: {err}");
5883        // valid names / ranges / numeric / * all pass
5884        for ok in [
5885            calendar("09:00", &["mon-fri"]),
5886            calendar("09:00", &["mon", "wed", "sun"]),
5887            calendar("09:00", &["1-5"]),
5888        ] {
5889            schedule_with(ok.clone(), RunsOn::Backend)
5890                .validate()
5891                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
5892        }
5893    }
5894
5895    #[test]
5896    fn validate_accepts_nth_weekday() {
5897        // #418: nth-weekday (Patch Tuesday). validate() also lowers to
5898        // a cron and parses it with croner, so passing here proves the
5899        // whole chain — token → DOW field → engine-acceptable cron.
5900        for ok in [
5901            calendar("09:00", &["tue#2"]),          // 2nd Tuesday
5902            calendar("09:00", &["fri#1"]),          // 1st Friday
5903            calendar("03:00", &["sun#5"]),          // 5th Sunday
5904            calendar("09:00", &["tue#2", "thu#2"]), // a list of nths
5905            calendar("09:00", &["2#2"]),            // numeric DOW + ordinal
5906            // Case-insensitive both sides: validate lowercases, croner
5907            // upper-cases the whole pattern before aliasing (claude #547).
5908            calendar("09:00", &["TUE#2"]),
5909        ] {
5910            schedule_with(ok.clone(), RunsOn::Backend)
5911                .validate()
5912                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
5913        }
5914    }
5915
5916    #[test]
5917    fn validate_rejects_bad_nth_weekday() {
5918        // ordinal out of 1..5, a range with #, and a bad day before #.
5919        for bad in ["tue#0", "tue#6", "tue#x", "mon-fri#2", "funday#2"] {
5920            let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
5921                .validate()
5922                .unwrap_err();
5923            assert!(err.contains("when.days"), "for '{bad}', got: {err}");
5924        }
5925    }
5926
5927    #[test]
5928    fn validate_accepts_last_weekday() {
5929        // #418: last-weekday (`friL` = last Friday). Like the nth case,
5930        // validate() lowers to a cron and round-trips it through croner,
5931        // so passing proves token → DOW field → engine-acceptable cron
5932        // with the verified last-<dow>-of-month semantics.
5933        for ok in [
5934            calendar("09:00", &["friL"]),         // last Friday
5935            calendar("03:00", &["sunL"]),         // last Sunday
5936            calendar("22:00", &["5L"]),           // numeric DOW + last
5937            calendar("00:00", &["0L"]),           // numeric Sunday (0…
5938            calendar("00:00", &["7L"]),           // …and its 7 alias)
5939            calendar("09:00", &["monL", "friL"]), // a list of last-weekdays
5940            // Case-insensitive both the weekday and the `L` suffix:
5941            // validate lowercases the day, croner upper-cases the whole
5942            // pattern before aliasing (claude #547).
5943            calendar("09:00", &["FRIL"]),
5944            calendar("09:00", &["fril"]),
5945        ] {
5946            schedule_with(ok.clone(), RunsOn::Backend)
5947                .validate()
5948                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
5949        }
5950    }
5951
5952    #[test]
5953    fn validate_rejects_bad_last_weekday() {
5954        // bare `L` (no weekday — a footgun croner reads as Saturday), a
5955        // range with L, a bad day before L, and an internal space that
5956        // would otherwise leak a malformed cron downstream (gemini #560).
5957        for bad in ["L", "l", "mon-friL", "fundayL", "8L", "*L", "fri L"] {
5958            let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
5959                .validate()
5960                .unwrap_err();
5961            assert!(err.contains("when.days"), "for '{bad}', got: {err}");
5962        }
5963    }
5964
5965    #[test]
5966    fn calendar_oneshot_instant_detects_past() {
5967        use chrono::TimeZone;
5968        // a dated `at` resolves to an absolute instant…
5969        let c = CalendarSpec {
5970            at: "2024-01-01 09:00".into(),
5971            days: vec![],
5972        };
5973        let t = c
5974            .oneshot_instant(ScheduleTz::Utc)
5975            .expect("one-shot instant");
5976        assert_eq!(
5977            t,
5978            chrono::Utc.with_ymd_and_hms(2024, 1, 1, 9, 0, 0).unwrap()
5979        );
5980        assert!(t < chrono::Utc::now(), "2024 is in the past");
5981        // …while a repeating (time-only) calendar has no instant
5982        let rep = CalendarSpec {
5983            at: "09:00".into(),
5984            days: vec!["mon-fri".into()],
5985        };
5986        assert!(rep.oneshot_instant(ScheduleTz::Utc).is_none());
5987    }
5988
5989    fn schedule_with_active(from: Option<&str>, until: Option<&str>) -> Schedule {
5990        let mut s = schedule_with(
5991            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5992            RunsOn::Backend,
5993        );
5994        s.active = Active {
5995            from: from.map(str::to_owned),
5996            until: until.map(str::to_owned),
5997        };
5998        s
5999    }
6000
6001    #[test]
6002    fn validate_accepts_active_window() {
6003        schedule_with_active(Some("2026-07-01"), Some("2026-08-01T12:00:00+09:00"))
6004            .validate()
6005            .expect("date + rfc3339 bounds should validate");
6006    }
6007
6008    #[test]
6009    fn validate_rejects_unparseable_active_bound() {
6010        let err = schedule_with_active(Some("July 1st"), None)
6011            .validate()
6012            .unwrap_err();
6013        assert!(err.contains("active"), "got: {err}");
6014    }
6015
6016    #[test]
6017    fn validate_rejects_from_not_before_until() {
6018        let err = schedule_with_active(Some("2026-08-01"), Some("2026-07-01"))
6019            .validate()
6020            .unwrap_err();
6021        assert!(err.contains("strictly before"), "got: {err}");
6022
6023        let err = schedule_with_active(Some("2026-07-01"), Some("2026-07-01"))
6024            .validate()
6025            .unwrap_err();
6026        assert!(err.contains("strictly before"), "got: {err}");
6027    }
6028
6029    // ---- Active window semantics ----
6030
6031    #[test]
6032    fn active_window_is_half_open() {
6033        use chrono::TimeZone;
6034        let active = Active {
6035            from: Some("2026-07-01".into()),
6036            until: Some("2026-08-01".into()),
6037        };
6038        // UTC tz so the date bounds are UTC midnight.
6039        let at = |y, m, d, h| chrono::Utc.with_ymd_and_hms(y, m, d, h, 0, 0).unwrap();
6040        let c = |t| active.contains(t, ScheduleTz::Utc);
6041        assert!(!c(at(2026, 6, 30, 23)), "before from");
6042        assert!(c(at(2026, 7, 1, 0)), "at from (inclusive)");
6043        assert!(c(at(2026, 7, 15, 12)), "inside");
6044        assert!(!c(at(2026, 8, 1, 0)), "at until (exclusive)");
6045        assert!(!c(at(2026, 8, 2, 0)), "after until");
6046    }
6047
6048    #[test]
6049    fn active_empty_window_is_always_active() {
6050        assert!(Active::default().contains(chrono::Utc::now(), ScheduleTz::Local));
6051    }
6052
6053    #[test]
6054    fn active_rfc3339_bound_honours_offset_regardless_of_tz() {
6055        use chrono::TimeZone;
6056        let active = Active {
6057            from: Some("2026-07-01T09:00:00+09:00".into()),
6058            until: None,
6059        };
6060        // RFC3339 carries its own offset → tz arg is ignored.
6061        // 09:00 JST = 00:00 UTC.
6062        for tz in [ScheduleTz::Utc, ScheduleTz::Local] {
6063            assert!(
6064                !active.contains(
6065                    chrono::Utc
6066                        .with_ymd_and_hms(2026, 6, 30, 23, 59, 0)
6067                        .unwrap(),
6068                    tz
6069                )
6070            );
6071            assert!(active.contains(
6072                chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap(),
6073                tz
6074            ));
6075        }
6076    }
6077
6078    #[test]
6079    fn active_date_bound_respects_tz() {
6080        // A bare `YYYY-MM-DD` bound is midnight *in the schedule's
6081        // tz* (#418 Phase 2). The UTC interpretation is exact and
6082        // host-independent; assert that precisely.
6083        use chrono::TimeZone;
6084        let utc = Active::parse_bound("2026-07-01", ScheduleTz::Utc).expect("utc");
6085        assert_eq!(
6086            utc,
6087            chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap()
6088        );
6089
6090        // The local interpretation must equal what chrono::Local
6091        // computes for the same wall-clock midnight — proves the tz
6092        // path is wired to the host zone (the magnitude vs UTC is
6093        // host-dependent, so we compare against Local directly rather
6094        // than hard-coding the JST offset, keeping CI green on UTC
6095        // runners).
6096        let local = Active::parse_bound("2026-07-01", ScheduleTz::Local).expect("local");
6097        let want = chrono::Local
6098            .with_ymd_and_hms(2026, 7, 1, 0, 0, 0)
6099            .single()
6100            .expect("local midnight is unambiguous")
6101            .with_timezone(&chrono::Utc);
6102        assert_eq!(local, want, "date bound resolved in host-local tz");
6103    }
6104
6105    #[test]
6106    fn active_empty_is_skipped_when_serialising() {
6107        let s = schedule_with(
6108            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6109            RunsOn::Backend,
6110        );
6111        let json = serde_json::to_value(&s).expect("serialise");
6112        assert!(
6113            json.get("active").is_none(),
6114            "empty active must not appear on the wire: {json}"
6115        );
6116    }
6117
6118    // ---- constraints.window (#418 Phase 3) ----
6119
6120    fn with_window(win: &str) -> Schedule {
6121        let mut s = schedule_with(
6122            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6123            RunsOn::Backend,
6124        );
6125        s.constraints.window = Some(win.into());
6126        s
6127    }
6128
6129    #[test]
6130    fn constraints_window_parses_and_round_trips() {
6131        let yaml = r#"
6132id: x
6133when:
6134  per_pc: { every: 6h }
6135job_id: y
6136target: { all: true }
6137constraints:
6138  window: "22:00-05:00"
6139"#;
6140        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6141        assert_eq!(s.constraints.window.as_deref(), Some("22:00-05:00"));
6142        let back: Schedule =
6143            serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
6144        assert_eq!(back.constraints.window.as_deref(), Some("22:00-05:00"));
6145    }
6146
6147    #[test]
6148    fn constraints_empty_is_skipped_when_serialising() {
6149        let s = schedule_with(
6150            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6151            RunsOn::Backend,
6152        );
6153        let json = serde_json::to_value(&s).expect("serialise");
6154        assert!(
6155            json.get("constraints").is_none(),
6156            "empty constraints must not appear on the wire: {json}"
6157        );
6158    }
6159
6160    #[test]
6161    fn window_no_constraint_always_allows() {
6162        let c = Constraints::default();
6163        assert!(c.allows(chrono::Utc::now(), ScheduleTz::Local));
6164    }
6165
6166    #[test]
6167    fn window_same_day_is_half_open() {
6168        use chrono::TimeZone;
6169        let s = with_window("09:00-17:00");
6170        let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
6171        let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
6172        assert!(!a(at(8, 59)), "before start");
6173        assert!(a(at(9, 0)), "at start (inclusive)");
6174        assert!(a(at(16, 59)), "inside");
6175        assert!(!a(at(17, 0)), "at end (exclusive)");
6176        assert!(!a(at(23, 0)), "after end");
6177    }
6178
6179    #[test]
6180    fn window_crossing_midnight() {
6181        use chrono::TimeZone;
6182        let s = with_window("22:00-05:00");
6183        let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
6184        let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
6185        assert!(a(at(22, 0)), "at start tonight");
6186        assert!(a(at(23, 30)), "late tonight");
6187        assert!(a(at(3, 0)), "early tomorrow");
6188        assert!(!a(at(5, 0)), "at end (exclusive)");
6189        assert!(!a(at(12, 0)), "midday outside");
6190        assert!(!a(at(21, 59)), "just before start");
6191    }
6192
6193    #[test]
6194    fn window_respects_tz() {
6195        // The same instant is inside the window under one tz and may
6196        // be outside under another. Compare UTC vs Local via the
6197        // host's own offset (kept CI-green on UTC runners like the
6198        // active tz test does).
6199        use chrono::TimeZone;
6200        let s = with_window("09:00-17:00");
6201        let noon_utc = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 12, 0, 0).unwrap();
6202        // Under UTC, 12:00 is inside 09:00-17:00.
6203        assert!(s.constraints.allows(noon_utc, ScheduleTz::Utc));
6204        // Under Local, the verdict tracks the host wall-clock time;
6205        // assert it matches a direct wall_time membership check.
6206        let local_t = noon_utc.with_timezone(&chrono::Local).time();
6207        let in_local = local_t >= chrono::NaiveTime::from_hms_opt(9, 0, 0).unwrap()
6208            && local_t < chrono::NaiveTime::from_hms_opt(17, 0, 0).unwrap();
6209        assert_eq!(s.constraints.allows(noon_utc, ScheduleTz::Local), in_local);
6210    }
6211
6212    #[test]
6213    fn validate_accepts_good_window() {
6214        for w in ["09:00-17:00", "22:00-05:00", "00:00-23:59"] {
6215            with_window(w)
6216                .validate()
6217                .unwrap_or_else(|e| panic!("'{w}' should validate: {e}"));
6218        }
6219    }
6220
6221    #[test]
6222    fn validate_rejects_bad_window() {
6223        for bad in ["9-5", "22:00", "22:00-22:00", "25:00-05:00", "09:00_17:00"] {
6224            let err = with_window(bad).validate().unwrap_err();
6225            assert!(
6226                err.contains("constraints.window"),
6227                "for '{bad}', got: {err}"
6228            );
6229        }
6230    }
6231
6232    // ---- constraints.skip_dates (#418 holiday exclusion) ----
6233
6234    fn with_skip_dates(dates: &[&str]) -> Schedule {
6235        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
6236        s.tz = ScheduleTz::Utc; // host-independent date assertions
6237        s.constraints.skip_dates = dates.iter().map(|d| (*d).to_string()).collect();
6238        s
6239    }
6240
6241    #[test]
6242    fn allows_blocks_listed_skip_date() {
6243        use chrono::TimeZone;
6244        let s = with_skip_dates(&["2026-06-10", "2026-12-25"]);
6245        // Any time on a listed date is blocked (whole day).
6246        let on = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap();
6247        assert!(!s.constraints.allows(on, ScheduleTz::Utc));
6248        let on_midnight = chrono::Utc.with_ymd_and_hms(2026, 12, 25, 0, 0, 0).unwrap();
6249        assert!(!s.constraints.allows(on_midnight, ScheduleTz::Utc));
6250        // A date not in the list fires normally.
6251        let off = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
6252        assert!(s.constraints.allows(off, ScheduleTz::Utc));
6253    }
6254
6255    #[test]
6256    fn allows_corrupt_skip_date_fails_closed() {
6257        use chrono::TimeZone;
6258        // A garbled entry (only reachable via hand-edited KV) blocks
6259        // rather than silently re-enabling fires — same posture as a
6260        // corrupt window.
6261        let s = with_skip_dates(&["not-a-date"]);
6262        let any = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
6263        assert!(!s.constraints.allows(any, ScheduleTz::Utc));
6264    }
6265
6266    #[test]
6267    fn validate_accepts_good_skip_dates() {
6268        with_skip_dates(&["2026-01-01", "2026-12-25", "2027-05-03"])
6269            .validate()
6270            .expect("well-formed skip dates should validate");
6271    }
6272
6273    #[test]
6274    fn validate_rejects_bad_skip_date() {
6275        for bad in ["2026-13-01", "01-01-2026", "nope", "2026/01/01"] {
6276            let err = with_skip_dates(&[bad]).validate().unwrap_err();
6277            assert!(
6278                err.contains("constraints.skip_dates"),
6279                "for '{bad}', got: {err}"
6280            );
6281        }
6282    }
6283
6284    #[test]
6285    fn preview_skips_holidays() {
6286        use chrono::TimeZone;
6287        // Daily 09:00 with two of the next five days marked as holidays
6288        // — preview drops exactly those, since it gates on `allows`.
6289        let mut s = cal_utc("09:00", &[]);
6290        s.constraints.skip_dates = vec!["2026-06-11".into(), "2026-06-13".into()];
6291        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
6292        let got = s.preview_fires(now, 4);
6293        let want: Vec<_> = [
6294            (2026, 6, 10),
6295            (2026, 6, 12), // skips 06-11
6296            (2026, 6, 14), // skips 06-13
6297            (2026, 6, 15),
6298        ]
6299        .iter()
6300        .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
6301        .collect();
6302        assert_eq!(got, want);
6303    }
6304
6305    // ---- constraints.max_concurrent (#418) ----
6306
6307    fn with_max_concurrent(max: u32, runs_on: RunsOn) -> Schedule {
6308        let mut s = schedule_with(
6309            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6310            runs_on,
6311        );
6312        s.constraints.max_concurrent = Some(max);
6313        s
6314    }
6315
6316    #[test]
6317    fn validate_accepts_backend_max_concurrent() {
6318        with_max_concurrent(5, RunsOn::Backend)
6319            .validate()
6320            .expect("backend max_concurrent should validate");
6321    }
6322
6323    #[test]
6324    fn validate_rejects_max_concurrent_on_agent() {
6325        // Decision E: a central running-instance cap needs a central
6326        // counter, which agents don't have.
6327        let err = with_max_concurrent(5, RunsOn::Agent)
6328            .validate()
6329            .unwrap_err();
6330        assert!(err.contains("constraints.max_concurrent"), "got: {err}");
6331        assert!(err.contains("runs_on: agent"), "got: {err}");
6332    }
6333
6334    #[test]
6335    fn validate_rejects_zero_max_concurrent() {
6336        let err = with_max_concurrent(0, RunsOn::Backend)
6337            .validate()
6338            .unwrap_err();
6339        assert!(err.contains("max_concurrent must be >= 1"), "got: {err}");
6340    }
6341
6342    #[test]
6343    fn max_concurrent_round_trips_and_skips_when_absent() {
6344        let s = with_max_concurrent(3, RunsOn::Backend);
6345        let json = serde_json::to_value(&s.constraints).expect("ser");
6346        assert_eq!(json.get("max_concurrent").and_then(|v| v.as_u64()), Some(3));
6347        // A schedule with no constraints omits the whole block.
6348        let bare = schedule_with(
6349            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6350            RunsOn::Backend,
6351        );
6352        assert!(bare.constraints.is_empty());
6353    }
6354
6355    #[test]
6356    fn window_fail_closed_on_corrupt_blob() {
6357        // A malformed window (only reachable via a hand-edited KV
6358        // blob — validate() rejects it at create) must BLOCK, not
6359        // silently allow fires during a change-freeze (gemini #452).
6360        let s = with_window("22:00_05:00");
6361        assert!(
6362            !s.constraints.allows(chrono::Utc::now(), ScheduleTz::Utc),
6363            "corrupt window fails closed"
6364        );
6365        // …and the scheduler can surface why it's stuck.
6366        assert!(
6367            s.bad_window().is_some(),
6368            "bad_window reports the parse error"
6369        );
6370        assert!(with_window("22:00-05:00").bad_window().is_none());
6371    }
6372
6373    #[test]
6374    fn calendar_outside_window_is_flagged() {
6375        // at 09:00 can never fall in 22:00-05:00 → never fires.
6376        let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
6377        s.constraints.window = Some("22:00-05:00".into());
6378        assert!(s.calendar_outside_window(), "09:00 is not in 22:00-05:00");
6379
6380        // at 23:00 IS inside the overnight window → fine.
6381        let mut s = schedule_with(calendar("23:00", &[]), RunsOn::Backend);
6382        s.constraints.window = Some("22:00-05:00".into());
6383        assert!(!s.calendar_outside_window(), "23:00 is in 22:00-05:00");
6384
6385        // reconcile shapes are never flagged (they poll every minute).
6386        let mut s = schedule_with(
6387            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6388            RunsOn::Backend,
6389        );
6390        s.constraints.window = Some("22:00-05:00".into());
6391        assert!(!s.calendar_outside_window(), "reconcile is unaffected");
6392
6393        // no window → never flagged.
6394        let s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
6395        assert!(!s.calendar_outside_window());
6396    }
6397
6398    // ---- on_failure.retry (#418 Phase 4) ----
6399
6400    fn with_retry(max: u32, backoff: &str) -> Schedule {
6401        let mut s = schedule_with(
6402            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6403            RunsOn::Backend,
6404        );
6405        s.on_failure.retry = Some(Retry {
6406            max,
6407            backoff: backoff.into(),
6408        });
6409        s
6410    }
6411
6412    #[test]
6413    fn on_failure_parses_and_round_trips() {
6414        let yaml = r#"
6415id: x
6416when:
6417  per_pc: { every: 6h }
6418job_id: y
6419target: { all: true }
6420on_failure:
6421  retry: { max: 3, backoff: 10m }
6422"#;
6423        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6424        let r = s.on_failure.retry.as_ref().expect("retry present");
6425        assert_eq!(r.max, 3);
6426        assert_eq!(r.backoff, "10m");
6427        let back: Schedule =
6428            serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
6429        assert_eq!(back.on_failure, s.on_failure);
6430    }
6431
6432    #[test]
6433    fn on_failure_empty_is_skipped_when_serialising() {
6434        let s = schedule_with(
6435            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6436            RunsOn::Backend,
6437        );
6438        let json = serde_json::to_value(&s).expect("serialise");
6439        assert!(
6440            json.get("on_failure").is_none(),
6441            "empty on_failure must not appear on the wire: {json}"
6442        );
6443    }
6444
6445    #[test]
6446    fn validate_accepts_good_retry() {
6447        for (max, backoff) in [(1, "30s"), (3, "10m"), (10, "1h")] {
6448            with_retry(max, backoff)
6449                .validate()
6450                .unwrap_or_else(|e| panic!("retry {{max:{max}, backoff:{backoff}}}: {e}"));
6451        }
6452    }
6453
6454    #[test]
6455    fn validate_rejects_bad_backoff() {
6456        let err = with_retry(3, "soon").validate().unwrap_err();
6457        assert!(err.contains("on_failure.retry.backoff"), "got: {err}");
6458    }
6459
6460    #[test]
6461    fn validate_rejects_sub_second_backoff() {
6462        // "500ms" parses as humantime but lowers to 0s on the wire —
6463        // reject it so the operator doesn't get a silent no-wait
6464        // (coderabbit #466).
6465        for bad in ["500ms", "0s", "999ms"] {
6466            let err = with_retry(3, bad).validate().unwrap_err();
6467            assert!(
6468                err.contains("on_failure.retry.backoff must be >= 1s"),
6469                "for '{bad}', got: {err}"
6470            );
6471        }
6472    }
6473
6474    #[test]
6475    fn validate_rejects_out_of_range_max() {
6476        for bad in [0u32, 11, 1000] {
6477            let err = with_retry(bad, "10m").validate().unwrap_err();
6478            assert!(
6479                err.contains("on_failure.retry.max"),
6480                "for max={bad}, got: {err}"
6481            );
6482        }
6483    }
6484
6485    #[test]
6486    fn lowered_retry_reduces_backoff_to_seconds() {
6487        let s = with_retry(3, "10m");
6488        let spec = s.on_failure.lowered_retry().expect("a retry policy");
6489        assert_eq!(spec.max, 3);
6490        assert_eq!(spec.backoff_secs, 600);
6491    }
6492
6493    #[test]
6494    fn lowered_retry_is_none_without_policy() {
6495        let s = schedule_with(
6496            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6497            RunsOn::Backend,
6498        );
6499        assert!(s.on_failure.lowered_retry().is_none());
6500    }
6501
6502    // ---- global change-freeze (#418 Phase 5) ----
6503
6504    #[test]
6505    fn freeze_empty_window_is_always_active() {
6506        // The big-red-button shape: no bounds = frozen until cleared.
6507        let f = Freeze::default();
6508        assert!(f.is_active(chrono::Utc::now()));
6509    }
6510
6511    #[test]
6512    fn freeze_window_is_half_open() {
6513        use chrono::TimeZone;
6514        let f = Freeze {
6515            from: Some("2026-12-20T00:00:00+00:00".into()),
6516            until: Some("2027-01-05T00:00:00+00:00".into()),
6517            reason: Some("year-end".into()),
6518            tz: ScheduleTz::Utc,
6519        };
6520        let at = |y, mo, d| chrono::Utc.with_ymd_and_hms(y, mo, d, 0, 0, 0).unwrap();
6521        assert!(!f.is_active(at(2026, 12, 19)), "before from = not frozen");
6522        assert!(f.is_active(at(2026, 12, 20)), "from is inclusive");
6523        assert!(f.is_active(at(2026, 12, 31)), "inside window");
6524        assert!(!f.is_active(at(2027, 1, 5)), "until is exclusive");
6525        assert!(!f.is_active(at(2027, 1, 6)), "after until = not frozen");
6526    }
6527
6528    #[test]
6529    fn freeze_fails_closed_on_corrupt_bound() {
6530        // A freeze is a safety switch: an unparseable bound (only
6531        // reachable via a hand-edited KV blob) must read as FROZEN, not
6532        // "fire normally" (coderabbit #472) — the opposite of `active`,
6533        // which fail-opens.
6534        let f = Freeze {
6535            from: Some("not-a-date".into()),
6536            until: None,
6537            reason: None,
6538            tz: ScheduleTz::Utc,
6539        };
6540        assert!(f.is_active(chrono::Utc::now()), "corrupt bound → frozen");
6541    }
6542
6543    #[test]
6544    fn freeze_validate_accepts_good_bounds() {
6545        Freeze {
6546            from: Some("2026-12-20".into()),
6547            until: Some("2027-01-05T12:00:00+09:00".into()),
6548            reason: None,
6549            tz: ScheduleTz::Local,
6550        }
6551        .validate()
6552        .expect("date + rfc3339 bounds should validate");
6553        // Empty (indefinite) freeze is valid.
6554        Freeze::default().validate().expect("empty freeze is valid");
6555    }
6556
6557    #[test]
6558    fn freeze_validate_rejects_bad_bound_and_inverted_window() {
6559        let err = Freeze {
6560            from: Some("never".into()),
6561            ..Default::default()
6562        }
6563        .validate()
6564        .unwrap_err();
6565        assert!(err.contains("freeze:"), "got: {err}");
6566
6567        let inverted = Freeze {
6568            from: Some("2027-01-05".into()),
6569            until: Some("2026-12-20".into()),
6570            ..Default::default()
6571        }
6572        .validate()
6573        .unwrap_err();
6574        assert!(inverted.contains("freeze.from"), "got: {inverted}");
6575    }
6576
6577    #[test]
6578    fn freeze_round_trips_and_skips_empty_fields() {
6579        let f = Freeze {
6580            from: None,
6581            until: Some("2027-01-05".into()),
6582            reason: Some("INC-1234".into()),
6583            tz: ScheduleTz::Utc,
6584        };
6585        let json = serde_json::to_value(&f).expect("serialise");
6586        assert!(json.get("from").is_none(), "empty from omitted: {json}");
6587        let back: Freeze = serde_json::from_value(json).expect("round-trip");
6588        assert_eq!(back, f);
6589    }
6590
6591    #[test]
6592    fn shipped_schedule_configs_parse_and_validate() {
6593        // Every YAML under configs/schedules/ must parse with the
6594        // current Schedule serde AND pass validate() — keeps the
6595        // shipped examples from drifting out of sync with the model
6596        // (#418 removed back-compat, so drift = broken at create).
6597        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../configs/schedules");
6598        let mut seen = 0;
6599        for entry in std::fs::read_dir(&dir).expect("read configs/schedules") {
6600            let path = entry.expect("dir entry").path();
6601            if path.extension().and_then(|e| e.to_str()) != Some("yaml") {
6602                continue;
6603            }
6604            let body = std::fs::read_to_string(&path).expect("read yaml");
6605            let s: Schedule = serde_yaml::from_str(&body)
6606                .unwrap_or_else(|e| panic!("{} failed to parse: {e}", path.display()));
6607            s.validate()
6608                .unwrap_or_else(|e| panic!("{} failed validate(): {e}", path.display()));
6609            seen += 1;
6610        }
6611        assert!(seen > 0, "no schedule YAMLs found in {}", dir.display());
6612    }
6613
6614    // ---- pre-existing enum wire formats (unchanged by #418) ----
6615
6616    #[test]
6617    fn exec_mode_serialises_snake_case() {
6618        for (mode, expected) in [
6619            (ExecMode::EveryTick, "every_tick"),
6620            (ExecMode::OncePerPc, "once_per_pc"),
6621            (ExecMode::OncePerTarget, "once_per_target"),
6622        ] {
6623            let s = serde_json::to_value(mode).expect("serialise");
6624            assert_eq!(s, serde_json::Value::String(expected.into()));
6625            let back: ExecMode = serde_json::from_value(serde_json::Value::String(expected.into()))
6626                .expect("deserialise");
6627            assert_eq!(back, mode, "round-trip for {expected}");
6628        }
6629    }
6630
6631    #[test]
6632    fn schedule_runs_on_defaults_to_backend() {
6633        let yaml = r#"
6634id: x
6635when:
6636  per_pc: once
6637job_id: y
6638target: { all: true }
6639"#;
6640        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6641        assert_eq!(s.runs_on, RunsOn::Backend);
6642    }
6643
6644    #[test]
6645    fn schedule_runs_on_agent_parses() {
6646        let yaml = r#"
6647id: offline-inv
6648when:
6649  per_pc: { every: 1h }
6650job_id: inventory-hw
6651target: { all: true }
6652runs_on: agent
6653"#;
6654        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6655        assert_eq!(s.runs_on, RunsOn::Agent);
6656        assert_eq!(s.lowered().mode, ExecMode::OncePerPc);
6657    }
6658
6659    #[test]
6660    fn runs_on_serialises_snake_case() {
6661        for (mode, expected) in [(RunsOn::Backend, "backend"), (RunsOn::Agent, "agent")] {
6662            let s = serde_json::to_value(mode).expect("serialise");
6663            assert_eq!(s, serde_json::Value::String(expected.into()));
6664            let back: RunsOn = serde_json::from_value(serde_json::Value::String(expected.into()))
6665                .expect("deserialise");
6666            assert_eq!(back, mode);
6667        }
6668    }
6669
6670    #[test]
6671    fn execute_shell_into_wire_shell() {
6672        assert_eq!(Shell::from(ExecuteShell::Powershell), Shell::Powershell);
6673        assert_eq!(Shell::from(ExecuteShell::Cmd), Shell::Cmd);
6674    }
6675
6676    #[test]
6677    fn manifest_staleness_defaults_to_cached() {
6678        let yaml = r#"
6679id: x
6680version: 1.0.0
6681execute:
6682  shell: powershell
6683  script: "echo"
6684  timeout: 1s
6685"#;
6686        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
6687        assert_eq!(m.staleness, Staleness::Cached);
6688    }
6689
6690    #[test]
6691    fn manifest_strict_staleness_parses() {
6692        let yaml = r#"
6693id: urgent-patch
6694version: 2.5.1
6695execute:
6696  shell: powershell
6697  script: Install-Hotfix
6698  timeout: 5m
6699staleness:
6700  mode: strict
6701  max_cache_age: 0s
6702"#;
6703        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
6704        match m.staleness {
6705            Staleness::Strict { max_cache_age } => assert_eq!(max_cache_age, "0s"),
6706            other => panic!("expected strict, got {other:?}"),
6707        }
6708    }
6709
6710    #[test]
6711    fn manifest_unchecked_staleness_parses() {
6712        let yaml = r#"
6713id: legacy
6714version: 0.1.0
6715execute:
6716  shell: cmd
6717  script: "echo"
6718  timeout: 1s
6719staleness:
6720  mode: unchecked
6721"#;
6722        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
6723        assert_eq!(m.staleness, Staleness::Unchecked);
6724    }
6725
6726    #[test]
6727    fn missing_required_field_errors() {
6728        // `id` missing.
6729        let yaml = r#"
6730version: 1.0.0
6731target: { all: true }
6732execute:
6733  shell: powershell
6734  script: "echo"
6735  timeout: 1s
6736"#;
6737        let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
6738        assert!(r.is_err(), "expected error, got {:?}", r);
6739    }
6740
6741    #[test]
6742    fn display_field_table_kind_round_trips_with_nested_columns() {
6743        // #39: `type: table` + `columns:` on a DisplayField gets
6744        // round-tripped through serde so the SPA receives the
6745        // nested schema verbatim. Nested columns themselves are
6746        // DisplayFields so they can carry `type: bytes` /
6747        // `type: number` for cell formatting.
6748        let yaml = r#"
6749id: inv-hw
6750version: 1.0.0
6751execute:
6752  shell: powershell
6753  script: "echo"
6754  timeout: 60s
6755inventory:
6756  display:
6757    - field: hostname
6758      label: Hostname
6759    - field: disks
6760      label: Disks
6761      type: table
6762      columns:
6763        - field: device_id
6764          label: Drive
6765        - field: size_bytes
6766          label: Size
6767          type: bytes
6768        - field: free_bytes
6769          label: Free
6770          type: bytes
6771        - field: file_system
6772          label: FS
6773"#;
6774        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
6775        let inv = m.inventory.as_ref().expect("inventory hint");
6776        let disks = inv
6777            .display
6778            .iter()
6779            .find(|d| d.field == "disks")
6780            .expect("disks display row");
6781        assert_eq!(disks.kind.as_deref(), Some("table"));
6782        let cols = disks.columns.as_ref().expect("table needs columns");
6783        assert_eq!(cols.len(), 4);
6784        assert_eq!(cols[1].field, "size_bytes");
6785        assert_eq!(cols[1].kind.as_deref(), Some("bytes"));
6786    }
6787
6788    #[test]
6789    fn display_field_scalar_kind_keeps_columns_none() {
6790        // Defensive: when type is a scalar (`bytes` / `number` /
6791        // `timestamp`) the `columns` field stays None — the SPA
6792        // uses its presence as the "render nested table" signal,
6793        // so it must not leak in via serde defaults.
6794        let yaml = r#"
6795id: x
6796version: 1.0.0
6797execute:
6798  shell: powershell
6799  script: "echo"
6800  timeout: 5s
6801inventory:
6802  display:
6803    - { field: ram_bytes, label: RAM, type: bytes }
6804"#;
6805        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
6806        let inv = m.inventory.as_ref().unwrap();
6807        assert!(inv.display[0].columns.is_none());
6808    }
6809
6810    // ---- checked-in JSON Schema freshness (docs/schemas/) ----
6811
6812    /// The JSON Schemas under `docs/schemas/` must match what
6813    /// `schema_for!` produces today — a Cargo.lock-style freshness guard
6814    /// so a `Schedule` / `Manifest` field change can't silently drift
6815    /// the operator-facing schema. The SPA editor, the backend
6816    /// `/api/schemas/*` endpoints, and these files all read the same
6817    /// derived shape; this test fails CI if the checked-in copy lags.
6818    /// Regenerate with:
6819    ///   `UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current`
6820    #[test]
6821    fn schema_files_are_current() {
6822        assert_schema_file("schedule.schema.json", &schemars::schema_for!(Schedule));
6823        assert_schema_file("job.schema.json", &schemars::schema_for!(Manifest));
6824        assert_schema_file("view.schema.json", &schemars::schema_for!(View));
6825    }
6826
6827    fn assert_schema_file(name: &str, schema: &schemars::Schema) {
6828        let generated = serde_json::to_string_pretty(schema).expect("serialize schema") + "\n";
6829        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
6830            .join("../../docs/schemas")
6831            .join(name);
6832        if std::env::var_os("UPDATE_SCHEMAS").is_some() {
6833            std::fs::create_dir_all(path.parent().unwrap()).expect("mkdir docs/schemas");
6834            std::fs::write(&path, &generated).unwrap_or_else(|e| panic!("write {path:?}: {e}"));
6835            return;
6836        }
6837        // Normalize CRLF→LF before comparing: `.gitattributes` already
6838        // pins these files to `eol=lf`, but a stray CRLF working-tree
6839        // copy (autocrlf, a tool rewrite) shouldn't turn a *content*-
6840        // freshness check into a confusing line-ending failure — that's
6841        // .gitattributes' job, not this test's (gemini #588).
6842        let on_disk = std::fs::read_to_string(&path)
6843            .unwrap_or_else(|e| {
6844                panic!(
6845                    "read {path:?}: {e}\n\
6846                     generate it with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
6847                )
6848            })
6849            .replace("\r\n", "\n");
6850        assert_eq!(
6851            on_disk, generated,
6852            "{name} is stale — a Schedule/Manifest schema change isn't reflected in docs/schemas/. \
6853             Refresh with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
6854        );
6855    }
6856}
6857
6858/// Periodic schedule (spec §2.4.3). v0.18.0 carries the fanout plan
6859/// (target + optional rollout + optional jitter) inline; the
6860/// referenced job (`job_id` → [`BUCKET_JOBS`]) supplies only the
6861/// script body. Two schedules of the same job can target different
6862/// groups on different cadences without copying the manifest.
6863///
6864/// #418 Phase 1: the cadence is the single [`When`] field. The old
6865/// `cron` × `mode` × `cooldown` × `auto_disable_when_done` quartet
6866/// is gone (no back-compat — pre-Phase-1 KV blobs fail to parse and
6867/// are warn-skipped; re-`schedule create` to upgrade them). The
6868/// engine underneath is unchanged: [`Schedule::lowered`] maps `when`
6869/// onto the same (cron, ExecMode, cooldown) trio the scheduler and
6870/// `decide_fire` always ran on.
6871#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
6872pub struct Schedule {
6873    pub id: String,
6874    /// When to fire — a reconcile cadence (`per_pc` / `per_target`)
6875    /// or a calendar time trigger (`at` / `days`). See [`When`].
6876    ///
6877    /// `singleton_map`: serde_yaml 0.9 renders externally-tagged
6878    /// enums as `!per_pc` YAML tags by default; this keeps the
6879    /// operator-facing map shape (`when: { per_pc: once }`). JSON
6880    /// output is identical either way, and the schemars schema
6881    /// (external tagging = oneOf of single-key objects) already
6882    /// matches the singleton-map wire shape.
6883    #[serde(with = "serde_yaml::with::singleton_map")]
6884    #[schemars(with = "When")]
6885    pub when: When,
6886    /// Key into [`crate::kv::BUCKET_JOBS`]. Must equal a registered
6887    /// Manifest's `id`.
6888    pub job_id: String,
6889    /// Who + how-to-phase + when-to-stagger. The Manifest doesn't
6890    /// carry these any more — same job + different fanout = different
6891    /// schedule.
6892    #[serde(flatten)]
6893    pub plan: FanoutPlan,
6894    /// Optional validity window. Outside `[from, until)` the
6895    /// schedule is dormant — still registered, still visible, but
6896    /// every tick is skipped (deleted ≠ dormant: a campaign that
6897    /// ended stays inspectable and can be re-armed by editing the
6898    /// window). Checked at tick time on both the backend scheduler
6899    /// and the agent's local scheduler.
6900    #[serde(default, skip_serializing_if = "Active::is_empty")]
6901    pub active: Active,
6902    /// #418 operational constraints gating *when within an active
6903    /// period* a fire may happen: a maintenance `window`, a fleet
6904    /// `max_concurrent` cap, and `skip_dates` (holiday exclusion). The
6905    /// wall-clock ones are evaluated in the schedule's `tz`; future
6906    /// `require` (env gates) lands in the same namespace. Checked at
6907    /// tick time on both schedulers (and surfaced by `preview`).
6908    #[serde(default, skip_serializing_if = "Constraints::is_empty")]
6909    pub constraints: Constraints,
6910    /// #418 Phase 4: what to do after a fire's script comes back
6911    /// failed. Currently just `retry` (fixed-backoff in-process
6912    /// re-run); future `notify` / `disable` join the same namespace.
6913    /// Applied fire-side in `handle_command` (the retry policy is
6914    /// lowered onto every Command this schedule produces), so it
6915    /// covers both `runs_on` locations.
6916    #[serde(default, skip_serializing_if = "OnFailure::is_empty")]
6917    pub on_failure: OnFailure,
6918    /// #418 Phase 2: the timezone this schedule's wall-clock fields
6919    /// are evaluated in — both the calendar `at` firing time AND the
6920    /// `active.{from,until}` window bounds. `local` (default) = the
6921    /// running host's TZ (the agent's for `runs_on: agent`, the
6922    /// backend server's otherwise); `utc` for TZ-independent
6923    /// schedules. Reconcile shapes (`per_pc`/`per_target`) ignore it
6924    /// for firing (poll cron runs every minute regardless) but still
6925    /// honor it for the `active` window.
6926    #[serde(default)]
6927    pub tz: ScheduleTz,
6928    /// v0.22: optional humantime window after a cron tick during
6929    /// which the Command is still considered "live". The scheduler
6930    /// computes `tick_at + starting_deadline` and stamps it onto
6931    /// each Command as `deadline_at`; agents skip Commands they
6932    /// receive after that absolute time. `None` (default) = no
6933    /// deadline, meaning a Command queued in the broker / stream
6934    /// during agent downtime runs whenever the agent reconnects —
6935    /// good for kitting / inventory / cleanup. Set this for
6936    /// time-of-day notifications, lunch reminders, etc., where
6937    /// "fire 3 hours late" would be wrong.
6938    #[serde(default, skip_serializing_if = "Option::is_none")]
6939    pub starting_deadline: Option<String>,
6940    /// v0.23: where does the cron tick happen? `Backend` (default,
6941    /// historical) = backend's scheduler fires Commands via NATS;
6942    /// agents passively receive. `Agent` = each targeted agent runs
6943    /// its own internal cron and fires locally, so the schedule
6944    /// keeps ticking even when the broker is unreachable (laptop on
6945    /// the train, broker maintenance window, full WAN outage). The
6946    /// two locations are mutually exclusive — when `Agent`, the
6947    /// backend scheduler stays out and just keeps the definition in
6948    /// KV for agents to read.
6949    #[serde(default)]
6950    pub runs_on: RunsOn,
6951    #[serde(default = "default_true")]
6952    pub enabled: bool,
6953    /// Free-form operator taxonomy for the Schedules page — the
6954    /// schedule-side mirror of `Manifest.tags` (added in #640; a plain
6955    /// code ref rather than an intra-doc link, since that field isn't
6956    /// on this branch until #640 merges). Purely a SPA-side
6957    /// organisational aid (search / filter chips alongside the
6958    /// id-prefix grouping); the scheduler never reads it, so any
6959    /// string is allowed and it carries no firing semantics. A
6960    /// schedule's own tags are independent of its job's: the same job
6961    /// may back a `weekly` maintenance schedule and a `canary` rollout
6962    /// schedule. Empty by default and `skip_serializing_if`-elided per
6963    /// the #492 gradual-upgrade wire rule.
6964    #[serde(default, skip_serializing_if = "Vec::is_empty")]
6965    pub tags: Vec<String>,
6966    /// GitOps provenance (#695) — see [`RepoOrigin`]. Stamped by
6967    /// `kanade schedule create` when the source YAML lives inside a Git
6968    /// work tree, so the SPA renders the schedule read-only and points
6969    /// edits back at the repo (SPEC design principle #3: 設定駆動 YAML +
6970    /// Git), parity with a job's [`Manifest::origin`]. `None` for
6971    /// SPA-born schedules and ones applied from outside any repo. Purely
6972    /// informational — the scheduler never reads it. New field ⇒ #492
6973    /// wire rule (`default` + `skip_serializing_if`).
6974    #[serde(default, skip_serializing_if = "Option::is_none")]
6975    pub origin: Option<RepoOrigin>,
6976}
6977
6978impl Schedule {
6979    /// Every valid top-level key on a Schedule YAML/JSON document —
6980    /// this struct's own fields PLUS the fields of the
6981    /// `#[serde(flatten)] plan: FanoutPlan`. The strict create
6982    /// boundary needs this because serde's flatten buffering hides
6983    /// unknown top-level keys from `serde_ignored`, so a typo like
6984    /// `jiter:` or `enabledd:` would otherwise be silently dropped
6985    /// (#924). Kept in sync with the field list by
6986    /// `schedule_top_level_keys_cover_serialized_fields`.
6987    pub const TOP_LEVEL_KEYS: &'static [&'static str] = &[
6988        // Schedule's own fields:
6989        "id",
6990        "when",
6991        "job_id",
6992        "active",
6993        "constraints",
6994        "on_failure",
6995        "tz",
6996        "starting_deadline",
6997        "runs_on",
6998        "enabled",
6999        "tags",
7000        "origin",
7001        // flattened FanoutPlan:
7002        "target",
7003        "rollout",
7004        "jitter",
7005        "deadline_at",
7006    ];
7007}
7008
7009impl crate::strict::StrictSchema for Schedule {
7010    fn strict_top_level_keys() -> Option<&'static [&'static str]> {
7011        Some(Self::TOP_LEVEL_KEYS)
7012    }
7013}
7014
7015/// Manifest has no `#[serde(flatten)]` field, so `serde_ignored`
7016/// already catches every top-level typo — the default (`None`) is
7017/// correct.
7018impl crate::strict::StrictSchema for Manifest {}
7019
7020/// View likewise has no flattened field.
7021impl crate::strict::StrictSchema for View {}
7022
7023/// v0.23 — where the cron tick fires from.
7024#[derive(
7025    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
7026)]
7027#[serde(rename_all = "snake_case")]
7028pub enum RunsOn {
7029    /// Backend's central scheduler ticks and publishes Commands to
7030    /// NATS. Historical default, what every pre-v0.23 schedule
7031    /// uses. Agent offline ⇒ Command queued in STREAM_EXEC; agent
7032    /// reconnects ⇒ catch-up via [`command_replay`](crate)
7033    /// (see kanade-agent's command_replay module).
7034    #[default]
7035    Backend,
7036    /// Each targeted agent runs the cron tick locally. Survives
7037    /// broker / WAN outages. Best for laptops / mobile devices that
7038    /// roam off the corporate network. Agent must be online for the
7039    /// initial schedule + job-catalog pull, but once cached the
7040    /// agent fires the script standalone.
7041    Agent,
7042}
7043
7044/// Per-pc/per-target dedup semantics for a [`Schedule`] (v0.19).
7045#[derive(
7046    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
7047)]
7048#[serde(rename_all = "snake_case")]
7049pub enum ExecMode {
7050    /// Fire on every cron tick at the whole target. Historical
7051    /// (pre-v0.19) behavior; no dedup.
7052    #[default]
7053    EveryTick,
7054    /// Fire at each pc until that pc succeeds; then skip it until
7055    /// the optional cooldown elapses (or forever if no cooldown).
7056    /// Use for kitting / first-boot / per-pc compliance checks.
7057    OncePerPc,
7058    /// Fire at the whole target until **any** pc succeeds; then
7059    /// skip the whole target until the optional cooldown elapses
7060    /// (or forever if no cooldown). Use for "one delegate is
7061    /// enough" tasks like license check-in.
7062    OncePerTarget,
7063    /// #418 OS-native event trigger (`when: { on: [...] }`). There is
7064    /// no cron — the agent fires it from an OS event source (boot /
7065    /// session-change), not a tick — so the scheduler skips
7066    /// `tokio-cron` registration for it. Each event occurrence fires
7067    /// once, gated by the standard freeze / active / window /
7068    /// skip_dates checks.
7069    Event,
7070}
7071
7072/// #418 Phase 1 — the single "when does this fire" axis.
7073///
7074/// Replaces the old `cron` + `mode` + `cooldown` trio whose
7075/// interactions were implicit (cron doubled as both a real
7076/// time-of-day trigger and a reconcile poll period; contradictory
7077/// combinations silently no-opped). Two shapes:
7078///
7079/// * **reconcile** (`per_pc` / `per_target`) — desired-state: "each
7080///   pc (or one delegate) should have run this within `every`".
7081///   The poll period is system-generated ([`POLL_CRON`], every
7082///   minute) and no longer the operator's concern.
7083/// * **calendar** (`{ at, days }`) — a wall-clock time trigger
7084///   (#418 Phase 2, replacing the old raw-cron escape hatch). Fires
7085///   the whole target at the given time, no dedup. `at: "09:00"` +
7086///   `days` repeats; `at: "2026-06-10 09:00"` (a date+time) fires
7087///   exactly once. Evaluated in the schedule's top-level `tz`.
7088#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7089#[serde(rename_all = "snake_case")]
7090pub enum When {
7091    /// Fire at each targeted pc: `once` (kitting — succeed once,
7092    /// skip forever, forever catching brand-new / re-imaged pcs)
7093    /// or `{ every: <humantime> }` (patrol — re-arm per pc after
7094    /// the interval).
7095    PerPc(PerPolicy),
7096    /// Fire until **any** one pc of the target succeeds, then skip
7097    /// the whole target (`once`) or re-arm after `every`. Needs
7098    /// fleet-wide completion data, so it is backend-only —
7099    /// `runs_on: agent` + `per_target` is rejected by
7100    /// [`Schedule::validate`].
7101    PerTarget(PerPolicy),
7102    /// Calendar time trigger: `{ at: "09:00", days: [mon-fri] }`
7103    /// (repeating) or `{ at: "2026-06-10 09:00" }` (one-shot). Fires
7104    /// the whole target at that wall-clock time in the schedule's
7105    /// `tz` — no dedup, no cooldown.
7106    Calendar(CalendarSpec),
7107    /// #418 OS-native event trigger: `when: { on: [startup, logon] }`.
7108    /// Fires when the agent observes the listed OS event(s) rather than
7109    /// on a clock — there is no cron. `runs_on: agent` only (the agent
7110    /// owns the event source); [`Schedule::validate`] rejects it on
7111    /// `backend` and rejects an empty list. Each event occurrence fires
7112    /// once, gated by the same freeze / active / `constraints.window` /
7113    /// `skip_dates` checks as the cron path. `startup` fires once per OS
7114    /// boot (deduped via the host boot time); a `starting_deadline`, if
7115    /// set, limits it to "agent came up within that long after boot".
7116    On(Vec<OnTrigger>),
7117}
7118
7119/// An OS event the agent can fire a schedule on (#418 `when: { on }`).
7120#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash)]
7121#[serde(rename_all = "snake_case")]
7122pub enum OnTrigger {
7123    /// Once per OS boot (the agent's first run for that boot). Catches
7124    /// freshly-imaged / reinstalled hosts at their next startup.
7125    Startup,
7126    /// On an interactive-session user logon — console, RDP, or
7127    /// auto-logon (Windows `WTS_SESSION_LOGON`). Does not fire for
7128    /// service / network / batch logons (no interactive session).
7129    Logon,
7130    /// When the workstation is locked (Win+L / idle lock; Windows
7131    /// `WTS_SESSION_LOCK`). Use for step-away compliance / cleanup.
7132    Lock,
7133    /// When the workstation is unlocked — the user returns to a locked
7134    /// session (Windows `WTS_SESSION_UNLOCK`). Use to re-check
7135    /// compliance / refresh state when work resumes.
7136    Unlock,
7137    /// When the host's network changes — IP address table change on
7138    /// connect / disconnect / DHCP renew / VPN / Wi-Fi roam (Windows
7139    /// `NotifyAddrChange`). Debounced agent-side (a burst of changes
7140    /// from one transition fires once after the network settles), so
7141    /// use it for "re-check connectivity / re-register on network move"
7142    /// rather than expecting one fire per raw adapter event.
7143    ///
7144    /// IPv4 only: `NotifyAddrChange` watches the IPv4 address table, so a
7145    /// transition that touches only IPv6 addresses won't fire. In practice
7146    /// dual-stack networks change both tables together, but a pure-IPv6
7147    /// move (e.g. an IPv6-only Wi-Fi roam) is not detected.
7148    NetworkChange,
7149}
7150
7151/// Calendar time trigger (#418 Phase 2). `at` is either a time of
7152/// day (`"HH:MM"`, repeating — combine with `days`) or a full
7153/// date+time (`"YYYY-MM-DD HH:MM"`, a one-shot that fires once and
7154/// never again). Evaluated in the schedule's top-level `tz`.
7155#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7156pub struct CalendarSpec {
7157    /// `"HH:MM"` (24h) for a repeating trigger, or
7158    /// `"YYYY-MM-DD HH:MM"` (hyphen / slash / `T` separators all
7159    /// accepted) for a one-shot. Parsed lazily —
7160    /// [`Schedule::validate`] rejects garbage at create time.
7161    pub at: String,
7162    /// Day-of-week filter for a time-of-day `at`: `["mon-fri"]`,
7163    /// `["mon","wed","fri"]`, … (passed verbatim to the cron DOW
7164    /// field, so ranges and names both work). An **nth-weekday**
7165    /// `["tue#2"]` fires only on the 2nd Tuesday of each month
7166    /// ("Patch Tuesday"); the ordinal is `1..5`. A **last-weekday**
7167    /// `["friL"]` fires only on the last Friday of each month (handy
7168    /// for monthly maintenance). Empty = every day. Must be empty
7169    /// when `at` carries a date (the date already pins the day).
7170    #[serde(default, skip_serializing_if = "Vec::is_empty")]
7171    pub days: Vec<String>,
7172}
7173
7174/// Parsed `CalendarSpec.at`: the wall-clock minute/hour, plus the
7175/// date for a one-shot (`None` = repeating time-of-day).
7176struct ParsedAt {
7177    minute: u32,
7178    hour: u32,
7179    date: Option<chrono::NaiveDate>,
7180}
7181
7182impl CalendarSpec {
7183    /// Parse `at`: a date+time (`YYYY-MM-DD HH:MM`, hyphen / slash /
7184    /// `T` separators) is a one-shot; a bare `HH:MM` is repeating.
7185    fn parse_at(&self) -> Result<ParsedAt, String> {
7186        use chrono::Timelike;
7187        let s = self.at.trim();
7188        for fmt in ["%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y/%m/%d %H:%M"] {
7189            if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, fmt) {
7190                return Ok(ParsedAt {
7191                    minute: dt.minute(),
7192                    hour: dt.hour(),
7193                    date: Some(dt.date()),
7194                });
7195            }
7196        }
7197        if let Ok(t) = chrono::NaiveTime::parse_from_str(s, "%H:%M") {
7198            return Ok(ParsedAt {
7199                minute: t.minute(),
7200                hour: t.hour(),
7201                date: None,
7202            });
7203        }
7204        Err(format!(
7205            "when.at: unparseable '{}' (want HH:MM or YYYY-MM-DD HH:MM)",
7206            self.at
7207        ))
7208    }
7209
7210    /// Pre-flight check on the `days` tokens so a bad day name gives
7211    /// a `when.days:`-scoped error instead of croner's confusing
7212    /// "when.at lowered to invalid cron" (claude #432 review). Each
7213    /// token is a day name (`mon`..`sun`), a numeric DOW (`0`..`7`),
7214    /// `*`, a `-` range of those, an **nth-weekday** like `tue#2`
7215    /// (2nd Tuesday of the month — "Patch Tuesday"), or a
7216    /// **last-weekday** like `friL` (last Friday of the month).
7217    fn validate_days(&self) -> Result<(), String> {
7218        const NAMES: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
7219        let is_day = |p: &str| NAMES.contains(&p) || p.parse::<u8>().is_ok_and(|n| n <= 7);
7220        for tok in &self.days {
7221            // Report the whole token on a malformed range like `mon-`
7222            // (which would otherwise split to a cryptic empty part —
7223            // claude #432 follow-up).
7224            let invalid = |reason: &str| {
7225                Err(format!(
7226                    "when.days: invalid day token '{tok}' ({reason}; \
7227                     want mon..sun, 0-7, a range like mon-fri, an nth-weekday \
7228                     like tue#2, a last-weekday like friL, or *)"
7229                ))
7230            };
7231            // #418: nth-weekday suffix (`tue#2` = 2nd Tuesday). Croner
7232            // accepts `<dow>#<n>` (n = 1..5) in the DOW field, and
7233            // `to_cron` passes the token through verbatim, so the
7234            // engine fires only on that occurrence. It's a single
7235            // weekday + ordinal — not combinable with a range.
7236            if let Some((day_part, nth_part)) = tok.split_once('#') {
7237                // Normalize once and use `d` consistently (gemini #547);
7238                // the outer `invalid` already echoes the raw `tok`.
7239                let d = day_part.trim().to_ascii_lowercase();
7240                if d.contains('-') || !is_day(&d) {
7241                    return invalid("the part before # must be a single weekday");
7242                }
7243                match nth_part.trim().parse::<u8>() {
7244                    Ok(n) if (1..=5).contains(&n) => {}
7245                    _ => return invalid("the # ordinal must be 1..5 (e.g. tue#2 = 2nd Tuesday)"),
7246                }
7247                continue;
7248            }
7249            // #418: last-weekday suffix (`friL` = last Friday of the
7250            // month — the monthly-maintenance sibling of Patch Tuesday).
7251            // Croner accepts `<dow>L` in the DOW field with verified
7252            // last-<dow>-of-month semantics, and `to_cron` passes it
7253            // through verbatim. A single weekday + `L` — bare `L` and
7254            // ranges are rejected (croner would read bare `L` as
7255            // Saturday, which is a confusing footgun).
7256            if let Some(day_part) = tok.strip_suffix(['L', 'l']) {
7257                // No `.trim()`: a cron DOW token can't carry internal
7258                // whitespace, so `"fri L"` must be *rejected* here (its
7259                // strip leaves `"fri "`, and `is_day` catches the space)
7260                // rather than trimmed into a clean `"fri"` that then
7261                // produces a malformed `fri L` cron downstream and a
7262                // confusing croner error (gemini #560).
7263                let d = day_part.to_ascii_lowercase();
7264                if d.is_empty() {
7265                    return invalid("`L` (last-weekday) needs a weekday before it, e.g. friL");
7266                }
7267                if d.contains('-') || !is_day(&d) {
7268                    return invalid(
7269                        "the part before L must be a single weekday (e.g. friL = last Friday)",
7270                    );
7271                }
7272                continue;
7273            }
7274            for part in tok.split('-') {
7275                let p = part.trim().to_ascii_lowercase();
7276                if p.is_empty() {
7277                    return invalid("empty range bound");
7278                }
7279                if p != "*" && !is_day(&p) {
7280                    return invalid(&format!("'{part}' is not a day"));
7281                }
7282            }
7283        }
7284        Ok(())
7285    }
7286
7287    /// For a one-shot (`at` carries a date), the absolute instant it
7288    /// fires in `tz`. `None` for a repeating calendar. Used to warn
7289    /// about a one-shot whose date is already in the past (it would
7290    /// never fire).
7291    pub fn oneshot_instant(&self, tz: ScheduleTz) -> Option<chrono::DateTime<chrono::Utc>> {
7292        let p = self.parse_at().ok()?;
7293        let date = p.date?;
7294        let naive = date.and_hms_opt(p.hour, p.minute, 0)?;
7295        tz.naive_to_utc(naive)
7296    }
7297
7298    /// The wall-clock time-of-day this calendar fires at (`None` if
7299    /// `at` is unparseable — validate() guards that). Used to detect
7300    /// a calendar whose fire time can never fall inside its
7301    /// `constraints.window` (claude #452 review).
7302    pub fn fire_time(&self) -> Option<chrono::NaiveTime> {
7303        let p = self.parse_at().ok()?;
7304        chrono::NaiveTime::from_hms_opt(p.hour, p.minute, 0)
7305    }
7306
7307    /// Lower to the cron string the scheduler engine runs. Repeating
7308    /// → 6-field `0 {min} {hour} * * {dow}`; one-shot → 7-field
7309    /// `0 {min} {hour} {day} {month} * {year}` (a past year never
7310    /// fires — that's what makes it one-shot).
7311    fn to_cron(&self) -> Result<String, String> {
7312        use chrono::Datelike;
7313        let ParsedAt { minute, hour, date } = self.parse_at()?;
7314        match date {
7315            Some(d) => {
7316                if !self.days.is_empty() {
7317                    return Err(
7318                        "when.at with a date is a one-shot and cannot be combined with days".into(),
7319                    );
7320                }
7321                Ok(format!(
7322                    "0 {minute} {hour} {} {} * {}",
7323                    d.day(),
7324                    d.month(),
7325                    d.year()
7326                ))
7327            }
7328            None => {
7329                let dow = if self.days.is_empty() {
7330                    "*".to_string()
7331                } else {
7332                    self.validate_days()?;
7333                    self.days.join(",")
7334                };
7335                Ok(format!("0 {minute} {hour} * * {dow}"))
7336            }
7337        }
7338    }
7339}
7340
7341/// The timezone a schedule's wall-clock fields (`when.at`,
7342/// `active.{from,until}`) are evaluated in (#418 Phase 2).
7343#[derive(
7344    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
7345)]
7346#[serde(rename_all = "snake_case")]
7347pub enum ScheduleTz {
7348    /// The running host's local timezone — the agent's for
7349    /// `runs_on: agent`, the backend server's otherwise. Default.
7350    #[default]
7351    Local,
7352    /// UTC — for timezone-independent schedules.
7353    Utc,
7354}
7355
7356impl ScheduleTz {
7357    /// Interpret a naive (zoneless) datetime as being in this tz and
7358    /// convert to UTC. On a DST *fold* (the local time occurs twice
7359    /// when clocks go back) we pick `.earliest()` rather than
7360    /// rejecting it; `None` is reserved for a true DST *gap* (a local
7361    /// time that never exists). `Utc` is fixed-offset so neither ever
7362    /// happens; `Local` is whatever timezone the running host is set
7363    /// to and *can* hit a gap/fold on any DST-observing host — not
7364    /// just the JST we run today (gemini + claude #432 review).
7365    fn naive_to_utc(self, naive: chrono::NaiveDateTime) -> Option<chrono::DateTime<chrono::Utc>> {
7366        use chrono::TimeZone;
7367        match self {
7368            ScheduleTz::Utc => Some(chrono::DateTime::from_naive_utc_and_offset(
7369                naive,
7370                chrono::Utc,
7371            )),
7372            ScheduleTz::Local => chrono::Local
7373                .from_local_datetime(&naive)
7374                .earliest()
7375                .map(|dt| dt.with_timezone(&chrono::Utc)),
7376        }
7377    }
7378
7379    /// The wall-clock time-of-day `now` reads as in this tz — used by
7380    /// [`Constraints::allows`] to test a maintenance window
7381    /// (#418 Phase 3). `Utc` is the naive UTC time; `Local` is the
7382    /// running host's local time.
7383    fn wall_time(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveTime {
7384        match self {
7385            ScheduleTz::Utc => now.time(),
7386            ScheduleTz::Local => now.with_timezone(&chrono::Local).time(),
7387        }
7388    }
7389
7390    /// The wall-clock *date* `now` reads as in this tz — used by
7391    /// [`Constraints::allows`] to test `skip_dates` (#418 holiday
7392    /// exclusion). Same tz semantics as [`Self::wall_time`].
7393    fn wall_date(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveDate {
7394        match self {
7395            ScheduleTz::Utc => now.date_naive(),
7396            ScheduleTz::Local => now.with_timezone(&chrono::Local).date_naive(),
7397        }
7398    }
7399
7400    /// Stable lowercase wire/display label (`local` / `utc`) — matches
7401    /// the serde `snake_case` representation. Used for the preview
7402    /// response's `tz` field so the JSON shape isn't coupled to the
7403    /// `Debug` repr (claude #578 review).
7404    pub fn as_str(self) -> &'static str {
7405        match self {
7406            ScheduleTz::Local => "local",
7407            ScheduleTz::Utc => "utc",
7408        }
7409    }
7410}
7411
7412impl std::fmt::Display for ScheduleTz {
7413    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7414        f.write_str(self.as_str())
7415    }
7416}
7417
7418/// `once` vs `{ every: <humantime> }` — shared by `per_pc` /
7419/// `per_target`. Untagged so the YAML stays the bare keyword or a
7420/// one-key map, nothing more ceremonial.
7421#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7422#[serde(untagged)]
7423pub enum PerPolicy {
7424    /// The bare string `once`: succeed once, then skip permanently
7425    /// (cooldown = infinity).
7426    Once(OnceLiteral),
7427    /// Re-arm after the humantime interval, e.g. `{ every: 6h }`.
7428    Every(EverySpec),
7429}
7430
7431/// Single-variant enum so serde accepts exactly the string `once`
7432/// (a free-form `String` would swallow typos like `onec`).
7433#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
7434#[serde(rename_all = "snake_case")]
7435pub enum OnceLiteral {
7436    Once,
7437}
7438
7439/// `{ every: <humantime> }`. Standalone struct (not an inline
7440/// struct variant). `{ evry: 6h }` still fails to parse (the
7441/// required `every` key is missing), and the create boundaries
7442/// reject the unknown `evry` via [`crate::strict`] with its path —
7443/// while agents reading a future writer's extra fields tolerate
7444/// them (#492).
7445#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7446pub struct EverySpec {
7447    /// Humantime interval (`10m`, `6h`, `1d`...). Parsed lazily —
7448    /// [`Schedule::validate`] rejects garbage at create time.
7449    pub every: String,
7450}
7451
7452impl PerPolicy {
7453    /// The cooldown this policy lowers to: `once` = `None`
7454    /// (permanent skip), `every` = the interval.
7455    fn cooldown(&self) -> Option<String> {
7456        match self {
7457            PerPolicy::Once(_) => None,
7458            PerPolicy::Every(EverySpec { every }) => Some(every.clone()),
7459        }
7460    }
7461}
7462
7463impl std::fmt::Display for When {
7464    /// Operator-facing one-liner (`per_pc once` / `per_pc every 6h`
7465    /// / `at 09:00 [mon-fri]` / `at 2026-06-10 09:00`) for log
7466    /// lines, audit payloads and the API's `ScheduleSummary`.
7467    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7468        let policy = |p: &PerPolicy| match p {
7469            PerPolicy::Once(_) => "once".to_string(),
7470            PerPolicy::Every(EverySpec { every }) => format!("every {every}"),
7471        };
7472        match self {
7473            When::PerPc(p) => write!(f, "per_pc {}", policy(p)),
7474            When::PerTarget(p) => write!(f, "per_target {}", policy(p)),
7475            When::Calendar(c) if c.days.is_empty() => write!(f, "at {}", c.at),
7476            When::Calendar(c) => write!(f, "at {} [{}]", c.at, c.days.join(",")),
7477            When::On(triggers) => {
7478                let names: Vec<&str> = triggers.iter().map(|t| t.as_str()).collect();
7479                write!(f, "on [{}]", names.join(","))
7480            }
7481        }
7482    }
7483}
7484
7485impl OnTrigger {
7486    /// Lowercase wire/display label (matches the serde `snake_case`).
7487    pub fn as_str(self) -> &'static str {
7488        match self {
7489            OnTrigger::Startup => "startup",
7490            OnTrigger::Logon => "logon",
7491            OnTrigger::Lock => "lock",
7492            OnTrigger::Unlock => "unlock",
7493            OnTrigger::NetworkChange => "network_change",
7494        }
7495    }
7496}
7497
7498/// Optional validity window for a [`Schedule`] (#418 decision G).
7499/// Half-open `[from, until)`; either bound may be omitted. Bounds
7500/// are `YYYY-MM-DD` (= that day's 00:00 in the schedule's `tz`) or
7501/// full RFC3339 (offset is honored as-is, `tz` ignored). Kept as
7502/// strings so the JSON Schema the SPA editor consumes stays two
7503/// plain string fields, mirroring `jitter` / `starting_deadline`.
7504///
7505/// #418 Phase 2: bounds are evaluated in the schedule's top-level
7506/// `tz` (was UTC-only in Phase 1) so `tz: local` makes both the
7507/// calendar `at` AND the `active` window local — one consistent
7508/// timezone per schedule.
7509#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
7510pub struct Active {
7511    /// Dormant before this instant.
7512    #[serde(default, skip_serializing_if = "Option::is_none")]
7513    pub from: Option<String>,
7514    /// Dormant from this instant on (exclusive).
7515    #[serde(default, skip_serializing_if = "Option::is_none")]
7516    pub until: Option<String>,
7517}
7518
7519impl Active {
7520    /// `skip_serializing_if` helper — an empty window means "always
7521    /// active" and is omitted from the wire format entirely.
7522    pub fn is_empty(&self) -> bool {
7523        self.from.is_none() && self.until.is_none()
7524    }
7525
7526    /// Parse one bound: RFC3339 first (offset honored, `tz`
7527    /// ignored), then bare `YYYY-MM-DD` (00:00 in `tz`).
7528    pub fn parse_bound(s: &str, tz: ScheduleTz) -> Result<chrono::DateTime<chrono::Utc>, String> {
7529        if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
7530            return Ok(dt.with_timezone(&chrono::Utc));
7531        }
7532        if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
7533            let midnight = d.and_hms_opt(0, 0, 0).expect("00:00:00 is always valid");
7534            return tz.naive_to_utc(midnight).ok_or_else(|| {
7535                format!("active: bound '{s}' falls in a DST gap for the schedule's tz")
7536            });
7537        }
7538        Err(format!(
7539            "active: unparseable bound '{s}' (want YYYY-MM-DD or RFC3339)"
7540        ))
7541    }
7542
7543    /// Is `now` inside the window? Unparseable bounds are treated
7544    /// as absent here (fail-open) — [`Schedule::validate`] is the
7545    /// place that rejects them loudly; this runs on every tick and
7546    /// must never panic on a stale KV blob.
7547    pub fn contains(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
7548        let bound = |s: &Option<String>| s.as_deref().and_then(|s| Self::parse_bound(s, tz).ok());
7549        if bound(&self.from).is_some_and(|from| now < from) {
7550            return false;
7551        }
7552        if bound(&self.until).is_some_and(|until| now >= until) {
7553            return false;
7554        }
7555        true
7556    }
7557}
7558
7559/// Host-environment gate (#418 `constraints.require`). Fire only when
7560/// the target host is in the required state. Sensed **in-process by the
7561/// agent** (Win32), so it is `runs_on: agent` only — the backend cannot
7562/// read a target host's power/idle state ([`Schedule::validate`]
7563/// rejects it on `runs_on: backend`, symmetric with `when: { on }`).
7564///
7565/// Evaluated at fire time as a skip-this-tick gate (NOT in
7566/// [`Constraints::allows`], which stays pure for `preview`): a reconcile
7567/// cadence re-checks every minute (so it effectively defers until the
7568/// state is met — the intended pairing); a `calendar` fire that lands
7569/// while the state is unmet is simply missed, same as `window`. It is
7570/// therefore a *runtime* gate and does not appear in `preview`.
7571// No `Eq`: `cpu_below: Option<f64>` is only `PartialEq` (f64 is not Eq).
7572#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
7573pub struct Require {
7574    /// Fire only while on **AC power** (skip on battery). Reads
7575    /// `GetSystemPowerStatus`; an unknown/unreadable status is treated
7576    /// as not-on-AC (fail-closed — a restrictive gate must not fire
7577    /// when it can't confirm the condition). `false` (default) = no
7578    /// power requirement.
7579    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
7580    pub ac_power: bool,
7581    /// Fire only when the active console session has had **no keyboard /
7582    /// mouse input for at least this long** (humantime, e.g. `"10m"`) —
7583    /// "don't run while the user is actively working". Input-based
7584    /// (simpler than Task Scheduler's CPU/disk-aware idle). A
7585    /// headless / disconnected console (no interactive user) trivially
7586    /// satisfies it. `None` (default) = no idle requirement. Parsed
7587    /// lazily; [`Schedule::validate`] rejects garbage at create time.
7588    #[serde(default, skip_serializing_if = "Option::is_none")]
7589    pub idle: Option<String>,
7590    /// Fire only when the **whole-machine CPU usage is below this
7591    /// percent** (0–100; e.g. `20.0` = "system CPU < 20%") — "don't run
7592    /// while the box is busy". Reuses the agent's `host_perf` system CPU%
7593    /// sample (`sysinfo` mean over cores), so the reading is up to one
7594    /// `host_perf` cadence old (default 60s) — fine as a "generally
7595    /// busy?" proxy, and more accurate than a fresh one-shot read (CPU%
7596    /// needs two samples). An unavailable sample (host_perf not warmed
7597    /// up yet, or stale) is treated as "not below" (fail-closed — a
7598    /// restrictive gate must not fire when it can't confirm). `None`
7599    /// (default) = no CPU requirement. [`Schedule::validate`] rejects an
7600    /// out-of-range value at create time.
7601    #[serde(default, skip_serializing_if = "Option::is_none")]
7602    pub cpu_below: Option<f64>,
7603    /// Fire only when the host has **internet connectivity** (Windows
7604    /// `GetNetworkConnectivityHint` reports InternetAccess) — "don't run
7605    /// until online" for jobs that download / phone home. A captive
7606    /// portal (ConstrainedInternetAccess), LAN-only (LocalAccess), or
7607    /// unknown/unreadable state is treated as offline (fail-closed) — a
7608    /// portal would just fail a download, so we hold the run. For VPN /
7609    /// SASE / app-specific conditions, use a custom script gate (separate
7610    /// slice). `false` (default) = no network requirement.
7611    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
7612    pub network: bool,
7613}
7614
7615impl Require {
7616    /// `skip_serializing_if` helper for an embedded empty `require`.
7617    pub fn is_empty(&self) -> bool {
7618        !self.ac_power && self.idle.is_none() && self.cpu_below.is_none() && !self.network
7619    }
7620
7621    /// Parsed minimum-idle duration (`None` = no idle requirement, or an
7622    /// unparseable value — `validate` rejects the latter at create time).
7623    pub fn min_idle(&self) -> Option<std::time::Duration> {
7624        self.idle
7625            .as_deref()
7626            .and_then(|s| humantime::parse_duration(s.trim()).ok())
7627    }
7628
7629    /// First unparseable field for create-time rejection (mirrors
7630    /// [`Constraints::bad_skip_date`]).
7631    pub fn bad_idle(&self) -> Option<String> {
7632        self.idle.as_deref().and_then(|s| {
7633            humantime::parse_duration(s.trim())
7634                .err()
7635                .map(|e| format!("constraints.require.idle: invalid duration '{s}': {e}"))
7636        })
7637    }
7638}
7639
7640/// Host-environment state sensed by the agent, fed to [`require_met`].
7641/// A named struct (not positional args) so the growing set of sensed
7642/// signals — several of them `bool` — can't be transposed at a call
7643/// site. The Win32 sensing lives in `kanade-agent::env_gate`.
7644#[derive(Debug, Clone, Copy, Default)]
7645pub struct EnvState {
7646    /// Is the host on AC power (`false` if on battery or unreadable).
7647    pub ac_online: bool,
7648    /// How long the console has been idle (`None` = couldn't determine).
7649    pub idle: Option<std::time::Duration>,
7650    /// Whole-machine CPU usage 0–100 (`None` = no sample yet).
7651    pub cpu_pct: Option<f64>,
7652    /// Does the host have internet connectivity (`false` if offline /
7653    /// LAN-only / unreadable).
7654    pub network_up: bool,
7655}
7656
7657/// Pure env-gate decision (#418 `constraints.require`). The Win32
7658/// sensing lives in the agent (`kanade-agent::env_gate`); this is the
7659/// testable core, fed the already-sensed [`EnvState`]. Deliberately a
7660/// free fn (not folded into [`Constraints::allows`]) so `allows` stays
7661/// pure and `preview` never evaluates a runtime gate. Each set
7662/// requirement is a restrictive AND: any unmet (or unknown) gate skips.
7663pub fn require_met(req: &Require, env: &EnvState) -> bool {
7664    if req.ac_power && !env.ac_online {
7665        return false;
7666    }
7667    if let Some(min) = req.min_idle() {
7668        match env.idle {
7669            Some(d) if d >= min => {}
7670            _ => return false,
7671        }
7672    }
7673    if let Some(max) = req.cpu_below {
7674        match env.cpu_pct {
7675            Some(p) if p < max => {}
7676            _ => return false,
7677        }
7678    }
7679    if req.network && !env.network_up {
7680        return false;
7681    }
7682    true
7683}
7684
7685/// [`Active`] decides *over what date range* a schedule is live,
7686/// `Constraints` decides *when, within an active period,* a fire is
7687/// allowed: `window` (a maintenance time-of-day window),
7688/// `max_concurrent` (a fleet-wide running-instance cap), `skip_dates`
7689/// (holiday exclusion) and `require` (host-environment gates, agent-only
7690/// — see [`Require`]).
7691// No `Eq`: contains `require: Option<Require>` which holds an f64.
7692#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
7693pub struct Constraints {
7694    /// `"HH:MM-HH:MM"` wall-clock window (evaluated in the schedule's
7695    /// `tz`). Fires outside it are skipped — mainly for reconcile
7696    /// cadences ("patrol every 6h, but only fire overnight") and
7697    /// daytime change-freezes. `start > end` crosses midnight
7698    /// (`"22:00-05:00"` = 22:00 through 05:00 next morning). Parsed
7699    /// lazily; [`Schedule::validate`] rejects garbage at create time.
7700    #[serde(default, skip_serializing_if = "Option::is_none")]
7701    pub window: Option<String>,
7702    /// Fleet-wide cap on how many instances of this schedule's job may
7703    /// run **at the same time** (#418 "同時実行ハード上限"). The
7704    /// backend scheduler counts the job's still-in-flight runs
7705    /// (`execution_results.finished_at IS NULL`) each tick and only
7706    /// dispatches to as many remaining pcs as there are free slots —
7707    /// a rolling window that refills as runs complete. Useful for
7708    /// disk/CPU/network-heavy jobs you don't want hammering the whole
7709    /// fleet at once.
7710    ///
7711    /// **Backend-only** (it needs a central counter): combining it
7712    /// with `runs_on: agent` is rejected by [`Schedule::validate`]
7713    /// (#418 decision E — "中央上限には中央が要る"). Most meaningful
7714    /// for `per_pc` reconcile cadences, where the poll re-ticks and
7715    /// refills slots. `None` (default) = no cap.
7716    #[serde(default, skip_serializing_if = "Option::is_none")]
7717    pub max_concurrent: Option<u32>,
7718    /// Calendar dates the schedule must **not** fire on — holidays,
7719    /// blackout days, one-off freeze dates (#418 "祝日除外"). Each is
7720    /// `YYYY-MM-DD`, evaluated as a wall-clock date in the schedule's
7721    /// `tz`. Applies to every `when` shape (a reconcile cadence skips
7722    /// the whole day; a calendar fire landing on the date is
7723    /// suppressed) and is honored by both the live scheduler and
7724    /// `preview`, since both gate on [`Constraints::allows`]. Empty
7725    /// (default) = no skips. Operator-supplied: there is no built-in
7726    /// holiday calendar — list the dates you care about. Parsed lazily;
7727    /// [`Schedule::validate`] rejects a malformed date at create time.
7728    #[serde(default, skip_serializing_if = "Vec::is_empty")]
7729    pub skip_dates: Vec<String>,
7730    /// Host-environment gate (#418): fire only when the target host is
7731    /// in the required state (on AC power, idle). Agent-sensed at fire
7732    /// time, `runs_on: agent` only. See [`Require`]. `None` (default) =
7733    /// no environment requirement.
7734    #[serde(default, skip_serializing_if = "Option::is_none")]
7735    pub require: Option<Require>,
7736}
7737
7738impl Constraints {
7739    /// `skip_serializing_if` helper — empty constraints are omitted
7740    /// from the wire format entirely.
7741    pub fn is_empty(&self) -> bool {
7742        self.window.is_none()
7743            && self.max_concurrent.is_none()
7744            && self.skip_dates.is_empty()
7745            && self.require.as_ref().is_none_or(Require::is_empty)
7746    }
7747
7748    /// The first unparseable `skip_dates` entry, if any — the
7749    /// scheduler logs it at register time so a fail-closed
7750    /// (never-firing) schedule from a hand-edited KV blob is
7751    /// diagnosable, mirroring [`Schedule::bad_window`].
7752    pub fn bad_skip_date(&self) -> Option<String> {
7753        self.skip_dates.iter().find_map(|s| {
7754            chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d")
7755                .err()
7756                .map(|e| format!("constraints.skip_dates: invalid date '{s}': {e}"))
7757        })
7758    }
7759
7760    /// Parse `"HH:MM-HH:MM"` into `(start, end)`. Equal bounds are an
7761    /// error (a zero-width or all-day window is ambiguous — write no
7762    /// window for "always").
7763    pub fn parse_window(s: &str) -> Result<(chrono::NaiveTime, chrono::NaiveTime), String> {
7764        let (a, b) = s
7765            .split_once('-')
7766            .ok_or_else(|| format!("constraints.window: '{s}' must be 'HH:MM-HH:MM'"))?;
7767        let parse = |part: &str| {
7768            chrono::NaiveTime::parse_from_str(part.trim(), "%H:%M")
7769                .map_err(|e| format!("constraints.window: invalid time '{}': {e}", part.trim()))
7770        };
7771        let (start, end) = (parse(a)?, parse(b)?);
7772        if start == end {
7773            return Err(format!(
7774                "constraints.window: start and end are equal ('{s}'); omit window for 'always'"
7775            ));
7776        }
7777        Ok((start, end))
7778    }
7779
7780    /// Is a fire allowed at `now` (evaluated in `tz`)? No window =
7781    /// always allowed. Half-open `[start, end)`; `start > end`
7782    /// crosses midnight.
7783    ///
7784    /// **Fail-closed** on an unparseable window (returns `false`,
7785    /// gemini #452 review): a window is a *restrictive* constraint
7786    /// (change-freeze / overnight-only), so a corrupt one must NOT
7787    /// silently allow fires during the restricted hours. Bad windows
7788    /// are rejected at create time by [`Schedule::validate`]; this
7789    /// only bites a hand-edited KV blob, where blocking is the safe
7790    /// direction. The scheduler warns at register time
7791    /// ([`Schedule::bad_window`]) so a stuck schedule is diagnosable.
7792    /// The tick path never panics regardless.
7793    pub fn allows(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
7794        // #418 holiday / blackout dates: never fire on a listed wall
7795        // date (in `tz`). Checked before the window since a skipped day
7796        // overrides any within-window allowance. Fail-closed on a
7797        // corrupt entry (same posture as `window`): a skip date is a
7798        // *restrictive* constraint, so a garbled one must not silently
7799        // re-enable fires — it blocks until fixed (`validate` rejects it
7800        // at create time; `bad_skip_date` lets the scheduler warn).
7801        if !self.skip_dates.is_empty() {
7802            let today = tz.wall_date(now);
7803            let blocked = self.skip_dates.iter().any(|s| {
7804                match chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d") {
7805                    Ok(d) => d == today,
7806                    Err(_) => true, // corrupt entry → fail-closed (block)
7807                }
7808            });
7809            if blocked {
7810                return false;
7811            }
7812        }
7813        match self.window.as_deref() {
7814            // No window → always allowed.
7815            None => true,
7816            // Window set: membership, or fail-closed if unparseable
7817            // (`window_contains` returns None for a corrupt window).
7818            Some(_) => self.window_contains(tz.wall_time(now)).unwrap_or(false),
7819        }
7820    }
7821
7822    /// Membership of a wall-clock time-of-day in the window. `None`
7823    /// when there is no window or it's unparseable (callers decide
7824    /// the failure direction). `start > end` crosses midnight.
7825    fn window_contains(&self, t: chrono::NaiveTime) -> Option<bool> {
7826        let (start, end) = Self::parse_window(self.window.as_deref()?).ok()?;
7827        Some(if start <= end {
7828            start <= t && t < end
7829        } else {
7830            t >= start || t < end
7831        })
7832    }
7833}
7834
7835/// What to do when a fire's script fails (#418 Phase 4 — the "高"
7836/// retry/backoff gap). Where [`Constraints`] gates *whether* a fire
7837/// happens, `OnFailure` decides what happens *after* one ran and
7838/// came back bad. Only `retry` so far; future `notify` / `disable`
7839/// would join the same namespace.
7840#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
7841pub struct OnFailure {
7842    /// Re-run the script in-process when it exits non-zero (or times
7843    /// out), up to a cap, with a fixed backoff between attempts.
7844    /// `None` (default) = no retry: a failed run is published as-is
7845    /// and (for reconcile cadences) simply re-fires on the next poll
7846    /// tick. See [`Retry`].
7847    #[serde(default, skip_serializing_if = "Option::is_none")]
7848    pub retry: Option<Retry>,
7849}
7850
7851impl OnFailure {
7852    /// `skip_serializing_if` helper — an empty policy is omitted from
7853    /// the wire format entirely.
7854    pub fn is_empty(&self) -> bool {
7855        self.retry.is_none()
7856    }
7857
7858    /// Lower the operator-facing `retry` (humantime backoff) onto the
7859    /// engine vocabulary the agent's executor runs on (backoff in
7860    /// whole seconds). Single seam shared by the backend command
7861    /// builder and the agent's local scheduler so the two stamp the
7862    /// same [`crate::wire::RetrySpec`] onto every Command. Returns
7863    /// `None` when there is no retry policy or the backoff is
7864    /// unparseable (validate() rejects the latter at create time;
7865    /// this stays fail-safe = "no retry" for a hand-edited KV blob
7866    /// rather than panicking on the fire path).
7867    pub fn lowered_retry(&self) -> Option<crate::wire::RetrySpec> {
7868        let r = self.retry.as_ref()?;
7869        let backoff_secs = humantime::parse_duration(&r.backoff).ok()?.as_secs();
7870        Some(crate::wire::RetrySpec {
7871            max: r.max,
7872            backoff_secs,
7873        })
7874    }
7875}
7876
7877/// Fixed-backoff retry policy (#418 Phase 4). `max` is the number of
7878/// *additional* attempts after the first run (so `max: 3` = up to 4
7879/// total executions); `backoff` is the humantime delay slept between
7880/// attempts. The retry happens fire-side (inside `kanade fire` /
7881/// `handle_command`) on every OS for the PoC — the Windows-native
7882/// "restart on failure" Task Scheduler path is deferred to the
7883/// native-delegation phase (#418 decision H).
7884#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
7885pub struct Retry {
7886    /// Max additional attempts after the first failure. Bounded
7887    /// `1..=10` by [`Schedule::validate`] — a typo'd `max: 1000`
7888    /// with a short backoff would otherwise pin a flapping script in
7889    /// a tight loop for the whole window.
7890    pub max: u32,
7891    /// Humantime delay slept between attempts (`"10m"`, `"30s"`).
7892    pub backoff: String,
7893}
7894
7895/// Fleet-wide change-freeze (#418 Phase 5 — the "メンテナンス窓 /
7896/// 変更凍結" gap's global half). Where [`Constraints::window`] is a
7897/// *per-schedule* time-of-day gate, a `Freeze` is a *single, fleet-
7898/// global* "stop all automated change" switch the operator flips
7899/// during an incident or a year-end change-freeze. It lives in its
7900/// own KV singleton ([`crate::kv::KEY_FREEZE`]); when present and
7901/// active, both the backend scheduler and every agent's local
7902/// scheduler skip *every* fire.
7903///
7904/// Shapes:
7905/// * `{}` (no bounds) — frozen indefinitely until the operator
7906///   clears it (incident "big red button").
7907/// * `{ from, until }` — frozen only within `[from, until)`,
7908///   evaluated in `tz` (planned change-freeze; auto-thaws).
7909///
7910/// The KV key being *absent* means "not frozen" — so clearing the
7911/// freeze is a KV delete, and `is_active` only ever runs on a freeze
7912/// the operator actually set.
7913#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
7914pub struct Freeze {
7915    /// Frozen from this instant (RFC3339 or bare `YYYY-MM-DD` in
7916    /// `tz`). `None` ⇒ frozen from the beginning of time.
7917    #[serde(default, skip_serializing_if = "Option::is_none")]
7918    pub from: Option<String>,
7919    /// Thawed from this instant on, exclusive. `None` ⇒ frozen with
7920    /// no scheduled end (manual clear required).
7921    #[serde(default, skip_serializing_if = "Option::is_none")]
7922    pub until: Option<String>,
7923    /// Operator-supplied note surfaced on the freeze-skip log and the
7924    /// SPA banner ("year-end change freeze", "INC-1234"). Advisory.
7925    #[serde(default, skip_serializing_if = "Option::is_none")]
7926    pub reason: Option<String>,
7927    /// Timezone the bare-date bounds are evaluated in (RFC3339 bounds
7928    /// carry their own offset). Defaults to host-local like a
7929    /// schedule's `tz`.
7930    #[serde(default)]
7931    pub tz: ScheduleTz,
7932}
7933
7934impl Freeze {
7935    /// Is the fleet frozen at `now`? An empty window (`from`/`until`
7936    /// both absent) is frozen unconditionally; otherwise membership of
7937    /// `[from, until)` in `tz`. Half-open like [`Active::contains`],
7938    /// but **fails CLOSED** on an unparseable bound — a freeze is a
7939    /// safety switch, so a corrupt window (only reachable via a
7940    /// hand-edited KV blob; `validate` rejects it at set time) must
7941    /// mean "frozen", not "fire normally" (coderabbit #472). This is
7942    /// the one deliberate divergence from `active`'s fail-OPEN
7943    /// behaviour, where an unparseable bound dormant-skips a schedule.
7944    pub fn is_active(&self, now: chrono::DateTime<chrono::Utc>) -> bool {
7945        // Parse a bound; an unparseable one short-circuits the whole
7946        // check to `true` (frozen) via the closure's `None` sentinel
7947        // handled below.
7948        let bound = |s: &Option<String>| -> Result<Option<chrono::DateTime<chrono::Utc>>, ()> {
7949            match s.as_deref() {
7950                None => Ok(None),
7951                Some(raw) => Active::parse_bound(raw, self.tz).map(Some).map_err(|_| ()),
7952            }
7953        };
7954        let (from, until) = match (bound(&self.from), bound(&self.until)) {
7955            (Ok(f), Ok(u)) => (f, u),
7956            // Any corrupt bound → fail closed (frozen).
7957            _ => return true,
7958        };
7959        if from.is_some_and(|f| now < f) {
7960            return false;
7961        }
7962        if until.is_some_and(|u| now >= u) {
7963            return false;
7964        }
7965        true
7966    }
7967
7968    /// Reject unparseable bounds / `from >= until` at set time (the
7969    /// API + CLI counterpart to [`Schedule::validate`]).
7970    pub fn validate(&self) -> Result<(), String> {
7971        let from = self
7972            .from
7973            .as_deref()
7974            .map(|s| Active::parse_bound(s, self.tz))
7975            .transpose()
7976            .map_err(|e| e.replace("active:", "freeze:"))?;
7977        let until = self
7978            .until
7979            .as_deref()
7980            .map(|s| Active::parse_bound(s, self.tz))
7981            .transpose()
7982            .map_err(|e| e.replace("active:", "freeze:"))?;
7983        if let (Some(f), Some(u)) = (from, until) {
7984            if f >= u {
7985                return Err(format!(
7986                    "freeze.from ({}) must be strictly before freeze.until ({})",
7987                    self.from.as_deref().unwrap_or_default(),
7988                    self.until.as_deref().unwrap_or_default(),
7989                ));
7990            }
7991        }
7992        Ok(())
7993    }
7994}
7995
7996/// The system-generated poll cadence every reconcile-shaped `when`
7997/// lowers to. Operators never write this: the real inter-run
7998/// spacing is the `every` cooldown; this only bounds "how soon do
7999/// we notice somebody is due" (#418 decision B took the poll
8000/// period away from the operator).
8001pub const POLL_CRON: &str = "0 * * * * *";
8002
8003/// What a [`When`] lowers to — the exact (cron, mode, cooldown)
8004/// trio the pre-#418 engine ran on. Keeping the engine vocabulary
8005/// unchanged is what lets Phase 1 swap the operator surface without
8006/// touching the tick / dedup machinery.
8007pub struct Lowered {
8008    /// Cron handed to `tokio-cron-scheduler` — [`POLL_CRON`] for
8009    /// reconcile shapes, a 6/7-field cron for calendar shapes.
8010    pub cron: String,
8011    /// Dedup semantics for `decide_fire`.
8012    pub mode: ExecMode,
8013    /// Humantime re-arm interval (`None` = succeed once, skip
8014    /// forever).
8015    pub cooldown: Option<String>,
8016    /// Timezone to evaluate `cron` in (#418 Phase 2). The scheduler
8017    /// passes this to `Job::new_async_tz`. Reconcile shapes carry
8018    /// the schedule's tz too even though POLL_CRON is tz-agnostic,
8019    /// so the same value drives the `active`-window check.
8020    pub tz: ScheduleTz,
8021}
8022
8023impl Schedule {
8024    /// The error message if this schedule's `constraints.window` is
8025    /// set but unparseable, else `None`. The scheduler logs this at
8026    /// register time so a fail-closed (never-firing) schedule from a
8027    /// hand-edited KV blob is diagnosable (gemini #452 review).
8028    pub fn bad_window(&self) -> Option<String> {
8029        let w = self.constraints.window.as_deref()?;
8030        Constraints::parse_window(w).err()
8031    }
8032
8033    /// True when this is a `calendar` schedule whose fire time can
8034    /// never fall inside its `constraints.window` — the cron fires,
8035    /// the window check rejects it, and (firing only at that
8036    /// time-of-day) it effectively never runs. An easy misconfig to
8037    /// set up by accident; the scheduler warns at register time
8038    /// (claude #452 review). Reconcile shapes poll every minute, so
8039    /// they always catch the window opening and aren't affected.
8040    pub fn calendar_outside_window(&self) -> bool {
8041        let When::Calendar(c) = &self.when else {
8042            return false;
8043        };
8044        let Some(t) = c.fire_time() else {
8045            return false;
8046        };
8047        matches!(self.constraints.window_contains(t), Some(false))
8048    }
8049
8050    /// Up to `count` future instants this schedule will fire, as
8051    /// absolute UTC, strictly after `now` — the dry-run / preview
8052    /// surface (#418 "ドライラン / プレビュー"). Only **calendar**
8053    /// schedules have discrete fire times; reconcile shapes
8054    /// (`per_pc`/`per_target`) poll every minute gated by cooldown, so
8055    /// they return an empty vec and the caller describes the cadence
8056    /// instead. Occurrences outside the `active.{from,until}` window or
8057    /// the `constraints.window` are **skipped**, so the list reflects
8058    /// when the schedule will ACTUALLY run, not the raw cron ticks.
8059    /// Evaluated in the schedule's `tz`, exactly like the scheduler's
8060    /// `Job::new_async_tz`, and with the same croner config the
8061    /// scheduler / [`Schedule::validate`] use, so a preview can never
8062    /// disagree with a real fire. A schedule that can never fire (a
8063    /// calendar time wholly outside its window, a past one-shot,
8064    /// `enabled: false` is *not* considered here — callers gate on
8065    /// `enabled` separately) yields an empty vec.
8066    pub fn preview_fires(
8067        &self,
8068        now: chrono::DateTime<chrono::Utc>,
8069        count: usize,
8070    ) -> Vec<chrono::DateTime<chrono::Utc>> {
8071        use croner::parser::{CronParser, Seconds};
8072        if !matches!(self.when, When::Calendar(_)) {
8073            return Vec::new();
8074        }
8075        // Same lowering + croner config as `next_calendar_fire` and the
8076        // live scheduler, so a preview can never disagree with a real
8077        // fire. `preview_fires` adds the N-occurrence walk and the
8078        // active / window filtering on top of that single seam.
8079        let lowered = self.lowered();
8080        let Ok(cron) = CronParser::builder()
8081            .seconds(Seconds::Required)
8082            .dom_and_dow(true)
8083            .build()
8084            .parse(&lowered.cron)
8085        else {
8086            return Vec::new();
8087        };
8088        let accept = |utc: chrono::DateTime<chrono::Utc>| {
8089            self.active.contains(utc, self.tz) && self.constraints.allows(utc, self.tz)
8090        };
8091        match self.tz {
8092            ScheduleTz::Utc => Self::next_occurrences(&cron, now, count, accept),
8093            ScheduleTz::Local => {
8094                Self::next_occurrences(&cron, now.with_timezone(&chrono::Local), count, accept)
8095            }
8096        }
8097    }
8098
8099    /// Walk croner forward from `after` collecting up to `count`
8100    /// accepted occurrences (converted to UTC). Generic over the tz the
8101    /// cron is evaluated in so `preview_fires` can run it in either
8102    /// `Utc` or `Local` without duplicating the loop.
8103    fn next_occurrences<Tz>(
8104        cron: &croner::Cron,
8105        after: chrono::DateTime<Tz>,
8106        count: usize,
8107        accept: impl Fn(chrono::DateTime<chrono::Utc>) -> bool,
8108    ) -> Vec<chrono::DateTime<chrono::Utc>>
8109    where
8110        Tz: chrono::TimeZone,
8111    {
8112        // Bound the scan so an `active`/window dead-end (every future
8113        // tick rejected) can't spin forever: ~4096 raw ticks covers
8114        // >10y of a daily calendar while staying instant for croner.
8115        const SCAN_CAP: usize = 4096;
8116        let mut out = Vec::with_capacity(count.min(SCAN_CAP));
8117        let mut cursor = after;
8118        let mut scanned = 0usize;
8119        while out.len() < count && scanned < SCAN_CAP {
8120            scanned += 1;
8121            let Ok(next) = cron.find_next_occurrence(&cursor, false) else {
8122                break;
8123            };
8124            let utc = next.with_timezone(&chrono::Utc);
8125            if accept(utc) {
8126                out.push(utc);
8127            }
8128            // `find_next_occurrence(.., inclusive = false)` already
8129            // advances strictly past `cursor`, so handing it `next`
8130            // verbatim gets the following occurrence — no manual +1s
8131            // nudge (and `DateTime<Tz>` is `Copy`, so no clone).
8132            cursor = next;
8133        }
8134        out
8135    }
8136
8137    /// Lower the operator-facing `when` onto the engine vocabulary.
8138    /// Single seam shared by the backend scheduler and the agent's
8139    /// local scheduler so the two can never drift.
8140    pub fn lowered(&self) -> Lowered {
8141        let tz = self.tz;
8142        match &self.when {
8143            When::PerPc(p) => Lowered {
8144                cron: POLL_CRON.into(),
8145                mode: ExecMode::OncePerPc,
8146                cooldown: p.cooldown(),
8147                tz,
8148            },
8149            When::PerTarget(p) => Lowered {
8150                cron: POLL_CRON.into(),
8151                mode: ExecMode::OncePerTarget,
8152                cooldown: p.cooldown(),
8153                tz,
8154            },
8155            // `to_cron` only fails on a malformed `at` (rejected by
8156            // validate() at create time). For a hand-edited KV blob
8157            // that slipped past, emit a deliberately-invalid cron so
8158            // register()'s Job::new_async_tz fails → warn+skip,
8159            // rather than firing at the wrong time.
8160            When::Calendar(c) => Lowered {
8161                cron: c
8162                    .to_cron()
8163                    .unwrap_or_else(|_| "# invalid calendar at".into()),
8164                mode: ExecMode::EveryTick,
8165                cooldown: None,
8166                tz,
8167            },
8168            // Event triggers have no cron — the agent fires them from an
8169            // OS event source. The `# event-trigger` cron is never
8170            // registered (the scheduler branches on `is_event()` first),
8171            // but keep it deliberately-invalid as a belt-and-suspenders
8172            // so a stray registration would fail rather than misfire.
8173            When::On(_) => Lowered {
8174                cron: "# event-trigger (no cron)".into(),
8175                mode: ExecMode::Event,
8176                cooldown: None,
8177                tz,
8178            },
8179        }
8180    }
8181
8182    /// True when this schedule fires from an OS event (`when: { on }`)
8183    /// rather than a clock — the agent skips `tokio-cron` registration
8184    /// for these and drives them from boot / session-change instead.
8185    pub fn is_event(&self) -> bool {
8186        matches!(self.when, When::On(_))
8187    }
8188
8189    /// The OS event triggers this schedule listens for, or `&[]` when it
8190    /// is not an event schedule.
8191    pub fn event_triggers(&self) -> &[OnTrigger] {
8192        match &self.when {
8193            When::On(t) => t,
8194            _ => &[],
8195        }
8196    }
8197
8198    /// The next absolute (UTC) time this schedule fires, or `None` when
8199    /// it has no discrete upcoming fire to preview.
8200    ///
8201    /// Used by the KLP `maintenance.list` preview ("what's about to
8202    /// happen on my PC", SPEC §2.1). Returns `None` for:
8203    ///
8204    /// - reconcile shapes (`per_pc` / `per_target`) — they lower to the
8205    ///   every-minute [`POLL_CRON`] and re-converge state continuously,
8206    ///   so "next fire" is always ~60s away and means nothing to a user
8207    ///   previewing upcoming maintenance;
8208    /// - a calendar schedule whose lowered cron won't parse (a
8209    ///   hand-edited KV blob that slipped past [`Schedule::validate`]);
8210    /// - a cron with no future occurrence.
8211    ///
8212    /// The wall-clock fire is evaluated in the schedule's own `tz`
8213    /// (matching the live tick's `Job::new_async_tz`) then normalised
8214    /// to UTC for the wire. `inclusive = false`: strictly the *next*
8215    /// fire after `now`, never one matching the current instant.
8216    pub fn next_calendar_fire(
8217        &self,
8218        now: chrono::DateTime<chrono::Utc>,
8219    ) -> Option<chrono::DateTime<chrono::Utc>> {
8220        if !matches!(self.when, When::Calendar(_)) {
8221            return None;
8222        }
8223        let lowered = self.lowered();
8224        // Same parser configuration tokio-cron-scheduler 0.15 uses
8225        // internally, so this can never compute a fire the live
8226        // scheduler wouldn't (seconds required, DOM-and-DOW honored).
8227        let cron = croner::parser::CronParser::builder()
8228            .seconds(croner::parser::Seconds::Required)
8229            .dom_and_dow(true)
8230            .build()
8231            .parse(&lowered.cron)
8232            .ok()?;
8233        match lowered.tz {
8234            ScheduleTz::Utc => cron.find_next_occurrence(&now, false).ok(),
8235            ScheduleTz::Local => {
8236                let now_local = now.with_timezone(&chrono::Local);
8237                cron.find_next_occurrence(&now_local, false)
8238                    .ok()
8239                    .map(|t| t.with_timezone(&chrono::Utc))
8240            }
8241        }
8242    }
8243
8244    /// Cross-field semantic checks that don't fit pure serde derive
8245    /// — the [`Manifest::validate`] counterpart (#418 decision F;
8246    /// pre-Phase-1 a broken schedule was accepted at create time
8247    /// and silently warn-skipped at tick time). Run at every create
8248    /// site: `kanade schedule create` (client-side) and
8249    /// `POST /api/schedules`. The job_id-exists check lives in the
8250    /// API handler instead — it needs the JOBS KV.
8251    pub fn validate(&self) -> Result<(), String> {
8252        if matches!(self.runs_on, RunsOn::Agent) && matches!(self.when, When::PerTarget(_)) {
8253            return Err(
8254                "when.per_target needs fleet-wide completion data and is backend-only; \
8255                 it cannot be combined with runs_on: agent (each agent self-schedules, \
8256                 so per-target dedup would be deduping across a target of 1)"
8257                    .into(),
8258            );
8259        }
8260        // #418 event triggers: the agent owns the OS event source
8261        // (boot / session-change), so `when: { on }` is agent-only and
8262        // needs at least one trigger.
8263        if let When::On(triggers) = &self.when {
8264            if !matches!(self.runs_on, RunsOn::Agent) {
8265                return Err(
8266                    "when.on (OS event trigger) is fired by the agent's own event \
8267                     source, so it requires runs_on: agent"
8268                        .into(),
8269                );
8270            }
8271            if triggers.is_empty() {
8272                return Err(
8273                    "when.on must list at least one trigger (e.g. [startup, logon])".into(),
8274                );
8275            }
8276        }
8277        if let Some(cd) = self.lowered().cooldown.as_deref() {
8278            humantime::parse_duration(cd)
8279                .map_err(|e| format!("when.every: invalid duration '{cd}': {e}"))?;
8280        }
8281        if let When::Calendar(c) = &self.when {
8282            // Lower the calendar form to its cron (catches a bad `at`
8283            // and the date+days conflict), then validate that cron
8284            // with the same parser configuration tokio-cron-scheduler
8285            // 0.15 uses internally (croner, seconds required,
8286            // DOM-and-DOW both honored, year optional) — create-time
8287            // validation can never accept what register() rejects.
8288            let cron = c.to_cron()?;
8289            croner::parser::CronParser::builder()
8290                .seconds(croner::parser::Seconds::Required)
8291                .dom_and_dow(true)
8292                .build()
8293                .parse(&cron)
8294                .map_err(|e| format!("when.at lowered to invalid cron '{cron}': {e}"))?;
8295        }
8296        // The other humantime strings on the schedule (claude #419
8297        // review): runtime degrades gracefully on both (bad jitter →
8298        // silent no-op, bad starting_deadline → warn + skipped tick),
8299        // but "rejected at create time" should cover every field the
8300        // operator can typo, not just `when`.
8301        if let Some(j) = &self.plan.jitter {
8302            humantime::parse_duration(j)
8303                .map_err(|e| format!("jitter: invalid duration '{j}': {e}"))?;
8304        }
8305        if let Some(sd) = &self.starting_deadline {
8306            humantime::parse_duration(sd)
8307                .map_err(|e| format!("starting_deadline: invalid duration '{sd}': {e}"))?;
8308        }
8309        // #917: the plan side got almost no create-time checks, so
8310        // several never-fires / fails-every-tick shapes were accepted
8311        // and only surfaced at dispatch time — or never:
8312        //
8313        // (1) a target that dispatches nothing. A runs_on: agent
8314        // schedule matches each agent against `target` (rollout waves
8315        // are backend-published and never reach that path), so an
8316        // unspecified target silently never fires; a runs_on: backend
8317        // one warn-fails every tick at the exec boundary, which
8318        // rejects the same shape with the same message.
8319        let has_waves = self
8320            .plan
8321            .rollout
8322            .as_ref()
8323            .is_some_and(|r| !r.waves.is_empty());
8324        if matches!(self.runs_on, RunsOn::Agent) {
8325            if !self.plan.target.is_specified() {
8326                return Err(
8327                    "target must specify at least one of `all` / `groups` / `pcs` — a \
8328                     runs_on: agent schedule matches each agent against `target`, so an \
8329                     unspecified target never fires anywhere"
8330                        .into(),
8331                );
8332            }
8333            if self.plan.rollout.is_some() {
8334                return Err(
8335                    "rollout waves are published by the backend and are ignored by \
8336                     runs_on: agent schedules (each agent self-schedules from `target`); \
8337                     drop `rollout:` or use runs_on: backend"
8338                        .into(),
8339                );
8340            }
8341        } else if !has_waves && !self.plan.target.is_specified() {
8342            return Err(
8343                "target must specify at least one of `all` / `groups` / `pcs` \
8344                 (or set `rollout.waves`) — the exec boundary rejects an \
8345                 unspecified target, so the schedule would fail every tick"
8346                    .into(),
8347            );
8348        }
8349        // (2) rollout waves were never validated: a blank group or an
8350        // unparseable delay failed at EVERY fire (the CLI doesn't even
8351        // expose waves, so the failure was always deferred to dispatch)
8352        // and an empty list dispatched nothing. (3) A wave delayed to
8353        // or past starting_deadline is dead on arrival: the deadline is
8354        // stamped once at tick time and the Command is serialised
8355        // before the wave sleep, so agents receive it already expired
8356        // (a synthetic exit-125 skip on every fire).
8357        if let Some(rollout) = &self.plan.rollout {
8358            if rollout.waves.is_empty() {
8359                return Err(
8360                    "rollout.waves must list at least one wave; omit `rollout:` for a \
8361                     one-shot fan-out of `target`"
8362                        .into(),
8363                );
8364            }
8365            let deadline = self
8366                .starting_deadline
8367                .as_deref()
8368                .and_then(|sd| humantime::parse_duration(sd).ok());
8369            for (i, wave) in rollout.waves.iter().enumerate() {
8370                if wave.group.trim().is_empty() {
8371                    return Err(format!("rollout.waves[{i}].group must not be blank"));
8372                }
8373                let delay = humantime::parse_duration(&wave.delay).map_err(|e| {
8374                    format!(
8375                        "rollout.waves[{i}].delay: invalid duration '{}': {e}",
8376                        wave.delay
8377                    )
8378                })?;
8379                if let Some(deadline) = deadline
8380                    && delay >= deadline
8381                {
8382                    return Err(format!(
8383                        "rollout.waves[{i}].delay ('{}') must be shorter than \
8384                         starting_deadline ('{}'): the deadline is stamped at tick time, \
8385                         so this wave's Commands would already be expired when published \
8386                         (skipped by every agent, every fire)",
8387                        wave.delay,
8388                        self.starting_deadline.as_deref().unwrap_or_default(),
8389                    ));
8390                }
8391            }
8392        }
8393        // (4) deadline_at is machine-stamped: the scheduler overwrites
8394        // it from `tick + starting_deadline` on every fire, so an
8395        // operator-set value is silently discarded — reject it and
8396        // point at the knob that does what they meant. (Ad-hoc POST
8397        // /api/exec bodies are a different write path and may still
8398        // carry it.)
8399        if self.plan.deadline_at.is_some() {
8400            return Err(
8401                "deadline_at is computed by the scheduler (tick time + starting_deadline) \
8402                 and overwritten on every fire — set `starting_deadline` instead"
8403                    .into(),
8404            );
8405        }
8406        let from = self
8407            .active
8408            .from
8409            .as_deref()
8410            .map(|s| Active::parse_bound(s, self.tz))
8411            .transpose()?;
8412        let until = self
8413            .active
8414            .until
8415            .as_deref()
8416            .map(|s| Active::parse_bound(s, self.tz))
8417            .transpose()?;
8418        if let (Some(f), Some(u)) = (from, until) {
8419            if f >= u {
8420                return Err(format!(
8421                    "active.from ({}) must be strictly before active.until ({})",
8422                    self.active.from.as_deref().unwrap_or_default(),
8423                    self.active.until.as_deref().unwrap_or_default(),
8424                ));
8425            }
8426        }
8427        // #418 Phase 3: a bad maintenance window is rejected at create
8428        // time (parse_window also catches equal bounds).
8429        if let Some(w) = self.constraints.window.as_deref() {
8430            Constraints::parse_window(w)?;
8431        }
8432        // #418 holiday exclusion: reject a malformed skip date at create
8433        // time so the fail-closed `allows` path only ever bites a
8434        // hand-edited KV blob, not a fresh `kanade schedule create`.
8435        if let Some(err) = self.constraints.bad_skip_date() {
8436            return Err(err);
8437        }
8438        // #418: constraints.max_concurrent is a central running-instance
8439        // cap, so it needs the backend's counter — reject it on
8440        // runs_on: agent (decision E), and reject a meaningless 0.
8441        if let Some(mc) = self.constraints.max_concurrent {
8442            // Check the structural incompatibility (agent has no central
8443            // counter) before the value range, so a `max_concurrent: 0`
8444            // + `runs_on: agent` combo reports the more fundamental
8445            // problem first (claude #542).
8446            if matches!(self.runs_on, RunsOn::Agent) {
8447                return Err(
8448                    "constraints.max_concurrent needs a central counter and is backend-only; \
8449                     it cannot be combined with runs_on: agent (each agent self-schedules, \
8450                     so there is no fleet-wide count to cap against)"
8451                        .into(),
8452                );
8453            }
8454            if mc == 0 {
8455                return Err(
8456                    "constraints.max_concurrent must be >= 1 (0 would never fire; \
8457                     omit it for no cap)"
8458                        .into(),
8459                );
8460            }
8461        }
8462        // #418: constraints.require (host-state env gates: ac_power /
8463        // idle / cpu_below / network) is sensed in-process by the agent,
8464        // so it needs runs_on: agent — the backend can't read a target
8465        // host's power / idle / cpu / connectivity state. Symmetric with
8466        // `when: { on }` (also agent-only); inverse of max_concurrent
8467        // (backend-only).
8468        if let Some(req) = &self.constraints.require {
8469            if !req.is_empty() && matches!(self.runs_on, RunsOn::Backend) {
8470                return Err(
8471                    "constraints.require (host-state env gates: ac_power / idle / cpu_below / \
8472                     network) is sensed in-process by the agent and needs runs_on: agent; the \
8473                     backend cannot read a target host's power / idle / cpu / connectivity state"
8474                        .into(),
8475                );
8476            }
8477            // Reject a malformed idle duration at create time so the
8478            // fail-closed runtime path only ever bites a hand-edited
8479            // KV blob (mirror skip_dates / on_failure.retry).
8480            if let Some(err) = req.bad_idle() {
8481                return Err(err);
8482            }
8483            // cpu_below is a percent — reject out-of-range so a typo
8484            // can't make a schedule that never (>=100 is always-busy?
8485            // no — <0 never matches) or trivially fires.
8486            if let Some(c) = req.cpu_below
8487                && !(c > 0.0 && c <= 100.0)
8488            {
8489                return Err(format!(
8490                    "constraints.require.cpu_below must be in (0, 100] percent (got {c}); \
8491                     omit it for no CPU requirement"
8492                ));
8493            }
8494        }
8495        // #418 Phase 4: a bad on_failure.retry is rejected at create
8496        // time — backoff must be valid humantime, and max is bounded
8497        // so a typo can't pin a flapping script in a tight loop.
8498        if let Some(r) = &self.on_failure.retry {
8499            let backoff = humantime::parse_duration(&r.backoff).map_err(|e| {
8500                format!(
8501                    "on_failure.retry.backoff: invalid duration '{}': {e}",
8502                    r.backoff
8503                )
8504            })?;
8505            // The wire form lowers backoff to whole seconds, so a
8506            // sub-second value would silently become a 0s no-wait
8507            // (coderabbit #466). Reject it rather than honour a backoff
8508            // the operator can't actually get.
8509            if backoff.as_secs() < 1 {
8510                return Err(format!(
8511                    "on_failure.retry.backoff must be >= 1s (got '{}'); sub-second backoffs \
8512                     round to 0 on the wire",
8513                    r.backoff
8514                ));
8515            }
8516            if !(1..=10).contains(&r.max) {
8517                return Err(format!(
8518                    "on_failure.retry.max must be 1..=10 (got {}); it counts additional \
8519                     attempts after the first run",
8520                    r.max
8521                ));
8522            }
8523        }
8524        // A blank / whitespace-only tag renders an empty filter chip on
8525        // the Schedules page — reject it at create time, mirroring the
8526        // Manifest::validate tag guard.
8527        for tag in &self.tags {
8528            if tag.trim().is_empty() {
8529                return Err("tags must not contain empty entries".to_string());
8530            }
8531        }
8532        Ok(())
8533    }
8534}
8535
8536/// Shared `serde(default)` for `bool` fields that default to `true`
8537/// (e.g. `CheckHint::fleet` / `CheckHint::health`). Generic name so it
8538/// doesn't read as "fleet" when reused for `health`.
8539fn default_true() -> bool {
8540    true
8541}