1use std::borrow::Cow;
2use std::fmt;
3
4use anyhow::{Error, Result};
5
6pub const ERR_READ_FILE: &str = "failed to read file";
8pub const ERR_WRITE_FILE: &str = "failed to write file";
9pub const ERR_READ_DIR: &str = "failed to read directory";
10pub const ERR_CREATE_DIR: &str = "failed to create directory";
11pub const ERR_REMOVE_FILE: &str = "failed to remove file";
12pub const ERR_REMOVE_DIR: &str = "failed to remove directory";
13pub const ERR_READ_DIR_ENTRY: &str = "failed to read directory entry";
14pub const ERR_GET_FILE_TYPE: &str = "failed to read file type";
15pub const ERR_GET_METADATA: &str = "failed to read file metadata";
16pub const ERR_CANONICALIZE_PATH: &str = "failed to canonicalize path";
17pub const ERR_READ_SYMLINK: &str = "failed to read symlink";
18
19pub const ERR_CREATE_SKILLS_DIR: &str = "failed to create skills directory";
21pub const ERR_CREATE_SKILL_DIR: &str = "failed to create skill directory";
22pub const ERR_READ_SKILL_CODE: &str = "failed to read skill code";
23pub const ERR_WRITE_SKILL_CODE: &str = "failed to write skill code";
24pub const ERR_READ_SKILL_METADATA: &str = "failed to read skill metadata";
25pub const ERR_WRITE_SKILL_METADATA: &str = "failed to write skill metadata";
26pub const ERR_PARSE_SKILL_METADATA: &str = "failed to parse skill metadata";
27pub const ERR_WRITE_SKILL_DOCS: &str = "failed to write skill documentation";
28pub const ERR_DELETE_SKILL: &str = "failed to delete skill";
29pub const ERR_READ_SKILLS_DIR: &str = "failed to read skills directory";
30pub const ERR_TOOL_DENIED: &str = "tool denied or unavailable by policy";
31
32pub const ERR_CREATE_AUDIT_DIR: &str = "Failed to create audit directory";
34pub const ERR_WRITE_AUDIT_LOG: &str = "failed to write audit log";
35
36pub const ERR_CREATE_CHECKPOINT_DIR: &str = "failed to create checkpoint directory";
38pub const ERR_WRITE_CHECKPOINT: &str = "failed to write checkpoint";
39pub const ERR_READ_CHECKPOINT: &str = "failed to read checkpoint";
40
41pub const ERR_CREATE_POLICY_DIR: &str = "Failed to create directory for tool policy config";
43pub const ERR_CREATE_WORKSPACE_POLICY_DIR: &str = "Failed to create workspace policy directory";
44
45pub const ERR_SERIALIZE_METADATA: &str = "failed to serialize skill metadata";
47pub const ERR_SERIALIZE_STATE: &str = "failed to serialize state";
48pub const ERR_DESERIALIZE: &str = "failed to deserialize data";
49
50pub const ERR_CREATE_IPC_DIR: &str = "failed to create IPC directory";
52pub const ERR_READ_REQUEST_FILE: &str = "failed to read request file";
53pub const ERR_READ_REQUEST_JSON: &str = "failed to read request JSON";
54pub const ERR_PARSE_REQUEST_JSON: &str = "failed to parse request JSON";
55pub const ERR_PARSE_ARGS: &str = "failed to parse tokenized args";
56pub const ERR_PARSE_RESULT: &str = "failed to parse de-tokenized result";
57
58#[macro_export]
61macro_rules! file_err {
62 ($path:expr, read) => {
63 format!("failed to read {}", $path)
64 };
65 ($path:expr, write) => {
66 format!("failed to write {}", $path)
67 };
68 ($path:expr, delete) => {
69 format!("failed to delete {}", $path)
70 };
71 ($path:expr, create) => {
72 format!("failed to create {}", $path)
73 };
74}
75
76#[macro_export]
79macro_rules! ctx_err {
80 ($op:expr, $ctx:expr) => {
81 format!("{}: {}", $op, $ctx)
82 };
83}
84
85pub trait ErrorFormatter: Send + Sync {
89 fn format_error(&self, error: &Error) -> Cow<'_, str>;
91}
92
93pub trait ErrorReporter: Send + Sync {
95 fn capture(&self, error: &Error) -> Result<()>;
97
98 fn capture_message(&self, message: impl Into<Cow<'static, str>>) -> Result<()> {
100 let message: Cow<'static, str> = message.into();
101 self.capture(&Error::msg(message))
102 }
103}
104
105#[derive(Debug, Default, Clone, Copy)]
108pub struct NoopErrorReporter;
109
110impl ErrorReporter for NoopErrorReporter {
111 fn capture(&self, _error: &Error) -> Result<()> {
112 Ok(())
113 }
114}
115
116#[derive(Debug, Default, Clone, Copy)]
118pub struct DisplayErrorFormatter;
119
120impl ErrorFormatter for DisplayErrorFormatter {
121 fn format_error(&self, error: &Error) -> Cow<'_, str> {
122 Cow::Owned(format!("{error}"))
123 }
124}
125
126#[derive(Debug, Clone)]
150pub struct MultiErrors<E = Error> {
151 errors: Vec<E>,
152}
153
154impl<E> MultiErrors<E> {
155 pub fn new() -> Self {
157 Self { errors: Vec::new() }
158 }
159
160 pub fn push(&mut self, error: E) {
162 self.errors.push(error);
163 }
164
165 pub fn extend(&mut self, iter: impl IntoIterator<Item = E>) {
167 self.errors.extend(iter);
168 }
169
170 #[must_use]
172 pub fn is_empty(&self) -> bool {
173 self.errors.is_empty()
174 }
175
176 #[must_use]
178 pub fn len(&self) -> usize {
179 self.errors.len()
180 }
181
182 #[must_use]
184 pub fn into_inner(self) -> Vec<E> {
185 self.errors
186 }
187
188 #[must_use]
190 pub fn as_slice(&self) -> &[E] {
191 &self.errors
192 }
193
194 pub fn iter(&self) -> std::slice::Iter<'_, E> {
196 self.errors.iter()
197 }
198
199 pub fn ok(self) -> std::result::Result<(), Self> {
201 if self.errors.is_empty() { Ok(()) } else { Err(self) }
202 }
203
204 pub fn clear(&mut self) {
206 self.errors.clear();
207 }
208
209 pub fn collect_result<T, F>(&mut self, result: std::result::Result<T, F>) -> Option<T>
214 where
215 F: Into<E>,
216 {
217 match result {
218 Ok(val) => Some(val),
219 Err(e) => {
220 self.errors.push(e.into());
221 None
222 }
223 }
224 }
225
226 #[must_use]
228 pub fn to_anyhow(&self) -> Error
229 where
230 E: fmt::Display,
231 {
232 Error::msg(self.to_string())
233 }
234}
235
236impl<E> Default for MultiErrors<E> {
237 fn default() -> Self {
238 Self::new()
239 }
240}
241
242impl<E> From<Vec<E>> for MultiErrors<E> {
243 fn from(errors: Vec<E>) -> Self {
244 Self { errors }
245 }
246}
247
248impl<E> IntoIterator for MultiErrors<E> {
249 type Item = E;
250 type IntoIter = std::vec::IntoIter<E>;
251
252 fn into_iter(self) -> Self::IntoIter {
253 self.errors.into_iter()
254 }
255}
256
257impl<E: serde::Serialize> serde::Serialize for MultiErrors<E> {
258 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
259 self.errors.serialize(serializer)
260 }
261}
262
263impl<'de, E: serde::Deserialize<'de>> serde::Deserialize<'de> for MultiErrors<E> {
264 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
265 Vec::<E>::deserialize(deserializer).map(|errors| Self { errors })
266 }
267}
268
269impl<E: fmt::Display> fmt::Display for MultiErrors<E> {
270 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271 match self.errors.len() {
272 0 => write!(f, "no errors"),
273 1 => write!(f, "{}", self.errors[0]),
274 _ => {
275 for (i, error) in self.errors.iter().enumerate() {
276 if i > 0 {
277 writeln!(f)?;
278 }
279 write!(f, " {}. {error}", i + 1)?;
280 }
281 Ok(())
282 }
283 }
284 }
285}
286
287impl<E: std::error::Error + 'static> std::error::Error for MultiErrors<E> {
288 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
289 self.errors.first().map(|e| e as &(dyn std::error::Error + 'static))
290 }
291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296
297 #[test]
298 fn formatter_uses_display() {
299 let formatter = DisplayErrorFormatter;
300 let error = Error::msg("test error");
301 assert_eq!(formatter.format_error(&error), "test error");
302 }
303
304 #[test]
305 fn noop_reporter_drops_errors() {
306 let reporter = NoopErrorReporter;
307 let error = Error::msg("test");
308 assert!(reporter.capture(&error).is_ok());
309 assert!(reporter.capture_message("message").is_ok());
310 }
311
312 #[test]
313 fn multi_errors_new_is_empty() {
314 let errors: MultiErrors<String> = MultiErrors::new();
315 assert!(errors.is_empty());
316 assert_eq!(errors.len(), 0);
317 }
318
319 #[test]
320 fn multi_errors_push_and_len() {
321 let mut errors = MultiErrors::new();
322 errors.push("error 1".to_string());
323 errors.push("error 2".to_string());
324 assert!(!errors.is_empty());
325 assert_eq!(errors.len(), 2);
326 }
327
328 #[test]
329 fn multi_errors_collect_result_ok() {
330 let mut errors: MultiErrors<String> = MultiErrors::new();
331 let value: i32 = errors.collect_result(Ok::<_, String>(42)).unwrap_or(0);
332 assert_eq!(value, 42);
333 assert!(errors.is_empty());
334 }
335
336 #[test]
337 fn multi_errors_collect_result_err() {
338 let mut errors: MultiErrors<String> = MultiErrors::new();
339 let value: i32 = errors.collect_result(Err::<i32, String>("bad".to_string())).unwrap_or(0);
340 assert_eq!(value, 0);
341 assert_eq!(errors.len(), 1);
342 }
343
344 #[test]
345 fn multi_errors_ok_succeeds_when_empty() {
346 let errors: MultiErrors<String> = MultiErrors::new();
347 assert!(errors.ok().is_ok());
348 }
349
350 #[test]
351 fn multi_errors_ok_fails_when_not_empty() {
352 let mut errors = MultiErrors::new();
353 errors.push("error".to_string());
354 assert!(errors.ok().is_err());
355 }
356
357 #[test]
358 fn multi_errors_display_empty() {
359 let errors: MultiErrors<String> = MultiErrors::new();
360 assert_eq!(errors.to_string(), "no errors");
361 }
362
363 #[test]
364 fn multi_errors_display_single() {
365 let mut errors = MultiErrors::new();
366 errors.push("something failed".to_string());
367 assert_eq!(errors.to_string(), "something failed");
368 }
369
370 #[test]
371 fn multi_errors_display_multiple() {
372 let mut errors = MultiErrors::new();
373 errors.push("first issue".to_string());
374 errors.push("second issue".to_string());
375 let display = errors.to_string();
376 assert!(display.contains("1. first issue"));
377 assert!(display.contains("2. second issue"));
378 }
379
380 #[test]
381 fn multi_errors_extend() {
382 let mut errors = MultiErrors::new();
383 errors.extend(vec!["a".to_string(), "b".to_string()]);
384 assert_eq!(errors.len(), 2);
385 }
386
387 #[test]
388 fn multi_errors_into_inner() {
389 let mut errors = MultiErrors::new();
390 errors.push("test".to_string());
391 let inner: Vec<String> = errors.into_inner();
392 assert_eq!(inner.len(), 1);
393 }
394
395 #[test]
396 fn multi_errors_from_vec() {
397 let errors: MultiErrors<String> = MultiErrors::from(vec!["a".to_string()]);
398 assert_eq!(errors.len(), 1);
399 }
400
401 #[test]
402 fn multi_errors_into_iterator() {
403 let mut errors = MultiErrors::new();
404 errors.push("a".to_string());
405 errors.push("b".to_string());
406 let collected: Vec<String> = errors.into_iter().collect();
407 assert_eq!(collected, vec!["a", "b"]);
408 }
409
410 #[test]
411 fn multi_errors_slice_access() {
412 let mut errors = MultiErrors::new();
413 errors.push("err".to_string());
414 assert_eq!(errors.as_slice(), &["err".to_string()]);
415 }
416
417 #[test]
418 fn multi_errors_to_anyhow() {
419 let mut errors = MultiErrors::new();
420 errors.push("something broke".to_string());
421 let err = errors.to_anyhow();
422 assert!(err.to_string().contains("something broke"));
423 }
424}