Skip to main content

kanade_shared/
manifest.rs

1use serde::{Deserialize, Serialize};
2
3use crate::wire::{FinalizeCommand, RunAs, Shell, Staleness};
4
5/// YAML job manifest (= registered "what to run", v0.18.0+).
6///
7/// Owns only script-intrinsic fields. **Who** (`target`), **how to
8/// phase fanout** (`rollout`), and **when to stagger start**
9/// (`jitter`) all moved to the Schedule / exec request side — same
10/// script can now be fired against different targets / rollouts
11/// without copying the script body.
12///
13/// #492: these types are READ fleet-wide (agents decode them from
14/// BUCKET_JOBS / BUCKET_SCHEDULES and inside live Commands), so they
15/// must tolerate unknown fields — `deny_unknown_fields` here made a
16/// gradually-upgrading fleet's OLD agents reject the whole object
17/// the moment a newer backend added any field. Operator typo
18/// protection (the old reason for the attribute) lives at the WRITE
19/// boundaries instead: `kanade job/schedule create` and the backend
20/// POST extractor parse via [`crate::strict`], which rejects unknown
21/// keys with their full paths. The wire rule: new fields always get
22/// `#[serde(default)]` (+ `skip_serializing_if` while old readers
23/// may still be strict).
24#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
25pub struct Manifest {
26    pub id: String,
27    pub version: String,
28    #[serde(default)]
29    pub description: Option<String>,
30    pub execute: Execute,
31    #[serde(default)]
32    pub require_approval: bool,
33    /// Opt-in marker that this job produces a JSON inventory fact
34    /// payload on stdout. When present, the backend's results
35    /// projector parses `ExecResult.stdout` as JSON and upserts an
36    /// `inventory_facts` row keyed by `(pc_id, manifest.id)`. The
37    /// `display` sub-config drives the SPA's Inventory page render.
38    #[serde(default)]
39    pub inventory: Option<InventoryHint>,
40    /// Issue #246: opt-in marker that this job emits per-line
41    /// observability events on stdout (one JSON `ObsEvent` per
42    /// newline). When present, the agent — after the script exits
43    /// successfully — parses each non-empty stdout line as an
44    /// `ObsEvent`, publishes it on `obs.<pc_id>` via the
45    /// `obs_outbox`, and (intentionally) **omits the stdout from
46    /// the `ExecResult`** so the timeline data doesn't double up
47    /// in `execution_results.stdout` (which would multiply rows
48    /// by ~50/day/PC of noise).
49    ///
50    /// Distinct from `inventory:` (single JSON object → projector
51    /// upsert) — events are append-only timeline points consumed
52    /// by the dedicated `obs_events` table.
53    #[serde(default)]
54    pub emit: Option<EmitConfig>,
55    /// #290: opt-in marker that this job is an operator-defined
56    /// **health check** whose result feeds the Client App's Health
57    /// tab over KLP (`StateSnapshot.checks`). The script prints a
58    /// free-form JSON object on stdout (like any inventory job); the
59    /// agent reads the [`CheckHint::status_field`] value dynamically
60    /// into a [`crate::ipc::state::Check`] named `check.name`.
61    /// Cadence / windows / conditions come from
62    /// the job's Schedule (exactly like inventory) — there is
63    /// deliberately no interval here. **Composes with `inventory:` and
64    /// `collect:`** (#821): each reads its own `#KANADE-<KIND>`-fenced
65    /// stdout block, so one job can drive a check, project inventory
66    /// facts, and collect files in a single run. Only `emit:` (NDJSON
67    /// stdout) is incompatible. A check-only job may skip the fence
68    /// (whole stdout is the JSON); a multi-hint job fences each block.
69    #[serde(default)]
70    pub check: Option<CheckHint>,
71    /// #219: opt-in marker that this job COLLECTS files into a bundle.
72    /// The script does the collection work and prints a single JSON
73    /// object on stdout carrying a `files` array of paths (the field
74    /// name is [`CollectHint::files_field`], default `"files"`); the
75    /// agent — after the script exits successfully — zips those files,
76    /// uploads the archive to the `OBJECT_COLLECTIONS` Object Store
77    /// bucket (key `<pc_id>/<job_id>/<timestamp>.zip`), and records the
78    /// key in [`crate::wire::ExecResult::collect_object`]. The operator
79    /// downloads bundles from the SPA Collect page.
80    ///
81    /// Like `inventory:` / `check:` this reads a JSON object from stdout.
82    /// #821: it reads its own `#KANADE-COLLECT-BEGIN/END`-fenced block,
83    /// so it **composes with `inventory:` / `check:`** (and a user
84    /// message) on one stdout — only `emit:` (NDJSON) is incompatible
85    /// (enforced in [`Manifest::validate`]). A collect-only job may skip
86    /// the fence. It also composes with `client:` — a `collect:` +
87    /// `client:` job lets an end user trigger a collection from the
88    /// Client App (the same-host agent runs it).
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub collect: Option<CollectHint>,
91    /// #720: opt-in declarative aggregation over `obs_events` that drives
92    /// the SPA **Analytics** page. Unlike the other hints this one never
93    /// touches stdout and is never delivered to the agent — it's a pure
94    /// *read spec* the backend reads from `BUCKET_JOBS` at query time and
95    /// turns into `json_extract` aggregation SQL. Each entry is one widget
96    /// (a `placement.analytics:` tab groups them); `scope:` selects per-PC vs
97    /// fleet-wide rollup. Because it consumes nothing at run time it
98    /// composes with every other hint (typically paired with `emit:`,
99    /// which produces the events it reads). See [`AggregateWidget`].
100    ///
101    /// New field ⇒ #492 wire rule (`default` + `skip_serializing_if`).
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub aggregate: Option<Vec<AggregateWidget>>,
104    /// v0.26: Layer 2 staleness policy (SPEC.md §2.6.2). Controls
105    /// what the agent does at fire time when it can't verify the
106    /// `script_current` / `script_status` KV values are fresh —
107    /// especially relevant for `runs_on: agent` schedules where
108    /// the agent may fire from cache while offline. Defaults to
109    /// `Staleness::Cached` (silently use cached values), which
110    /// matches every pre-v0.26 Manifest.
111    #[serde(default)]
112    pub staleness: Staleness,
113    /// #291: opt-in marker that this job is offered to **end users**
114    /// in the Client App's job tabs over KLP (`jobs.list` →
115    /// `jobs.execute`). Parallel to [`inventory`] / [`check`] /
116    /// [`emit`]: the block's mere presence is the opt-in, and it
117    /// groups the end-user presentation fields (name / category /
118    /// icon) that only make sense for a user-facing job. `None`
119    /// (the default) ⇒ an operator-only job — inventory, checks,
120    /// scheduled maintenance — that never surfaces in the catalog.
121    ///
122    /// The agent re-reads this at every `jobs.list` / `jobs.execute`
123    /// (SPEC §2.1), so removing the block takes a job out of a
124    /// running client on its next action.
125    ///
126    /// [`inventory`]: Manifest::inventory
127    /// [`check`]: Manifest::check
128    /// [`emit`]: Manifest::emit
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub client: Option<ClientHint>,
131    /// Free-form operator taxonomy for the Jobs catalog. Purely a
132    /// SPA-side organisational aid — agents / scheduler / projector
133    /// never read it — so it carries no runtime semantics and any
134    /// string is allowed (`security`, `weekly`, `windows`, …). Jobs
135    /// cross-cut (a `check-bitlocker` is at once a health-check, a
136    /// security control, and Windows-specific), which is why this is
137    /// a multi-valued list rather than the single closed-enum
138    /// [`ClientHint::category`] (whose values are the end-user Client
139    /// App's tabs, a different concern). The operator Jobs page groups
140    /// rows by id-prefix for free; tags add the orthogonal filter axis
141    /// prefixes can't express.
142    ///
143    /// Empty by default (the overwhelming majority of jobs), and a
144    /// new field, so it follows the #492 wire rule: `serde(default)`
145    /// plus `skip_serializing_if` keep gradually-upgrading old readers
146    /// from tripping over its absence / presence.
147    #[serde(default, skip_serializing_if = "Vec::is_empty")]
148    pub tags: Vec<String>,
149    /// GitOps provenance (#678) — see [`RepoOrigin`]. Stamped by
150    /// `kanade job create` when the source YAML lives inside a Git work
151    /// tree, so the SPA can render the job read-only and point edits
152    /// back at the repo instead of letting a ClickOps edit silently
153    /// diverge from Git (SPEC design principle #3: 設定駆動 YAML + Git).
154    /// `None` for SPA-born jobs and for manifests applied from outside
155    /// any Git repo. Purely informational: agents / scheduler /
156    /// projector never read it, and it survives `script_file:` inlining
157    /// (it's orthogonal to the exactly-one-of script-source rule). New
158    /// field ⇒ #492 wire rule (`default` + `skip_serializing_if`).
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub origin: Option<RepoOrigin>,
161    /// Job-generic post-step hook. When set, the agent runs this script
162    /// AFTER the main `execute:` script exits cleanly (and, for a
163    /// `collect:` job, after the bundle finishes uploading), so the
164    /// operator can delete / move / notify based on what the step
165    /// produced. Best-effort: a finalize failure is logged but never
166    /// fails the run — the upload (if any) already succeeded.
167    ///
168    /// For `collect:` jobs the agent injects the environment variable
169    /// `KANADE_COLLECT_RESULT` — a JSON object
170    /// `{ "ok": true, "bundles": [ { "key", "uploaded", "files": [...] } ] }`
171    /// — so the hook acts on exactly the files that were bundled and
172    /// uploaded (e.g. deletes only the `uploaded` ones). Composes with
173    /// every hint. New field ⇒ #492 wire rule (`default` +
174    /// `skip_serializing_if`).
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub finalize: Option<FinalizeSpec>,
177    /// #vuln-roadmap: declarative **external-data feeds**. Each entry fetches
178    /// global reference data (a vulnerability catalog, an EOL table, a license
179    /// roster) and projects it into the shared `feeds` table keyed
180    /// `(feed_id, item_id)` — fleet-wide, with no `pc_id`, unlike the per-PC
181    /// inventory [`ExplodeSpec`]. The job's script (run on the trusted
182    /// controller tier) fetches + shapes the data and prints the array under
183    /// each spec's [`field`](FeedSpec::field) inside a
184    /// `#KANADE-FEED-BEGIN/END` fence; the projector replaces that feed's rows
185    /// wholesale. A non-empty `feed:` **implies** `tier: controller` (the
186    /// dispatch guard treats it as such), so an external fetch never lands on
187    /// an employee endpoint. Composes with the other fenced hints. New field ⇒
188    /// #492 wire rule (`default` + `skip_serializing_if`). See [`FeedSpec`].
189    #[serde(default, skip_serializing_if = "Vec::is_empty")]
190    pub feed: Vec<FeedSpec>,
191    /// Execution tier (#vuln-roadmap). `None` / `endpoint` (default) ⇒ the
192    /// job dispatches to the targeted fleet agents like any job. `controller`
193    /// ⇒ it may run ONLY on trusted infra hosts — the backend constrains
194    /// dispatch to members of the operator-configured `controller_group`
195    /// (`server_settings` KV), and refuses to run anywhere if that group is
196    /// unset (fail-safe). This keeps `feed:` (external-fetch) and future
197    /// privileged hints off employee endpoints. The `feed:` hint implies
198    /// `controller`; it can also be set explicitly. New field ⇒ #492 wire
199    /// rule (`default` + `skip_serializing_if`).
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub tier: Option<Tier>,
202}
203
204/// Execution tier for a [`Manifest`] — see [`Manifest::tier`]. `endpoint`
205/// is the default (a normal fleet job); `controller` restricts dispatch to
206/// the trusted `controller_group`. `Unknown` is the #492 forward-compat
207/// catch-all: an older reader still *decodes* a job that names a future
208/// tier (so it doesn't fail the whole document), but `Manifest::validate()`
209/// **rejects** it — for a security field we fail closed rather than fall
210/// back to unrestricted `endpoint` dispatch (a future tier is presumably
211/// *more* restrictive, and a typo'd `controller` must not silently widen).
212#[derive(
213    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
214)]
215#[serde(rename_all = "snake_case")]
216#[non_exhaustive]
217pub enum Tier {
218    /// Dispatch to the targeted fleet agents (the default).
219    #[default]
220    Endpoint,
221    /// Dispatch only to members of the configured `controller_group`.
222    Controller,
223    /// #492 forward-compat catch-all (a future tier this build can't act on).
224    #[serde(other)]
225    Unknown,
226}
227
228/// GitOps provenance for a repo-managed YAML artifact — a [`Manifest`]
229/// (#678) or a [`Schedule`] (#695). Populated by `kanade job create` /
230/// `kanade schedule create` from the Git context of the source YAML;
231/// the SPA reads it to render Git-managed entries read-only and link
232/// the operator back at the repo. Never consulted by the runtime.
233#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
234pub struct RepoOrigin {
235    /// Repo-relative path of the source YAML — the primary edit target
236    /// the SPA surfaces (e.g. `configs/jobs/foo.yaml`). Forward slashes
237    /// regardless of the authoring OS.
238    pub path: String,
239    /// `origin` remote URL, when the repo has one. Lets the SPA turn
240    /// `path` into a clickable link; `None` for remote-less repos.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub repo: Option<String>,
243    /// Repo-relative path of the `script_file:` a job manifest inlined,
244    /// when it used one — a secondary pointer shown beneath `path`.
245    /// Always `None` for schedules (they carry no script).
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    pub script_file: Option<String>,
248}
249
250/// "Who + how + when-to-stagger" — the fanout-plan side of an exec.
251/// Used both as the POST `/api/exec/{job_id}` body and as the embedded
252/// `target` / `rollout` / `jitter` slot on [`Schedule`]. Centralising
253/// here keeps the validation + serialisation logic in one place.
254#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default)]
255pub struct FanoutPlan {
256    #[serde(default)]
257    pub target: Target,
258    /// Optional wave rollout — when present, the backend publishes
259    /// each wave's group subject on its own delay schedule instead
260    /// of fanning out the `target` block in one go. `target` then
261    /// only labels the deploy for the audit log.
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub rollout: Option<Rollout>,
264    /// Optional humantime jitter; agent uses it to randomise
265    /// execution start. Lives here (not on the script) so different
266    /// schedules / ad-hoc fires of the same job can pick different
267    /// stagger windows.
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub jitter: Option<String>,
270    /// Absolute time the scheduler stamps on each emitted Command
271    /// when this exec was driven by a [`Schedule`] with
272    /// `starting_deadline`. Agents receiving a Command after this
273    /// instant publish a synthetic skipped-result instead of
274    /// running the script. `None` (default) = no deadline / catch
275    /// up whenever delivered. Computed by the scheduler from
276    /// `tick_at + starting_deadline` and overwritten on every fire —
277    /// on a Schedule, setting it by hand is rejected at create time
278    /// (#917, use `starting_deadline`); it remains settable on an
279    /// ad-hoc POST /api/exec body.
280    #[serde(default, skip_serializing_if = "Option::is_none")]
281    pub deadline_at: Option<chrono::DateTime<chrono::Utc>>,
282}
283
284/// Sentinel lines that fence a hint's structured JSON payload inside an
285/// otherwise human-readable job stdout. Each stdout-reading hint
286/// (`inventory:` / `check:` / `collect:`) has its OWN `#KANADE-<KIND>-
287/// BEGIN`/`-END` pair, so one job can carry several of them at once
288/// (and/or a user-facing message) on its single stdout stream — every
289/// consumer extracts only its own block via [`fenced_payload`].
290///
291/// Originated for inventory (#793): a `client:` job couldn't put both a
292/// friendly message and a JSON object on one stdout (the Client App
293/// renders stdout verbatim, the projector needs JSON). #821 generalised
294/// it so inventory / check / collect can coexist. `emit:` is the
295/// exception — its stdout is line-delimited NDJSON consumed whole, so it
296/// never fences and never coexists with the others.
297///
298/// A job carrying a SINGLE hint may still skip the fence —
299/// [`fenced_payload`] falls back to the whole stdout — but a job
300/// COMBINING hints must fence each block (else every consumer would try
301/// to parse the same whole stdout).
302pub const INVENTORY_BLOCK_BEGIN: &str = "#KANADE-INVENTORY-BEGIN";
303/// Closing marker — see [`INVENTORY_BLOCK_BEGIN`].
304pub const INVENTORY_BLOCK_END: &str = "#KANADE-INVENTORY-END";
305/// Check-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
306pub const CHECK_BLOCK_BEGIN: &str = "#KANADE-CHECK-BEGIN";
307/// Check-payload closing marker.
308pub const CHECK_BLOCK_END: &str = "#KANADE-CHECK-END";
309/// Collect-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
310pub const COLLECT_BLOCK_BEGIN: &str = "#KANADE-COLLECT-BEGIN";
311/// Collect-payload closing marker.
312pub const COLLECT_BLOCK_END: &str = "#KANADE-COLLECT-END";
313/// Feed-payload opening marker — see [`INVENTORY_BLOCK_BEGIN`].
314pub const FEED_BLOCK_BEGIN: &str = "#KANADE-FEED-BEGIN";
315/// Feed-payload closing marker.
316pub const FEED_BLOCK_END: &str = "#KANADE-FEED-END";
317
318/// Extract a hint's fenced block when the `begin` marker is present, else
319/// `None`. An unterminated fence (closing marker missing, e.g. truncated
320/// output) takes everything after the opener. Trimmed so surrounding
321/// message text / whitespace never reaches the JSON parser.
322pub fn fenced_payload_if_present<'a>(stdout: &'a str, begin: &str, end: &str) -> Option<&'a str> {
323    let b = find_line_marker(stdout, begin)?;
324    let after = &stdout[b + begin.len()..];
325    let inner = match find_line_marker(after, end) {
326        Some(e) => &after[..e],
327        None => after,
328    };
329    Some(inner.trim())
330}
331
332/// True if stdout carries ANY `#KANADE-<KIND>-BEGIN` fence at a line
333/// start — i.e. the script opted into fenced output. Used to decide
334/// whether a missing fence means "single-hint, use the whole stdout" or
335/// "multi-hint author error / truncation, this hint just has no block".
336pub fn has_any_hint_fence(stdout: &str) -> bool {
337    [
338        INVENTORY_BLOCK_BEGIN,
339        CHECK_BLOCK_BEGIN,
340        COLLECT_BLOCK_BEGIN,
341        FEED_BLOCK_BEGIN,
342    ]
343    .iter()
344    .any(|m| find_line_marker(stdout, m).is_some())
345}
346
347/// Extract one hint's JSON payload from a job's stdout. When the hint's
348/// own `#KANADE-<KIND>` fence is present, return that block. When it's
349/// absent, fall back to the WHOLE stdout only for an unfenced (single-
350/// hint) job; if any OTHER hint's fence is present (#821 multi-hint
351/// output) return `""` instead — the script opted into fences but this
352/// block is missing (author error or truncation), so this consumer must
353/// NOT grab a sibling hint's block. An empty payload fails the consumer's
354/// JSON parse and degrades to "no data for this hint", never cross-parse.
355pub fn fenced_payload<'a>(stdout: &'a str, begin: &str, end: &str) -> &'a str {
356    if let Some(p) = fenced_payload_if_present(stdout, begin, end) {
357        return p;
358    }
359    if has_any_hint_fence(stdout) {
360        ""
361    } else {
362        stdout.trim()
363    }
364}
365
366/// Inventory's fenced payload — [`fenced_payload`] with the inventory
367/// markers. Kept as a named helper for the projector call site.
368pub fn inventory_payload(stdout: &str) -> &str {
369    fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END)
370}
371
372/// Feed's fenced payload — [`fenced_payload`] with the feed markers. Kept as
373/// a named helper for the projector call site.
374pub fn feed_payload(stdout: &str) -> &str {
375    fenced_payload(stdout, FEED_BLOCK_BEGIN, FEED_BLOCK_END)
376}
377
378/// Find `needle` only where it begins a line (start of `hay` or right
379/// after a `\n`). Anchoring to line start means a script echoing the
380/// literal sentinel mid-message (e.g. printing a command name) can't
381/// false-trigger the fence (Claude #793).
382fn find_line_marker(hay: &str, needle: &str) -> Option<usize> {
383    if hay.starts_with(needle) {
384        return Some(0);
385    }
386    hay.find(&format!("\n{needle}")).map(|p| p + 1)
387}
388
389/// Manifest sub-section: how the SPA should render the inventory
390/// facts this job produces. Each field name (`field`) is a top-level
391/// key in the stdout JSON, e.g. `hostname`, `ram_gb`.
392///
393/// Two render modes:
394///   * `display` — vertical "field / value" per PC, used by the
395///     `/inventory?pc=<id>` detail view. ALL columns the operator
396///     wants visible on the detail page.
397///   * `summary` — horizontal table across the fleet (row = PC,
398///     column = field) on `/inventory`. Optional; when omitted the
399///     SPA falls back to `display`, but operators usually want a
400///     trimmer "hostname / OS / CPU / RAM" set for the fleet view.
401#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
402pub struct InventoryHint {
403    /// Detail-view columns, in order.
404    pub display: Vec<DisplayField>,
405    /// Optional fleet-list columns (row = PC). Defaults to `display`
406    /// when omitted, but operators usually pick a 3-5 column subset.
407    #[serde(default, skip_serializing_if = "Option::is_none")]
408    pub summary: Option<Vec<DisplayField>>,
409    /// v0.31 / #40: payload arrays that should be exploded into
410    /// per-element rows of a derived SQLite table. Lets operators
411    /// answer cross-PC questions ("which PCs still have Chrome <
412    /// 120?", "C: >90% full") with normal SQL filters + indexes
413    /// instead of grepping JSON. The projector creates the derived
414    /// table on register and replaces this PC's rows on each result
415    /// (DELETE WHERE pc_id=? AND job_id=? + bulk INSERT). See
416    /// [`ExplodeSpec`] for the per-spec schema.
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub explode: Option<Vec<ExplodeSpec>>,
419    /// v0.35 / #93: top-level scalar fields whose changes the
420    /// projector logs to `inventory_history` (one event per
421    /// changed field per scan). Pairs with `explode[].track_history`
422    /// — that covers array elements; this covers single-valued
423    /// fields like `ram_bytes` / `os_version` / `cpu_model` /
424    /// `os_build` that operators want to track for "did the RAM
425    /// get upgraded?" / "when did Win 11 land on this PC?" /
426    /// "BIOS / firmware bumped?" questions. Field name = `field_path`
427    /// in the history row, `identity_json` is NULL, `before_json`
428    /// / `after_json` each carry `{"value": <prior or new value>}`.
429    /// First-ever observation of a scalar (no prior facts row)
430    /// emits `added`; subsequent value changes emit `changed`. No
431    /// `removed` events — a scalar disappearing from the payload
432    /// is rare and the operator can still see the last value via
433    /// the `before_json` of the most recent change.
434    #[serde(default, skip_serializing_if = "Option::is_none")]
435    pub history_scalars: Option<Vec<String>>,
436}
437
438/// Manifest sub-section (#290): marks a job as an operator-defined
439/// **health check**. Parallel to [`InventoryHint`] / `EmitConfig`.
440/// The stdout contract is a free-form JSON object (same as any
441/// inventory job) from which the agent reads `status_field` /
442/// `detail_field` to build the KLP [`crate::ipc::state::Check`] shown
443/// on the Client App's Health tab.
444///
445/// There is deliberately **no timing field** — when / how often /
446/// in which window a check runs is driven by the job's Schedule,
447/// exactly like inventory jobs, so operators get the full `when:` /
448/// rollout / `runs_on` expressiveness for free.
449///
450/// A check's stdout is a **free-form inventory object** (arbitrary
451/// key/value pairs + arrays) — same as any inventory job — that also
452/// carries a status field. `check:` adds only the health semantics on
453/// top: which field is the ok/warn/fail/unknown status, an optional
454/// one-line summary field, and a remediation job. Everything else
455/// (rich per-PC detail, `explode` sub-tables like a software list) is
456/// driven by a co-present [`InventoryHint`] and rendered with the
457/// SAME display logic the SPA Inventory page uses — on the Client App
458/// too. This keeps checks maximally expressive without a bespoke
459/// payload type.
460#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
461pub struct CheckHint {
462    /// Stable check id → [`Check.name`](crate::ipc::state::Check),
463    /// the SPA/Client React key + analytics label. Unique within the
464    /// fleet's check set. Machine-friendly slug (`disk_space`,
465    /// `defender_rtp`); for the human-facing row title see [`label`].
466    ///
467    /// [`label`]: CheckHint::label
468    pub name: String,
469    /// Optional human-facing display title →
470    /// [`Check.label`](crate::ipc::state::Check). The Client App's
471    /// Health tab and the operator SPA's Compliance page render this
472    /// instead of the [`name`](CheckHint::name) slug when set
473    /// (`"ウイルス対策のリアルタイム保護"` reads better than
474    /// `defender_rtp`). Falls back to the slug when absent, so it's
475    /// purely additive. Author it in the check's language — there's no
476    /// per-locale variant; checks are operator-defined per fleet.
477    #[serde(default, skip_serializing_if = "Option::is_none")]
478    pub label: Option<String>,
479    /// Top-level stdout field whose string value
480    /// (`ok`/`warn`/`fail`/`unknown`) becomes the Health-tab light
481    /// ([`CheckStatus`](crate::ipc::state::CheckStatus)). Defaults to
482    /// `"status"`; a missing / unparseable value → `unknown`.
483    #[serde(default = "default_status_field")]
484    pub status_field: String,
485    /// Top-level stdout field used as the Health-tab row's one-line
486    /// summary. Defaults to `"detail"`; absent in the payload → no
487    /// detail line (the rich breakdown lives in the inventory view).
488    #[serde(default = "default_detail_field")]
489    pub detail_field: String,
490    /// Optional remediation job id →
491    /// [`Check.troubleshoot`](crate::ipc::state::Check). The Client
492    /// App shows a "修復する" button when present; that job must be
493    /// `user_invokable`.
494    #[serde(default, skip_serializing_if = "Option::is_none")]
495    pub troubleshoot: Option<String>,
496    /// #290 PR-E: when `true` (default), the backend also projects this
497    /// check's `status` / `detail` into the `check_status` table so the
498    /// operator SPA gets a fleet-wide compliance view for free — no
499    /// `inventory:` block needed. Set `fleet: false` for a client-only
500    /// check the operator doesn't want surfaced across the fleet.
501    #[serde(default = "default_true")]
502    pub fleet: bool,
503    /// When `true` (default), this check is shown on the Client App's
504    /// Health tab (the end user sees its ok/warn/fail row). Set
505    /// `health: false` for a **gate-only** check — one that exists purely
506    /// to drive a `client.show_when` display gate (e.g. `myapp-up-to-date`)
507    /// and would just be noise as a Health row. The agent still records it
508    /// into `StateSnapshot.checks` (so `show_when` can read it and the gate
509    /// keeps working); only the Client App's Health *rendering* skips it,
510    /// via the [`Check.health_hidden`](crate::ipc::state::Check::health_hidden)
511    /// wire flag. Orthogonal to [`fleet`](CheckHint::fleet): `fleet` gates
512    /// the operator SPA fleet view, `health` gates the end-user Health tab,
513    /// so a pure gate detector typically sets neither (`fleet: false` +
514    /// `health: false`) to stay invisible everywhere while still driving
515    /// the gate.
516    #[serde(default = "default_true")]
517    pub health: bool,
518    /// Optional auto-notification on a compliance transition. When set, the
519    /// backend publishes an end-user notification the moment this check
520    /// transitions *into* one of [`CheckAlert::on`] (e.g. ok → fail) — to
521    /// the failing PC's user and/or operator groups. Fired once per
522    /// transition (not on every poll). Requires `fleet: true` (the alert
523    /// rides the same projection that fills `check_status`).
524    #[serde(default, skip_serializing_if = "Option::is_none")]
525    pub alert: Option<CheckAlert>,
526}
527
528/// Auto-notification rule for a [`CheckHint`] (compliance alerting). When a
529/// check's status transitions into one of [`on`](Self::on), the backend
530/// publishes a notification to the failing PC's user
531/// ([`notify_user`](Self::notify_user)) and/or operator groups
532/// ([`notify_groups`](Self::notify_groups)). Deliberately config-driven:
533/// who gets told, how loud, and the wording all live in the manifest, not
534/// hardcoded in the backend.
535#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
536pub struct CheckAlert {
537    /// Statuses that fire the alert on *transition into* them (a check that
538    /// stays failing doesn't re-alert every poll). Defaults to `[fail]`.
539    /// `ok` is not representable — [`CheckAlertStatus`] has no `Ok` variant,
540    /// so a YAML `on: [ok]` fails to deserialize (before `validate()` is
541    /// even reached); "recovered" notifications are out of scope.
542    #[serde(default = "default_alert_on")]
543    pub on: Vec<CheckAlertStatus>,
544    /// Notify the user(s) on the failing PC (`notifications.pc.<pc_id>`).
545    #[serde(default)]
546    pub notify_user: bool,
547    /// Notify these operator groups (`notifications.group.<name>`).
548    #[serde(default, skip_serializing_if = "Vec::is_empty")]
549    pub notify_groups: Vec<String>,
550    /// Notification priority (colour/label only — toasting is the separate
551    /// `toast` flag). Defaults to `warn`.
552    #[serde(default = "default_alert_priority")]
553    pub priority: crate::ipc::notifications::NotificationPriority,
554    /// Require the recipient to click 確認 to dismiss.
555    #[serde(default)]
556    pub require_ack: bool,
557    /// Surface an OS toast (launches a closed Client App, Action Center
558    /// while locked). Recommended `true` for `notify_user` so a
559    /// non-emergency "your PC is non-compliant" nudge still reaches a user
560    /// whose app is closed.
561    #[serde(default)]
562    pub toast: bool,
563    /// Also send the alert by email, to every address mapped to the
564    /// `notify_groups` (via the `group_contacts` KV, edited on the SPA
565    /// Groups page). Opt-in: defaults to `false`, so an existing alert
566    /// never starts emailing on its own. Requires `notify_groups` to be
567    /// non-empty (there is no per-PC user email) and the backend's
568    /// `[mail]` config to be present; otherwise the email is a logged
569    /// no-op while the in-app/toast notification still fires.
570    #[serde(default)]
571    pub email: bool,
572    /// Notification title (required). May use the same `{…}` placeholders
573    /// as [`body`](Self::body).
574    pub title: String,
575    /// Notification body template. Placeholders: `{pc_id}`, `{name}` (check
576    /// slug), `{label}` (check label, falls back to slug), `{status}`,
577    /// `{detail}` (the check's one-line summary), `{last_logon}` (the PC's
578    /// last sign-in account). Absent → empty body.
579    #[serde(default, skip_serializing_if = "Option::is_none")]
580    pub body: Option<String>,
581}
582
583/// A check status that can trigger a [`CheckAlert`]. Mirrors the
584/// projected `check_status.status` values minus `ok` (alerting on `ok` is
585/// rejected at validation).
586#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash)]
587#[serde(rename_all = "snake_case")]
588pub enum CheckAlertStatus {
589    Warn,
590    Fail,
591    Unknown,
592}
593
594impl CheckAlertStatus {
595    /// The wire string, matching the projected `check_status.status`.
596    pub fn as_str(self) -> &'static str {
597        match self {
598            Self::Warn => "warn",
599            Self::Fail => "fail",
600            Self::Unknown => "unknown",
601        }
602    }
603}
604
605fn default_alert_on() -> Vec<CheckAlertStatus> {
606    vec![CheckAlertStatus::Fail]
607}
608
609fn default_alert_priority() -> crate::ipc::notifications::NotificationPriority {
610    crate::ipc::notifications::NotificationPriority::Warn
611}
612
613fn default_status_field() -> String {
614    "status".to_string()
615}
616
617fn default_detail_field() -> String {
618    "detail".to_string()
619}
620
621fn default_files_field() -> String {
622    "files".to_string()
623}
624
625/// Fallback cap on a collect bundle's total input size when the
626/// manifest's `collect.max_size` is unset. 50 MB (decimal).
627pub const DEFAULT_COLLECT_MAX_SIZE: u64 = 50 * 1_000_000;
628
629/// Manifest sub-section (#219): marks a job as a **file collector** and
630/// carries how the collected bundle presents in the SPA. Parallel to
631/// [`InventoryHint`] / [`CheckHint`] — the block's presence is the
632/// opt-in. The script prints a single JSON object on stdout whose
633/// [`files_field`](CollectHint::files_field) key holds an array of file
634/// paths to bundle (env vars are expanded); the agent zips them and
635/// uploads to `OBJECT_COLLECTIONS`. See [`Manifest::collect`].
636#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
637pub struct CollectHint {
638    /// Operator/end-user-facing title for the collection, shown as the
639    /// bundle's heading on the SPA Collect page (and the Client App row
640    /// when paired with `client:`). Required; validated non-empty.
641    pub name: String,
642    /// Optional one-line description of what the bundle contains.
643    #[serde(default, skip_serializing_if = "Option::is_none")]
644    pub description: Option<String>,
645    /// Human-readable cap on the bundle's total input size
646    /// (`"50MB"`, `"500KB"`, `"1GiB"`). The agent refuses to build a
647    /// bundle whose listed files exceed this. `None` ⇒
648    /// [`DEFAULT_COLLECT_MAX_SIZE`]. Parsed by [`parse_size_bytes`];
649    /// [`Manifest::validate`] rejects an unparseable value at create
650    /// time.
651    ///
652    /// Note: this bounds the **uncompressed** bytes the agent reads off
653    /// disk, not the resulting zip. Text logs compress well, so the
654    /// download is usually much smaller; many tiny files add a little
655    /// per-entry zip overhead. Read it as "how much the agent reads +
656    /// packs", not "the exact download size".
657    #[serde(default, skip_serializing_if = "Option::is_none")]
658    pub max_size: Option<String>,
659    /// Top-level stdout JSON key holding the array of file paths to
660    /// bundle. Defaults to `"files"`.
661    #[serde(default = "default_files_field")]
662    pub files_field: String,
663}
664
665impl CollectHint {
666    /// The effective size cap in bytes — the parsed `max_size` or
667    /// [`DEFAULT_COLLECT_MAX_SIZE`] when unset. Assumes `max_size` (if
668    /// present) already passed [`Manifest::validate`]; falls back to the
669    /// default on a parse error rather than panicking on the fire path.
670    pub fn max_size_bytes(&self) -> u64 {
671        match &self.max_size {
672            Some(s) => parse_size_bytes(s).unwrap_or(DEFAULT_COLLECT_MAX_SIZE),
673            None => DEFAULT_COLLECT_MAX_SIZE,
674        }
675    }
676}
677
678/// Parse a human-readable byte size (`"50MB"`, `"500 KB"`, `"1GiB"`,
679/// `"1024"`). Decimal units (KB/MB/GB) are 1000-based; binary units
680/// (KiB/MiB/GiB) are 1024-based; a bare number (or `B`) is bytes.
681/// Case-insensitive. Shared by `collect.max_size` validation and the
682/// agent's bundle-size enforcement.
683pub fn parse_size_bytes(s: &str) -> Result<u64, String> {
684    let t = s.trim();
685    if t.is_empty() {
686        return Err("size must not be empty".to_string());
687    }
688    let split = t.find(|c: char| !c.is_ascii_digit()).unwrap_or(t.len());
689    let (num_str, unit_raw) = t.split_at(split);
690    if num_str.is_empty() {
691        return Err(format!("size '{s}': missing leading number"));
692    }
693    let num: u64 = num_str
694        .parse()
695        .map_err(|_| format!("size '{s}': bad number '{num_str}'"))?;
696    let mult: u64 = match unit_raw.trim().to_ascii_lowercase().as_str() {
697        "" | "b" => 1,
698        "kb" => 1_000,
699        "mb" => 1_000_000,
700        "gb" => 1_000_000_000,
701        "kib" => 1024,
702        "mib" => 1024 * 1024,
703        "gib" => 1024 * 1024 * 1024,
704        other => {
705            return Err(format!(
706                "size '{s}': unknown unit '{other}' (use B/KB/MB/GB/KiB/MiB/GiB)"
707            ));
708        }
709    };
710    num.checked_mul(mult)
711        .ok_or_else(|| format!("size '{s}': overflow"))
712}
713
714/// Manifest sub-section (#291): marks a job as **user-invokable**
715/// from the Client App and carries how it presents to the end user.
716/// Parallel to [`InventoryHint`] / [`CheckHint`] / `EmitConfig` —
717/// the block's presence is the opt-in (no separate boolean), and its
718/// required fields (`name`, `category`) are enforced by serde at
719/// parse time, so a half-filled catalog entry fails
720/// `kanade job create` instead of rendering a nameless / tab-less row.
721///
722/// The agent maps this 1:1 into the KLP
723/// [`UserInvokableJob`](crate::ipc::jobs::UserInvokableJob) wire shape
724/// that `jobs.list` returns; the Client App renders one row per job in
725/// the tab named by `category`.
726#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
727pub struct ClientHint {
728    /// End-user-facing title for the job row. The operator-internal
729    /// `Manifest::id` slug is rarely what an end user should read, so
730    /// this is required (and validated non-empty by
731    /// [`Manifest::validate`]). Maps to `UserInvokableJob::display_name`.
732    pub name: String,
733    /// Optional one-line subtitle under `name` in the Client App.
734    /// Distinct from the operator-facing top-level
735    /// [`Manifest::description`] — this one is written for the end
736    /// user. Maps to `UserInvokableJob::display_description`.
737    #[serde(default, skip_serializing_if = "Option::is_none")]
738    pub description: Option<String>,
739    /// Which Client App tab the job lives in — a **free-form category
740    /// key** (#792). The Client App renders one tab per distinct key.
741    /// Well-known keys (`software_update`, `troubleshoot`, `catalog`)
742    /// carry built-in tab labels/icons; any other key defines a new tab
743    /// (style it with `category_label` / `category_icon`). Required and
744    /// validated non-empty — without it the agent can't place the job.
745    /// Note: the `software_update` key also drives the agent's
746    /// maintenance / auto-reboot grouping.
747    pub category: String,
748    /// Optional display name for the category's TAB. Set it on (at least
749    /// one of) a custom category's jobs to name the tab; `None` ⇒ a
750    /// built-in default for a well-known key, else the key itself.
751    #[serde(default, skip_serializing_if = "Option::is_none")]
752    pub category_label: Option<String>,
753    /// Optional icon for the category's TAB (lucide name or `data:` URL).
754    /// `None` ⇒ Client App default for the key.
755    #[serde(default, skip_serializing_if = "Option::is_none")]
756    pub category_icon: Option<String>,
757    /// Optional sort order for the TAB; lower sorts first. `None` ⇒
758    /// default (well-known keys keep their familiar order; custom keys
759    /// sort after, then by label).
760    #[serde(default, skip_serializing_if = "Option::is_none")]
761    pub category_order: Option<i64>,
762    /// Optional icon hint for the job ROW — a lucide-react icon name
763    /// or a `data:` URL. `None` ⇒ the Client App falls back to the
764    /// category's icon. Surfaced verbatim in `jobs.list[].icon`.
765    #[serde(default, skip_serializing_if = "Option::is_none")]
766    pub icon: Option<String>,
767    /// Optional visibility scope for the end-user Client App (#816).
768    ///
769    /// `None` ⇒ visible to every PC (current behavior). When set, only
770    /// agents whose `pc_id` / group membership match the [`Target`] list
771    /// the job in `jobs.list` and may run it via KLP `jobs.execute`.
772    ///
773    /// This gates the END-USER surface ONLY. Operators are unaffected:
774    /// `POST /api/exec/{job_id}` (SPA / `kanade exec`) is a separate path
775    /// that never consults `client:`, so an operator can still run the
776    /// job on any PC regardless of `visible_to`. Reuses the schedule
777    /// `Target` shape (`all` / `groups` / `pcs`); a present-but-empty
778    /// target is rejected by [`Manifest::validate`].
779    #[serde(default, skip_serializing_if = "Option::is_none")]
780    pub visible_to: Option<Target>,
781    /// Optional **dynamic display gate** keyed on a health check's result.
782    ///
783    /// `None` ⇒ always listed (current behavior). When set, the agent
784    /// lists the job in `jobs.list` ONLY while the named [`check:`] slug's
785    /// latest result is one of [`ShowWhen::is`]. The canonical use is an
786    /// update action that hides itself once the machine is already current:
787    /// pair the update job with a `check:` that reports `ok` when up to
788    /// date and gate on `is: [fail]`.
789    ///
790    /// Evaluated agent-side at `jobs.list` time against the live
791    /// `StateSnapshot.checks`, which is **keyed by check name** — so the
792    /// detector `check:` and this job may live in *different* manifests and
793    /// still share one slug. Distinct from [`visible_to`](ClientHint::visible_to):
794    /// that gates BOTH listing and `jobs.execute` (an authorization
795    /// boundary); `show_when` gates listing ONLY (a UX hint), so it can't
796    /// cause a list/execute race. New field ⇒ #492 wire rule.
797    ///
798    /// [`check:`]: crate::manifest::CheckHint
799    #[serde(default, skip_serializing_if = "Option::is_none")]
800    pub show_when: Option<ShowWhen>,
801    /// Optional **confirmation-dialog** config for the Client App's 実行
802    /// button.
803    ///
804    /// `None` ⇒ the historical default: the client shows a modal
805    /// confirmation with a built-in 「「{name}」を実行しますか?」 message
806    /// before firing the job (a mis-click guard for a possibly heavy /
807    /// destructive action). When set, the operator controls it:
808    /// - a bare bool — `confirm: false` runs immediately with **no** prompt;
809    ///   `confirm: true` is the same as omitting the block (default message);
810    /// - a struct — `confirm: { message: "…" }` shows the dialog with a
811    ///   custom message (and, redundantly with the scalar, `enabled: false`
812    ///   to suppress it).
813    ///
814    /// Gates the END-USER Client App surface only — the operator `POST
815    /// /api/exec` path never consults `client:`, so an operator-driven run
816    /// is unaffected. New field ⇒ #492 wire rule (`serde(default)` +
817    /// `skip_serializing_if`). Deserializes from bool-or-struct via
818    /// [`de_confirm`]; the JSON schema advertises the struct form (the
819    /// scalar is author ergonomics, like [`ShowWhen::is`]).
820    #[serde(
821        default,
822        deserialize_with = "de_confirm",
823        skip_serializing_if = "Option::is_none"
824    )]
825    pub confirm: Option<ConfirmHint>,
826    /// Optional **unlock scope** — the "裏コマンド" display gate. `None` (the
827    /// overwhelming default) ⇒ the job behaves as it always has. `Some(scope)`
828    /// ⇒ the job is **hidden from `jobs.list`** unless the calling OS user
829    /// currently holds an unlock grant for that scope, obtained by typing the
830    /// operator's secret code into the Client App (`support.unlock`).
831    ///
832    /// The intended use is helpdesk-only actions: a job that has no business
833    /// sitting in an end user's everyday catalog, but which the IT desk can
834    /// surface in seconds while walking that user through a problem — without
835    /// an operator-side exec, which needs SPA access and a correctly-cased
836    /// `pc_id`.
837    ///
838    /// The scope is a free-form slug (`support`, `admin`, …) matched against
839    /// the scopes configured in `ServerSettings::support_codes`, so one
840    /// deployment can run a first-line code and a stronger administrator code
841    /// side by side, each revealing a different set of jobs. A scope with no
842    /// configured code opens for nobody — a typo hides the job rather than
843    /// exposing it.
844    ///
845    /// **Listing only, like [`show_when`](ClientHint::show_when) and unlike
846    /// [`visible_to`](ClientHint::visible_to).** The agent does NOT re-check
847    /// it in `jobs.execute`, which has two consequences worth being explicit
848    /// about:
849    ///
850    /// - Anything the user can see, they can run — no race where the row is
851    ///   visible, the grant lapses, and pressing 実行 fails on a button they
852    ///   were just looking at.
853    /// - It is therefore **not a security boundary**: a standard user who
854    ///   speaks KLP to the agent's pipe directly and knows the job id can
855    ///   still run it. Approval controls for privileged work live on the
856    ///   operator (SPA) exec path; this hides a button, it does not guard a
857    ///   capability.
858    ///
859    /// The operator paths are unaffected in both directions: `POST
860    /// /api/exec/{job_id}` and `kanade exec` never consult `client:`, so an
861    /// operator can run the job on any PC whether or not anyone unlocked it.
862    /// New field ⇒ #492 wire rule (`serde(default)` + `skip_serializing_if`).
863    #[serde(default, skip_serializing_if = "Option::is_none")]
864    pub unlock: Option<String>,
865}
866
867/// Confirmation-dialog config for a [`ClientHint`] — see
868/// [`ClientHint::confirm`]. Controls the Client App's pre-run modal:
869/// whether it appears at all (`enabled`) and what it says (`message`).
870///
871/// Authored as either a bare bool (`confirm: false` / `true`) or a struct
872/// (`confirm: { message: "…" }`); both normalise here via [`de_confirm`].
873#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
874pub struct ConfirmHint {
875    /// Whether the Client App shows the confirmation dialog before running.
876    /// `false` fires the job immediately with no prompt. Defaults to `true`
877    /// (so an author who only sets `message` still gets the dialog, and the
878    /// struct form never accidentally suppresses it).
879    #[serde(default = "default_confirm_enabled")]
880    pub enabled: bool,
881    /// Custom dialog message. `None` ⇒ the client's built-in
882    /// 「「{name}」を実行しますか?」. Only meaningful while `enabled`;
883    /// rejected if present-but-blank by [`Manifest::validate`].
884    #[serde(default, skip_serializing_if = "Option::is_none")]
885    pub message: Option<String>,
886}
887
888/// `enabled` defaults to `true`: the historical behaviour is "always
889/// confirm", so a struct form that omits `enabled` (e.g. sets only
890/// `message`) still shows the dialog.
891fn default_confirm_enabled() -> bool {
892    true
893}
894
895/// Accept either a bare bool (`confirm: false` / `confirm: true`) or a
896/// struct (`confirm: { message: "…" }`) for [`ClientHint::confirm`],
897/// normalising to a [`ConfirmHint`]. The bool is pure author ergonomics —
898/// `false` ⇒ suppress the dialog, `true` ⇒ default message — while the
899/// struct carries a custom message. Called only when the key is present
900/// (absence is handled by `serde(default)` ⇒ `None`). An explicit
901/// `confirm: null` — which the generated schema permits (the field is
902/// `Option`) — maps to `None` too, so it can't produce a parse error;
903/// deserializing through `Option<BoolOrHint>` handles that cleanly (Gemini
904/// #960).
905fn de_confirm<'de, D>(d: D) -> Result<Option<ConfirmHint>, D::Error>
906where
907    D: serde::Deserializer<'de>,
908{
909    #[derive(Deserialize)]
910    #[serde(untagged)]
911    enum BoolOrHint {
912        Bool(bool),
913        Hint(ConfirmHint),
914    }
915    Ok(Option::<BoolOrHint>::deserialize(d)?.map(|b| match b {
916        BoolOrHint::Bool(enabled) => ConfirmHint {
917            enabled,
918            message: None,
919        },
920        BoolOrHint::Hint(h) => h,
921    }))
922}
923
924/// Dynamic display gate for a [`ClientHint`] — see
925/// [`ClientHint::show_when`]. Shows the job only while the named check's
926/// latest status is one of [`is`](ShowWhen::is).
927#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
928pub struct ShowWhen {
929    /// The `check:` slug (a [`CheckHint::name`](crate::manifest::CheckHint::name))
930    /// whose latest status gates this job. May be defined by a *different*
931    /// manifest: checks are keyed by name in the agent's snapshot, so a
932    /// standalone detector job and this one can share a slug. A check that
933    /// has never run (absent from the snapshot) does NOT match — the job
934    /// stays hidden until the detector first reports (fails closed, like
935    /// `visible_to`).
936    pub check: String,
937    /// The check status(es) in which the job is SHOWN. Accepts a single
938    /// status (`is: fail`) or a list (`is: [fail, unknown]`); both
939    /// deserialize to a `Vec`. The `length(min = 1)` schema constraint +
940    /// [`Manifest::validate`] both reject an empty set (it would match
941    /// nothing and silently hide the job) so schema-driven tooling and the
942    /// write path agree.
943    #[serde(deserialize_with = "de_one_or_many_check_status")]
944    #[schemars(length(min = 1))]
945    pub is: Vec<crate::ipc::state::CheckStatus>,
946}
947
948/// Accept either a single `CheckStatus` (`is: fail`) or a sequence
949/// (`is: [fail, unknown]`) for [`ShowWhen::is`], normalising to a `Vec`.
950/// The scalar form is purely author ergonomics; the JSON schema advertises
951/// the canonical array form (`#[schemars(with = ...)]`).
952fn de_one_or_many_check_status<'de, D>(
953    d: D,
954) -> Result<Vec<crate::ipc::state::CheckStatus>, D::Error>
955where
956    D: serde::Deserializer<'de>,
957{
958    use crate::ipc::state::CheckStatus;
959    #[derive(Deserialize)]
960    #[serde(untagged)]
961    enum OneOrMany {
962        One(CheckStatus),
963        Many(Vec<CheckStatus>),
964    }
965    Ok(match OneOrMany::deserialize(d)? {
966        OneOrMany::One(c) => vec![c],
967        OneOrMany::Many(v) => v,
968    })
969}
970
971/// #720 — one widget on the SPA **Analytics** page: a declarative
972/// aggregation over the `obs_events` table. The backend reads these off
973/// `Manifest::aggregate` (from `BUCKET_JOBS`) at query time and builds
974/// the `json_extract` GROUP BY / time-bucket SQL from these generic
975/// primitives, so an operator can chart any emitted event without a Rust
976/// change. The reference shapes are the attendance dashboards
977/// (presence / app_sample / web_visit), but the same DSL covers logon /
978/// reboot / agent-health trends, etc.
979#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
980pub struct AggregateWidget {
981    /// Where this widget surfaces — an Analytics tab and/or a pinned
982    /// Dashboard card. Same block a view's `sql_widgets:` uses, so the
983    /// two widget kinds are authored identically; previously this was a
984    /// flat `dashboard:` + `pin_dashboard:` pair that meant the same
985    /// thing in a different shape.
986    pub placement: Placement,
987    /// Widget heading. Required, validated non-empty.
988    pub title: String,
989    /// Optional one-line subtitle shown muted under the `title` on the
990    /// Analytics page — room for a unit, a caveat, or what the number
991    /// means ("samples × 2 min", "Security 4624 only"). Rejected if
992    /// present-but-blank.
993    #[serde(default, skip_serializing_if = "Option::is_none")]
994    pub description: Option<String>,
995    /// Optional sort weight (#743). Once the order-aware sort lands (PR2)
996    /// widgets render in `(order, dashboard, title)` order, so a lower
997    /// `order` pulls a widget — and its tab — earlier; equal/absent `order`
998    /// falls back to the alphabetical `(dashboard, title)` ordering. Treated
999    /// as `0` when unset, so a fleet with no `order` anywhere stays purely
1000    /// alphabetical (today's behaviour); negatives are allowed to pin
1001    /// something first. (This field only carries the value; the backend
1002    /// applies it.)
1003    #[serde(default, skip_serializing_if = "Option::is_none")]
1004    pub order: Option<i32>,
1005    /// `pc` rolls up a single selected PC; `fleet` rolls up all PCs
1006    /// (and unlocks `group_by: pc_id` to rank PCs against each other).
1007    /// Defaults to `pc`.
1008    #[serde(default)]
1009    pub scope: AggregateScope,
1010    /// `obs_events.kind` this widget reads (e.g. `app_sample`,
1011    /// `presence`, `unexpected_shutdown`). Required for every aggregation
1012    /// render (`bar`/`gauge`/`timeline`/`stat`); rejected for
1013    /// `op_timeline`, which reconstructs a fixed multi-kind operational
1014    /// swimlane (power/session/sleep) baked into the SPA and so reads no
1015    /// single `kind`.
1016    #[serde(default, skip_serializing_if = "Option::is_none")]
1017    pub kind: Option<String>,
1018    /// Optional `obs_events.source` filter, when one `kind` is emitted by
1019    /// more than one collector.
1020    #[serde(default, skip_serializing_if = "Option::is_none")]
1021    pub source: Option<String>,
1022    /// How to roll the matching events up. See [`AggregateAgg`]. Required
1023    /// for every aggregation render; rejected for `op_timeline` (which
1024    /// performs no rollup — it returns the raw operational events and the
1025    /// SPA folds them into lane spans).
1026    #[serde(default, skip_serializing_if = "Option::is_none")]
1027    pub agg: Option<AggregateAgg>,
1028    /// Dotted JSON path (no `$.` prefix) to group by for `agg: count` /
1029    /// `sum` — e.g. `foreground.app`. The literal `pc_id` is special:
1030    /// it groups by the `pc_id` column (fleet ranking), not a payload
1031    /// field. Omit for a single total. Required when `agg: sum` needs a
1032    /// breakdown; for `agg: count` omitting it yields the grand total.
1033    #[serde(default, skip_serializing_if = "Option::is_none")]
1034    pub group_by: Option<String>,
1035    /// Dotted JSON path to a boolean for `agg: ratio` (e.g. `active`):
1036    /// the widget reports `true_count / total`. Required when `agg: ratio`.
1037    #[serde(default, skip_serializing_if = "Option::is_none")]
1038    pub bool_path: Option<String>,
1039    /// Dotted JSON path to a number for `agg: sum`. Required when `agg: sum`.
1040    #[serde(default, skip_serializing_if = "Option::is_none")]
1041    pub value_path: Option<String>,
1042    /// Optional value transform applied before grouping. Currently only
1043    /// `host` (parse a URL down to its host) — used by the top-sites
1044    /// widget, where SQLite can't parse a URL so the backend does it in
1045    /// Rust. See [`AggregateTransform`].
1046    #[serde(default, skip_serializing_if = "Option::is_none")]
1047    pub transform: Option<AggregateTransform>,
1048    /// Optional sampling cadence in minutes. When set, a `count` is also
1049    /// reported as estimated time (`count × sample_minutes`) — e.g. a
1050    /// 2-minute app sampler turns 11 samples into ~22 minutes. Must be ≥ 1.
1051    #[serde(default, skip_serializing_if = "Option::is_none")]
1052    #[schemars(range(min = 1))]
1053    pub sample_minutes: Option<u32>,
1054    /// Grouped values to drop from the rollup (e.g. `["LockApp"]` so the
1055    /// lock screen doesn't top the app ranking). Empty by default.
1056    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1057    pub exclude: Vec<String>,
1058    /// Optional time bucketing — `hour` buckets events by local
1059    /// hour-of-day for a `timeline` render. See [`AggregateTimeBucket`].
1060    #[serde(default, skip_serializing_if = "Option::is_none")]
1061    pub time_bucket: Option<AggregateTimeBucket>,
1062    /// Top-N cap for grouped renders (`bar`). Defaults to 10 when unset.
1063    #[serde(default, skip_serializing_if = "Option::is_none")]
1064    #[schemars(range(min = 1))]
1065    pub limit: Option<u32>,
1066    /// Which widget the SPA draws. See [`AggregateRender`].
1067    pub render: AggregateRender,
1068}
1069
1070/// How much of the widget grid a widget asks for (#1257).
1071///
1072/// Both the Analytics page and the Dashboard's pinned strip lay widgets
1073/// out two-up on a wide screen. Until this existed, the width was
1074/// decided purely by `render`: `bar` / `timeline` / `op_timeline` /
1075/// `table` always claimed the full row, everything else a single
1076/// column. That is a sensible default but a bad rule — an operator who
1077/// pins two `bar` widgets that answer the same question (app usage
1078/// alongside browsing, say) cannot put them side by side, and each
1079/// pushes the rest of the page further down.
1080///
1081/// Absent ⇒ keep the per-`render` default, so every existing manifest
1082/// renders exactly as before.
1083#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1084#[serde(rename_all = "lowercase")]
1085#[non_exhaustive]
1086pub enum WidgetWidth {
1087    /// Span the whole widget row.
1088    Full,
1089    /// Take one column, so a sibling can share the row.
1090    Half,
1091    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1092    /// Rendered as if unset — a width hint is presentation-only, so an
1093    /// unreadable variant must not drop the widget.
1094    #[serde(other)]
1095    Unknown,
1096}
1097
1098/// Per-PC vs fleet-wide rollup for an [`AggregateWidget`].
1099#[derive(
1100    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
1101)]
1102#[serde(rename_all = "lowercase")]
1103#[non_exhaustive]
1104pub enum AggregateScope {
1105    /// Roll up the single PC the operator selected. The default.
1106    #[default]
1107    Pc,
1108    /// Roll up across every PC. Unlocks `group_by: pc_id`.
1109    Fleet,
1110    /// #492 forward-compat catch-all — a Manifest is read fleet-wide, so
1111    /// an older reader must tolerate a future variant rather than failing
1112    /// to decode the whole job. The backend skips an `Unknown` widget.
1113    #[serde(other)]
1114    Unknown,
1115}
1116
1117/// The rollup function for an [`AggregateWidget`].
1118#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1119#[serde(rename_all = "lowercase")]
1120#[non_exhaustive]
1121pub enum AggregateAgg {
1122    /// Row count, optionally grouped (`group_by`) and time-estimated
1123    /// (`sample_minutes`).
1124    Count,
1125    /// `true_count / total` over `bool_path`.
1126    Ratio,
1127    /// Sum of `value_path`, optionally grouped.
1128    Sum,
1129    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1130    #[serde(other)]
1131    Unknown,
1132}
1133
1134/// Optional pre-grouping value transform for an [`AggregateWidget`].
1135#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1136#[serde(rename_all = "lowercase")]
1137#[non_exhaustive]
1138pub enum AggregateTransform {
1139    /// Parse the grouped value as a URL and keep only its host.
1140    Host,
1141    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1142    #[serde(other)]
1143    Unknown,
1144}
1145
1146/// Time bucketing for an [`AggregateWidget`] (drives a `timeline`).
1147#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1148#[serde(rename_all = "lowercase")]
1149#[non_exhaustive]
1150pub enum AggregateTimeBucket {
1151    /// Bucket by local hour-of-day (0–23), summed over the window.
1152    Hour,
1153    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1154    #[serde(other)]
1155    Unknown,
1156}
1157
1158/// Which visual the SPA renders an [`AggregateWidget`] as.
1159#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
1160#[serde(rename_all = "lowercase")]
1161#[non_exhaustive]
1162pub enum AggregateRender {
1163    /// Ranked horizontal bars (a grouped `count` / `sum`).
1164    Bar,
1165    /// A single ratio dial (`agg: ratio`).
1166    Gauge,
1167    /// 24-hour activity strip (`time_bucket: hour`).
1168    Timeline,
1169    /// A single headline number (an ungrouped total).
1170    Stat,
1171    /// Per-PC operational swimlane (power / session / sleep) reconstructed
1172    /// from a fixed multi-kind event set. Unlike the aggregation renders it
1173    /// reads no single `kind`/`agg`: the backend returns the raw events in
1174    /// the window and the SPA folds them into lane spans (shared with the
1175    /// Events page strip). Per-PC only (`scope: pc`).
1176    #[serde(rename = "op_timeline")]
1177    OpTimeline,
1178    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1179    #[serde(other)]
1180    Unknown,
1181}
1182
1183/// True if `p` is a well-formed dotted JSON path of `[A-Za-z0-9_]`
1184/// segments joined by single dots — the shape safe to bind into
1185/// `json_extract(payload, '$.' || ?)`. The charset blocks injection; the
1186/// segment check additionally rejects `"."`, `".foo"`, `"foo."`,
1187/// `"foo..bar"`, which would pass the charset but produce a malformed
1188/// `$.` path that errors at query time. Accepts `pc_id`, `foreground.app`,
1189/// `active`, etc.
1190fn is_valid_json_path(p: &str) -> bool {
1191    !p.is_empty()
1192        && p.split('.').all(|seg| {
1193            !seg.is_empty() && seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
1194        })
1195}
1196
1197/// Per-widget validation for a list of [`AggregateWidget`]s — shared by
1198/// the `aggregate:` job hint ([`Manifest::validate`]) and the standalone
1199/// [`View`] resource (#743) so the two can't diverge. `field` names the
1200/// containing key for error messages (`"aggregate"` or `"widgets"`).
1201///
1202/// Enforces: non-empty list; non-empty dashboard/title (and `kind`/`agg`
1203/// for every aggregation render); a blank-when-set `source`; rejection of
1204/// any #492 `Unknown` enum (an operator typo at create time); safe dotted
1205/// JSON paths; the value path each `agg` needs (and rejection of mis-paired
1206/// ones); `pc_id` grouping only in `fleet` scope; `transform`/`limit`/
1207/// `exclude` only with a `group_by`; positive `limit`/`sample_minutes`;
1208/// `gauge`⇔`ratio`; and `timeline`⇔`time_bucket`. A `render: op_timeline`
1209/// widget is validated separately (per-PC, no aggregation knobs) — see
1210/// [`validate_op_timeline_widget`].
1211pub fn validate_aggregate_widgets(widgets: &[AggregateWidget], field: &str) -> Result<(), String> {
1212    if widgets.is_empty() {
1213        return Err(format!(
1214            "`{field}:` must list at least one widget when present"
1215        ));
1216    }
1217    for (i, w) in widgets.iter().enumerate() {
1218        let at = format!("{field}[{i}]");
1219        if w.title.trim().is_empty() {
1220            return Err(format!("{at}.title must not be empty"));
1221        }
1222        // Same rule the SQL widgets get: a widget that is neither on a
1223        // tab nor pinned renders nowhere, which is never what was meant.
1224        validate_placement(&w.placement, &at)?;
1225        // A present-but-blank `description` renders an empty muted line —
1226        // reject it so the subtitle only shows when it says something.
1227        if let Some(description) = &w.description {
1228            if description.trim().is_empty() {
1229                return Err(format!("{at}.description must not be empty when set"));
1230            }
1231        }
1232        // Reject values that fell through to the #492 `Unknown` catch-all:
1233        // at create time on the current version that's an operator typo. (A
1234        // genuinely-future variant only reaches an older reader via a stored
1235        // resource, which is never re-validated, so forward-compat holds.)
1236        if w.scope == AggregateScope::Unknown {
1237            return Err(format!("{at}.scope is not a known value (pc | fleet)"));
1238        }
1239        if w.render == AggregateRender::Unknown {
1240            return Err(format!(
1241                "{at}.render is not a known value (bar | gauge | timeline | stat | op_timeline)"
1242            ));
1243        }
1244        // `op_timeline` reconstructs a fixed per-PC operational swimlane
1245        // (power/session/sleep) from a baked-in multi-kind set — it uses none
1246        // of the aggregation knobs, so validate it on its own terms (per-PC,
1247        // no `kind`/`agg`/grouping) and skip the rollup rules below.
1248        if w.render == AggregateRender::OpTimeline {
1249            validate_op_timeline_widget(w, &at)?;
1250            continue;
1251        }
1252        // Every other render is an aggregation over a single `kind`.
1253        if w.kind.as_deref().map(str::trim).unwrap_or("").is_empty() {
1254            return Err(format!("{at}.kind must not be empty"));
1255        }
1256        let agg = match w.agg {
1257            Some(AggregateAgg::Unknown) => {
1258                return Err(format!(
1259                    "{at}.agg is not a known value (count | ratio | sum)"
1260                ));
1261            }
1262            Some(agg) => agg,
1263            None => return Err(format!("{at}.agg is required")),
1264        };
1265        // A present-but-blank `source` is a no-op filter — reject like the
1266        // other blank-when-set guards.
1267        if let Some(source) = &w.source {
1268            if source.trim().is_empty() {
1269                return Err(format!("{at}.source must not be empty when set"));
1270            }
1271        }
1272        if w.transform == Some(AggregateTransform::Unknown) {
1273            return Err(format!("{at}.transform is not a known value (host)"));
1274        }
1275        if w.time_bucket == Some(AggregateTimeBucket::Unknown) {
1276            return Err(format!("{at}.time_bucket is not a known value (hour)"));
1277        }
1278        for (label, path) in [
1279            ("group_by", &w.group_by),
1280            ("bool_path", &w.bool_path),
1281            ("value_path", &w.value_path),
1282        ] {
1283            if let Some(p) = path {
1284                if !is_valid_json_path(p) {
1285                    return Err(format!(
1286                        "{at}.{label} '{p}' must be a dotted JSON path of [A-Za-z0-9_] segments"
1287                    ));
1288                }
1289            }
1290        }
1291        // Each agg uses exactly one value path; reject a mis-paired path so
1292        // a typo fails at create rather than being ignored.
1293        match agg {
1294            // count: grouped → ranking, ungrouped → grand total.
1295            AggregateAgg::Count => {
1296                for (label, path) in [("bool_path", &w.bool_path), ("value_path", &w.value_path)] {
1297                    if path.is_some() {
1298                        return Err(format!("{at}.agg=count does not use `{label}`"));
1299                    }
1300                }
1301            }
1302            AggregateAgg::Ratio => {
1303                if w.bool_path.is_none() {
1304                    return Err(format!("{at}.agg=ratio requires `bool_path`"));
1305                }
1306                if w.value_path.is_some() {
1307                    return Err(format!("{at}.agg=ratio does not use `value_path`"));
1308                }
1309            }
1310            AggregateAgg::Sum => {
1311                if w.value_path.is_none() {
1312                    return Err(format!("{at}.agg=sum requires `value_path`"));
1313                }
1314                if w.bool_path.is_some() {
1315                    return Err(format!("{at}.agg=sum does not use `bool_path`"));
1316                }
1317            }
1318            // Rejected above; arm exists only for exhaustiveness.
1319            AggregateAgg::Unknown => {}
1320        }
1321        // Ranking PCs against each other only means something across the
1322        // fleet — within one PC it's a single bar.
1323        if w.group_by.as_deref() == Some("pc_id") && w.scope != AggregateScope::Fleet {
1324            return Err(format!(
1325                "{at}.group_by: pc_id is only valid with scope: fleet"
1326            ));
1327        }
1328        // `transform` rewrites the grouped PAYLOAD value (URL→host); it's
1329        // meaningless on a `pc_id` grouping (the pc_id column, not a payload
1330        // field), so reject the combo at create time.
1331        if w.transform.is_some() && w.group_by.as_deref() == Some("pc_id") {
1332            return Err(format!("{at}.transform is not valid with group_by: pc_id"));
1333        }
1334        // limit / transform / exclude all operate on grouped values, so
1335        // without a `group_by` they're silent no-ops — reject.
1336        if w.group_by.is_none() {
1337            if w.limit.is_some() {
1338                return Err(format!("{at}.limit requires `group_by`"));
1339            }
1340            if w.transform.is_some() {
1341                return Err(format!("{at}.transform requires `group_by`"));
1342            }
1343            if !w.exclude.is_empty() {
1344                return Err(format!("{at}.exclude requires `group_by`"));
1345            }
1346        }
1347        if w.limit == Some(0) {
1348            return Err(format!("{at}.limit must be > 0"));
1349        }
1350        if w.sample_minutes == Some(0) {
1351            return Err(format!("{at}.sample_minutes must be > 0"));
1352        }
1353        for ex in &w.exclude {
1354            if ex.trim().is_empty() {
1355                return Err(format!("{at}.exclude must not contain empty entries"));
1356            }
1357        }
1358        // A gauge draws a single ratio dial — only meaningful for agg: ratio.
1359        if w.render == AggregateRender::Gauge && agg != AggregateAgg::Ratio {
1360            return Err(format!("{at}.render=gauge is only valid with agg: ratio"));
1361        }
1362        // A timeline needs a bucket; a bucket on any other render is a no-op
1363        // that signals operator confusion — reject both.
1364        match (w.render, &w.time_bucket) {
1365            (AggregateRender::Timeline, None) => {
1366                return Err(format!("{at}.render=timeline requires `time_bucket`"));
1367            }
1368            (r, Some(_)) if r != AggregateRender::Timeline => {
1369                return Err(format!(
1370                    "{at}.time_bucket is only valid with render: timeline"
1371                ));
1372            }
1373            _ => {}
1374        }
1375    }
1376    Ok(())
1377}
1378
1379/// Validate a `render: op_timeline` widget. It draws a fixed per-PC
1380/// operational swimlane (power / session / sleep) reconstructed by the SPA
1381/// from a baked-in multi-kind event set, so it uses none of the aggregation
1382/// knobs: require `scope: pc` and reject every field that only makes sense
1383/// for a rollup (`kind`/`source`/`agg`/`group_by`/`bool_path`/`value_path`/
1384/// `transform`/`sample_minutes`/`exclude`/`time_bucket`/`limit`). Rejecting
1385/// the unused fields (rather than ignoring them) keeps an operator typo from
1386/// silently doing nothing, matching the rest of this validator.
1387fn validate_op_timeline_widget(w: &AggregateWidget, at: &str) -> Result<(), String> {
1388    // Per-PC only: a fleet-wide swimlane of every PC's spans is unbounded
1389    // and unreadable, and the backend only computes it in per-PC scope.
1390    if w.scope != AggregateScope::Pc {
1391        return Err(format!("{at}.render=op_timeline requires scope: pc"));
1392    }
1393    // Each unused field, with the name the operator wrote, so the error
1394    // points at exactly what to delete.
1395    if w.kind.is_some() {
1396        return Err(format!("{at}.render=op_timeline does not use `kind`"));
1397    }
1398    if w.source.is_some() {
1399        return Err(format!("{at}.render=op_timeline does not use `source`"));
1400    }
1401    if w.agg.is_some() {
1402        return Err(format!("{at}.render=op_timeline does not use `agg`"));
1403    }
1404    for (label, set) in [
1405        ("group_by", w.group_by.is_some()),
1406        ("bool_path", w.bool_path.is_some()),
1407        ("value_path", w.value_path.is_some()),
1408        ("transform", w.transform.is_some()),
1409        ("sample_minutes", w.sample_minutes.is_some()),
1410        ("time_bucket", w.time_bucket.is_some()),
1411        ("limit", w.limit.is_some()),
1412        ("exclude", !w.exclude.is_empty()),
1413    ] {
1414        if set {
1415            return Err(format!("{at}.render=op_timeline does not use `{label}`"));
1416        }
1417    }
1418    Ok(())
1419}
1420
1421/// Default materialization cadence for a [`SqlWidget`] whose `refresh` is
1422/// unset — 1 hour. A view over feed/inventory tables changes only as fast as
1423/// its underlying feed refresh (often daily), so an hour is fresh enough while
1424/// keeping an expensive correlation join off the ~30s Dashboard poll path.
1425pub const DEFAULT_VIEW_REFRESH: std::time::Duration = std::time::Duration::from_secs(3600);
1426
1427/// #vuln-roadmap PR3: a **SQL-backed, materialized** widget on a [`View`].
1428///
1429/// Where an [`AggregateWidget`] encodes an `obs_events` rollup in structured
1430/// YAML fields, a `SqlWidget` carries a raw read-only `SELECT`/`WITH` over the
1431/// projector's tables (inventory `explode:` tables, `feeds`, `check_status`,
1432/// …) — the correlation that powers a vulnerability / EOL / license dashboard
1433/// is just a `JOIN`, far more expressive than a YAML DSL. The backend runs the
1434/// query in the read-only sandbox (`api::query`), caches the result on the
1435/// `refresh` cadence, and maps it to the same render-ready shape the existing
1436/// widget components consume, via [`RenderSpec`]. See [`View::sql_widgets`].
1437#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1438pub struct SqlWidget {
1439    /// Widget heading. Required, validated non-empty.
1440    pub title: String,
1441    /// Optional muted subtitle (a unit, a caveat). Rejected if present-blank.
1442    #[serde(default, skip_serializing_if = "Option::is_none")]
1443    pub description: Option<String>,
1444    /// The read-only SQL. Executed in the `api::query` sandbox: a single
1445    /// `SELECT`/`WITH` on a `SQLITE_OPEN_READONLY` connection, row-capped and
1446    /// time-bounded. The backend validates it read-only at `view create` and
1447    /// again at run time; a write verb / stacked statement is rejected.
1448    pub query: String,
1449    /// How the query's result columns map to a visual — see [`RenderSpec`].
1450    pub render: RenderSpec,
1451    /// Materialization cadence as a humantime duration (`"6h"`, `"30m"`).
1452    /// Absent ⇒ [`DEFAULT_VIEW_REFRESH`]. The backend re-runs the query at
1453    /// most this often; reads in between hit the cache.
1454    #[serde(default, skip_serializing_if = "Option::is_none")]
1455    pub refresh: Option<String>,
1456    /// Where the widget surfaces — an Analytics tab and/or a pinned Dashboard
1457    /// card. At least one must be set (else it renders nowhere).
1458    pub placement: Placement,
1459}
1460
1461impl SqlWidget {
1462    /// The effective refresh cadence — the parsed `refresh` or
1463    /// [`DEFAULT_VIEW_REFRESH`]. Falls back to the default on an unparseable
1464    /// value rather than panicking on the read path (validation already
1465    /// rejected a bad value at `view create`).
1466    pub fn refresh_interval(&self) -> std::time::Duration {
1467        self.refresh
1468            .as_deref()
1469            .and_then(|s| humantime::parse_duration(s).ok())
1470            .unwrap_or(DEFAULT_VIEW_REFRESH)
1471    }
1472}
1473
1474/// How a [`SqlWidget`]'s SQL result columns map onto a visual. A `kind` names
1475/// the chart; the channel fields (`value`, `label`, `columns`, …) name which
1476/// result columns feed it. Only the channels a `kind` uses are read; the
1477/// backend validates the named columns exist in the result. New chart types
1478/// are "one renderer + the same mapping", so this stays a flat, additive shape.
1479#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Hash)]
1480pub struct RenderSpec {
1481    /// Which visual to render the result as.
1482    pub kind: RenderKind,
1483    /// `table` only: the columns to show, in order. Absent ⇒ every result
1484    /// column (the universal default).
1485    #[serde(default, skip_serializing_if = "Option::is_none")]
1486    pub columns: Option<Vec<String>>,
1487    /// `table` only: optional per-column header relabelling (result column →
1488    /// display name). Columns not listed keep their SQL name.
1489    #[serde(default, skip_serializing_if = "Option::is_none")]
1490    pub labels: Option<std::collections::BTreeMap<String, String>>,
1491    /// `stat` / `bar` / `pie` / `gauge`: the result column holding the numeric
1492    /// value (`stat`/`gauge` read the first row; `bar`/`pie` read every row).
1493    #[serde(default, skip_serializing_if = "Option::is_none")]
1494    pub value: Option<String>,
1495    /// `bar` / `pie`: the result column holding each row's category label.
1496    #[serde(default, skip_serializing_if = "Option::is_none")]
1497    pub label: Option<String>,
1498    /// `bar` / `pie`: keep only the top-N rows (by value). Absent ⇒ all rows.
1499    #[serde(default, skip_serializing_if = "Option::is_none")]
1500    pub limit: Option<u32>,
1501    /// `pie` only: render as a donut (a hole with the total in the centre).
1502    #[serde(default, skip_serializing_if = "Option::is_none")]
1503    pub donut: Option<bool>,
1504    /// `gauge` only: the numerator column (paired with `den`). Alternative to
1505    /// a precomputed `value` ratio.
1506    #[serde(default, skip_serializing_if = "Option::is_none")]
1507    pub num: Option<String>,
1508    /// `gauge` only: the denominator column (paired with `num`).
1509    #[serde(default, skip_serializing_if = "Option::is_none")]
1510    pub den: Option<String>,
1511}
1512
1513/// The chart kind for a [`RenderSpec`]. `table` and `pie` are new in PR3; the
1514/// rest reuse the existing `obs_events` widget renderers.
1515#[derive(
1516    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash, Default,
1517)]
1518#[serde(rename_all = "lowercase")]
1519pub enum RenderKind {
1520    /// The full result grid (new renderer). The universal default.
1521    #[default]
1522    Table,
1523    /// A single headline number from the first row's `value` cell.
1524    Stat,
1525    /// Ranked horizontal bars — `label` + `value` per row, optional top-N.
1526    Bar,
1527    /// Parts-of-a-whole (new renderer) — `label` + `value` per row.
1528    Pie,
1529    /// A ratio dial — a `value` ratio, or a `num`/`den` pair.
1530    Gauge,
1531    /// #492 forward-compat catch-all (see [`AggregateScope::Unknown`]).
1532    #[serde(other)]
1533    Unknown,
1534}
1535
1536/// Where a widget surfaces in the SPA — an Analytics tab and/or a pinned
1537/// Dashboard card. Shared verbatim by both widget kinds: a job's
1538/// [`AggregateWidget`] and a view's [`SqlWidget`] are authored the same
1539/// way. (#1257 folded the aggregate side's flat `dashboard:` +
1540/// `pin_dashboard:` pair into this block; expressing one idea in two
1541/// shapes meant a width had to be invented twice.)
1542#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1543pub struct Placement {
1544    /// The Analytics tab this widget groups under. Absent ⇒ not shown on
1545    /// the Analytics page.
1546    ///
1547    /// Written either as a bare tab name or as a block, so the common
1548    /// case stays one line and a width is there when it's wanted:
1549    ///
1550    /// ```yaml
1551    /// analytics: app-usage
1552    /// # or
1553    /// analytics: { tab: app-usage, width: half }
1554    /// ```
1555    #[serde(
1556        default,
1557        deserialize_with = "de_analytics",
1558        skip_serializing_if = "Option::is_none"
1559    )]
1560    #[schemars(with = "Option<AnalyticsPlacementSchema>")]
1561    pub analytics: Option<AnalyticsPlacement>,
1562    /// Promote to the main Dashboard (reuses #900's pinned section). Absent ⇒
1563    /// not pinned.
1564    #[serde(default, skip_serializing_if = "Option::is_none")]
1565    pub dashboard: Option<DashboardPlacement>,
1566}
1567
1568impl Placement {
1569    /// True when the widget is pinned to the main Dashboard.
1570    pub fn is_pinned(&self) -> bool {
1571        self.dashboard.as_ref().is_some_and(|d| d.pin)
1572    }
1573    /// The Analytics tab name, or a fallback so a dashboard-only widget still
1574    /// carries a group label for the shared widget list.
1575    pub fn tab(&self) -> &str {
1576        self.analytics
1577            .as_ref()
1578            .map_or("Dashboard", |a| a.tab.as_str())
1579    }
1580    /// Width to render at on the surface being served. The two surfaces
1581    /// are independent: the Dashboard's pinned strip is a summary where
1582    /// two full-width widgets push everything else below the fold, while
1583    /// an Analytics tab gives the widget the room and usually wants the
1584    /// per-`render` default.
1585    pub fn width_for(&self, pinned: bool) -> Option<WidgetWidth> {
1586        if pinned {
1587            self.dashboard.as_ref().and_then(|d| d.width)
1588        } else {
1589            self.analytics.as_ref().and_then(|a| a.width)
1590        }
1591    }
1592}
1593
1594/// The `placement.analytics` block — see [`Placement::analytics`].
1595///
1596/// Deserialized from a bare string as well as a map, so
1597/// `analytics: app-usage` and `analytics: { tab: app-usage, width: half }`
1598/// both work. Serialized back as a bare string whenever no `width` is set,
1599/// which keeps the stored resource JSON in its terse form for every
1600/// widget that doesn't ask for a width — i.e. almost all of them.
1601#[derive(Deserialize, schemars::JsonSchema, Debug, Clone)]
1602pub struct AnalyticsPlacement {
1603    /// Tab this widget groups under. Widgets from every job/view are
1604    /// collected and grouped by this label, so the same string across
1605    /// sources builds one multi-source dashboard.
1606    pub tab: String,
1607    /// How much of the Analytics row this widget takes (#1257). Absent ⇒
1608    /// the per-`render` default.
1609    #[serde(default, skip_serializing_if = "Option::is_none")]
1610    pub width: Option<WidgetWidth>,
1611}
1612
1613impl Serialize for AnalyticsPlacement {
1614    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1615        match self.width {
1616            None => s.serialize_str(&self.tab),
1617            Some(width) => {
1618                use serde::ser::SerializeStruct;
1619                let mut st = s.serialize_struct("AnalyticsPlacement", 2)?;
1620                st.serialize_field("tab", &self.tab)?;
1621                st.serialize_field("width", &width)?;
1622                st.end()
1623            }
1624        }
1625    }
1626}
1627
1628/// Schema-only mirror of the two shapes [`de_analytics`] accepts.
1629///
1630/// Needed because the generated schema is what the SPA's YAML editor
1631/// validates against. Pointing `schemars` at [`AnalyticsPlacement`]
1632/// directly advertises only the block form, which would put a red
1633/// squiggle under `analytics: app-usage` — the bare-string form every
1634/// widget in `configs/` actually uses, and the one the field
1635/// serializes back to. The deserializer would still accept it; the
1636/// operator would just be told, in the editor we ship, that correct
1637/// config is wrong.
1638///
1639/// (Contrast [`ConfirmHint`], where the scalar really is a rarely-used
1640/// shorthand for the canonical struct, so advertising the struct alone
1641/// is a reasonable trade. Here the scalar is the canonical form.)
1642#[derive(schemars::JsonSchema)]
1643#[serde(untagged)]
1644#[allow(dead_code)] // constructed only by `schemars`, never at run time
1645enum AnalyticsPlacementSchema {
1646    /// `analytics: app-usage`
1647    Tab(String),
1648    /// `analytics: { tab: app-usage, width: half }`
1649    Block(AnalyticsPlacement),
1650}
1651
1652/// Reads [`Placement::analytics`] from either a bare tab name or a block.
1653/// An explicit `analytics: null` maps to `None` rather than erroring, the
1654/// same way [`de_confirm`] handles it.
1655fn de_analytics<'de, D>(d: D) -> Result<Option<AnalyticsPlacement>, D::Error>
1656where
1657    D: serde::Deserializer<'de>,
1658{
1659    #[derive(Deserialize)]
1660    #[serde(untagged)]
1661    enum StrOrBlock {
1662        Tab(String),
1663        Block(AnalyticsPlacement),
1664    }
1665    Ok(Option::<StrOrBlock>::deserialize(d)?.map(|v| match v {
1666        StrOrBlock::Tab(tab) => AnalyticsPlacement { tab, width: None },
1667        StrOrBlock::Block(b) => b,
1668    }))
1669}
1670
1671/// The `placement.dashboard` block — see [`Placement::dashboard`].
1672#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1673pub struct DashboardPlacement {
1674    /// Pin this widget to the main Dashboard's promoted section.
1675    #[serde(default)]
1676    pub pin: bool,
1677    /// How much of the Dashboard's pinned row this widget takes (#1257).
1678    /// Absent ⇒ the per-`render` default. See [`WidgetWidth`].
1679    ///
1680    /// Nested under `dashboard` on purpose: the Dashboard's pinned strip
1681    /// is a summary where two full-width widgets push everything else
1682    /// below the fold, while the Analytics page gives a widget the tab to
1683    /// itself and wants the default. Living here says "Dashboard only"
1684    /// structurally, instead of needing a `pin_`-prefixed name to say it.
1685    /// An `analytics` width can be added later by promoting that field to
1686    /// a string-or-block, without disturbing this one.
1687    #[serde(default, skip_serializing_if = "Option::is_none")]
1688    pub width: Option<WidgetWidth>,
1689}
1690
1691/// Shared placement rules for both widget kinds. `at` names the widget
1692/// for error messages.
1693///
1694/// A widget that surfaces nowhere is an invisible no-op. A `dashboard:`
1695/// block with `pin: false` doesn't count — it pins nowhere — so gate on
1696/// the effective pin, not the block's presence (Gemini / CodeRabbit).
1697pub fn validate_placement(p: &Placement, at: &str) -> Result<(), String> {
1698    if p.analytics.is_none() && !p.is_pinned() {
1699        return Err(format!(
1700            "{at}.placement must set `analytics` and/or pin to `dashboard` (else the widget renders nowhere)"
1701        ));
1702    }
1703    if let Some(a) = &p.analytics {
1704        if a.tab.trim().is_empty() {
1705            return Err(format!(
1706                "{at}.placement.analytics must not be empty when set"
1707            ));
1708        }
1709    }
1710    Ok(())
1711}
1712
1713/// Per-widget validation for a list of [`SqlWidget`]s — shared by the
1714/// [`View`] resource so authoring errors surface at `view create`. `field`
1715/// names the containing key for error messages. The read-only SQL check is
1716/// NOT here (it lives in the backend `api::query` sandbox, which kanade-shared
1717/// can't depend on) — this validates structure: non-empty title/query, a
1718/// known `kind`, the channels each `kind` needs, a real placement, and a
1719/// parseable `refresh`.
1720pub fn validate_sql_widgets(widgets: &[SqlWidget], field: &str) -> Result<(), String> {
1721    for (i, w) in widgets.iter().enumerate() {
1722        let at = format!("{field}[{i}]");
1723        if w.title.trim().is_empty() {
1724            return Err(format!("{at}.title must not be empty"));
1725        }
1726        if w.query.trim().is_empty() {
1727            return Err(format!("{at}.query must not be empty"));
1728        }
1729        if let Some(description) = &w.description {
1730            if description.trim().is_empty() {
1731                return Err(format!("{at}.description must not be empty when set"));
1732            }
1733        }
1734        if let Some(refresh) = &w.refresh {
1735            humantime::parse_duration(refresh)
1736                .map_err(|e| format!("{at}.refresh '{refresh}' is not a valid duration: {e}"))?;
1737        }
1738        validate_placement(&w.placement, &at)?;
1739        // A per-PC widget (its query binds `:pc_id`) renders only in the
1740        // per-PC Analytics scope, bound to the selected PC. The Dashboard's
1741        // pinned section is fleet-scope and never sends a PC, so a pinned
1742        // per-PC widget would be silently dropped on every request — reject
1743        // the contradiction at create time rather than let it vanish (claude
1744        // review). Literal-aware so a `:pc_id` inside a string literal doesn't
1745        // trip it (see [`rewrite_pc_id_param`]).
1746        if w.placement.is_pinned() && rewrite_pc_id_param(&w.query).1 > 0 {
1747            return Err(format!(
1748                "{at}: a per-PC widget (its query binds `:pc_id`) cannot pin to the Dashboard \
1749                 (the Dashboard is fleet-scope, it never selects a PC) — use `analytics` placement only"
1750            ));
1751        }
1752        validate_render_spec(&w.render, &at)?;
1753    }
1754    Ok(())
1755}
1756
1757/// The named parameter a per-PC [`SqlWidget`] binds to the selected PC. Its
1758/// presence in a widget's query is what makes the widget per-PC.
1759pub const PC_ID_PARAM: &str = ":pc_id";
1760
1761/// Rewrite every *real* `:pc_id` parameter in a widget query to a positional
1762/// `?`, returning `(rewritten_sql, count)`. "Real" = OUTSIDE string literals,
1763/// quoted identifiers and comments, and a whole token (the char after `:pc_id`
1764/// isn't a word char, so `:pc_idx` is left alone). One scanner shared by three
1765/// call sites so they can't disagree on how many `?` SQLite will actually see:
1766///   * per-PC scope detection (`count > 0` ⇒ the widget is per-PC),
1767///   * the backend's bind path (sqlx-sqlite binds POSITIONAL `?` only, not
1768///     `:name`, so the token must be rewritten and bound once per occurrence),
1769///   * and `validate_sql_widgets`' pinned-per-PC rejection above.
1770///
1771/// The literal/comment skipping mirrors the read-only sandbox's
1772/// `strip_sql_noise`, so a `:pc_id` inside `SELECT 'see :pc_id docs'` is copied
1773/// verbatim and NOT counted — it would otherwise be miscounted (a bind-count
1774/// mismatch → `SQLITE_RANGE`) and misclassify the widget's scope (Gemini /
1775/// claude review).
1776pub fn rewrite_pc_id_param(sql: &str) -> (String, usize) {
1777    let mut out = String::with_capacity(sql.len());
1778    let mut count = 0usize;
1779    let mut chars = sql.char_indices().peekable();
1780    while let Some((idx, c)) = chars.next() {
1781        match c {
1782            // String literal / quoted identifier — copy verbatim, honouring the
1783            // doubled-quote escape (`''` / `""` stays inside).
1784            '\'' | '"' => {
1785                out.push(c);
1786                let quote = c;
1787                while let Some((_, d)) = chars.next() {
1788                    out.push(d);
1789                    if d == quote {
1790                        if chars.peek().map(|&(_, e)| e) == Some(quote) {
1791                            let (_, e) = chars.next().unwrap();
1792                            out.push(e);
1793                        } else {
1794                            break;
1795                        }
1796                    }
1797                }
1798            }
1799            // Line comment — copy to end of line.
1800            '-' if chars.peek().map(|&(_, e)| e) == Some('-') => {
1801                out.push(c);
1802                for (_, d) in chars.by_ref() {
1803                    out.push(d);
1804                    if d == '\n' {
1805                        break;
1806                    }
1807                }
1808            }
1809            // Block comment — copy to `*/`.
1810            '/' if chars.peek().map(|&(_, e)| e) == Some('*') => {
1811                out.push(c);
1812                let (_, star) = chars.next().unwrap();
1813                out.push(star);
1814                let mut prev = ' ';
1815                for (_, d) in chars.by_ref() {
1816                    out.push(d);
1817                    if prev == '*' && d == '/' {
1818                        break;
1819                    }
1820                    prev = d;
1821                }
1822            }
1823            // A `:pc_id` token outside any literal/comment — rewrite if it's a
1824            // whole token (not the prefix of `:pc_idx`).
1825            ':' if sql[idx..].starts_with(PC_ID_PARAM) => {
1826                let after = idx + PC_ID_PARAM.len();
1827                let next_is_word = sql[after..]
1828                    .chars()
1829                    .next()
1830                    .is_some_and(|w| w.is_alphanumeric() || w == '_');
1831                if next_is_word {
1832                    out.push(c);
1833                } else {
1834                    out.push('?');
1835                    count += 1;
1836                    for _ in 0..PC_ID_PARAM.chars().count() - 1 {
1837                        chars.next();
1838                    }
1839                }
1840            }
1841            _ => out.push(c),
1842        }
1843    }
1844    (out, count)
1845}
1846
1847/// Validate a [`RenderSpec`]: reject the #492 `Unknown` catch-all (an operator
1848/// typo at create time) and require the channel columns each `kind` reads.
1849fn validate_render_spec(r: &RenderSpec, at: &str) -> Result<(), String> {
1850    // A channel column is "given" when present and non-blank.
1851    let given = |v: &Option<String>| v.as_deref().map(str::trim).is_some_and(|s| !s.is_empty());
1852    match r.kind {
1853        RenderKind::Unknown => {
1854            return Err(format!(
1855                "{at}.render.kind is not a known value (table | stat | bar | pie | gauge)"
1856            ));
1857        }
1858        RenderKind::Table => {
1859            // `columns` optional; if given, each name must be non-blank.
1860            if let Some(cols) = &r.columns {
1861                if cols.iter().any(|c| c.trim().is_empty()) {
1862                    return Err(format!("{at}.render.columns must not contain blank names"));
1863                }
1864            }
1865            if let Some(labels) = &r.labels {
1866                for (k, v) in labels {
1867                    if k.trim().is_empty() || v.trim().is_empty() {
1868                        return Err(format!(
1869                            "{at}.render.labels keys and values must be non-empty"
1870                        ));
1871                    }
1872                }
1873            }
1874        }
1875        RenderKind::Stat => {
1876            if !given(&r.value) {
1877                return Err(format!("{at}.render.value is required for kind=stat"));
1878            }
1879        }
1880        RenderKind::Bar | RenderKind::Pie => {
1881            let kind = if r.kind == RenderKind::Bar {
1882                "bar"
1883            } else {
1884                "pie"
1885            };
1886            if !given(&r.label) {
1887                return Err(format!("{at}.render.label is required for kind={kind}"));
1888            }
1889            if !given(&r.value) {
1890                return Err(format!("{at}.render.value is required for kind={kind}"));
1891            }
1892            // `limit: 0` truncates to no rows — an invisible widget, almost
1893            // certainly a typo. Omit `limit` for "all rows" (CodeRabbit).
1894            if r.limit == Some(0) {
1895                return Err(format!(
1896                    "{at}.render.limit must be >= 1 (omit it to keep all rows)"
1897                ));
1898            }
1899        }
1900        RenderKind::Gauge => {
1901            // Either a precomputed `value` ratio, or a `num`/`den` pair —
1902            // exactly one of the two forms.
1903            match (given(&r.value), given(&r.num), given(&r.den)) {
1904                (true, false, false) => {}
1905                (false, true, true) => {}
1906                _ => {
1907                    return Err(format!(
1908                        "{at}.render for kind=gauge needs either `value` (a ratio) or both `num` and `den`"
1909                    ));
1910                }
1911            }
1912        }
1913    }
1914    Ok(())
1915}
1916
1917/// A standalone declarative read/aggregation for the Analytics page (#743).
1918///
1919/// A **view** aggregates stored fleet data (`obs_events`, …) without an
1920/// `execute` or a schedule — unlike a [`Manifest`] it only declares
1921/// [`AggregateWidget`]s. (The first line is concise on purpose: `schemars`
1922/// uses it as the generated schema's `title`.) The backend reads views from
1923/// `BUCKET_VIEWS` at
1924/// query time and merges their widgets with the co-located `aggregate:`
1925/// hints on jobs, so a cross-cutting dashboard (one that charts events
1926/// emitted by several other jobs / the agent) has a home that doesn't need
1927/// a noop job carrier. Stored JSON in `BUCKET_VIEWS`, keyed by `id`.
1928#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
1929pub struct View {
1930    /// Stable identifier (the KV key). Required, validated non-empty.
1931    pub id: String,
1932    /// Optional human description shown on the Views admin page.
1933    #[serde(default, skip_serializing_if = "Option::is_none")]
1934    pub description: Option<String>,
1935    /// The `obs_events` aggregate widgets this view contributes to the
1936    /// Analytics page. Optional since PR3 — a view may instead (or also)
1937    /// carry [`sql_widgets`](View::sql_widgets); a view must have at least one
1938    /// widget across the two lists.
1939    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1940    pub widgets: Vec<AggregateWidget>,
1941    /// #vuln-roadmap PR3: SQL-backed, materialized widgets — raw read-only SQL
1942    /// over the projector tables (inventory/feeds/…) mapped to a visual. This
1943    /// is how a correlation dashboard (vulnerability / EOL / license) is
1944    /// expressed as config. See [`SqlWidget`].
1945    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1946    pub sql_widgets: Vec<SqlWidget>,
1947    /// Free-form operator taxonomy (same role as [`Manifest::tags`]).
1948    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1949    pub tags: Vec<String>,
1950    /// GitOps provenance (#678), stamped by `kanade view create` from the
1951    /// source YAML's Git context — same as [`Manifest::origin`].
1952    #[serde(default, skip_serializing_if = "Option::is_none")]
1953    pub origin: Option<RepoOrigin>,
1954}
1955
1956/// True if `id` is a safe resource identifier — non-empty and only
1957/// `[A-Za-z0-9._-]`. A view `id` becomes a NATS KV key *and* a URL path
1958/// segment (`/api/views/{id}`), so this blocks `/`, `..`, whitespace and
1959/// other characters that would break the KV key or let a CLI arg wander
1960/// the URL space. (#743 / #744 follow-up — a deliberately small charset
1961/// rather than the looser set NATS technically allows.)
1962pub fn is_valid_resource_id(id: &str) -> bool {
1963    !id.is_empty()
1964        && id
1965            .chars()
1966            .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-')
1967}
1968
1969impl View {
1970    pub fn validate(&self) -> Result<(), String> {
1971        // Validate the id exactly as stored — no `.trim()`. `views::create`
1972        // uses `self.id` verbatim as the KV key and it's the `/api/views/{id}`
1973        // URL segment a lookup matches, so a padded id like `" my-view "` that
1974        // validated as its trimmed form but was stored raw would silently never
1975        // match. The charset excludes whitespace, so checking the untrimmed id
1976        // rejects such an id outright.
1977        if !is_valid_resource_id(&self.id) {
1978            return Err(
1979                "view.id must be non-empty and only [A-Za-z0-9._-] (it's a KV key + URL segment; \
1980                 no surrounding whitespace)"
1981                    .to_string(),
1982            );
1983        }
1984        // A view must contribute at least one widget across the two lists;
1985        // `validate_aggregate_widgets` rejects an empty `widgets` on its own,
1986        // so only call it when that list is non-empty (a pure-SQL view is
1987        // valid with an empty `widgets`).
1988        if self.widgets.is_empty() && self.sql_widgets.is_empty() {
1989            return Err(
1990                "view must declare at least one widget (`widgets:` and/or `sql_widgets:`)"
1991                    .to_string(),
1992            );
1993        }
1994        if !self.widgets.is_empty() {
1995            validate_aggregate_widgets(&self.widgets, "widgets")?;
1996        }
1997        validate_sql_widgets(&self.sql_widgets, "sql_widgets")?;
1998        for tag in &self.tags {
1999            if tag.trim().is_empty() {
2000                return Err("tags must not contain empty entries".to_string());
2001            }
2002        }
2003        Ok(())
2004    }
2005}
2006
2007/// Default membership-recompute cadence for a dynamic [`GroupDef`] whose
2008/// `refresh` is unset — 10 minutes. A group's SQL is evaluated lazily (only
2009/// when a schedule targeting it fires, or the members preview is requested)
2010/// and the result cached for this long, so fleet facts (inventory updates, a
2011/// newly-registered PC) reach the group within at most one cadence while an
2012/// expensive correlation query stays off the hot scheduler-tick path. A
2013/// static `members:` group ignores this (its membership is literal).
2014pub const DEFAULT_GROUP_REFRESH: std::time::Duration = std::time::Duration::from_secs(600);
2015
2016/// A **declared fleet group** (#1032): the third manifest kind alongside
2017/// [`Manifest`] (jobs) and [`Schedule`] (schedules), stored in
2018/// `BUCKET_GROUP_DEFS` keyed by [`id`](GroupDef::id).
2019///
2020/// (The first doc line deliberately does not start with `#NNN` — schemars
2021/// treats a leading `#` as a Markdown heading and would extract it as the
2022/// schema `title`, garbling it. Same reason [`View`]'s doc leads with prose.)
2023///
2024/// A group definition names a set of PCs in one of two mutually-exclusive
2025/// ways:
2026///   * **static** — a literal [`members`](GroupDef::members) list. Declared,
2027///     git-reviewable membership (the auditability win over hand-editing the
2028///     imperative `agent_groups` KV).
2029///   * **dynamic** — a read-only SQL [`query`](GroupDef::query) that returns a
2030///     `pc_id` column. Membership is *derived from the fleet's own facts*
2031///     (`agents`, `inventory_facts` + `json_extract(facts_json, …)`, `feeds`,
2032///     `check_status`, `explode:` tables — anything in the projector DB), so
2033///     "every client OS", "the servers sharing a hostname prefix", "machines
2034///     still on build 26100" are all just a `SELECT`. The query runs in the
2035///     backend read-only sandbox (`api::query`), never on the endpoint.
2036///
2037/// A schedule's `target.groups` resolves a defined group (static or dynamic)
2038/// **in addition to** the imperative `agent_groups` membership, so declared
2039/// groups and manually-assigned ones coexist and this never mutates
2040/// `agent_groups`.
2041#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2042pub struct GroupDef {
2043    /// Stable identifier (the KV key + URL segment + the name a schedule's
2044    /// `target.groups` references). Required; same `[A-Za-z0-9._-]` charset
2045    /// as a [`View`] id via [`is_valid_resource_id`].
2046    pub id: String,
2047    /// Optional human description shown on the groups admin page.
2048    #[serde(default, skip_serializing_if = "Option::is_none")]
2049    pub description: Option<String>,
2050    /// Static membership — a literal list of `pc_id`s. Mutually exclusive with
2051    /// [`query`](GroupDef::query); exactly one of the two must be set
2052    /// (enforced by [`GroupDef::validate`]).
2053    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2054    pub members: Vec<String>,
2055    /// Dynamic membership — a read-only `SELECT`/`WITH` returning a `pc_id`
2056    /// column. Mutually exclusive with [`members`](GroupDef::members). The
2057    /// backend validates it read-only at `group create` and again at run time;
2058    /// a write verb / stacked statement is rejected. Empty string is treated
2059    /// as unset so an operator can comment the body out to switch to
2060    /// `members:` without dropping the key.
2061    #[serde(default, skip_serializing_if = "Option::is_none")]
2062    pub query: Option<String>,
2063    /// Membership-recompute cadence for a dynamic group as a humantime
2064    /// duration (`"30m"`, `"6h"`). Absent ⇒ [`DEFAULT_GROUP_REFRESH`]. Ignored
2065    /// for a static group.
2066    #[serde(default, skip_serializing_if = "Option::is_none")]
2067    pub refresh: Option<String>,
2068    /// Free-form operator taxonomy (same role as [`Manifest::tags`]).
2069    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2070    pub tags: Vec<String>,
2071    /// GitOps provenance (#678), stamped by `kanade group def create` from the
2072    /// source YAML's Git context — same as [`View::origin`].
2073    #[serde(default, skip_serializing_if = "Option::is_none")]
2074    pub origin: Option<RepoOrigin>,
2075}
2076
2077impl GroupDef {
2078    /// The dynamic SQL body if this is a dynamic group — a non-blank `query`.
2079    /// (An empty-string `query` reads as unset, mirroring [`Execute::script`].)
2080    pub fn dynamic_query(&self) -> Option<&str> {
2081        self.query
2082            .as_deref()
2083            .map(str::trim)
2084            .filter(|q| !q.is_empty())
2085    }
2086
2087    /// The effective recompute cadence for a dynamic group — the parsed
2088    /// `refresh` or [`DEFAULT_GROUP_REFRESH`]. Falls back to the default on an
2089    /// unparseable value rather than panicking on the read path (validation
2090    /// already rejected a bad value at create time).
2091    pub fn refresh_interval(&self) -> std::time::Duration {
2092        self.refresh
2093            .as_deref()
2094            .and_then(|s| humantime::parse_duration(s).ok())
2095            .unwrap_or(DEFAULT_GROUP_REFRESH)
2096    }
2097
2098    pub fn validate(&self) -> Result<(), String> {
2099        // Validate the id EXACTLY as stored — no `.trim()`. The id is used
2100        // verbatim as the KV key (`group_defs::create` does `kv.put(&group.id,
2101        // …)`) and as the name a schedule's `target.groups` matches, so a
2102        // padded id like `" clients "` that validated as its trimmed form but
2103        // was stored raw would silently never match. The charset excludes
2104        // whitespace, so checking the untrimmed id rejects such an id outright.
2105        if !is_valid_resource_id(&self.id) {
2106            return Err(
2107                "group.id must be non-empty and only [A-Za-z0-9._-] (it's a KV key + URL segment; \
2108                 no surrounding whitespace)"
2109                    .to_string(),
2110            );
2111        }
2112        // Exactly one of members / query. A blank `query` counts as unset so
2113        // the "comment the body out" workflow lands on the members branch
2114        // rather than a confusing "both set" error.
2115        let has_members = !self.members.is_empty();
2116        let has_query = self.dynamic_query().is_some();
2117        match (has_members, has_query) {
2118            (false, false) => {
2119                return Err(
2120                    "group must declare either a static `members:` list or a dynamic `query:`"
2121                        .to_string(),
2122                );
2123            }
2124            (true, true) => {
2125                return Err(
2126                    "`members:` and `query:` are mutually exclusive — a group is either static or dynamic"
2127                        .to_string(),
2128                );
2129            }
2130            _ => {}
2131        }
2132        for m in &self.members {
2133            if m.trim().is_empty() {
2134                return Err("members must not contain empty entries".to_string());
2135            }
2136        }
2137        // A dynamic group's refresh must parse (a static group ignores it, but
2138        // reject a bad value either way so a later members→query switch can't
2139        // surprise the operator).
2140        if let Some(r) = &self.refresh
2141            && humantime::parse_duration(r).is_err()
2142        {
2143            return Err(format!(
2144                "group.refresh '{r}' is not a valid duration (e.g. '30m', '6h')"
2145            ));
2146        }
2147        for tag in &self.tags {
2148            if tag.trim().is_empty() {
2149                return Err("tags must not contain empty entries".to_string());
2150            }
2151        }
2152        Ok(())
2153    }
2154}
2155
2156/// Issue #246 — `emit:` manifest block for jobs whose stdout is
2157/// NDJSON observability events (one `ObsEvent` per line). Parallel
2158/// to `inventory:` but for the append-only timeline pipeline; see
2159/// `Manifest::emit` for the full contract.
2160#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2161pub struct EmitConfig {
2162    /// What kind of payload the agent should expect on stdout. Only
2163    /// `events` is defined today (parses each non-empty line as
2164    /// `ObsEvent` and publishes on `obs.<pc_id>`); future variants
2165    /// (e.g. metrics streams, structured trace events) plug in here.
2166    #[serde(rename = "type")]
2167    pub kind: EmitKind,
2168    /// Operator hint for where the script keeps its own state — the
2169    /// watermark file the PowerShell / sh body reads + writes
2170    /// between runs so it only emits NEW events since the last
2171    /// poll. The agent doesn't read this; it's documentation that
2172    /// the SPA (and `kanade job edit`) can surface to operators
2173    /// reviewing the manifest. Optional; the script is allowed to
2174    /// keep state anywhere (registry, env, etc.) — the field's
2175    /// presence makes the convention discoverable.
2176    #[serde(default, skip_serializing_if = "Option::is_none")]
2177    pub watermark_path: Option<String>,
2178}
2179
2180/// `emit.type` enum. Lowercase serde so manifests read
2181/// `type: events` rather than `Events`.
2182#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
2183#[serde(rename_all = "lowercase")]
2184pub enum EmitKind {
2185    /// Per-line `ObsEvent` JSON. Agent parses + publishes on
2186    /// `obs.<pc_id>`, drops the stdout from the resulting
2187    /// `ExecResult`.
2188    Events,
2189}
2190
2191/// v0.31 / #40: declarative "flatten this JSON array into a real
2192/// SQLite table" spec on an inventory manifest. The projector
2193/// creates the table on first registration (CREATE TABLE IF NOT
2194/// EXISTS + indexes) and writes a row per element of
2195/// `payload[field]` on every result, scoped by (pc_id, job_id) so
2196/// each PC's rows replace cleanly without a per-PC schema.
2197#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2198pub struct ExplodeSpec {
2199    /// JSON array key under the payload to explode. E.g. `"apps"`
2200    /// for `payload: { apps: [{...}, {...}] }`.
2201    pub field: String,
2202    /// Derived SQLite table name. Operators choose this — pick
2203    /// something namespaced + stable (`inventory_sw_apps`, not
2204    /// `apps`) so multiple inventory manifests don't collide on a
2205    /// generic name.
2206    pub table: String,
2207    /// Element-level fields that uniquely identify a row inside one
2208    /// PC's payload. The full PK is `(pc_id, job_id) + these
2209    /// columns`. Required — operators must think about uniqueness
2210    /// (e.g. `["name", "source"]` for installed apps because the
2211    /// same name appears in multiple uninstall hives).
2212    ///
2213    /// v0.31 / #41: same tuple drives history identity. When
2214    /// `track_history` is on, the projector serialises these
2215    /// fields' values into `inventory_history.identity_json` for
2216    /// every change event, so queries like "every PC that ever
2217    /// installed Chrome (any source)" filter on identity_json
2218    /// content without a per-manifest schema.
2219    pub primary_key: Vec<String>,
2220    /// Per-element fields that become columns in the derived table.
2221    pub columns: Vec<ExplodeColumn>,
2222    /// v0.31 / #41: when true (default false), the projector
2223    /// diffs each PC's incoming payload against the prior rows
2224    /// for the same (pc_id, job_id) BEFORE the DELETE-then-INSERT
2225    /// replace, and writes added / removed / changed events into
2226    /// `inventory_history`. Lets operators answer time-dimension
2227    /// questions ("when did Chrome 120 first appear on PC X?",
2228    /// "what's the Win 11 23H2 rollout curve") without storing
2229    /// per-scan snapshots. Off by default so operators opt in
2230    /// per-spec — history has a real storage cost on long-lived
2231    /// deployments (mitigated by the 90-day default retention
2232    /// sweeper, see `cleanup` module).
2233    #[serde(default)]
2234    pub track_history: bool,
2235}
2236
2237/// One column in an [`ExplodeSpec`]'s derived table.
2238#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2239pub struct ExplodeColumn {
2240    /// JSON key under each array element. Becomes the column name
2241    /// in the derived SQLite table — we don't rename.
2242    pub field: String,
2243    /// SQLite affinity: `"text"` (default), `"integer"`, `"real"`.
2244    /// Storage maps directly via `sqlx::query.bind(...)`; type
2245    /// mismatches at INSERT-time fail loudly rather than silently
2246    /// dropping the row.
2247    #[serde(default, skip_serializing_if = "Option::is_none")]
2248    #[serde(rename = "type")]
2249    pub kind: Option<String>,
2250    /// When true, the projector creates a `CREATE INDEX` on this
2251    /// column at table-creation time. Boost for the common-filter
2252    /// columns (`name`, `version`) — operators mark them
2253    /// explicitly, the projector won't guess.
2254    #[serde(default)]
2255    pub index: bool,
2256}
2257
2258/// #vuln-roadmap: one declarative **external-data feed** on a `feed:`
2259/// manifest — see [`Manifest::feed`]. Unlike inventory [`ExplodeSpec`]
2260/// (keyed per `(pc_id, job_id)`), a feed is GLOBAL fleet-wide reference
2261/// data: the controller-tier job's script fetches + shapes it, prints the
2262/// array under [`field`](FeedSpec::field) inside a `#KANADE-FEED-BEGIN/END`
2263/// fence, and the projector REPLACES that feed's rows wholesale in the
2264/// shared `feeds` table keyed `(feed_id, item_id)`. The full element JSON
2265/// lands in a `data` column, so a `view:` SQL `json_extract`s whatever
2266/// shape the feed carries — no per-feed schema, no dynamic DDL. One
2267/// manifest may declare several feeds.
2268#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2269pub struct FeedSpec {
2270    /// Stable feed identifier — the `feed_id` partition in the shared
2271    /// `feeds` table. Operators choose this; namespace it (`cisa-kev`,
2272    /// `endoflife-windows`) so feeds don't collide. A new result for the
2273    /// same id replaces that partition wholesale.
2274    pub id: String,
2275    /// JSON array key under the (fenced) payload to ingest. E.g.
2276    /// `"vulnerabilities"` for `{ vulnerabilities: [{...}, {...}] }`.
2277    pub field: String,
2278    /// Element-level field(s) whose values uniquely identify an item
2279    /// within the feed — they form the `item_id` key (joined for a
2280    /// composite key). Required: operators must think about uniqueness
2281    /// (e.g. `["cveID"]` for CISA KEV). An element missing any of these is
2282    /// skipped (it has no stable identity).
2283    pub primary_key: Vec<String>,
2284}
2285
2286#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2287pub struct DisplayField {
2288    /// Top-level key in the stdout JSON.
2289    pub field: String,
2290    /// Human-readable column header.
2291    pub label: String,
2292    /// Optional render hint — `"number"`, `"bytes"`, `"timestamp"`,
2293    /// or `"table"` (#39). Defaults to plain text rendering on the
2294    /// SPA side. `"table"` expects the field's value to be a JSON
2295    /// array of objects and renders a nested sub-table on the
2296    /// per-PC detail page using `columns` as the schema; the fleet
2297    /// summary view falls back to showing the row count for
2298    /// `"table"` cells so the wide list stays compact.
2299    #[serde(default, skip_serializing_if = "Option::is_none")]
2300    #[serde(rename = "type")]
2301    pub kind: Option<String>,
2302    /// v0.30 / #39: when `kind == "table"`, the SPA renders the
2303    /// field's value (an array of objects like
2304    /// `disks: [{ device_id, size_bytes, ... }]`) as a nested
2305    /// sub-table using these columns. Each column is itself a
2306    /// `DisplayField`, so the nested cells reuse the same render
2307    /// hints (`bytes`, `number`, `timestamp`) — no parallel format
2308    /// pipeline. Ignored for any other `kind`.
2309    #[serde(default, skip_serializing_if = "Option::is_none")]
2310    pub columns: Option<Vec<DisplayField>>,
2311}
2312
2313#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2314pub struct Rollout {
2315    #[serde(default)]
2316    pub strategy: RolloutStrategy,
2317    pub waves: Vec<Wave>,
2318}
2319
2320#[derive(
2321    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
2322)]
2323#[serde(rename_all = "lowercase")]
2324pub enum RolloutStrategy {
2325    #[default]
2326    Wave,
2327}
2328
2329#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2330pub struct Wave {
2331    pub group: String,
2332    /// humantime delay measured from the deploy's publish time. wave[0]
2333    /// typically has "0s"; subsequent waves use minutes / hours.
2334    pub delay: String,
2335}
2336
2337#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default)]
2338pub struct Target {
2339    #[serde(default)]
2340    pub groups: Vec<String>,
2341    #[serde(default)]
2342    pub pcs: Vec<String>,
2343    #[serde(default)]
2344    pub all: bool,
2345}
2346
2347impl Target {
2348    /// At least one of all / groups / pcs is set.
2349    pub fn is_specified(&self) -> bool {
2350        self.all || !self.groups.is_empty() || !self.pcs.is_empty()
2351    }
2352
2353    /// Whether a PC (its `pc_id` + group membership) falls in this target:
2354    /// `all`, or the pc is listed, or it belongs to a listed group. Used
2355    /// by the agent to scope `client.visible_to` (#816). An unspecified
2356    /// target matches nobody (callers should treat "no target" as
2357    /// "visible to all" before calling this).
2358    pub fn matches(&self, pc_id: &str, groups: &[String]) -> bool {
2359        self.all
2360            || self.pcs.iter().any(|p| p == pc_id)
2361            || self.groups.iter().any(|g| groups.contains(g))
2362    }
2363}
2364
2365#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2366pub struct Execute {
2367    /// Critical jobs can bypass the PC limit and consume no slot.
2368    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2369    pub bypass_local_limit: bool,
2370    pub shell: ExecuteShell,
2371    /// Inline script body. Mutually exclusive with [`script_file`]
2372    /// and [`script_object`]; exactly one of the three must be set
2373    /// (enforced by [`Execute::validate_script_source`] at the
2374    /// write-side parse boundaries — `kanade job create` and
2375    /// `POST /api/jobs`).
2376    ///
2377    /// Empty string is treated as **unset** so operators can swap
2378    /// to a `script_file:` / `script_object:` alternative just by
2379    /// commenting out the body, without having to also drop the
2380    /// `script:` key entirely.
2381    ///
2382    /// [`script_file`]: Self::script_file
2383    /// [`script_object`]: Self::script_object
2384    #[serde(default, skip_serializing_if = "Option::is_none")]
2385    pub script: Option<String>,
2386    /// Repo-local file path resolved by the operator-side CLI at
2387    /// `kanade job create` time. The CLI reads the file, slots its
2388    /// contents into `script`, and clears this field before
2389    /// POSTing — so the backend / agents never see `script_file`
2390    /// in stored manifests. SPEC §2.4.1.
2391    ///
2392    /// The resolver shipped with #210: `kanade job create` /
2393    /// `kanade job validate` inline this field end-to-end. Because
2394    /// resolution is CLI-side (it needs the operator's filesystem),
2395    /// `POST /api/jobs` rejects a manifest that still carries it
2396    /// (#918) — a stored `script_file` job would 400 at every exec.
2397    /// Inline the script or use `script_object` when writing through
2398    /// the API / SPA editor.
2399    #[serde(default, skip_serializing_if = "Option::is_none")]
2400    pub script_file: Option<String>,
2401    /// Object Store reference (`<name>/<version>`) into the
2402    /// `scripts` bucket (`OBJECT_SCRIPTS`). Agents fetch the body
2403    /// at Execute time via `/api/script-objects/{name}/{version}`
2404    /// and cache it locally. SPEC §2.4.1.
2405    ///
2406    /// Fully wired (#210/#211): the backend resolves the digest at
2407    /// exec submission (`api::exec::resolve_script_source`), the agent
2408    /// fetches + sha-verifies + caches the body (`script_cache`), and
2409    /// `kanade script` CRUDs the store. Unlike `script_file:` (inlined
2410    /// CLI-side, git-managed), this keeps the body in versioned,
2411    /// digest-pinned object storage — the ops-managed counterpart.
2412    #[serde(default, skip_serializing_if = "Option::is_none")]
2413    pub script_object: Option<String>,
2414    /// humantime duration string (e.g. "30s", "10m"). Script-intrinsic
2415    /// — represents how long this script reasonably takes to run.
2416    pub timeout: String,
2417    /// Token + session combination the agent uses to launch the
2418    /// script (v0.21). Default = [`RunAs::System`] (Session 0,
2419    /// LocalSystem privileges, no GUI; root on macOS) — matches
2420    /// pre-v0.21 behavior. `user` / `system_gui` run in the logged-in
2421    /// console user's session on Windows and macOS, and fail when
2422    /// nobody is logged in; Linux agents skip them.
2423    #[serde(default)]
2424    pub run_as: RunAs,
2425    /// Working directory for the spawned child (v0.21.1). When
2426    /// unset, the child inherits the agent's cwd — on Windows that
2427    /// means `%SystemRoot%\System32` for the prod service, which is
2428    /// almost never what operators actually want (a macOS `run_as:
2429    /// user` job starts in the user's home instead: the daemon's own
2430    /// cwd is its 0700 data dir). Use an absolute path; relative paths
2431    /// are passed through to the OS verbatim. The agent expands a
2432    /// leading `~` to the home of the identity the job runs as (the
2433    /// user for `run_as: user`), and on Windows `%FOO%` from that
2434    /// identity's environment — so `%PROGRAMDATA%` works for `run_as:
2435    /// system`, `~\src` / `%USERPROFILE%` for `run_as: user`. A macOS
2436    /// agent expands only `~`.
2437    #[serde(default, skip_serializing_if = "Option::is_none")]
2438    pub cwd: Option<String>,
2439}
2440
2441impl Execute {
2442    /// Treat an empty — or whitespace-only (#918) — `script:` body as
2443    /// "intentionally unset". Operators commenting out a block-scalar
2444    /// tend to leave the key behind, and failing the validator on
2445    /// `script: ""` would surprise them; a body of blank lines can't
2446    /// be a real script either, only a commented-out one, and letting
2447    /// it count as "set" shipped a validated do-nothing job.
2448    fn has_inline_script(&self) -> bool {
2449        matches!(&self.script, Some(s) if !s.trim().is_empty())
2450    }
2451
2452    /// Enforce that exactly one of `script` / `script_file` /
2453    /// `script_object` is set. Called at the write-side parse
2454    /// boundaries (CLI `kanade job create` + backend
2455    /// `POST /api/jobs`) so ambiguous YAML is rejected before it
2456    /// reaches the JOBS KV. Read paths (projector, agent
2457    /// scheduler, list endpoints) skip this check — they only ever
2458    /// see what the write path already validated.
2459    pub fn validate_script_source(&self) -> Result<(), String> {
2460        // #918: a blank-but-present alternate source is a typo, not a
2461        // choice — `script_file: ""` used to count as "set", pass the
2462        // exactly-one check, and only fail at use time (the CLI reads
2463        // a file named ""; a stored blank script_object 404s on every
2464        // exec). Reject it with the field named. Inline `script` keeps
2465        // its documented empty-means-unset semantics instead — see
2466        // `has_inline_script`.
2467        if matches!(&self.script_file, Some(s) if s.trim().is_empty()) {
2468            return Err(
2469                "execute.script_file must not be blank when set (drop the key to use \
2470                 another source)"
2471                    .into(),
2472            );
2473        }
2474        if matches!(&self.script_object, Some(s) if s.trim().is_empty()) {
2475            return Err(
2476                "execute.script_object must not be blank when set (drop the key to use \
2477                 another source)"
2478                    .into(),
2479            );
2480        }
2481        let inline = self.has_inline_script();
2482        let file = self.script_file.is_some();
2483        let obj = self.script_object.is_some();
2484        let set = [inline, file, obj].into_iter().filter(|b| *b).count();
2485        match set {
2486            1 => {}
2487            0 => {
2488                return Err(
2489                    "execute: one of `script`, `script_file`, `script_object` must be set".into(),
2490                );
2491            }
2492            _ => {
2493                return Err(format!(
2494                    "execute: only one of `script` / `script_file` / `script_object` may be set \
2495                     (got script={inline}, script_file={file}, script_object={obj})"
2496                ));
2497            }
2498        }
2499        // #918: a script_object ref is `<name>/<version>` — the agent
2500        // fetches the body via `/api/script-objects/{name}/{version}`
2501        // and the backend uses the ref *verbatim* as the Object Store
2502        // key (`resolve_script_source`), so each half must be a
2503        // well-formed resource id: exactly one slash, and both halves
2504        // [A-Za-z0-9._-]. `is_valid_resource_id` also rejects a half
2505        // that's blank OR merely whitespace-padded (`"foo/bar "`) —
2506        // padding survives a JSON POST body (unlike a YAML plain
2507        // scalar) and would 404 on every exec (gemini/claude #943).
2508        if let Some(obj_ref) = self.script_object.as_deref() {
2509            let parts: Vec<&str> = obj_ref.split('/').collect();
2510            if parts.len() != 2 || parts.iter().any(|p| !is_valid_resource_id(p)) {
2511                return Err(format!(
2512                    "execute.script_object must be `<name>/<version>` with each half \
2513                     [A-Za-z0-9._-] (got '{obj_ref}'); publish bodies with \
2514                     `kanade script publish <name> <version>`"
2515                ));
2516            }
2517        }
2518        Ok(())
2519    }
2520}
2521
2522/// Job-generic post-step hook (see [`Manifest::finalize`]). Runs after
2523/// the main `execute:` script (and the collect upload) on a clean exit,
2524/// with the step's structured result injected via an environment
2525/// variable. P1 supports an inline `script:` only — `script_file:` /
2526/// `script_object:` are follow-ups.
2527#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
2528pub struct FinalizeSpec {
2529    pub shell: ExecuteShell,
2530    /// Inline script body (required; inline-only in P1).
2531    pub script: String,
2532    /// humantime duration string (e.g. `"60s"`, `"5m"`). Defaults to
2533    /// `60s` when unset.
2534    #[serde(default = "default_finalize_timeout")]
2535    pub timeout: String,
2536    /// Token + session combination, like [`Execute::run_as`]. Defaults
2537    /// to [`RunAs::System`].
2538    #[serde(default)]
2539    pub run_as: RunAs,
2540    /// Working directory for the hook child, like [`Execute::cwd`].
2541    #[serde(default, skip_serializing_if = "Option::is_none")]
2542    pub cwd: Option<String>,
2543    /// #965: for a `collect:` job, run this hook once per uploaded
2544    /// bundle (with a single-bundle `KANADE_COLLECT_RESULT`) as each
2545    /// bundle uploads, instead of once after the whole set. Lets an
2546    /// interrupted collect still clean up the days it managed to
2547    /// upload (partial progress sticks), breaking the
2548    /// offline-before-finalize backlog spiral.
2549    ///
2550    /// **Opt-in** (default `false` = one call after all bundles, the
2551    /// established contract) because per-bundle changes the hook's
2552    /// payload (all → one) and invocation count (1 → N), which would
2553    /// break a hook written for the all-at-once assumption (cross-bundle
2554    /// aggregation, once-only side effects, all-or-nothing). Only valid
2555    /// with a `collect:` hint — [`Manifest::validate`] rejects it
2556    /// otherwise, since a non-collect finalize has no bundles to iterate.
2557    #[serde(default)]
2558    pub on_each_bundle: bool,
2559}
2560
2561/// Default `finalize.timeout` when the operator omits it.
2562fn default_finalize_timeout() -> String {
2563    "60s".to_string()
2564}
2565
2566impl FinalizeSpec {
2567    /// Lower to the wire form forwarded onto a [`Command`]. The timeout
2568    /// parse falls back to 60s — [`Manifest::validate`] already rejects
2569    /// an unparseable value at create time, so the fire path uses a safe
2570    /// default rather than failing (mirrors
2571    /// [`CollectHint::max_size_bytes`]). A sub-second timeout floors at
2572    /// 1s for the same reason `build_command` does.
2573    pub fn lower(&self) -> FinalizeCommand {
2574        let timeout_secs = humantime::parse_duration(&self.timeout)
2575            .map(|d| d.as_secs().max(1))
2576            .unwrap_or(60);
2577        FinalizeCommand {
2578            shell: self.shell.into(),
2579            script: self.script.clone(),
2580            timeout_secs,
2581            run_as: self.run_as,
2582            cwd: self.cwd.clone(),
2583            on_each_bundle: self.on_each_bundle,
2584        }
2585    }
2586}
2587
2588impl Manifest {
2589    /// Cross-field semantic checks that don't fit into pure serde
2590    /// derive. Currently delegates to
2591    /// [`Execute::validate_script_source`] — see that method's
2592    /// docs for the rationale on which call sites should run this.
2593    pub fn validate(&self) -> Result<(), String> {
2594        self.execute.validate_script_source()?;
2595        // Fail CLOSED on an unrecognised execution tier. `#[serde(other)]`
2596        // turns a typo (`tier: controler`) or a future tier into
2597        // `Tier::Unknown`; without this check the controller gate would
2598        // fall back to normal endpoint dispatch, so an operator who *meant*
2599        // to confine a job to the controller tier would silently get
2600        // fleet-wide dispatch (CodeRabbit #905). Rejecting it at the write
2601        // boundary surfaces the typo at `job create`, and — since
2602        // `exec_manifest` re-validates — a hand-poked KV manifest can't slip
2603        // a controller-tier job onto endpoints either.
2604        if matches!(self.tier, Some(Tier::Unknown)) {
2605            return Err(
2606                "tier: unrecognised execution tier — use `endpoint` or `controller` \
2607                 (this is a typo, or a tier a newer kanade supports that this backend does not)"
2608                    .to_string(),
2609            );
2610        }
2611        // #vuln-roadmap: a `feed:` spec drives the global `feeds`
2612        // projection. id / item_id are stored as *values* (the `feeds`
2613        // table is fixed-schema — no identifier splicing), but blank
2614        // values are silent projection bugs: a blank id collides every
2615        // feed under "", a blank field never matches the payload array,
2616        // and an empty primary_key yields no item_id (every row dropped).
2617        // Reject them at the write boundary so `kanade job create` surfaces
2618        // the typo instead of producing an empty/garbled feed at run time.
2619        let mut seen_feed_ids: Vec<&str> = Vec::new();
2620        for spec in &self.feed {
2621            let id = spec.id.trim();
2622            if id.is_empty() {
2623                return Err("feed.id must not be empty".to_string());
2624            }
2625            if spec.field.trim().is_empty() {
2626                return Err(format!("feed '{id}' field must not be empty"));
2627            }
2628            if spec.primary_key.is_empty() {
2629                return Err(format!("feed '{id}' needs at least one primary_key field"));
2630            }
2631            if spec.primary_key.iter().any(|k| k.trim().is_empty()) {
2632                return Err(format!(
2633                    "feed '{id}' primary_key must not contain blank entries"
2634                ));
2635            }
2636            // Two specs sharing an id both target the same `feeds`
2637            // partition and would clobber each other on every run —
2638            // reject the ambiguity rather than let last-write-wins.
2639            if seen_feed_ids.contains(&id) {
2640                return Err(format!("feed id '{id}' is declared more than once"));
2641            }
2642            seen_feed_ids.push(id);
2643        }
2644        // A `feed:` job fetches external data and MUST run on the trusted
2645        // controller tier — the dispatch guard (`requires_controller`) treats
2646        // a non-empty `feed:` as implying `controller`. An explicit
2647        // `tier: endpoint` contradicts that intent; reject it rather than
2648        // silently overriding, so the operator can't believe a feed runs on
2649        // endpoints. Omitting `tier:` (the default) is fine — the implication
2650        // confines it; `tier: controller` is the redundant-but-explicit form.
2651        if !self.feed.is_empty() && matches!(self.tier, Some(Tier::Endpoint)) {
2652            return Err(
2653                "feed: requires the controller tier — remove `tier: endpoint` (a feed: job \
2654                 fetches external data and is confined to the controller_group)"
2655                    .to_string(),
2656            );
2657        }
2658        // A present-but-empty finalize script is an invisible no-op
2659        // (the hook would run an empty body); reject it at the write
2660        // boundary. Inline-only in P1, so `script` is the sole source.
2661        if let Some(finalize) = &self.finalize {
2662            if finalize.script.trim().is_empty() {
2663                return Err("finalize.script must not be empty".to_string());
2664            }
2665            // Reject an unparseable timeout at the write boundary so the
2666            // operator sees the error at `job create` rather than getting
2667            // a silent fire-time fallback (`FinalizeSpec::lower` floors to
2668            // 60s, which would otherwise mask a typo).
2669            if humantime::parse_duration(&finalize.timeout).is_err() {
2670                return Err(format!(
2671                    "finalize.timeout '{}' is not a valid duration",
2672                    finalize.timeout
2673                ));
2674            }
2675            // Disallow cmd for finalize: the agent injects the result JSON
2676            // into the hook's environment, and cmd.exe quoting doesn't
2677            // nest — JSON's `"` plus shell metacharacters in a collected
2678            // path/key could break out into command injection at the
2679            // agent's (often LocalSystem) privilege. PowerShell's
2680            // single-quote escaping is safe, and finalize hooks are
2681            // PowerShell by convention anyway.
2682            // `sh` is rejected for the same injection reason (its
2683            // single-word quoting doesn't nest around the JSON result
2684            // either), and additionally because the injected prelude is
2685            // PowerShell syntax (`$env:KANADE_COLLECT_RESULT = '...'`) —
2686            // it would be malformed in a POSIX shell. `pwsh` IS allowed:
2687            // it's PowerShell, so the prelude + single-quote escaping are
2688            // valid and safe.
2689            if matches!(finalize.shell, ExecuteShell::Cmd | ExecuteShell::Sh) {
2690                return Err(
2691                    "finalize.shell: cmd and sh are not supported for finalize hooks \
2692                     (shell-injection risk when the result JSON is injected, and the injected \
2693                     prelude is PowerShell syntax); use powershell or pwsh"
2694                        .to_string(),
2695                );
2696            }
2697            // #965: per-bundle finalize only means anything for a
2698            // collect: job — a non-collect finalize has no bundles to
2699            // iterate (it runs once after the script). Reject the
2700            // combination at the write boundary so a confused operator
2701            // is told rather than silently getting a no-op.
2702            if finalize.on_each_bundle && self.collect.is_none() {
2703                return Err(
2704                    "finalize.on_each_bundle: true requires a collect: hint — a non-collect \
2705                     finalize has no bundles to iterate (it runs once after the script)"
2706                        .to_string(),
2707                );
2708            }
2709        }
2710        // Stdout-format compatibility (#821). `inventory:` / `check:` /
2711        // `collect:` now COMPOSE: each reads its own `#KANADE-<KIND>-
2712        // BEGIN/END`-fenced JSON block from stdout, so a single job can
2713        // project inventory facts, drive a Health-tab check, AND collect
2714        // files in one run. (A single-hint job may still skip the fence;
2715        // a multi-hint job must fence each block.)
2716        //
2717        // `emit:` remains the exception — its stdout is line-delimited
2718        // NDJSON consumed whole and then omitted from the result — so it
2719        // can't share stdout with any fenced hint. `feed:` is another fenced
2720        // stdout consumer (`#KANADE-FEED`), so it belongs in this exclusion
2721        // too: with `emit:` present the projector never sees the feed's fence
2722        // (CodeRabbit).
2723        if self.emit.is_some()
2724            && (self.inventory.is_some()
2725                || self.check.is_some()
2726                || self.collect.is_some()
2727                || !self.feed.is_empty())
2728        {
2729            return Err(
2730                "`emit:` is incompatible with `inventory:` / `check:` / `collect:` / `feed:` — \
2731                 emit's stdout is NDJSON timeline events (consumed whole and omitted from the \
2732                 result), while the others read fenced JSON blocks from stdout"
2733                    .to_string(),
2734            );
2735        }
2736        // A check's `name` is the Health-tab row id (React key); the
2737        // field names tell the agent where to read status/detail.
2738        // An empty value is an invisible runtime bug, and the serde
2739        // defaults don't guard an operator who writes `status_field:
2740        // ""` explicitly — reject all three here.
2741        if let Some(check) = &self.check {
2742            for (label, value) in [
2743                ("check.name", &check.name),
2744                ("check.status_field", &check.status_field),
2745                ("check.detail_field", &check.detail_field),
2746            ] {
2747                if value.trim().is_empty() {
2748                    return Err(format!("{label} must not be empty"));
2749                }
2750            }
2751            // A present-but-blank `troubleshoot` is a broken
2752            // remediation job id (the "修復する" button would target
2753            // an empty manifest id) — reject it too.
2754            if let Some(troubleshoot) = &check.troubleshoot {
2755                if troubleshoot.trim().is_empty() {
2756                    return Err("check.troubleshoot must not be empty when set".to_string());
2757                }
2758            }
2759            // A present-but-blank `label` would render an empty row
2760            // title on the Health tab / Compliance page — reject it so
2761            // the slug fallback only ever kicks in when label is absent.
2762            if let Some(label) = &check.label {
2763                if label.trim().is_empty() {
2764                    return Err("check.label must not be empty when set".to_string());
2765                }
2766            }
2767            if let Some(alert) = &check.alert {
2768                // An alert that names no recipient is a silent no-op.
2769                if !alert.notify_user && alert.notify_groups.is_empty() {
2770                    return Err("check.alert must set notify_user and/or notify_groups".to_string());
2771                }
2772                if alert.title.trim().is_empty() {
2773                    return Err("check.alert.title must not be empty".to_string());
2774                }
2775                // `on: []` would never fire; an empty group name resolves to
2776                // a malformed `notifications.group.` subject.
2777                if alert.on.is_empty() {
2778                    return Err("check.alert.on must list at least one status".to_string());
2779                }
2780                if alert.notify_groups.iter().any(|g| g.trim().is_empty()) {
2781                    return Err("check.alert.notify_groups must not contain blanks".to_string());
2782                }
2783                // Email is addressed via group_contacts (group → email), so
2784                // there must be a group to map. notify_user has no email.
2785                if alert.email && alert.notify_groups.is_empty() {
2786                    return Err(
2787                        "check.alert.email requires notify_groups (email is addressed per group, not per user)"
2788                            .to_string(),
2789                    );
2790                }
2791                // The alert rides the `check_status` projection, which only
2792                // runs for `fleet: true`.
2793                if !check.fleet {
2794                    return Err(
2795                        "check.alert requires fleet: true (the alert rides the compliance projection)"
2796                            .to_string(),
2797                    );
2798                }
2799            }
2800        }
2801        // #291: a `client:` job is rendered in the Client App's
2802        // catalog (`jobs.list` → `jobs.execute`). serde already makes
2803        // `name` + `category` required at parse time; the only gap is
2804        // a present-but-blank `name`, which would render an empty row
2805        // title — reject it like the other display-id fields.
2806        if let Some(client) = &self.client {
2807            if client.name.trim().is_empty() {
2808                return Err("client.name must not be empty".to_string());
2809            }
2810            // #792: category is a free-form key now, so a blank one would
2811            // group the job under an empty tab — reject it like `name`.
2812            if client.category.trim().is_empty() {
2813                return Err("client.category must not be empty".to_string());
2814            }
2815            // Optional display fields, when present, must be
2816            // meaningful: a blank `description` renders an empty
2817            // subtitle and a blank `icon` is a dangling lucide name.
2818            // Same present-but-blank guard the `check:` block applies
2819            // to its optional `troubleshoot` id.
2820            for (label, value) in [
2821                ("client.description", &client.description),
2822                ("client.icon", &client.icon),
2823                ("client.category_label", &client.category_label),
2824                ("client.category_icon", &client.category_icon),
2825            ] {
2826                if let Some(v) = value {
2827                    if v.trim().is_empty() {
2828                        return Err(format!("{label} must not be empty when set"));
2829                    }
2830                }
2831            }
2832            // #816: a present-but-empty `visible_to` (no all/groups/pcs)
2833            // would hide the job from everyone in the Client App — almost
2834            // certainly a mistake. Require at least one selector; omit the
2835            // whole block to mean "visible to all".
2836            if let Some(t) = &client.visible_to {
2837                if !t.is_specified() {
2838                    return Err(
2839                        "client.visible_to must set at least one of all / groups / pcs (omit it for all PCs)"
2840                            .to_string(),
2841                    );
2842                }
2843            }
2844            // show_when: a dynamic display gate keyed on a check result. A
2845            // malformed check slug matches nothing and an empty status list
2846            // matches nothing — both would silently hide the job forever,
2847            // so reject them at create time rather than at a confused
2848            // "why isn't my job showing?" later. The slug must be a clean
2849            // resource id (same charset checks/jobs use): a typo with spaces
2850            // or punctuation can never match a real check name, so catch it
2851            // here instead of failing closed at runtime. (Whether the slug
2852            // names a check that actually EXISTS can't be checked here —
2853            // checks are keyed by name across manifests — so a valid-but-
2854            // unknown slug stays a runtime miss = hidden, the documented
2855            // fail-closed behavior.)
2856            if let Some(sw) = &client.show_when {
2857                if !is_valid_resource_id(sw.check.trim()) {
2858                    return Err(
2859                        "client.show_when.check must be a non-empty check slug ([A-Za-z0-9._-])"
2860                            .to_string(),
2861                    );
2862                }
2863                if sw.is.is_empty() {
2864                    return Err(
2865                        "client.show_when.is must list at least one check status".to_string()
2866                    );
2867                }
2868            }
2869            // confirm: a present-but-blank custom message would render an
2870            // empty dialog title — reject it like the other display fields.
2871            // (A `confirm: false` / `enabled: false` with no message is fine:
2872            // the dialog is suppressed, so there's nothing to render.)
2873            if let Some(c) = &client.confirm {
2874                if let Some(msg) = &c.message {
2875                    if msg.trim().is_empty() {
2876                        return Err("client.confirm.message must not be empty when set".to_string());
2877                    }
2878                }
2879            }
2880            // unlock: the scope slug is matched byte-for-byte against the
2881            // operator's configured `support_codes[].scope`, so a slug with
2882            // stray whitespace / punctuation can never match one — and
2883            // because the gate fails closed, the job would simply be
2884            // invisible forever with no error anywhere. Reject it at create
2885            // time. (Whether a code is actually CONFIGURED for the scope
2886            // can't be checked here — that lives in server settings, not the
2887            // manifest — so an unconfigured scope stays a runtime miss =
2888            // hidden.)
2889            //
2890            // Validated EXACTLY AS STORED — no `.trim()`, the same no-trim
2891            // rule `View::validate` / `AgentGroup::validate` spell out. The
2892            // backend trims a support code's scope before storing it, so a
2893            // padded manifest scope that validated as its trimmed form but
2894            // was stored raw would pass this check and then never match a
2895            // code — precisely the silent-forever-hidden failure this guard
2896            // exists to prevent.
2897            if let Some(scope) = &client.unlock {
2898                if !is_valid_resource_id(scope) {
2899                    return Err(
2900                        "client.unlock must be a non-empty unlock scope slug ([A-Za-z0-9._-]) \
2901                         with no surrounding whitespace"
2902                            .to_string(),
2903                    );
2904                }
2905            }
2906        }
2907        // #219: a `collect:` job's `name` heads the bundle on the SPA
2908        // Collect page (and the Client App row when paired with
2909        // `client:`), `files_field` tells the agent where to read the
2910        // path list, and `max_size` must be a parseable size so a typo
2911        // is caught at create time rather than silently capping the
2912        // bundle at the default on the fire path.
2913        if let Some(collect) = &self.collect {
2914            if collect.name.trim().is_empty() {
2915                return Err("collect.name must not be empty".to_string());
2916            }
2917            if collect.files_field.trim().is_empty() {
2918                return Err("collect.files_field must not be empty".to_string());
2919            }
2920            if let Some(description) = &collect.description {
2921                if description.trim().is_empty() {
2922                    return Err("collect.description must not be empty when set".to_string());
2923                }
2924            }
2925            if let Some(max_size) = &collect.max_size {
2926                parse_size_bytes(max_size).map_err(|e| format!("collect.max_size: {e}"))?;
2927            }
2928        }
2929        // #720/#743: `aggregate:` is a pure read-spec (it never touches
2930        // stdout and is never sent to an agent), so it composes with every
2931        // other hint. The per-widget rules are shared with the standalone
2932        // `view` resource — see [`validate_aggregate_widgets`].
2933        if let Some(widgets) = &self.aggregate {
2934            validate_aggregate_widgets(widgets, "aggregate")?;
2935        }
2936        // A blank / whitespace-only tag is an invisible operator typo
2937        // that would render an empty filter chip on the Jobs page —
2938        // reject it like the other present-but-blank display fields.
2939        for tag in &self.tags {
2940            if tag.trim().is_empty() {
2941                return Err("tags must not contain empty entries".to_string());
2942            }
2943        }
2944        Ok(())
2945    }
2946}
2947
2948#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
2949#[serde(rename_all = "lowercase")]
2950pub enum ExecuteShell {
2951    /// Windows PowerShell 5.1 (`powershell`).
2952    Powershell,
2953    /// `cmd.exe` (`cmd /C`). Windows only.
2954    Cmd,
2955    /// POSIX shell (`sh -c`). Linux/macOS.
2956    Sh,
2957    /// PowerShell 7, cross-platform (`pwsh`).
2958    Pwsh,
2959}
2960
2961impl From<ExecuteShell> for Shell {
2962    fn from(s: ExecuteShell) -> Self {
2963        match s {
2964            ExecuteShell::Powershell => Shell::Powershell,
2965            ExecuteShell::Cmd => Shell::Cmd,
2966            ExecuteShell::Sh => Shell::Sh,
2967            ExecuteShell::Pwsh => Shell::Pwsh,
2968        }
2969    }
2970}
2971
2972#[cfg(test)]
2973mod tests {
2974    use super::*;
2975
2976    #[test]
2977    fn inventory_payload_extracts_fenced_block() {
2978        // Readable message + fenced JSON → only the JSON, trimmed.
2979        let stdout = "Wi-Fi 設定を適用しました。\n\
2980            #KANADE-INVENTORY-BEGIN\n\
2981            {\"applied\": true}\n\
2982            #KANADE-INVENTORY-END\n";
2983        assert_eq!(inventory_payload(stdout), "{\"applied\": true}");
2984    }
2985
2986    #[test]
2987    fn inventory_payload_falls_back_to_whole_stdout() {
2988        // No fence (a plain inventory job) → whole stdout, trimmed.
2989        assert_eq!(
2990            inventory_payload("  {\"ram_gb\": 16}\n"),
2991            "{\"ram_gb\": 16}"
2992        );
2993    }
2994
2995    #[test]
2996    fn inventory_payload_handles_unterminated_fence() {
2997        // Closing marker missing (e.g. truncated) → everything after the
2998        // opener, trimmed.
2999        let stdout = "msg\n#KANADE-INVENTORY-BEGIN\n{\"a\": 1}";
3000        assert_eq!(inventory_payload(stdout), "{\"a\": 1}");
3001    }
3002
3003    #[test]
3004    fn inventory_payload_ignores_mid_line_sentinel() {
3005        // The marker echoed mid-line (not at a line start) must NOT be
3006        // treated as a fence — fall back to the whole stdout.
3007        let stdout = "see #KANADE-INVENTORY-BEGIN in the docs\nnot json";
3008        assert_eq!(inventory_payload(stdout), stdout.trim());
3009    }
3010
3011    #[test]
3012    fn fenced_payload_extracts_each_hint_block_independently() {
3013        // #821: one stdout carrying a user message + all three fenced
3014        // blocks — every consumer pulls only its own.
3015        let stdout = "\
3016done!
3017#KANADE-INVENTORY-BEGIN
3018{\"os\":\"win\"}
3019#KANADE-INVENTORY-END
3020#KANADE-CHECK-BEGIN
3021{\"status\":\"ok\"}
3022#KANADE-CHECK-END
3023#KANADE-COLLECT-BEGIN
3024{\"files\":[\"a\"]}
3025#KANADE-COLLECT-END
3026";
3027        assert_eq!(
3028            fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
3029            "{\"os\":\"win\"}"
3030        );
3031        assert_eq!(
3032            fenced_payload(stdout, CHECK_BLOCK_BEGIN, CHECK_BLOCK_END),
3033            "{\"status\":\"ok\"}"
3034        );
3035        assert_eq!(
3036            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
3037            "{\"files\":[\"a\"]}"
3038        );
3039    }
3040
3041    #[test]
3042    fn fenced_payload_falls_back_to_whole_stdout_without_fence() {
3043        // A single-hint job needs no fence — the whole (trimmed) stdout is
3044        // the payload.
3045        let stdout = "  {\"files\":[\"a\"]}  ";
3046        assert_eq!(
3047            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
3048            "{\"files\":[\"a\"]}"
3049        );
3050    }
3051
3052    #[test]
3053    fn fenced_payload_returns_empty_when_other_fences_present_but_mine_missing() {
3054        // Multi-hint output (inventory + check fenced) but the COLLECT
3055        // fence is missing — collect must NOT fall back to the whole
3056        // stdout (which holds the inventory/check blocks) and cross-parse
3057        // a sibling block; it gets "" → its JSON parse fails → no data.
3058        let stdout = "\
3059#KANADE-INVENTORY-BEGIN
3060{\"os\":\"win\"}
3061#KANADE-INVENTORY-END
3062#KANADE-CHECK-BEGIN
3063{\"status\":\"ok\"}
3064#KANADE-CHECK-END
3065";
3066        assert_eq!(
3067            fenced_payload(stdout, COLLECT_BLOCK_BEGIN, COLLECT_BLOCK_END),
3068            ""
3069        );
3070        // ...while the hints that DID fence still extract correctly.
3071        assert_eq!(
3072            fenced_payload(stdout, INVENTORY_BLOCK_BEGIN, INVENTORY_BLOCK_END),
3073            "{\"os\":\"win\"}"
3074        );
3075    }
3076
3077    /// The example check-job + schedule YAMLs shipped under `configs/`
3078    /// must stay valid as the schema evolves (#290 PR-C). `include_str!`
3079    /// pins them at compile time so a breaking edit fails `cargo test`
3080    /// rather than only `kanade job create` at deploy time.
3081    #[test]
3082    fn example_check_job_yamls_parse_and_validate() {
3083        let jobs = [
3084            (
3085                "check-bitlocker",
3086                include_str!("../../../configs/jobs/check-bitlocker.yaml"),
3087            ),
3088            (
3089                "check-av-signature",
3090                include_str!("../../../configs/jobs/check-av-signature.yaml"),
3091            ),
3092            (
3093                "check-cert-expiry",
3094                include_str!("../../../configs/jobs/check-cert-expiry.yaml"),
3095            ),
3096            (
3097                "check-disk-space",
3098                include_str!("../../../configs/jobs/check-disk-space.yaml"),
3099            ),
3100            (
3101                "check-pending-reboot",
3102                include_str!("../../../configs/jobs/check-pending-reboot.yaml"),
3103            ),
3104            (
3105                "check-defender-rtp",
3106                include_str!("../../../configs/jobs/check-defender-rtp.yaml"),
3107            ),
3108            (
3109                "check-firewall",
3110                include_str!("../../../configs/jobs/check-firewall.yaml"),
3111            ),
3112        ];
3113        for (name, yaml) in jobs {
3114            let m: Manifest =
3115                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} parse: {e}"));
3116            m.validate()
3117                .unwrap_or_else(|e| panic!("{name} validate: {e}"));
3118            let check = m
3119                .check
3120                .as_ref()
3121                .unwrap_or_else(|| panic!("{name} must carry a check: hint"));
3122            assert!(!check.name.trim().is_empty(), "{name} check.name empty");
3123            // These examples all read admin-only WMI / registry / netsh
3124            // state, so they run_as system. NOTE: that's a property of
3125            // these particular checks, NOT of the `check:` contract — a
3126            // check probing user-session state could run_as user.
3127            assert_eq!(
3128                m.execute.run_as,
3129                RunAs::System,
3130                "{name} should run_as system"
3131            );
3132        }
3133    }
3134
3135    /// The example user-invokable job YAMLs (#291) shipped under
3136    /// `configs/jobs/` must stay valid as the `client:` schema
3137    /// evolves. `include_str!` pins them at compile time so a breaking
3138    /// edit fails `cargo test`, not `kanade job create` at deploy.
3139    #[test]
3140    fn example_client_job_yamls_parse_and_validate() {
3141        let jobs = [
3142            (
3143                "fix-teams-cache",
3144                "troubleshoot",
3145                include_str!("../../../configs/jobs/fix-teams-cache.yaml"),
3146            ),
3147            (
3148                "chrome-update",
3149                "software_update",
3150                include_str!("../../../configs/jobs/chrome-update.yaml"),
3151            ),
3152            (
3153                "install-slack",
3154                "catalog",
3155                include_str!("../../../configs/jobs/install-slack.yaml"),
3156            ),
3157            (
3158                "fix-defender-rtp",
3159                "troubleshoot",
3160                include_str!("../../../configs/jobs/fix-defender-rtp.yaml"),
3161            ),
3162            // #792 custom category ("settings") + #809 message/inventory.
3163            (
3164                "example-power-plan",
3165                "settings",
3166                include_str!("../../../configs/jobs/example-power-plan.yaml"),
3167            ),
3168            // #792: diagnostics moved to its own "support" tab.
3169            (
3170                "collect-diagnostics",
3171                "support",
3172                include_str!("../../../configs/jobs/collect-diagnostics.yaml"),
3173            ),
3174        ];
3175        for (id, category, yaml) in jobs {
3176            let m: Manifest =
3177                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
3178            m.validate()
3179                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
3180            assert_eq!(m.id, id, "{id} id mismatch");
3181            let client = m
3182                .client
3183                .as_ref()
3184                .unwrap_or_else(|| panic!("{id} must carry a client: block"));
3185            assert!(!client.name.trim().is_empty(), "{id} client.name empty");
3186            assert_eq!(client.category, category, "{id} category");
3187        }
3188    }
3189
3190    /// #219: the shipped `collect:` example must stay valid as the
3191    /// schema evolves. `include_str!` pins it at compile time so a
3192    /// breaking edit (or a YAML typo in the PowerShell block) fails
3193    /// `cargo test` rather than `kanade job create` at deploy. It carries
3194    /// both `collect:` and `client:` (end-user-triggerable), which must
3195    /// compose.
3196    #[test]
3197    fn example_collect_job_yaml_parses_and_validates() {
3198        let yaml = include_str!("../../../configs/jobs/collect-diagnostics.yaml");
3199        let m: Manifest = serde_yaml::from_str(yaml).expect("collect-diagnostics parse");
3200        m.validate().expect("collect-diagnostics validate");
3201        assert_eq!(m.id, "collect-diagnostics");
3202        let collect = m.collect.as_ref().expect("collect: block present");
3203        assert!(!collect.name.trim().is_empty());
3204        assert_eq!(collect.files_field, "files");
3205        assert_eq!(collect.max_size_bytes(), 50_000_000);
3206        // collect + client compose — the Client App can trigger it.
3207        assert!(
3208            m.client.is_some(),
3209            "collect-diagnostics also carries client:"
3210        );
3211    }
3212
3213    /// The `emit: { type: events }` collector jobs under
3214    /// `configs/jobs/` feed the obs_events timeline. `include_str!`
3215    /// pins them at compile time so a breaking edit (e.g. an `emit:`
3216    /// paired with `check:`/`inventory:`, a bad watermark field, or a
3217    /// YAML typo in the PowerShell block) fails `cargo test` rather
3218    /// than `kanade job create` at deploy. Every one must carry an
3219    /// `emit.type=events` block and NO check/inventory (validate()
3220    /// rejects the pairing).
3221    #[test]
3222    fn example_event_collector_job_yamls_parse_and_validate() {
3223        let jobs = [
3224            // collect-winlog-events was retired in #841 PR2 — the scheduled
3225            // human-session / power timeline is now read natively by the
3226            // agent (kanade-agent `winlog` module via EvtQuery), no
3227            // PowerShell job. collect-winlog-logons-all stays as the
3228            // on-demand forensic all-token-logons companion.
3229            (
3230                "collect-winlog-logons-all",
3231                include_str!("../../../configs/jobs/collect-winlog-logons-all.yaml"),
3232            ),
3233            (
3234                "collect-wlan-events",
3235                include_str!("../../../configs/jobs/collect-wlan-events.yaml"),
3236            ),
3237        ];
3238        for (id, yaml) in jobs {
3239            // Strict parse so an unknown-key typo in these fixtures fails
3240            // here (not silently at deploy) — the runtime Manifest is
3241            // unknown-key-tolerant, so the lenient serde_yaml::from_str
3242            // wouldn't catch fixture drift (CodeRabbit #689).
3243            let m: Manifest =
3244                crate::strict::from_yaml_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
3245            m.validate()
3246                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
3247            assert_eq!(m.id, id, "{id} id mismatch");
3248            let emit = m
3249                .emit
3250                .as_ref()
3251                .unwrap_or_else(|| panic!("{id} must carry an emit: block"));
3252            assert_eq!(emit.kind, EmitKind::Events, "{id} emit.type");
3253            assert!(
3254                m.check.is_none() && m.inventory.is_none(),
3255                "{id}: emit jobs must not pair with check/inventory"
3256            );
3257        }
3258    }
3259
3260    /// The `inventory:` snapshot jobs under `configs/jobs/` project
3261    /// facts into `inventory_facts` + exploded tables. `include_str!`
3262    /// pins them at compile time so a breaking edit (bad explode
3263    /// schema, a YAML typo in the PowerShell block, an `inventory:`
3264    /// accidentally paired with `emit:`) fails `cargo test` rather
3265    /// than the projector at deploy. Each must carry an `inventory:`
3266    /// block and NO emit (validate() rejects the pairing).
3267    #[test]
3268    fn example_inventory_job_yamls_parse_and_validate() {
3269        let jobs = [
3270            (
3271                "inventory-hw",
3272                include_str!("../../../configs/jobs/inventory-hw.yaml"),
3273            ),
3274            (
3275                "inventory-sw",
3276                include_str!("../../../configs/jobs/inventory-sw.yaml"),
3277            ),
3278            (
3279                "inventory-driver",
3280                include_str!("../../../configs/jobs/inventory-driver.yaml"),
3281            ),
3282        ];
3283        for (id, yaml) in jobs {
3284            let m: Manifest =
3285                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{id} parse: {e}"));
3286            m.validate()
3287                .unwrap_or_else(|e| panic!("{id} validate: {e}"));
3288            assert_eq!(m.id, id, "{id} id mismatch");
3289            assert!(m.inventory.is_some(), "{id} must carry an inventory: block");
3290            assert!(m.emit.is_none(), "{id}: inventory jobs must not set emit:");
3291        }
3292    }
3293
3294    #[test]
3295    fn example_check_schedule_yamls_parse_and_validate() {
3296        let schedules = [
3297            (
3298                "check-bitlocker",
3299                include_str!("../../../configs/schedules/check-bitlocker.yaml"),
3300            ),
3301            (
3302                "check-av-signature",
3303                include_str!("../../../configs/schedules/check-av-signature.yaml"),
3304            ),
3305            (
3306                "check-cert-expiry",
3307                include_str!("../../../configs/schedules/check-cert-expiry.yaml"),
3308            ),
3309            (
3310                "check-disk-space",
3311                include_str!("../../../configs/schedules/check-disk-space.yaml"),
3312            ),
3313            (
3314                "check-pending-reboot",
3315                include_str!("../../../configs/schedules/check-pending-reboot.yaml"),
3316            ),
3317            (
3318                "check-defender-rtp",
3319                include_str!("../../../configs/schedules/check-defender-rtp.yaml"),
3320            ),
3321            (
3322                "check-firewall",
3323                include_str!("../../../configs/schedules/check-firewall.yaml"),
3324            ),
3325        ];
3326        for (name, yaml) in schedules {
3327            let s: Schedule =
3328                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
3329            s.validate()
3330                .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
3331            assert_eq!(s.job_id, name, "{name} schedule must reference its job");
3332        }
3333    }
3334
3335    /// Inventory schedule wrappers (`per_pc` cadence) must stay valid
3336    /// alongside the schedule schema. `include_str!` pins them so a
3337    /// breaking edit fails `cargo test`, not `kanade schedule create`.
3338    #[test]
3339    fn example_inventory_schedule_yamls_parse_and_validate() {
3340        let schedules = [
3341            (
3342                "inventory-hw",
3343                include_str!("../../../configs/schedules/inventory-hw.yaml"),
3344            ),
3345            (
3346                "inventory-sw",
3347                include_str!("../../../configs/schedules/inventory-sw.yaml"),
3348            ),
3349            (
3350                "inventory-driver",
3351                include_str!("../../../configs/schedules/inventory-driver.yaml"),
3352            ),
3353        ];
3354        for (name, yaml) in schedules {
3355            let s: Schedule =
3356                serde_yaml::from_str(yaml).unwrap_or_else(|e| panic!("{name} schedule parse: {e}"));
3357            s.validate()
3358                .unwrap_or_else(|e| panic!("{name} schedule validate: {e}"));
3359            assert_eq!(s.job_id, name, "{name} schedule must reference its job");
3360        }
3361    }
3362
3363    #[test]
3364    fn target_is_specified_requires_at_least_one_field() {
3365        let empty = Target::default();
3366        assert!(!empty.is_specified());
3367
3368        let with_all = Target {
3369            all: true,
3370            ..Target::default()
3371        };
3372        assert!(with_all.is_specified());
3373
3374        let with_groups = Target {
3375            groups: vec!["canary".into()],
3376            ..Target::default()
3377        };
3378        assert!(with_groups.is_specified());
3379
3380        let with_pcs = Target {
3381            pcs: vec!["pc-01".into()],
3382            ..Target::default()
3383        };
3384        assert!(with_pcs.is_specified());
3385    }
3386
3387    #[test]
3388    fn manifest_deserialises_minimal_yaml() {
3389        // Matches jobs/echo-test.yaml. v0.18: no target/rollout/jitter
3390        // — those live on the schedule / exec request now.
3391        let yaml = r#"
3392id: echo-test
3393version: 0.0.1
3394execute:
3395  shell: powershell
3396  script: "echo 'kanade'"
3397  timeout: 30s
3398"#;
3399        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3400        assert_eq!(m.id, "echo-test");
3401        assert_eq!(m.version, "0.0.1");
3402        assert!(matches!(m.execute.shell, ExecuteShell::Powershell));
3403        assert_eq!(
3404            m.execute.script.as_deref().map(str::trim),
3405            Some("echo 'kanade'")
3406        );
3407        assert!(m.execute.script_file.is_none());
3408        assert!(m.execute.script_object.is_none());
3409        assert_eq!(m.execute.timeout, "30s");
3410        assert!(!m.require_approval);
3411        m.validate()
3412            .expect("inline-script manifest passes validation");
3413    }
3414
3415    #[test]
3416    fn manifest_parses_check_job_and_validates() {
3417        // An operator-defined health check (#290): a `check:` hint +
3418        // a PowerShell script that prints {status, detail}.
3419        let yaml = r#"
3420id: check-bitlocker
3421version: 0.1.0
3422execute:
3423  shell: powershell
3424  run_as: system
3425  timeout: 15s
3426  script: |
3427    [pscustomobject]@{ status = 'ok'; detail = 'all volumes protected' } | ConvertTo-Json -Compress
3428check:
3429  name: bitlocker
3430  troubleshoot: fix-bitlocker
3431"#;
3432        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3433        let check = m.check.as_ref().expect("check hint present");
3434        assert_eq!(check.name, "bitlocker");
3435        assert_eq!(check.troubleshoot.as_deref(), Some("fix-bitlocker"));
3436        // Field names default to the conventional "status" / "detail".
3437        assert_eq!(check.status_field, "status");
3438        assert_eq!(check.detail_field, "detail");
3439        assert!(m.inventory.is_none() && m.emit.is_none());
3440        m.validate().expect("check-only manifest passes validation");
3441    }
3442
3443    #[test]
3444    fn manifest_check_defaults_and_custom_fields() {
3445        // Minimal: only `name`; status/detail fields default.
3446        let m: Manifest = serde_yaml::from_str(
3447            r#"
3448id: check-disk
3449version: 0.1.0
3450execute:
3451  shell: powershell
3452  script: "[pscustomobject]@{ status = 'ok' } | ConvertTo-Json -Compress"
3453  timeout: 10s
3454check:
3455  name: disk_free
3456"#,
3457        )
3458        .expect("parse");
3459        let c = m.check.as_ref().unwrap();
3460        assert_eq!(c.name, "disk_free");
3461        assert_eq!(c.status_field, "status");
3462        assert_eq!(c.detail_field, "detail");
3463        assert!(c.troubleshoot.is_none());
3464        m.validate().expect("validates");
3465
3466        // The operator can point status/detail at any field of their
3467        // free-form inventory object.
3468        let m2: Manifest = serde_yaml::from_str(
3469            r#"
3470id: check-custom
3471version: 0.1.0
3472execute:
3473  shell: powershell
3474  script: "echo x"
3475  timeout: 10s
3476check:
3477  name: patch_level
3478  status_field: compliance
3479  detail_field: summary
3480"#,
3481        )
3482        .expect("parse");
3483        let c2 = m2.check.as_ref().unwrap();
3484        assert_eq!(c2.status_field, "compliance");
3485        assert_eq!(c2.detail_field, "summary");
3486    }
3487
3488    #[test]
3489    fn manifest_allows_check_composed_with_inventory() {
3490        // `check:` + `inventory:` COMPOSE on the same stdout object:
3491        // status/detail → Health tab, the rest → SPA projection +
3492        // explode sub-tables. Must pass validation.
3493        let yaml = r#"
3494id: check-bitlocker-detailed
3495version: 0.1.0
3496execute:
3497  shell: powershell
3498  script: "echo x"
3499  timeout: 10s
3500check:
3501  name: bitlocker
3502inventory:
3503  display:
3504    - { field: status, label: Status }
3505"#;
3506        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3507        assert!(m.check.is_some() && m.inventory.is_some());
3508        m.validate().expect("check + inventory compose");
3509    }
3510
3511    #[test]
3512    fn manifest_parses_collect_job_and_validates() {
3513        // #219: a `collect:` hint + a script that lists files on stdout.
3514        let yaml = r#"
3515id: collect-diagnostics
3516version: 0.1.0
3517execute:
3518  shell: powershell
3519  run_as: system
3520  timeout: 120s
3521  script: |
3522    @{ files = @("$env:KANADE_COLLECT_DIR/system.csv") } | ConvertTo-Json
3523collect:
3524  name: "Full diagnostics"
3525  description: "Event logs + process"
3526  max_size: 50MB
3527"#;
3528        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3529        let c = m.collect.as_ref().expect("collect hint present");
3530        assert_eq!(c.name, "Full diagnostics");
3531        assert_eq!(c.files_field, "files"); // default
3532        assert_eq!(c.max_size_bytes(), 50_000_000);
3533        m.validate().expect("collect-only manifest validates");
3534    }
3535
3536    #[test]
3537    fn manifest_finalize_powershell_validates_and_lowers() {
3538        let yaml = r#"
3539id: collect-fin
3540version: 0.1.0
3541execute:
3542  shell: powershell
3543  timeout: 120s
3544  script: |
3545    @{ files = @() } | ConvertTo-Json
3546collect:
3547  name: "diag"
3548  max_size: 50MB
3549finalize:
3550  shell: powershell
3551  timeout: 30s
3552  run_as: system
3553  script: |
3554    Write-Output "cleanup"
3555"#;
3556        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3557        m.validate().expect("powershell finalize validates");
3558        let lowered = m.finalize.as_ref().expect("finalize present").lower();
3559        assert_eq!(lowered.timeout_secs, 30);
3560        assert!(matches!(lowered.shell, Shell::Powershell));
3561        // #965: default is the one-call-after-all contract.
3562        assert!(!lowered.on_each_bundle);
3563    }
3564
3565    #[test]
3566    fn manifest_finalize_on_each_bundle_validates_with_collect_and_lowers() {
3567        // #965: on_each_bundle + a collect hint is the intended
3568        // combination — validates, and the flag survives lowering.
3569        let yaml = r#"
3570id: collect-fin-each
3571version: 0.1.0
3572execute:
3573  shell: powershell
3574  timeout: 120s
3575  script: |
3576    @{ files = @() } | ConvertTo-Json
3577collect:
3578  name: "diag"
3579  max_size: 50MB
3580finalize:
3581  shell: powershell
3582  on_each_bundle: true
3583  script: |
3584    Write-Output "cleanup"
3585"#;
3586        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3587        m.validate().expect("on_each_bundle + collect validates");
3588        let lowered = m.finalize.as_ref().expect("finalize present").lower();
3589        assert!(lowered.on_each_bundle, "flag survives lowering");
3590    }
3591
3592    #[test]
3593    fn manifest_finalize_on_each_bundle_without_collect_rejected() {
3594        // #965: a non-collect finalize has no bundles to iterate, so
3595        // on_each_bundle is a no-op — reject it at the write boundary so
3596        // the operator is told rather than silently getting nothing.
3597        let yaml = r#"
3598id: fin-each-no-collect
3599version: 0.1.0
3600execute:
3601  shell: powershell
3602  timeout: 120s
3603  script: |
3604    Write-Output "hi"
3605finalize:
3606  shell: powershell
3607  on_each_bundle: true
3608  script: |
3609    Write-Output "cleanup"
3610"#;
3611        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3612        let err = m
3613            .validate()
3614            .expect_err("on_each_bundle without collect rejected");
3615        assert!(err.contains("on_each_bundle"), "got: {err}");
3616        assert!(err.contains("collect"), "got: {err}");
3617    }
3618
3619    #[test]
3620    fn manifest_finalize_rejects_cmd_shell() {
3621        // cmd finalize is an injection risk (the agent injects JSON into
3622        // the hook's env; cmd.exe quoting doesn't nest) — validate must
3623        // reject it.
3624        let yaml = r#"
3625id: collect-fin-cmd
3626version: 0.1.0
3627execute:
3628  shell: powershell
3629  timeout: 120s
3630  script: |
3631    @{ files = @() } | ConvertTo-Json
3632finalize:
3633  shell: cmd
3634  script: |
3635    echo hi
3636"#;
3637        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3638        let err = m.validate().expect_err("cmd finalize rejected");
3639        assert!(err.contains("finalize.shell"), "got: {err}");
3640    }
3641
3642    #[test]
3643    fn manifest_finalize_rejects_sh_shell() {
3644        // sh finalize is rejected for the same reason as cmd: the agent
3645        // injects the result JSON, and the injected prelude is PowerShell
3646        // syntax that a POSIX shell can't run.
3647        let yaml = r#"
3648id: collect-fin-sh
3649version: 0.1.0
3650execute:
3651  shell: powershell
3652  timeout: 120s
3653  script: |
3654    @{ files = @() } | ConvertTo-Json
3655finalize:
3656  shell: sh
3657  script: |
3658    echo hi
3659"#;
3660        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3661        let err = m.validate().expect_err("sh finalize rejected");
3662        assert!(err.contains("finalize.shell"), "got: {err}");
3663    }
3664
3665    #[test]
3666    fn manifest_finalize_accepts_pwsh_shell() {
3667        // pwsh IS PowerShell, so the injected prelude + single-quote
3668        // escaping are valid and safe — a pwsh finalize must validate.
3669        let yaml = r#"
3670id: collect-fin-pwsh
3671version: 0.1.0
3672execute:
3673  shell: pwsh
3674  timeout: 120s
3675  script: |
3676    @{ files = @() } | ConvertTo-Json
3677finalize:
3678  shell: pwsh
3679  script: |
3680    Write-Output hi
3681"#;
3682        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3683        m.validate().expect("pwsh finalize accepted");
3684    }
3685
3686    #[test]
3687    fn manifest_finalize_rejects_empty_script() {
3688        let yaml = r#"
3689id: collect-fin-empty
3690version: 0.1.0
3691execute:
3692  shell: powershell
3693  timeout: 120s
3694  script: |
3695    @{ files = @() } | ConvertTo-Json
3696finalize:
3697  shell: powershell
3698  script: "   "
3699"#;
3700        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3701        let err = m.validate().expect_err("empty finalize script rejected");
3702        assert!(err.contains("finalize.script"), "got: {err}");
3703    }
3704
3705    #[test]
3706    fn manifest_collect_max_size_defaults_when_unset() {
3707        let m: Manifest = serde_yaml::from_str(
3708            r#"
3709id: collect-min
3710version: 0.1.0
3711execute:
3712  shell: powershell
3713  script: "echo x"
3714  timeout: 10s
3715collect:
3716  name: minimal
3717"#,
3718        )
3719        .expect("parse");
3720        let c = m.collect.as_ref().unwrap();
3721        assert!(c.max_size.is_none());
3722        assert_eq!(c.max_size_bytes(), DEFAULT_COLLECT_MAX_SIZE);
3723        m.validate().expect("validates");
3724    }
3725
3726    #[test]
3727    fn manifest_allows_collect_with_client() {
3728        // collect composes with client (client doesn't touch stdout):
3729        // an end user can trigger a collection from the Client App.
3730        let yaml = r#"
3731id: collect-diag-client
3732version: 0.1.0
3733execute:
3734  shell: powershell
3735  script: "echo x"
3736  timeout: 10s
3737collect:
3738  name: diagnostics
3739client:
3740  name: "Send diagnostics"
3741  category: troubleshoot
3742"#;
3743        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3744        assert!(m.collect.is_some() && m.client.is_some());
3745        m.validate().expect("collect + client compose");
3746    }
3747
3748    #[test]
3749    fn manifest_allows_inventory_check_collect_coexistence() {
3750        // #821: the three fenced hints now COMPOSE — each reads its own
3751        // `#KANADE-<KIND>` stdout block, so one job can do all three.
3752        let yaml = r#"
3753id: multi-hint
3754version: 0.1.0
3755execute:
3756  shell: powershell
3757  script: "echo x"
3758  timeout: 10s
3759inventory:
3760  display:
3761    - { field: status, label: Status }
3762check:
3763  name: health
3764collect:
3765  name: diag
3766"#;
3767        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3768        m.validate()
3769            .expect("inventory + check + collect coexist after #821");
3770    }
3771
3772    #[test]
3773    fn manifest_rejects_emit_combined_with_fenced_hints() {
3774        // `emit:` consumes stdout as NDJSON (and blanks it), so it still
3775        // can't share with any fenced hint — inventory, check, OR collect.
3776        for extra in [
3777            "inventory:\n  display:\n    - { field: s, label: S }\n",
3778            "check:\n  name: health\n",
3779            "collect:\n  name: diag\n",
3780        ] {
3781            let yaml = format!(
3782                "id: bad-emit-mix\nversion: 0.1.0\nexecute:\n  shell: powershell\n  \
3783                 script: \"echo x\"\n  timeout: 10s\nemit:\n  type: events\n{extra}"
3784            );
3785            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
3786            let err = m
3787                .validate()
3788                .expect_err("emit + fenced hint must be rejected");
3789            assert!(err.contains("emit"), "error mentions emit: {err}");
3790        }
3791    }
3792
3793    #[test]
3794    fn manifest_rejects_collect_empty_name_and_bad_size() {
3795        let empty_name: Manifest = serde_yaml::from_str(
3796            r#"
3797id: c
3798version: 0.1.0
3799execute: { shell: powershell, script: "echo x", timeout: 10s }
3800collect: { name: "  " }
3801"#,
3802        )
3803        .expect("parse");
3804        assert!(
3805            empty_name.validate().is_err(),
3806            "blank collect.name rejected"
3807        );
3808
3809        let bad_size: Manifest = serde_yaml::from_str(
3810            r#"
3811id: c
3812version: 0.1.0
3813execute: { shell: powershell, script: "echo x", timeout: 10s }
3814collect: { name: diag, max_size: "50 quux" }
3815"#,
3816        )
3817        .expect("parse");
3818        let err = bad_size.validate().expect_err("bad max_size rejected");
3819        assert!(err.contains("max_size"), "error mentions max_size: {err}");
3820    }
3821
3822    #[test]
3823    fn parse_size_bytes_units() {
3824        assert_eq!(parse_size_bytes("1024").unwrap(), 1024);
3825        assert_eq!(parse_size_bytes("1B").unwrap(), 1);
3826        assert_eq!(parse_size_bytes("50MB").unwrap(), 50_000_000);
3827        assert_eq!(parse_size_bytes("500 KB").unwrap(), 500_000);
3828        assert_eq!(parse_size_bytes("1GiB").unwrap(), 1024 * 1024 * 1024);
3829        assert_eq!(parse_size_bytes("2mib").unwrap(), 2 * 1024 * 1024);
3830        assert!(parse_size_bytes("").is_err());
3831        assert!(parse_size_bytes("MB").is_err());
3832        assert!(parse_size_bytes("12 zonks").is_err());
3833    }
3834
3835    #[test]
3836    fn manifest_rejects_check_combined_with_emit() {
3837        // `emit:` stdout is NDJSON (and omitted from the result), so
3838        // it can't pair with `check:` (which needs a single JSON
3839        // object on stdout).
3840        let yaml = r#"
3841id: bad-mix
3842version: 0.1.0
3843execute:
3844  shell: powershell
3845  script: "echo x"
3846  timeout: 10s
3847check:
3848  name: bitlocker
3849emit:
3850  type: events
3851"#;
3852        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3853        let err = m.validate().expect_err("emit + check must fail");
3854        assert!(err.contains("incompatible"), "err: {err}");
3855    }
3856
3857    #[test]
3858    fn manifest_rejects_emit_combined_with_inventory() {
3859        // The other half of the emit-incompatibility condition.
3860        let yaml = r#"
3861id: bad-mix-2
3862version: 0.1.0
3863execute:
3864  shell: powershell
3865  script: "echo x"
3866  timeout: 10s
3867emit:
3868  type: events
3869inventory:
3870  display:
3871    - { field: status, label: Status }
3872"#;
3873        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3874        let err = m.validate().expect_err("emit + inventory must fail");
3875        assert!(err.contains("incompatible"), "err: {err}");
3876    }
3877
3878    #[test]
3879    fn manifest_rejects_empty_check_field_names() {
3880        // Empty name / status_field / detail_field are invisible
3881        // runtime bugs (empty React key, agent reads the wrong field)
3882        // — reject them even though serde supplies non-empty defaults.
3883        let base = |inner: &str| {
3884            format!(
3885                "id: c\nversion: 0.1.0\nexecute:\n  shell: powershell\n  script: \"echo x\"\n  timeout: 10s\ncheck:\n{inner}"
3886            )
3887        };
3888        for inner in [
3889            "  name: \"\"\n",
3890            "  name: ok\n  status_field: \"\"\n",
3891            "  name: ok\n  detail_field: \"   \"\n",
3892            // present-but-blank troubleshoot → broken remediation id.
3893            "  name: ok\n  troubleshoot: \"  \"\n",
3894        ] {
3895            let m: Manifest = serde_yaml::from_str(&base(inner)).expect("parse");
3896            let err = m.validate().expect_err("empty field must fail");
3897            assert!(err.contains("must not be empty"), "err: {err}");
3898        }
3899    }
3900
3901    #[test]
3902    fn check_alert_decodes_with_defaults_and_validates() {
3903        let yaml = r#"
3904id: c
3905version: 0.1.0
3906execute:
3907  shell: powershell
3908  script: "echo x"
3909  timeout: 10s
3910check:
3911  name: bitlocker
3912  alert:
3913    notify_user: true
3914    title: "BitLocker 未準拠"
3915"#;
3916        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3917        m.validate().expect("valid alert");
3918        let alert = m.check.unwrap().alert.unwrap();
3919        // Defaults: on = [fail], priority = warn, body = None.
3920        assert_eq!(alert.on, vec![CheckAlertStatus::Fail]);
3921        assert_eq!(
3922            alert.priority,
3923            crate::ipc::notifications::NotificationPriority::Warn
3924        );
3925        assert!(alert.body.is_none());
3926        assert!(alert.notify_user);
3927    }
3928
3929    #[test]
3930    fn check_alert_validation_rejects_bad_configs() {
3931        let base = |alert: &str| {
3932            format!(
3933                "id: c\nversion: 0.1.0\nexecute:\n  shell: powershell\n  script: \"echo x\"\n  timeout: 10s\ncheck:\n  name: bitlocker\n  alert:\n{alert}"
3934            )
3935        };
3936        let cases = [
3937            // No recipient.
3938            ("    title: t\n", "notify_user and/or notify_groups"),
3939            // Empty title.
3940            (
3941                "    notify_user: true\n    title: \"  \"\n",
3942                "title must not be empty",
3943            ),
3944            // Empty `on`.
3945            (
3946                "    notify_user: true\n    title: t\n    on: []\n",
3947                "on must list at least one status",
3948            ),
3949            // Blank group name.
3950            (
3951                "    notify_groups: [\"  \"]\n    title: t\n",
3952                "notify_groups must not contain blanks",
3953            ),
3954            // alert requires fleet: true.
3955            (
3956                "    notify_user: true\n    title: t\n  fleet: false\n",
3957                "requires fleet: true",
3958            ),
3959            // email opt-in without a group to address.
3960            (
3961                "    notify_user: true\n    email: true\n    title: t\n",
3962                "email requires notify_groups",
3963            ),
3964        ];
3965        for (alert, want) in cases {
3966            let m: Manifest = serde_yaml::from_str(&base(alert)).expect("parse");
3967            let err = m.validate().expect_err("bad alert must fail");
3968            assert!(err.contains(want), "for {alert:?}: got {err}");
3969        }
3970    }
3971
3972    #[test]
3973    fn manifest_client_absent_by_default() {
3974        // A plain operator job (the overwhelming majority) carries no
3975        // `client:` block, so it never surfaces in the end-user
3976        // catalog.
3977        let yaml = r#"
3978id: echo-test
3979version: 0.0.1
3980execute:
3981  shell: powershell
3982  script: "echo 'kanade'"
3983  timeout: 30s
3984"#;
3985        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
3986        assert!(m.client.is_none());
3987        m.validate().expect("operator-only job validates");
3988    }
3989
3990    #[test]
3991    fn manifest_client_parses_and_validates() {
3992        // The Client App "困ったとき" remediation job shape: a
3993        // user-invokable troubleshoot job with the end-user fields the
3994        // KLP `jobs.list` wire needs, grouped under `client:`.
3995        let yaml = r#"
3996id: fix-teams-cache
3997version: 1.0.0
3998execute:
3999  shell: powershell
4000  script: "echo clearing"
4001  timeout: 60s
4002client:
4003  name: "Teams のキャッシュをクリア"
4004  description: "Teams が重いときに試してください"
4005  category: troubleshoot
4006  icon: brush-cleaning
4007"#;
4008        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4009        let c = m.client.as_ref().expect("client block present");
4010        assert_eq!(c.name, "Teams のキャッシュをクリア");
4011        assert_eq!(
4012            c.description.as_deref(),
4013            Some("Teams が重いときに試してください")
4014        );
4015        assert_eq!(c.category, "troubleshoot");
4016        assert_eq!(c.icon.as_deref(), Some("brush-cleaning"));
4017        m.validate().expect("user-invokable job validates");
4018    }
4019
4020    #[test]
4021    fn manifest_client_minimal_only_name_and_category() {
4022        // description + icon are optional; name + category are the
4023        // serde-required minimum.
4024        let yaml = r#"
4025id: install-slack
4026version: 1.0.0
4027execute:
4028  shell: powershell
4029  script: "echo install"
4030  timeout: 600s
4031client:
4032  name: Slack
4033  category: catalog
4034"#;
4035        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4036        let c = m.client.as_ref().expect("client present");
4037        assert_eq!(c.category, "catalog");
4038        assert!(c.description.is_none() && c.icon.is_none());
4039        m.validate().expect("minimal client validates");
4040    }
4041
4042    #[test]
4043    fn manifest_client_rejects_blank_name() {
4044        // serde guarantees `name`/`category` are present; the one gap
4045        // is a present-but-blank name → empty catalog row title.
4046        let yaml = r#"
4047id: j
4048version: 1.0.0
4049execute:
4050  shell: powershell
4051  script: "echo x"
4052  timeout: 30s
4053client:
4054  name: "   "
4055  category: catalog
4056"#;
4057        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4058        let err = m.validate().expect_err("blank name must fail");
4059        assert!(err.contains("client.name"), "err: {err}");
4060    }
4061
4062    #[test]
4063    fn manifest_client_rejects_blank_optional_fields() {
4064        // description / icon are optional, but a present-but-blank
4065        // value is a bug (empty subtitle / dangling icon name) — reject
4066        // it, mirroring the check: block's troubleshoot guard.
4067        for (field, line) in [
4068            ("client.description", "  description: \"  \"\n"),
4069            ("client.icon", "  icon: \"\"\n"),
4070            // #792: the new category tab-metadata fields get the same
4071            // present-but-blank guard.
4072            ("client.category_label", "  category_label: \"  \"\n"),
4073            ("client.category_icon", "  category_icon: \"\"\n"),
4074        ] {
4075            let yaml = format!(
4076                "id: j\nversion: 1.0.0\nexecute:\n  shell: powershell\n  script: \"echo x\"\n  timeout: 30s\nclient:\n  name: A\n  category: catalog\n{line}"
4077            );
4078            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
4079            let err = m.validate().expect_err("blank optional field must fail");
4080            assert!(err.contains(field), "expected {field} in err: {err}");
4081        }
4082    }
4083
4084    #[test]
4085    fn manifest_client_rejects_blank_category() {
4086        // #792: category is a free-form key now; serde keeps it required,
4087        // but a present-but-blank value would group the job under an empty
4088        // tab — validate() must reject it.
4089        let yaml = r#"
4090id: j
4091version: 1.0.0
4092execute:
4093  shell: powershell
4094  script: "echo x"
4095  timeout: 30s
4096client:
4097  name: "A job"
4098  category: "   "
4099"#;
4100        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4101        let err = m.validate().expect_err("blank category must fail");
4102        assert!(err.contains("client.category"), "err: {err}");
4103    }
4104
4105    #[test]
4106    fn target_matches_pc_group_and_all() {
4107        // #816: pc match, group match, all, and the no-match case.
4108        let by_pc = Target {
4109            pcs: vec!["PC1".into()],
4110            ..Default::default()
4111        };
4112        assert!(by_pc.matches("PC1", &[]));
4113        assert!(!by_pc.matches("PC2", &["g1".into()]));
4114
4115        let by_group = Target {
4116            groups: vec!["g1".into()],
4117            ..Default::default()
4118        };
4119        assert!(by_group.matches("PC2", &["g1".into()]));
4120        assert!(!by_group.matches("PC2", &["g2".into()]));
4121
4122        let all = Target {
4123            all: true,
4124            ..Default::default()
4125        };
4126        assert!(all.matches("anyPC", &[]));
4127    }
4128
4129    #[test]
4130    fn manifest_client_rejects_empty_visible_to() {
4131        // #816: a present-but-empty visible_to (no all/groups/pcs) would
4132        // hide the job from everyone — validate() must reject it.
4133        let yaml = r#"
4134id: j
4135version: 1.0.0
4136execute:
4137  shell: powershell
4138  script: "echo x"
4139  timeout: 30s
4140client:
4141  name: "A job"
4142  category: troubleshoot
4143  visible_to: {}
4144"#;
4145        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4146        let err = m.validate().expect_err("empty visible_to must fail");
4147        assert!(err.contains("client.visible_to"), "err: {err}");
4148    }
4149
4150    #[test]
4151    fn manifest_client_accepts_visible_to_groups() {
4152        let yaml = r#"
4153id: j
4154version: 1.0.0
4155execute:
4156  shell: powershell
4157  script: "echo x"
4158  timeout: 30s
4159client:
4160  name: "A job"
4161  category: settings
4162  visible_to:
4163    groups: [wifi-affected]
4164"#;
4165        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4166        m.validate().expect("visible_to with a group validates");
4167        let vt = m.client.unwrap().visible_to.unwrap();
4168        assert_eq!(vt.groups, vec!["wifi-affected".to_string()]);
4169    }
4170
4171    #[test]
4172    fn manifest_client_show_when_accepts_scalar_and_seq() {
4173        use crate::ipc::state::CheckStatus;
4174        // `is:` accepts a single status (author ergonomics) ...
4175        let scalar = r#"
4176id: office-update
4177version: 1.0.0
4178execute:
4179  shell: powershell
4180  script: "echo x"
4181  timeout: 30s
4182client:
4183  name: "Office を最新に更新"
4184  category: software_update
4185  show_when:
4186    check: office-up-to-date
4187    is: fail
4188"#;
4189        let m: Manifest = serde_yaml::from_str(scalar).expect("parse scalar");
4190        m.validate().expect("scalar show_when validates");
4191        let sw = m.client.unwrap().show_when.unwrap();
4192        assert_eq!(sw.check, "office-up-to-date");
4193        assert_eq!(sw.is, vec![CheckStatus::Fail]);
4194
4195        // ... and a list (e.g. fail-open on a not-yet-run check).
4196        let seq = scalar.replace("is: fail", "is: [fail, unknown]");
4197        let m: Manifest = serde_yaml::from_str(&seq).expect("parse seq");
4198        m.validate().expect("seq show_when validates");
4199        assert_eq!(
4200            m.client.unwrap().show_when.unwrap().is,
4201            vec![CheckStatus::Fail, CheckStatus::Unknown]
4202        );
4203    }
4204
4205    #[test]
4206    fn manifest_client_unlock_round_trips_and_defaults_absent() {
4207        let yaml = r#"
4208id: j
4209version: 1.0.0
4210execute:
4211  shell: powershell
4212  script: "echo x"
4213  timeout: 30s
4214client:
4215  name: "A job"
4216  category: troubleshoot
4217  unlock: support
4218"#;
4219        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4220        m.validate().expect("valid");
4221        assert_eq!(
4222            m.client.as_ref().unwrap().unlock.as_deref(),
4223            Some("support")
4224        );
4225
4226        // Absent ⇒ an ordinary job, and absent from the encoded form too, so
4227        // an older reader sees byte-for-byte what it saw before the field.
4228        let plain = yaml.replace("  unlock: support\n", "");
4229        let m: Manifest = serde_yaml::from_str(&plain).expect("parse");
4230        assert!(m.client.as_ref().unwrap().unlock.is_none());
4231        let v = serde_json::to_value(&m).unwrap();
4232        assert!(v["client"].get("unlock").is_none(), "wire: {v:?}");
4233    }
4234
4235    #[test]
4236    fn manifest_client_unlock_rejects_a_malformed_scope() {
4237        // The scope is compared byte-for-byte with a configured support
4238        // code's scope, and the gate fails closed — so a typo with spaces
4239        // would hide the job forever with no error anywhere. Catch it at
4240        // create time instead.
4241        let yaml = r#"
4242id: j
4243version: 1.0.0
4244execute:
4245  shell: powershell
4246  script: "echo x"
4247  timeout: 30s
4248client:
4249  name: "A job"
4250  category: troubleshoot
4251  unlock: "help desk"
4252"#;
4253        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4254        let err = m.validate().expect_err("malformed unlock scope must fail");
4255        assert!(err.contains("client.unlock"), "err: {err}");
4256
4257        let blank = yaml.replace(r#"unlock: "help desk""#, r#"unlock: "  ""#);
4258        let m: Manifest = serde_yaml::from_str(&blank).expect("parse");
4259        let err = m.validate().expect_err("blank unlock scope must fail");
4260        assert!(err.contains("client.unlock"), "err: {err}");
4261
4262        // The padded-but-otherwise-valid case (Claude review on #1166): the
4263        // charset check runs on the scope EXACTLY AS STORED, so these must
4264        // fail here rather than pass validation and then silently never
4265        // match a support code (whose scope the backend trims before
4266        // storing) — leaving the job hidden forever with no error anywhere.
4267        for padded in [r#"unlock: " support""#, r#"unlock: "support ""#] {
4268            let m: Manifest = serde_yaml::from_str(&yaml.replace(r#"unlock: "help desk""#, padded))
4269                .expect("parse");
4270            let err = m
4271                .validate()
4272                .expect_err("padded unlock scope must fail: {padded}");
4273            assert!(err.contains("client.unlock"), "{padded} err: {err}");
4274        }
4275    }
4276
4277    #[test]
4278    fn manifest_client_show_when_rejects_empty() {
4279        // A malformed check slug (here: internal spaces — a typo that could
4280        // never match a real check name) or an empty status list would
4281        // silently hide the job forever — validate() must reject both.
4282        let bad_check = r#"
4283id: j
4284version: 1.0.0
4285execute:
4286  shell: powershell
4287  script: "echo x"
4288  timeout: 30s
4289client:
4290  name: "A job"
4291  category: software_update
4292  show_when:
4293    check: "office up to date"
4294    is: fail
4295"#;
4296        let m: Manifest = serde_yaml::from_str(bad_check).expect("parse");
4297        let err = m.validate().expect_err("malformed check slug must fail");
4298        assert!(err.contains("client.show_when.check"), "err: {err}");
4299
4300        let empty_is = r#"
4301id: j
4302version: 1.0.0
4303execute:
4304  shell: powershell
4305  script: "echo x"
4306  timeout: 30s
4307client:
4308  name: "A job"
4309  category: software_update
4310  show_when:
4311    check: office-up-to-date
4312    is: []
4313"#;
4314        let m: Manifest = serde_yaml::from_str(empty_is).expect("parse");
4315        let err = m.validate().expect_err("empty is[] must fail");
4316        assert!(err.contains("client.show_when.is"), "err: {err}");
4317    }
4318
4319    #[test]
4320    fn manifest_client_confirm_accepts_bool_and_struct() {
4321        // `confirm:` deserializes from a bare bool or a struct. A bool
4322        // sets `enabled` (message stays default); a struct carries a custom
4323        // message and defaults `enabled` to true.
4324        let base = r#"
4325id: j
4326version: 1.0.0
4327execute:
4328  shell: powershell
4329  script: "echo x"
4330  timeout: 30s
4331client:
4332  name: "Wi-Fi 省電力を切る"
4333  category: settings
4334"#;
4335        // `confirm: false` ⇒ dialog suppressed.
4336        let off: Manifest =
4337            serde_yaml::from_str(&format!("{base}  confirm: false\n")).expect("parse false");
4338        off.validate().expect("confirm: false validates");
4339        let c = off.client.unwrap().confirm.unwrap();
4340        assert!(!c.enabled);
4341        assert!(c.message.is_none());
4342
4343        // `confirm: true` ⇒ same as omitting (dialog shown, default message).
4344        let on: Manifest =
4345            serde_yaml::from_str(&format!("{base}  confirm: true\n")).expect("parse true");
4346        let c = on.client.unwrap().confirm.unwrap();
4347        assert!(c.enabled);
4348        assert!(c.message.is_none());
4349
4350        // Struct with only a message ⇒ enabled defaults true, custom text.
4351        let msg: Manifest = serde_yaml::from_str(&format!(
4352            "{base}  confirm:\n    message: \"再インストールには数分かかります。よろしいですか?\"\n"
4353        ))
4354        .expect("parse struct");
4355        msg.validate().expect("confirm message validates");
4356        let c = msg.client.unwrap().confirm.unwrap();
4357        assert!(c.enabled);
4358        assert_eq!(
4359            c.message.as_deref(),
4360            Some("再インストールには数分かかります。よろしいですか?")
4361        );
4362
4363        // Absent ⇒ None (historical default handled by the client).
4364        let none: Manifest = serde_yaml::from_str(base).expect("parse none");
4365        assert!(none.client.unwrap().confirm.is_none());
4366
4367        // Explicit `confirm: null` is schema-valid (the field is Option) and
4368        // must map to None, not a parse error (Gemini #960).
4369        let null: Manifest =
4370            serde_yaml::from_str(&format!("{base}  confirm: null\n")).expect("parse null");
4371        assert!(null.client.unwrap().confirm.is_none());
4372    }
4373
4374    #[test]
4375    fn manifest_client_confirm_rejects_blank_message() {
4376        // A present-but-blank custom message would render an empty dialog
4377        // title — validate() must reject it, like the other display fields.
4378        let yaml = r#"
4379id: j
4380version: 1.0.0
4381execute:
4382  shell: powershell
4383  script: "echo x"
4384  timeout: 30s
4385client:
4386  name: "A job"
4387  category: settings
4388  confirm:
4389    message: "   "
4390"#;
4391        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4392        let err = m.validate().expect_err("blank confirm.message must fail");
4393        assert!(err.contains("client.confirm.message"), "err: {err}");
4394    }
4395
4396    #[test]
4397    fn manifest_client_requires_category_at_parse() {
4398        // A `client:` block missing `category` is a hard parse error
4399        // (serde required field) — no manual validate() needed.
4400        let yaml = r#"
4401id: j
4402version: 1.0.0
4403execute:
4404  shell: powershell
4405  script: "echo x"
4406  timeout: 30s
4407client:
4408  name: "A job"
4409"#;
4410        let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
4411        assert!(
4412            r.is_err(),
4413            "missing category must be a parse error, got {r:?}"
4414        );
4415    }
4416
4417    #[test]
4418    fn manifest_client_rejects_unknown_field() {
4419        // #492: the strict create boundary catches a fat-fingered
4420        // `displayname:` (with its path) instead of silently
4421        // dropping it; the tolerant read path accepts it.
4422        let yaml = r#"
4423id: j
4424version: 1.0.0
4425execute:
4426  shell: powershell
4427  script: "echo x"
4428  timeout: 30s
4429client:
4430  name: "A job"
4431  category: catalog
4432  displayname: oops
4433"#;
4434        let r = crate::strict::from_yaml_str::<Manifest>(yaml);
4435        let err = r.expect_err("unknown client field must be rejected at the write boundary");
4436        // serde_ignored renders the Option layer as `?`:
4437        // `client.?.displayname`. Assert on the leaf key.
4438        assert!(err.contains("displayname"), "{err}");
4439        // The READ path tolerates the same payload (gradual-upgrade
4440        // contract: an old agent must accept a newer writer's field).
4441        let m: Manifest = serde_yaml::from_str(yaml).expect("tolerant read");
4442        assert_eq!(m.client.as_ref().map(|c| c.name.as_str()), Some("A job"));
4443    }
4444
4445    #[test]
4446    fn manifest_tags_default_empty() {
4447        // The overwhelming majority of jobs carry no tags; the field
4448        // must default to an empty Vec (not fail to parse) and skip
4449        // serialisation so old readers never see the key.
4450        let yaml = r#"
4451id: echo-test
4452version: 0.0.1
4453execute:
4454  shell: powershell
4455  script: "echo 'kanade'"
4456  timeout: 30s
4457"#;
4458        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4459        assert!(m.tags.is_empty());
4460        m.validate().expect("tag-less job validates");
4461        // skip_serializing_if = empty ⇒ the key is absent from JSON.
4462        let json = serde_json::to_string(&m).expect("serialize");
4463        assert!(
4464            !json.contains("tags"),
4465            "empty tags must not serialise: {json}"
4466        );
4467    }
4468
4469    #[test]
4470    fn manifest_parses_and_validates_tags() {
4471        let yaml = r#"
4472id: check-bitlocker
4473version: 0.1.0
4474execute:
4475  shell: powershell
4476  script: "echo x"
4477  timeout: 30s
4478tags: [security, windows, health-check]
4479"#;
4480        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4481        assert_eq!(m.tags, vec!["security", "windows", "health-check"]);
4482        m.validate().expect("tagged job validates");
4483        // Round-trips through JSON (the wire format the SPA reads).
4484        let json = serde_json::to_string(&m).expect("serialize");
4485        assert!(json.contains("\"tags\""), "non-empty tags must serialise");
4486    }
4487
4488    #[test]
4489    fn manifest_rejects_blank_tag() {
4490        // A whitespace-only tag renders an empty filter chip — reject
4491        // it at the write boundary like the other blank display fields.
4492        let yaml = r#"
4493id: j
4494version: 0.1.0
4495execute:
4496  shell: powershell
4497  script: "echo x"
4498  timeout: 30s
4499tags: [ok, "   "]
4500"#;
4501        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
4502        let err = m.validate().expect_err("blank tag must fail");
4503        assert!(err.contains("tags must not contain empty"), "err: {err}");
4504    }
4505
4506    #[test]
4507    fn validate_rejects_unknown_tier_and_accepts_known() {
4508        let base =
4509            "id: t\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: x\n  timeout: 30s\n";
4510        // A typo / future tier decodes to Tier::Unknown (#[serde(other)]) and
4511        // must FAIL CLOSED — never fall back to unrestricted endpoint dispatch.
4512        let bogus: Manifest =
4513            serde_yaml::from_str(&format!("{base}tier: controler\n")).expect("parse");
4514        let err = bogus.validate().expect_err("unknown tier must be rejected");
4515        assert!(err.contains("tier"), "err: {err}");
4516        // The two known tiers pass.
4517        serde_yaml::from_str::<Manifest>(&format!("{base}tier: controller\n"))
4518            .unwrap()
4519            .validate()
4520            .expect("controller tier is valid");
4521        serde_yaml::from_str::<Manifest>(&format!("{base}tier: endpoint\n"))
4522            .unwrap()
4523            .validate()
4524            .expect("endpoint tier is valid");
4525    }
4526
4527    #[test]
4528    fn feed_payload_extracts_fenced_block() {
4529        let stdout = "fetched 1500 KEV entries\n\
4530            #KANADE-FEED-BEGIN\n\
4531            {\"vulnerabilities\": []}\n\
4532            #KANADE-FEED-END\n";
4533        assert_eq!(feed_payload(stdout), "{\"vulnerabilities\": []}");
4534    }
4535
4536    #[test]
4537    fn validate_feed_rules() {
4538        let base =
4539            "id: f\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: x\n  timeout: 30s\n";
4540        // A well-formed feed (controller implied; no explicit tier) passes.
4541        serde_yaml::from_str::<Manifest>(&format!(
4542            "{base}feed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4543        ))
4544        .unwrap()
4545        .validate()
4546        .expect("a well-formed feed is valid");
4547
4548        // Empty primary_key is rejected (no item_id → every row dropped).
4549        let err = serde_yaml::from_str::<Manifest>(&format!(
4550            "{base}feed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: []\n"
4551        ))
4552        .unwrap()
4553        .validate()
4554        .expect_err("empty primary_key must be rejected");
4555        assert!(err.contains("primary_key"), "err: {err}");
4556
4557        // A duplicate feed id clobbers a partition — rejected.
4558        let err = serde_yaml::from_str::<Manifest>(&format!(
4559            "{base}feed:\n  - id: dup\n    field: a\n    primary_key: [k]\n  - id: dup\n    field: b\n    primary_key: [k]\n"
4560        ))
4561        .unwrap()
4562        .validate()
4563        .expect_err("duplicate feed id must be rejected");
4564        assert!(err.contains("more than once"), "err: {err}");
4565
4566        // `feed:` + explicit `tier: endpoint` is contradictory — rejected.
4567        let err = serde_yaml::from_str::<Manifest>(&format!(
4568            "{base}tier: endpoint\nfeed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4569        ))
4570        .unwrap()
4571        .validate()
4572        .expect_err("feed + tier: endpoint must be rejected");
4573        assert!(err.contains("controller tier"), "err: {err}");
4574
4575        // `feed:` + `emit:` is incompatible — emit consumes stdout whole, so
4576        // the feed's fence never reaches the projector.
4577        let err = serde_yaml::from_str::<Manifest>(&format!(
4578            "{base}emit:\n  type: events\nfeed:\n  - id: cisa-kev\n    field: vulnerabilities\n    primary_key: [cveID]\n"
4579        ))
4580        .unwrap()
4581        .validate()
4582        .expect_err("feed + emit must be rejected");
4583        assert!(err.contains("emit"), "err: {err}");
4584    }
4585
4586    // #720 — wrap an `aggregate:` YAML block (already indented as a
4587    // top-level key body) into an otherwise-minimal valid manifest.
4588    fn manifest_with_aggregate(aggregate_block: &str) -> Manifest {
4589        let yaml = format!(
4590            "id: t\nversion: 0.0.1\nexecute:\n  shell: powershell\n  script: echo hi\n  timeout: 30s\n{aggregate_block}"
4591        );
4592        serde_yaml::from_str(&yaml).expect("parse aggregate manifest")
4593    }
4594
4595    #[test]
4596    fn aggregate_accepts_full_valid_spec() {
4597        // count+group_by+exclude+sample_minutes, ratio+bool_path,
4598        // timeline+time_bucket, fleet ranking via group_by: pc_id, and a
4599        // bare total stat — alongside emit (composes with every hint).
4600        let m = manifest_with_aggregate(
4601            "emit:\n  type: events\naggregate:\n\
4602             - { placement: { analytics: Utilization }, title: Top apps, kind: app_sample, agg: count, group_by: foreground.app, sample_minutes: 2, exclude: [LockApp], render: bar }\n\
4603             - { placement: { analytics: Utilization }, title: Active ratio, kind: presence, agg: ratio, bool_path: active, sample_minutes: 5, render: gauge }\n\
4604             - { placement: { analytics: Utilization }, title: By hour, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: timeline }\n\
4605             - { placement: { analytics: Reliability }, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
4606             - { placement: { analytics: Reliability }, title: Total crashes, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
4607        );
4608        m.validate().expect("valid aggregate spec");
4609    }
4610
4611    #[test]
4612    fn aggregate_rejects_empty_list() {
4613        let m = manifest_with_aggregate("aggregate: []\n");
4614        let err = m.validate().expect_err("empty list must fail");
4615        assert!(err.contains("at least one widget"), "err: {err}");
4616    }
4617
4618    #[test]
4619    fn aggregate_rejects_ratio_without_bool_path() {
4620        let m = manifest_with_aggregate(
4621            "aggregate:\n- { placement: { analytics: D }, title: T, kind: presence, agg: ratio, render: gauge }\n",
4622        );
4623        let err = m.validate().expect_err("ratio needs bool_path");
4624        assert!(err.contains("agg=ratio requires `bool_path`"), "err: {err}");
4625    }
4626
4627    #[test]
4628    fn aggregate_rejects_sum_without_value_path() {
4629        let m = manifest_with_aggregate(
4630            "aggregate:\n- { placement: { analytics: D }, title: T, kind: io, agg: sum, render: bar }\n",
4631        );
4632        let err = m.validate().expect_err("sum needs value_path");
4633        assert!(err.contains("agg=sum requires `value_path`"), "err: {err}");
4634    }
4635
4636    #[test]
4637    fn aggregate_rejects_pc_id_group_without_fleet() {
4638        let m = manifest_with_aggregate(
4639            "aggregate:\n- { placement: { analytics: D }, title: T, kind: presence, agg: count, group_by: pc_id, render: bar }\n",
4640        );
4641        let err = m.validate().expect_err("pc_id grouping needs fleet");
4642        assert!(
4643            err.contains("pc_id is only valid with scope: fleet"),
4644            "err: {err}"
4645        );
4646    }
4647
4648    #[test]
4649    fn aggregate_rejects_transform_with_pc_id_group() {
4650        let m = manifest_with_aggregate(
4651            "aggregate:\n- { placement: { analytics: D }, title: T, scope: fleet, kind: web_visit, agg: count, group_by: pc_id, transform: host, render: bar }\n",
4652        );
4653        let err = m
4654            .validate()
4655            .expect_err("transform on pc_id grouping must fail");
4656        assert!(
4657            err.contains("transform is not valid with group_by: pc_id"),
4658            "err: {err}"
4659        );
4660    }
4661
4662    #[test]
4663    fn aggregate_rejects_timeline_without_bucket() {
4664        let m = manifest_with_aggregate(
4665            "aggregate:\n- { placement: { analytics: D }, title: T, kind: presence, agg: ratio, bool_path: active, render: timeline }\n",
4666        );
4667        let err = m.validate().expect_err("timeline needs a bucket");
4668        assert!(
4669            err.contains("render=timeline requires `time_bucket`"),
4670            "err: {err}"
4671        );
4672    }
4673
4674    #[test]
4675    fn aggregate_rejects_bucket_on_non_timeline() {
4676        let m = manifest_with_aggregate(
4677            "aggregate:\n- { placement: { analytics: D }, title: T, kind: presence, agg: ratio, bool_path: active, time_bucket: hour, render: gauge }\n",
4678        );
4679        let err = m.validate().expect_err("bucket only on timeline");
4680        assert!(
4681            err.contains("time_bucket is only valid with render: timeline"),
4682            "err: {err}"
4683        );
4684    }
4685
4686    #[test]
4687    fn aggregate_rejects_unsafe_json_path() {
4688        // A path with characters outside [A-Za-z0-9_.] could break out of
4689        // the `'$.' || ?` bind — reject at create time.
4690        let m = manifest_with_aggregate(
4691            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, group_by: \"foo'; DROP\", render: bar }\n",
4692        );
4693        let err = m.validate().expect_err("unsafe path must fail");
4694        assert!(err.contains("dotted JSON path"), "err: {err}");
4695    }
4696
4697    #[test]
4698    fn aggregate_rejects_blank_title() {
4699        let m = manifest_with_aggregate(
4700            "aggregate:\n- { placement: { analytics: D }, title: \"  \", kind: k, agg: count, render: stat }\n",
4701        );
4702        let err = m.validate().expect_err("blank title must fail");
4703        assert!(err.contains("title must not be empty"), "err: {err}");
4704    }
4705
4706    #[test]
4707    fn aggregate_rejects_blank_kind() {
4708        let m = manifest_with_aggregate(
4709            "aggregate:\n- { placement: { analytics: D }, title: T, kind: \" \", agg: count, render: stat }\n",
4710        );
4711        let err = m.validate().expect_err("blank kind must fail");
4712        assert!(err.contains("kind must not be empty"), "err: {err}");
4713    }
4714
4715    #[test]
4716    fn aggregate_rejects_blank_source_when_set() {
4717        let m = manifest_with_aggregate(
4718            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, source: \"\", agg: count, render: stat }\n",
4719        );
4720        let err = m.validate().expect_err("blank source must fail");
4721        assert!(
4722            err.contains("source must not be empty when set"),
4723            "err: {err}"
4724        );
4725    }
4726
4727    #[test]
4728    fn aggregate_accepts_description_and_rejects_blank() {
4729        let ok = manifest_with_aggregate(
4730            "aggregate:\n- { placement: { analytics: D }, title: T, description: \"samples x 2 min\", kind: k, agg: count, render: stat }\n",
4731        );
4732        ok.validate()
4733            .expect("description is a valid optional field");
4734        assert_eq!(
4735            ok.aggregate.as_ref().unwrap()[0].description.as_deref(),
4736            Some("samples x 2 min")
4737        );
4738        let bad = manifest_with_aggregate(
4739            "aggregate:\n- { placement: { analytics: D }, title: T, description: \"  \", kind: k, agg: count, render: stat }\n",
4740        );
4741        let err = bad.validate().expect_err("blank description must fail");
4742        assert!(
4743            err.contains("description must not be empty when set"),
4744            "err: {err}"
4745        );
4746    }
4747
4748    #[test]
4749    fn aggregate_rejects_count_with_value_path() {
4750        let m = manifest_with_aggregate(
4751            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, value_path: bytes, render: stat }\n",
4752        );
4753        let err = m.validate().expect_err("count must not use value_path");
4754        assert!(
4755            err.contains("agg=count does not use `value_path`"),
4756            "err: {err}"
4757        );
4758    }
4759
4760    #[test]
4761    fn aggregate_rejects_ratio_with_value_path() {
4762        let m = manifest_with_aggregate(
4763            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: ratio, bool_path: active, value_path: bytes, render: gauge }\n",
4764        );
4765        let err = m.validate().expect_err("ratio must not use value_path");
4766        assert!(
4767            err.contains("agg=ratio does not use `value_path`"),
4768            "err: {err}"
4769        );
4770    }
4771
4772    #[test]
4773    fn aggregate_rejects_gauge_without_ratio() {
4774        let m = manifest_with_aggregate(
4775            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, group_by: app, render: gauge }\n",
4776        );
4777        let err = m.validate().expect_err("gauge needs ratio");
4778        assert!(
4779            err.contains("render=gauge is only valid with agg: ratio"),
4780            "err: {err}"
4781        );
4782    }
4783
4784    #[test]
4785    fn aggregate_rejects_limit_without_group_by() {
4786        let m = manifest_with_aggregate(
4787            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, limit: 5, render: stat }\n",
4788        );
4789        let err = m.validate().expect_err("limit needs group_by");
4790        assert!(err.contains("limit requires `group_by`"), "err: {err}");
4791    }
4792
4793    #[test]
4794    fn aggregate_rejects_exclude_without_group_by() {
4795        let m = manifest_with_aggregate(
4796            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, exclude: [x], render: stat }\n",
4797        );
4798        let err = m.validate().expect_err("exclude needs group_by");
4799        assert!(err.contains("exclude requires `group_by`"), "err: {err}");
4800    }
4801
4802    #[test]
4803    fn aggregate_rejects_zero_limit_and_zero_sample_minutes() {
4804        let m = manifest_with_aggregate(
4805            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, group_by: app, limit: 0, render: bar }\n",
4806        );
4807        assert!(m.validate().unwrap_err().contains("limit must be > 0"));
4808        let m = manifest_with_aggregate(
4809            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, group_by: app, sample_minutes: 0, render: bar }\n",
4810        );
4811        assert!(
4812            m.validate()
4813                .unwrap_err()
4814                .contains("sample_minutes must be > 0")
4815        );
4816    }
4817
4818    #[test]
4819    fn aggregate_rejects_empty_exclude_entry() {
4820        let m = manifest_with_aggregate(
4821            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, group_by: app, exclude: [\"  \"], render: bar }\n",
4822        );
4823        let err = m.validate().expect_err("blank exclude entry must fail");
4824        assert!(
4825            err.contains("exclude must not contain empty entries"),
4826            "err: {err}"
4827        );
4828    }
4829
4830    #[test]
4831    fn aggregate_rejects_malformed_dotted_paths() {
4832        for bad in [".foo", "foo.", "foo..bar", "."] {
4833            let m = manifest_with_aggregate(&format!(
4834                "aggregate:\n- {{ placement: {{ analytics: D }}, title: T, kind: k, agg: count, group_by: \"{bad}\", render: bar }}\n"
4835            ));
4836            let err = m.validate().expect_err("malformed path must fail");
4837            assert!(err.contains("dotted JSON path"), "path {bad}: {err}");
4838        }
4839    }
4840
4841    #[test]
4842    fn aggregate_rejects_unknown_enum_value() {
4843        // An unrecognised render string deserialises to the #492 Unknown
4844        // catch-all (so old readers don't choke); validate() rejects it as
4845        // a typo at create time.
4846        let m = manifest_with_aggregate(
4847            "aggregate:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, render: heatmap }\n",
4848        );
4849        let err = m.validate().expect_err("unknown render must fail");
4850        assert!(err.contains("render is not a known value"), "err: {err}");
4851    }
4852
4853    #[test]
4854    fn aggregate_accepts_order_field() {
4855        let m = manifest_with_aggregate(
4856            "aggregate:\n- { placement: { analytics: D }, title: T, order: -5, kind: k, agg: count, render: stat }\n",
4857        );
4858        m.validate().expect("order is a valid optional field");
4859        let w = &m.aggregate.as_ref().unwrap()[0];
4860        assert_eq!(w.order, Some(-5));
4861    }
4862
4863    // #1257 moved aggregate widgets onto the shared `placement:` block, so
4864    // `validate_placement` is now reachable from a second call site
4865    // (`validate_aggregate_widgets`). The SqlWidget side already covers the
4866    // rule; these pin it down where it is new, since a regression there
4867    // would be invisible to those tests.
4868
4869    #[test]
4870    fn aggregate_rejects_widget_that_surfaces_nowhere() {
4871        // No `analytics` tab and not pinned ⇒ the widget renders nowhere.
4872        // Before #1257 this was unrepresentable (`dashboard` was a required
4873        // String), so it's a genuinely new way to write a broken widget.
4874        let err = manifest_with_aggregate(
4875            "aggregate:\n- { placement: {}, title: T, kind: k, agg: count, render: stat }\n",
4876        )
4877        .validate()
4878        .expect_err("a widget with no surface must be rejected");
4879        assert!(err.contains("placement must set"), "err: {err}");
4880
4881        // `pin: false` is a block that pins nowhere — presence of the block
4882        // must not be mistaken for an actual surface.
4883        let err = manifest_with_aggregate(
4884            "aggregate:\n- { placement: { dashboard: { pin: false } }, title: T, kind: k, agg: count, render: stat }\n",
4885        )
4886        .validate()
4887        .expect_err("pin: false surfaces nowhere either");
4888        assert!(err.contains("placement must set"), "err: {err}");
4889    }
4890
4891    #[test]
4892    fn aggregate_accepts_dashboard_only_widget() {
4893        // The capability the refactor unlocks: an aggregate widget that is
4894        // pinned to the Dashboard without also claiming an Analytics tab.
4895        // `tab()` falls back to a label so the grouped widget list still has
4896        // a key to group under.
4897        let m = manifest_with_aggregate(
4898            "aggregate:\n- { placement: { dashboard: { pin: true } }, title: T, scope: fleet, kind: k, agg: count, render: stat }\n",
4899        );
4900        m.validate().expect("dashboard-only placement is valid");
4901        let p = &m.aggregate.as_ref().unwrap()[0].placement;
4902        assert!(p.is_pinned());
4903        assert!(p.analytics.is_none());
4904        assert_eq!(p.tab(), "Dashboard");
4905    }
4906
4907    #[test]
4908    fn analytics_placement_reads_both_shapes_and_serializes_terse() {
4909        // The scalar-or-block contract, and the one-way collapse back to
4910        // the terse form: a block that sets no width is stored as the bare
4911        // string, so resource JSON doesn't grow a wrapper for the ~all
4912        // widgets that never ask for a width.
4913        let bare = manifest_with_aggregate(
4914            "aggregate:\n- { placement: { analytics: Uptime }, title: T, kind: k, agg: count, render: stat }\n",
4915        );
4916        let block = manifest_with_aggregate(
4917            "aggregate:\n- { placement: { analytics: { tab: Uptime } }, title: T, kind: k, agg: count, render: stat }\n",
4918        );
4919        for m in [&bare, &block] {
4920            assert_eq!(m.aggregate.as_ref().unwrap()[0].placement.tab(), "Uptime");
4921        }
4922        let json = serde_json::to_string(&bare.aggregate.as_ref().unwrap()[0].placement)
4923            .expect("serialize placement");
4924        assert!(json.contains(r#""analytics":"Uptime""#), "json: {json}");
4925
4926        // With a width it has to keep the block form, or the width is lost.
4927        let wide = manifest_with_aggregate(
4928            "aggregate:\n- { placement: { analytics: { tab: Uptime, width: half } }, title: T, kind: k, agg: count, render: stat }\n",
4929        );
4930        let p = &wide.aggregate.as_ref().unwrap()[0].placement;
4931        assert_eq!(p.width_for(false), Some(WidgetWidth::Half));
4932        // …and the Dashboard surface is untouched by an Analytics width.
4933        assert_eq!(p.width_for(true), None);
4934        let json = serde_json::to_string(p).expect("serialize placement");
4935        assert!(json.contains(r#""tab":"Uptime""#), "json: {json}");
4936        assert!(json.contains(r#""width":"half""#), "json: {json}");
4937    }
4938
4939    #[test]
4940    fn aggregate_accepts_minimal_op_timeline() {
4941        // op_timeline needs no kind/agg — it reconstructs a fixed multi-kind
4942        // swimlane. A bare per-PC spec is valid, and `kind`/`agg` stay None.
4943        let m = manifest_with_aggregate(
4944            "aggregate:\n- { placement: { analytics: Uptime }, title: Operational state, scope: pc, render: op_timeline }\n",
4945        );
4946        m.validate().expect("minimal op_timeline is valid");
4947        let w = &m.aggregate.as_ref().unwrap()[0];
4948        assert_eq!(w.render, AggregateRender::OpTimeline);
4949        assert!(w.kind.is_none());
4950        assert!(w.agg.is_none());
4951    }
4952
4953    #[test]
4954    fn aggregate_rejects_op_timeline_with_fleet_scope() {
4955        let m = manifest_with_aggregate(
4956            "aggregate:\n- { placement: { analytics: Uptime }, title: T, scope: fleet, render: op_timeline }\n",
4957        );
4958        let err = m.validate().expect_err("op_timeline must be per-PC");
4959        assert!(
4960            err.contains("render=op_timeline requires scope: pc"),
4961            "err: {err}"
4962        );
4963    }
4964
4965    #[test]
4966    fn aggregate_rejects_op_timeline_with_aggregation_fields() {
4967        // Each aggregation knob the operator might paste in is rejected
4968        // (rather than silently ignored), pointing at the field to delete.
4969        for (block, field) in [
4970            ("kind: boot", "kind"),
4971            ("agg: count", "agg"),
4972            ("source: winlog:Security", "source"),
4973            ("group_by: pc_id", "group_by"),
4974            ("bool_path: active", "bool_path"),
4975            ("time_bucket: hour", "time_bucket"),
4976            ("limit: 5", "limit"),
4977        ] {
4978            let m = manifest_with_aggregate(&format!(
4979                "aggregate:\n- {{ placement: {{ analytics: Uptime }}, title: T, scope: pc, {block}, render: op_timeline }}\n"
4980            ));
4981            let err = m
4982                .validate()
4983                .expect_err(&format!("op_timeline must reject {field}"));
4984            assert!(
4985                err.contains(&format!("render=op_timeline does not use `{field}`")),
4986                "field {field}: {err}"
4987            );
4988        }
4989    }
4990
4991    // ── #743 View resource ───────────────────────────────────────────
4992    fn view_from(yaml_body: &str) -> View {
4993        serde_yaml::from_str(&format!("id: v1\n{yaml_body}")).expect("parse view")
4994    }
4995
4996    #[test]
4997    fn view_accepts_valid_widgets() {
4998        let v = view_from(
4999            "widgets:\n\
5000             - { placement: { analytics: Reliability }, title: Crashes by PC, scope: fleet, kind: unexpected_shutdown, agg: count, group_by: pc_id, render: bar }\n\
5001             - { placement: { analytics: Reliability }, title: Total, scope: fleet, kind: unexpected_shutdown, agg: count, render: stat }\n",
5002        );
5003        v.validate().expect("valid view");
5004    }
5005
5006    #[test]
5007    fn view_rejects_empty_widgets() {
5008        let v = view_from("widgets: []\n");
5009        let err = v.validate().expect_err("empty widgets must fail");
5010        assert!(err.contains("at least one widget"), "err: {err}");
5011    }
5012
5013    #[test]
5014    fn view_rejects_blank_id() {
5015        let v: View = serde_yaml::from_str(
5016            "id: \"  \"\nwidgets:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, render: stat }\n",
5017        )
5018        .expect("parse");
5019        let err = v.validate().expect_err("blank id must fail");
5020        assert!(err.contains("view.id must"), "err: {err}");
5021    }
5022
5023    #[test]
5024    fn view_rejects_unsafe_id() {
5025        // A `/` or `..` in the id would break the KV key and the
5026        // `/api/views/{id}` URL segment — reject at create time.
5027        for bad in ["../etc", "a/b", "has space", "x;y"] {
5028            let v: View = serde_yaml::from_str(&format!(
5029                "id: \"{bad}\"\nwidgets:\n- {{ placement: {{ analytics: D }}, title: T, kind: k, agg: count, render: stat }}\n",
5030            ))
5031            .expect("parse");
5032            let err = v.validate().expect_err("unsafe id must fail");
5033            assert!(err.contains("[A-Za-z0-9._-]"), "id {bad}: {err}");
5034        }
5035        assert!(is_valid_resource_id("dashboards-fleet.v1_2"));
5036    }
5037
5038    #[test]
5039    fn view_rejects_untrimmed_id() {
5040        // A padded id validated-as-trimmed but stored-raw would be a KV key
5041        // (and `/api/views/{id}` segment) nothing matches — reject it outright
5042        // (the id is used verbatim).
5043        let v: View = serde_yaml::from_str(
5044            "id: \" my-view \"\nwidgets:\n- { placement: { analytics: D }, title: T, kind: k, agg: count, render: stat }\n",
5045        )
5046        .expect("parse");
5047        let err = v.validate().expect_err("padded id must fail");
5048        assert!(err.contains("view.id must"), "err: {err}");
5049    }
5050
5051    #[test]
5052    fn view_reuses_shared_widget_validation() {
5053        // The same per-widget rule the job hint enforces (ratio needs
5054        // bool_path), reported under the `widgets[..]` field.
5055        let v = view_from(
5056            "widgets:\n- { placement: { analytics: D }, title: T, kind: presence, agg: ratio, render: gauge }\n",
5057        );
5058        let err = v.validate().expect_err("ratio without bool_path must fail");
5059        assert!(
5060            err.contains("widgets[0].agg=ratio requires `bool_path`"),
5061            "err: {err}"
5062        );
5063    }
5064
5065    // ── #vuln-roadmap PR3 SQL-backed views ───────────────────────────
5066    #[test]
5067    fn view_accepts_pure_sql_widgets() {
5068        // A view with only sql_widgets (no obs_events aggregate widgets) is
5069        // valid — the vulnerability-dashboard shape.
5070        let v = view_from(
5071            "sql_widgets:
5072  - title: KEV-affected hosts
5073    query: \"SELECT pc_id, 1 AS cves FROM inventory_sw_apps\"
5074    refresh: 6h
5075    render: { kind: table, columns: [pc_id, cves], labels: { cves: CVE count } }
5076    placement: { analytics: Security, dashboard: { pin: true } }
5077",
5078        );
5079        v.validate().expect("valid sql view");
5080        // refresh parses; pin/tab helpers read the placement.
5081        let w = &v.sql_widgets[0];
5082        assert_eq!(
5083            w.refresh_interval(),
5084            std::time::Duration::from_secs(6 * 3600)
5085        );
5086        assert!(w.placement.is_pinned());
5087        assert_eq!(w.placement.tab(), "Security");
5088    }
5089
5090    #[test]
5091    fn sql_widget_defaults_and_mix() {
5092        // No refresh ⇒ default; a view can mix aggregate + sql widgets.
5093        let v = view_from(
5094            "widgets:
5095  - { placement: { analytics: D }, title: T, kind: k, agg: count, render: stat }
5096sql_widgets:
5097  - title: N affected
5098    query: \"SELECT count(*) AS n FROM feeds\"
5099    render: { kind: stat, value: n }
5100    placement: { dashboard: { pin: true } }
5101",
5102        );
5103        v.validate().expect("mixed view is valid");
5104        assert_eq!(v.sql_widgets[0].refresh_interval(), DEFAULT_VIEW_REFRESH);
5105        // dashboard-only placement (no analytics tab) falls back to a label.
5106        assert_eq!(v.sql_widgets[0].placement.tab(), "Dashboard");
5107    }
5108
5109    #[test]
5110    fn sql_widget_validation_rules() {
5111        // helper: build a view with one sql_widget from an inline render+placement
5112        let mk = |render: &str, placement: &str| -> Result<(), String> {
5113            view_from(&format!(
5114                "sql_widgets:
5115  - title: W
5116    query: \"SELECT 1 AS a\"
5117    render: {render}
5118    placement: {placement}
5119"
5120            ))
5121            .validate()
5122        };
5123        // bar needs label + value
5124        let err = mk("{ kind: bar, value: a }", "{ analytics: T }").unwrap_err();
5125        assert!(
5126            err.contains("render.label is required for kind=bar"),
5127            "err: {err}"
5128        );
5129        // pie needs value
5130        let err = mk("{ kind: pie, label: a }", "{ analytics: T }").unwrap_err();
5131        assert!(
5132            err.contains("render.value is required for kind=pie"),
5133            "err: {err}"
5134        );
5135        // stat needs value
5136        let err = mk("{ kind: stat }", "{ analytics: T }").unwrap_err();
5137        assert!(
5138            err.contains("render.value is required for kind=stat"),
5139            "err: {err}"
5140        );
5141        // gauge needs value XOR num+den
5142        let err = mk("{ kind: gauge, num: a }", "{ analytics: T }").unwrap_err();
5143        assert!(err.contains("needs either `value`"), "err: {err}");
5144        mk("{ kind: gauge, value: a }", "{ analytics: T }").expect("gauge value ok");
5145        mk("{ kind: gauge, num: a, den: a }", "{ analytics: T }").expect("gauge num/den ok");
5146        // unknown kind rejected
5147        let err = mk("{ kind: sunburst }", "{ analytics: T }").unwrap_err();
5148        assert!(
5149            err.contains("render.kind is not a known value"),
5150            "err: {err}"
5151        );
5152        // placement must surface somewhere
5153        let err = mk("{ kind: table }", "{}").unwrap_err();
5154        assert!(err.contains("placement must set"), "err: {err}");
5155        // a `dashboard: { pin: false }` block still surfaces nowhere.
5156        let err = mk("{ kind: table }", "{ dashboard: { pin: false } }").unwrap_err();
5157        assert!(err.contains("placement must set"), "err: {err}");
5158        mk("{ kind: table }", "{ dashboard: { pin: true } }").expect("pinned dashboard ok");
5159        // limit: 0 on a bar/pie is an invisible widget — rejected.
5160        let err = mk(
5161            "{ kind: bar, label: a, value: a, limit: 0 }",
5162            "{ analytics: T }",
5163        )
5164        .unwrap_err();
5165        assert!(err.contains("limit must be >= 1"), "err: {err}");
5166        // bad refresh duration rejected
5167        let err = view_from(
5168            "sql_widgets:
5169  - { title: W, query: \"SELECT 1\", refresh: \"6 sidereal days\", render: { kind: table }, placement: { analytics: T } }
5170",
5171        )
5172        .validate()
5173        .unwrap_err();
5174        assert!(
5175            err.contains("refresh") && err.contains("not a valid duration"),
5176            "err: {err}"
5177        );
5178        // table is fine with no channels
5179        mk("{ kind: table }", "{ analytics: T }").expect("bare table ok");
5180    }
5181
5182    #[test]
5183    fn rewrite_pc_id_param_is_literal_and_boundary_aware() {
5184        // A real param outside any literal is rewritten + counted.
5185        let (sql, n) = rewrite_pc_id_param("SELECT * FROM t WHERE pc_id = :pc_id");
5186        assert_eq!(n, 1);
5187        assert!(sql.ends_with("pc_id = ?"), "sql: {sql}");
5188        // Appearing twice → two `?`, count 2 (one bind each — the caller binds
5189        // pc_id per occurrence since sqlx-sqlite has no named params).
5190        let (sql, n) = rewrite_pc_id_param("WHERE a = :pc_id AND (:pc_id IS NOT NULL)");
5191        assert_eq!(n, 2);
5192        assert_eq!(sql, "WHERE a = ? AND (? IS NOT NULL)");
5193        // Inside a string literal → copied verbatim, NOT counted (would else be
5194        // a bind-count mismatch → SQLITE_RANGE, and misclassify scope).
5195        let (sql, n) = rewrite_pc_id_param("SELECT 'see :pc_id docs' AS hint");
5196        assert_eq!(n, 0);
5197        assert_eq!(sql, "SELECT 'see :pc_id docs' AS hint");
5198        // Inside a comment → left alone.
5199        let (_, n) = rewrite_pc_id_param("SELECT 1 -- filter by :pc_id\n");
5200        assert_eq!(n, 0);
5201        // A longer identifier prefix (`:pc_idx`) is not our token.
5202        let (sql, n) = rewrite_pc_id_param("WHERE x = :pc_idx");
5203        assert_eq!(n, 0);
5204        assert_eq!(sql, "WHERE x = :pc_idx");
5205    }
5206
5207    #[test]
5208    fn validate_rejects_pinned_per_pc_widget() {
5209        // A per-PC widget (binds :pc_id) that also pins to the Dashboard is a
5210        // create-time contradiction (Dashboard is fleet-scope) — rejected.
5211        let err = view_from(
5212            "sql_widgets:
5213  - title: W
5214    query: \"SELECT count(*) AS n FROM inventory_sw_apps WHERE pc_id = :pc_id\"
5215    render: { kind: stat, value: n }
5216    placement: { analytics: Security, dashboard: { pin: true } }
5217",
5218        )
5219        .validate()
5220        .unwrap_err();
5221        assert!(err.contains("per-PC widget"), "err: {err}");
5222        // The same widget WITHOUT the pin is fine (per-PC, analytics only).
5223        view_from(
5224            "sql_widgets:
5225  - title: W
5226    query: \"SELECT count(*) AS n FROM inventory_sw_apps WHERE pc_id = :pc_id\"
5227    render: { kind: stat, value: n }
5228    placement: { analytics: Security }
5229",
5230        )
5231        .validate()
5232        .expect("per-PC analytics-only widget is valid");
5233    }
5234
5235    fn execute_with(
5236        script: Option<&str>,
5237        script_file: Option<&str>,
5238        script_object: Option<&str>,
5239    ) -> Execute {
5240        Execute {
5241            bypass_local_limit: false,
5242            shell: ExecuteShell::Powershell,
5243            script: script.map(str::to_owned),
5244            script_file: script_file.map(str::to_owned),
5245            script_object: script_object.map(str::to_owned),
5246            timeout: "30s".into(),
5247            run_as: RunAs::default(),
5248            cwd: None,
5249        }
5250    }
5251
5252    #[test]
5253    fn validate_accepts_inline_script() {
5254        let e = execute_with(Some("echo hi"), None, None);
5255        assert!(e.validate_script_source().is_ok());
5256    }
5257
5258    #[test]
5259    fn validate_accepts_script_file_alone() {
5260        let e = execute_with(None, Some("scripts/cleanup.ps1"), None);
5261        assert!(e.validate_script_source().is_ok());
5262    }
5263
5264    #[test]
5265    fn validate_accepts_script_object_alone() {
5266        let e = execute_with(None, None, Some("cleanup/1.0.0"));
5267        assert!(e.validate_script_source().is_ok());
5268    }
5269
5270    #[test]
5271    fn validate_treats_empty_inline_script_as_unset() {
5272        // `script: ""` + `script_object` set is the natural shape
5273        // when an operator comments out the YAML block-scalar body
5274        // but leaves the key. Should pass.
5275        let e = execute_with(Some(""), None, Some("cleanup/1.0.0"));
5276        assert!(e.validate_script_source().is_ok());
5277    }
5278
5279    #[test]
5280    fn validate_rejects_zero_sources() {
5281        let e = execute_with(None, None, None);
5282        let err = e.validate_script_source().unwrap_err();
5283        assert!(err.contains("must be set"), "got: {err}");
5284    }
5285
5286    #[test]
5287    fn validate_rejects_empty_inline_only() {
5288        let e = execute_with(Some(""), None, None);
5289        let err = e.validate_script_source().unwrap_err();
5290        assert!(err.contains("must be set"), "got: {err}");
5291    }
5292
5293    #[test]
5294    fn validate_rejects_inline_plus_file() {
5295        let e = execute_with(Some("echo hi"), Some("scripts/cleanup.ps1"), None);
5296        let err = e.validate_script_source().unwrap_err();
5297        assert!(err.contains("only one of"), "got: {err}");
5298    }
5299
5300    #[test]
5301    fn validate_rejects_inline_plus_object() {
5302        let e = execute_with(Some("echo hi"), None, Some("cleanup/1.0.0"));
5303        let err = e.validate_script_source().unwrap_err();
5304        assert!(err.contains("only one of"), "got: {err}");
5305    }
5306
5307    #[test]
5308    fn validate_rejects_file_plus_object() {
5309        let e = execute_with(None, Some("scripts/cleanup.ps1"), Some("cleanup/1.0.0"));
5310        let err = e.validate_script_source().unwrap_err();
5311        assert!(err.contains("only one of"), "got: {err}");
5312    }
5313
5314    #[test]
5315    fn validate_rejects_all_three() {
5316        let e = execute_with(
5317            Some("echo hi"),
5318            Some("scripts/cleanup.ps1"),
5319            Some("cleanup/1.0.0"),
5320        );
5321        let err = e.validate_script_source().unwrap_err();
5322        assert!(err.contains("only one of"), "got: {err}");
5323    }
5324
5325    #[test]
5326    fn validate_rejects_blank_script_file() {
5327        // #918: a blank `script_file` used to count as "set" and pass
5328        // the exactly-one check, then fail at use time (the CLI reads
5329        // a file named "").
5330        for blank in ["", "   "] {
5331            let e = execute_with(None, Some(blank), None);
5332            let err = e.validate_script_source().unwrap_err();
5333            assert!(err.contains("script_file must not be blank"), "got: {err}");
5334        }
5335    }
5336
5337    #[test]
5338    fn validate_rejects_blank_script_object() {
5339        // #918: same for a blank `script_object` (would 404 every exec).
5340        for blank in ["", "   "] {
5341            let e = execute_with(None, None, Some(blank));
5342            let err = e.validate_script_source().unwrap_err();
5343            assert!(
5344                err.contains("script_object must not be blank"),
5345                "got: {err}"
5346            );
5347        }
5348    }
5349
5350    #[test]
5351    fn validate_treats_whitespace_inline_script_as_unset() {
5352        // #918: a whitespace-only inline body is a commented-out block,
5353        // not a real script — with no other source it's "zero sources".
5354        let e = execute_with(Some("   \n  "), None, None);
5355        let err = e.validate_script_source().unwrap_err();
5356        assert!(err.contains("must be set"), "got: {err}");
5357    }
5358
5359    #[test]
5360    fn validate_rejects_malformed_script_object_ref() {
5361        // #918: the ref must be `<name>/<version>`; a missing slash,
5362        // extra slash, blank half, or whitespace-padded half (the last
5363        // survives a JSON POST body and 404s at exec — gemini/claude
5364        // #943) can never resolve.
5365        for bad in [
5366            "no-slash", "a/b/c", "/1.0.0", "cleanup/", " / ", "foo/bar ", " foo/bar", "foo /bar",
5367        ] {
5368            let e = execute_with(None, None, Some(bad));
5369            let err = e.validate_script_source().unwrap_err();
5370            assert!(
5371                err.contains("must be `<name>/<version>`"),
5372                "for '{bad}', got: {err}"
5373            );
5374        }
5375    }
5376
5377    #[test]
5378    fn manifest_deserialises_script_object_yaml() {
5379        // SPEC §2.4.1 example shape with the Object Store
5380        // reference picked over inline.
5381        let yaml = r#"
5382id: cleanup-disk-temp
5383version: 1.0.1
5384execute:
5385  shell: powershell
5386  script_object: cleanup-disk-temp/1.0.1
5387  timeout: 600s
5388"#;
5389        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
5390        assert_eq!(
5391            m.execute.script_object.as_deref(),
5392            Some("cleanup-disk-temp/1.0.1")
5393        );
5394        assert!(m.execute.script.is_none());
5395        m.validate()
5396            .expect("script_object-only manifest passes validation");
5397    }
5398
5399    #[test]
5400    fn manifest_rejects_typo_in_script_field_name() {
5401        // #492: the strict create boundary catches `script_objectt`
5402        // and similar fat-fingers (with the full path) instead of
5403        // letting them silently fall through to "all three unset".
5404        let yaml = r#"
5405id: typo
5406version: 1.0.0
5407execute:
5408  shell: powershell
5409  script_objectt: oops
5410  timeout: 30s
5411"#;
5412        let err = crate::strict::from_yaml_str::<Manifest>(yaml)
5413            .expect_err("typo'd execute field must be rejected at the write boundary");
5414        assert!(err.contains("execute.script_objectt"), "{err}");
5415    }
5416
5417    #[test]
5418    fn schedule_validate_refuses_a_pc_id_with_too_many_labels() {
5419        let parse = |pc: &str| -> Schedule {
5420            serde_yaml::from_str(&format!(
5421                "id: s\nwhen:\n  per_pc: {{ every: 1h }}\njob_id: j\ntarget:\n  pcs: [\"{pc}\"]\n"
5422            ))
5423            .expect("parse")
5424        };
5425        assert!(parse("a.b.c.d").validate().is_ok());
5426        let err = parse("a.b.c.d.e").validate().unwrap_err();
5427        assert!(err.contains("at most 4"), "{err}");
5428    }
5429
5430    #[test]
5431    fn schedule_carries_target_and_rollout() {
5432        let yaml = r#"
5433id: hourly-cleanup-canary
5434when:
5435  per_pc: { every: 1h }
5436job_id: cleanup
5437enabled: true
5438target:
5439  groups: [canary, wave1]
5440jitter: 30s
5441rollout:
5442  strategy: wave
5443  waves:
5444    - { group: canary, delay: 0s }
5445    - { group: wave1,  delay: 5s }
5446"#;
5447        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5448        assert_eq!(s.id, "hourly-cleanup-canary");
5449        assert_eq!(s.job_id, "cleanup");
5450        assert_eq!(s.plan.target.groups, vec!["canary", "wave1"]);
5451        assert_eq!(s.plan.jitter.as_deref(), Some("30s"));
5452        let rollout = s.plan.rollout.expect("rollout present");
5453        assert_eq!(rollout.waves.len(), 2);
5454        assert_eq!(rollout.waves[0].group, "canary");
5455        assert_eq!(rollout.waves[1].delay, "5s");
5456        assert_eq!(rollout.strategy, RolloutStrategy::Wave);
5457    }
5458
5459    #[test]
5460    fn schedule_minimal_target_all() {
5461        let yaml = r#"
5462id: kitting
5463when:
5464  per_pc: once
5465enabled: true
5466job_id: scheduled-echo
5467target: { all: true }
5468"#;
5469        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5470        assert_eq!(s.id, "kitting");
5471        assert_eq!(s.when, When::PerPc(PerPolicy::Once(OnceLiteral::Once)));
5472        assert!(s.enabled);
5473        assert_eq!(s.job_id, "scheduled-echo");
5474        assert!(s.plan.target.all);
5475        assert!(s.plan.rollout.is_none());
5476        assert!(s.plan.jitter.is_none());
5477        assert!(s.active.is_empty());
5478    }
5479
5480    #[test]
5481    fn schedule_enabled_defaults_to_true() {
5482        let yaml = r#"
5483id: x
5484when:
5485  per_pc: once
5486job_id: y
5487target: { all: true }
5488"#;
5489        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5490        assert!(s.enabled);
5491    }
5492
5493    fn once_per_version_yaml(runs_on: &str, per: &str) -> String {
5494        format!(
5495            "id: x\nwhen:\n  {per}\njob_id: install-kanade-client\n\
5496             target: {{ groups: [dejisen] }}\nruns_on: {runs_on}\n"
5497        )
5498    }
5499
5500    #[test]
5501    fn per_pc_once_per_version_parses() {
5502        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5503            "backend",
5504            "per_pc: once_per_version",
5505        ))
5506        .expect("parse");
5507        assert_eq!(
5508            s.when,
5509            When::PerPc(PerPolicy::OncePerVersion(
5510                OncePerVersionLiteral::OncePerVersion
5511            ))
5512        );
5513    }
5514
5515    #[test]
5516    fn per_pc_once_per_version_lowers_to_version_mode_no_cooldown() {
5517        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5518            "backend",
5519            "per_pc: once_per_version",
5520        ))
5521        .expect("parse");
5522        let l = s.lowered();
5523        assert_eq!(l.mode, ExecMode::OncePerPcVersion);
5524        assert_eq!(l.cooldown, None, "version re-arm is not a cooldown");
5525    }
5526
5527    #[test]
5528    fn once_per_version_displays_and_serialises() {
5529        let w = When::PerPc(PerPolicy::OncePerVersion(
5530            OncePerVersionLiteral::OncePerVersion,
5531        ));
5532        assert_eq!(w.to_string(), "per_pc once_per_version");
5533        // serde round-trips through the ergonomic bare string.
5534        let json = serde_json::to_value(&w).unwrap();
5535        assert_eq!(json, serde_json::json!({ "per_pc": "once_per_version" }));
5536    }
5537
5538    #[test]
5539    fn once_per_version_rejects_typo() {
5540        // The distinct literal still catches typos (no free-form String).
5541        let r: Result<Schedule, _> = serde_yaml::from_str(&once_per_version_yaml(
5542            "backend",
5543            "per_pc: once_per_verison",
5544        ));
5545        assert!(r.is_err(), "typo should not parse");
5546    }
5547
5548    #[test]
5549    fn validate_accepts_once_per_version_on_backend() {
5550        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5551            "backend",
5552            "per_pc: once_per_version",
5553        ))
5554        .expect("parse");
5555        assert!(s.validate().is_ok(), "got: {:?}", s.validate());
5556    }
5557
5558    #[test]
5559    fn validate_rejects_once_per_version_on_agent() {
5560        let s: Schedule =
5561            serde_yaml::from_str(&once_per_version_yaml("agent", "per_pc: once_per_version"))
5562                .expect("parse");
5563        let err = s
5564            .validate()
5565            .expect_err("agent + once_per_version must be rejected");
5566        assert!(err.contains("once_per_version"), "got: {err}");
5567        assert!(err.contains("backend"), "got: {err}");
5568    }
5569
5570    #[test]
5571    fn validate_rejects_once_per_version_on_per_target() {
5572        let s: Schedule = serde_yaml::from_str(&once_per_version_yaml(
5573            "backend",
5574            "per_target: once_per_version",
5575        ))
5576        .expect("parse");
5577        let err = s
5578            .validate()
5579            .expect_err("per_target + once_per_version must be rejected");
5580        assert!(err.contains("once_per_version"), "got: {err}");
5581        assert!(err.contains("per_pc"), "got: {err}");
5582    }
5583
5584    #[test]
5585    fn schedule_tags_default_empty_and_skip_serialise() {
5586        let yaml = r#"
5587id: x
5588when:
5589  per_pc: once
5590job_id: y
5591target: { all: true }
5592"#;
5593        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5594        assert!(s.tags.is_empty());
5595        s.validate().expect("tag-less schedule validates");
5596        let json = serde_json::to_string(&s).expect("serialize");
5597        assert!(
5598            !json.contains("tags"),
5599            "empty tags must not serialise: {json}"
5600        );
5601    }
5602
5603    #[test]
5604    fn schedule_parses_and_validates_tags() {
5605        let yaml = r#"
5606id: weekly-cleanup
5607when:
5608  per_pc: { every: 1h }
5609job_id: cleanup
5610target: { all: true }
5611tags: [weekly, maintenance]
5612"#;
5613        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5614        assert_eq!(s.tags, vec!["weekly", "maintenance"]);
5615        s.validate().expect("tagged schedule validates");
5616    }
5617
5618    #[test]
5619    fn schedule_rejects_blank_tag() {
5620        let yaml = r#"
5621id: x
5622when:
5623  per_pc: once
5624job_id: y
5625target: { all: true }
5626tags: [ok, "  "]
5627"#;
5628        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
5629        let err = s.validate().expect_err("blank tag must fail");
5630        assert!(err.contains("tags must not contain empty"), "err: {err}");
5631    }
5632
5633    // ---- `when` parsing (#418 Phase 1) ----
5634
5635    fn schedule_yaml_with(when_block: &str) -> String {
5636        format!(
5637            r#"
5638id: x
5639when:
5640{when_block}
5641job_id: y
5642target: {{ all: true }}
5643"#
5644        )
5645    }
5646
5647    #[test]
5648    fn when_per_pc_every_parses_unquoted_humantime() {
5649        // `6h` is digit-led but non-numeric → YAML string, same as
5650        // the old `cooldown: 6h` convention. No quotes needed.
5651        let s: Schedule =
5652            serde_yaml::from_str(&schedule_yaml_with("  per_pc: { every: 6h }")).expect("parse");
5653        assert_eq!(
5654            s.when,
5655            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() }))
5656        );
5657    }
5658
5659    #[test]
5660    fn when_per_target_every_parses() {
5661        let s: Schedule = serde_yaml::from_str(&schedule_yaml_with("  per_target: { every: 24h }"))
5662            .expect("parse");
5663        assert_eq!(
5664            s.when,
5665            When::PerTarget(PerPolicy::Every(EverySpec {
5666                every: "24h".into()
5667            }))
5668        );
5669    }
5670
5671    #[test]
5672    fn when_per_target_once_parses() {
5673        // Falls out of the shared PerPolicy shape and decide_fire
5674        // already implements it ("any one pc succeeds → skip the
5675        // target forever"), so it is allowed, not rejected.
5676        let s: Schedule =
5677            serde_yaml::from_str(&schedule_yaml_with("  per_target: once")).expect("parse");
5678        assert_eq!(s.when, When::PerTarget(PerPolicy::Once(OnceLiteral::Once)));
5679    }
5680
5681    #[test]
5682    fn when_calendar_time_parses() {
5683        let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(
5684            "  calendar:\n    at: \"09:00\"\n    days: [mon-fri]",
5685        ))
5686        .expect("parse");
5687        match &s.when {
5688            When::Calendar(c) => {
5689                assert_eq!(c.at, "09:00");
5690                assert_eq!(c.days, vec!["mon-fri"]);
5691            }
5692            other => panic!("expected calendar, got {other:?}"),
5693        }
5694    }
5695
5696    #[test]
5697    fn when_calendar_days_default_empty() {
5698        let s: Schedule =
5699            serde_yaml::from_str(&schedule_yaml_with("  calendar:\n    at: \"09:00\""))
5700                .expect("parse");
5701        match &s.when {
5702            When::Calendar(c) => assert!(c.days.is_empty(), "days defaults to empty (= daily)"),
5703            other => panic!("expected calendar, got {other:?}"),
5704        }
5705    }
5706
5707    #[test]
5708    fn when_calendar_datetime_parses_all_separators() {
5709        // one-shot: date+time in hyphen / ISO-T / slash forms
5710        for at in ["2026-06-10 09:00", "2026-06-10T09:00", "2026/06/10 09:00"] {
5711            let block = format!("  calendar:\n    at: \"{at}\"");
5712            let s: Schedule = serde_yaml::from_str(&schedule_yaml_with(&block))
5713                .unwrap_or_else(|e| panic!("parse '{at}': {e}"));
5714            match &s.when {
5715                When::Calendar(c) => {
5716                    use chrono::Datelike;
5717                    let p = c.parse_at().expect("parse_at");
5718                    let d = p.date.expect("datetime at carries a date");
5719                    assert_eq!((d.year(), d.month(), d.day()), (2026, 6, 10), "for '{at}'");
5720                }
5721                other => panic!("expected calendar, got {other:?}"),
5722            }
5723        }
5724    }
5725
5726    #[test]
5727    fn when_rejects_bad_once_keyword() {
5728        // `onec` must be a parse error, not a silently-absorbed
5729        // string (OnceLiteral is a single-variant enum for exactly
5730        // this reason).
5731        let r: Result<Schedule, _> = serde_yaml::from_str(&schedule_yaml_with("  per_pc: onec"));
5732        assert!(r.is_err(), "expected parse error, got {r:?}");
5733    }
5734
5735    #[test]
5736    fn when_rejects_unknown_key_in_every() {
5737        // `{ evry: 6h }` still fails on the tolerant read path: the
5738        // required `every` key is missing, so no PerPolicy variant
5739        // matches (#492 removed deny_unknown_fields, but required
5740        // keys keep the untagged disambiguation honest).
5741        let r: Result<Schedule, _> =
5742            serde_yaml::from_str(&schedule_yaml_with("  per_pc: { evry: 6h }"));
5743        assert!(r.is_err(), "expected parse error, got {r:?}");
5744    }
5745
5746    #[test]
5747    fn when_rejects_unknown_variant() {
5748        let r: Result<Schedule, _> =
5749            serde_yaml::from_str(&schedule_yaml_with("  per_galaxy: once"));
5750        assert!(r.is_err(), "expected parse error, got {r:?}");
5751    }
5752
5753    #[test]
5754    fn when_rejects_old_top_level_cron_field() {
5755        // Pre-#418 shape: top-level `cron:` + no `when:`. Must fail
5756        // loudly (missing `when`), which is what turns stale KV
5757        // blobs into warn-skips after the upgrade.
5758        let yaml = r#"
5759id: x
5760cron: "* * * * * *"
5761job_id: y
5762target: { all: true }
5763"#;
5764        let r: Result<Schedule, _> = serde_yaml::from_str(yaml);
5765        assert!(r.is_err(), "expected parse error, got {r:?}");
5766    }
5767
5768    #[test]
5769    fn when_rejects_retired_cron_escape_hatch() {
5770        // #418 Phase 2 retired `when: { cron: "..." }`. A raw cron
5771        // is now an unknown variant → parse error (operators use the
5772        // calendar form instead).
5773        let r: Result<Schedule, _> =
5774            serde_yaml::from_str(&schedule_yaml_with("  cron: \"0 0 9 * * mon-fri\""));
5775        assert!(
5776            r.is_err(),
5777            "expected parse error for retired cron, got {r:?}"
5778        );
5779    }
5780
5781    #[test]
5782    fn when_round_trips_json_and_yaml() {
5783        // Round-trip through the full Schedule: that is the wire
5784        // unit for both stores (JSON catalog KV + YAML mirror), and
5785        // it exercises the singleton_map field attribute that keeps
5786        // serde_yaml on the map shape instead of `!per_pc` tags.
5787        for when in [
5788            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5789            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5790            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5791            When::PerTarget(PerPolicy::Every(EverySpec {
5792                every: "24h".into(),
5793            })),
5794            calendar("09:00", &["mon-fri"]),
5795            calendar("2026-06-10 09:00", &[]),
5796            When::On(vec![OnTrigger::Startup]),
5797            When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
5798            When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
5799            When::On(vec![OnTrigger::NetworkChange]),
5800        ] {
5801            // Event triggers are agent-only; the rest validate on backend.
5802            let runs_on = if matches!(when, When::On(_)) {
5803                RunsOn::Agent
5804            } else {
5805                RunsOn::Backend
5806            };
5807            let s = schedule_with(when.clone(), runs_on);
5808
5809            let json = serde_json::to_string(&s).expect("json serialise");
5810            let back: Schedule = serde_json::from_str(&json).expect("json deserialise");
5811            assert_eq!(back.when, when, "json round-trip for {when}");
5812
5813            let yaml = serde_yaml::to_string(&s).expect("yaml serialise");
5814            assert!(
5815                !yaml.contains('!'),
5816                "yaml must use the map shape, not tags: {yaml}"
5817            );
5818            let back: Schedule = serde_yaml::from_str(&yaml).expect("yaml deserialise");
5819            assert_eq!(back.when, when, "yaml round-trip for {when}");
5820        }
5821    }
5822
5823    #[test]
5824    fn when_once_serialises_as_bare_keyword() {
5825        // The wire shape operators see in the YAML mirror must stay
5826        // the ergonomic `per_pc: once`, not a one-variant map.
5827        let json = serde_json::to_value(When::PerPc(PerPolicy::Once(OnceLiteral::Once)))
5828            .expect("serialise");
5829        assert_eq!(json, serde_json::json!({ "per_pc": "once" }));
5830    }
5831
5832    #[test]
5833    fn when_displays_operator_summary() {
5834        for (when, expected) in [
5835            (
5836                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5837                "per_pc once",
5838            ),
5839            (
5840                When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5841                "per_pc every 6h",
5842            ),
5843            (
5844                When::PerTarget(PerPolicy::Every(EverySpec {
5845                    every: "24h".into(),
5846                })),
5847                "per_target every 24h",
5848            ),
5849            (calendar("09:00", &["mon-fri"]), "at 09:00 [mon-fri]"),
5850            (calendar("2026-06-10 09:00", &[]), "at 2026-06-10 09:00"),
5851            (When::On(vec![OnTrigger::Startup]), "on [startup]"),
5852            (
5853                When::On(vec![OnTrigger::Startup, OnTrigger::Logon]),
5854                "on [startup,logon]",
5855            ),
5856            (
5857                When::On(vec![OnTrigger::Lock, OnTrigger::Unlock]),
5858                "on [lock,unlock]",
5859            ),
5860            (
5861                When::On(vec![OnTrigger::NetworkChange]),
5862                "on [network_change]",
5863            ),
5864        ] {
5865            assert_eq!(when.to_string(), expected);
5866        }
5867    }
5868
5869    // ---- lowering (#418: when → engine vocabulary) ----
5870
5871    fn schedule_with(when: When, runs_on: RunsOn) -> Schedule {
5872        Schedule {
5873            id: "x".into(),
5874            when,
5875            job_id: "y".into(),
5876            // #917: validate() now rejects a target that dispatches
5877            // nothing, so the baseline helper carries the simplest
5878            // specified target.
5879            plan: FanoutPlan {
5880                target: Target {
5881                    all: true,
5882                    ..Target::default()
5883                },
5884                ..FanoutPlan::default()
5885            },
5886            active: Active::default(),
5887            constraints: Constraints::default(),
5888            on_failure: OnFailure::default(),
5889            tz: ScheduleTz::default(),
5890            starting_deadline: None,
5891            runs_on,
5892            enabled: true,
5893            tags: Vec::new(),
5894            origin: None,
5895        }
5896    }
5897
5898    fn calendar(at: &str, days: &[&str]) -> When {
5899        When::Calendar(CalendarSpec {
5900            at: at.into(),
5901            days: days.iter().map(|d| (*d).to_string()).collect(),
5902        })
5903    }
5904
5905    #[test]
5906    fn next_calendar_fire_returns_next_utc_occurrence() {
5907        use chrono::TimeZone;
5908        // Daily 09:00, evaluated in UTC. From 08:00 the same day, the
5909        // next strict occurrence is 09:00 that day.
5910        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5911        s.tz = ScheduleTz::Utc;
5912        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 8, 0, 0).unwrap();
5913        let next = s.next_calendar_fire(now).expect("calendar has a next fire");
5914        assert_eq!(
5915            next,
5916            chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap()
5917        );
5918    }
5919
5920    #[test]
5921    fn next_calendar_fire_is_strictly_after_now() {
5922        use chrono::TimeZone;
5923        // Standing exactly on a fire instant must preview the *next*
5924        // one (inclusive = false), not the one firing right now.
5925        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
5926        s.tz = ScheduleTz::Utc;
5927        let on_fire = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap();
5928        let next = s
5929            .next_calendar_fire(on_fire)
5930            .expect("calendar has a next fire");
5931        assert_eq!(
5932            next,
5933            chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()
5934        );
5935    }
5936
5937    #[test]
5938    fn next_calendar_fire_none_for_reconcile_shapes() {
5939        // `per_pc` / `per_target` lower to the every-minute poll cron —
5940        // no discrete upcoming event to preview, so `None`.
5941        let now = chrono::Utc::now();
5942        for when in [
5943            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
5944            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
5945            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
5946            When::PerTarget(PerPolicy::Every(EverySpec {
5947                every: "24h".into(),
5948            })),
5949        ] {
5950            let s = schedule_with(when, RunsOn::Backend);
5951            assert!(
5952                s.next_calendar_fire(now).is_none(),
5953                "reconcile shapes have no calendar fire",
5954            );
5955        }
5956    }
5957
5958    // ---- preview_fires (#418 dry-run / preview) ----
5959
5960    fn cal_utc(at: &str, days: &[&str]) -> Schedule {
5961        let mut s = schedule_with(calendar(at, days), RunsOn::Backend);
5962        s.tz = ScheduleTz::Utc; // host-independent assertions
5963        s
5964    }
5965
5966    #[test]
5967    fn preview_lists_next_calendar_occurrences() {
5968        use chrono::TimeZone;
5969        // Weekday 09:00, from Wed 2026-06-10 00:00 UTC: the next five
5970        // fires skip the weekend (Sat 13 / Sun 14).
5971        let s = cal_utc("09:00", &["mon-fri"]);
5972        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
5973        let got = s.preview_fires(now, 5);
5974        let want: Vec<_> = [
5975            (2026, 6, 10), // Wed
5976            (2026, 6, 11), // Thu
5977            (2026, 6, 12), // Fri
5978            (2026, 6, 15), // Mon (skips Sat 13 / Sun 14)
5979            (2026, 6, 16), // Tue
5980        ]
5981        .iter()
5982        .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
5983        .collect();
5984        assert_eq!(got, want);
5985    }
5986
5987    #[test]
5988    fn preview_handles_nth_and_last_weekday() {
5989        use chrono::TimeZone;
5990        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
5991        // 2nd Tuesday (Patch Tuesday): Jun 9, Jul 14 2026.
5992        let nth = cal_utc("09:00", &["tue#2"]).preview_fires(now, 2);
5993        assert_eq!(
5994            nth,
5995            vec![
5996                chrono::Utc.with_ymd_and_hms(2026, 6, 9, 9, 0, 0).unwrap(),
5997                chrono::Utc.with_ymd_and_hms(2026, 7, 14, 9, 0, 0).unwrap(),
5998            ]
5999        );
6000        // Last Friday of the month: Jun 26, Jul 31 2026.
6001        let last = cal_utc("22:00", &["friL"]).preview_fires(now, 2);
6002        assert_eq!(
6003            last,
6004            vec![
6005                chrono::Utc.with_ymd_and_hms(2026, 6, 26, 22, 0, 0).unwrap(),
6006                chrono::Utc.with_ymd_and_hms(2026, 7, 31, 22, 0, 0).unwrap(),
6007            ]
6008        );
6009    }
6010
6011    #[test]
6012    fn preview_is_empty_for_reconcile_and_zero_count() {
6013        let now = chrono::Utc::now();
6014        // reconcile shapes have no discrete fire times
6015        let recon = schedule_with(
6016            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6017            RunsOn::Backend,
6018        );
6019        assert!(recon.preview_fires(now, 5).is_empty());
6020        // count == 0 yields nothing even for a calendar
6021        assert!(cal_utc("09:00", &[]).preview_fires(now, 0).is_empty());
6022    }
6023
6024    #[test]
6025    fn preview_skips_outside_active_window() {
6026        use chrono::TimeZone;
6027        // Daily 09:00, active only [2026-06-15, 2026-06-17). Occurrences
6028        // before `from` are skipped; `until` is exclusive, so 06-17's
6029        // fire is out — leaving exactly the 15th and 16th.
6030        let mut s = cal_utc("09:00", &[]);
6031        s.active = Active {
6032            from: Some("2026-06-15".into()),
6033            until: Some("2026-06-17".into()),
6034        };
6035        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
6036        let got = s.preview_fires(now, 5);
6037        assert_eq!(
6038            got,
6039            vec![
6040                chrono::Utc.with_ymd_and_hms(2026, 6, 15, 9, 0, 0).unwrap(),
6041                chrono::Utc.with_ymd_and_hms(2026, 6, 16, 9, 0, 0).unwrap(),
6042            ]
6043        );
6044    }
6045
6046    #[test]
6047    fn preview_empty_when_calendar_time_outside_window() {
6048        use chrono::TimeZone;
6049        // Fires at 09:00 but the maintenance window is overnight — it can
6050        // never run, so the preview is empty (matches
6051        // `calendar_outside_window`), and the scan still terminates.
6052        let mut s = cal_utc("09:00", &[]);
6053        s.constraints = Constraints {
6054            window: Some("22:00-05:00".into()),
6055            ..Constraints::default()
6056        };
6057        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
6058        assert!(s.preview_fires(now, 5).is_empty());
6059        // Every candidate tick is rejected, so this also exercises the
6060        // SCAN_CAP bound: a large `count` must still terminate (and
6061        // return empty) rather than spin (claude #578 review).
6062        assert!(s.preview_fires(now, 50).is_empty());
6063    }
6064
6065    #[test]
6066    fn preview_past_one_shot_is_empty() {
6067        use chrono::TimeZone;
6068        // A dated one-shot whose instant has passed never fires again.
6069        let s = cal_utc("2026-06-10 09:00", &[]);
6070        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 0, 0, 0).unwrap();
6071        assert!(s.preview_fires(now, 5).is_empty());
6072        // …but from before it, the single future fire shows up.
6073        let before = chrono::Utc.with_ymd_and_hms(2026, 6, 1, 0, 0, 0).unwrap();
6074        assert_eq!(
6075            s.preview_fires(before, 5),
6076            vec![chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap()]
6077        );
6078    }
6079
6080    #[test]
6081    fn lowering_matches_the_418_table() {
6082        let cases = [
6083            (
6084                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6085                (POLL_CRON, ExecMode::OncePerPc, None),
6086            ),
6087            (
6088                When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6089                (POLL_CRON, ExecMode::OncePerPc, Some("6h")),
6090            ),
6091            (
6092                When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
6093                (POLL_CRON, ExecMode::OncePerTarget, None),
6094            ),
6095            (
6096                When::PerTarget(PerPolicy::Every(EverySpec {
6097                    every: "24h".into(),
6098                })),
6099                (POLL_CRON, ExecMode::OncePerTarget, Some("24h")),
6100            ),
6101            // calendar repeating → 6-field cron
6102            (
6103                calendar("09:00", &["mon-fri"]),
6104                ("0 0 9 * * mon-fri", ExecMode::EveryTick, None),
6105            ),
6106            // calendar daily (no days) → DOW *
6107            (
6108                calendar("18:30", &[]),
6109                ("0 30 18 * * *", ExecMode::EveryTick, None),
6110            ),
6111            // calendar one-shot → 7-field year cron
6112            (
6113                calendar("2026-06-10 09:00", &[]),
6114                ("0 0 9 10 6 * 2026", ExecMode::EveryTick, None),
6115            ),
6116        ];
6117        for (when, (cron, mode, cooldown)) in cases {
6118            let l = schedule_with(when.clone(), RunsOn::Backend).lowered();
6119            assert_eq!(l.cron, cron, "cron for {when}");
6120            assert_eq!(l.mode, mode, "mode for {when}");
6121            assert_eq!(l.cooldown.as_deref(), cooldown, "cooldown for {when}");
6122        }
6123    }
6124
6125    #[test]
6126    fn lowered_carries_schedule_tz() {
6127        for (tz, want) in [
6128            (ScheduleTz::Local, ScheduleTz::Local),
6129            (ScheduleTz::Utc, ScheduleTz::Utc),
6130        ] {
6131            let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
6132            s.tz = tz;
6133            assert_eq!(s.lowered().tz, want, "calendar carries tz");
6134            // reconcile shapes carry tz too (for the active-window check)
6135            let mut s = schedule_with(
6136                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6137                RunsOn::Backend,
6138            );
6139            s.tz = tz;
6140            assert_eq!(s.lowered().tz, want, "reconcile carries tz");
6141        }
6142    }
6143
6144    #[test]
6145    fn poll_cron_is_accepted_by_the_engine_parser() {
6146        // POLL_CRON is system-generated — if the engine's parser
6147        // ever rejected it every reconcile schedule would die at
6148        // register time. Validate it with the same croner config
6149        // (Seconds::Required, dom_and_dow, year optional).
6150        croner::parser::CronParser::builder()
6151            .seconds(croner::parser::Seconds::Required)
6152            .dom_and_dow(true)
6153            .build()
6154            .parse(POLL_CRON)
6155            .expect("POLL_CRON must parse");
6156    }
6157
6158    // ---- Schedule::validate() (#418 decision F) ----
6159
6160    #[test]
6161    fn validate_accepts_reconcile_shapes() {
6162        for when in [
6163            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6164            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
6165            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
6166            When::PerTarget(PerPolicy::Every(EverySpec {
6167                every: "24h".into(),
6168            })),
6169        ] {
6170            schedule_with(when.clone(), RunsOn::Backend)
6171                .validate()
6172                .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
6173        }
6174    }
6175
6176    #[test]
6177    fn validate_accepts_per_pc_on_agent() {
6178        schedule_with(
6179            When::PerPc(PerPolicy::Every(EverySpec { every: "1h".into() })),
6180            RunsOn::Agent,
6181        )
6182        .validate()
6183        .expect("per_pc + agent is the offline-inventory shape");
6184    }
6185
6186    // ---- #418 event triggers (when: { on }) ----
6187
6188    #[test]
6189    fn validate_accepts_event_on_agent() {
6190        for triggers in [
6191            vec![OnTrigger::Startup],
6192            vec![OnTrigger::Logon],
6193            vec![OnTrigger::Lock],
6194            vec![OnTrigger::Unlock],
6195            vec![OnTrigger::NetworkChange],
6196            vec![
6197                OnTrigger::Startup,
6198                OnTrigger::Logon,
6199                OnTrigger::Lock,
6200                OnTrigger::Unlock,
6201                OnTrigger::NetworkChange,
6202            ],
6203        ] {
6204            schedule_with(When::On(triggers), RunsOn::Agent)
6205                .validate()
6206                .expect("when.on is valid on runs_on: agent");
6207        }
6208    }
6209
6210    #[test]
6211    fn validate_rejects_event_on_backend() {
6212        let err = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Backend)
6213            .validate()
6214            .unwrap_err();
6215        assert!(err.contains("when.on"), "got: {err}");
6216        assert!(err.contains("runs_on: agent"), "got: {err}");
6217    }
6218
6219    #[test]
6220    fn validate_rejects_empty_event_list() {
6221        let err = schedule_with(When::On(vec![]), RunsOn::Agent)
6222            .validate()
6223            .unwrap_err();
6224        assert!(err.contains("when.on"), "got: {err}");
6225        assert!(err.contains("at least one"), "got: {err}");
6226    }
6227
6228    #[test]
6229    fn event_schedule_lowers_to_event_mode_and_is_event() {
6230        let s = schedule_with(When::On(vec![OnTrigger::Startup]), RunsOn::Agent);
6231        assert!(s.is_event());
6232        assert_eq!(s.lowered().mode, ExecMode::Event);
6233        assert_eq!(s.event_triggers(), &[OnTrigger::Startup]);
6234        // non-event schedules report no triggers.
6235        let cal = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
6236        assert!(!cal.is_event());
6237        assert!(cal.event_triggers().is_empty());
6238    }
6239
6240    // ---- #418 constraints.require (env gates) ----
6241
6242    fn require_schedule(req: Require, runs_on: RunsOn) -> Schedule {
6243        let mut s = schedule_with(
6244            When::PerPc(PerPolicy::Every(EverySpec { every: "1m".into() })),
6245            runs_on,
6246        );
6247        s.constraints.require = Some(req);
6248        s
6249    }
6250
6251    #[test]
6252    fn require_met_combinations() {
6253        use std::time::Duration;
6254        let idle = |m: u64| Some(Duration::from_secs(m * 60));
6255        // Builder for the sensed state: (ac, idle, cpu, network).
6256        let env = |ac, idle, cpu, net| EnvState {
6257            ac_online: ac,
6258            idle,
6259            cpu_pct: cpu,
6260            network_up: net,
6261        };
6262        // Empty require — always met regardless of sensed state.
6263        assert!(require_met(
6264            &Require::default(),
6265            &env(false, None, None, false)
6266        ));
6267        // ac_power: only on AC.
6268        let ac = Require {
6269            ac_power: true,
6270            ..Default::default()
6271        };
6272        assert!(!require_met(&ac, &env(false, None, None, true)));
6273        assert!(require_met(&ac, &env(true, None, None, false)));
6274        // idle: needs >= the configured min; None idle never satisfies.
6275        let idle10 = Require {
6276            idle: Some("10m".into()),
6277            ..Default::default()
6278        };
6279        assert!(!require_met(&idle10, &env(true, None, None, true)));
6280        assert!(!require_met(&idle10, &env(true, idle(5), None, true)));
6281        assert!(require_met(&idle10, &env(true, idle(15), None, true)));
6282        assert!(require_met(&idle10, &env(true, idle(10), None, true))); // boundary inclusive
6283        // cpu_below: needs CPU strictly < threshold; None cpu never satisfies.
6284        let cpu20 = Require {
6285            cpu_below: Some(20.0),
6286            ..Default::default()
6287        };
6288        assert!(!require_met(&cpu20, &env(true, None, None, true))); // no sample → fail-closed
6289        assert!(!require_met(&cpu20, &env(true, None, Some(20.0), true))); // == threshold
6290        assert!(!require_met(&cpu20, &env(true, None, Some(55.0), true))); // busy
6291        assert!(require_met(&cpu20, &env(true, None, Some(5.0), true))); // quiet
6292        // network: only when online.
6293        let net = Require {
6294            network: true,
6295            ..Default::default()
6296        };
6297        assert!(!require_met(&net, &env(true, None, None, false))); // offline
6298        assert!(require_met(&net, &env(true, None, None, true))); // online
6299        // all four: AND.
6300        let all = Require {
6301            ac_power: true,
6302            idle: Some("10m".into()),
6303            cpu_below: Some(20.0),
6304            network: true,
6305        };
6306        assert!(!require_met(&all, &env(false, idle(20), Some(5.0), true))); // on battery
6307        assert!(!require_met(&all, &env(true, idle(1), Some(5.0), true))); // not idle enough
6308        assert!(!require_met(&all, &env(true, idle(20), Some(50.0), true))); // busy
6309        assert!(!require_met(&all, &env(true, idle(20), Some(5.0), false))); // offline
6310        assert!(require_met(&all, &env(true, idle(20), Some(5.0), true)));
6311        // An unparseable idle is treated as no-requirement by require_met
6312        // (validate rejects it at create time, so this only guards a
6313        // hand-edited blob): ac still gates.
6314        let bad = Require {
6315            ac_power: true,
6316            idle: Some("garbage".into()),
6317            ..Default::default()
6318        };
6319        assert!(require_met(&bad, &env(true, None, None, true)));
6320        assert!(!require_met(&bad, &env(false, None, None, true)));
6321    }
6322
6323    #[test]
6324    fn validate_accepts_and_rejects_cpu_below() {
6325        // In-range accepted.
6326        require_schedule(
6327            Require {
6328                cpu_below: Some(20.0),
6329                ..Default::default()
6330            },
6331            RunsOn::Agent,
6332        )
6333        .validate()
6334        .expect("cpu_below 20 is valid");
6335        // Upper boundary: 100.0 is accepted (fires unless CPU is exactly
6336        // 100%). Pins the inclusive upper bound against a future c < 100.0.
6337        require_schedule(
6338            Require {
6339                cpu_below: Some(100.0),
6340                ..Default::default()
6341            },
6342            RunsOn::Agent,
6343        )
6344        .validate()
6345        .expect("cpu_below 100 is valid");
6346        // Out of range rejected (0 and >100).
6347        for bad in [0.0, -5.0, 100.1] {
6348            let err = require_schedule(
6349                Require {
6350                    cpu_below: Some(bad),
6351                    ..Default::default()
6352                },
6353                RunsOn::Agent,
6354            )
6355            .validate()
6356            .unwrap_err();
6357            assert!(
6358                err.contains("constraints.require.cpu_below"),
6359                "cpu_below {bad}: {err}"
6360            );
6361        }
6362    }
6363
6364    #[test]
6365    fn validate_accepts_require_on_agent() {
6366        require_schedule(
6367            Require {
6368                ac_power: true,
6369                idle: Some("10m".into()),
6370                cpu_below: Some(20.0),
6371                network: true,
6372            },
6373            RunsOn::Agent,
6374        )
6375        .validate()
6376        .expect("constraints.require is valid on runs_on: agent");
6377    }
6378
6379    #[test]
6380    fn validate_rejects_require_on_backend() {
6381        let err = require_schedule(
6382            Require {
6383                ac_power: true,
6384                ..Default::default()
6385            },
6386            RunsOn::Backend,
6387        )
6388        .validate()
6389        .unwrap_err();
6390        assert!(err.contains("constraints.require"), "got: {err}");
6391        assert!(err.contains("runs_on: agent"), "got: {err}");
6392
6393        // An idle-only require (ac_power: false) is also non-empty
6394        // (is_empty folds the fields) and must reject on backend too —
6395        // guards against a regression in Require::is_empty.
6396        let err = require_schedule(
6397            Require {
6398                idle: Some("10m".into()),
6399                ..Default::default()
6400            },
6401            RunsOn::Backend,
6402        )
6403        .validate()
6404        .unwrap_err();
6405        assert!(
6406            err.contains("constraints.require"),
6407            "idle-only on backend: {err}"
6408        );
6409    }
6410
6411    #[test]
6412    fn validate_rejects_bad_require_idle() {
6413        let err = require_schedule(
6414            Require {
6415                idle: Some("not-a-duration".into()),
6416                ..Default::default()
6417            },
6418            RunsOn::Agent,
6419        )
6420        .validate()
6421        .unwrap_err();
6422        assert!(err.contains("constraints.require.idle"), "got: {err}");
6423    }
6424
6425    #[test]
6426    fn require_round_trips_and_skips_empty() {
6427        // ac_power: false is skipped; an all-default require nested in
6428        // constraints is omitted (is_empty folds it in).
6429        let yaml = "id: s\nwhen: { per_pc: { every: 1m } }\njob_id: j\nruns_on: agent\n\
6430                    constraints: { require: { ac_power: true, idle: 10m, cpu_below: 20, \
6431                    network: true } }\n";
6432        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
6433        let req = s.constraints.require.as_ref().expect("require present");
6434        assert!(req.ac_power);
6435        assert_eq!(req.idle.as_deref(), Some("10m"));
6436        assert_eq!(req.cpu_below, Some(20.0));
6437        assert!(req.network);
6438        // Re-serialize: idle + cpu_below + network present, ac_power true.
6439        let back = serde_json::to_string(&s.constraints).unwrap();
6440        assert!(back.contains("\"idle\":\"10m\""), "got: {back}");
6441        assert!(back.contains("\"cpu_below\":20"), "got: {back}");
6442        assert!(back.contains("\"network\":true"), "got: {back}");
6443        // An empty require is omitted entirely by is_empty.
6444        let mut empty = s.clone();
6445        empty.constraints.require = Some(Require::default());
6446        assert!(empty.constraints.is_empty());
6447    }
6448
6449    #[test]
6450    fn validate_rejects_per_target_on_agent() {
6451        let err = schedule_with(
6452            When::PerTarget(PerPolicy::Every(EverySpec {
6453                every: "24h".into(),
6454            })),
6455            RunsOn::Agent,
6456        )
6457        .validate()
6458        .unwrap_err();
6459        assert!(err.contains("per_target"), "got: {err}");
6460        assert!(err.contains("runs_on: agent"), "got: {err}");
6461
6462        // per_target: once is also backend-only.
6463        let err = schedule_with(
6464            When::PerTarget(PerPolicy::Once(OnceLiteral::Once)),
6465            RunsOn::Agent,
6466        )
6467        .validate()
6468        .unwrap_err();
6469        assert!(err.contains("per_target"), "got (once): {err}");
6470        assert!(err.contains("runs_on: agent"), "got (once): {err}");
6471    }
6472
6473    #[test]
6474    fn validate_rejects_bad_every_duration() {
6475        let err = schedule_with(
6476            When::PerPc(PerPolicy::Every(EverySpec { every: "6x".into() })),
6477            RunsOn::Backend,
6478        )
6479        .validate()
6480        .unwrap_err();
6481        assert!(err.contains("when.every"), "got: {err}");
6482    }
6483
6484    #[test]
6485    fn validate_rejects_bad_jitter_and_starting_deadline() {
6486        let mut s = schedule_with(
6487            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6488            RunsOn::Backend,
6489        );
6490        s.plan.jitter = Some("5x".into());
6491        let err = s.validate().unwrap_err();
6492        assert!(err.contains("jitter"), "got: {err}");
6493
6494        let mut s = schedule_with(
6495            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6496            RunsOn::Backend,
6497        );
6498        s.starting_deadline = Some("soon".into());
6499        let err = s.validate().unwrap_err();
6500        assert!(err.contains("starting_deadline"), "got: {err}");
6501    }
6502
6503    #[test]
6504    fn validate_rejects_unspecified_target() {
6505        // #917 (1): an all-default target never dispatches anywhere —
6506        // runs_on: agent silently never fires, runs_on: backend
6507        // warn-fails every tick at the exec boundary. Both rejected.
6508        for runs_on in [RunsOn::Backend, RunsOn::Agent] {
6509            let mut s = schedule_with(When::PerPc(PerPolicy::Once(OnceLiteral::Once)), runs_on);
6510            s.plan.target = Target::default();
6511            let err = s.validate().unwrap_err();
6512            assert!(err.contains("target"), "for {runs_on:?}, got: {err}");
6513        }
6514    }
6515
6516    /// A Schedule with every top-level field populated so each one
6517    /// actually serialises (the optional ones are `skip_serializing_if`).
6518    fn fully_populated_schedule() -> Schedule {
6519        let mut s = schedule_with(
6520            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6521            RunsOn::Backend,
6522        );
6523        s.plan.rollout = Some(Rollout {
6524            strategy: RolloutStrategy::Wave,
6525            waves: vec![Wave {
6526                group: "canary".into(),
6527                delay: "0s".into(),
6528            }],
6529        });
6530        s.plan.jitter = Some("5m".into());
6531        s.plan.deadline_at = Some(chrono::Utc::now());
6532        s.active = Active {
6533            from: Some("2026-01-01 00:00".into()),
6534            until: Some("2026-12-31 00:00".into()),
6535        };
6536        s.constraints = Constraints {
6537            window: Some("09:00-17:00".into()),
6538            ..Constraints::default()
6539        };
6540        s.on_failure = OnFailure {
6541            retry: Some(Retry {
6542                max: 1,
6543                backoff: "10s".into(),
6544            }),
6545        };
6546        s.starting_deadline = Some("30m".into());
6547        s.tags = vec!["health".into()];
6548        s.origin = Some(RepoOrigin {
6549            path: "configs/schedules/x.yaml".into(),
6550            repo: None,
6551            script_file: None,
6552        });
6553        s
6554    }
6555
6556    #[test]
6557    fn schedule_top_level_keys_cover_serialized_fields() {
6558        // #924 drift guard: the hand-maintained TOP_LEVEL_KEYS list must
6559        // match exactly what a fully-populated Schedule serialises — so a
6560        // future field added to Schedule or FanoutPlan can't slip past
6561        // the flatten-aware strict guard by being forgotten here.
6562        let s = fully_populated_schedule();
6563        let value = serde_json::to_value(&s).expect("serialize schedule");
6564        let serialized: std::collections::BTreeSet<String> = value
6565            .as_object()
6566            .expect("schedule serialises to an object")
6567            .keys()
6568            .cloned()
6569            .collect();
6570        let listed: std::collections::BTreeSet<String> = Schedule::TOP_LEVEL_KEYS
6571            .iter()
6572            .map(|s| s.to_string())
6573            .collect();
6574        assert_eq!(
6575            serialized, listed,
6576            "TOP_LEVEL_KEYS is out of sync with Schedule's serialized fields \
6577             (flatten-aware strict guard would miss a real field or reject a valid one)"
6578        );
6579    }
6580
6581    #[test]
6582    fn strict_rejects_flatten_hidden_top_level_typo() {
6583        // #924: a top-level typo on a flattening type (jiter / enabledd)
6584        // is buffered into the flatten target by serde and hidden from
6585        // serde_ignored — the top-level guard must catch it. Verified on
6586        // both the YAML and JSON strict boundaries.
6587        let yaml = "\
6588id: s1
6589job_id: j1
6590when:
6591  per_pc: once
6592target:
6593  all: true
6594jiter: 5m
6595";
6596        let err = crate::strict::from_yaml_str::<Schedule>(yaml).unwrap_err();
6597        assert!(err.contains("jiter"), "got: {err}");
6598
6599        let json = serde_json::json!({
6600            "id": "s1",
6601            "job_id": "j1",
6602            "when": { "per_pc": "once" },
6603            "target": { "all": true },
6604            "enabledd": false,
6605        });
6606        let err = crate::strict::from_json_slice::<Schedule>(&serde_json::to_vec(&json).unwrap())
6607            .unwrap_err();
6608        assert!(err.contains("enabledd"), "got: {err}");
6609    }
6610
6611    #[test]
6612    fn strict_accepts_all_valid_schedule_top_level_keys() {
6613        // The guard must not reject any legitimate key — round-trip a
6614        // fully-populated schedule through the strict YAML boundary.
6615        let s = fully_populated_schedule();
6616        let yaml = serde_yaml::to_string(&s).expect("serialize");
6617        crate::strict::from_yaml_str::<Schedule>(&yaml)
6618            .expect("every serialized key must be accepted by the strict guard");
6619    }
6620
6621    #[test]
6622    fn strict_rejects_non_string_top_level_yaml_key() {
6623        // #924 (gemini #945): a YAML key isn't always a string — an
6624        // unquoted `true:` parses as a boolean, `123:` as a number. A
6625        // `filter_map` on `as_str()` would drop these and let them slip
6626        // past the flatten guard; `yaml_key_label` renders them so they
6627        // are still rejected. (serde_yaml is YAML 1.2, so `on:` stays a
6628        // *string* "on" — also rejected, just via the string path.)
6629        let base = "\
6630id: s1
6631job_id: j1
6632when:
6633  per_pc: once
6634target:
6635  all: true
6636";
6637        for (extra, needle) in [
6638            ("true: x\n", "true"),
6639            ("123: x\n", "123"),
6640            ("on: y\n", "on"),
6641        ] {
6642            let yaml = format!("{base}{extra}");
6643            let err = crate::strict::from_yaml_str::<Schedule>(&yaml).unwrap_err();
6644            assert!(err.contains(needle), "for '{extra}', got: {err}");
6645        }
6646    }
6647
6648    #[test]
6649    fn validate_accepts_waves_instead_of_target_on_backend() {
6650        // #917 (1): the exec boundary accepts rollout-only plans
6651        // (target then just labels the audit row) — so does validate.
6652        let mut s = schedule_with(
6653            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6654            RunsOn::Backend,
6655        );
6656        s.plan.target = Target::default();
6657        s.plan.rollout = Some(Rollout {
6658            strategy: RolloutStrategy::Wave,
6659            waves: vec![Wave {
6660                group: "canary".into(),
6661                delay: "0s".into(),
6662            }],
6663        });
6664        s.validate().expect("rollout-only plan should validate");
6665    }
6666
6667    #[test]
6668    fn validate_rejects_rollout_on_agent() {
6669        // #917 (1): rollout waves are backend-published; a runs_on:
6670        // agent schedule never reads them, so the combination is a
6671        // silent no-op — reject like max_concurrent-on-agent.
6672        let mut s = schedule_with(
6673            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6674            RunsOn::Agent,
6675        );
6676        s.plan.rollout = Some(Rollout {
6677            strategy: RolloutStrategy::Wave,
6678            waves: vec![Wave {
6679                group: "canary".into(),
6680                delay: "0s".into(),
6681            }],
6682        });
6683        let err = s.validate().unwrap_err();
6684        assert!(err.contains("rollout"), "got: {err}");
6685    }
6686
6687    #[test]
6688    fn validate_rejects_bad_waves() {
6689        // #917 (2): empty waves, blank group, unparseable delay — all
6690        // previously accepted and failed (or no-opped) at every fire.
6691        let base = || {
6692            schedule_with(
6693                When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6694                RunsOn::Backend,
6695            )
6696        };
6697
6698        let mut s = base();
6699        s.plan.rollout = Some(Rollout {
6700            strategy: RolloutStrategy::Wave,
6701            waves: vec![],
6702        });
6703        let err = s.validate().unwrap_err();
6704        assert!(err.contains("at least one wave"), "got: {err}");
6705
6706        let mut s = base();
6707        s.plan.rollout = Some(Rollout {
6708            strategy: RolloutStrategy::Wave,
6709            waves: vec![Wave {
6710                group: "  ".into(),
6711                delay: "0s".into(),
6712            }],
6713        });
6714        let err = s.validate().unwrap_err();
6715        assert!(err.contains("waves[0].group"), "got: {err}");
6716
6717        let mut s = base();
6718        s.plan.rollout = Some(Rollout {
6719            strategy: RolloutStrategy::Wave,
6720            waves: vec![
6721                Wave {
6722                    group: "canary".into(),
6723                    delay: "0s".into(),
6724                },
6725                Wave {
6726                    group: "wave1".into(),
6727                    delay: "5 minuts".into(),
6728                },
6729            ],
6730        });
6731        let err = s.validate().unwrap_err();
6732        assert!(err.contains("waves[1].delay"), "got: {err}");
6733    }
6734
6735    #[test]
6736    fn validate_rejects_wave_delay_at_or_past_starting_deadline() {
6737        // #917 (3): the deadline is stamped once at tick time, so a
6738        // wave sleeping >= starting_deadline publishes already-expired
6739        // Commands — dead on arrival, every fire.
6740        let mut s = schedule_with(
6741            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6742            RunsOn::Backend,
6743        );
6744        s.starting_deadline = Some("30m".into());
6745        s.plan.rollout = Some(Rollout {
6746            strategy: RolloutStrategy::Wave,
6747            waves: vec![
6748                Wave {
6749                    group: "canary".into(),
6750                    delay: "0s".into(),
6751                },
6752                Wave {
6753                    group: "wave1".into(),
6754                    delay: "30m".into(),
6755                },
6756            ],
6757        });
6758        let err = s.validate().unwrap_err();
6759        assert!(
6760            err.contains("waves[1].delay") && err.contains("starting_deadline"),
6761            "got: {err}"
6762        );
6763
6764        // Strictly shorter is fine.
6765        s.plan.rollout.as_mut().unwrap().waves[1].delay = "29m".into();
6766        s.validate().expect("delay < deadline should validate");
6767    }
6768
6769    #[test]
6770    fn validate_rejects_operator_set_deadline_at() {
6771        // #917 (4): machine-stamped field — the scheduler overwrites it
6772        // on every fire, so a hand-set value is silently discarded.
6773        let mut s = schedule_with(
6774            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6775            RunsOn::Backend,
6776        );
6777        s.plan.deadline_at = Some(chrono::Utc::now());
6778        let err = s.validate().unwrap_err();
6779        assert!(
6780            err.contains("deadline_at") && err.contains("starting_deadline"),
6781            "got: {err}"
6782        );
6783    }
6784
6785    #[test]
6786    fn validate_accepts_calendar_shapes() {
6787        for when in [
6788            calendar("09:00", &["mon-fri"]),   // weekday morning
6789            calendar("00:00", &["sun"]),       // weekly
6790            calendar("18:30", &[]),            // daily
6791            calendar("2026-06-10 09:00", &[]), // one-shot
6792            calendar("2026/12/25 00:00", &[]), // one-shot, slash form
6793        ] {
6794            schedule_with(when.clone(), RunsOn::Backend)
6795                .validate()
6796                .unwrap_or_else(|e| panic!("{when} should validate: {e}"));
6797        }
6798    }
6799
6800    #[test]
6801    fn validate_rejects_bad_at() {
6802        for bad in ["25:00", "09:60", "9", "noon", "2026-13-01 09:00"] {
6803            let err = schedule_with(calendar(bad, &[]), RunsOn::Backend)
6804                .validate()
6805                .unwrap_err();
6806            assert!(err.contains("when.at"), "for '{bad}', got: {err}");
6807        }
6808    }
6809
6810    #[test]
6811    fn validate_rejects_datetime_at_with_days() {
6812        // A dated `at` is a one-shot — pairing it with days is a
6813        // contradiction (the date already pins the day).
6814        let err = schedule_with(calendar("2026-06-10 09:00", &["mon"]), RunsOn::Backend)
6815            .validate()
6816            .unwrap_err();
6817        assert!(
6818            err.contains("one-shot") && err.contains("days"),
6819            "got: {err}"
6820        );
6821    }
6822
6823    #[test]
6824    fn validate_rejects_bad_day_name() {
6825        // A garbage DOW token is caught by the days pre-flight and
6826        // reported against `when.days`, not the confusing
6827        // "when.at lowered to invalid cron" (claude #432 review).
6828        let err = schedule_with(calendar("09:00", &["funday"]), RunsOn::Backend)
6829            .validate()
6830            .unwrap_err();
6831        assert!(err.contains("when.days"), "got: {err}");
6832        assert!(err.contains("funday"), "names the bad token: {err}");
6833        // a degenerate range like `mon-` reports the whole token, not
6834        // a cryptic empty part (claude #432 follow-up)
6835        let err = schedule_with(calendar("09:00", &["mon-"]), RunsOn::Backend)
6836            .validate()
6837            .unwrap_err();
6838        assert!(err.contains("'mon-'"), "names the whole token: {err}");
6839        // valid names / ranges / numeric / * all pass
6840        for ok in [
6841            calendar("09:00", &["mon-fri"]),
6842            calendar("09:00", &["mon", "wed", "sun"]),
6843            calendar("09:00", &["1-5"]),
6844        ] {
6845            schedule_with(ok.clone(), RunsOn::Backend)
6846                .validate()
6847                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6848        }
6849    }
6850
6851    #[test]
6852    fn validate_accepts_nth_weekday() {
6853        // #418: nth-weekday (Patch Tuesday). validate() also lowers to
6854        // a cron and parses it with croner, so passing here proves the
6855        // whole chain — token → DOW field → engine-acceptable cron.
6856        for ok in [
6857            calendar("09:00", &["tue#2"]),          // 2nd Tuesday
6858            calendar("09:00", &["fri#1"]),          // 1st Friday
6859            calendar("03:00", &["sun#5"]),          // 5th Sunday
6860            calendar("09:00", &["tue#2", "thu#2"]), // a list of nths
6861            calendar("09:00", &["2#2"]),            // numeric DOW + ordinal
6862            // Case-insensitive both sides: validate lowercases, croner
6863            // upper-cases the whole pattern before aliasing (claude #547).
6864            calendar("09:00", &["TUE#2"]),
6865        ] {
6866            schedule_with(ok.clone(), RunsOn::Backend)
6867                .validate()
6868                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6869        }
6870    }
6871
6872    #[test]
6873    fn validate_rejects_bad_nth_weekday() {
6874        // ordinal out of 1..5, a range with #, and a bad day before #.
6875        for bad in ["tue#0", "tue#6", "tue#x", "mon-fri#2", "funday#2"] {
6876            let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
6877                .validate()
6878                .unwrap_err();
6879            assert!(err.contains("when.days"), "for '{bad}', got: {err}");
6880        }
6881    }
6882
6883    #[test]
6884    fn validate_accepts_last_weekday() {
6885        // #418: last-weekday (`friL` = last Friday). Like the nth case,
6886        // validate() lowers to a cron and round-trips it through croner,
6887        // so passing proves token → DOW field → engine-acceptable cron
6888        // with the verified last-<dow>-of-month semantics.
6889        for ok in [
6890            calendar("09:00", &["friL"]),         // last Friday
6891            calendar("03:00", &["sunL"]),         // last Sunday
6892            calendar("22:00", &["5L"]),           // numeric DOW + last
6893            calendar("00:00", &["0L"]),           // numeric Sunday (0…
6894            calendar("00:00", &["7L"]),           // …and its 7 alias)
6895            calendar("09:00", &["monL", "friL"]), // a list of last-weekdays
6896            // Case-insensitive both the weekday and the `L` suffix:
6897            // validate lowercases the day, croner upper-cases the whole
6898            // pattern before aliasing (claude #547).
6899            calendar("09:00", &["FRIL"]),
6900            calendar("09:00", &["fril"]),
6901        ] {
6902            schedule_with(ok.clone(), RunsOn::Backend)
6903                .validate()
6904                .unwrap_or_else(|e| panic!("{ok} should validate: {e}"));
6905        }
6906    }
6907
6908    #[test]
6909    fn validate_rejects_bad_last_weekday() {
6910        // bare `L` (no weekday — a footgun croner reads as Saturday), a
6911        // range with L, a bad day before L, and an internal space that
6912        // would otherwise leak a malformed cron downstream (gemini #560).
6913        for bad in ["L", "l", "mon-friL", "fundayL", "8L", "*L", "fri L"] {
6914            let err = schedule_with(calendar("09:00", &[bad]), RunsOn::Backend)
6915                .validate()
6916                .unwrap_err();
6917            assert!(err.contains("when.days"), "for '{bad}', got: {err}");
6918        }
6919    }
6920
6921    #[test]
6922    fn calendar_oneshot_instant_detects_past() {
6923        use chrono::TimeZone;
6924        // a dated `at` resolves to an absolute instant…
6925        let c = CalendarSpec {
6926            at: "2024-01-01 09:00".into(),
6927            days: vec![],
6928        };
6929        let t = c
6930            .oneshot_instant(ScheduleTz::Utc)
6931            .expect("one-shot instant");
6932        assert_eq!(
6933            t,
6934            chrono::Utc.with_ymd_and_hms(2024, 1, 1, 9, 0, 0).unwrap()
6935        );
6936        assert!(t < chrono::Utc::now(), "2024 is in the past");
6937        // …while a repeating (time-only) calendar has no instant
6938        let rep = CalendarSpec {
6939            at: "09:00".into(),
6940            days: vec!["mon-fri".into()],
6941        };
6942        assert!(rep.oneshot_instant(ScheduleTz::Utc).is_none());
6943    }
6944
6945    fn schedule_with_active(from: Option<&str>, until: Option<&str>) -> Schedule {
6946        let mut s = schedule_with(
6947            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
6948            RunsOn::Backend,
6949        );
6950        s.active = Active {
6951            from: from.map(str::to_owned),
6952            until: until.map(str::to_owned),
6953        };
6954        s
6955    }
6956
6957    #[test]
6958    fn validate_accepts_active_window() {
6959        schedule_with_active(Some("2026-07-01"), Some("2026-08-01T12:00:00+09:00"))
6960            .validate()
6961            .expect("date + rfc3339 bounds should validate");
6962    }
6963
6964    #[test]
6965    fn validate_rejects_unparseable_active_bound() {
6966        let err = schedule_with_active(Some("July 1st"), None)
6967            .validate()
6968            .unwrap_err();
6969        assert!(err.contains("active"), "got: {err}");
6970    }
6971
6972    #[test]
6973    fn validate_rejects_from_not_before_until() {
6974        let err = schedule_with_active(Some("2026-08-01"), Some("2026-07-01"))
6975            .validate()
6976            .unwrap_err();
6977        assert!(err.contains("strictly before"), "got: {err}");
6978
6979        let err = schedule_with_active(Some("2026-07-01"), Some("2026-07-01"))
6980            .validate()
6981            .unwrap_err();
6982        assert!(err.contains("strictly before"), "got: {err}");
6983    }
6984
6985    // ---- Active window semantics ----
6986
6987    #[test]
6988    fn active_window_is_half_open() {
6989        use chrono::TimeZone;
6990        let active = Active {
6991            from: Some("2026-07-01".into()),
6992            until: Some("2026-08-01".into()),
6993        };
6994        // UTC tz so the date bounds are UTC midnight.
6995        let at = |y, m, d, h| chrono::Utc.with_ymd_and_hms(y, m, d, h, 0, 0).unwrap();
6996        let c = |t| active.contains(t, ScheduleTz::Utc);
6997        assert!(!c(at(2026, 6, 30, 23)), "before from");
6998        assert!(c(at(2026, 7, 1, 0)), "at from (inclusive)");
6999        assert!(c(at(2026, 7, 15, 12)), "inside");
7000        assert!(!c(at(2026, 8, 1, 0)), "at until (exclusive)");
7001        assert!(!c(at(2026, 8, 2, 0)), "after until");
7002    }
7003
7004    #[test]
7005    fn active_empty_window_is_always_active() {
7006        assert!(Active::default().contains(chrono::Utc::now(), ScheduleTz::Local));
7007    }
7008
7009    #[test]
7010    fn active_rfc3339_bound_honours_offset_regardless_of_tz() {
7011        use chrono::TimeZone;
7012        let active = Active {
7013            from: Some("2026-07-01T09:00:00+09:00".into()),
7014            until: None,
7015        };
7016        // RFC3339 carries its own offset → tz arg is ignored.
7017        // 09:00 JST = 00:00 UTC.
7018        for tz in [ScheduleTz::Utc, ScheduleTz::Local] {
7019            assert!(
7020                !active.contains(
7021                    chrono::Utc
7022                        .with_ymd_and_hms(2026, 6, 30, 23, 59, 0)
7023                        .unwrap(),
7024                    tz
7025                )
7026            );
7027            assert!(active.contains(
7028                chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap(),
7029                tz
7030            ));
7031        }
7032    }
7033
7034    #[test]
7035    fn active_date_bound_respects_tz() {
7036        // A bare `YYYY-MM-DD` bound is midnight *in the schedule's
7037        // tz* (#418 Phase 2). The UTC interpretation is exact and
7038        // host-independent; assert that precisely.
7039        use chrono::TimeZone;
7040        let utc = Active::parse_bound("2026-07-01", ScheduleTz::Utc).expect("utc");
7041        assert_eq!(
7042            utc,
7043            chrono::Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap()
7044        );
7045
7046        // The local interpretation must equal what chrono::Local
7047        // computes for the same wall-clock midnight — proves the tz
7048        // path is wired to the host zone (the magnitude vs UTC is
7049        // host-dependent, so we compare against Local directly rather
7050        // than hard-coding the JST offset, keeping CI green on UTC
7051        // runners).
7052        let local = Active::parse_bound("2026-07-01", ScheduleTz::Local).expect("local");
7053        let want = chrono::Local
7054            .with_ymd_and_hms(2026, 7, 1, 0, 0, 0)
7055            .single()
7056            .expect("local midnight is unambiguous")
7057            .with_timezone(&chrono::Utc);
7058        assert_eq!(local, want, "date bound resolved in host-local tz");
7059    }
7060
7061    #[test]
7062    fn active_empty_is_skipped_when_serialising() {
7063        let s = schedule_with(
7064            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7065            RunsOn::Backend,
7066        );
7067        let json = serde_json::to_value(&s).expect("serialise");
7068        assert!(
7069            json.get("active").is_none(),
7070            "empty active must not appear on the wire: {json}"
7071        );
7072    }
7073
7074    // ---- constraints.window (#418 Phase 3) ----
7075
7076    fn with_window(win: &str) -> Schedule {
7077        let mut s = schedule_with(
7078            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
7079            RunsOn::Backend,
7080        );
7081        s.constraints.window = Some(win.into());
7082        s
7083    }
7084
7085    #[test]
7086    fn constraints_window_parses_and_round_trips() {
7087        let yaml = r#"
7088id: x
7089when:
7090  per_pc: { every: 6h }
7091job_id: y
7092target: { all: true }
7093constraints:
7094  window: "22:00-05:00"
7095"#;
7096        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7097        assert_eq!(s.constraints.window.as_deref(), Some("22:00-05:00"));
7098        let back: Schedule =
7099            serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
7100        assert_eq!(back.constraints.window.as_deref(), Some("22:00-05:00"));
7101    }
7102
7103    #[test]
7104    fn constraints_empty_is_skipped_when_serialising() {
7105        let s = schedule_with(
7106            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7107            RunsOn::Backend,
7108        );
7109        let json = serde_json::to_value(&s).expect("serialise");
7110        assert!(
7111            json.get("constraints").is_none(),
7112            "empty constraints must not appear on the wire: {json}"
7113        );
7114    }
7115
7116    #[test]
7117    fn window_no_constraint_always_allows() {
7118        let c = Constraints::default();
7119        assert!(c.allows(chrono::Utc::now(), ScheduleTz::Local));
7120    }
7121
7122    #[test]
7123    fn window_same_day_is_half_open() {
7124        use chrono::TimeZone;
7125        let s = with_window("09:00-17:00");
7126        let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
7127        let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
7128        assert!(!a(at(8, 59)), "before start");
7129        assert!(a(at(9, 0)), "at start (inclusive)");
7130        assert!(a(at(16, 59)), "inside");
7131        assert!(!a(at(17, 0)), "at end (exclusive)");
7132        assert!(!a(at(23, 0)), "after end");
7133    }
7134
7135    #[test]
7136    fn window_crossing_midnight() {
7137        use chrono::TimeZone;
7138        let s = with_window("22:00-05:00");
7139        let at = |h, m| chrono::Utc.with_ymd_and_hms(2026, 6, 9, h, m, 0).unwrap();
7140        let a = |t| s.constraints.allows(t, ScheduleTz::Utc);
7141        assert!(a(at(22, 0)), "at start tonight");
7142        assert!(a(at(23, 30)), "late tonight");
7143        assert!(a(at(3, 0)), "early tomorrow");
7144        assert!(!a(at(5, 0)), "at end (exclusive)");
7145        assert!(!a(at(12, 0)), "midday outside");
7146        assert!(!a(at(21, 59)), "just before start");
7147    }
7148
7149    #[test]
7150    fn window_respects_tz() {
7151        // The same instant is inside the window under one tz and may
7152        // be outside under another. Compare UTC vs Local via the
7153        // host's own offset (kept CI-green on UTC runners like the
7154        // active tz test does).
7155        use chrono::TimeZone;
7156        let s = with_window("09:00-17:00");
7157        let noon_utc = chrono::Utc.with_ymd_and_hms(2026, 6, 9, 12, 0, 0).unwrap();
7158        // Under UTC, 12:00 is inside 09:00-17:00.
7159        assert!(s.constraints.allows(noon_utc, ScheduleTz::Utc));
7160        // Under Local, the verdict tracks the host wall-clock time;
7161        // assert it matches a direct wall_time membership check.
7162        let local_t = noon_utc.with_timezone(&chrono::Local).time();
7163        let in_local = local_t >= chrono::NaiveTime::from_hms_opt(9, 0, 0).unwrap()
7164            && local_t < chrono::NaiveTime::from_hms_opt(17, 0, 0).unwrap();
7165        assert_eq!(s.constraints.allows(noon_utc, ScheduleTz::Local), in_local);
7166    }
7167
7168    #[test]
7169    fn validate_accepts_good_window() {
7170        for w in ["09:00-17:00", "22:00-05:00", "00:00-23:59"] {
7171            with_window(w)
7172                .validate()
7173                .unwrap_or_else(|e| panic!("'{w}' should validate: {e}"));
7174        }
7175    }
7176
7177    #[test]
7178    fn validate_rejects_bad_window() {
7179        for bad in ["9-5", "22:00", "22:00-22:00", "25:00-05:00", "09:00_17:00"] {
7180            let err = with_window(bad).validate().unwrap_err();
7181            assert!(
7182                err.contains("constraints.window"),
7183                "for '{bad}', got: {err}"
7184            );
7185        }
7186    }
7187
7188    // ---- constraints.skip_dates (#418 holiday exclusion) ----
7189
7190    fn with_skip_dates(dates: &[&str]) -> Schedule {
7191        let mut s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
7192        s.tz = ScheduleTz::Utc; // host-independent date assertions
7193        s.constraints.skip_dates = dates.iter().map(|d| (*d).to_string()).collect();
7194        s
7195    }
7196
7197    #[test]
7198    fn allows_blocks_listed_skip_date() {
7199        use chrono::TimeZone;
7200        let s = with_skip_dates(&["2026-06-10", "2026-12-25"]);
7201        // Any time on a listed date is blocked (whole day).
7202        let on = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 9, 0, 0).unwrap();
7203        assert!(!s.constraints.allows(on, ScheduleTz::Utc));
7204        let on_midnight = chrono::Utc.with_ymd_and_hms(2026, 12, 25, 0, 0, 0).unwrap();
7205        assert!(!s.constraints.allows(on_midnight, ScheduleTz::Utc));
7206        // A date not in the list fires normally.
7207        let off = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
7208        assert!(s.constraints.allows(off, ScheduleTz::Utc));
7209    }
7210
7211    #[test]
7212    fn allows_corrupt_skip_date_fails_closed() {
7213        use chrono::TimeZone;
7214        // A garbled entry (only reachable via hand-edited KV) blocks
7215        // rather than silently re-enabling fires — same posture as a
7216        // corrupt window.
7217        let s = with_skip_dates(&["not-a-date"]);
7218        let any = chrono::Utc.with_ymd_and_hms(2026, 6, 11, 9, 0, 0).unwrap();
7219        assert!(!s.constraints.allows(any, ScheduleTz::Utc));
7220    }
7221
7222    #[test]
7223    fn validate_accepts_good_skip_dates() {
7224        with_skip_dates(&["2026-01-01", "2026-12-25", "2027-05-03"])
7225            .validate()
7226            .expect("well-formed skip dates should validate");
7227    }
7228
7229    #[test]
7230    fn validate_rejects_bad_skip_date() {
7231        for bad in ["2026-13-01", "01-01-2026", "nope", "2026/01/01"] {
7232            let err = with_skip_dates(&[bad]).validate().unwrap_err();
7233            assert!(
7234                err.contains("constraints.skip_dates"),
7235                "for '{bad}', got: {err}"
7236            );
7237        }
7238    }
7239
7240    #[test]
7241    fn preview_skips_holidays() {
7242        use chrono::TimeZone;
7243        // Daily 09:00 with two of the next five days marked as holidays
7244        // — preview drops exactly those, since it gates on `allows`.
7245        let mut s = cal_utc("09:00", &[]);
7246        s.constraints.skip_dates = vec!["2026-06-11".into(), "2026-06-13".into()];
7247        let now = chrono::Utc.with_ymd_and_hms(2026, 6, 10, 0, 0, 0).unwrap();
7248        let got = s.preview_fires(now, 4);
7249        let want: Vec<_> = [
7250            (2026, 6, 10),
7251            (2026, 6, 12), // skips 06-11
7252            (2026, 6, 14), // skips 06-13
7253            (2026, 6, 15),
7254        ]
7255        .iter()
7256        .map(|(y, m, d)| chrono::Utc.with_ymd_and_hms(*y, *m, *d, 9, 0, 0).unwrap())
7257        .collect();
7258        assert_eq!(got, want);
7259    }
7260
7261    // ---- constraints.max_concurrent (#418) ----
7262
7263    fn with_max_concurrent(max: u32, runs_on: RunsOn) -> Schedule {
7264        let mut s = schedule_with(
7265            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
7266            runs_on,
7267        );
7268        s.constraints.max_concurrent = Some(max);
7269        s
7270    }
7271
7272    #[test]
7273    fn validate_accepts_backend_max_concurrent() {
7274        with_max_concurrent(5, RunsOn::Backend)
7275            .validate()
7276            .expect("backend max_concurrent should validate");
7277    }
7278
7279    #[test]
7280    fn validate_rejects_max_concurrent_on_agent() {
7281        // Decision E: a central running-instance cap needs a central
7282        // counter, which agents don't have.
7283        let err = with_max_concurrent(5, RunsOn::Agent)
7284            .validate()
7285            .unwrap_err();
7286        assert!(err.contains("constraints.max_concurrent"), "got: {err}");
7287        assert!(err.contains("runs_on: agent"), "got: {err}");
7288    }
7289
7290    #[test]
7291    fn validate_rejects_zero_max_concurrent() {
7292        let err = with_max_concurrent(0, RunsOn::Backend)
7293            .validate()
7294            .unwrap_err();
7295        assert!(err.contains("max_concurrent must be >= 1"), "got: {err}");
7296    }
7297
7298    #[test]
7299    fn max_concurrent_round_trips_and_skips_when_absent() {
7300        let s = with_max_concurrent(3, RunsOn::Backend);
7301        let json = serde_json::to_value(&s.constraints).expect("ser");
7302        assert_eq!(json.get("max_concurrent").and_then(|v| v.as_u64()), Some(3));
7303        // A schedule with no constraints omits the whole block.
7304        let bare = schedule_with(
7305            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7306            RunsOn::Backend,
7307        );
7308        assert!(bare.constraints.is_empty());
7309    }
7310
7311    #[test]
7312    fn window_fail_closed_on_corrupt_blob() {
7313        // A malformed window (only reachable via a hand-edited KV
7314        // blob — validate() rejects it at create) must BLOCK, not
7315        // silently allow fires during a change-freeze (gemini #452).
7316        let s = with_window("22:00_05:00");
7317        assert!(
7318            !s.constraints.allows(chrono::Utc::now(), ScheduleTz::Utc),
7319            "corrupt window fails closed"
7320        );
7321        // …and the scheduler can surface why it's stuck.
7322        assert!(
7323            s.bad_window().is_some(),
7324            "bad_window reports the parse error"
7325        );
7326        assert!(with_window("22:00-05:00").bad_window().is_none());
7327    }
7328
7329    #[test]
7330    fn calendar_outside_window_is_flagged() {
7331        // at 09:00 can never fall in 22:00-05:00 → never fires.
7332        let mut s = schedule_with(calendar("09:00", &["mon-fri"]), RunsOn::Backend);
7333        s.constraints.window = Some("22:00-05:00".into());
7334        assert!(s.calendar_outside_window(), "09:00 is not in 22:00-05:00");
7335
7336        // at 23:00 IS inside the overnight window → fine.
7337        let mut s = schedule_with(calendar("23:00", &[]), RunsOn::Backend);
7338        s.constraints.window = Some("22:00-05:00".into());
7339        assert!(!s.calendar_outside_window(), "23:00 is in 22:00-05:00");
7340
7341        // reconcile shapes are never flagged (they poll every minute).
7342        let mut s = schedule_with(
7343            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
7344            RunsOn::Backend,
7345        );
7346        s.constraints.window = Some("22:00-05:00".into());
7347        assert!(!s.calendar_outside_window(), "reconcile is unaffected");
7348
7349        // no window → never flagged.
7350        let s = schedule_with(calendar("09:00", &[]), RunsOn::Backend);
7351        assert!(!s.calendar_outside_window());
7352    }
7353
7354    // ---- on_failure.retry (#418 Phase 4) ----
7355
7356    fn with_retry(max: u32, backoff: &str) -> Schedule {
7357        let mut s = schedule_with(
7358            When::PerPc(PerPolicy::Every(EverySpec { every: "6h".into() })),
7359            RunsOn::Backend,
7360        );
7361        s.on_failure.retry = Some(Retry {
7362            max,
7363            backoff: backoff.into(),
7364        });
7365        s
7366    }
7367
7368    #[test]
7369    fn on_failure_parses_and_round_trips() {
7370        let yaml = r#"
7371id: x
7372when:
7373  per_pc: { every: 6h }
7374job_id: y
7375target: { all: true }
7376on_failure:
7377  retry: { max: 3, backoff: 10m }
7378"#;
7379        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7380        let r = s.on_failure.retry.as_ref().expect("retry present");
7381        assert_eq!(r.max, 3);
7382        assert_eq!(r.backoff, "10m");
7383        let back: Schedule =
7384            serde_json::from_str(&serde_json::to_string(&s).expect("ser")).expect("de");
7385        assert_eq!(back.on_failure, s.on_failure);
7386    }
7387
7388    #[test]
7389    fn on_failure_empty_is_skipped_when_serialising() {
7390        let s = schedule_with(
7391            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7392            RunsOn::Backend,
7393        );
7394        let json = serde_json::to_value(&s).expect("serialise");
7395        assert!(
7396            json.get("on_failure").is_none(),
7397            "empty on_failure must not appear on the wire: {json}"
7398        );
7399    }
7400
7401    #[test]
7402    fn validate_accepts_good_retry() {
7403        for (max, backoff) in [(1, "30s"), (3, "10m"), (10, "1h")] {
7404            with_retry(max, backoff)
7405                .validate()
7406                .unwrap_or_else(|e| panic!("retry {{max:{max}, backoff:{backoff}}}: {e}"));
7407        }
7408    }
7409
7410    #[test]
7411    fn validate_rejects_bad_backoff() {
7412        let err = with_retry(3, "soon").validate().unwrap_err();
7413        assert!(err.contains("on_failure.retry.backoff"), "got: {err}");
7414    }
7415
7416    #[test]
7417    fn validate_rejects_sub_second_backoff() {
7418        // "500ms" parses as humantime but lowers to 0s on the wire —
7419        // reject it so the operator doesn't get a silent no-wait
7420        // (coderabbit #466).
7421        for bad in ["500ms", "0s", "999ms"] {
7422            let err = with_retry(3, bad).validate().unwrap_err();
7423            assert!(
7424                err.contains("on_failure.retry.backoff must be >= 1s"),
7425                "for '{bad}', got: {err}"
7426            );
7427        }
7428    }
7429
7430    #[test]
7431    fn validate_rejects_out_of_range_max() {
7432        for bad in [0u32, 11, 1000] {
7433            let err = with_retry(bad, "10m").validate().unwrap_err();
7434            assert!(
7435                err.contains("on_failure.retry.max"),
7436                "for max={bad}, got: {err}"
7437            );
7438        }
7439    }
7440
7441    #[test]
7442    fn lowered_retry_reduces_backoff_to_seconds() {
7443        let s = with_retry(3, "10m");
7444        let spec = s.on_failure.lowered_retry().expect("a retry policy");
7445        assert_eq!(spec.max, 3);
7446        assert_eq!(spec.backoff_secs, 600);
7447    }
7448
7449    #[test]
7450    fn lowered_retry_is_none_without_policy() {
7451        let s = schedule_with(
7452            When::PerPc(PerPolicy::Once(OnceLiteral::Once)),
7453            RunsOn::Backend,
7454        );
7455        assert!(s.on_failure.lowered_retry().is_none());
7456    }
7457
7458    // ---- global change-freeze (#418 Phase 5) ----
7459
7460    #[test]
7461    fn freeze_empty_window_is_always_active() {
7462        // The big-red-button shape: no bounds = frozen until cleared.
7463        let f = Freeze::default();
7464        assert!(f.is_active(chrono::Utc::now()));
7465    }
7466
7467    #[test]
7468    fn freeze_window_is_half_open() {
7469        use chrono::TimeZone;
7470        let f = Freeze {
7471            from: Some("2026-12-20T00:00:00+00:00".into()),
7472            until: Some("2027-01-05T00:00:00+00:00".into()),
7473            reason: Some("year-end".into()),
7474            tz: ScheduleTz::Utc,
7475        };
7476        let at = |y, mo, d| chrono::Utc.with_ymd_and_hms(y, mo, d, 0, 0, 0).unwrap();
7477        assert!(!f.is_active(at(2026, 12, 19)), "before from = not frozen");
7478        assert!(f.is_active(at(2026, 12, 20)), "from is inclusive");
7479        assert!(f.is_active(at(2026, 12, 31)), "inside window");
7480        assert!(!f.is_active(at(2027, 1, 5)), "until is exclusive");
7481        assert!(!f.is_active(at(2027, 1, 6)), "after until = not frozen");
7482    }
7483
7484    #[test]
7485    fn freeze_fails_closed_on_corrupt_bound() {
7486        // A freeze is a safety switch: an unparseable bound (only
7487        // reachable via a hand-edited KV blob) must read as FROZEN, not
7488        // "fire normally" (coderabbit #472) — the opposite of `active`,
7489        // which fail-opens.
7490        let f = Freeze {
7491            from: Some("not-a-date".into()),
7492            until: None,
7493            reason: None,
7494            tz: ScheduleTz::Utc,
7495        };
7496        assert!(f.is_active(chrono::Utc::now()), "corrupt bound → frozen");
7497    }
7498
7499    #[test]
7500    fn freeze_validate_accepts_good_bounds() {
7501        Freeze {
7502            from: Some("2026-12-20".into()),
7503            until: Some("2027-01-05T12:00:00+09:00".into()),
7504            reason: None,
7505            tz: ScheduleTz::Local,
7506        }
7507        .validate()
7508        .expect("date + rfc3339 bounds should validate");
7509        // Empty (indefinite) freeze is valid.
7510        Freeze::default().validate().expect("empty freeze is valid");
7511    }
7512
7513    #[test]
7514    fn freeze_validate_rejects_bad_bound_and_inverted_window() {
7515        let err = Freeze {
7516            from: Some("never".into()),
7517            ..Default::default()
7518        }
7519        .validate()
7520        .unwrap_err();
7521        assert!(err.contains("freeze:"), "got: {err}");
7522
7523        let inverted = Freeze {
7524            from: Some("2027-01-05".into()),
7525            until: Some("2026-12-20".into()),
7526            ..Default::default()
7527        }
7528        .validate()
7529        .unwrap_err();
7530        assert!(inverted.contains("freeze.from"), "got: {inverted}");
7531    }
7532
7533    #[test]
7534    fn freeze_round_trips_and_skips_empty_fields() {
7535        let f = Freeze {
7536            from: None,
7537            until: Some("2027-01-05".into()),
7538            reason: Some("INC-1234".into()),
7539            tz: ScheduleTz::Utc,
7540        };
7541        let json = serde_json::to_value(&f).expect("serialise");
7542        assert!(json.get("from").is_none(), "empty from omitted: {json}");
7543        let back: Freeze = serde_json::from_value(json).expect("round-trip");
7544        assert_eq!(back, f);
7545    }
7546
7547    #[test]
7548    fn shipped_schedule_configs_parse_and_validate() {
7549        // Every YAML under configs/schedules/ must parse with the
7550        // current Schedule serde AND pass validate() — keeps the
7551        // shipped examples from drifting out of sync with the model
7552        // (#418 removed back-compat, so drift = broken at create).
7553        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../configs/schedules");
7554        let mut seen = 0;
7555        for entry in std::fs::read_dir(&dir).expect("read configs/schedules") {
7556            let path = entry.expect("dir entry").path();
7557            if path.extension().and_then(|e| e.to_str()) != Some("yaml") {
7558                continue;
7559            }
7560            let body = std::fs::read_to_string(&path).expect("read yaml");
7561            let s: Schedule = serde_yaml::from_str(&body)
7562                .unwrap_or_else(|e| panic!("{} failed to parse: {e}", path.display()));
7563            s.validate()
7564                .unwrap_or_else(|e| panic!("{} failed validate(): {e}", path.display()));
7565            seen += 1;
7566        }
7567        assert!(seen > 0, "no schedule YAMLs found in {}", dir.display());
7568    }
7569
7570    // ---- pre-existing enum wire formats (unchanged by #418) ----
7571
7572    #[test]
7573    fn exec_mode_serialises_snake_case() {
7574        for (mode, expected) in [
7575            (ExecMode::EveryTick, "every_tick"),
7576            (ExecMode::OncePerPc, "once_per_pc"),
7577            (ExecMode::OncePerTarget, "once_per_target"),
7578        ] {
7579            let s = serde_json::to_value(mode).expect("serialise");
7580            assert_eq!(s, serde_json::Value::String(expected.into()));
7581            let back: ExecMode = serde_json::from_value(serde_json::Value::String(expected.into()))
7582                .expect("deserialise");
7583            assert_eq!(back, mode, "round-trip for {expected}");
7584        }
7585    }
7586
7587    #[test]
7588    fn schedule_runs_on_defaults_to_backend() {
7589        let yaml = r#"
7590id: x
7591when:
7592  per_pc: once
7593job_id: y
7594target: { all: true }
7595"#;
7596        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7597        assert_eq!(s.runs_on, RunsOn::Backend);
7598    }
7599
7600    #[test]
7601    fn schedule_runs_on_agent_parses() {
7602        let yaml = r#"
7603id: offline-inv
7604when:
7605  per_pc: { every: 1h }
7606job_id: inventory-hw
7607target: { all: true }
7608runs_on: agent
7609"#;
7610        let s: Schedule = serde_yaml::from_str(yaml).expect("parse");
7611        assert_eq!(s.runs_on, RunsOn::Agent);
7612        assert_eq!(s.lowered().mode, ExecMode::OncePerPc);
7613    }
7614
7615    #[test]
7616    fn runs_on_serialises_snake_case() {
7617        for (mode, expected) in [(RunsOn::Backend, "backend"), (RunsOn::Agent, "agent")] {
7618            let s = serde_json::to_value(mode).expect("serialise");
7619            assert_eq!(s, serde_json::Value::String(expected.into()));
7620            let back: RunsOn = serde_json::from_value(serde_json::Value::String(expected.into()))
7621                .expect("deserialise");
7622            assert_eq!(back, mode);
7623        }
7624    }
7625
7626    #[test]
7627    fn execute_shell_into_wire_shell() {
7628        assert_eq!(Shell::from(ExecuteShell::Powershell), Shell::Powershell);
7629        assert_eq!(Shell::from(ExecuteShell::Cmd), Shell::Cmd);
7630        assert_eq!(Shell::from(ExecuteShell::Sh), Shell::Sh);
7631        assert_eq!(Shell::from(ExecuteShell::Pwsh), Shell::Pwsh);
7632    }
7633
7634    #[test]
7635    fn execute_shell_parses_sh_and_pwsh() {
7636        // The manifest `execute.shell` accepts the two new lowercase
7637        // tokens end-to-end (serde), so an operator can author a Linux
7638        // job.
7639        for (yaml_shell, want) in [("sh", ExecuteShell::Sh), ("pwsh", ExecuteShell::Pwsh)] {
7640            let yaml = format!(
7641                "id: x\nversion: 1.0.0\nexecute:\n  shell: {yaml_shell}\n  script: \"echo\"\n  timeout: 1s\n"
7642            );
7643            let m: Manifest = serde_yaml::from_str(&yaml).expect("parse");
7644            assert_eq!(m.execute.shell, want, "shell {yaml_shell}");
7645        }
7646    }
7647
7648    #[test]
7649    fn manifest_staleness_defaults_to_cached() {
7650        let yaml = r#"
7651id: x
7652version: 1.0.0
7653execute:
7654  shell: powershell
7655  script: "echo"
7656  timeout: 1s
7657"#;
7658        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7659        assert_eq!(m.staleness, Staleness::Cached);
7660    }
7661
7662    #[test]
7663    fn manifest_strict_staleness_parses() {
7664        let yaml = r#"
7665id: urgent-patch
7666version: 2.5.1
7667execute:
7668  shell: powershell
7669  script: Install-Hotfix
7670  timeout: 5m
7671staleness:
7672  mode: strict
7673  max_cache_age: 0s
7674"#;
7675        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7676        match m.staleness {
7677            Staleness::Strict { max_cache_age } => assert_eq!(max_cache_age, "0s"),
7678            other => panic!("expected strict, got {other:?}"),
7679        }
7680    }
7681
7682    #[test]
7683    fn manifest_unchecked_staleness_parses() {
7684        let yaml = r#"
7685id: legacy
7686version: 0.1.0
7687execute:
7688  shell: cmd
7689  script: "echo"
7690  timeout: 1s
7691staleness:
7692  mode: unchecked
7693"#;
7694        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7695        assert_eq!(m.staleness, Staleness::Unchecked);
7696    }
7697
7698    #[test]
7699    fn missing_required_field_errors() {
7700        // `id` missing.
7701        let yaml = r#"
7702version: 1.0.0
7703target: { all: true }
7704execute:
7705  shell: powershell
7706  script: "echo"
7707  timeout: 1s
7708"#;
7709        let r: Result<Manifest, _> = serde_yaml::from_str(yaml);
7710        assert!(r.is_err(), "expected error, got {:?}", r);
7711    }
7712
7713    #[test]
7714    fn display_field_table_kind_round_trips_with_nested_columns() {
7715        // #39: `type: table` + `columns:` on a DisplayField gets
7716        // round-tripped through serde so the SPA receives the
7717        // nested schema verbatim. Nested columns themselves are
7718        // DisplayFields so they can carry `type: bytes` /
7719        // `type: number` for cell formatting.
7720        let yaml = r#"
7721id: inv-hw
7722version: 1.0.0
7723execute:
7724  shell: powershell
7725  script: "echo"
7726  timeout: 60s
7727inventory:
7728  display:
7729    - field: hostname
7730      label: Hostname
7731    - field: disks
7732      label: Disks
7733      type: table
7734      columns:
7735        - field: device_id
7736          label: Drive
7737        - field: size_bytes
7738          label: Size
7739          type: bytes
7740        - field: free_bytes
7741          label: Free
7742          type: bytes
7743        - field: file_system
7744          label: FS
7745"#;
7746        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7747        let inv = m.inventory.as_ref().expect("inventory hint");
7748        let disks = inv
7749            .display
7750            .iter()
7751            .find(|d| d.field == "disks")
7752            .expect("disks display row");
7753        assert_eq!(disks.kind.as_deref(), Some("table"));
7754        let cols = disks.columns.as_ref().expect("table needs columns");
7755        assert_eq!(cols.len(), 4);
7756        assert_eq!(cols[1].field, "size_bytes");
7757        assert_eq!(cols[1].kind.as_deref(), Some("bytes"));
7758    }
7759
7760    #[test]
7761    fn display_field_scalar_kind_keeps_columns_none() {
7762        // Defensive: when type is a scalar (`bytes` / `number` /
7763        // `timestamp`) the `columns` field stays None — the SPA
7764        // uses its presence as the "render nested table" signal,
7765        // so it must not leak in via serde defaults.
7766        let yaml = r#"
7767id: x
7768version: 1.0.0
7769execute:
7770  shell: powershell
7771  script: "echo"
7772  timeout: 5s
7773inventory:
7774  display:
7775    - { field: ram_bytes, label: RAM, type: bytes }
7776"#;
7777        let m: Manifest = serde_yaml::from_str(yaml).expect("parse");
7778        let inv = m.inventory.as_ref().unwrap();
7779        assert!(inv.display[0].columns.is_none());
7780    }
7781
7782    // ---- GroupDef (#1032 dynamic groups) ----
7783
7784    fn group_def(yaml: &str) -> Result<GroupDef, String> {
7785        let g: GroupDef = crate::strict::from_yaml_str(yaml).map_err(|e| e.to_string())?;
7786        g.validate().map(|()| g)
7787    }
7788
7789    #[test]
7790    fn group_def_static_members_valid() {
7791        let g = group_def("id: pilot\nmembers: [PC-A, PC-B]\n").expect("valid static group");
7792        assert_eq!(g.members, vec!["PC-A", "PC-B"]);
7793        assert!(g.dynamic_query().is_none());
7794    }
7795
7796    #[test]
7797    fn group_def_dynamic_query_valid() {
7798        let g = group_def(
7799            "id: clients\nquery: \"SELECT pc_id FROM agents WHERE hostname LIKE 'X%'\"\nrefresh: 30m\n",
7800        )
7801        .expect("valid dynamic group");
7802        assert_eq!(
7803            g.dynamic_query(),
7804            Some("SELECT pc_id FROM agents WHERE hostname LIKE 'X%'")
7805        );
7806        assert_eq!(g.refresh_interval(), std::time::Duration::from_secs(1800));
7807    }
7808
7809    #[test]
7810    fn group_def_refresh_defaults_when_absent() {
7811        let g = group_def("id: c\nquery: \"SELECT pc_id FROM agents\"\n").unwrap();
7812        assert_eq!(g.refresh_interval(), DEFAULT_GROUP_REFRESH);
7813    }
7814
7815    #[test]
7816    fn group_def_rejects_neither_members_nor_query() {
7817        let err = group_def("id: empty\n").unwrap_err();
7818        assert!(err.contains("either"), "err: {err}");
7819    }
7820
7821    #[test]
7822    fn group_def_rejects_both_members_and_query() {
7823        let err = group_def("id: both\nmembers: [PC-A]\nquery: \"SELECT pc_id FROM agents\"\n")
7824            .unwrap_err();
7825        assert!(err.contains("mutually exclusive"), "err: {err}");
7826    }
7827
7828    #[test]
7829    fn group_def_blank_query_is_unset_not_both() {
7830        // An empty-string query reads as unset, so a members group with a
7831        // commented-out (emptied) query is still valid, not a "both set" error.
7832        let g =
7833            group_def("id: pilot\nmembers: [PC-A]\nquery: \"\"\n").expect("blank query = unset");
7834        assert!(g.dynamic_query().is_none());
7835    }
7836
7837    #[test]
7838    fn group_def_rejects_bad_id_charset() {
7839        let err = group_def("id: bad/id\nmembers: [PC-A]\n").unwrap_err();
7840        assert!(err.contains("group.id"), "err: {err}");
7841    }
7842
7843    #[test]
7844    fn group_def_rejects_untrimmed_id() {
7845        // A padded id validated-as-trimmed but stored-raw would be a KV key
7846        // nothing matches — reject it outright (the id is used verbatim).
7847        let err = group_def("id: \" clients \"\nmembers: [PC-A]\n").unwrap_err();
7848        assert!(err.contains("group.id"), "err: {err}");
7849    }
7850
7851    #[test]
7852    fn group_def_rejects_bad_refresh() {
7853        let err =
7854            group_def("id: c\nquery: \"SELECT pc_id FROM agents\"\nrefresh: soon\n").unwrap_err();
7855        assert!(err.contains("refresh"), "err: {err}");
7856    }
7857
7858    #[test]
7859    fn group_def_rejects_unknown_key() {
7860        // Strict parse (#492) — a typo'd key is an operator error, not silently
7861        // dropped.
7862        let err = group_def("id: c\nmembers: [PC-A]\nrlue: x\n").unwrap_err();
7863        assert!(err.to_lowercase().contains("unknown"), "err: {err}");
7864    }
7865
7866    // ---- checked-in JSON Schema freshness (docs/schemas/) ----
7867
7868    /// The JSON Schemas under `docs/schemas/` must match what
7869    /// `schema_for!` produces today — a Cargo.lock-style freshness guard
7870    /// so a `Schedule` / `Manifest` field change can't silently drift
7871    /// the operator-facing schema. The SPA editor, the backend
7872    /// `/api/schemas/*` endpoints, and these files all read the same
7873    /// derived shape; this test fails CI if the checked-in copy lags.
7874    /// Regenerate with:
7875    ///   `UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current`
7876    #[test]
7877    fn schema_files_are_current() {
7878        assert_schema_file("schedule.schema.json", &schemars::schema_for!(Schedule));
7879        assert_schema_file("job.schema.json", &schemars::schema_for!(Manifest));
7880        assert_schema_file("view.schema.json", &schemars::schema_for!(View));
7881        assert_schema_file("group-def.schema.json", &schemars::schema_for!(GroupDef));
7882    }
7883
7884    fn assert_schema_file(name: &str, schema: &schemars::Schema) {
7885        let generated = serde_json::to_string_pretty(schema).expect("serialize schema") + "\n";
7886        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7887            .join("../../docs/schemas")
7888            .join(name);
7889        if std::env::var_os("UPDATE_SCHEMAS").is_some() {
7890            std::fs::create_dir_all(path.parent().unwrap()).expect("mkdir docs/schemas");
7891            std::fs::write(&path, &generated).unwrap_or_else(|e| panic!("write {path:?}: {e}"));
7892            return;
7893        }
7894        // Normalize CRLF→LF before comparing: `.gitattributes` already
7895        // pins these files to `eol=lf`, but a stray CRLF working-tree
7896        // copy (autocrlf, a tool rewrite) shouldn't turn a *content*-
7897        // freshness check into a confusing line-ending failure — that's
7898        // .gitattributes' job, not this test's (gemini #588).
7899        let on_disk = std::fs::read_to_string(&path)
7900            .unwrap_or_else(|e| {
7901                panic!(
7902                    "read {path:?}: {e}\n\
7903                     generate it with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
7904                )
7905            })
7906            .replace("\r\n", "\n");
7907        assert_eq!(
7908            on_disk, generated,
7909            "{name} is stale — a Schedule/Manifest schema change isn't reflected in docs/schemas/. \
7910             Refresh with: UPDATE_SCHEMAS=1 cargo test -p kanade-shared schema_files_are_current"
7911        );
7912    }
7913}
7914
7915/// Periodic schedule (spec §2.4.3). v0.18.0 carries the fanout plan
7916/// (target + optional rollout + optional jitter) inline; the
7917/// referenced job (`job_id` → [`BUCKET_JOBS`]) supplies only the
7918/// script body. Two schedules of the same job can target different
7919/// groups on different cadences without copying the manifest.
7920///
7921/// #418 Phase 1: the cadence is the single [`When`] field. The old
7922/// `cron` × `mode` × `cooldown` × `auto_disable_when_done` quartet
7923/// is gone (no back-compat — pre-Phase-1 KV blobs fail to parse and
7924/// are warn-skipped; re-`schedule create` to upgrade them). The
7925/// engine underneath is unchanged: [`Schedule::lowered`] maps `when`
7926/// onto the same (cron, ExecMode, cooldown) trio the scheduler and
7927/// `decide_fire` always ran on.
7928#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
7929pub struct Schedule {
7930    pub id: String,
7931    /// When to fire — a reconcile cadence (`per_pc` / `per_target`)
7932    /// or a calendar time trigger (`at` / `days`). See [`When`].
7933    ///
7934    /// `singleton_map`: serde_yaml 0.9 renders externally-tagged
7935    /// enums as `!per_pc` YAML tags by default; this keeps the
7936    /// operator-facing map shape (`when: { per_pc: once }`). JSON
7937    /// output is identical either way, and the schemars schema
7938    /// (external tagging = oneOf of single-key objects) already
7939    /// matches the singleton-map wire shape.
7940    #[serde(with = "serde_yaml::with::singleton_map")]
7941    #[schemars(with = "When")]
7942    pub when: When,
7943    /// Key into [`crate::kv::BUCKET_JOBS`]. Must equal a registered
7944    /// Manifest's `id`.
7945    pub job_id: String,
7946    /// Who + how-to-phase + when-to-stagger. The Manifest doesn't
7947    /// carry these any more — same job + different fanout = different
7948    /// schedule.
7949    #[serde(flatten)]
7950    pub plan: FanoutPlan,
7951    /// Optional validity window. Outside `[from, until)` the
7952    /// schedule is dormant — still registered, still visible, but
7953    /// every tick is skipped (deleted ≠ dormant: a campaign that
7954    /// ended stays inspectable and can be re-armed by editing the
7955    /// window). Checked at tick time on both the backend scheduler
7956    /// and the agent's local scheduler.
7957    #[serde(default, skip_serializing_if = "Active::is_empty")]
7958    pub active: Active,
7959    /// #418 operational constraints gating *when within an active
7960    /// period* a fire may happen: a maintenance `window`, a fleet
7961    /// `max_concurrent` cap, and `skip_dates` (holiday exclusion). The
7962    /// wall-clock ones are evaluated in the schedule's `tz`; future
7963    /// `require` (env gates) lands in the same namespace. Checked at
7964    /// tick time on both schedulers (and surfaced by `preview`).
7965    #[serde(default, skip_serializing_if = "Constraints::is_empty")]
7966    pub constraints: Constraints,
7967    /// #418 Phase 4: what to do after a fire's script comes back
7968    /// failed. Currently just `retry` (fixed-backoff in-process
7969    /// re-run); future `notify` / `disable` join the same namespace.
7970    /// Applied fire-side in `handle_command` (the retry policy is
7971    /// lowered onto every Command this schedule produces), so it
7972    /// covers both `runs_on` locations.
7973    #[serde(default, skip_serializing_if = "OnFailure::is_empty")]
7974    pub on_failure: OnFailure,
7975    /// #418 Phase 2: the timezone this schedule's wall-clock fields
7976    /// are evaluated in — both the calendar `at` firing time AND the
7977    /// `active.{from,until}` window bounds. `local` (default) = the
7978    /// running host's TZ (the agent's for `runs_on: agent`, the
7979    /// backend server's otherwise); `utc` for TZ-independent
7980    /// schedules. Reconcile shapes (`per_pc`/`per_target`) ignore it
7981    /// for firing (poll cron runs every minute regardless) but still
7982    /// honor it for the `active` window.
7983    #[serde(default)]
7984    pub tz: ScheduleTz,
7985    /// v0.22: optional humantime window after a cron tick during
7986    /// which the Command is still considered "live". The scheduler
7987    /// computes `tick_at + starting_deadline` and stamps it onto
7988    /// each Command as `deadline_at`; agents skip Commands they
7989    /// receive after that absolute time. `None` (default) = no
7990    /// deadline, meaning a Command queued in the broker / stream
7991    /// during agent downtime runs whenever the agent reconnects —
7992    /// good for kitting / inventory / cleanup. Set this for
7993    /// time-of-day notifications, lunch reminders, etc., where
7994    /// "fire 3 hours late" would be wrong.
7995    #[serde(default, skip_serializing_if = "Option::is_none")]
7996    pub starting_deadline: Option<String>,
7997    /// v0.23: where does the cron tick happen? `Backend` (default,
7998    /// historical) = backend's scheduler fires Commands via NATS;
7999    /// agents passively receive. `Agent` = each targeted agent runs
8000    /// its own internal cron and fires locally, so the schedule
8001    /// keeps ticking even when the broker is unreachable (laptop on
8002    /// the train, broker maintenance window, full WAN outage). The
8003    /// two locations are mutually exclusive — when `Agent`, the
8004    /// backend scheduler stays out and just keeps the definition in
8005    /// KV for agents to read.
8006    #[serde(default)]
8007    pub runs_on: RunsOn,
8008    #[serde(default = "default_true")]
8009    pub enabled: bool,
8010    /// Free-form operator taxonomy for the Schedules page — the
8011    /// schedule-side mirror of `Manifest.tags` (added in #640; a plain
8012    /// code ref rather than an intra-doc link, since that field isn't
8013    /// on this branch until #640 merges). Purely a SPA-side
8014    /// organisational aid (search / filter chips alongside the
8015    /// id-prefix grouping); the scheduler never reads it, so any
8016    /// string is allowed and it carries no firing semantics. A
8017    /// schedule's own tags are independent of its job's: the same job
8018    /// may back a `weekly` maintenance schedule and a `canary` rollout
8019    /// schedule. Empty by default and `skip_serializing_if`-elided per
8020    /// the #492 gradual-upgrade wire rule.
8021    #[serde(default, skip_serializing_if = "Vec::is_empty")]
8022    pub tags: Vec<String>,
8023    /// GitOps provenance (#695) — see [`RepoOrigin`]. Stamped by
8024    /// `kanade schedule create` when the source YAML lives inside a Git
8025    /// work tree, so the SPA renders the schedule read-only and points
8026    /// edits back at the repo (SPEC design principle #3: 設定駆動 YAML +
8027    /// Git), parity with a job's [`Manifest::origin`]. `None` for
8028    /// SPA-born schedules and ones applied from outside any repo. Purely
8029    /// informational — the scheduler never reads it. New field ⇒ #492
8030    /// wire rule (`default` + `skip_serializing_if`).
8031    #[serde(default, skip_serializing_if = "Option::is_none")]
8032    pub origin: Option<RepoOrigin>,
8033}
8034
8035impl Schedule {
8036    /// Every valid top-level key on a Schedule YAML/JSON document —
8037    /// this struct's own fields PLUS the fields of the
8038    /// `#[serde(flatten)] plan: FanoutPlan`. The strict create
8039    /// boundary needs this because serde's flatten buffering hides
8040    /// unknown top-level keys from `serde_ignored`, so a typo like
8041    /// `jiter:` or `enabledd:` would otherwise be silently dropped
8042    /// (#924). Kept in sync with the field list by
8043    /// `schedule_top_level_keys_cover_serialized_fields`.
8044    pub const TOP_LEVEL_KEYS: &'static [&'static str] = &[
8045        // Schedule's own fields:
8046        "id",
8047        "when",
8048        "job_id",
8049        "active",
8050        "constraints",
8051        "on_failure",
8052        "tz",
8053        "starting_deadline",
8054        "runs_on",
8055        "enabled",
8056        "tags",
8057        "origin",
8058        // flattened FanoutPlan:
8059        "target",
8060        "rollout",
8061        "jitter",
8062        "deadline_at",
8063    ];
8064}
8065
8066impl crate::strict::StrictSchema for Schedule {
8067    fn strict_top_level_keys() -> Option<&'static [&'static str]> {
8068        Some(Self::TOP_LEVEL_KEYS)
8069    }
8070}
8071
8072/// Manifest has no `#[serde(flatten)]` field, so `serde_ignored`
8073/// already catches every top-level typo — the default (`None`) is
8074/// correct.
8075impl crate::strict::StrictSchema for Manifest {}
8076
8077/// View likewise has no flattened field.
8078impl crate::strict::StrictSchema for View {}
8079
8080/// GroupDef likewise has no flattened field.
8081impl crate::strict::StrictSchema for GroupDef {}
8082
8083/// v0.23 — where the cron tick fires from.
8084#[derive(
8085    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
8086)]
8087#[serde(rename_all = "snake_case")]
8088pub enum RunsOn {
8089    /// Backend's central scheduler ticks and publishes Commands to
8090    /// NATS. Historical default, what every pre-v0.23 schedule
8091    /// uses. Agent offline ⇒ Command queued in STREAM_EXEC; agent
8092    /// reconnects ⇒ catch-up via [`command_replay`](crate)
8093    /// (see kanade-agent's command_replay module).
8094    #[default]
8095    Backend,
8096    /// Each targeted agent runs the cron tick locally. Survives
8097    /// broker / WAN outages. Best for laptops / mobile devices that
8098    /// roam off the corporate network. Agent must be online for the
8099    /// initial schedule + job-catalog pull, but once cached the
8100    /// agent fires the script standalone.
8101    Agent,
8102}
8103
8104/// Per-pc/per-target dedup semantics for a [`Schedule`] (v0.19).
8105#[derive(
8106    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
8107)]
8108#[serde(rename_all = "snake_case")]
8109pub enum ExecMode {
8110    /// Fire on every cron tick at the whole target. Historical
8111    /// (pre-v0.19) behavior; no dedup.
8112    #[default]
8113    EveryTick,
8114    /// Fire at each pc until that pc succeeds; then skip it until
8115    /// the optional cooldown elapses (or forever if no cooldown).
8116    /// Use for kitting / first-boot / per-pc compliance checks.
8117    OncePerPc,
8118    /// Fire at the whole target until **any** pc succeeds; then
8119    /// skip the whole target until the optional cooldown elapses
8120    /// (or forever if no cooldown). Use for "one delegate is
8121    /// enough" tasks like license check-in.
8122    OncePerTarget,
8123    /// Like [`OncePerPc`](ExecMode::OncePerPc), but the "already
8124    /// succeeded ⇒ skip" check is scoped to the CURRENT manifest
8125    /// version: a pc whose only successful run recorded an OLDER
8126    /// manifest version re-fires so the new version reaches it. Bumping
8127    /// the job's YAML `version` is the redistribution trigger. Plain
8128    /// `OncePerPc` (kitting) is version-blind — a pc that ever succeeded
8129    /// is skipped forever; this mode re-arms per version. per_pc only —
8130    /// `Schedule::validate` rejects `per_target: once_per_version`.
8131    OncePerPcVersion,
8132    /// #418 OS-native event trigger (`when: { on: [...] }`). There is
8133    /// no cron — the agent fires it from an OS event source (boot /
8134    /// session-change), not a tick — so the scheduler skips
8135    /// `tokio-cron` registration for it. Each event occurrence fires
8136    /// once, gated by the standard freeze / active / window /
8137    /// skip_dates checks.
8138    Event,
8139}
8140
8141/// #418 Phase 1 — the single "when does this fire" axis.
8142///
8143/// Replaces the old `cron` + `mode` + `cooldown` trio whose
8144/// interactions were implicit (cron doubled as both a real
8145/// time-of-day trigger and a reconcile poll period; contradictory
8146/// combinations silently no-opped). Two shapes:
8147///
8148/// * **reconcile** (`per_pc` / `per_target`) — desired-state: "each
8149///   pc (or one delegate) should have run this within `every`".
8150///   The poll period is system-generated ([`POLL_CRON`], every
8151///   minute) and no longer the operator's concern.
8152/// * **calendar** (`{ at, days }`) — a wall-clock time trigger
8153///   (#418 Phase 2, replacing the old raw-cron escape hatch). Fires
8154///   the whole target at the given time, no dedup. `at: "09:00"` +
8155///   `days` repeats; `at: "2026-06-10 09:00"` (a date+time) fires
8156///   exactly once. Evaluated in the schedule's top-level `tz`.
8157#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8158#[serde(rename_all = "snake_case")]
8159pub enum When {
8160    /// Fire at each targeted pc: `once` (kitting — succeed once,
8161    /// skip forever, forever catching brand-new / re-imaged pcs)
8162    /// or `{ every: <humantime> }` (patrol — re-arm per pc after
8163    /// the interval).
8164    PerPc(PerPolicy),
8165    /// Fire until **any** one pc of the target succeeds, then skip
8166    /// the whole target (`once`) or re-arm after `every`. Needs
8167    /// fleet-wide completion data, so it is backend-only —
8168    /// `runs_on: agent` + `per_target` is rejected by
8169    /// [`Schedule::validate`].
8170    PerTarget(PerPolicy),
8171    /// Calendar time trigger: `{ at: "09:00", days: [mon-fri] }`
8172    /// (repeating) or `{ at: "2026-06-10 09:00" }` (one-shot). Fires
8173    /// the whole target at that wall-clock time in the schedule's
8174    /// `tz` — no dedup, no cooldown.
8175    Calendar(CalendarSpec),
8176    /// #418 OS-native event trigger: `when: { on: [startup, logon] }`.
8177    /// Fires when the agent observes the listed OS event(s) rather than
8178    /// on a clock — there is no cron. `runs_on: agent` only (the agent
8179    /// owns the event source); [`Schedule::validate`] rejects it on
8180    /// `backend` and rejects an empty list. Each event occurrence fires
8181    /// once, gated by the same freeze / active / `constraints.window` /
8182    /// `skip_dates` checks as the cron path. `startup` fires once per OS
8183    /// boot (deduped via the host boot time); a `starting_deadline`, if
8184    /// set, limits it to "agent came up within that long after boot".
8185    /// Only `startup` has an event source on every OS; `logon` / `lock` /
8186    /// `unlock` / `network_change` are Windows-only — on macOS / Linux
8187    /// they never fire, and the agent says so once per schedule / job
8188    /// version (WARN + a synthetic skipped result, exit 122) when it loads it.
8189    On(Vec<OnTrigger>),
8190}
8191
8192/// An OS event the agent can fire a schedule on (#418 `when: { on }`).
8193#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Hash)]
8194#[serde(rename_all = "snake_case")]
8195pub enum OnTrigger {
8196    /// Once per OS boot (the agent's first run for that boot). Catches
8197    /// freshly-imaged / reinstalled hosts at their next startup.
8198    Startup,
8199    /// On an interactive-session user logon — console, RDP, or
8200    /// auto-logon (Windows `WTS_SESSION_LOGON`; Windows only). Does not fire for
8201    /// service / network / batch logons (no interactive session).
8202    Logon,
8203    /// When the workstation is locked (Win+L / idle lock; Windows
8204    /// `WTS_SESSION_LOCK`; Windows only). Use for step-away compliance / cleanup.
8205    Lock,
8206    /// When the workstation is unlocked — the user returns to a locked
8207    /// session (Windows `WTS_SESSION_UNLOCK`; Windows only). Use to re-check
8208    /// compliance / refresh state when work resumes.
8209    Unlock,
8210    /// When the host's network changes — IP address table change on
8211    /// connect / disconnect / DHCP renew / VPN / Wi-Fi roam (Windows
8212    /// `NotifyAddrChange`; Windows only). Debounced agent-side (a burst of changes
8213    /// from one transition fires once after the network settles), so
8214    /// use it for "re-check connectivity / re-register on network move"
8215    /// rather than expecting one fire per raw adapter event.
8216    ///
8217    /// IPv4 only: `NotifyAddrChange` watches the IPv4 address table, so a
8218    /// transition that touches only IPv6 addresses won't fire. In practice
8219    /// dual-stack networks change both tables together, but a pure-IPv6
8220    /// move (e.g. an IPv6-only Wi-Fi roam) is not detected.
8221    NetworkChange,
8222}
8223
8224/// Calendar time trigger (#418 Phase 2). `at` is either a time of
8225/// day (`"HH:MM"`, repeating — combine with `days`) or a full
8226/// date+time (`"YYYY-MM-DD HH:MM"`, a one-shot that fires once and
8227/// never again). Evaluated in the schedule's top-level `tz`.
8228#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8229pub struct CalendarSpec {
8230    /// `"HH:MM"` (24h) for a repeating trigger, or
8231    /// `"YYYY-MM-DD HH:MM"` (hyphen / slash / `T` separators all
8232    /// accepted) for a one-shot. Parsed lazily —
8233    /// [`Schedule::validate`] rejects garbage at create time.
8234    pub at: String,
8235    /// Day-of-week filter for a time-of-day `at`: `["mon-fri"]`,
8236    /// `["mon","wed","fri"]`, … (passed verbatim to the cron DOW
8237    /// field, so ranges and names both work). An **nth-weekday**
8238    /// `["tue#2"]` fires only on the 2nd Tuesday of each month
8239    /// ("Patch Tuesday"); the ordinal is `1..5`. A **last-weekday**
8240    /// `["friL"]` fires only on the last Friday of each month (handy
8241    /// for monthly maintenance). Empty = every day. Must be empty
8242    /// when `at` carries a date (the date already pins the day).
8243    #[serde(default, skip_serializing_if = "Vec::is_empty")]
8244    pub days: Vec<String>,
8245}
8246
8247/// Parsed `CalendarSpec.at`: the wall-clock minute/hour, plus the
8248/// date for a one-shot (`None` = repeating time-of-day).
8249struct ParsedAt {
8250    minute: u32,
8251    hour: u32,
8252    date: Option<chrono::NaiveDate>,
8253}
8254
8255impl CalendarSpec {
8256    /// Parse `at`: a date+time (`YYYY-MM-DD HH:MM`, hyphen / slash /
8257    /// `T` separators) is a one-shot; a bare `HH:MM` is repeating.
8258    fn parse_at(&self) -> Result<ParsedAt, String> {
8259        use chrono::Timelike;
8260        let s = self.at.trim();
8261        for fmt in ["%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y/%m/%d %H:%M"] {
8262            if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, fmt) {
8263                return Ok(ParsedAt {
8264                    minute: dt.minute(),
8265                    hour: dt.hour(),
8266                    date: Some(dt.date()),
8267                });
8268            }
8269        }
8270        if let Ok(t) = chrono::NaiveTime::parse_from_str(s, "%H:%M") {
8271            return Ok(ParsedAt {
8272                minute: t.minute(),
8273                hour: t.hour(),
8274                date: None,
8275            });
8276        }
8277        Err(format!(
8278            "when.at: unparseable '{}' (want HH:MM or YYYY-MM-DD HH:MM)",
8279            self.at
8280        ))
8281    }
8282
8283    /// Pre-flight check on the `days` tokens so a bad day name gives
8284    /// a `when.days:`-scoped error instead of croner's confusing
8285    /// "when.at lowered to invalid cron" (claude #432 review). Each
8286    /// token is a day name (`mon`..`sun`), a numeric DOW (`0`..`7`),
8287    /// `*`, a `-` range of those, an **nth-weekday** like `tue#2`
8288    /// (2nd Tuesday of the month — "Patch Tuesday"), or a
8289    /// **last-weekday** like `friL` (last Friday of the month).
8290    fn validate_days(&self) -> Result<(), String> {
8291        const NAMES: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
8292        let is_day = |p: &str| NAMES.contains(&p) || p.parse::<u8>().is_ok_and(|n| n <= 7);
8293        for tok in &self.days {
8294            // Report the whole token on a malformed range like `mon-`
8295            // (which would otherwise split to a cryptic empty part —
8296            // claude #432 follow-up).
8297            let invalid = |reason: &str| {
8298                Err(format!(
8299                    "when.days: invalid day token '{tok}' ({reason}; \
8300                     want mon..sun, 0-7, a range like mon-fri, an nth-weekday \
8301                     like tue#2, a last-weekday like friL, or *)"
8302                ))
8303            };
8304            // #418: nth-weekday suffix (`tue#2` = 2nd Tuesday). Croner
8305            // accepts `<dow>#<n>` (n = 1..5) in the DOW field, and
8306            // `to_cron` passes the token through verbatim, so the
8307            // engine fires only on that occurrence. It's a single
8308            // weekday + ordinal — not combinable with a range.
8309            if let Some((day_part, nth_part)) = tok.split_once('#') {
8310                // Normalize once and use `d` consistently (gemini #547);
8311                // the outer `invalid` already echoes the raw `tok`.
8312                let d = day_part.trim().to_ascii_lowercase();
8313                if d.contains('-') || !is_day(&d) {
8314                    return invalid("the part before # must be a single weekday");
8315                }
8316                match nth_part.trim().parse::<u8>() {
8317                    Ok(n) if (1..=5).contains(&n) => {}
8318                    _ => return invalid("the # ordinal must be 1..5 (e.g. tue#2 = 2nd Tuesday)"),
8319                }
8320                continue;
8321            }
8322            // #418: last-weekday suffix (`friL` = last Friday of the
8323            // month — the monthly-maintenance sibling of Patch Tuesday).
8324            // Croner accepts `<dow>L` in the DOW field with verified
8325            // last-<dow>-of-month semantics, and `to_cron` passes it
8326            // through verbatim. A single weekday + `L` — bare `L` and
8327            // ranges are rejected (croner would read bare `L` as
8328            // Saturday, which is a confusing footgun).
8329            if let Some(day_part) = tok.strip_suffix(['L', 'l']) {
8330                // No `.trim()`: a cron DOW token can't carry internal
8331                // whitespace, so `"fri L"` must be *rejected* here (its
8332                // strip leaves `"fri "`, and `is_day` catches the space)
8333                // rather than trimmed into a clean `"fri"` that then
8334                // produces a malformed `fri L` cron downstream and a
8335                // confusing croner error (gemini #560).
8336                let d = day_part.to_ascii_lowercase();
8337                if d.is_empty() {
8338                    return invalid("`L` (last-weekday) needs a weekday before it, e.g. friL");
8339                }
8340                if d.contains('-') || !is_day(&d) {
8341                    return invalid(
8342                        "the part before L must be a single weekday (e.g. friL = last Friday)",
8343                    );
8344                }
8345                continue;
8346            }
8347            for part in tok.split('-') {
8348                let p = part.trim().to_ascii_lowercase();
8349                if p.is_empty() {
8350                    return invalid("empty range bound");
8351                }
8352                if p != "*" && !is_day(&p) {
8353                    return invalid(&format!("'{part}' is not a day"));
8354                }
8355            }
8356        }
8357        Ok(())
8358    }
8359
8360    /// For a one-shot (`at` carries a date), the absolute instant it
8361    /// fires in `tz`. `None` for a repeating calendar. Used to warn
8362    /// about a one-shot whose date is already in the past (it would
8363    /// never fire).
8364    pub fn oneshot_instant(&self, tz: ScheduleTz) -> Option<chrono::DateTime<chrono::Utc>> {
8365        let p = self.parse_at().ok()?;
8366        let date = p.date?;
8367        let naive = date.and_hms_opt(p.hour, p.minute, 0)?;
8368        tz.naive_to_utc(naive)
8369    }
8370
8371    /// The wall-clock time-of-day this calendar fires at (`None` if
8372    /// `at` is unparseable — validate() guards that). Used to detect
8373    /// a calendar whose fire time can never fall inside its
8374    /// `constraints.window` (claude #452 review).
8375    pub fn fire_time(&self) -> Option<chrono::NaiveTime> {
8376        let p = self.parse_at().ok()?;
8377        chrono::NaiveTime::from_hms_opt(p.hour, p.minute, 0)
8378    }
8379
8380    /// Lower to the cron string the scheduler engine runs. Repeating
8381    /// → 6-field `0 {min} {hour} * * {dow}`; one-shot → 7-field
8382    /// `0 {min} {hour} {day} {month} * {year}` (a past year never
8383    /// fires — that's what makes it one-shot).
8384    fn to_cron(&self) -> Result<String, String> {
8385        use chrono::Datelike;
8386        let ParsedAt { minute, hour, date } = self.parse_at()?;
8387        match date {
8388            Some(d) => {
8389                if !self.days.is_empty() {
8390                    return Err(
8391                        "when.at with a date is a one-shot and cannot be combined with days".into(),
8392                    );
8393                }
8394                Ok(format!(
8395                    "0 {minute} {hour} {} {} * {}",
8396                    d.day(),
8397                    d.month(),
8398                    d.year()
8399                ))
8400            }
8401            None => {
8402                let dow = if self.days.is_empty() {
8403                    "*".to_string()
8404                } else {
8405                    self.validate_days()?;
8406                    self.days.join(",")
8407                };
8408                Ok(format!("0 {minute} {hour} * * {dow}"))
8409            }
8410        }
8411    }
8412}
8413
8414/// The timezone a schedule's wall-clock fields (`when.at`,
8415/// `active.{from,until}`) are evaluated in (#418 Phase 2).
8416#[derive(
8417    Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
8418)]
8419#[serde(rename_all = "snake_case")]
8420pub enum ScheduleTz {
8421    /// The running host's local timezone — the agent's for
8422    /// `runs_on: agent`, the backend server's otherwise. Default.
8423    #[default]
8424    Local,
8425    /// UTC — for timezone-independent schedules.
8426    Utc,
8427}
8428
8429impl ScheduleTz {
8430    /// Interpret a naive (zoneless) datetime as being in this tz and
8431    /// convert to UTC. On a DST *fold* (the local time occurs twice
8432    /// when clocks go back) we pick `.earliest()` rather than
8433    /// rejecting it; `None` is reserved for a true DST *gap* (a local
8434    /// time that never exists). `Utc` is fixed-offset so neither ever
8435    /// happens; `Local` is whatever timezone the running host is set
8436    /// to and *can* hit a gap/fold on any DST-observing host — not
8437    /// just the JST we run today (gemini + claude #432 review).
8438    fn naive_to_utc(self, naive: chrono::NaiveDateTime) -> Option<chrono::DateTime<chrono::Utc>> {
8439        use chrono::TimeZone;
8440        match self {
8441            ScheduleTz::Utc => Some(chrono::DateTime::from_naive_utc_and_offset(
8442                naive,
8443                chrono::Utc,
8444            )),
8445            ScheduleTz::Local => chrono::Local
8446                .from_local_datetime(&naive)
8447                .earliest()
8448                .map(|dt| dt.with_timezone(&chrono::Utc)),
8449        }
8450    }
8451
8452    /// The wall-clock time-of-day `now` reads as in this tz — used by
8453    /// [`Constraints::allows`] to test a maintenance window
8454    /// (#418 Phase 3). `Utc` is the naive UTC time; `Local` is the
8455    /// running host's local time.
8456    fn wall_time(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveTime {
8457        match self {
8458            ScheduleTz::Utc => now.time(),
8459            ScheduleTz::Local => now.with_timezone(&chrono::Local).time(),
8460        }
8461    }
8462
8463    /// The wall-clock *date* `now` reads as in this tz — used by
8464    /// [`Constraints::allows`] to test `skip_dates` (#418 holiday
8465    /// exclusion). Same tz semantics as [`Self::wall_time`].
8466    fn wall_date(self, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveDate {
8467        match self {
8468            ScheduleTz::Utc => now.date_naive(),
8469            ScheduleTz::Local => now.with_timezone(&chrono::Local).date_naive(),
8470        }
8471    }
8472
8473    /// Stable lowercase wire/display label (`local` / `utc`) — matches
8474    /// the serde `snake_case` representation. Used for the preview
8475    /// response's `tz` field so the JSON shape isn't coupled to the
8476    /// `Debug` repr (claude #578 review).
8477    pub fn as_str(self) -> &'static str {
8478        match self {
8479            ScheduleTz::Local => "local",
8480            ScheduleTz::Utc => "utc",
8481        }
8482    }
8483}
8484
8485impl std::fmt::Display for ScheduleTz {
8486    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8487        f.write_str(self.as_str())
8488    }
8489}
8490
8491/// `once` / `once_per_version` / `{ every: <humantime> }` — shared by
8492/// `per_pc` / `per_target`. Untagged so the YAML stays the bare keyword
8493/// or a one-key map, nothing more ceremonial. `once_per_version` is
8494/// per_pc + backend only (see the variant doc and `Schedule::validate`).
8495#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8496#[serde(untagged)]
8497pub enum PerPolicy {
8498    /// The bare string `once`: succeed once, then skip permanently
8499    /// (cooldown = infinity), version-blind.
8500    Once(OnceLiteral),
8501    /// The bare string `once_per_version`: succeed once *per manifest
8502    /// version*, then skip until the job's YAML `version` changes. Like
8503    /// `once` but re-arms each pc when the version it succeeded at is no
8504    /// longer current — the version-aware redistribution shape. per_pc
8505    /// only (`Schedule::validate` rejects it on `per_target`).
8506    OncePerVersion(OncePerVersionLiteral),
8507    /// Re-arm after the humantime interval, e.g. `{ every: 6h }`.
8508    Every(EverySpec),
8509}
8510
8511/// Single-variant enum so serde accepts exactly the string `once`
8512/// (a free-form `String` would swallow typos like `onec`).
8513#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
8514#[serde(rename_all = "snake_case")]
8515pub enum OnceLiteral {
8516    Once,
8517}
8518
8519/// Single-variant enum so serde accepts exactly the string
8520/// `once_per_version` (mirrors [`OnceLiteral`]'s typo-catching). The
8521/// distinct literal — rather than a bool field on `once` — keeps the
8522/// ergonomic bare-string surface (`per_pc: once_per_version`).
8523#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
8524#[serde(rename_all = "snake_case")]
8525pub enum OncePerVersionLiteral {
8526    OncePerVersion,
8527}
8528
8529/// `{ every: <humantime> }`. Standalone struct (not an inline
8530/// struct variant). `{ evry: 6h }` still fails to parse (the
8531/// required `every` key is missing), and the create boundaries
8532/// reject the unknown `evry` via [`crate::strict`] with its path —
8533/// while agents reading a future writer's extra fields tolerate
8534/// them (#492).
8535#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8536pub struct EverySpec {
8537    /// Humantime interval (`10m`, `6h`, `1d`...). Parsed lazily —
8538    /// [`Schedule::validate`] rejects garbage at create time.
8539    pub every: String,
8540}
8541
8542impl PerPolicy {
8543    /// The cooldown this policy lowers to: `once` = `None`
8544    /// (permanent skip), `every` = the interval.
8545    fn cooldown(&self) -> Option<String> {
8546        match self {
8547            // Both `once` shapes lower to "no time-based re-arm". The
8548            // version-aware re-arm for `once_per_version` is not a
8549            // cooldown — it is the version filter the scheduler applies
8550            // to the completion set, so the cooldown stays None here.
8551            PerPolicy::Once(_) | PerPolicy::OncePerVersion(_) => None,
8552            PerPolicy::Every(EverySpec { every }) => Some(every.clone()),
8553        }
8554    }
8555}
8556
8557impl std::fmt::Display for When {
8558    /// Operator-facing one-liner (`per_pc once` / `per_pc every 6h`
8559    /// / `at 09:00 [mon-fri]` / `at 2026-06-10 09:00`) for log
8560    /// lines, audit payloads and the API's `ScheduleSummary`.
8561    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8562        let policy = |p: &PerPolicy| match p {
8563            PerPolicy::Once(_) => "once".to_string(),
8564            PerPolicy::OncePerVersion(_) => "once_per_version".to_string(),
8565            PerPolicy::Every(EverySpec { every }) => format!("every {every}"),
8566        };
8567        match self {
8568            When::PerPc(p) => write!(f, "per_pc {}", policy(p)),
8569            When::PerTarget(p) => write!(f, "per_target {}", policy(p)),
8570            When::Calendar(c) if c.days.is_empty() => write!(f, "at {}", c.at),
8571            When::Calendar(c) => write!(f, "at {} [{}]", c.at, c.days.join(",")),
8572            When::On(triggers) => {
8573                let names: Vec<&str> = triggers.iter().map(|t| t.as_str()).collect();
8574                write!(f, "on [{}]", names.join(","))
8575            }
8576        }
8577    }
8578}
8579
8580impl OnTrigger {
8581    /// Lowercase wire/display label (matches the serde `snake_case`).
8582    pub fn as_str(self) -> &'static str {
8583        match self {
8584            OnTrigger::Startup => "startup",
8585            OnTrigger::Logon => "logon",
8586            OnTrigger::Lock => "lock",
8587            OnTrigger::Unlock => "unlock",
8588            OnTrigger::NetworkChange => "network_change",
8589        }
8590    }
8591}
8592
8593/// Optional validity window for a [`Schedule`] (#418 decision G).
8594/// Half-open `[from, until)`; either bound may be omitted. Bounds
8595/// are `YYYY-MM-DD` (= that day's 00:00 in the schedule's `tz`) or
8596/// full RFC3339 (offset is honored as-is, `tz` ignored). Kept as
8597/// strings so the JSON Schema the SPA editor consumes stays two
8598/// plain string fields, mirroring `jitter` / `starting_deadline`.
8599///
8600/// #418 Phase 2: bounds are evaluated in the schedule's top-level
8601/// `tz` (was UTC-only in Phase 1) so `tz: local` makes both the
8602/// calendar `at` AND the `active` window local — one consistent
8603/// timezone per schedule.
8604#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
8605pub struct Active {
8606    /// Dormant before this instant.
8607    #[serde(default, skip_serializing_if = "Option::is_none")]
8608    pub from: Option<String>,
8609    /// Dormant from this instant on (exclusive).
8610    #[serde(default, skip_serializing_if = "Option::is_none")]
8611    pub until: Option<String>,
8612}
8613
8614impl Active {
8615    /// `skip_serializing_if` helper — an empty window means "always
8616    /// active" and is omitted from the wire format entirely.
8617    pub fn is_empty(&self) -> bool {
8618        self.from.is_none() && self.until.is_none()
8619    }
8620
8621    /// Parse one bound: RFC3339 first (offset honored, `tz`
8622    /// ignored), then bare `YYYY-MM-DD` (00:00 in `tz`).
8623    pub fn parse_bound(s: &str, tz: ScheduleTz) -> Result<chrono::DateTime<chrono::Utc>, String> {
8624        if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
8625            return Ok(dt.with_timezone(&chrono::Utc));
8626        }
8627        if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
8628            let midnight = d.and_hms_opt(0, 0, 0).expect("00:00:00 is always valid");
8629            return tz.naive_to_utc(midnight).ok_or_else(|| {
8630                format!("active: bound '{s}' falls in a DST gap for the schedule's tz")
8631            });
8632        }
8633        Err(format!(
8634            "active: unparseable bound '{s}' (want YYYY-MM-DD or RFC3339)"
8635        ))
8636    }
8637
8638    /// Is `now` inside the window? Unparseable bounds are treated
8639    /// as absent here (fail-open) — [`Schedule::validate`] is the
8640    /// place that rejects them loudly; this runs on every tick and
8641    /// must never panic on a stale KV blob.
8642    pub fn contains(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
8643        let bound = |s: &Option<String>| s.as_deref().and_then(|s| Self::parse_bound(s, tz).ok());
8644        if bound(&self.from).is_some_and(|from| now < from) {
8645            return false;
8646        }
8647        if bound(&self.until).is_some_and(|until| now >= until) {
8648            return false;
8649        }
8650        true
8651    }
8652}
8653
8654/// Host-environment gate (#418 `constraints.require`). Fire only when
8655/// the target host is in the required state. Sensed **in-process by the
8656/// agent** (Win32), so it is `runs_on: agent` only — the backend cannot
8657/// read a target host's power/idle state ([`Schedule::validate`]
8658/// rejects it on `runs_on: backend`, symmetric with `when: { on }`).
8659///
8660/// Evaluated at fire time as a skip-this-tick gate (NOT in
8661/// [`Constraints::allows`], which stays pure for `preview`): a reconcile
8662/// cadence re-checks every minute (so it effectively defers until the
8663/// state is met — the intended pairing); a `calendar` fire that lands
8664/// while the state is unmet is simply missed, same as `window`. It is
8665/// therefore a *runtime* gate and does not appear in `preview`.
8666///
8667/// Off Windows only `cpu_below` can be sensed. On macOS / Linux any other
8668/// set gate cannot be evaluated, so the agent fails closed: the job does
8669/// not run, no per-pc completion is recorded (it still runs once the gate
8670/// is supported), and one WARN + one synthetic skipped result (exit 122,
8671/// naming the gate) is published per schedule / job version.
8672// No `Eq`: `cpu_below: Option<f64>` is only `PartialEq` (f64 is not Eq).
8673#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
8674pub struct Require {
8675    /// Fire only while on **AC power** (skip on battery). Reads
8676    /// `GetSystemPowerStatus`; an unknown/unreadable status is treated
8677    /// as not-on-AC (fail-closed — a restrictive gate must not fire
8678    /// when it can't confirm the condition). `false` (default) = no
8679    /// power requirement. Windows only (fail-closed skip elsewhere).
8680    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
8681    pub ac_power: bool,
8682    /// Fire only when the active console session has had **no keyboard /
8683    /// mouse input for at least this long** (humantime, e.g. `"10m"`) —
8684    /// "don't run while the user is actively working". Input-based
8685    /// (simpler than Task Scheduler's CPU/disk-aware idle). A
8686    /// headless / disconnected console (no interactive user) trivially
8687    /// satisfies it. `None` (default) = no idle requirement. Parsed
8688    /// lazily; [`Schedule::validate`] rejects garbage at create time.
8689    /// Windows only (fail-closed skip elsewhere).
8690    #[serde(default, skip_serializing_if = "Option::is_none")]
8691    pub idle: Option<String>,
8692    /// Fire only when the **whole-machine CPU usage is below this
8693    /// percent** (0–100; e.g. `20.0` = "system CPU < 20%") — "don't run
8694    /// while the box is busy". Reuses the agent's `host_perf` system CPU%
8695    /// sample (`sysinfo` mean over cores), so the reading is up to one
8696    /// `host_perf` cadence old (default 60s) — fine as a "generally
8697    /// busy?" proxy, and more accurate than a fresh one-shot read (CPU%
8698    /// needs two samples). An unavailable sample (host_perf not warmed
8699    /// up yet, or stale) is treated as "not below" (fail-closed — a
8700    /// restrictive gate must not fire when it can't confirm). `None`
8701    /// (default) = no CPU requirement. [`Schedule::validate`] rejects an
8702    /// out-of-range value at create time.
8703    #[serde(default, skip_serializing_if = "Option::is_none")]
8704    pub cpu_below: Option<f64>,
8705    /// Fire only when the host has **internet connectivity** (Windows
8706    /// `GetNetworkConnectivityHint` reports InternetAccess) — "don't run
8707    /// until online" for jobs that download / phone home. A captive
8708    /// portal (ConstrainedInternetAccess), LAN-only (LocalAccess), or
8709    /// unknown/unreadable state is treated as offline (fail-closed) — a
8710    /// portal would just fail a download, so we hold the run. For VPN /
8711    /// SASE / app-specific conditions, use a custom script gate (separate
8712    /// slice). `false` (default) = no network requirement. Windows only
8713    /// (fail-closed skip elsewhere).
8714    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
8715    pub network: bool,
8716}
8717
8718impl Require {
8719    /// `skip_serializing_if` helper for an embedded empty `require`.
8720    pub fn is_empty(&self) -> bool {
8721        !self.ac_power && self.idle.is_none() && self.cpu_below.is_none() && !self.network
8722    }
8723
8724    /// Parsed minimum-idle duration (`None` = no idle requirement, or an
8725    /// unparseable value — `validate` rejects the latter at create time).
8726    pub fn min_idle(&self) -> Option<std::time::Duration> {
8727        self.idle
8728            .as_deref()
8729            .and_then(|s| humantime::parse_duration(s.trim()).ok())
8730    }
8731
8732    /// First unparseable field for create-time rejection (mirrors
8733    /// [`Constraints::bad_skip_date`]).
8734    pub fn bad_idle(&self) -> Option<String> {
8735        self.idle.as_deref().and_then(|s| {
8736            humantime::parse_duration(s.trim())
8737                .err()
8738                .map(|e| format!("constraints.require.idle: invalid duration '{s}': {e}"))
8739        })
8740    }
8741}
8742
8743/// Host-environment state sensed by the agent, fed to [`require_met`].
8744/// A named struct (not positional args) so the growing set of sensed
8745/// signals — several of them `bool` — can't be transposed at a call
8746/// site. The Win32 sensing lives in `kanade-agent::env_gate`.
8747#[derive(Debug, Clone, Copy, Default)]
8748pub struct EnvState {
8749    /// Is the host on AC power (`false` if on battery or unreadable).
8750    pub ac_online: bool,
8751    /// How long the console has been idle (`None` = couldn't determine).
8752    pub idle: Option<std::time::Duration>,
8753    /// Whole-machine CPU usage 0–100 (`None` = no sample yet).
8754    pub cpu_pct: Option<f64>,
8755    /// Does the host have internet connectivity (`false` if offline /
8756    /// LAN-only / unreadable).
8757    pub network_up: bool,
8758}
8759
8760/// Pure env-gate decision (#418 `constraints.require`). The Win32
8761/// sensing lives in the agent (`kanade-agent::env_gate`); this is the
8762/// testable core, fed the already-sensed [`EnvState`]. Deliberately a
8763/// free fn (not folded into [`Constraints::allows`]) so `allows` stays
8764/// pure and `preview` never evaluates a runtime gate. Each set
8765/// requirement is a restrictive AND: any unmet (or unknown) gate skips.
8766pub fn require_met(req: &Require, env: &EnvState) -> bool {
8767    if req.ac_power && !env.ac_online {
8768        return false;
8769    }
8770    if let Some(min) = req.min_idle() {
8771        match env.idle {
8772            Some(d) if d >= min => {}
8773            _ => return false,
8774        }
8775    }
8776    if let Some(max) = req.cpu_below {
8777        match env.cpu_pct {
8778            Some(p) if p < max => {}
8779            _ => return false,
8780        }
8781    }
8782    if req.network && !env.network_up {
8783        return false;
8784    }
8785    true
8786}
8787
8788/// [`Active`] decides *over what date range* a schedule is live,
8789/// `Constraints` decides *when, within an active period,* a fire is
8790/// allowed: `window` (a maintenance time-of-day window),
8791/// `max_concurrent` (a fleet-wide running-instance cap), `skip_dates`
8792/// (holiday exclusion) and `require` (host-environment gates, agent-only
8793/// — see [`Require`]).
8794// No `Eq`: contains `require: Option<Require>` which holds an f64.
8795#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq)]
8796pub struct Constraints {
8797    /// `"HH:MM-HH:MM"` wall-clock window (evaluated in the schedule's
8798    /// `tz`). Fires outside it are skipped — mainly for reconcile
8799    /// cadences ("patrol every 6h, but only fire overnight") and
8800    /// daytime change-freezes. `start > end` crosses midnight
8801    /// (`"22:00-05:00"` = 22:00 through 05:00 next morning). Parsed
8802    /// lazily; [`Schedule::validate`] rejects garbage at create time.
8803    #[serde(default, skip_serializing_if = "Option::is_none")]
8804    pub window: Option<String>,
8805    /// Fleet-wide cap on how many instances of this schedule's job may
8806    /// run **at the same time** (#418 "同時実行ハード上限"). The
8807    /// backend scheduler counts the job's still-in-flight runs
8808    /// (`execution_results.finished_at IS NULL`) each tick and only
8809    /// dispatches to as many remaining pcs as there are free slots —
8810    /// a rolling window that refills as runs complete. Useful for
8811    /// disk/CPU/network-heavy jobs you don't want hammering the whole
8812    /// fleet at once.
8813    ///
8814    /// **Backend-only** (it needs a central counter): combining it
8815    /// with `runs_on: agent` is rejected by [`Schedule::validate`]
8816    /// (#418 decision E — "中央上限には中央が要る"). Most meaningful
8817    /// for `per_pc` reconcile cadences, where the poll re-ticks and
8818    /// refills slots. `None` (default) = no cap.
8819    #[serde(default, skip_serializing_if = "Option::is_none")]
8820    pub max_concurrent: Option<u32>,
8821    /// Calendar dates the schedule must **not** fire on — holidays,
8822    /// blackout days, one-off freeze dates (#418 "祝日除外"). Each is
8823    /// `YYYY-MM-DD`, evaluated as a wall-clock date in the schedule's
8824    /// `tz`. Applies to every `when` shape (a reconcile cadence skips
8825    /// the whole day; a calendar fire landing on the date is
8826    /// suppressed) and is honored by both the live scheduler and
8827    /// `preview`, since both gate on [`Constraints::allows`]. Empty
8828    /// (default) = no skips. Operator-supplied: there is no built-in
8829    /// holiday calendar — list the dates you care about. Parsed lazily;
8830    /// [`Schedule::validate`] rejects a malformed date at create time.
8831    #[serde(default, skip_serializing_if = "Vec::is_empty")]
8832    pub skip_dates: Vec<String>,
8833    /// Host-environment gate (#418): fire only when the target host is
8834    /// in the required state (on AC power, idle). Agent-sensed at fire
8835    /// time, `runs_on: agent` only. See [`Require`]. `None` (default) =
8836    /// no environment requirement.
8837    #[serde(default, skip_serializing_if = "Option::is_none")]
8838    pub require: Option<Require>,
8839}
8840
8841impl Constraints {
8842    /// `skip_serializing_if` helper — empty constraints are omitted
8843    /// from the wire format entirely.
8844    pub fn is_empty(&self) -> bool {
8845        self.window.is_none()
8846            && self.max_concurrent.is_none()
8847            && self.skip_dates.is_empty()
8848            && self.require.as_ref().is_none_or(Require::is_empty)
8849    }
8850
8851    /// The first unparseable `skip_dates` entry, if any — the
8852    /// scheduler logs it at register time so a fail-closed
8853    /// (never-firing) schedule from a hand-edited KV blob is
8854    /// diagnosable, mirroring [`Schedule::bad_window`].
8855    pub fn bad_skip_date(&self) -> Option<String> {
8856        self.skip_dates.iter().find_map(|s| {
8857            chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d")
8858                .err()
8859                .map(|e| format!("constraints.skip_dates: invalid date '{s}': {e}"))
8860        })
8861    }
8862
8863    /// Parse `"HH:MM-HH:MM"` into `(start, end)`. Equal bounds are an
8864    /// error (a zero-width or all-day window is ambiguous — write no
8865    /// window for "always").
8866    pub fn parse_window(s: &str) -> Result<(chrono::NaiveTime, chrono::NaiveTime), String> {
8867        let (a, b) = s
8868            .split_once('-')
8869            .ok_or_else(|| format!("constraints.window: '{s}' must be 'HH:MM-HH:MM'"))?;
8870        let parse = |part: &str| {
8871            chrono::NaiveTime::parse_from_str(part.trim(), "%H:%M")
8872                .map_err(|e| format!("constraints.window: invalid time '{}': {e}", part.trim()))
8873        };
8874        let (start, end) = (parse(a)?, parse(b)?);
8875        if start == end {
8876            return Err(format!(
8877                "constraints.window: start and end are equal ('{s}'); omit window for 'always'"
8878            ));
8879        }
8880        Ok((start, end))
8881    }
8882
8883    /// Is a fire allowed at `now` (evaluated in `tz`)? No window =
8884    /// always allowed. Half-open `[start, end)`; `start > end`
8885    /// crosses midnight.
8886    ///
8887    /// **Fail-closed** on an unparseable window (returns `false`,
8888    /// gemini #452 review): a window is a *restrictive* constraint
8889    /// (change-freeze / overnight-only), so a corrupt one must NOT
8890    /// silently allow fires during the restricted hours. Bad windows
8891    /// are rejected at create time by [`Schedule::validate`]; this
8892    /// only bites a hand-edited KV blob, where blocking is the safe
8893    /// direction. The scheduler warns at register time
8894    /// ([`Schedule::bad_window`]) so a stuck schedule is diagnosable.
8895    /// The tick path never panics regardless.
8896    pub fn allows(&self, now: chrono::DateTime<chrono::Utc>, tz: ScheduleTz) -> bool {
8897        // #418 holiday / blackout dates: never fire on a listed wall
8898        // date (in `tz`). Checked before the window since a skipped day
8899        // overrides any within-window allowance. Fail-closed on a
8900        // corrupt entry (same posture as `window`): a skip date is a
8901        // *restrictive* constraint, so a garbled one must not silently
8902        // re-enable fires — it blocks until fixed (`validate` rejects it
8903        // at create time; `bad_skip_date` lets the scheduler warn).
8904        if !self.skip_dates.is_empty() {
8905            let today = tz.wall_date(now);
8906            let blocked = self.skip_dates.iter().any(|s| {
8907                match chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d") {
8908                    Ok(d) => d == today,
8909                    Err(_) => true, // corrupt entry → fail-closed (block)
8910                }
8911            });
8912            if blocked {
8913                return false;
8914            }
8915        }
8916        match self.window.as_deref() {
8917            // No window → always allowed.
8918            None => true,
8919            // Window set: membership, or fail-closed if unparseable
8920            // (`window_contains` returns None for a corrupt window).
8921            Some(_) => self.window_contains(tz.wall_time(now)).unwrap_or(false),
8922        }
8923    }
8924
8925    /// Membership of a wall-clock time-of-day in the window. `None`
8926    /// when there is no window or it's unparseable (callers decide
8927    /// the failure direction). `start > end` crosses midnight.
8928    fn window_contains(&self, t: chrono::NaiveTime) -> Option<bool> {
8929        let (start, end) = Self::parse_window(self.window.as_deref()?).ok()?;
8930        Some(if start <= end {
8931            start <= t && t < end
8932        } else {
8933            t >= start || t < end
8934        })
8935    }
8936}
8937
8938/// What to do when a fire's script fails (#418 Phase 4 — the "高"
8939/// retry/backoff gap). Where [`Constraints`] gates *whether* a fire
8940/// happens, `OnFailure` decides what happens *after* one ran and
8941/// came back bad. Only `retry` so far; future `notify` / `disable`
8942/// would join the same namespace.
8943#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
8944pub struct OnFailure {
8945    /// Re-run the script in-process when it exits non-zero (or times
8946    /// out), up to a cap, with a fixed backoff between attempts.
8947    /// `None` (default) = no retry: a failed run is published as-is
8948    /// and (for reconcile cadences) simply re-fires on the next poll
8949    /// tick. See [`Retry`].
8950    #[serde(default, skip_serializing_if = "Option::is_none")]
8951    pub retry: Option<Retry>,
8952}
8953
8954impl OnFailure {
8955    /// `skip_serializing_if` helper — an empty policy is omitted from
8956    /// the wire format entirely.
8957    pub fn is_empty(&self) -> bool {
8958        self.retry.is_none()
8959    }
8960
8961    /// Lower the operator-facing `retry` (humantime backoff) onto the
8962    /// engine vocabulary the agent's executor runs on (backoff in
8963    /// whole seconds). Single seam shared by the backend command
8964    /// builder and the agent's local scheduler so the two stamp the
8965    /// same [`crate::wire::RetrySpec`] onto every Command. Returns
8966    /// `None` when there is no retry policy or the backoff is
8967    /// unparseable (validate() rejects the latter at create time;
8968    /// this stays fail-safe = "no retry" for a hand-edited KV blob
8969    /// rather than panicking on the fire path).
8970    pub fn lowered_retry(&self) -> Option<crate::wire::RetrySpec> {
8971        let r = self.retry.as_ref()?;
8972        let backoff_secs = humantime::parse_duration(&r.backoff).ok()?.as_secs();
8973        Some(crate::wire::RetrySpec {
8974            max: r.max,
8975            backoff_secs,
8976        })
8977    }
8978}
8979
8980/// Fixed-backoff retry policy (#418 Phase 4). `max` is the number of
8981/// *additional* attempts after the first run (so `max: 3` = up to 4
8982/// total executions); `backoff` is the humantime delay slept between
8983/// attempts. The retry happens fire-side (inside `kanade fire` /
8984/// `handle_command`) on every OS for the PoC — the Windows-native
8985/// "restart on failure" Task Scheduler path is deferred to the
8986/// native-delegation phase (#418 decision H).
8987#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq, Eq)]
8988pub struct Retry {
8989    /// Max additional attempts after the first failure. Bounded
8990    /// `1..=10` by [`Schedule::validate`] — a typo'd `max: 1000`
8991    /// with a short backoff would otherwise pin a flapping script in
8992    /// a tight loop for the whole window.
8993    pub max: u32,
8994    /// Humantime delay slept between attempts (`"10m"`, `"30s"`).
8995    pub backoff: String,
8996}
8997
8998/// Fleet-wide change-freeze (#418 Phase 5 — the "メンテナンス窓 /
8999/// 変更凍結" gap's global half). Where [`Constraints::window`] is a
9000/// *per-schedule* time-of-day gate, a `Freeze` is a *single, fleet-
9001/// global* "stop all automated change" switch the operator flips
9002/// during an incident or a year-end change-freeze. It lives in its
9003/// own KV singleton ([`crate::kv::KEY_FREEZE`]); when present and
9004/// active, both the backend scheduler and every agent's local
9005/// scheduler skip *every* fire.
9006///
9007/// Shapes:
9008/// * `{}` (no bounds) — frozen indefinitely until the operator
9009///   clears it (incident "big red button").
9010/// * `{ from, until }` — frozen only within `[from, until)`,
9011///   evaluated in `tz` (planned change-freeze; auto-thaws).
9012///
9013/// The KV key being *absent* means "not frozen" — so clearing the
9014/// freeze is a KV delete, and `is_active` only ever runs on a freeze
9015/// the operator actually set.
9016#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Default, PartialEq, Eq)]
9017pub struct Freeze {
9018    /// Frozen from this instant (RFC3339 or bare `YYYY-MM-DD` in
9019    /// `tz`). `None` ⇒ frozen from the beginning of time.
9020    #[serde(default, skip_serializing_if = "Option::is_none")]
9021    pub from: Option<String>,
9022    /// Thawed from this instant on, exclusive. `None` ⇒ frozen with
9023    /// no scheduled end (manual clear required).
9024    #[serde(default, skip_serializing_if = "Option::is_none")]
9025    pub until: Option<String>,
9026    /// Operator-supplied note surfaced on the freeze-skip log and the
9027    /// SPA banner ("year-end change freeze", "INC-1234"). Advisory.
9028    #[serde(default, skip_serializing_if = "Option::is_none")]
9029    pub reason: Option<String>,
9030    /// Timezone the bare-date bounds are evaluated in (RFC3339 bounds
9031    /// carry their own offset). Defaults to host-local like a
9032    /// schedule's `tz`.
9033    #[serde(default)]
9034    pub tz: ScheduleTz,
9035}
9036
9037impl Freeze {
9038    /// Is the fleet frozen at `now`? An empty window (`from`/`until`
9039    /// both absent) is frozen unconditionally; otherwise membership of
9040    /// `[from, until)` in `tz`. Half-open like [`Active::contains`],
9041    /// but **fails CLOSED** on an unparseable bound — a freeze is a
9042    /// safety switch, so a corrupt window (only reachable via a
9043    /// hand-edited KV blob; `validate` rejects it at set time) must
9044    /// mean "frozen", not "fire normally" (coderabbit #472). This is
9045    /// the one deliberate divergence from `active`'s fail-OPEN
9046    /// behaviour, where an unparseable bound dormant-skips a schedule.
9047    pub fn is_active(&self, now: chrono::DateTime<chrono::Utc>) -> bool {
9048        // Parse a bound; an unparseable one short-circuits the whole
9049        // check to `true` (frozen) via the closure's `None` sentinel
9050        // handled below.
9051        let bound = |s: &Option<String>| -> Result<Option<chrono::DateTime<chrono::Utc>>, ()> {
9052            match s.as_deref() {
9053                None => Ok(None),
9054                Some(raw) => Active::parse_bound(raw, self.tz).map(Some).map_err(|_| ()),
9055            }
9056        };
9057        let (from, until) = match (bound(&self.from), bound(&self.until)) {
9058            (Ok(f), Ok(u)) => (f, u),
9059            // Any corrupt bound → fail closed (frozen).
9060            _ => return true,
9061        };
9062        if from.is_some_and(|f| now < f) {
9063            return false;
9064        }
9065        if until.is_some_and(|u| now >= u) {
9066            return false;
9067        }
9068        true
9069    }
9070
9071    /// Reject unparseable bounds / `from >= until` at set time (the
9072    /// API + CLI counterpart to [`Schedule::validate`]).
9073    pub fn validate(&self) -> Result<(), String> {
9074        let from = self
9075            .from
9076            .as_deref()
9077            .map(|s| Active::parse_bound(s, self.tz))
9078            .transpose()
9079            .map_err(|e| e.replace("active:", "freeze:"))?;
9080        let until = self
9081            .until
9082            .as_deref()
9083            .map(|s| Active::parse_bound(s, self.tz))
9084            .transpose()
9085            .map_err(|e| e.replace("active:", "freeze:"))?;
9086        if let (Some(f), Some(u)) = (from, until) {
9087            if f >= u {
9088                return Err(format!(
9089                    "freeze.from ({}) must be strictly before freeze.until ({})",
9090                    self.from.as_deref().unwrap_or_default(),
9091                    self.until.as_deref().unwrap_or_default(),
9092                ));
9093            }
9094        }
9095        Ok(())
9096    }
9097}
9098
9099/// The system-generated poll cadence every reconcile-shaped `when`
9100/// lowers to. Operators never write this: the real inter-run
9101/// spacing is the `every` cooldown; this only bounds "how soon do
9102/// we notice somebody is due" (#418 decision B took the poll
9103/// period away from the operator).
9104pub const POLL_CRON: &str = "0 * * * * *";
9105
9106/// What a [`When`] lowers to — the exact (cron, mode, cooldown)
9107/// trio the pre-#418 engine ran on. Keeping the engine vocabulary
9108/// unchanged is what lets Phase 1 swap the operator surface without
9109/// touching the tick / dedup machinery.
9110pub struct Lowered {
9111    /// Cron handed to `tokio-cron-scheduler` — [`POLL_CRON`] for
9112    /// reconcile shapes, a 6/7-field cron for calendar shapes.
9113    pub cron: String,
9114    /// Dedup semantics for `decide_fire`.
9115    pub mode: ExecMode,
9116    /// Humantime re-arm interval (`None` = succeed once, skip
9117    /// forever).
9118    pub cooldown: Option<String>,
9119    /// Timezone to evaluate `cron` in (#418 Phase 2). The scheduler
9120    /// passes this to `Job::new_async_tz`. Reconcile shapes carry
9121    /// the schedule's tz too even though POLL_CRON is tz-agnostic,
9122    /// so the same value drives the `active`-window check.
9123    pub tz: ScheduleTz,
9124}
9125
9126impl Schedule {
9127    /// The error message if this schedule's `constraints.window` is
9128    /// set but unparseable, else `None`. The scheduler logs this at
9129    /// register time so a fail-closed (never-firing) schedule from a
9130    /// hand-edited KV blob is diagnosable (gemini #452 review).
9131    pub fn bad_window(&self) -> Option<String> {
9132        let w = self.constraints.window.as_deref()?;
9133        Constraints::parse_window(w).err()
9134    }
9135
9136    /// True when this is a `calendar` schedule whose fire time can
9137    /// never fall inside its `constraints.window` — the cron fires,
9138    /// the window check rejects it, and (firing only at that
9139    /// time-of-day) it effectively never runs. An easy misconfig to
9140    /// set up by accident; the scheduler warns at register time
9141    /// (claude #452 review). Reconcile shapes poll every minute, so
9142    /// they always catch the window opening and aren't affected.
9143    pub fn calendar_outside_window(&self) -> bool {
9144        let When::Calendar(c) = &self.when else {
9145            return false;
9146        };
9147        let Some(t) = c.fire_time() else {
9148            return false;
9149        };
9150        matches!(self.constraints.window_contains(t), Some(false))
9151    }
9152
9153    /// Up to `count` future instants this schedule will fire, as
9154    /// absolute UTC, strictly after `now` — the dry-run / preview
9155    /// surface (#418 "ドライラン / プレビュー"). Only **calendar**
9156    /// schedules have discrete fire times; reconcile shapes
9157    /// (`per_pc`/`per_target`) poll every minute gated by cooldown, so
9158    /// they return an empty vec and the caller describes the cadence
9159    /// instead. Occurrences outside the `active.{from,until}` window or
9160    /// the `constraints.window` are **skipped**, so the list reflects
9161    /// when the schedule will ACTUALLY run, not the raw cron ticks.
9162    /// Evaluated in the schedule's `tz`, exactly like the scheduler's
9163    /// `Job::new_async_tz`, and with the same croner config the
9164    /// scheduler / [`Schedule::validate`] use, so a preview can never
9165    /// disagree with a real fire. A schedule that can never fire (a
9166    /// calendar time wholly outside its window, a past one-shot,
9167    /// `enabled: false` is *not* considered here — callers gate on
9168    /// `enabled` separately) yields an empty vec.
9169    pub fn preview_fires(
9170        &self,
9171        now: chrono::DateTime<chrono::Utc>,
9172        count: usize,
9173    ) -> Vec<chrono::DateTime<chrono::Utc>> {
9174        use croner::parser::{CronParser, Seconds};
9175        if !matches!(self.when, When::Calendar(_)) {
9176            return Vec::new();
9177        }
9178        // Same lowering + croner config as `next_calendar_fire` and the
9179        // live scheduler, so a preview can never disagree with a real
9180        // fire. `preview_fires` adds the N-occurrence walk and the
9181        // active / window filtering on top of that single seam.
9182        let lowered = self.lowered();
9183        let Ok(cron) = CronParser::builder()
9184            .seconds(Seconds::Required)
9185            .dom_and_dow(true)
9186            .build()
9187            .parse(&lowered.cron)
9188        else {
9189            return Vec::new();
9190        };
9191        let accept = |utc: chrono::DateTime<chrono::Utc>| {
9192            self.active.contains(utc, self.tz) && self.constraints.allows(utc, self.tz)
9193        };
9194        match self.tz {
9195            ScheduleTz::Utc => Self::next_occurrences(&cron, now, count, accept),
9196            ScheduleTz::Local => {
9197                Self::next_occurrences(&cron, now.with_timezone(&chrono::Local), count, accept)
9198            }
9199        }
9200    }
9201
9202    /// Walk croner forward from `after` collecting up to `count`
9203    /// accepted occurrences (converted to UTC). Generic over the tz the
9204    /// cron is evaluated in so `preview_fires` can run it in either
9205    /// `Utc` or `Local` without duplicating the loop.
9206    fn next_occurrences<Tz>(
9207        cron: &croner::Cron,
9208        after: chrono::DateTime<Tz>,
9209        count: usize,
9210        accept: impl Fn(chrono::DateTime<chrono::Utc>) -> bool,
9211    ) -> Vec<chrono::DateTime<chrono::Utc>>
9212    where
9213        Tz: chrono::TimeZone,
9214    {
9215        // Bound the scan so an `active`/window dead-end (every future
9216        // tick rejected) can't spin forever: ~4096 raw ticks covers
9217        // >10y of a daily calendar while staying instant for croner.
9218        const SCAN_CAP: usize = 4096;
9219        let mut out = Vec::with_capacity(count.min(SCAN_CAP));
9220        let mut cursor = after;
9221        let mut scanned = 0usize;
9222        while out.len() < count && scanned < SCAN_CAP {
9223            scanned += 1;
9224            let Ok(next) = cron.find_next_occurrence(&cursor, false) else {
9225                break;
9226            };
9227            let utc = next.with_timezone(&chrono::Utc);
9228            if accept(utc) {
9229                out.push(utc);
9230            }
9231            // `find_next_occurrence(.., inclusive = false)` already
9232            // advances strictly past `cursor`, so handing it `next`
9233            // verbatim gets the following occurrence — no manual +1s
9234            // nudge (and `DateTime<Tz>` is `Copy`, so no clone).
9235            cursor = next;
9236        }
9237        out
9238    }
9239
9240    /// Lower the operator-facing `when` onto the engine vocabulary.
9241    /// Single seam shared by the backend scheduler and the agent's
9242    /// local scheduler so the two can never drift.
9243    pub fn lowered(&self) -> Lowered {
9244        let tz = self.tz;
9245        match &self.when {
9246            When::PerPc(p) => Lowered {
9247                cron: POLL_CRON.into(),
9248                // `once_per_version` re-arms each pc when the manifest
9249                // version changes; the scheduler keys that dedup on
9250                // `execution_results.version`. Plain `once` / `every`
9251                // stay version-blind.
9252                mode: match p {
9253                    PerPolicy::OncePerVersion(_) => ExecMode::OncePerPcVersion,
9254                    PerPolicy::Once(_) | PerPolicy::Every(_) => ExecMode::OncePerPc,
9255                },
9256                cooldown: p.cooldown(),
9257                tz,
9258            },
9259            When::PerTarget(p) => Lowered {
9260                cron: POLL_CRON.into(),
9261                mode: ExecMode::OncePerTarget,
9262                cooldown: p.cooldown(),
9263                tz,
9264            },
9265            // `to_cron` only fails on a malformed `at` (rejected by
9266            // validate() at create time). For a hand-edited KV blob
9267            // that slipped past, emit a deliberately-invalid cron so
9268            // register()'s Job::new_async_tz fails → warn+skip,
9269            // rather than firing at the wrong time.
9270            When::Calendar(c) => Lowered {
9271                cron: c
9272                    .to_cron()
9273                    .unwrap_or_else(|_| "# invalid calendar at".into()),
9274                mode: ExecMode::EveryTick,
9275                cooldown: None,
9276                tz,
9277            },
9278            // Event triggers have no cron — the agent fires them from an
9279            // OS event source. The `# event-trigger` cron is never
9280            // registered (the scheduler branches on `is_event()` first),
9281            // but keep it deliberately-invalid as a belt-and-suspenders
9282            // so a stray registration would fail rather than misfire.
9283            When::On(_) => Lowered {
9284                cron: "# event-trigger (no cron)".into(),
9285                mode: ExecMode::Event,
9286                cooldown: None,
9287                tz,
9288            },
9289        }
9290    }
9291
9292    /// True when this schedule fires from an OS event (`when: { on }`)
9293    /// rather than a clock — the agent skips `tokio-cron` registration
9294    /// for these and drives them from boot / session-change instead.
9295    pub fn is_event(&self) -> bool {
9296        matches!(self.when, When::On(_))
9297    }
9298
9299    /// The OS event triggers this schedule listens for, or `&[]` when it
9300    /// is not an event schedule.
9301    pub fn event_triggers(&self) -> &[OnTrigger] {
9302        match &self.when {
9303            When::On(t) => t,
9304            _ => &[],
9305        }
9306    }
9307
9308    /// The next absolute (UTC) time this schedule fires, or `None` when
9309    /// it has no discrete upcoming fire to preview.
9310    ///
9311    /// Used by the KLP `maintenance.list` preview ("what's about to
9312    /// happen on my PC", SPEC §2.1). Returns `None` for:
9313    ///
9314    /// - reconcile shapes (`per_pc` / `per_target`) — they lower to the
9315    ///   every-minute [`POLL_CRON`] and re-converge state continuously,
9316    ///   so "next fire" is always ~60s away and means nothing to a user
9317    ///   previewing upcoming maintenance;
9318    /// - a calendar schedule whose lowered cron won't parse (a
9319    ///   hand-edited KV blob that slipped past [`Schedule::validate`]);
9320    /// - a cron with no future occurrence.
9321    ///
9322    /// The wall-clock fire is evaluated in the schedule's own `tz`
9323    /// (matching the live tick's `Job::new_async_tz`) then normalised
9324    /// to UTC for the wire. `inclusive = false`: strictly the *next*
9325    /// fire after `now`, never one matching the current instant.
9326    pub fn next_calendar_fire(
9327        &self,
9328        now: chrono::DateTime<chrono::Utc>,
9329    ) -> Option<chrono::DateTime<chrono::Utc>> {
9330        if !matches!(self.when, When::Calendar(_)) {
9331            return None;
9332        }
9333        let lowered = self.lowered();
9334        // Same parser configuration tokio-cron-scheduler 0.15 uses
9335        // internally, so this can never compute a fire the live
9336        // scheduler wouldn't (seconds required, DOM-and-DOW honored).
9337        let cron = croner::parser::CronParser::builder()
9338            .seconds(croner::parser::Seconds::Required)
9339            .dom_and_dow(true)
9340            .build()
9341            .parse(&lowered.cron)
9342            .ok()?;
9343        match lowered.tz {
9344            ScheduleTz::Utc => cron.find_next_occurrence(&now, false).ok(),
9345            ScheduleTz::Local => {
9346                let now_local = now.with_timezone(&chrono::Local);
9347                cron.find_next_occurrence(&now_local, false)
9348                    .ok()
9349                    .map(|t| t.with_timezone(&chrono::Utc))
9350            }
9351        }
9352    }
9353
9354    /// Cross-field semantic checks that don't fit pure serde derive
9355    /// — the [`Manifest::validate`] counterpart (#418 decision F;
9356    /// pre-Phase-1 a broken schedule was accepted at create time
9357    /// and silently warn-skipped at tick time). Run at every create
9358    /// site: `kanade schedule create` (client-side) and
9359    /// `POST /api/schedules`. The job_id-exists check lives in the
9360    /// API handler instead — it needs the JOBS KV.
9361    pub fn validate(&self) -> Result<(), String> {
9362        for pc in &self.plan.target.pcs {
9363            crate::subject::validate_pc_id(pc)?;
9364        }
9365        if matches!(self.runs_on, RunsOn::Agent) && matches!(self.when, When::PerTarget(_)) {
9366            return Err(
9367                "when.per_target needs fleet-wide completion data and is backend-only; \
9368                 it cannot be combined with runs_on: agent (each agent self-schedules, \
9369                 so per-target dedup would be deduping across a target of 1)"
9370                    .into(),
9371            );
9372        }
9373        // `once_per_version` is a per_pc-only shape: it re-arms an
9374        // individual pc when the manifest version it succeeded at is no
9375        // longer current. "One delegate per version" for a whole target
9376        // has no clear meaning, so reject it rather than silently
9377        // lowering to plain per_target (version-blind).
9378        if matches!(self.when, When::PerTarget(PerPolicy::OncePerVersion(_))) {
9379            return Err(
9380                "when.per_target: once_per_version is not supported — once_per_version \
9381                 re-arms per pc per manifest version, which only makes sense for per_pc. \
9382                 Use `per_pc: once_per_version`."
9383                    .into(),
9384            );
9385        }
9386        // `once_per_version` keys its dedup on the backend's
9387        // `execution_results.version` history. A runs_on: agent schedule
9388        // self-schedules from the agent's local completion map, which has
9389        // no per-version record, so it is backend-only (symmetric with
9390        // per_target). Reject it rather than silently degrade to
9391        // version-blind kitting-once on the agent.
9392        if matches!(self.runs_on, RunsOn::Agent)
9393            && matches!(self.when, When::PerPc(PerPolicy::OncePerVersion(_)))
9394        {
9395            return Err(
9396                "when.per_pc: once_per_version keys its dedup on the backend's per-version \
9397                 completion history and is backend-only; it cannot be combined with \
9398                 runs_on: agent (the agent self-schedules with no per-version record). \
9399                 Use runs_on: backend."
9400                    .into(),
9401            );
9402        }
9403        // #418 event triggers: the agent owns the OS event source
9404        // (boot / session-change), so `when: { on }` is agent-only and
9405        // needs at least one trigger.
9406        if let When::On(triggers) = &self.when {
9407            if !matches!(self.runs_on, RunsOn::Agent) {
9408                return Err(
9409                    "when.on (OS event trigger) is fired by the agent's own event \
9410                     source, so it requires runs_on: agent"
9411                        .into(),
9412                );
9413            }
9414            if triggers.is_empty() {
9415                return Err(
9416                    "when.on must list at least one trigger (e.g. [startup, logon])".into(),
9417                );
9418            }
9419        }
9420        if let Some(cd) = self.lowered().cooldown.as_deref() {
9421            humantime::parse_duration(cd)
9422                .map_err(|e| format!("when.every: invalid duration '{cd}': {e}"))?;
9423        }
9424        if let When::Calendar(c) = &self.when {
9425            // Lower the calendar form to its cron (catches a bad `at`
9426            // and the date+days conflict), then validate that cron
9427            // with the same parser configuration tokio-cron-scheduler
9428            // 0.15 uses internally (croner, seconds required,
9429            // DOM-and-DOW both honored, year optional) — create-time
9430            // validation can never accept what register() rejects.
9431            let cron = c.to_cron()?;
9432            croner::parser::CronParser::builder()
9433                .seconds(croner::parser::Seconds::Required)
9434                .dom_and_dow(true)
9435                .build()
9436                .parse(&cron)
9437                .map_err(|e| format!("when.at lowered to invalid cron '{cron}': {e}"))?;
9438        }
9439        // The other humantime strings on the schedule (claude #419
9440        // review): runtime degrades gracefully on both (bad jitter →
9441        // silent no-op, bad starting_deadline → warn + skipped tick),
9442        // but "rejected at create time" should cover every field the
9443        // operator can typo, not just `when`.
9444        if let Some(j) = &self.plan.jitter {
9445            humantime::parse_duration(j)
9446                .map_err(|e| format!("jitter: invalid duration '{j}': {e}"))?;
9447        }
9448        if let Some(sd) = &self.starting_deadline {
9449            humantime::parse_duration(sd)
9450                .map_err(|e| format!("starting_deadline: invalid duration '{sd}': {e}"))?;
9451        }
9452        // #917: the plan side got almost no create-time checks, so
9453        // several never-fires / fails-every-tick shapes were accepted
9454        // and only surfaced at dispatch time — or never:
9455        //
9456        // (1) a target that dispatches nothing. A runs_on: agent
9457        // schedule matches each agent against `target` (rollout waves
9458        // are backend-published and never reach that path), so an
9459        // unspecified target silently never fires; a runs_on: backend
9460        // one warn-fails every tick at the exec boundary, which
9461        // rejects the same shape with the same message.
9462        let has_waves = self
9463            .plan
9464            .rollout
9465            .as_ref()
9466            .is_some_and(|r| !r.waves.is_empty());
9467        if matches!(self.runs_on, RunsOn::Agent) {
9468            if !self.plan.target.is_specified() {
9469                return Err(
9470                    "target must specify at least one of `all` / `groups` / `pcs` — a \
9471                     runs_on: agent schedule matches each agent against `target`, so an \
9472                     unspecified target never fires anywhere"
9473                        .into(),
9474                );
9475            }
9476            if self.plan.rollout.is_some() {
9477                return Err(
9478                    "rollout waves are published by the backend and are ignored by \
9479                     runs_on: agent schedules (each agent self-schedules from `target`); \
9480                     drop `rollout:` or use runs_on: backend"
9481                        .into(),
9482                );
9483            }
9484        } else if !has_waves && !self.plan.target.is_specified() {
9485            return Err(
9486                "target must specify at least one of `all` / `groups` / `pcs` \
9487                 (or set `rollout.waves`) — the exec boundary rejects an \
9488                 unspecified target, so the schedule would fail every tick"
9489                    .into(),
9490            );
9491        }
9492        // (2) rollout waves were never validated: a blank group or an
9493        // unparseable delay failed at EVERY fire (the CLI doesn't even
9494        // expose waves, so the failure was always deferred to dispatch)
9495        // and an empty list dispatched nothing. (3) A wave delayed to
9496        // or past starting_deadline is dead on arrival: the deadline is
9497        // stamped once at tick time and the Command is serialised
9498        // before the wave sleep, so agents receive it already expired
9499        // (a synthetic exit-125 skip on every fire).
9500        if let Some(rollout) = &self.plan.rollout {
9501            if rollout.waves.is_empty() {
9502                return Err(
9503                    "rollout.waves must list at least one wave; omit `rollout:` for a \
9504                     one-shot fan-out of `target`"
9505                        .into(),
9506                );
9507            }
9508            let deadline = self
9509                .starting_deadline
9510                .as_deref()
9511                .and_then(|sd| humantime::parse_duration(sd).ok());
9512            for (i, wave) in rollout.waves.iter().enumerate() {
9513                if wave.group.trim().is_empty() {
9514                    return Err(format!("rollout.waves[{i}].group must not be blank"));
9515                }
9516                let delay = humantime::parse_duration(&wave.delay).map_err(|e| {
9517                    format!(
9518                        "rollout.waves[{i}].delay: invalid duration '{}': {e}",
9519                        wave.delay
9520                    )
9521                })?;
9522                if let Some(deadline) = deadline
9523                    && delay >= deadline
9524                {
9525                    return Err(format!(
9526                        "rollout.waves[{i}].delay ('{}') must be shorter than \
9527                         starting_deadline ('{}'): the deadline is stamped at tick time, \
9528                         so this wave's Commands would already be expired when published \
9529                         (skipped by every agent, every fire)",
9530                        wave.delay,
9531                        self.starting_deadline.as_deref().unwrap_or_default(),
9532                    ));
9533                }
9534            }
9535        }
9536        // (4) deadline_at is machine-stamped: the scheduler overwrites
9537        // it from `tick + starting_deadline` on every fire, so an
9538        // operator-set value is silently discarded — reject it and
9539        // point at the knob that does what they meant. (Ad-hoc POST
9540        // /api/exec bodies are a different write path and may still
9541        // carry it.)
9542        if self.plan.deadline_at.is_some() {
9543            return Err(
9544                "deadline_at is computed by the scheduler (tick time + starting_deadline) \
9545                 and overwritten on every fire — set `starting_deadline` instead"
9546                    .into(),
9547            );
9548        }
9549        let from = self
9550            .active
9551            .from
9552            .as_deref()
9553            .map(|s| Active::parse_bound(s, self.tz))
9554            .transpose()?;
9555        let until = self
9556            .active
9557            .until
9558            .as_deref()
9559            .map(|s| Active::parse_bound(s, self.tz))
9560            .transpose()?;
9561        if let (Some(f), Some(u)) = (from, until) {
9562            if f >= u {
9563                return Err(format!(
9564                    "active.from ({}) must be strictly before active.until ({})",
9565                    self.active.from.as_deref().unwrap_or_default(),
9566                    self.active.until.as_deref().unwrap_or_default(),
9567                ));
9568            }
9569        }
9570        // #418 Phase 3: a bad maintenance window is rejected at create
9571        // time (parse_window also catches equal bounds).
9572        if let Some(w) = self.constraints.window.as_deref() {
9573            Constraints::parse_window(w)?;
9574        }
9575        // #418 holiday exclusion: reject a malformed skip date at create
9576        // time so the fail-closed `allows` path only ever bites a
9577        // hand-edited KV blob, not a fresh `kanade schedule create`.
9578        if let Some(err) = self.constraints.bad_skip_date() {
9579            return Err(err);
9580        }
9581        // #418: constraints.max_concurrent is a central running-instance
9582        // cap, so it needs the backend's counter — reject it on
9583        // runs_on: agent (decision E), and reject a meaningless 0.
9584        if let Some(mc) = self.constraints.max_concurrent {
9585            // Check the structural incompatibility (agent has no central
9586            // counter) before the value range, so a `max_concurrent: 0`
9587            // + `runs_on: agent` combo reports the more fundamental
9588            // problem first (claude #542).
9589            if matches!(self.runs_on, RunsOn::Agent) {
9590                return Err(
9591                    "constraints.max_concurrent needs a central counter and is backend-only; \
9592                     it cannot be combined with runs_on: agent (each agent self-schedules, \
9593                     so there is no fleet-wide count to cap against)"
9594                        .into(),
9595                );
9596            }
9597            if mc == 0 {
9598                return Err(
9599                    "constraints.max_concurrent must be >= 1 (0 would never fire; \
9600                     omit it for no cap)"
9601                        .into(),
9602                );
9603            }
9604        }
9605        // #418: constraints.require (host-state env gates: ac_power /
9606        // idle / cpu_below / network) is sensed in-process by the agent,
9607        // so it needs runs_on: agent — the backend can't read a target
9608        // host's power / idle / cpu / connectivity state. Symmetric with
9609        // `when: { on }` (also agent-only); inverse of max_concurrent
9610        // (backend-only).
9611        if let Some(req) = &self.constraints.require {
9612            if !req.is_empty() && matches!(self.runs_on, RunsOn::Backend) {
9613                return Err(
9614                    "constraints.require (host-state env gates: ac_power / idle / cpu_below / \
9615                     network) is sensed in-process by the agent and needs runs_on: agent; the \
9616                     backend cannot read a target host's power / idle / cpu / connectivity state"
9617                        .into(),
9618                );
9619            }
9620            // Reject a malformed idle duration at create time so the
9621            // fail-closed runtime path only ever bites a hand-edited
9622            // KV blob (mirror skip_dates / on_failure.retry).
9623            if let Some(err) = req.bad_idle() {
9624                return Err(err);
9625            }
9626            // cpu_below is a percent — reject out-of-range so a typo
9627            // can't make a schedule that never (>=100 is always-busy?
9628            // no — <0 never matches) or trivially fires.
9629            if let Some(c) = req.cpu_below
9630                && !(c > 0.0 && c <= 100.0)
9631            {
9632                return Err(format!(
9633                    "constraints.require.cpu_below must be in (0, 100] percent (got {c}); \
9634                     omit it for no CPU requirement"
9635                ));
9636            }
9637        }
9638        // #418 Phase 4: a bad on_failure.retry is rejected at create
9639        // time — backoff must be valid humantime, and max is bounded
9640        // so a typo can't pin a flapping script in a tight loop.
9641        if let Some(r) = &self.on_failure.retry {
9642            let backoff = humantime::parse_duration(&r.backoff).map_err(|e| {
9643                format!(
9644                    "on_failure.retry.backoff: invalid duration '{}': {e}",
9645                    r.backoff
9646                )
9647            })?;
9648            // The wire form lowers backoff to whole seconds, so a
9649            // sub-second value would silently become a 0s no-wait
9650            // (coderabbit #466). Reject it rather than honour a backoff
9651            // the operator can't actually get.
9652            if backoff.as_secs() < 1 {
9653                return Err(format!(
9654                    "on_failure.retry.backoff must be >= 1s (got '{}'); sub-second backoffs \
9655                     round to 0 on the wire",
9656                    r.backoff
9657                ));
9658            }
9659            if !(1..=10).contains(&r.max) {
9660                return Err(format!(
9661                    "on_failure.retry.max must be 1..=10 (got {}); it counts additional \
9662                     attempts after the first run",
9663                    r.max
9664                ));
9665            }
9666        }
9667        // A blank / whitespace-only tag renders an empty filter chip on
9668        // the Schedules page — reject it at create time, mirroring the
9669        // Manifest::validate tag guard.
9670        for tag in &self.tags {
9671            if tag.trim().is_empty() {
9672                return Err("tags must not contain empty entries".to_string());
9673            }
9674        }
9675        Ok(())
9676    }
9677}
9678
9679/// Shared `serde(default)` for `bool` fields that default to `true`
9680/// (e.g. `CheckHint::fleet` / `CheckHint::health`). Generic name so it
9681/// doesn't read as "fleet" when reused for `health`.
9682fn default_true() -> bool {
9683    true
9684}