kanade_shared/wire/command.rs
1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3
4use super::Staleness;
5use crate::manifest::{CheckHint, EmitConfig};
6
7#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone)]
8pub struct Command {
9 pub id: String,
10 pub version: String,
11 pub request_id: String,
12 /// v0.29 / Issue #19: the deployment / scheduler-fire UUID this
13 /// Command belongs to. Forwarded into `ExecResult.exec_id` by the
14 /// agent so the projector can attribute results back to the
15 /// originating `executions` row. `None` for ad-hoc `kanade run`
16 /// (no deployment row exists). Pre-v0.29 wire used the field name
17 /// `job_id` for this same value — `serde(alias)` keeps old
18 /// publishes in STREAM_EXEC decodable across the upgrade window.
19 #[serde(alias = "job_id")]
20 pub exec_id: Option<String>,
21 pub shell: Shell,
22 /// Inline script body, OR empty when [`script_object`] is set.
23 /// Mutually exclusive with `script_object` at the wire level —
24 /// backend builders fill one or the other (never both) and the
25 /// agent's resolver picks the populated one. Pre-v0.43 wire
26 /// always carries this populated.
27 ///
28 /// [`script_object`]: Self::script_object
29 pub script: String,
30 /// SPEC §2.4.1 / yukimemi/kanade#210: Object Store reference
31 /// (`<name>/<version>` key into `OBJECT_SCRIPTS`). When set,
32 /// the agent fetches the body via `script_cache` and verifies
33 /// its sha256 against [`script_object_sha256`] before launching.
34 /// `None` ⇒ inline `script` carries the body (legacy + the
35 /// majority of jobs).
36 ///
37 /// [`script_object_sha256`]: Self::script_object_sha256
38 #[serde(default, skip_serializing_if = "Option::is_none")]
39 pub script_object: Option<String>,
40 /// Hex-encoded sha256 of the bytes the operator approved at
41 /// Command-build time. Required when [`script_object`] is set;
42 /// the agent treats a mismatch on fetch as "operator
43 /// re-uploaded the script between exec submission and agent
44 /// fire" and aborts the run rather than silently executing the
45 /// new bytes. Pre-v0.43 wire omits this; the resolver path
46 /// requires both fields to be `Some`.
47 ///
48 /// [`script_object`]: Self::script_object
49 #[serde(default, skip_serializing_if = "Option::is_none")]
50 pub script_object_sha256: Option<String>,
51 pub timeout_secs: u64,
52 pub jitter_secs: Option<u64>,
53 /// Which (token, session) combination the agent should launch the
54 /// child process under (v0.21). Defaults to [`RunAs::System`] for
55 /// back-compat with pre-v0.21 backends that don't send this field.
56 #[serde(default)]
57 pub run_as: RunAs,
58 /// Working directory for the spawned child (v0.21.1). `None` ⇒
59 /// inherit the agent's cwd. Pre-v0.21.1 wire payloads omit this
60 /// field and parse fine via `#[serde(default)]`.
61 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub cwd: Option<String>,
63 /// Absolute time after which the agent should refuse to run
64 /// this Command (v0.22). Set by the scheduler from
65 /// `Schedule.starting_deadline` (humantime) measured against
66 /// the cron tick time. `None` ⇒ no deadline, run whenever
67 /// received (default for ad-hoc `kanade exec` + back-compat
68 /// for pre-v0.22 wire). The agent stamps a synthetic
69 /// `ExecResult { exit_code: 125, stderr: "skipped: deadline
70 /// expired ..." }` when it skips, so the operator sees the
71 /// outcome on the Results / Dashboard pages instead of silence.
72 #[serde(default, skip_serializing_if = "Option::is_none")]
73 pub deadline_at: Option<DateTime<Utc>>,
74 /// v0.26: Manifest-declared Layer 2 staleness policy
75 /// (see SPEC.md §2.6.2). Forwarded from `Manifest.staleness` so
76 /// the agent can evaluate it at fire time without re-fetching the
77 /// Manifest from `BUCKET_JOBS`. Pre-v0.26 wire omits this and
78 /// `#[serde(default)]` falls back to `Staleness::Cached`, matching
79 /// pre-v0.26 behaviour (silently use cached KV values).
80 #[serde(default)]
81 pub staleness: Staleness,
82 /// Issue #246: forwarded from `Manifest.emit` so the agent
83 /// doesn't have to re-fetch the manifest at fire time. When
84 /// `Some` and `EmitKind::Events`, the agent parses script
85 /// stdout as NDJSON `ObsEvent` and publishes each line on
86 /// `obs.<pc_id>`. Pre-#246 wire omits this; the `#[serde(default)]`
87 /// fallback to `None` preserves prior behaviour (stdout flows
88 /// to `ExecResult` unchanged).
89 #[serde(default, skip_serializing_if = "Option::is_none")]
90 pub emit: Option<EmitConfig>,
91 /// #290: forwarded from `Manifest.check` so the agent can build a
92 /// KLP Health-tab [`Check`](crate::ipc::state::Check) from the
93 /// job's stdout without re-fetching the Manifest. When `Some`, the
94 /// agent reads the `status_field` / `detail_field` values out of
95 /// the stdout JSON object after a successful run and caches the
96 /// result into `StateSnapshot.checks`. Pre-#290 wire omits this;
97 /// `#[serde(default)]` → `None` preserves prior behaviour.
98 #[serde(default, skip_serializing_if = "Option::is_none")]
99 pub check: Option<CheckHint>,
100}
101
102#[derive(Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
103#[serde(rename_all = "lowercase")]
104pub enum Shell {
105 Powershell,
106 Cmd,
107}
108
109/// **Token + session combination** the agent uses to spawn a job's
110/// child process. Two orthogonal axes — *whose privileges* and *which
111/// session* — collapse into three meaningful combinations:
112///
113/// | variant | session | privileges | GUI |
114/// |--------------------|------------------------|-------------|-----|
115/// | `System` (default) | Session 0 (services) | LocalSystem | ❌ |
116/// | `User` | active console session | logged-in user (UAC-filtered when admin) | ✅ |
117/// | `SystemGui` | active console session | LocalSystem | ✅ |
118///
119/// `SystemGui` is the "PsExec `-i -s`" pattern: the agent duplicates
120/// its own SYSTEM token and rewrites `TokenSessionId` to the user's
121/// console session, then launches with that hybrid token — useful
122/// when an installer needs admin power *and* needs the user to see
123/// its UI.
124#[derive(
125 Serialize, Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default,
126)]
127#[serde(rename_all = "snake_case")]
128pub enum RunAs {
129 /// LocalSystem privileges in Session 0. No GUI. Historical
130 /// default — every pre-v0.21 job ran this way.
131 #[default]
132 System,
133 /// The currently-logged-in console user's identity, in their
134 /// session. Can write HKCU / %APPDATA% / show GUI to the user.
135 /// Privileges are whatever the user has (admin users get the
136 /// UAC-filtered limited token, not the elevated one).
137 User,
138 /// LocalSystem privileges in the user's session — admin power
139 /// with GUI visibility. Niche but real (force-restart dialogs,
140 /// admin installers with progress UI).
141 SystemGui,
142}
143
144#[cfg(test)]
145mod tests {
146 use super::*;
147
148 fn sample_command() -> Command {
149 Command {
150 id: "echo-test".into(),
151 version: "1.0.0".into(),
152 request_id: "req-1".into(),
153 exec_id: Some("dep-1".into()),
154 shell: Shell::Powershell,
155 script: "echo hi".into(),
156 script_object: None,
157 script_object_sha256: None,
158 timeout_secs: 30,
159 jitter_secs: Some(5),
160 run_as: RunAs::System,
161 cwd: None,
162 deadline_at: None,
163 staleness: Staleness::Cached,
164 emit: None,
165 check: None,
166 }
167 }
168
169 #[test]
170 fn shell_serialises_lowercase() {
171 let json = serde_json::to_string(&Shell::Powershell).unwrap();
172 assert_eq!(json, "\"powershell\"");
173 let json = serde_json::to_string(&Shell::Cmd).unwrap();
174 assert_eq!(json, "\"cmd\"");
175 }
176
177 #[test]
178 fn run_as_serialises_snake_case() {
179 for (mode, expected) in [
180 (RunAs::System, "\"system\""),
181 (RunAs::User, "\"user\""),
182 (RunAs::SystemGui, "\"system_gui\""),
183 ] {
184 let json = serde_json::to_string(&mode).unwrap();
185 assert_eq!(json, expected, "serialise {mode:?}");
186 let back: RunAs = serde_json::from_str(expected).unwrap();
187 assert_eq!(back, mode, "round-trip {expected}");
188 }
189 }
190
191 #[test]
192 fn run_as_defaults_to_system() {
193 assert_eq!(RunAs::default(), RunAs::System);
194 }
195
196 #[test]
197 fn command_round_trips_through_json() {
198 let orig = sample_command();
199 let json = serde_json::to_string(&orig).expect("encode");
200 let decoded: Command = serde_json::from_str(&json).expect("decode");
201 assert_eq!(decoded.id, orig.id);
202 assert_eq!(decoded.version, orig.version);
203 assert_eq!(decoded.request_id, orig.request_id);
204 assert_eq!(decoded.exec_id, orig.exec_id);
205 assert_eq!(decoded.shell, orig.shell);
206 assert_eq!(decoded.script, orig.script);
207 assert_eq!(decoded.timeout_secs, orig.timeout_secs);
208 assert_eq!(decoded.jitter_secs, orig.jitter_secs);
209 assert_eq!(decoded.run_as, orig.run_as);
210 }
211
212 #[test]
213 fn command_round_trips_each_run_as_variant() {
214 for mode in [RunAs::System, RunAs::User, RunAs::SystemGui] {
215 let cmd = Command {
216 run_as: mode,
217 ..sample_command()
218 };
219 let json = serde_json::to_string(&cmd).unwrap();
220 let back: Command = serde_json::from_str(&json).unwrap();
221 assert_eq!(back.run_as, mode);
222 }
223 }
224
225 #[test]
226 fn command_accepts_missing_optional_fields() {
227 let json = r#"{
228 "id": "x",
229 "version": "1.0.0",
230 "request_id": "r",
231 "shell": "cmd",
232 "script": "echo",
233 "timeout_secs": 5
234 }"#;
235 let cmd: Command = serde_json::from_str(json).expect("decode");
236 assert!(cmd.exec_id.is_none());
237 assert!(cmd.jitter_secs.is_none());
238 assert_eq!(cmd.shell, Shell::Cmd);
239 // Pre-v0.21 wire payloads omit run_as → falls back to System.
240 assert_eq!(cmd.run_as, RunAs::System);
241 // Pre-v0.21.1 omit cwd → None (= inherit agent cwd).
242 assert!(cmd.cwd.is_none());
243 // Pre-v0.22 omit deadline_at → None (= no deadline).
244 assert!(cmd.deadline_at.is_none());
245 // Pre-v0.43 wire omits both script_object fields — agent
246 // falls back to the inline `script` body.
247 assert!(cmd.script_object.is_none());
248 assert!(cmd.script_object_sha256.is_none());
249 }
250
251 #[test]
252 fn command_round_trips_script_object_fields() {
253 // yukimemi/kanade#210: backend builds Commands carrying an
254 // OBJECT_SCRIPTS reference + the operator-approved digest;
255 // agent resolves on fetch. Both fields must survive a JSON
256 // round-trip with the same shape.
257 let cmd = Command {
258 script: String::new(),
259 script_object: Some("cleanup-disk-temp/1.0.1".into()),
260 script_object_sha256: Some(
261 "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".into(),
262 ),
263 ..sample_command()
264 };
265 let json = serde_json::to_string(&cmd).expect("encode");
266 let back: Command = serde_json::from_str(&json).expect("decode");
267 assert_eq!(back.script, "");
268 assert_eq!(
269 back.script_object.as_deref(),
270 Some("cleanup-disk-temp/1.0.1")
271 );
272 assert_eq!(
273 back.script_object_sha256.as_deref(),
274 Some("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef")
275 );
276 }
277
278 #[test]
279 fn command_decodes_legacy_job_id_field_as_exec_id() {
280 // v0.29 / Issue #19: Commands sitting in STREAM_EXEC published
281 // by a pre-v0.29 backend still carry the field named `job_id`.
282 // The `#[serde(alias = "job_id")]` on `exec_id` keeps them
283 // decodable through the upgrade window so the agent doesn't
284 // start dropping replays on first boot of a new binary.
285 let json = r#"{
286 "id": "x",
287 "version": "1.0.0",
288 "request_id": "r",
289 "job_id": "legacy-exec-uuid",
290 "shell": "powershell",
291 "script": "echo",
292 "timeout_secs": 5
293 }"#;
294 let cmd: Command = serde_json::from_str(json).expect("decode legacy");
295 assert_eq!(cmd.exec_id.as_deref(), Some("legacy-exec-uuid"));
296 }
297
298 #[test]
299 fn command_deadline_at_round_trips() {
300 use chrono::TimeZone;
301 let deadline = Utc.with_ymd_and_hms(2026, 5, 18, 9, 30, 0).unwrap();
302 let cmd = Command {
303 deadline_at: Some(deadline),
304 ..sample_command()
305 };
306 let json = serde_json::to_string(&cmd).unwrap();
307 let back: Command = serde_json::from_str(&json).unwrap();
308 assert_eq!(back.deadline_at, Some(deadline));
309 }
310}