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    "ProAttach",
299    "ProDetach",
300    "EnableProService",
301    "DisableProService",
302    // Ubuntu / Livepatch (Tier 3)
303    "LivepatchStatus",
304    // Ubuntu / Multipass (Tier 3)
305    "MultipassList",
306    // Ubuntu / ufw Tier 3
307    "UfwDeleteRule",
308    "UfwLimit",
309];
310
311/// A validated action name from the approved SysKnife catalogue.
312///
313/// Constructed via [`ActionName::parse`], which rejects any string not in
314/// [`KNOWN_ACTION_NAMES`].  Holding an `ActionName` is a compile-time
315/// guarantee that the contained string is in the catalogue — downstream
316/// code does not need to re-validate.
317#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
318#[serde(transparent)]
319pub struct ActionName(String);
320
321impl ActionName {
322    /// Parse a string into a validated `ActionName`.
323    pub fn parse(name: impl Into<String>) -> Result<Self, UnknownActionName> {
324        let name = name.into();
325        if KNOWN_ACTION_NAMES.contains(&name.as_str()) {
326            Ok(Self(name))
327        } else {
328            Err(UnknownActionName(name))
329        }
330    }
331
332    /// Return the inner string slice.
333    pub fn as_str(&self) -> &str {
334        &self.0
335    }
336}
337
338impl std::fmt::Display for ActionName {
339    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
340        f.write_str(&self.0)
341    }
342}
343
344impl AsRef<str> for ActionName {
345    fn as_ref(&self) -> &str {
346        &self.0
347    }
348}
349
350/// Returned by [`ActionName::parse`] when the string is not a known action.
351#[derive(Clone, Debug, PartialEq, Eq)]
352pub struct UnknownActionName(pub String);
353
354impl std::fmt::Display for UnknownActionName {
355    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
356        write!(f, "unknown action name: '{}'", self.0)
357    }
358}
359
360impl std::error::Error for UnknownActionName {}
361
362// ---------------------------------------------------------------------------
363// Request hash newtype
364// ---------------------------------------------------------------------------
365
366/// Hex-encoded SHA-256 hash of a [`RequestEnvelope`].
367///
368/// `serde(transparent)` keeps the wire format identical to a bare string so
369/// existing JSON IPC frames deserialize unchanged.
370#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
371#[serde(transparent)]
372pub struct RequestHash(String);
373
374impl RequestHash {
375    pub fn new(s: impl Into<String>) -> Self {
376        Self(s.into())
377    }
378    pub fn as_str(&self) -> &str {
379        &self.0
380    }
381    pub fn into_inner(self) -> String {
382        self.0
383    }
384}
385
386impl std::fmt::Display for RequestHash {
387    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
388        f.write_str(&self.0)
389    }
390}
391
392impl AsRef<str> for RequestHash {
393    fn as_ref(&self) -> &str {
394        &self.0
395    }
396}
397
398impl From<String> for RequestHash {
399    fn from(s: String) -> Self {
400        Self(s)
401    }
402}
403
404// ---------------------------------------------------------------------------
405// Approval-flow newtypes
406// ---------------------------------------------------------------------------
407
408/// Identifier for one preview/approve/execute round-trip.
409///
410/// Distinct from [`ApprovalReceipt`] at the type level because the two are
411/// indistinguishable at the value level: both are opaque strings passed side by
412/// side into the same calls. `execute(transaction_id, action_name, params,
413/// approval_receipt, …)` took three bare `&str` in a row, so transposing any
414/// two of them compiled and failed at runtime as a stale-approval error, which
415/// reads like an expiry rather than a call-site bug.
416#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
417#[serde(transparent)]
418pub struct TransactionId(String);
419
420/// A one-time bearer receipt minted by `sysknife approve`.
421///
422/// This is a **credential**: whoever holds it can execute the approved step
423/// once. `Debug` is redacted so a `tracing::debug!("{req:?}")` on any struct
424/// carrying one cannot spill it into a log. Use [`ApprovalReceipt::as_str`]
425/// where the real value is genuinely needed.
426#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
427#[serde(transparent)]
428pub struct ApprovalReceipt(String);
429
430impl std::fmt::Debug for ApprovalReceipt {
431    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
432        f.write_str("ApprovalReceipt(<redacted>)")
433    }
434}
435
436macro_rules! opaque_string_newtype {
437    ($name:ident) => {
438        impl $name {
439            pub fn new(s: impl Into<String>) -> Self {
440                Self(s.into())
441            }
442            pub fn as_str(&self) -> &str {
443                &self.0
444            }
445            pub fn into_inner(self) -> String {
446                self.0
447            }
448        }
449
450        impl AsRef<str> for $name {
451            fn as_ref(&self) -> &str {
452                &self.0
453            }
454        }
455
456        impl From<String> for $name {
457            fn from(s: String) -> Self {
458                Self(s)
459            }
460        }
461    };
462}
463
464opaque_string_newtype!(TransactionId);
465opaque_string_newtype!(ApprovalReceipt);
466
467// `Display` only for the identifier. `ApprovalReceipt` deliberately has none:
468// a credential that formats itself into any `{}` is one interpolation away
469// from a log line, and the explicit `as_str()` marks the places that really
470// need the secret.
471impl std::fmt::Display for TransactionId {
472    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
473        f.write_str(&self.0)
474    }
475}
476
477/// Caller privilege tier, ordered least to most privileged.
478///
479/// **Variant order is the privilege order** and `Ord` is derived from it, so
480/// `caller >= required` is the authorization comparison. This mirrors what
481/// v0.2.10 did for `PlanRiskLevel`; `CallerRole` kept a hand-written
482/// `role_rank` match until now, which is a second encoding of the same
483/// ordering that could drift from this declaration.
484///
485/// Adding a variant means placing it at the correct privilege position, not
486/// appending it.
487#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
488#[serde(rename_all = "snake_case")]
489pub enum CallerRole {
490    Observer,
491    Dev,
492    Admin,
493    Boot,
494}
495
496impl CallerRole {
497    /// Stable lowercase spelling, identical to the serde representation.
498    ///
499    /// The audit chain signs this string, so it is a wire format: renaming a
500    /// variant must not silently change what past signatures were made over.
501    /// `format!("{role:?}")` cannot be used for that — `Debug` carries no
502    /// stability promise and tracks the identifier. `caller_role_as_str_matches_serde`
503    /// pins the two encodings together.
504    pub fn as_str(&self) -> &'static str {
505        match self {
506            Self::Observer => "observer",
507            Self::Dev => "dev",
508            Self::Admin => "admin",
509            Self::Boot => "boot",
510        }
511    }
512}
513
514#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
515#[serde(rename_all = "snake_case")]
516pub enum RiskLevel {
517    Low,
518    Medium,
519    High,
520}
521
522#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
523#[serde(rename_all = "snake_case")]
524pub enum JobState {
525    Queued,
526    Running,
527    Succeeded,
528    Failed,
529    Canceled,
530    RolledBack,
531    NeedsReboot,
532}
533
534/// Structured failure categories for the IPC error protocol.
535///
536/// Currently used only in the proto bridge layer (sysknife-types <-> sysknife-proto
537/// conversions) and their tests. The daemon dispatcher uses string category
538/// names on the wire today; these variants will replace those strings when the
539/// daemon adopts the proto layer end-to-end.
540#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
541#[serde(rename_all = "snake_case")]
542pub enum FailureCategory {
543    ValidationFailure,
544    AuthorizationFailure,
545    PolicyDenied,
546    StaleApproval,
547    ExecutionFailure,
548    TransientInfrastructureFailure,
549    Cancellation,
550    StuckExecution,
551    RebootRequired,
552    RollbackFailure,
553}
554
555#[derive(Debug, thiserror::Error)]
556pub enum BridgeError {
557    #[error("invalid json payload for {0}")]
558    InvalidJson(&'static str, #[source] serde_json::Error),
559
560    #[error("invalid enum value {value} for {field}")]
561    InvalidEnum { field: &'static str, value: i32 },
562}
563
564#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
565pub struct RequestEnvelope {
566    pub action_name: String,
567    pub request_id: String,
568    pub params: Value,
569    pub caller_role: CallerRole,
570    pub request_hash: RequestHash,
571}
572
573#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
574pub struct PreviewEnvelope {
575    pub summary: String,
576    pub risk_level: RiskLevel,
577    pub current_state: Value,
578    pub proposed_change: Value,
579    pub expected_side_effects: Vec<String>,
580    pub reboot_required: bool,
581    pub rollback_available: bool,
582    pub warnings: Vec<String>,
583    pub request_hash: RequestHash,
584}
585
586#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
587pub struct ResultEnvelope {
588    pub status: JobState,
589    pub summary: String,
590    pub warnings: Vec<String>,
591    pub job_id: Option<String>,
592    pub needs_reboot: bool,
593    pub rollback_ref: Option<String>,
594    pub transaction_id: String,
595}
596
597#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
598pub struct TransactionRecord {
599    pub transaction_id: String,
600    pub request_id: String,
601    pub request_hash: String,
602    pub action_name: String,
603    pub risk_level: RiskLevel,
604    pub status: JobState,
605    pub approval_id: Option<String>,
606    pub summary: String,
607    pub warnings: Vec<String>,
608}
609
610impl From<CallerRole> for proto::CallerRole {
611    // Matched directly against the variants rather than round-tripping through
612    // an i32 code table, so a renumbered `.proto` moves this conversion along
613    // with the prost-generated enum instead of drifting behind it. The
614    // conversion is total, so it cannot panic.
615    fn from(value: CallerRole) -> Self {
616        match value {
617            CallerRole::Observer => proto::CallerRole::Observer,
618            CallerRole::Dev => proto::CallerRole::Dev,
619            CallerRole::Admin => proto::CallerRole::Admin,
620            CallerRole::Boot => proto::CallerRole::Boot,
621        }
622    }
623}
624
625impl TryFrom<proto::CallerRole> for CallerRole {
626    type Error = BridgeError;
627
628    fn try_from(value: proto::CallerRole) -> Result<Self, Self::Error> {
629        match i32::from(value) {
630            1 => Ok(CallerRole::Observer),
631            2 => Ok(CallerRole::Dev),
632            3 => Ok(CallerRole::Admin),
633            4 => Ok(CallerRole::Boot),
634            code => Err(BridgeError::InvalidEnum {
635                field: "caller_role",
636                value: code,
637            }),
638        }
639    }
640}
641
642impl From<RiskLevel> for proto::RiskLevel {
643    fn from(value: RiskLevel) -> Self {
644        match value {
645            RiskLevel::Low => proto::RiskLevel::Low,
646            RiskLevel::Medium => proto::RiskLevel::Medium,
647            RiskLevel::High => proto::RiskLevel::High,
648        }
649    }
650}
651
652impl TryFrom<proto::RiskLevel> for RiskLevel {
653    type Error = BridgeError;
654
655    fn try_from(value: proto::RiskLevel) -> Result<Self, Self::Error> {
656        match i32::from(value) {
657            1 => Ok(RiskLevel::Low),
658            2 => Ok(RiskLevel::Medium),
659            3 => Ok(RiskLevel::High),
660            code => Err(BridgeError::InvalidEnum {
661                field: "risk_level",
662                value: code,
663            }),
664        }
665    }
666}
667
668impl From<JobState> for proto::JobState {
669    fn from(value: JobState) -> Self {
670        match value {
671            JobState::Queued => proto::JobState::Queued,
672            JobState::Running => proto::JobState::Running,
673            JobState::Succeeded => proto::JobState::Succeeded,
674            JobState::Failed => proto::JobState::Failed,
675            JobState::Canceled => proto::JobState::Canceled,
676            JobState::RolledBack => proto::JobState::RolledBack,
677            JobState::NeedsReboot => proto::JobState::NeedsReboot,
678        }
679    }
680}
681
682impl TryFrom<proto::JobState> for JobState {
683    type Error = BridgeError;
684
685    fn try_from(value: proto::JobState) -> Result<Self, Self::Error> {
686        match i32::from(value) {
687            1 => Ok(JobState::Queued),
688            2 => Ok(JobState::Running),
689            3 => Ok(JobState::Succeeded),
690            4 => Ok(JobState::Failed),
691            5 => Ok(JobState::Canceled),
692            6 => Ok(JobState::RolledBack),
693            7 => Ok(JobState::NeedsReboot),
694            code => Err(BridgeError::InvalidEnum {
695                field: "job_state",
696                value: code,
697            }),
698        }
699    }
700}
701
702impl From<FailureCategory> for proto::FailureCategory {
703    fn from(value: FailureCategory) -> Self {
704        match value {
705            FailureCategory::ValidationFailure => proto::FailureCategory::ValidationFailure,
706            FailureCategory::AuthorizationFailure => proto::FailureCategory::AuthorizationFailure,
707            FailureCategory::PolicyDenied => proto::FailureCategory::PolicyDenied,
708            FailureCategory::StaleApproval => proto::FailureCategory::StaleApproval,
709            FailureCategory::ExecutionFailure => proto::FailureCategory::ExecutionFailure,
710            FailureCategory::TransientInfrastructureFailure => {
711                proto::FailureCategory::TransientInfrastructureFailure
712            }
713            FailureCategory::Cancellation => proto::FailureCategory::Cancellation,
714            FailureCategory::StuckExecution => proto::FailureCategory::StuckExecution,
715            FailureCategory::RebootRequired => proto::FailureCategory::RebootRequired,
716            FailureCategory::RollbackFailure => proto::FailureCategory::RollbackFailure,
717        }
718    }
719}
720
721impl TryFrom<proto::FailureCategory> for FailureCategory {
722    type Error = BridgeError;
723
724    fn try_from(value: proto::FailureCategory) -> Result<Self, Self::Error> {
725        match i32::from(value) {
726            1 => Ok(FailureCategory::ValidationFailure),
727            2 => Ok(FailureCategory::AuthorizationFailure),
728            3 => Ok(FailureCategory::PolicyDenied),
729            4 => Ok(FailureCategory::StaleApproval),
730            5 => Ok(FailureCategory::ExecutionFailure),
731            6 => Ok(FailureCategory::TransientInfrastructureFailure),
732            7 => Ok(FailureCategory::Cancellation),
733            8 => Ok(FailureCategory::StuckExecution),
734            9 => Ok(FailureCategory::RebootRequired),
735            10 => Ok(FailureCategory::RollbackFailure),
736            code => Err(BridgeError::InvalidEnum {
737                field: "failure_category",
738                value: code,
739            }),
740        }
741    }
742}
743
744impl From<RequestEnvelope> for proto::RequestEnvelope {
745    fn from(value: RequestEnvelope) -> Self {
746        Self {
747            action_name: value.action_name,
748            request_id: value.request_id,
749            params_json: serde_json::to_string(&value.params).expect("json serialization"),
750            caller_role: i32::from(proto::CallerRole::from(value.caller_role)),
751            request_hash: value.request_hash.into_inner(),
752        }
753    }
754}
755
756impl TryFrom<proto::RequestEnvelope> for RequestEnvelope {
757    type Error = BridgeError;
758
759    fn try_from(value: proto::RequestEnvelope) -> Result<Self, Self::Error> {
760        let params = serde_json::from_str(&value.params_json)
761            .map_err(|error| BridgeError::InvalidJson("params_json", error))?;
762
763        Ok(Self {
764            action_name: value.action_name,
765            request_id: value.request_id,
766            params,
767            caller_role: CallerRole::try_from(
768                proto::CallerRole::try_from(value.caller_role).map_err(|_| {
769                    BridgeError::InvalidEnum {
770                        field: "caller_role",
771                        value: value.caller_role,
772                    }
773                })?,
774            )?,
775            request_hash: RequestHash::from(value.request_hash),
776        })
777    }
778}
779
780impl From<PreviewEnvelope> for proto::PreviewEnvelope {
781    fn from(value: PreviewEnvelope) -> Self {
782        Self {
783            summary: value.summary,
784            risk_level: i32::from(proto::RiskLevel::from(value.risk_level)),
785            current_state_json: serde_json::to_string(&value.current_state)
786                .expect("json serialization"),
787            proposed_change_json: serde_json::to_string(&value.proposed_change)
788                .expect("json serialization"),
789            expected_side_effects: value.expected_side_effects,
790            reboot_required: value.reboot_required,
791            rollback_available: value.rollback_available,
792            warnings: value.warnings,
793            request_hash: value.request_hash.into_inner(),
794        }
795    }
796}
797
798impl TryFrom<proto::PreviewEnvelope> for PreviewEnvelope {
799    type Error = BridgeError;
800
801    fn try_from(value: proto::PreviewEnvelope) -> Result<Self, Self::Error> {
802        let current_state = serde_json::from_str(&value.current_state_json)
803            .map_err(|error| BridgeError::InvalidJson("current_state_json", error))?;
804        let proposed_change = serde_json::from_str(&value.proposed_change_json)
805            .map_err(|error| BridgeError::InvalidJson("proposed_change_json", error))?;
806
807        Ok(Self {
808            summary: value.summary,
809            risk_level: RiskLevel::try_from(
810                proto::RiskLevel::try_from(value.risk_level).map_err(|_| {
811                    BridgeError::InvalidEnum {
812                        field: "risk_level",
813                        value: value.risk_level,
814                    }
815                })?,
816            )?,
817            current_state,
818            proposed_change,
819            expected_side_effects: value.expected_side_effects,
820            reboot_required: value.reboot_required,
821            rollback_available: value.rollback_available,
822            warnings: value.warnings,
823            request_hash: RequestHash::from(value.request_hash),
824        })
825    }
826}
827
828impl From<ResultEnvelope> for proto::ResultEnvelope {
829    fn from(value: ResultEnvelope) -> Self {
830        Self {
831            status: i32::from(proto::JobState::from(value.status)),
832            summary: value.summary,
833            warnings: value.warnings,
834            job_id: value.job_id.unwrap_or_default(),
835            needs_reboot: value.needs_reboot,
836            rollback_ref: value.rollback_ref.unwrap_or_default(),
837            transaction_id: value.transaction_id,
838        }
839    }
840}
841
842impl TryFrom<proto::ResultEnvelope> for ResultEnvelope {
843    type Error = BridgeError;
844
845    fn try_from(value: proto::ResultEnvelope) -> Result<Self, Self::Error> {
846        Ok(Self {
847            status: JobState::try_from(proto::JobState::try_from(value.status).map_err(|_| {
848                BridgeError::InvalidEnum {
849                    field: "job_state",
850                    value: value.status,
851                }
852            })?)?,
853            summary: value.summary,
854            warnings: value.warnings,
855            job_id: if value.job_id.is_empty() {
856                None
857            } else {
858                Some(value.job_id)
859            },
860            needs_reboot: value.needs_reboot,
861            rollback_ref: if value.rollback_ref.is_empty() {
862                None
863            } else {
864                Some(value.rollback_ref)
865            },
866            transaction_id: value.transaction_id,
867        })
868    }
869}
870
871impl From<TransactionRecord> for proto::TransactionRecord {
872    fn from(value: TransactionRecord) -> Self {
873        Self {
874            transaction_id: value.transaction_id,
875            request_id: value.request_id,
876            request_hash: value.request_hash,
877            action_name: value.action_name,
878            risk_level: i32::from(proto::RiskLevel::from(value.risk_level)),
879            status: i32::from(proto::JobState::from(value.status)),
880            approval_id: value.approval_id.unwrap_or_default(),
881            summary: value.summary,
882            warnings: value.warnings,
883        }
884    }
885}
886
887impl TryFrom<proto::TransactionRecord> for TransactionRecord {
888    type Error = BridgeError;
889
890    fn try_from(value: proto::TransactionRecord) -> Result<Self, Self::Error> {
891        Ok(Self {
892            transaction_id: value.transaction_id,
893            request_id: value.request_id,
894            request_hash: value.request_hash,
895            action_name: value.action_name,
896            risk_level: RiskLevel::try_from(
897                proto::RiskLevel::try_from(value.risk_level).map_err(|_| {
898                    BridgeError::InvalidEnum {
899                        field: "risk_level",
900                        value: value.risk_level,
901                    }
902                })?,
903            )?,
904            status: JobState::try_from(proto::JobState::try_from(value.status).map_err(|_| {
905                BridgeError::InvalidEnum {
906                    field: "job_state",
907                    value: value.status,
908                }
909            })?)?,
910            approval_id: if value.approval_id.is_empty() {
911                None
912            } else {
913                Some(value.approval_id)
914            },
915            summary: value.summary,
916            warnings: value.warnings,
917        })
918    }
919}
920
921#[cfg(test)]
922mod request_hash_tests {
923    use super::*;
924
925    #[test]
926    fn serde_round_trips_via_transparent_string() {
927        // The newtype must serialise to a bare string so existing JSON IPC
928        // frames continue to deserialise unchanged.
929        let r = RequestHash::new("abc123".to_string());
930        let json = serde_json::to_string(&r).unwrap();
931        assert_eq!(json, "\"abc123\"");
932        let back: RequestHash = serde_json::from_str("\"abc123\"").unwrap();
933        assert_eq!(back, r);
934    }
935}
936
937#[cfg(test)]
938mod caller_role_ordering_tests {
939    use super::CallerRole;
940
941    #[test]
942    fn caller_role_orders_least_to_most_privileged() {
943        // The derived `Ord` IS the authorization comparison, so a variant
944        // reordered during an edit would silently change who can do what.
945        assert!(CallerRole::Observer < CallerRole::Dev);
946        assert!(CallerRole::Dev < CallerRole::Admin);
947        assert!(CallerRole::Admin < CallerRole::Boot);
948
949        // The comparison call sites rely on this shape directly.
950        assert!(CallerRole::Admin >= CallerRole::Dev);
951        assert!(!(CallerRole::Observer >= CallerRole::Dev));
952    }
953
954    #[test]
955    fn max_selects_the_higher_privilege() {
956        // `highest_role_from_groups` folds with `max`; a user in both the
957        // observer and admin groups must end up Admin.
958        assert_eq!(
959            CallerRole::Observer.max(CallerRole::Admin),
960            CallerRole::Admin
961        );
962        assert_eq!(CallerRole::Boot.max(CallerRole::Dev), CallerRole::Boot);
963    }
964}
965
966#[cfg(test)]
967mod frame_limit_declaration_tests {
968    use std::fs;
969    use std::path::{Path, PathBuf};
970
971    /// Walk the workspace root: climb from this crate's manifest dir until a
972    /// `Cargo.toml` declaring `[workspace]` is found.
973    fn workspace_root() -> PathBuf {
974        let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
975        loop {
976            let manifest = dir.join("Cargo.toml");
977            if manifest.is_file() {
978                if let Ok(text) = fs::read_to_string(&manifest) {
979                    if text.contains("[workspace]") {
980                        return dir;
981                    }
982                }
983            }
984            if !dir.pop() {
985                panic!("could not locate the workspace root");
986            }
987        }
988    }
989
990    /// Collect every `.rs` file under `dir`, skipping build output.
991    fn walk_rs(dir: &Path, out: &mut Vec<PathBuf>) {
992        if let Ok(entries) = fs::read_dir(dir) {
993            for entry in entries.flatten() {
994                let path = entry.path();
995                if path.file_name().is_some_and(|n| n == "target") {
996                    continue;
997                }
998                if path.is_dir() {
999                    walk_rs(&path, out);
1000                } else if path.extension().is_some_and(|e| e == "rs") {
1001                    out.push(path);
1002                }
1003            }
1004        }
1005    }
1006
1007    /// The 4 MiB frame limit must be declared in exactly one place.
1008    ///
1009    /// `MAX_MESSAGE_BYTES` is a wire fact and therefore lives only in
1010    /// `sysknife-types` (the protocol crate every side depends on). The daemon
1011    /// and CLI import it rather than redeclare it. If a second `4 MiB`
1012    /// *constant* is added anywhere in the daemon or CLI (a re-introduced
1013    /// `MAX_FRAME_BYTES`), the limit can silently diverge and one peer can
1014    /// reject frames the other side already accepted. That regression is what
1015    /// this test catches: it scans the workspace for constant *declarations*
1016    /// carrying the 4 MiB initialiser and requires exactly one, in this crate.
1017    ///
1018    /// Lines that merely use the literal as a buffer size (e.g. a
1019    /// `tokio::io::duplex(...)` in a test) or that reference the imported
1020    /// constant are not declarations and are intentionally ignored.
1021    ///
1022    /// The scan matches the `4 * 1024 * 1024` literal *form*, not the value:
1023    /// a re-declaration written as `4194304` or `4 << 20` would slip past it,
1024    /// as would one split across two lines. That is a known, accepted gap —
1025    /// the duplicates it must catch arrived as copy-pastes of the existing
1026    /// literal. No reader should over-trust it as a value-graph check.
1027    #[test]
1028    fn frame_limit_is_declared_once() {
1029        let root = workspace_root();
1030        let mut files: Vec<PathBuf> = Vec::new();
1031        for crate_dir in [
1032            "crates/sysknife-types",
1033            "crates/sysknife-daemon",
1034            "apps/sysknife-cli",
1035        ] {
1036            walk_rs(&root.join(crate_dir), &mut files);
1037        }
1038
1039        let mut declarations: Vec<String> = Vec::new();
1040        for path in &files {
1041            let text = fs::read_to_string(path).unwrap();
1042            for (idx, raw) in text.lines().enumerate() {
1043                let line = raw.trim();
1044                let is_const_decl = [
1045                    "const ",
1046                    "pub const ",
1047                    "pub(crate) const ",
1048                    "pub(super) const ",
1049                ]
1050                .iter()
1051                .any(|p| line.starts_with(p));
1052                // A declaration names a constant AND carries the 4 MiB value.
1053                // Doc comments (start with `///`) and usages never both match.
1054                if is_const_decl && line.contains("4 * 1024 * 1024") {
1055                    declarations.push(format!("{}:{}", path.display(), idx + 1));
1056                }
1057            }
1058        }
1059
1060        assert_eq!(
1061            declarations.len(),
1062            1,
1063            "expected exactly one declaration of the 4 MiB frame limit, \
1064             found {}:\n{:#?}",
1065            declarations.len(),
1066            declarations
1067        );
1068        let (decl_path, _line) = declarations[0].rsplit_once(':').unwrap();
1069        let relativized = PathBuf::from(decl_path.replace(&format!("{}/", root.display()), ""));
1070        assert_eq!(
1071            relativized,
1072            Path::new("crates/sysknife-types/src/lib.rs"),
1073            "the single frame-limit declaration must live in sysknife-types"
1074        );
1075    }
1076}