exomonad-core 0.1.0

ExoMonad core: effect system, WASM hosting, MCP server, built-in handlers, shared types
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! Domain types with parse-at-edge validation.
//!
//! This module provides newtype wrappers for string domain concepts
//! with validation at construction time. All parsing happens at the
//! boundary (deserialization, construction) to ensure invalid values
//! never enter the system.

use serde::{Deserialize, Serialize};
use std::fmt;

// ============================================================================
// Error Types
// ============================================================================

/// Domain validation errors.
#[derive(Debug, thiserror::Error)]
pub enum DomainError {
    /// Empty field value.
    #[error("empty {field}")]
    Empty { field: &'static str },

    /// Invalid field value.
    #[error("invalid {field}: {value}")]
    Invalid { field: &'static str, value: String },

    /// Parse error for numeric types.
    #[error("parse error for {field}: {value}")]
    ParseError { field: &'static str, value: String },
}

// ============================================================================
// Validated String Macro
// ============================================================================

/// Generate a validated non-empty string newtype with standard impls.
///
/// Provides: TryFrom<String>, From<&str>, From<T> for String, Display,
/// as_str(), and serde support via try_from/into.
macro_rules! validated_string {
    ($(#[doc = $doc:expr])* $name:ident, $field:expr) => {
        $(#[doc = $doc])*
        #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
        #[serde(try_from = "String", into = "String")]
        pub struct $name(String);

        impl TryFrom<String> for $name {
            type Error = DomainError;

            fn try_from(s: String) -> Result<Self, Self::Error> {
                if s.is_empty() {
                    return Err(DomainError::Empty { field: $field });
                }
                Ok(Self(s))
            }
        }

        impl From<$name> for String {
            fn from(val: $name) -> String {
                val.0
            }
        }

        impl From<&str> for $name {
            fn from(s: &str) -> Self {
                Self(s.to_string())
            }
        }

        impl $name {
            /// Get the value as a string slice.
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "{}", self.0)
            }
        }
    };
}

// ============================================================================
// String Newtypes
// ============================================================================

validated_string!(
    #[doc = "Session identifier (non-empty string)."]
    SessionId,
    "session_id"
);
validated_string!(
    #[doc = "Tool name identifier (non-empty string)."]
    ToolName,
    "tool_name"
);
validated_string!(
    #[doc = "GitHub repository owner (non-empty string)."]
    GithubOwner,
    "github_owner"
);
validated_string!(
    #[doc = "GitHub repository name (non-empty string)."]
    GithubRepo,
    "github_repo"
);

#[cfg(test)]
impl SessionId {
    /// Create from &str (unchecked, for tests).
    pub fn from_str_unchecked(s: &str) -> Self {
        Self(s.to_string())
    }
}

// ============================================================================
// GitHub Issue Number
// ============================================================================

/// GitHub issue number (positive integer).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "u64", into = "u64")]
pub struct IssueNumber(u64);

impl TryFrom<u64> for IssueNumber {
    type Error = DomainError;

    fn try_from(n: u64) -> Result<Self, Self::Error> {
        if n == 0 {
            return Err(DomainError::Invalid {
                field: "issue_number",
                value: "0".to_string(),
            });
        }
        Ok(Self(n))
    }
}

impl TryFrom<String> for IssueNumber {
    type Error = DomainError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        let n = s.parse::<u64>().map_err(|_| DomainError::ParseError {
            field: "issue_number",
            value: s,
        })?;
        Self::try_from(n)
    }
}

impl From<IssueNumber> for u64 {
    fn from(num: IssueNumber) -> u64 {
        num.0
    }
}

impl IssueNumber {
    /// Get the issue number as a u64.
    pub fn as_u64(&self) -> u64 {
        self.0
    }
}

impl fmt::Display for IssueNumber {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

// ============================================================================
// Tool Permission
// ============================================================================

/// Tool execution permission for PreToolUse hooks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ToolPermission {
    /// Allow the tool to execute.
    Allow,
    /// Deny tool execution.
    Deny,
    /// Ask the user for permission.
    Ask,
}

impl fmt::Display for ToolPermission {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Allow => write!(f, "allow"),
            Self::Deny => write!(f, "deny"),
            Self::Ask => write!(f, "ask"),
        }
    }
}

impl TryFrom<String> for ToolPermission {
    type Error = DomainError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        match s.to_lowercase().as_str() {
            "allow" => Ok(Self::Allow),
            "deny" => Ok(Self::Deny),
            "ask" => Ok(Self::Ask),
            _ => Err(DomainError::Invalid {
                field: "tool_permission",
                value: s,
            }),
        }
    }
}

