Skip to main content

stackless_core/
fault.rs

1//! The agent-facing error contract (ARCHITECTURE.md §2).
2//!
3//! Every error stackless emits carries three parts: *what* failed (the
4//! step and instance), *why* (the observed cause), and *how to proceed*
5//! (a concrete command, flag, or fix). Agents branch on stable codes,
6//! never on prose.
7
8use serde::{Deserialize, Serialize};
9
10/// Lines of captured output included in failure context (hooks, health,
11/// prepare). Aligns with `stackless logs --tail` defaults for operators.
12pub const FAILURE_LOG_TAIL_LINES: usize = 80;
13
14/// Factual observables agents use to locate and inspect a failure.
15#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
16pub struct ErrorContext {
17    pub service: Option<String>,
18    pub hook: Option<String>,
19    pub command: Option<String>,
20    pub source_dir: Option<String>,
21    pub log_path: Option<String>,
22    pub log_hint: Option<String>,
23    pub exit_status: Option<String>,
24    pub log_tail: Option<String>,
25}
26
27/// Stable machine-readable error codes.
28///
29/// Codes are versioned API surface: renaming one is a breaking change
30/// (ARCHITECTURE.md §2). Every code lives here, in one registry, so the
31/// full surface is greppable and uniqueness is testable.
32pub mod codes {
33    pub const DEF_PARSE_SYNTAX: &str = "def.parse.syntax";
34    pub const DEF_PARSE_SCHEMA: &str = "def.parse.schema";
35    pub const DEF_NAME_INVALID: &str = "def.validate.name_invalid";
36    pub const DEF_NO_SERVICES: &str = "def.validate.no_services";
37    pub const DEF_UNKNOWN_KEY: &str = "def.validate.unknown_key";
38    pub const DEF_DEPENDS_ON_REJECTED: &str = "def.validate.depends_on_rejected";
39    pub const DEF_SUBSTRATE_BLOCK_INVALID: &str = "def.validate.substrate_block_invalid";
40    pub const DEF_SUBSTRATE_CONFIG_MISSING: &str = "def.validate.substrate_config_missing";
41    pub const DEF_ROOT_ORIGIN_CONFLICT: &str = "def.validate.root_origin_conflict";
42    pub const DEF_REFERENCE_SYNTAX: &str = "def.validate.reference_syntax";
43    pub const DEF_ENDPOINT_UNAVAILABLE: &str = "def.resolve.endpoint_unavailable";
44    pub const DEF_UNDECLARED_REFERENCE: &str = "def.validate.undeclared_reference";
45    pub const DEF_SECRET_NOT_REQUIRED: &str = "def.validate.secret_not_required";
46    pub const DEF_INTEGRATION_INVALID: &str = "def.validate.integration_invalid";
47    pub const DEF_WIRING_CYCLE: &str = "def.validate.wiring_cycle";
48    pub const DEF_ENV_NOT_STRINGS: &str = "def.validate.env_not_strings";
49    pub const CLI_FILE_READ: &str = "cli.file.read";
50    pub const CLI_FILE_MISSING: &str = "cli.file.missing";
51    pub const CLI_SUBSTRATE_UNKNOWN: &str = "cli.substrate.unknown";
52    pub const STATE_OPEN: &str = "state.open_failed";
53    pub const STATE_MIGRATE: &str = "state.migrate_failed";
54    pub const STATE_QUERY: &str = "state.query_failed";
55    pub const STATE_PLACEMENT_CONFLICT: &str = "state.placement_conflict";
56    pub const STATE_INSTANCE_EXISTS: &str = "state.instance.exists";
57    pub const STATE_INSTANCE_NOT_FOUND: &str = "state.instance.not_found";
58    pub const STATE_LOCK_HELD: &str = "state.lock.held";
59    pub const STATE_GC_FAILED: &str = "state.gc_failed";
60    pub const STATE_REMOTE_DISABLED: &str = "state.remote.disabled";
61    pub const STATE_REMOTE_OPEN: &str = "state.remote.open_failed";
62    pub const STATE_REMOTE_QUERY: &str = "state.remote.query_failed";
63    pub const STATE_REMOTE_RUNTIME: &str = "state.remote.runtime_failed";
64    pub const STATE_REMOTE_WORKER: &str = "state.remote.worker_gone";
65    pub const STATE_ROW_DECODE: &str = "state.row.decode_failed";
66    pub const ENGINE_SUBSTRATE_MISMATCH: &str = "engine.substrate.mismatch";
67    pub const ENGINE_SUBSTRATE_REQUIRED: &str = "engine.substrate.required";
68    pub const ENGINE_SOURCE_OVERRIDE_UNSUPPORTED: &str = "engine.source_override.unsupported";
69    pub const ENGINE_SOURCE_OVERRIDE_SHARED: &str = "engine.source_override.shared";
70    pub const OPERATION_CANCELLED: &str = "operation.cancelled";
71    pub const OPERATION_INTERRUPTED: &str = "operation.interrupted";
72    pub const OPERATION_RESULT_MISSING: &str = "operation.result_missing";
73    pub const ENGINE_STEP_FAILED: &str = "engine.step.failed";
74    pub const ENGINE_TEARDOWN_SURVIVORS: &str = "engine.teardown.survivors";
75    pub const DAEMON_UNREACHABLE: &str = "daemon.unreachable";
76    pub const DAEMON_REQUEST_FAILED: &str = "daemon.request_failed";
77    pub const DAEMON_SPAWN_FAILED: &str = "daemon.spawn_failed";
78    pub const DAEMON_BINARY_NOT_FOUND: &str = "daemon.binary_not_found";
79    pub const CLI_RUNTIME: &str = "cli.runtime";
80    pub const LOCAL_MATERIALIZE_UNAVAILABLE: &str = "local.materialize.unavailable";
81    pub const LOCAL_SOURCE_PATH_INVALID: &str = "local.source_path.invalid";
82    pub const LOCAL_CONFIG_INVALID: &str = "local.config.invalid";
83    pub const LOCAL_PORT_ALLOC: &str = "local.port.alloc_failed";
84    pub const LOCAL_LOG_FILE: &str = "local.log_file";
85    pub const LOCAL_SPAWN_FAILED: &str = "local.spawn_failed";
86    pub const LOCAL_HOOK_FAILED: &str = "local.hook_failed";
87    pub const LOCAL_HEALTH_FAILED: &str = "local.health_failed";
88    pub const LOCAL_SERVICE_DIED: &str = "local.service_died";
89    pub const LOCAL_ENV_RESOLVE: &str = "local.env_resolve";
90    pub const LOCAL_KILL_FAILED: &str = "local.kill_failed";
91    pub const LOCAL_GIT_CLONE_FAILED: &str = "local.git.clone_failed";
92    pub const LOCAL_GIT_FETCH_FAILED: &str = "local.git.fetch_failed";
93    pub const LOCAL_GIT_REF_NOT_FOUND: &str = "local.git.ref_not_found";
94    pub const LOCAL_GIT_CHECKOUT_FAILED: &str = "local.git.checkout_failed";
95    pub const CLI_BAD_ARGUMENT: &str = "cli.bad_argument";
96    pub const CLI_FILE_WRITE: &str = "cli.file.write";
97    pub const CLI_INIT_EXISTS: &str = "cli.init.exists";
98    pub const CLI_INIT_NAME_INVALID: &str = "cli.init.name_invalid";
99    pub const CLI_ADOPT_EXISTS: &str = "cli.adopt.exists";
100    pub const CLI_ADOPT_INSPECT: &str = "cli.adopt.inspect";
101    pub const CLI_SELF_UPDATE: &str = "cli.self_update";
102    pub const DOCTOR_CHECKS_FAILED: &str = "doctor.checks.failed";
103    /// Legacy local Docker datastore teardown (pre-`[datastores.*]` removal).
104    pub const LOCAL_DOCKER_ENGINE: &str = "local.docker.engine";
105    pub const LOCAL_DATASTORE_FAILED: &str = "local.datastore.failed";
106    pub const SECRETS_UNRESOLVED: &str = "secrets.unresolved";
107    pub const VERIFY_FAILED: &str = "verify.failed";
108    pub const VERIFY_NOT_DECLARED: &str = "verify.not_declared";
109    pub const VERIFY_SOURCE_UNAVAILABLE: &str = "verify.source_unavailable";
110    pub const VERIFY_TIER_UNKNOWN: &str = "verify.tier_unknown";
111    pub const VERIFY_TIER_REQUIRED: &str = "verify.tier_required";
112    pub const STRIPE_PROJECTS_UNAVAILABLE: &str = "stripe.projects.unavailable";
113    pub const STRIPE_PROJECTS_AUTH: &str = "stripe.projects.auth";
114    pub const STRIPE_PROJECTS_FAILED: &str = "stripe.projects.failed";
115    pub const STRIPE_PROJECTS_LOCK_HELD: &str = "stripe.projects.lock_held";
116    pub const STRIPE_PROJECTS_TIMEOUT: &str = "stripe.projects.timeout";
117    pub const STRIPE_PROJECTS_OUTPUT_LIMIT: &str = "stripe.projects.output_limit";
118    pub const STRIPE_PROJECTS_OUTPUT_UNAVAILABLE: &str = "stripe.projects.output_unavailable";
119    pub const STRIPE_PROJECTS_CLEANUP_FAILED: &str = "stripe.projects.cleanup_failed";
120    pub const STRIPE_PROJECT_ANCHOR: &str = "stripe.project.anchor";
121    pub const STRIPE_PROJECTS_PROVISION_FAILED: &str = "stripe.projects.provision_failed";
122    pub const STRIPE_PROJECTS_CATALOG_MISSING: &str = "stripe.projects.catalog_missing";
123    pub const STRIPE_PROJECTS_CONFIG_SCHEMA: &str = "stripe.projects.config_schema";
124    pub const INTEGRATION_CONFIG_INVALID: &str = "integration.config.invalid";
125    pub const INTEGRATION_HOST_UNSUPPORTED: &str = "integration.host.unsupported";
126
127    /// Every core code, for uniqueness tests. Substrate codes live in their
128    /// own crates (`stackless_render::codes`, …); the binary aggregates them
129    /// with these for a workspace-wide uniqueness check.
130    pub const ALL: &[&str] = &[
131        DEF_PARSE_SYNTAX,
132        DEF_PARSE_SCHEMA,
133        DEF_NAME_INVALID,
134        DEF_NO_SERVICES,
135        DEF_UNKNOWN_KEY,
136        DEF_DEPENDS_ON_REJECTED,
137        DEF_SUBSTRATE_BLOCK_INVALID,
138        DEF_SUBSTRATE_CONFIG_MISSING,
139        DEF_ROOT_ORIGIN_CONFLICT,
140        DEF_REFERENCE_SYNTAX,
141        DEF_UNDECLARED_REFERENCE,
142        DEF_ENDPOINT_UNAVAILABLE,
143        DEF_SECRET_NOT_REQUIRED,
144        DEF_INTEGRATION_INVALID,
145        DEF_WIRING_CYCLE,
146        DEF_ENV_NOT_STRINGS,
147        CLI_FILE_READ,
148        CLI_FILE_MISSING,
149        CLI_SUBSTRATE_UNKNOWN,
150        STATE_OPEN,
151        STATE_MIGRATE,
152        STATE_QUERY,
153        STATE_INSTANCE_EXISTS,
154        STATE_PLACEMENT_CONFLICT,
155        STATE_INSTANCE_NOT_FOUND,
156        STATE_LOCK_HELD,
157        STATE_GC_FAILED,
158        STATE_REMOTE_DISABLED,
159        STATE_REMOTE_OPEN,
160        STATE_REMOTE_QUERY,
161        STATE_REMOTE_RUNTIME,
162        STATE_REMOTE_WORKER,
163        STATE_ROW_DECODE,
164        ENGINE_SUBSTRATE_MISMATCH,
165        ENGINE_SUBSTRATE_REQUIRED,
166        ENGINE_SOURCE_OVERRIDE_UNSUPPORTED,
167        ENGINE_SOURCE_OVERRIDE_SHARED,
168        OPERATION_CANCELLED,
169        OPERATION_INTERRUPTED,
170        OPERATION_RESULT_MISSING,
171        ENGINE_STEP_FAILED,
172        ENGINE_TEARDOWN_SURVIVORS,
173        DAEMON_UNREACHABLE,
174        DAEMON_REQUEST_FAILED,
175        DAEMON_SPAWN_FAILED,
176        DAEMON_BINARY_NOT_FOUND,
177        CLI_RUNTIME,
178        LOCAL_MATERIALIZE_UNAVAILABLE,
179        LOCAL_SOURCE_PATH_INVALID,
180        LOCAL_CONFIG_INVALID,
181        LOCAL_PORT_ALLOC,
182        LOCAL_LOG_FILE,
183        LOCAL_SPAWN_FAILED,
184        LOCAL_HOOK_FAILED,
185        LOCAL_HEALTH_FAILED,
186        LOCAL_SERVICE_DIED,
187        LOCAL_ENV_RESOLVE,
188        LOCAL_KILL_FAILED,
189        LOCAL_GIT_CLONE_FAILED,
190        LOCAL_GIT_FETCH_FAILED,
191        LOCAL_GIT_REF_NOT_FOUND,
192        LOCAL_GIT_CHECKOUT_FAILED,
193        CLI_BAD_ARGUMENT,
194        CLI_FILE_WRITE,
195        CLI_INIT_EXISTS,
196        CLI_INIT_NAME_INVALID,
197        CLI_ADOPT_EXISTS,
198        CLI_ADOPT_INSPECT,
199        CLI_SELF_UPDATE,
200        DOCTOR_CHECKS_FAILED,
201        LOCAL_DOCKER_ENGINE,
202        LOCAL_DATASTORE_FAILED,
203        SECRETS_UNRESOLVED,
204        VERIFY_FAILED,
205        VERIFY_NOT_DECLARED,
206        VERIFY_SOURCE_UNAVAILABLE,
207        VERIFY_TIER_UNKNOWN,
208        VERIFY_TIER_REQUIRED,
209        STRIPE_PROJECTS_UNAVAILABLE,
210        STRIPE_PROJECTS_AUTH,
211        STRIPE_PROJECTS_FAILED,
212        STRIPE_PROJECTS_LOCK_HELD,
213        STRIPE_PROJECTS_TIMEOUT,
214        STRIPE_PROJECTS_OUTPUT_LIMIT,
215        STRIPE_PROJECTS_OUTPUT_UNAVAILABLE,
216        STRIPE_PROJECTS_CLEANUP_FAILED,
217        STRIPE_PROJECT_ANCHOR,
218        STRIPE_PROJECTS_PROVISION_FAILED,
219        STRIPE_PROJECTS_CATALOG_MISSING,
220        STRIPE_PROJECTS_CONFIG_SCHEMA,
221        INTEGRATION_CONFIG_INVALID,
222        INTEGRATION_HOST_UNSUPPORTED,
223    ];
224}
225
226/// Implemented by every error enum in every stackless crate.
227///
228/// A new error variant is only complete when its remediation text says
229/// what the operator should actually do (ARCHITECTURE.md §8).
230pub trait Fault: std::error::Error {
231    /// The stable machine-readable code from [`codes`].
232    fn code(&self) -> &str;
233    /// How to proceed: a concrete command, flag, or fix.
234    fn remediation(&self) -> String;
235    /// The lifecycle step that failed, when one was executing.
236    fn step(&self) -> Option<&str> {
237        None
238    }
239    /// The instance the failure belongs to, when there is one.
240    fn instance(&self) -> Option<&str> {
241        None
242    }
243    /// Structured observables for agents (`command`, `log_path`, `log_tail`, …).
244    fn context(&self) -> ErrorContext {
245        ErrorContext::default()
246    }
247}
248
249/// The serialized error shape agents consume in `--json` mode.
250#[derive(Debug, Serialize, Deserialize)]
251pub struct Report {
252    pub schema_version: u32,
253    pub code: String,
254    pub message: String,
255    #[serde(skip_serializing_if = "Option::is_none")]
256    pub step: Option<String>,
257    #[serde(skip_serializing_if = "Option::is_none")]
258    pub instance: Option<String>,
259    pub remediation: String,
260    pub context: ErrorContext,
261}
262
263impl Report {
264    pub fn from_fault(fault: &dyn Fault) -> Self {
265        Self {
266            schema_version: 2,
267            code: fault.code().to_owned(),
268            message: fault.to_string(),
269            step: fault.step().map(str::to_owned),
270            instance: fault.instance().map(str::to_owned),
271            remediation: fault.remediation(),
272            context: fault.context(),
273        }
274    }
275}
276
277impl std::fmt::Display for Report {
278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279        f.write_str(&self.message)
280    }
281}
282
283impl std::error::Error for Report {}
284
285impl Fault for Report {
286    fn code(&self) -> &str {
287        &self.code
288    }
289    fn remediation(&self) -> String {
290        self.remediation.clone()
291    }
292    fn step(&self) -> Option<&str> {
293        self.step.as_deref()
294    }
295    fn instance(&self) -> Option<&str> {
296        self.instance.as_deref()
297    }
298    fn context(&self) -> ErrorContext {
299        self.context.clone()
300    }
301}
302
303#[cfg(test)]
304mod tests {
305    use super::{ErrorContext, Report, codes};
306    use crate::substrate::SubstrateFault;
307    use std::collections::BTreeSet;
308
309    #[test]
310    fn codes_are_unique() {
311        let set: BTreeSet<_> = codes::ALL.iter().collect();
312        assert_eq!(set.len(), codes::ALL.len());
313    }
314
315    #[test]
316    fn report_serializes_schema_version_and_context() {
317        let fault = SubstrateFault {
318            code: codes::LOCAL_HOOK_FAILED.into(),
319            message: "setup hook exited with exit status: 1".into(),
320            remediation: "re-run up".into(),
321            context: Box::new(ErrorContext {
322                service: Some("web".into()),
323                hook: Some("setup".into()),
324                command: Some("mise install".into()),
325                source_dir: Some("/tmp/web".into()),
326                log_path: Some("/tmp/logs/web.log".into()),
327                exit_status: Some("exit status: 1".into()),
328                log_tail: Some("error: trust denied".into()),
329                ..ErrorContext::default()
330            }),
331        };
332        let report = Report::from_fault(&fault);
333        assert_eq!(report.schema_version, 2);
334        assert_eq!(report.context.service.as_deref(), Some("web"));
335        let json = serde_json::to_value(&report).unwrap();
336        assert_eq!(json["schema_version"], 2);
337        assert_eq!(json["context"]["command"], "mise install");
338        assert_eq!(json["context"]["log_tail"], "error: trust denied");
339    }
340}