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::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, 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_UNDECLARED_REFERENCE: &str = "def.validate.undeclared_reference";
44    pub const DEF_SECRET_NOT_REQUIRED: &str = "def.validate.secret_not_required";
45    pub const DEF_INTEGRATION_INVALID: &str = "def.validate.integration_invalid";
46    pub const DEF_WIRING_CYCLE: &str = "def.validate.wiring_cycle";
47    pub const DEF_ENV_NOT_STRINGS: &str = "def.validate.env_not_strings";
48    pub const CLI_FILE_READ: &str = "cli.file.read";
49    pub const CLI_FILE_MISSING: &str = "cli.file.missing";
50    pub const CLI_SUBSTRATE_UNKNOWN: &str = "cli.substrate.unknown";
51    pub const STATE_OPEN: &str = "state.open_failed";
52    pub const STATE_MIGRATE: &str = "state.migrate_failed";
53    pub const STATE_QUERY: &str = "state.query_failed";
54    pub const STATE_INSTANCE_EXISTS: &str = "state.instance.exists";
55    pub const STATE_INSTANCE_NOT_FOUND: &str = "state.instance.not_found";
56    pub const STATE_LOCK_HELD: &str = "state.lock.held";
57    pub const STATE_GC_FAILED: &str = "state.gc_failed";
58    pub const STATE_REMOTE_OPEN: &str = "state.remote.open_failed";
59    pub const STATE_REMOTE_QUERY: &str = "state.remote.query_failed";
60    pub const STATE_REMOTE_RUNTIME: &str = "state.remote.runtime_failed";
61    pub const STATE_REMOTE_WORKER: &str = "state.remote.worker_gone";
62    pub const STATE_ROW_DECODE: &str = "state.row.decode_failed";
63    pub const ENGINE_SUBSTRATE_MISMATCH: &str = "engine.substrate.mismatch";
64    pub const ENGINE_SUBSTRATE_REQUIRED: &str = "engine.substrate.required";
65    pub const ENGINE_SOURCE_OVERRIDE_UNSUPPORTED: &str = "engine.source_override.unsupported";
66    pub const ENGINE_SOURCE_OVERRIDE_SHARED: &str = "engine.source_override.shared";
67    pub const ENGINE_STEP_FAILED: &str = "engine.step.failed";
68    pub const ENGINE_TEARDOWN_SURVIVORS: &str = "engine.teardown.survivors";
69    pub const DAEMON_UNREACHABLE: &str = "daemon.unreachable";
70    pub const DAEMON_REQUEST_FAILED: &str = "daemon.request_failed";
71    pub const DAEMON_SPAWN_FAILED: &str = "daemon.spawn_failed";
72    pub const DAEMON_BINARY_NOT_FOUND: &str = "daemon.binary_not_found";
73    pub const CLI_RUNTIME: &str = "cli.runtime";
74    pub const LOCAL_MATERIALIZE_UNAVAILABLE: &str = "local.materialize.unavailable";
75    pub const LOCAL_SOURCE_PATH_INVALID: &str = "local.source_path.invalid";
76    pub const LOCAL_CONFIG_INVALID: &str = "local.config.invalid";
77    pub const LOCAL_PORT_ALLOC: &str = "local.port.alloc_failed";
78    pub const LOCAL_LOG_FILE: &str = "local.log_file";
79    pub const LOCAL_SPAWN_FAILED: &str = "local.spawn_failed";
80    pub const LOCAL_HOOK_FAILED: &str = "local.hook_failed";
81    pub const LOCAL_HEALTH_FAILED: &str = "local.health_failed";
82    pub const LOCAL_SERVICE_DIED: &str = "local.service_died";
83    pub const LOCAL_ENV_RESOLVE: &str = "local.env_resolve";
84    pub const LOCAL_KILL_FAILED: &str = "local.kill_failed";
85    pub const LOCAL_GIT_CLONE_FAILED: &str = "local.git.clone_failed";
86    pub const LOCAL_GIT_FETCH_FAILED: &str = "local.git.fetch_failed";
87    pub const LOCAL_GIT_REF_NOT_FOUND: &str = "local.git.ref_not_found";
88    pub const LOCAL_GIT_CHECKOUT_FAILED: &str = "local.git.checkout_failed";
89    pub const CLI_BAD_ARGUMENT: &str = "cli.bad_argument";
90    pub const CLI_FILE_WRITE: &str = "cli.file.write";
91    pub const CLI_INIT_EXISTS: &str = "cli.init.exists";
92    pub const CLI_INIT_NAME_INVALID: &str = "cli.init.name_invalid";
93    pub const CLI_ADOPT_EXISTS: &str = "cli.adopt.exists";
94    pub const CLI_ADOPT_INSPECT: &str = "cli.adopt.inspect";
95    pub const CLI_SELF_UPDATE: &str = "cli.self_update";
96    pub const DOCTOR_CHECKS_FAILED: &str = "doctor.checks.failed";
97    /// Legacy local Docker datastore teardown (pre-`[datastores.*]` removal).
98    pub const LOCAL_DOCKER_ENGINE: &str = "local.docker.engine";
99    pub const LOCAL_DATASTORE_FAILED: &str = "local.datastore.failed";
100    pub const SECRETS_UNRESOLVED: &str = "secrets.unresolved";
101    pub const VERIFY_FAILED: &str = "verify.failed";
102    pub const VERIFY_NOT_DECLARED: &str = "verify.not_declared";
103    pub const VERIFY_SOURCE_UNAVAILABLE: &str = "verify.source_unavailable";
104    pub const VERIFY_TIER_UNKNOWN: &str = "verify.tier_unknown";
105    pub const VERIFY_TIER_REQUIRED: &str = "verify.tier_required";
106    pub const STRIPE_PROJECTS_UNAVAILABLE: &str = "stripe.projects.unavailable";
107    pub const STRIPE_PROJECTS_AUTH: &str = "stripe.projects.auth";
108    pub const STRIPE_PROJECTS_FAILED: &str = "stripe.projects.failed";
109    pub const STRIPE_PROJECTS_LOCK_HELD: &str = "stripe.projects.lock_held";
110    pub const STRIPE_PROJECT_ANCHOR: &str = "stripe.project.anchor";
111    pub const STRIPE_PROJECTS_PROVISION_FAILED: &str = "stripe.projects.provision_failed";
112    pub const STRIPE_PROJECTS_CATALOG_MISSING: &str = "stripe.projects.catalog_missing";
113    pub const STRIPE_PROJECTS_CONFIG_SCHEMA: &str = "stripe.projects.config_schema";
114    pub const INTEGRATION_CONFIG_INVALID: &str = "integration.config.invalid";
115    pub const INTEGRATION_HOST_UNSUPPORTED: &str = "integration.host.unsupported";
116
117    /// Every core code, for uniqueness tests. Substrate codes live in their
118    /// own crates (`stackless_render::codes`, …); the binary aggregates them
119    /// with these for a workspace-wide uniqueness check.
120    pub const ALL: &[&str] = &[
121        DEF_PARSE_SYNTAX,
122        DEF_PARSE_SCHEMA,
123        DEF_NAME_INVALID,
124        DEF_NO_SERVICES,
125        DEF_UNKNOWN_KEY,
126        DEF_DEPENDS_ON_REJECTED,
127        DEF_SUBSTRATE_BLOCK_INVALID,
128        DEF_SUBSTRATE_CONFIG_MISSING,
129        DEF_ROOT_ORIGIN_CONFLICT,
130        DEF_REFERENCE_SYNTAX,
131        DEF_UNDECLARED_REFERENCE,
132        DEF_SECRET_NOT_REQUIRED,
133        DEF_INTEGRATION_INVALID,
134        DEF_WIRING_CYCLE,
135        DEF_ENV_NOT_STRINGS,
136        CLI_FILE_READ,
137        CLI_FILE_MISSING,
138        CLI_SUBSTRATE_UNKNOWN,
139        STATE_OPEN,
140        STATE_MIGRATE,
141        STATE_QUERY,
142        STATE_INSTANCE_EXISTS,
143        STATE_INSTANCE_NOT_FOUND,
144        STATE_LOCK_HELD,
145        STATE_GC_FAILED,
146        STATE_REMOTE_OPEN,
147        STATE_REMOTE_QUERY,
148        STATE_REMOTE_RUNTIME,
149        STATE_REMOTE_WORKER,
150        STATE_ROW_DECODE,
151        ENGINE_SUBSTRATE_MISMATCH,
152        ENGINE_SUBSTRATE_REQUIRED,
153        ENGINE_SOURCE_OVERRIDE_UNSUPPORTED,
154        ENGINE_SOURCE_OVERRIDE_SHARED,
155        ENGINE_STEP_FAILED,
156        ENGINE_TEARDOWN_SURVIVORS,
157        DAEMON_UNREACHABLE,
158        DAEMON_REQUEST_FAILED,
159        DAEMON_SPAWN_FAILED,
160        DAEMON_BINARY_NOT_FOUND,
161        CLI_RUNTIME,
162        LOCAL_MATERIALIZE_UNAVAILABLE,
163        LOCAL_SOURCE_PATH_INVALID,
164        LOCAL_CONFIG_INVALID,
165        LOCAL_PORT_ALLOC,
166        LOCAL_LOG_FILE,
167        LOCAL_SPAWN_FAILED,
168        LOCAL_HOOK_FAILED,
169        LOCAL_HEALTH_FAILED,
170        LOCAL_SERVICE_DIED,
171        LOCAL_ENV_RESOLVE,
172        LOCAL_KILL_FAILED,
173        LOCAL_GIT_CLONE_FAILED,
174        LOCAL_GIT_FETCH_FAILED,
175        LOCAL_GIT_REF_NOT_FOUND,
176        LOCAL_GIT_CHECKOUT_FAILED,
177        CLI_BAD_ARGUMENT,
178        CLI_FILE_WRITE,
179        CLI_INIT_EXISTS,
180        CLI_INIT_NAME_INVALID,
181        CLI_ADOPT_EXISTS,
182        CLI_ADOPT_INSPECT,
183        CLI_SELF_UPDATE,
184        DOCTOR_CHECKS_FAILED,
185        LOCAL_DOCKER_ENGINE,
186        LOCAL_DATASTORE_FAILED,
187        SECRETS_UNRESOLVED,
188        VERIFY_FAILED,
189        VERIFY_NOT_DECLARED,
190        VERIFY_SOURCE_UNAVAILABLE,
191        VERIFY_TIER_UNKNOWN,
192        VERIFY_TIER_REQUIRED,
193        STRIPE_PROJECTS_UNAVAILABLE,
194        STRIPE_PROJECTS_AUTH,
195        STRIPE_PROJECTS_FAILED,
196        STRIPE_PROJECTS_LOCK_HELD,
197        STRIPE_PROJECT_ANCHOR,
198        STRIPE_PROJECTS_PROVISION_FAILED,
199        STRIPE_PROJECTS_CATALOG_MISSING,
200        STRIPE_PROJECTS_CONFIG_SCHEMA,
201        INTEGRATION_CONFIG_INVALID,
202        INTEGRATION_HOST_UNSUPPORTED,
203    ];
204}
205
206/// Implemented by every error enum in every stackless crate.
207///
208/// A new error variant is only complete when its remediation text says
209/// what the operator should actually do (ARCHITECTURE.md §8).
210pub trait Fault: std::error::Error {
211    /// The stable machine-readable code from [`codes`].
212    fn code(&self) -> &'static str;
213    /// How to proceed: a concrete command, flag, or fix.
214    fn remediation(&self) -> String;
215    /// The lifecycle step that failed, when one was executing.
216    fn step(&self) -> Option<&str> {
217        None
218    }
219    /// The instance the failure belongs to, when there is one.
220    fn instance(&self) -> Option<&str> {
221        None
222    }
223    /// Structured observables for agents (`command`, `log_path`, `log_tail`, …).
224    fn context(&self) -> ErrorContext {
225        ErrorContext::default()
226    }
227}
228
229/// The serialized error shape agents consume in `--json` mode.
230#[derive(Debug, Serialize)]
231pub struct Report {
232    pub schema_version: u32,
233    pub code: &'static str,
234    pub message: String,
235    #[serde(skip_serializing_if = "Option::is_none")]
236    pub step: Option<String>,
237    #[serde(skip_serializing_if = "Option::is_none")]
238    pub instance: Option<String>,
239    pub remediation: String,
240    pub context: ErrorContext,
241}
242
243impl Report {
244    pub fn from_fault(fault: &dyn Fault) -> Self {
245        Self {
246            schema_version: 1,
247            code: fault.code(),
248            message: fault.to_string(),
249            step: fault.step().map(str::to_owned),
250            instance: fault.instance().map(str::to_owned),
251            remediation: fault.remediation(),
252            context: fault.context(),
253        }
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::{ErrorContext, Report, codes};
260    use crate::substrate::SubstrateFault;
261    use std::collections::BTreeSet;
262
263    #[test]
264    fn codes_are_unique() {
265        let set: BTreeSet<_> = codes::ALL.iter().collect();
266        assert_eq!(set.len(), codes::ALL.len());
267    }
268
269    #[test]
270    fn report_serializes_schema_version_and_context() {
271        let fault = SubstrateFault {
272            code: codes::LOCAL_HOOK_FAILED,
273            message: "setup hook exited with exit status: 1".into(),
274            remediation: "re-run up".into(),
275            context: Box::new(ErrorContext {
276                service: Some("web".into()),
277                hook: Some("setup".into()),
278                command: Some("mise install".into()),
279                source_dir: Some("/tmp/web".into()),
280                log_path: Some("/tmp/logs/web.log".into()),
281                exit_status: Some("exit status: 1".into()),
282                log_tail: Some("error: trust denied".into()),
283                ..ErrorContext::default()
284            }),
285        };
286        let report = Report::from_fault(&fault);
287        assert_eq!(report.schema_version, 1);
288        assert_eq!(report.context.service.as_deref(), Some("web"));
289        let json = serde_json::to_value(&report).unwrap();
290        assert_eq!(json["schema_version"], 1);
291        assert_eq!(json["context"]["command"], "mise install");
292        assert_eq!(json["context"]["log_tail"], "error: trust denied");
293    }
294}