symforge/server_api.rs
1//! Feature 020 V11, `symforge::server_api` — the public server entry
2//! (C5: the keyword flip executed, the entry wired).
3//!
4//! The contract's four atoms name this module: [`run`], [`ServerExit`],
5//! [`ServerBootstrapError`], and the module itself, public behind the
6//! frozen `feature=server` availability gate (the embed-v11 projection
7//! excludes it). `run` dispatches the whole symforge CLI through
8//! `cli::entry::run_main` — the binary is a shim over this door, and the
9//! retired raw module surface is no longer reachable from outside the
10//! crate.
11
12use std::ffi::OsString;
13
14/// Why the server could not come up. OPAQUE by contract (C1 ruling): the
15/// frozen record pins `kind: "struct"` with no public fields and
16/// `has_nonpublic_fields: true`, so external code can neither construct one
17/// nor match it exhaustively — every future refusal cause is non-breaking.
18///
19/// The cause chain is CAPTURED AS TEXT at construction: the frozen
20/// trait_impls pin all five auto traits on this type, and holding the
21/// dispatch error itself (`anyhow::Error`) would lose `RefUnwindSafe`.
22#[derive(Debug)]
23pub struct ServerBootstrapError {
24 reason: String,
25}
26
27impl ServerBootstrapError {
28 /// Wrap a dispatch failure, rendering its full cause chain.
29 fn from_dispatch(error: &anyhow::Error) -> Self {
30 Self {
31 reason: format!("{error:#}"),
32 }
33 }
34}
35
36impl std::fmt::Display for ServerBootstrapError {
37 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38 f.write_str(&self.reason)
39 }
40}
41
42impl std::error::Error for ServerBootstrapError {}
43
44/// How a completed server run ended. The two variants are TRANSCRIBED from
45/// the frozen contract record — an earlier draft invented a `Clean` variant
46/// here, the exact T043 failure mode, caught by T049's consumer fixtures and
47/// corrected against `public-api-v11.json`.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum ServerExit {
50 /// The server declined to come up and reported that as its exit (the
51 /// cli-serve contract maps this to process exit code 2).
52 RefusedToStart,
53 /// Clean successful shutdown.
54 Success,
55}
56
57/// The contract entry point: run the symforge CLI with `args` (`argv\[0\]`
58/// included). Dispatches every subcommand exactly as the binary always
59/// has — daemon, serve, stdio MCP, init/setup/admin/hook/trust/update —
60/// and maps the typed outcome onto the contract shapes. Argument-parse
61/// failures follow CLI convention (clap prints usage and exits).
62pub fn run(args: Vec<OsString>) -> Result<ServerExit, ServerBootstrapError> {
63 match crate::cli::entry::run_main(args) {
64 Ok(crate::cli::entry::MainExit::Success) => Ok(ServerExit::Success),
65 Ok(crate::cli::entry::MainExit::ServeRefusedToStart) => Ok(ServerExit::RefusedToStart),
66 Err(error) => Err(ServerBootstrapError::from_dispatch(&error)),
67 }
68}
69
70#[cfg(test)]
71mod tests {
72 use super::*;
73
74 /// C5: the wired entry preserves the contract shapes the dark stand-in
75 /// pinned — the two exit variants stay a closed set, the bootstrap
76 /// error keeps all five auto traits, and `run` actually dispatches
77 /// (the `--version` fast path completes and reports success).
78 #[test]
79 fn wired_run_dispatches_and_the_contract_shapes_hold() {
80 let exit = run(vec![
81 OsString::from("symforge"),
82 OsString::from("--version"),
83 ])
84 .expect("the --version fast path succeeds");
85 assert_eq!(exit, ServerExit::Success);
86
87 // The contract's two exit variants, verbatim from the frozen record;
88 // the match keeps the set CLOSED — a third variant fails compilation
89 // here before it can drift the surface.
90 let exits = [ServerExit::RefusedToStart, ServerExit::Success];
91 for exit in exits {
92 match exit {
93 ServerExit::RefusedToStart | ServerExit::Success => {}
94 }
95 }
96
97 fn all_five_auto<
98 T: Send + Sync + Unpin + std::panic::RefUnwindSafe + std::panic::UnwindSafe,
99 >() {
100 }
101 all_five_auto::<ServerBootstrapError>();
102 all_five_auto::<ServerExit>();
103
104 // The error renders its captured cause chain.
105 let refusal = ServerBootstrapError::from_dispatch(&anyhow::anyhow!("boom"));
106 assert!(format!("{refusal}").contains("boom"));
107 let _as_error: &dyn std::error::Error = &refusal;
108 }
109
110 /// C1 ruling: pin the ITEM KIND, not just the trait surface. The frozen
111 /// contract makes `ServerBootstrapError` an OPAQUE STRUCT — external
112 /// constructability must be impossible, which no runtime value-check can
113 /// observe from inside the crate, so the pin is a source assertion: the
114 /// declaration is a struct, never an enum, and its body holds no `pub`
115 /// field. An enum with a public variant survived every trait oracle
116 /// once; this is what would have caught it.
117 #[test]
118 fn bootstrap_error_is_an_opaque_struct_not_an_enum() {
119 let source = include_str!("server_api.rs");
120 // The needles are built at runtime with a REAL leading newline so
121 // they match only a column-zero declaration, never these string
122 // literals (which sit mid-line in the included source of this very
123 // test) — without this, the pin would match itself and be vacuous.
124 let struct_needle = format!("\n{} ServerBootstrapError", "pub struct");
125 let enum_needle = format!("\n{} ServerBootstrapError", "pub enum");
126 assert!(
127 source.contains(&struct_needle),
128 "the contract pins kind: struct"
129 );
130 assert!(
131 !source.contains(&enum_needle),
132 "an enum here is the invented-surface defect the contract's \
133 opaque struct exists to prevent"
134 );
135 let declaration = source
136 .split(struct_needle.as_str())
137 .nth(1)
138 .expect("declaration present");
139 // A tuple struct (`pub struct X(pub ...)`) has no brace body, and a
140 // naive `find('{')` would silently scan some LATER block — so the
141 // brace must be the first non-whitespace after the name (round-2
142 // hardening of this pin).
143 let after_name = declaration.trim_start();
144 assert!(
145 after_name.starts_with('{'),
146 "the declaration must open a brace body immediately — a tuple \
147 struct's parenthesized fields would evade the field scan"
148 );
149 let body_end = after_name.find('}').expect("struct body closes");
150 let body = &after_name[1..body_end];
151 assert!(
152 !body.contains("pub "),
153 "has_nonpublic_fields: every field stays private, got: {body}"
154 );
155 }
156}