Skip to main content

m1nd_core/
error.rs

1// === crates/m1nd-core/src/error.rs ===
2
3use crate::types::{EdgeIdx, Generation, NodeId};
4
5/// Central error type covering all failure modes from 05-HARDENING-SYNTHESIS.
6/// Each variant references its FM-ID for traceability.
7#[derive(Debug, thiserror::Error)]
8pub enum M1ndError {
9    // --- Graph integrity ---
10    /// FM-ACT-011: Edge references a node index that does not exist.
11    #[error("dangling edge: edge {edge:?} references non-existent node {node:?}")]
12    DanglingEdge { edge: EdgeIdx, node: NodeId },
13
14    /// FM-PL-006: Graph structure changed since engine was initialised.
15    #[error("graph generation mismatch: expected {expected:?}, actual {actual:?}")]
16    GraphGenerationMismatch {
17        expected: Generation,
18        actual: Generation,
19    },
20
21    /// FM-ACT-016: Attempted to add a node whose interned ID already exists.
22    #[error("duplicate node: interned ID {0:?}")]
23    DuplicateNode(NodeId),
24
25    /// Graph not finalised — CSR not built yet.
26    #[error("graph not finalised: call Graph::finalize() before queries")]
27    GraphNotFinalized,
28
29    /// Graph is empty (zero nodes).
30    #[error("graph is empty")]
31    EmptyGraph,
32
33    // --- Numerical safety ---
34    /// FM-PL-001: Non-finite value detected at a NaN firewall boundary.
35    #[error("non-finite value at firewall: node={node:?}, value={value}")]
36    NonFiniteActivation { node: NodeId, value: f32 },
37
38    /// FM-ACT-012: A tuneable parameter is outside its valid range.
39    #[error("parameter out of range: {name} = {value} (expected {range})")]
40    ParameterOutOfRange {
41        name: &'static str,
42        value: f64,
43        range: &'static str,
44    },
45
46    /// FM-RES-001: Zero or negative wavelength/frequency supplied.
47    #[error("non-positive resonance parameter: {name} = {value}")]
48    NonPositiveResonanceParam { name: &'static str, value: f32 },
49
50    // --- Resource exhaustion ---
51    /// FM-RES-004: Pulse propagation exceeded budget.
52    #[error("pulse budget exhausted: {budget} pulses processed")]
53    PulseBudgetExhausted { budget: u64 },
54
55    /// FM-TMP-005: Causal chain DFS exceeded budget.
56    #[error("chain budget exhausted: {budget} chains generated")]
57    ChainBudgetExhausted { budget: u64 },
58
59    /// FM-TMP-001: Co-change sparse matrix exceeded entry budget.
60    #[error("matrix entry budget exhausted: {budget} entries")]
61    MatrixBudgetExhausted { budget: u64 },
62
63    /// FM-ING-002: Ingestion exceeded timeout.
64    #[error("ingestion timeout after {elapsed_s:.1}s")]
65    IngestionTimeout { elapsed_s: f64 },
66
67    /// FM-ING-002: Ingestion exceeded node count budget.
68    #[error("ingestion node budget exhausted: {budget} nodes")]
69    IngestionNodeBudget { budget: u64 },
70
71    /// FM-TOP-014: Fingerprint pair budget exceeded.
72    #[error("fingerprint pair budget exhausted: {budget} pairs")]
73    FingerprintPairBudget { budget: u64 },
74
75    // --- Analysis quality ---
76    /// FM-XLR-010: XLR cancelled all signal — fallback to hot-only.
77    #[error("XLR over-cancellation: all signal cancelled")]
78    XlrOverCancellation,
79
80    /// FM-TOP-003: Louvain community detection did not converge.
81    #[error("Louvain non-convergence after {passes} passes")]
82    LouvainNonConvergence { passes: u32 },
83
84    /// FM-TOP-010: Power iteration may have diverged.
85    #[error("spectral analysis: power iteration divergence suspected")]
86    SpectralDivergence,
87
88    /// FM-RES-020: Division by zero in normalization (max_amp == 0).
89    #[error("resonance normalization: max amplitude is zero")]
90    ResonanceZeroAmplitude,
91
92    /// FM-ACT-019: Atomic CAS retry limit exceeded during concurrent weight update.
93    #[error("CAS retry limit ({limit}) exceeded at edge {edge:?}")]
94    CasRetryExhausted { edge: EdgeIdx, limit: u32 },
95
96    // --- Ingestion ---
97    /// FM-ING-003: File encoding could not be determined.
98    #[error("encoding detection failed for {path} (confidence={confidence:.2})")]
99    EncodingDetectionFailed { path: String, confidence: f32 },
100
101    /// FM-ING-004: Binary file detected and skipped.
102    #[error("binary file skipped: {path}")]
103    BinaryFileSkipped { path: String },
104
105    /// FM-ING-008: Label collision — multiple nodes share a label.
106    #[error("label collision: {label} maps to {count} nodes")]
107    LabelCollision { label: String, count: usize },
108
109    // --- Persistence ---
110    /// FM-PL-007: Corrupt state file on load.
111    #[error("corrupt persistence state: {reason}")]
112    CorruptState { reason: String },
113
114    /// FM-PL-009: Schema drift — edge identity mismatch on import.
115    #[error("schema drift on import: {reason}")]
116    SchemaDrift { reason: String },
117
118    /// OPTIONAL `embed` feature: failed to load or run the static embedding model.
119    #[error("embed error: {0}")]
120    EmbedError(String),
121
122    // --- Counterfactual ---
123    /// FM-CF-001: Seed node was in the removal set.
124    #[error("counterfactual seed overlap: seed {node:?} is in the removal set")]
125    CounterfactualSeedOverlap { node: NodeId },
126
127    // --- Perspective / Lock / Navigation (12-PERSPECTIVE-SYNTHESIS Theme 3) ---
128    /// Theme 3: Unknown tool name in dispatch.
129    #[error("unknown tool: {name}")]
130    UnknownTool { name: String },
131
132    /// Theme 3: Invalid parameters for a tool call.
133    #[error("invalid params for {tool}: {detail}")]
134    InvalidParams { tool: String, detail: String },
135
136    /// Theme 3: Perspective does not exist for agent.
137    #[error("perspective not found: {perspective_id} for agent {agent_id}")]
138    PerspectiveNotFound {
139        perspective_id: String,
140        agent_id: String,
141    },
142
143    /// Theme 3: Perspective route set is stale (generation mismatch).
144    #[error(
145        "perspective stale: {perspective_id} expected gen {expected_gen}, actual {actual_gen}"
146    )]
147    PerspectiveStale {
148        perspective_id: String,
149        expected_gen: u64,
150        actual_gen: u64,
151    },
152
153    /// Theme 3: Agent exceeded max perspective count.
154    #[error("perspective limit exceeded for agent {agent_id}: {current}/{limit}")]
155    PerspectiveLimitExceeded {
156        agent_id: String,
157        current: usize,
158        limit: usize,
159    },
160
161    /// Theme 3: Route set version mismatch (stale cached routes).
162    #[error("route set stale: version {route_set_version}, current {current_version}")]
163    RouteSetStale {
164        route_set_version: u64,
165        current_version: u64,
166    },
167
168    /// Theme 3: Route not found in perspective.
169    #[error("route not found: {route_id} in perspective {perspective_id}")]
170    RouteNotFound {
171        route_id: String,
172        perspective_id: String,
173    },
174
175    /// Theme 3: Cannot navigate back — already at root.
176    #[error("navigation at root: perspective {perspective_id}")]
177    NavigationAtRoot { perspective_id: String },
178
179    /// Theme 3: Branch depth limit exceeded.
180    #[error("branch depth exceeded in {perspective_id}: depth {depth}/{limit}")]
181    BranchDepthExceeded {
182        perspective_id: String,
183        depth: usize,
184        limit: usize,
185    },
186
187    /// Theme 3: Lock not found.
188    #[error("lock not found: {lock_id}")]
189    LockNotFound { lock_id: String },
190
191    /// Theme 3: Lock ownership violation.
192    #[error("lock ownership violation: {lock_id} owned by {owner}, called by {caller}")]
193    LockOwnership {
194        lock_id: String,
195        owner: String,
196        caller: String,
197    },
198
199    /// Theme 3: Lock scope too large (BFS budget exceeded).
200    #[error("lock scope too large: {node_count} nodes exceeds cap of {cap}")]
201    LockScopeTooLarge { node_count: usize, cap: usize },
202
203    /// Theme 3: Agent exceeded max lock count.
204    #[error("lock limit exceeded for agent {agent_id}: {current}/{limit}")]
205    LockLimitExceeded {
206        agent_id: String,
207        current: usize,
208        limit: usize,
209    },
210
211    /// Theme 3: Watcher strategy not supported (e.g. Periodic in V1).
212    #[error("watch strategy not supported: {strategy}")]
213    WatchStrategyNotSupported { strategy: String },
214
215    /// Theme 3: Affinity computation exceeded time budget.
216    #[error("affinity timeout: {elapsed_ms:.1}ms exceeded budget of {budget_ms:.1}ms")]
217    AffinityTimeout { elapsed_ms: f64, budget_ms: f64 },
218
219    // --- Antibody ---
220    /// FM-AB-001: Antibody pattern specificity below minimum threshold.
221    #[error("pattern too broad: specificity {specificity:.2} below minimum {minimum:.2}")]
222    PatternTooBroad { specificity: f32, minimum: f32 },
223
224    /// Antibody not found by ID.
225    #[error("antibody not found: {id}")]
226    AntibodyNotFound { id: String },
227
228    /// Antibody storage limit exceeded.
229    #[error("antibody limit exceeded: {current}/{limit}")]
230    AntibodyLimitExceeded { current: usize, limit: usize },
231
232    // --- Epidemic ---
233    /// Epidemic burnout: too many nodes infected too fast.
234    #[error("epidemic burnout: {infected_pct:.1}% infected in {iteration} iterations")]
235    EpidemicBurnout { infected_pct: f32, iteration: u32 },
236
237    /// No valid infected nodes provided for epidemic simulation.
238    #[error("no valid infected nodes")]
239    NoValidInfectedNodes,
240
241    // --- Flow ---
242    /// No entry points found for flow simulation.
243    #[error("no entry points found for flow simulation")]
244    NoEntryPoints,
245
246    // --- Layers ---
247    /// Layer level not found in detection result.
248    #[error("layer not found: level {level}")]
249    LayerNotFound { level: u8 },
250
251    // --- Ingestion (runtime) ---
252    /// Tree-sitter or extractor runtime error.
253    #[error("ingest error: {0}")]
254    IngestError(String),
255
256    // --- I/O ---
257    #[error("I/O error: {0}")]
258    Io(#[from] std::io::Error),
259
260    #[error("serialization error: {0}")]
261    Serde(#[from] serde_json::Error),
262
263    #[error("persistence failed: {0}")]
264    PersistenceFailed(String),
265}
266
267/// Convenience alias used throughout the crate.
268pub type M1ndResult<T> = Result<T, M1ndError>;