// ============================================================================
// Role
// ============================================================================

/// Agent role (dev, tl, pm).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    /// Developer role.
    #[default]
    Dev,
    /// Tech lead role.
    TL,
    /// Product manager role.
    PM,
}

impl fmt::Display for Role {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Dev => write!(f, "dev"),
            Self::TL => write!(f, "tl"),
            Self::PM => write!(f, "pm"),
        }
    }
}

impl TryFrom<String> for Role {
    type Error = DomainError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        match s.to_lowercase().as_str() {
            "dev" => Ok(Self::Dev),
            "tl" => Ok(Self::TL),
            "pm" => Ok(Self::PM),
            _ => Err(DomainError::Invalid {
                field: "role",
                value: s,
            }),
        }
    }
}

// ============================================================================
// GitHub States
// ============================================================================

/// State of an item (Issue/PR) - Open, Closed, or Unknown.
///
/// Deserializes case-insensitively to handle both lowercase API responses
/// and SCREAMING_SNAKE_CASE from GitHub's GraphQL API.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum ItemState {
    /// Item is currently open.
    Open,
    /// Item is closed or merged.
    Closed,
    /// State could not be determined.
    Unknown,
}

impl fmt::Display for ItemState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Open => write!(f, "open"),
            Self::Closed => write!(f, "closed"),
            Self::Unknown => write!(f, "unknown"),
        }
    }
}

impl<'de> Deserialize<'de> for ItemState {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        match s.to_lowercase().as_str() {
            "open" => Ok(Self::Open),
            "closed" => Ok(Self::Closed),
            _ => Ok(Self::Unknown),
        }
    }
}

/// State of a GitHub Review.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ReviewState {
    /// Review is pending.
    Pending,
    /// Review is approved.
    Approved,
    /// Changes were requested.
    ChangesRequested,
    /// Review was dismissed.
    Dismissed,
    /// Comment was left without explicit approval/request.
    Commented,
}

impl fmt::Display for ReviewState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            ReviewState::Pending => "PENDING",
            ReviewState::Approved => "APPROVED",
            ReviewState::ChangesRequested => "CHANGES_REQUESTED",
            ReviewState::Dismissed => "DISMISSED",
            ReviewState::Commented => "COMMENTED",
        };
        write!(f, "{}", s)
    }
}

// ============================================================================
// Path Types
// ============================================================================

use std::path::{Path, PathBuf};

/// Path validation errors.
#[derive(Debug, thiserror::Error)]
pub enum PathError {
    #[error("path must be absolute: {path}")]
    NotAbsolute { path: PathBuf },

    #[error("path does not exist: {path}")]
    NotFound { path: PathBuf },

    #[error("I/O error for path {path}: {source}")]
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
}

/// Absolute path (must be absolute).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AbsolutePath(PathBuf);

impl TryFrom<PathBuf> for AbsolutePath {
    type Error = PathError;

    fn try_from(p: PathBuf) -> Result<Self, Self::Error> {
        if !p.is_absolute() {
            return Err(PathError::NotAbsolute { path: p });
        }
        Ok(Self(p))
    }
}

impl From<AbsolutePath> for PathBuf {
    fn from(p: AbsolutePath) -> PathBuf {
        p.0
    }
}

impl AbsolutePath {
    /// Get the path as a Path reference.
    pub fn as_path(&self) -> &Path {
        &self.0
    }

    /// Convert to PathBuf (consumes self).
    pub fn into_path_buf(self) -> PathBuf {
        self.0
    }
}

impl AsRef<Path> for AbsolutePath {
    fn as_ref(&self) -> &Path {
        &self.0
    }
}

