enact-core 0.0.1

Core agent runtime for Enact - Graph-Native AI agents
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
//! Inbox Message Types
//!
//! @see docs/TECHNICAL/31-MID-EXECUTION-GUIDANCE.md Section 3

use crate::kernel::ExecutionId;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// Inbox message - wraps all message types
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum InboxMessage {
    /// Control message (pause/resume/cancel)
    Control(ControlMessage),
    /// User or system guidance
    Guidance(GuidanceMessage),
    /// Evidence update from discovery or external source
    Evidence(EvidenceUpdate),
    /// Agent-to-Agent message
    A2a(A2aMessage),
}

impl InboxMessage {
    /// Get the message type for logging/audit
    pub fn message_type(&self) -> InboxMessageType {
        match self {
            InboxMessage::Control(_) => InboxMessageType::Control,
            InboxMessage::Guidance(_) => InboxMessageType::Guidance,
            InboxMessage::Evidence(_) => InboxMessageType::Evidence,
            InboxMessage::A2a(_) => InboxMessageType::A2a,
        }
    }

    /// Get the message ID
    pub fn id(&self) -> &str {
        match self {
            InboxMessage::Control(m) => &m.id,
            InboxMessage::Guidance(m) => &m.id,
            InboxMessage::Evidence(m) => &m.id,
            InboxMessage::A2a(m) => &m.id,
        }
    }

    /// Get the execution ID this message is for
    pub fn execution_id(&self) -> &ExecutionId {
        match self {
            InboxMessage::Control(m) => &m.execution_id,
            InboxMessage::Guidance(m) => &m.execution_id,
            InboxMessage::Evidence(m) => &m.execution_id,
            InboxMessage::A2a(m) => &m.execution_id,
        }
    }

    /// Get the priority for sorting (lower = higher priority)
    ///
    /// INV-INBOX-002: Control messages have highest priority
    pub fn priority_order(&self) -> u8 {
        match self {
            InboxMessage::Control(_) => 0, // Highest priority
            InboxMessage::Evidence(e) if e.impact == EvidenceImpact::ContradictsPlan => 1,
            InboxMessage::Evidence(_) => 2,
            InboxMessage::Guidance(g) if g.priority == GuidancePriority::High => 3,
            InboxMessage::Guidance(_) => 4,
            InboxMessage::A2a(_) => 5, // Lowest priority
        }
    }

    /// Check if this is a control message
    pub fn is_control(&self) -> bool {
        matches!(self, InboxMessage::Control(_))
    }
}

/// Message type for logging
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InboxMessageType {
    Control,
    Guidance,
    Evidence,
    A2a,
}

// =============================================================================
// Control Messages
// =============================================================================

/// Control message - pause/resume/cancel execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ControlMessage {
    /// Unique message ID
    pub id: String,
    /// Target execution
    pub execution_id: ExecutionId,
    /// Control action
    pub action: ControlAction,
    /// Reason for the action
    pub reason: Option<String>,
    /// Actor who initiated (user_id, system, agent_id)
    pub actor: String,
    /// When the message was created
    pub created_at: DateTime<Utc>,
}

impl ControlMessage {
    /// Create a new control message
    pub fn new(execution_id: ExecutionId, action: ControlAction, actor: impl Into<String>) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            execution_id,
            action,
            reason: None,
            actor: actor.into(),
            created_at: Utc::now(),
        }
    }

    /// Add a reason
    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
        self.reason = Some(reason.into());
        self
    }
}

/// Control action
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ControlAction {
    /// Pause execution
    Pause,
    /// Resume paused execution
    Resume,
    /// Cancel execution
    Cancel,
    /// Create a checkpoint
    Checkpoint,
    /// Compact context (free memory)
    Compact,
}

// =============================================================================
// Guidance Messages
// =============================================================================

/// Guidance message - user or system guidance
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GuidanceMessage {
    /// Unique message ID
    pub id: String,
    /// Target execution
    pub execution_id: ExecutionId,
    /// Source of guidance
    pub from: GuidanceSource,
    /// Guidance content
    pub content: String,
    /// Additional context
    pub context: Option<serde_json::Value>,
    /// Priority level
    pub priority: GuidancePriority,
    /// When the message was created
    pub created_at: DateTime<Utc>,
}

impl GuidanceMessage {
    /// Create a new guidance message from user
    pub fn from_user(
        execution_id: ExecutionId,
        content: impl Into<String>,
    ) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            execution_id,
            from: GuidanceSource::User,
            content: content.into(),
            context: None,
            priority: GuidancePriority::Medium,
            created_at: Utc::now(),
        }
    }

    /// Set priority
    pub fn with_priority(mut self, priority: GuidancePriority) -> Self {
        self.priority = priority;
        self
    }

    /// Add context
    pub fn with_context(mut self, context: serde_json::Value) -> Self {
        self.context = Some(context);
        self
    }
}

