Skip to main content

sysknife_types/
lib.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3use std::convert::TryFrom;
4
5use sysknife_proto::sysknife::v1 as proto;
6
7// ---------------------------------------------------------------------------
8// Framing / wire protocol
9// ---------------------------------------------------------------------------
10
11/// Maximum size of a single message exchanged over a sysknife socket, in bytes
12/// (4 MiB).
13///
14/// As a wire fact, the frame limit belongs to the protocol crate that every
15/// side already depends on, rather than to any one executor (the daemon), so
16/// that the daemon and the CLI agree on it without a dependency edge from a
17/// consumer up to a privileged producer. Duplicate declarations of the limit
18/// elsewhere are guarded against by `tests::frame_limit_is_declared_once`.
19pub const MAX_MESSAGE_BYTES: usize = 4 * 1024 * 1024;
20
21// ---------------------------------------------------------------------------
22// DistroHint — planner-facing snapshot of the running distro
23// ---------------------------------------------------------------------------
24
25/// Planner-facing distro snapshot injected into the system prompt.
26///
27/// This is a deliberately lightweight type: it captures only what the planner
28/// needs to pick the right action family (`family`), distinguish Ubuntu-only
29/// mechanisms (`id`), and produce human-readable output (`version`). Detection and the full
30/// `DistroId` enum stay in `sysknife-core`; the CLI converts `DistroId` →
31/// `DistroHint` at startup so the brain never depends on `sysknife-core`.
32///
33/// # Design rationale
34///
35/// Moving `DistroId` to `sysknife-types` would add proto-bridge boilerplate
36/// and force every crate that imports types to compile the detection logic.
37/// A thin snapshot type is smaller-diff and still gives the planner everything
38/// it needs.
39#[derive(Clone, Debug, PartialEq, Eq)]
40pub struct DistroHint {
41    /// Detected distribution ID, e.g. `ubuntu` or `debian`. Family membership
42    /// alone cannot authorize an Ubuntu-only mechanism. Never derive this from
43    /// the human-readable version string.
44    pub id: String,
45    /// Broad distro family: `"fedora"`, `"debian"`, or `"other"`.
46    ///
47    /// Use `DISTRO_FAMILY_FEDORA`, `DISTRO_FAMILY_DEBIAN`, and
48    /// `DISTRO_FAMILY_OTHER` for comparison to avoid magic strings.
49    pub family: &'static str,
50    /// Human-readable version string, e.g. `"Fedora 41"`, `"Ubuntu 24.04"`.
51    /// `None` when the version could not be determined.
52    pub version: Option<String>,
53}
54
55/// Family label for Fedora-family distros (Fedora, FedoraSilverblue, etc.).
56pub const DISTRO_FAMILY_FEDORA: &str = "fedora";
57
58/// Family label for Debian-family distros (Ubuntu, Debian, etc.).
59pub const DISTRO_FAMILY_DEBIAN: &str = "debian";
60
61/// Family label for distros that do not fit into a known family.
62pub const DISTRO_FAMILY_OTHER: &str = "other";
63
64// ---------------------------------------------------------------------------
65// ActionName — validated action catalogue primitive
66// ---------------------------------------------------------------------------
67
68/// Canonical names of every action in the SysKnife catalogue.
69///
70/// This is the single source of truth for "is this string a valid action
71/// name?" — kept in `sysknife-types` (not `sysknife-brain`) so every crate
72/// that validates an action name (the daemon's `policy::min_role_for_action`,
73/// the CLI's approval flow, the proto bridge) sees the same list without
74/// depending on the brain.
75///
76/// Note: [`RequestEnvelope::action_name`] itself is a plain `String` — it is
77/// **not** validated against this list at deserialization time; that would
78/// require a custom `Deserialize` impl this type does not have. Validation
79/// happens downstream, via [`ActionName::parse`] against the value once it
80/// has been pulled out of the envelope (the daemon does this before acting
81/// on a request).
82///
83/// **Cross-module invariant:** `sysknife_brain::propose_plan::KNOWN_ACTIONS`
84/// (which pairs each name with an LLM-facing description) MUST list every
85/// name that appears here, in either order.  The brain has a unit test
86/// (`every_known_action_name_is_in_types`) that pins this — adding an
87/// action requires a coordinated update to both lists.
88pub const KNOWN_ACTION_NAMES: &[&str] = &[
89    "GetSystemState",
90    "CollectDiagnostics",
91    "GetDeploymentHistory",
92    "ListDeployments",
93    "UpdateSystem",
94    "CleanupDeployments",
95    "RebootSystem",
96    "RollbackDeployment",
97    "GetKernelArguments",
98    "PinDeployment",
99    "UnpinDeployment",
100    "RebaseSystem",
101    "SetKernelArguments",
102    "InstallFlatpak",
103    "RemoveFlatpak",
104    "UpdateFlatpak",
105    "SearchFlatpakApps",
106    "ListFlatpakRemotes",
107    "ListInstalledFlatpaks",
108    "AddFlatpakRemote",
109    "RemoveFlatpakRemote",
110    "GetFlatpakAppInfo",
111    "ListToolboxes",
112    "CreateToolbox",
113    "RemoveToolbox",
114    "GetLayeredPackages",
115    "ResetLayeredPackageOverride",
116    "GetPendingUpdates",
117    "InstallPackages",
118    "RemovePackages",
119    "AddLayeredPackage",
120    "RemoveLayeredPackage",
121    "ReplaceLayeredPackage",
122    "RemoveBasePackage",
123    "ListServices",
124    "ListTimers",
125    "ReloadDaemon",
126    "CreateScheduledJob",
127    "StartService",
128    "StopService",
129    "RestartService",
130    "ReloadService",
131    "SetServiceEnabled",
132    "MaskService",
133    "UnmaskService",
134    "GetServiceLogs",
135    "GetServiceStatus",
136    "GetServiceResourceLimits",
137    "SetServiceResourceLimits",
138    "GetFirewallState",
139    "GetNetworkStatus",
140    "GetListeningPorts",
141    "GetNftablesRuleset",
142    "GetFirewallBackendState",
143    "ConfigureWifi",
144    "SetDnsServers",
145    "ConfigureFirewall",
146    "GetDiskUsage",
147    "ListProcesses",
148    "SignalProcess",
149    "GetMemoryInfo",
150    "GetHostState",
151    // Observability / journald (cross-distro)
152    "GetJournalLog",
153    "VacuumJournal",
154    // Storage / LVM (cross-distro)
155    "GetLvmReport",
156    "ExtendLogicalVolume",
157    "CreateLogicalVolume",
158    "CreateLvSnapshot",
159    // Kernel / sysctl (cross-distro)
160    "GetSysctl",
161    "SetSysctl",
162    // Filesystem mounts / swap (cross-distro)
163    "GetMounts",
164    "AddMount",
165    "RemoveMount",
166    "AddSwap",
167    "RemoveSwap",
168    // Scoped sudoers.d (cross-distro)
169    "GetSudoGrants",
170    "GrantSudoAccess",
171    "RevokeSudoAccess",
172    // Log management (cross-distro)
173    "GetLogrotateStatus",
174    "ConfigureLogRotation",
175    "RemoveLogRotation",
176    "ConfigureRemoteSyslog",
177    "RemoveRemoteSyslog",
178    // PAM password policy (cross-distro)
179    "GetPasswordAging",
180    "SetPasswordAging",
181    "SetPasswordPolicy",
182    "SetAccountLockout",
183    // auditd file-watch rules (cross-distro)
184    "GetAuditRules",
185    "AddAuditRule",
186    "RemoveAuditRule",
187    // certbot / ACME (cross-distro)
188    "GetCertificates",
189    "ObtainCertificate",
190    "RenewCertificates",
191    "GetDateTime",
192    "SetHostname",
193    "SetTimezone",
194    "SetLocale",
195    "SetNtp",
196    "ListPackageRepositories",
197    "AddPackageRepository",
198    "RemovePackageRepository",
199    "EnablePackageRepository",
200    "DisablePackageRepository",
201    "ListContainers",
202    "CreateContainer",
203    "StartContainer",
204    "StopContainer",
205    "RemoveContainer",
206    "GetContainerInfo",
207    "ListUsers",
208    "ListGroups",
209    "CreateUser",
210    "DeleteUser",
211    "AddUserToGroup",
212    "RemoveUserFromGroup",
213    "CreateGroup",
214    "DeleteGroup",
215    "LockUserAccount",
216    "UnlockUserAccount",
217    "GetAuthorizedKeys",
218    "AddAuthorizedKey",
219    "RemoveAuthorizedKey",
220    "SetSshdOption",
221    "ListJobHistory",
222    // Ubuntu / apt
223    "AptUpdate",
224    "AptUpgrade",
225    "AptInstall",
226    "AptRemove",
227    "AptPurge",
228    "AptAutoremove",
229    "AptHold",
230    "AptUnhold",
231    "AptSearch",
232    "AptListInstalled",
233    "AptShow",
234    "AptListUpgradable",
235    "AptHistoryList",
236    "UnattendedUpgradesStatus",
237    "ConfigureUnattendedUpgrades",
238    "GetAptPins",
239    "SetAptPin",
240    "RemoveAptPin",
241    // Ubuntu / ppa
242    "AddPpa",
243    "RemovePpa",
244    // Ubuntu / snap
245    "SnapInstall",
246    "SnapRemove",
247    "SnapRefresh",
248    "SnapHold",
249    "SnapUnhold",
250    "SnapList",
251    "SnapInfo",
252    "SnapRevert",
253    "SnapClassicInstall",
254    // Ubuntu / ufw
255    "UfwEnable",
256    "UfwDisable",
257    "UfwAllow",
258    "UfwDeny",
259    "UfwReset",
260    "UfwStatus",
261    // Ubuntu / distrobox
262    "DistroboxList",
263    "DistroboxCreate",
264    "DistroboxRemove",
265    // Ubuntu / netplan
266    "NetplanGetConfig",
267    "NetplanApply",
268    "NetplanSet",
269    "NetplanGenerate",
270    // Ubuntu / grub
271    "GrubGetKargs",
272    "GrubSetKargs",
273    // Ubuntu / reboot
274    "CheckPendingReboot",
275    // Cross-distro / resolvectl (systemd-resolved)
276    "ResolvectlStatus",
277    "ResolvectlSetDns",
278    // Ubuntu / apparmor
279    "AppArmorStatus",
280    "AppArmorEnforce",
281    "AppArmorComplain",
282    // Ubuntu / cloud-init
283    "CloudInitStatus",
284    // Ubuntu / flatpak (Ubuntu-specific routing)
285    "UbuntuInstallFlatpak",
286    "UbuntuRemoveFlatpak",
287    "UbuntuUpdateFlatpak",
288    "UbuntuListFlatpaks",
289    // Ubuntu / fail2ban
290    "Fail2banStatus",
291    "Fail2banBanIp",
292    "Fail2banUnbanIp",
293    "ConfigureFail2banJail",
294    // Ubuntu / release upgrade (Tier 3)
295    "UbuntuReleaseUpgrade",
296    // Ubuntu / Ubuntu Pro (Tier 3)
297    "ProStatus",
298    "ProSecurityStatus",
299    "ProAttach",
300    "ProDetach",
301    "EnableProService",
302    "DisableProService",
303    // Ubuntu / Livepatch (Tier 3)
304    "LivepatchStatus",
305    // Ubuntu / Multipass (Tier 3)
306    "MultipassList",
307    // Ubuntu / ufw Tier 3
308    "UfwDeleteRule",
309    "UfwLimit",
310];
311
312/// A validated action name from the approved SysKnife catalogue.
313///
314/// Constructed via [`ActionName::parse`], which rejects any string not in
315/// [`KNOWN_ACTION_NAMES`].  Holding an `ActionName` is a compile-time
316/// guarantee that the contained string is in the catalogue — downstream
317/// code does not need to re-validate.
318#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
319#[serde(transparent)]
320pub struct ActionName(String);
321
322impl ActionName {
323    /// Parse a string into a validated `ActionName`.
324    pub fn parse(name: impl Into<String>) -> Result<Self, UnknownActionName> {
325        let name = name.into();
326        if KNOWN_ACTION_NAMES.contains(&name.as_str()) {
327            Ok(Self(name))
328        } else {
329            Err(UnknownActionName(name))
330        }
331    }
332
333    /// Return the inner string slice.
334    pub fn as_str(&self) -> &str {
335        &self.0
336    }
337}
338
339impl std::fmt::Display for ActionName {
340    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
341        f.write_str(&self.0)
342    }
343}
344
345impl AsRef<str> for ActionName {
346    fn as_ref(&self) -> &str {
347        &self.0
348    }
349}
350
351/// Returned by [`ActionName::parse`] when the string is not a known action.
352#[derive(Clone, Debug, PartialEq, Eq)]
353pub struct UnknownActionName(pub String);
354
355impl std::fmt::Display for UnknownActionName {
356    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
357        write!(f, "unknown action name: '{}'", self.0)
358    }
359}
360
361impl std::error::Error for UnknownActionName {}
362
363// ---------------------------------------------------------------------------
364// Request hash newtype
365// ---------------------------------------------------------------------------
366
367/// Hex-encoded SHA-256 hash of a [`RequestEnvelope`].
368///
369/// `serde(transparent)` keeps the wire format identical to a bare string so
370/// existing JSON IPC frames deserialize unchanged.
371#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
372#[serde(transparent)]
373pub struct RequestHash(String);
374
375impl RequestHash {
376    pub fn new(s: impl Into<String>) -> Self {
377        Self(s.into())
378    }
379    pub fn as_str(&self) -> &str {
380        &self.0
381    }
382    pub fn into_inner(self) -> String {
383        self.0
384    }
385}
386
387impl std::fmt::Display for RequestHash {
388    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
389        f.write_str(&self.0)
390    }
391}
392
393impl AsRef<str> for RequestHash {
394    fn as_ref(&self) -> &str {
395        &self.0
396    }
397}
398
399impl From<String> for RequestHash {
400    fn from(s: String) -> Self {
401        Self(s)
402    }
403}
404
405// ---------------------------------------------------------------------------
406// Approval-flow newtypes
407// ---------------------------------------------------------------------------
408
409/// Identifier for one preview/approve/execute round-trip.
410///
411/// Distinct from [`ApprovalReceipt`] at the type level because the two are
412/// indistinguishable at the value level: both are opaque strings passed side by
413/// side into the same calls. `execute(transaction_id, action_name, params,
414/// approval_receipt, …)` took three bare `&str` in a row, so transposing any
415/// two of them compiled and failed at runtime as a stale-approval error, which
416/// reads like an expiry rather than a call-site bug.
417#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
418#[serde(transparent)]
419pub struct TransactionId(String);
420
421/// A one-time bearer receipt minted by `sysknife approve`.
422///
423/// This is a **credential**: whoever holds it can execute the approved step
424/// once. `Debug` is redacted so a `tracing::debug!("{req:?}")` on any struct
425/// carrying one cannot spill it into a log. Use [`ApprovalReceipt::as_str`]
426/// where the real value is genuinely needed.
427#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
428#[serde(transparent)]
429pub struct ApprovalReceipt(String);
430
431impl std::fmt::Debug for ApprovalReceipt {
432    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
433        f.write_str("ApprovalReceipt(<redacted>)")
434    }
435}
436
437macro_rules! opaque_string_newtype {
438    ($name:ident) => {
439        impl $name {
440            pub fn new(s: impl Into<String>) -> Self {
441                Self(s.into())
442            }
443            pub fn as_str(&self) -> &str {
444                &self.0
445            }
446            pub fn into_inner(self) -> String {
447                self.0
448            }
449        }
450
451        impl AsRef<str> for $name {
452            fn as_ref(&self) -> &str {
453                &self.0
454            }
455        }
456
457        impl From<String> for $name {
458            fn from(s: String) -> Self {
459                Self(s)
460            }
461        }
462    };
463}
464
465opaque_string_newtype!(TransactionId);
466opaque_string_newtype!(ApprovalReceipt);
467
468// `Display` only for the identifier. `ApprovalReceipt` deliberately has none:
469// a credential that formats itself into any `{}` is one interpolation away
470// from a log line, and the explicit `as_str()` marks the places that really
471// need the secret.
472impl std::fmt::Display for TransactionId {
473    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
474        f.write_str(&self.0)
475    }
476}
477
478/// Caller privilege tier, ordered least to most privileged.
479///
480/// **Variant order is the privilege order** and `Ord` is derived from it, so
481/// `caller >= required` is the authorization comparison. This mirrors what
482/// v0.2.10 did for `PlanRiskLevel`; `CallerRole` kept a hand-written
483/// `role_rank` match until now, which is a second encoding of the same
484/// ordering that could drift from this declaration.
485///
486/// Adding a variant means placing it at the correct privilege position, not
487/// appending it.
488#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
489#[serde(rename_all = "snake_case")]
490pub enum CallerRole {
491    Observer,
492    Dev,
493    Admin,
494    Boot,
495}
496
497impl CallerRole {
498    /// Stable lowercase spelling, identical to the serde representation.
499    ///
500    /// The audit chain signs this string, so it is a wire format: renaming a
501    /// variant must not silently change what past signatures were made over.
502    /// `format!("{role:?}")` cannot be used for that — `Debug` carries no
503    /// stability promise and tracks the identifier. `caller_role_as_str_matches_serde`
504    /// pins the two encodings together.
505    pub fn as_str(&self) -> &'static str {
506        match self {
507            Self::Observer => "observer",
508            Self::Dev => "dev",
509            Self::Admin => "admin",
510            Self::Boot => "boot",
511        }
512    }
513}
514
515#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
516#[serde(rename_all = "snake_case")]
517pub enum RiskLevel {
518    Low,
519    Medium,
520    High,
521}
522
523#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
524#[serde(rename_all = "snake_case")]
525pub enum JobState {
526    Queued,
527    Running,
528    Succeeded,
529    Failed,
530    Canceled,
531    RolledBack,
532    NeedsReboot,
533}
534
535/// Structured failure categories for the IPC error protocol.
536///
537/// Currently used only in the proto bridge layer (sysknife-types <-> sysknife-proto
538/// conversions) and their tests. The daemon dispatcher uses string category
539/// names on the wire today; these variants will replace those strings when the
540/// daemon adopts the proto layer end-to-end.
541#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
542#[serde(rename_all = "snake_case")]
543pub enum FailureCategory {
544    ValidationFailure,
545    AuthorizationFailure,
546    PolicyDenied,
547    StaleApproval,
548    ExecutionFailure,
549    TransientInfrastructureFailure,
550    Cancellation,
551    StuckExecution,
552    RebootRequired,
553    RollbackFailure,
554}
555
556#[derive(Debug, thiserror::Error)]
557pub enum BridgeError {
558    #[error("invalid json payload for {0}")]
559    InvalidJson(&'static str, #[source] serde_json::Error),
560
561    #[error("invalid enum value {value} for {field}")]
562    InvalidEnum { field: &'static str, value: i32 },
563}
564
565#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
566pub struct RequestEnvelope {
567    pub action_name: String,
568    pub request_id: String,
569    pub params: Value,
570    pub caller_role: CallerRole,
571    pub request_hash: RequestHash,
572}
573
574#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
575pub struct PreviewEnvelope {
576    pub summary: String,
577    pub risk_level: RiskLevel,
578    pub current_state: Value,
579    pub proposed_change: Value,
580    pub expected_side_effects: Vec<String>,
581    pub reboot_required: bool,
582    pub rollback_available: bool,
583    pub warnings: Vec<String>,
584    pub request_hash: RequestHash,
585}
586
587#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
588pub struct ResultEnvelope {
589    pub status: JobState,
590    pub summary: String,
591    pub warnings: Vec<String>,
592    pub job_id: Option<String>,
593    pub needs_reboot: bool,
594    pub rollback_ref: Option<String>,
595    pub transaction_id: String,
596}
597
598#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
599pub struct TransactionRecord {
600    pub transaction_id: String,
601    pub request_id: String,
602    pub request_hash: String,
603    pub action_name: String,
604    pub risk_level: RiskLevel,
605    pub status: JobState,
606    pub approval_id: Option<String>,
607    pub summary: String,
608    pub warnings: Vec<String>,
609}
610
611impl From<CallerRole> for proto::CallerRole {
612    // Matched directly against the variants rather than round-tripping through
613    // an i32 code table, so a renumbered `.proto` moves this conversion along
614    // with the prost-generated enum instead of drifting behind it. The
615    // conversion is total, so it cannot panic.
616    fn from(value: CallerRole) -> Self {
617        match value {
618            CallerRole::Observer => proto::CallerRole::Observer,
619            CallerRole::Dev => proto::CallerRole::Dev,
620            CallerRole::Admin => proto::CallerRole::Admin,
621            CallerRole::Boot => proto::CallerRole::Boot,
622        }
623    }
624}
625
626impl TryFrom<proto::CallerRole> for CallerRole {
627    type Error = BridgeError;
628
629    fn try_from(value: proto::CallerRole) -> Result<Self, Self::Error> {
630        match i32::from(value) {
631            1 => Ok(CallerRole::Observer),
632            2 => Ok(CallerRole::Dev),
633            3 => Ok(CallerRole::Admin),
634            4 => Ok(CallerRole::Boot),
635            code => Err(BridgeError::InvalidEnum {
636                field: "caller_role",
637                value: code,
638            }),
639        }
640    }
641}
642
643impl From<RiskLevel> for proto::RiskLevel {
644    fn from(value: RiskLevel) -> Self {
645        match value {
646            RiskLevel::Low => proto::RiskLevel::Low,
647            RiskLevel::Medium => proto::RiskLevel::Medium,
648            RiskLevel::High => proto::RiskLevel::High,
649        }
650    }
651}
652
653impl TryFrom<proto::RiskLevel> for RiskLevel {
654    type Error = BridgeError;
655
656    fn try_from(value: proto::RiskLevel) -> Result<Self, Self::Error> {
657        match i32::from(value) {
658            1 => Ok(RiskLevel::Low),
659            2 => Ok(RiskLevel::Medium),
660            3 => Ok(RiskLevel::High),
661            code => Err(BridgeError::InvalidEnum {
662                field: "risk_level",
663                value: code,
664            }),
665        }
666    }
667}
668
669impl From<JobState> for proto::JobState {
670    fn from(value: JobState) -> Self {
671        match value {
672            JobState::Queued => proto::JobState::Queued,
673            JobState::Running => proto::JobState::Running,
674            JobState::Succeeded => proto::JobState::Succeeded,
675            JobState::Failed => proto::JobState::Failed,
676            JobState::Canceled => proto::JobState::Canceled,
677            JobState::RolledBack => proto::JobState::RolledBack,
678            JobState::NeedsReboot => proto::JobState::NeedsReboot,
679        }
680    }
681}
682
683impl TryFrom<proto::JobState> for JobState {
684    type Error = BridgeError;
685
686    fn try_from(value: proto::JobState) -> Result<Self, Self::Error> {
687        match i32::from(value) {
688            1 => Ok(JobState::Queued),
689            2 => Ok(JobState::Running),
690            3 => Ok(JobState::Succeeded),
691            4 => Ok(JobState::Failed),
692            5 => Ok(JobState::Canceled),
693            6 => Ok(JobState::RolledBack),
694            7 => Ok(JobState::NeedsReboot),
695            code => Err(BridgeError::InvalidEnum {
696                field: "job_state",
697                value: code,
698            }),
699        }
700    }
701}
702
703impl From<FailureCategory> for proto::FailureCategory {
704    fn from(value: FailureCategory) -> Self {
705        match value {
706            FailureCategory::ValidationFailure => proto::FailureCategory::ValidationFailure,
707            FailureCategory::AuthorizationFailure => proto::FailureCategory::AuthorizationFailure,
708            FailureCategory::PolicyDenied => proto::FailureCategory::PolicyDenied,
709            FailureCategory::StaleApproval => proto::FailureCategory::StaleApproval,
710            FailureCategory::ExecutionFailure => proto::FailureCategory::ExecutionFailure,
711            FailureCategory::TransientInfrastructureFailure => {
712                proto::FailureCategory::TransientInfrastructureFailure
713            }
714            FailureCategory::Cancellation => proto::FailureCategory::Cancellation,
715            FailureCategory::StuckExecution => proto::FailureCategory::StuckExecution,
716            FailureCategory::RebootRequired => proto::FailureCategory::RebootRequired,
717            FailureCategory::RollbackFailure => proto::FailureCategory::RollbackFailure,
718        }
719    }
720}
721
722impl TryFrom<proto::FailureCategory> for FailureCategory {
723    type Error = BridgeError;
724
725    fn try_from(value: proto::FailureCategory) -> Result<Self, Self::Error> {
726        match i32::from(value) {
727            1 => Ok(FailureCategory::ValidationFailure),
728            2 => Ok(FailureCategory::AuthorizationFailure),
729            3 => Ok(FailureCategory::PolicyDenied),
730            4 => Ok(FailureCategory::StaleApproval),
731            5 => Ok(FailureCategory::ExecutionFailure),
732            6 => Ok(FailureCategory::TransientInfrastructureFailure),
733            7 => Ok(FailureCategory::Cancellation),
734            8 => Ok(FailureCategory::StuckExecution),
735            9 => Ok(FailureCategory::RebootRequired),
736            10 => Ok(FailureCategory::RollbackFailure),
737            code => Err(BridgeError::InvalidEnum {
738                field: "failure_category",
739                value: code,
740            }),
741        }
742    }
743}
744
745impl From<RequestEnvelope> for proto::RequestEnvelope {
746    fn from(value: RequestEnvelope) -> Self {
747        Self {
748            action_name: value.action_name,
749            request_id: value.request_id,
750            params_json: serde_json::to_string(&value.params).expect("json serialization"),
751            caller_role: i32::from(proto::CallerRole::from(value.caller_role)),
752            request_hash: value.request_hash.into_inner(),
753        }
754    }
755}
756
757impl TryFrom<proto::RequestEnvelope> for RequestEnvelope {
758    type Error = BridgeError;
759
760    fn try_from(value: proto::RequestEnvelope) -> Result<Self, Self::Error> {
761        let params = serde_json::from_str(&value.params_json)
762            .map_err(|error| BridgeError::InvalidJson("params_json", error))?;
763
764        Ok(Self {
765            action_name: value.action_name,
766            request_id: value.request_id,
767            params,
768            caller_role: CallerRole::try_from(
769                proto::CallerRole::try_from(value.caller_role).map_err(|_| {
770                    BridgeError::InvalidEnum {
771                        field: "caller_role",
772                        value: value.caller_role,
773                    }
774                })?,
775            )?,
776            request_hash: RequestHash::from(value.request_hash),
777        })
778    }
779}
780
781impl From<PreviewEnvelope> for proto::PreviewEnvelope {
782    fn from(value: PreviewEnvelope) -> Self {
783        Self {
784            summary: value.summary,
785            risk_level: i32::from(proto::RiskLevel::from(value.risk_level)),
786            current_state_json: serde_json::to_string(&value.current_state)
787                .expect("json serialization"),
788            proposed_change_json: serde_json::to_string(&value.proposed_change)
789                .expect("json serialization"),
790            expected_side_effects: value.expected_side_effects,
791            reboot_required: value.reboot_required,
792            rollback_available: value.rollback_available,
793            warnings: value.warnings,
794            request_hash: value.request_hash.into_inner(),
795        }
796    }
797}
798
799impl TryFrom<proto::PreviewEnvelope> for PreviewEnvelope {
800    type Error = BridgeError;
801
802    fn try_from(value: proto::PreviewEnvelope) -> Result<Self, Self::Error> {
803        let current_state = serde_json::from_str(&value.current_state_json)
804            .map_err(|error| BridgeError::InvalidJson("current_state_json", error))?;
805        let proposed_change = serde_json::from_str(&value.proposed_change_json)
806            .map_err(|error| BridgeError::InvalidJson("proposed_change_json", error))?;
807
808        Ok(Self {
809            summary: value.summary,
810            risk_level: RiskLevel::try_from(
811                proto::RiskLevel::try_from(value.risk_level).map_err(|_| {
812                    BridgeError::InvalidEnum {
813                        field: "risk_level",
814                        value: value.risk_level,
815                    }
816                })?,
817            )?,
818            current_state,
819            proposed_change,
820            expected_side_effects: value.expected_side_effects,
821            reboot_required: value.reboot_required,
822            rollback_available: value.rollback_available,
823            warnings: value.warnings,
824            request_hash: RequestHash::from(value.request_hash),
825        })
826    }
827}
828
829impl From<ResultEnvelope> for proto::ResultEnvelope {
830    fn from(value: ResultEnvelope) -> Self {
831        Self {
832            status: i32::from(proto::JobState::from(value.status)),
833            summary: value.summary,
834            warnings: value.warnings,
835            job_id: value.job_id.unwrap_or_default(),
836            needs_reboot: value.needs_reboot,
837            rollback_ref: value.rollback_ref.unwrap_or_default(),
838            transaction_id: value.transaction_id,
839        }
840    }
841}
842
843impl TryFrom<proto::ResultEnvelope> for ResultEnvelope {
844    type Error = BridgeError;
845
846    fn try_from(value: proto::ResultEnvelope) -> Result<Self, Self::Error> {
847        Ok(Self {
848            status: JobState::try_from(proto::JobState::try_from(value.status).map_err(|_| {
849                BridgeError::InvalidEnum {
850                    field: "job_state",
851                    value: value.status,
852                }
853            })?)?,
854            summary: value.summary,
855            warnings: value.warnings,
856            job_id: if value.job_id.is_empty() {
857                None
858            } else {
859                Some(value.job_id)
860            },
861            needs_reboot: value.needs_reboot,
862            rollback_ref: if value.rollback_ref.is_empty() {
863                None
864            } else {
865                Some(value.rollback_ref)
866            },
867            transaction_id: value.transaction_id,
868        })
869    }
870}
871
872impl From<TransactionRecord> for proto::TransactionRecord {
873    fn from(value: TransactionRecord) -> Self {
874        Self {
875            transaction_id: value.transaction_id,
876            request_id: value.request_id,
877            request_hash: value.request_hash,
878            action_name: value.action_name,
879            risk_level: i32::from(proto::RiskLevel::from(value.risk_level)),
880            status: i32::from(proto::JobState::from(value.status)),
881            approval_id: value.approval_id.unwrap_or_default(),
882            summary: value.summary,
883            warnings: value.warnings,
884        }
885    }
886}
887
888impl TryFrom<proto::TransactionRecord> for TransactionRecord {
889    type Error = BridgeError;
890
891    fn try_from(value: proto::TransactionRecord) -> Result<Self, Self::Error> {
892        Ok(Self {
893            transaction_id: value.transaction_id,
894            request_id: value.request_id,
895            request_hash: value.request_hash,
896            action_name: value.action_name,
897            risk_level: RiskLevel::try_from(
898                proto::RiskLevel::try_from(value.risk_level).map_err(|_| {
899                    BridgeError::InvalidEnum {
900                        field: "risk_level",
901                        value: value.risk_level,
902                    }
903                })?,
904            )?,
905            status: JobState::try_from(proto::JobState::try_from(value.status).map_err(|_| {
906                BridgeError::InvalidEnum {
907                    field: "job_state",
908                    value: value.status,
909                }
910            })?)?,
911            approval_id: if value.approval_id.is_empty() {
912                None
913            } else {
914                Some(value.approval_id)
915            },
916            summary: value.summary,
917            warnings: value.warnings,
918        })
919    }
920}
921
922#[cfg(test)]
923mod request_hash_tests {
924    use super::*;
925
926    #[test]
927    fn serde_round_trips_via_transparent_string() {
928        // The newtype must serialise to a bare string so existing JSON IPC
929        // frames continue to deserialise unchanged.
930        let r = RequestHash::new("abc123".to_string());
931        let json = serde_json::to_string(&r).unwrap();
932        assert_eq!(json, "\"abc123\"");
933        let back: RequestHash = serde_json::from_str("\"abc123\"").unwrap();
934        assert_eq!(back, r);
935    }
936}
937
938#[cfg(test)]
939mod caller_role_ordering_tests {
940    use super::CallerRole;
941
942    #[test]
943    fn caller_role_orders_least_to_most_privileged() {
944        // The derived `Ord` IS the authorization comparison, so a variant
945        // reordered during an edit would silently change who can do what.
946        assert!(CallerRole::Observer < CallerRole::Dev);
947        assert!(CallerRole::Dev < CallerRole::Admin);
948        assert!(CallerRole::Admin < CallerRole::Boot);
949
950        // The comparison call sites rely on this shape directly.
951        assert!(CallerRole::Admin >= CallerRole::Dev);
952        assert!(!(CallerRole::Observer >= CallerRole::Dev));
953    }
954
955    #[test]
956    fn max_selects_the_higher_privilege() {
957        // `highest_role_from_groups` folds with `max`; a user in both the
958        // observer and admin groups must end up Admin.
959        assert_eq!(
960            CallerRole::Observer.max(CallerRole::Admin),
961            CallerRole::Admin
962        );
963        assert_eq!(CallerRole::Boot.max(CallerRole::Dev), CallerRole::Boot);
964    }
965}
966
967#[cfg(test)]
968mod frame_limit_declaration_tests {
969    use std::fs;
970    use std::path::{Path, PathBuf};
971
972    /// Walk the workspace root: climb from this crate's manifest dir until a
973    /// `Cargo.toml` declaring `[workspace]` is found.
974    fn workspace_root() -> PathBuf {
975        let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
976        loop {
977            let manifest = dir.join("Cargo.toml");
978            if manifest.is_file() {
979                if let Ok(text) = fs::read_to_string(&manifest) {
980                    if text.contains("[workspace]") {
981                        return dir;
982                    }
983                }
984            }
985            if !dir.pop() {
986                panic!("could not locate the workspace root");
987            }
988        }
989    }
990
991    /// Collect every `.rs` file under `dir`, skipping build output.
992    fn walk_rs(dir: &Path, out: &mut Vec<PathBuf>) {
993        if let Ok(entries) = fs::read_dir(dir) {
994            for entry in entries.flatten() {
995                let path = entry.path();
996                if path.file_name().is_some_and(|n| n == "target") {
997                    continue;
998                }
999                if path.is_dir() {
1000                    walk_rs(&path, out);
1001                } else if path.extension().is_some_and(|e| e == "rs") {
1002                    out.push(path);
1003                }
1004            }
1005        }
1006    }
1007
1008    /// The 4 MiB frame limit must be declared in exactly one place.
1009    ///
1010    /// `MAX_MESSAGE_BYTES` is a wire fact and therefore lives only in
1011    /// `sysknife-types` (the protocol crate every side depends on). The daemon
1012    /// and CLI import it rather than redeclare it. If a second `4 MiB`
1013    /// *constant* is added anywhere in the daemon or CLI (a re-introduced
1014    /// `MAX_FRAME_BYTES`), the limit can silently diverge and one peer can
1015    /// reject frames the other side already accepted. That regression is what
1016    /// this test catches: it scans the workspace for constant *declarations*
1017    /// carrying the 4 MiB initialiser and requires exactly one, in this crate.
1018    ///
1019    /// Lines that merely use the literal as a buffer size (e.g. a
1020    /// `tokio::io::duplex(...)` in a test) or that reference the imported
1021    /// constant are not declarations and are intentionally ignored.
1022    ///
1023    /// The scan matches the `4 * 1024 * 1024` literal *form*, not the value:
1024    /// a re-declaration written as `4194304` or `4 << 20` would slip past it,
1025    /// as would one split across two lines. That is a known, accepted gap —
1026    /// the duplicates it must catch arrived as copy-pastes of the existing
1027    /// literal. No reader should over-trust it as a value-graph check.
1028    #[test]
1029    fn frame_limit_is_declared_once() {
1030        let root = workspace_root();
1031        let mut files: Vec<PathBuf> = Vec::new();
1032        for crate_dir in [
1033            "crates/sysknife-types",
1034            "crates/sysknife-daemon",
1035            "apps/sysknife-cli",
1036        ] {
1037            walk_rs(&root.join(crate_dir), &mut files);
1038        }
1039
1040        let mut declarations: Vec<String> = Vec::new();
1041        for path in &files {
1042            let text = fs::read_to_string(path).unwrap();
1043            for (idx, raw) in text.lines().enumerate() {
1044                let line = raw.trim();
1045                let is_const_decl = [
1046                    "const ",
1047                    "pub const ",
1048                    "pub(crate) const ",
1049                    "pub(super) const ",
1050                ]
1051                .iter()
1052                .any(|p| line.starts_with(p));
1053                // A declaration names a constant AND carries the 4 MiB value.
1054                // Doc comments (start with `///`) and usages never both match.
1055                if is_const_decl && line.contains("4 * 1024 * 1024") {
1056                    declarations.push(format!("{}:{}", path.display(), idx + 1));
1057                }
1058            }
1059        }
1060
1061        assert_eq!(
1062            declarations.len(),
1063            1,
1064            "expected exactly one declaration of the 4 MiB frame limit, \
1065             found {}:\n{:#?}",
1066            declarations.len(),
1067            declarations
1068        );
1069        let (decl_path, _line) = declarations[0].rsplit_once(':').unwrap();
1070        let relativized = PathBuf::from(decl_path.replace(&format!("{}/", root.display()), ""));
1071        assert_eq!(
1072            relativized,
1073            Path::new("crates/sysknife-types/src/lib.rs"),
1074            "the single frame-limit declaration must live in sysknife-types"
1075        );
1076    }
1077}