Skip to main content

kanade_shared/
manifest.rs

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