/// Source of guidance
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GuidanceSource {
    User,
    System,
    Agent,
}

/// Guidance priority
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GuidancePriority {
    Low,
    Medium,
    High,
}

// =============================================================================
// Evidence Updates
// =============================================================================

/// Evidence update - new information that may affect execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EvidenceUpdate {
    /// Unique message ID
    pub id: String,
    /// Target execution
    pub execution_id: ExecutionId,
    /// Source of evidence
    pub source: EvidenceSource,
    /// The evidence content
    pub title: String,
    /// Detailed content
    pub content: serde_json::Value,
    /// Confidence score (0.0 - 1.0)
    pub confidence: Option<f64>,
    /// Impact classification
    pub impact: EvidenceImpact,
    /// When the message was created
    pub created_at: DateTime<Utc>,
}

impl EvidenceUpdate {
    /// Create a new evidence update
    pub fn new(
        execution_id: ExecutionId,
        source: EvidenceSource,
        title: impl Into<String>,
        content: serde_json::Value,
        impact: EvidenceImpact,
    ) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            execution_id,
            source,
            title: title.into(),
            content,
            confidence: None,
            impact,
            created_at: Utc::now(),
        }
    }

    /// Set confidence score
    pub fn with_confidence(mut self, confidence: f64) -> Self {
        self.confidence = Some(confidence.clamp(0.0, 1.0));
        self
    }
}

/// Source of evidence
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EvidenceSource {
    /// Discovered during execution
    Discovery,
    /// From a tool result
    ToolResult,
    /// From external source
    External,
    /// From memory retrieval
    Memory,
}

/// Evidence impact classification
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EvidenceImpact {
    /// Just informational, add to context
    Informational,
    /// Requires human review
    RequiresReview,
    /// Contradicts current plan
    ContradictsPlan,
}

// =============================================================================
// A2A Messages (Agent-to-Agent)
// =============================================================================

/// Agent-to-Agent message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct A2aMessage {
    /// Unique message ID
    pub id: String,
    /// Target execution
    pub execution_id: ExecutionId,
    /// Source agent ID
    pub from_agent: String,
    /// Message type
    pub message_type: String,
    /// Message payload
    pub payload: serde_json::Value,
    /// When the message was created
    pub created_at: DateTime<Utc>,
}

impl A2aMessage {
    /// Create a new A2A message
    pub fn new(
        execution_id: ExecutionId,
        from_agent: impl Into<String>,
        message_type: impl Into<String>,
        payload: serde_json::Value,
    ) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            execution_id,
            from_agent: from_agent.into(),
            message_type: message_type.into(),
            payload,
            created_at: Utc::now(),
        }
    }
}

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

    #[test]
    fn test_control_message_priority() {
        let exec_id = ExecutionId::new();
        let control = InboxMessage::Control(ControlMessage::new(
            exec_id.clone(),
            ControlAction::Pause,
            "test_user",
        ));

        assert_eq!(control.priority_order(), 0);
        assert!(control.is_control());
    }

    #[test]
    fn test_evidence_priority_contradicts() {
        let exec_id = ExecutionId::new();
        let evidence = InboxMessage::Evidence(EvidenceUpdate::new(
            exec_id,
            EvidenceSource::Discovery,
            "Found conflict",
            serde_json::json!({}),
            EvidenceImpact::ContradictsPlan,
        ));

        assert_eq!(evidence.priority_order(), 1);
    }

    #[test]
    fn test_guidance_priority() {
        let exec_id = ExecutionId::new();
        let high = InboxMessage::Guidance(
            GuidanceMessage::from_user(exec_id.clone(), "Focus on EU")
                .with_priority(GuidancePriority::High),
        );
        let low = InboxMessage::Guidance(
            GuidanceMessage::from_user(exec_id, "Also check this")
                .with_priority(GuidancePriority::Low),
        );

        assert_eq!(high.priority_order(), 3);
        assert_eq!(low.priority_order(), 4);
    }

    #[test]
    fn test_message_sorting() {
        let exec_id = ExecutionId::new();
        let mut messages = vec![
            InboxMessage::Guidance(GuidanceMessage::from_user(exec_id.clone(), "test")),
            InboxMessage::Control(ControlMessage::new(
                exec_id.clone(),
                ControlAction::Pause,
                "user",
            )),
            InboxMessage::Evidence(EvidenceUpdate::new(
                exec_id,
                EvidenceSource::Discovery,
                "Found",
                serde_json::json!({}),
                EvidenceImpact::Informational,
            )),
        ];

        // Sort by priority (INV-INBOX-002)
        messages.sort_by_key(|m| m.priority_order());

        // Control should be first
        assert!(messages[0].is_control());
        assert!(matches!(messages[1], InboxMessage::Evidence(_)));
        assert!(matches!(messages[2], InboxMessage::Guidance(_)));
    }
}