impl fmt::Display for AbsolutePath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0.display())
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_session_id_validation() {
        // Valid
        let id = SessionId::try_from("session-123".to_string()).unwrap();
        assert_eq!(id.as_str(), "session-123");

        // Empty
        let result = SessionId::try_from("".to_string());
        assert!(matches!(result, Err(DomainError::Empty { .. })));
    }

    #[test]
    fn test_tool_name_validation() {
        // Valid
        let name = ToolName::try_from("Write".to_string()).unwrap();
        assert_eq!(name.as_str(), "Write");

        // Empty
        let result = ToolName::try_from("".to_string());
        assert!(matches!(result, Err(DomainError::Empty { .. })));
    }

    #[test]
    fn test_github_identifiers() {
        // Valid owner
        let owner = GithubOwner::try_from("anthropics".to_string()).unwrap();
        assert_eq!(owner.as_str(), "anthropics");

        // Valid repo
        let repo = GithubRepo::try_from("claude-code".to_string()).unwrap();
        assert_eq!(repo.as_str(), "claude-code");

        // Empty owner
        let result = GithubOwner::try_from("".to_string());
        assert!(matches!(result, Err(DomainError::Empty { .. })));

        // Empty repo
        let result = GithubRepo::try_from("".to_string());
        assert!(matches!(result, Err(DomainError::Empty { .. })));
    }

    #[test]
    fn test_issue_number_validation() {
        // Valid
        let num = IssueNumber::try_from(123u64).unwrap();
        assert_eq!(num.as_u64(), 123);

        // Zero
        let result = IssueNumber::try_from(0u64);
        assert!(matches!(result, Err(DomainError::Invalid { .. })));

        // From string
        let num = IssueNumber::try_from("456".to_string()).unwrap();
        assert_eq!(num.as_u64(), 456);

        // Invalid string
        let result = IssueNumber::try_from("not-a-number".to_string());
        assert!(matches!(result, Err(DomainError::ParseError { .. })));
    }

    #[test]
    fn test_tool_permission() {
        assert_eq!(
            ToolPermission::try_from("allow".to_string()).unwrap(),
            ToolPermission::Allow
        );
        assert_eq!(
            ToolPermission::try_from("deny".to_string()).unwrap(),
            ToolPermission::Deny
        );
        assert_eq!(
            ToolPermission::try_from("ask".to_string()).unwrap(),
            ToolPermission::Ask
        );

        // Case insensitive
        assert_eq!(
            ToolPermission::try_from("ALLOW".to_string()).unwrap(),
            ToolPermission::Allow
        );

        // Invalid
        let result = ToolPermission::try_from("invalid".to_string());
        assert!(matches!(result, Err(DomainError::Invalid { .. })));
    }

    #[test]
    fn test_role() {
        assert_eq!(Role::try_from("dev".to_string()).unwrap(), Role::Dev);
        assert_eq!(Role::try_from("tl".to_string()).unwrap(), Role::TL);
        assert_eq!(Role::try_from("pm".to_string()).unwrap(), Role::PM);

        // Case insensitive
        assert_eq!(Role::try_from("DEV".to_string()).unwrap(), Role::Dev);

        // Invalid
        let result = Role::try_from("invalid".to_string());
        assert!(matches!(result, Err(DomainError::Invalid { .. })));

        // Default
        assert_eq!(Role::default(), Role::Dev);
    }

    #[test]
    fn test_item_state_case_insensitive() {
        // lowercase
        let s: ItemState = serde_json::from_str("\"open\"").unwrap();
        assert_eq!(s, ItemState::Open);

        // UPPERCASE
        let s: ItemState = serde_json::from_str("\"OPEN\"").unwrap();
        assert_eq!(s, ItemState::Open);

        let s: ItemState = serde_json::from_str("\"CLOSED\"").unwrap();
        assert_eq!(s, ItemState::Closed);

        // Unknown
        let s: ItemState = serde_json::from_str("\"something_else\"").unwrap();
        assert_eq!(s, ItemState::Unknown);
    }

    #[test]
    fn test_serde_roundtrip() {
        // SessionId
        let id = SessionId::try_from("test-session".to_string()).unwrap();
        let json = serde_json::to_string(&id).unwrap();
        let deserialized: SessionId = serde_json::from_str(&json).unwrap();
        assert_eq!(id, deserialized);

        // IssueNumber
        let num = IssueNumber::try_from(42u64).unwrap();
        let json = serde_json::to_string(&num).unwrap();
        let deserialized: IssueNumber = serde_json::from_str(&json).unwrap();
        assert_eq!(num, deserialized);

        // ToolPermission
        let permission = ToolPermission::Allow;
        let json = serde_json::to_string(&permission).unwrap();
        let deserialized: ToolPermission = serde_json::from_str(&json).unwrap();
        assert_eq!(permission, deserialized);
    }

    #[test]
    fn test_absolute_path() {
        // Valid absolute path
        let abs = AbsolutePath::try_from(PathBuf::from("/tmp/test")).unwrap();
        assert_eq!(abs.as_path(), Path::new("/tmp/test"));

        // Relative path should fail
        let result = AbsolutePath::try_from(PathBuf::from("relative/path"));
        assert!(matches!(result, Err(PathError::NotAbsolute { .. })));

        // Test as_ref
        let _: &Path = abs.as_ref();
    }
}