pe-core 0.1.0

Core types for Potential Expectations — messages, channels, state, traits
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
//! Error taxonomy — complete set of errors the library produces.
//! Based on Group 7 of the pre-plan.

use thiserror::Error;

#[derive(Error, Debug, Clone)]
#[non_exhaustive]
pub enum PeError {
    // === Graph errors ===
    #[error("Graph recursion limit reached ({limit} supersteps)")]
    GraphRecursion { limit: u32 },

    #[error("Graph interrupt: {reason}")]
    GraphInterrupt { reason: String },

    #[error("Node interrupt: {reason}")]
    NodeInterrupt { reason: String },

    #[error("Invalid state update: {details}")]
    InvalidUpdate { details: String },

    #[error("Channel '{channel}' was never written")]
    EmptyChannel { channel: String },

    #[error("Invalid graph structure: {details}")]
    GraphValue { details: String },

    #[error("Node '{node}' is unreachable — no path from START")]
    UnreachableNode { node: String },

    #[error("Graph invoked with no input")]
    EmptyInput,

    #[error("Multiple subgraphs conflict: {details}")]
    MultipleSubgraphs { details: String },

    // === Agent errors ===
    #[error("Agent '{agent_id}' not found in registry")]
    AgentNotFound { agent_id: String },

    #[error("Agent '{agent_id}' is unreachable: {reason}")]
    AgentUnreachable { agent_id: String, reason: String },

    #[error("Handoff cycle detected: {path}")]
    HandoffCycle { path: String },

    #[error("Max handoffs ({max}) exceeded")]
    MaxHandoffs { max: u32 },

    // === Boundary errors ===
    #[error("Permission denied: {action}")]
    PermissionDenied { action: String },

    #[error("Tool '{tool}' denied by policy: {reason}")]
    ToolDenied { tool: String, reason: String },

    #[error("Communication with '{target}' blocked by rules")]
    CommunicationBlocked { target: String },

    #[error("Approval denied for '{action}': {reason}")]
    ApprovalDenied { action: String, reason: String },

    #[error("Approval required for '{action}', but no approval resolver is configured")]
    ApprovalRequired { action: String },

    #[error("Guardrail violated: {guardrail} — {details}")]
    GuardrailViolation { guardrail: String, details: String },

    #[error("Write governance violation on '{destination}': {reason}")]
    WriteGovernanceViolation { destination: String, reason: String },

    #[error("Inspection denied for '{root}': {reason}")]
    InspectionDenied { root: String, reason: String },

    #[error("Inspection failed for '{path}': {reason}")]
    InspectionFailed { path: String, reason: String },

    // === Tool errors ===
    #[error("Tool '{tool}' execution failed: {reason}")]
    ToolExecution { tool: String, reason: String },

    #[error("Tool '{tool}' not found in registry")]
    ToolNotFound { tool: String },

    #[error("Tool '{tool}' is already registered")]
    ToolAlreadyRegistered { tool: String },

    // === LLM errors ===
    #[error("LLM provider error: {details}")]
    LlmProvider { details: String },

    /// Authentication/authorization failed (HTTP 401/403). NOT retryable —
    /// a bad API key will never succeed on retry.
    #[error("LLM auth failed: {details}")]
    LlmAuth { details: String },

    /// Rate limited by the provider (HTTP 429). Retryable with backoff.
    #[error("LLM rate limited: {details}")]
    LlmRateLimit { details: String },

    #[error("LLM provider returned no response")]
    LlmEmpty,

    #[error("MockProvider response queue exhausted — add more responses with .respond_with()")]
    MockProviderExhausted,

    #[error("Embedding dimension mismatch: expected {expected}, got {actual}")]
    EmbeddingDimension { expected: usize, actual: usize },

    #[error("Structured output parse failed: {details}")]
    StructuredOutput { details: String },

    // === Storage errors ===
    #[error("Storage error: {details}")]
    Storage { details: String },

    #[error("Checkpoint not found for thread '{thread_id}'")]
    CheckpointNotFound { thread_id: String },

    // === Bus / Negotiation errors ===
    #[error("Bus error: {details}")]
    BusError { details: String },

    #[error("Negotiation failed: {reason}")]
    NegotiationFailed { reason: String },

    #[error("Negotiation interrupted: {reason}")]
    NegotiationInterrupted { reason: String },

    // === Execution errors ===
    #[error("Execution timeout after {seconds:.2}s")]
    Timeout { seconds: f64 },

    #[error("Execution budget exceeded: {budget_type}")]
    BudgetExceeded { budget_type: String },

    // === Agent construction ===
    #[error("Invalid agent: {0}")]
    InvalidAgent(String),

    #[error("Manifest load failed: {0}")]
    ManifestLoad(String),

    #[error("Manifest parse failed: {0}")]
    ManifestParse(String),

    // === Delegation errors ===
    #[error("Cyclic delegation detected: {chain:?} → {attempted}")]
    CyclicDelegation {
        chain: Vec<String>,
        attempted: String,
    },

    // === Resume errors ===
    /// Resume point mismatch between checkpoint and command.
    #[error("Resume point mismatch: expected '{expected}', got '{actual}'")]
    ResumePointMismatch {
        /// The resume point stored in the checkpoint.
        expected: String,
        /// The resume point provided by the caller.
        actual: String,
    },

    /// Node expected human input on resume but none was provided.
    #[error("Missing human input — node expected HumanInput on resume but none was provided")]
    MissingHumanInput,

    // === Matrix errors ===
    #[error("Matrix dimension mismatch: expected {expected}, got {actual}")]
    MatrixDimensionMismatch { expected: usize, actual: usize },

    #[error("Node '{node}' not found in transition matrix")]
    NodeNotFound { node: String },

    #[error("Tensor constraint {constraint} violated: {detail}")]
    ConstraintViolation { constraint: String, detail: String },

    #[error("Tensor composition failed: {reason}")]
    CompositionError { reason: String },

    #[error("Invalid payload: {reason}")]
    InvalidPayload { reason: String },

    // === Cognitive errors ===
    /// Cognitive budget exhausted — lobes consumed all allocated tokens/time.
    #[error("Cognitive budget exhausted for agent '{agent_id}': used {tokens_used}/{limit} tokens")]
    CognitiveBudgetExhausted {
        agent_id: String,
        tokens_used: u32,
        limit: u32,
    },

    /// A lobe vetoed the output — blocks execution.
    #[error("Cognitive veto by lobe '{lobe}' for agent '{agent_id}': {reason}")]
    CognitiveSignalVeto {
        agent_id: String,
        lobe: String,
        reason: String,
    },

    /// A lobe failed to activate or process.
    ///
    /// This is a structural failure (not transient). Transient failures
    /// (e.g., model unavailable) should be reported as [`PeError::LlmProvider`] or
    /// [`PeError::Timeout`] by the lobe itself before returning this error.
    #[error("Lobe activation failed for '{lobe}': {reason}")]
    LobeActivationFailed { lobe: String, reason: String },

    // === Internal ===
    #[error("Internal error: {details}")]
    Internal { details: String },
}

impl PeError {
    /// Whether this error is retryable by a retry policy.
    ///
    /// Transient failures (timeouts, LLM provider errors, tool execution
    /// errors) are retryable. Structural errors (invalid graph, permission
    /// denied, missing input) are not.
    pub fn is_retryable(&self) -> bool {
        matches!(
            self,
            PeError::Timeout { .. }
                | PeError::LlmProvider { .. }
                | PeError::LlmRateLimit { .. }
                | PeError::LlmEmpty
                | PeError::ToolExecution { .. }
                | PeError::Storage { .. }
        )
        // Note: LlmAuth is NOT retryable — bad credentials never succeed on retry
    }

    /// Whether this error represents a transient condition that may resolve later.
    ///
    /// Transient errors are temporary — the same operation might succeed on retry
    /// or after a delay. Permanent errors indicate structural problems that will
    /// never resolve without code/config changes.
    ///
    /// `is_retryable()` is a subset of `is_transient()`: all retryable errors are
    /// transient, but some transient errors (like `BusError`) may not benefit from
    /// immediate retry.
    pub fn is_transient(&self) -> bool {
        matches!(
            self,
            PeError::Timeout { .. }
                | PeError::LlmProvider { .. }
                | PeError::LlmRateLimit { .. }
                | PeError::LlmEmpty
                | PeError::ToolExecution { .. }
                | PeError::Storage { .. }
                | PeError::BusError { .. }
                | PeError::NegotiationFailed { .. }
                | PeError::MockProviderExhausted
        )
    }
}

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

    /// Exhaustive classification of every PeError variant.
    /// If a new variant is added, this function will fail to compile
    /// until updated — ensuring classification stays complete.
    fn classify_all_variants() -> Vec<(PeError, bool, bool)> {
        // (error, expected_transient, expected_retryable)
        vec![
            // Transient + retryable
            (PeError::Timeout { seconds: 30.0 }, true, true),
            (
                PeError::LlmProvider {
                    details: "rate limited".into(),
                },
                true,
                true,
            ),
            (PeError::LlmEmpty, true, true),
            (
                PeError::LlmAuth {
                    details: "invalid api key".into(),
                },
                false, // NOT retryable — bad credentials never succeed
                false, // NOT transient — structural problem
            ),
            (
                PeError::LlmRateLimit {
                    details: "too many requests".into(),
                },
                true, // retryable with backoff
                true, // transient
            ),
            (
                PeError::ToolExecution {
                    tool: "search".into(),
                    reason: "network error".into(),
                },
                true,
                true,
            ),
            (
                PeError::Storage {
                    details: "connection refused".into(),
                },
                true,
                true,
            ),
            // Transient but not immediately retryable
            (
                PeError::BusError {
                    details: "disconnected".into(),
                },
                true,
                false,
            ),
            (
                PeError::NegotiationFailed {
                    reason: "timeout".into(),
                },
                true,
                false,
            ),
            (PeError::MockProviderExhausted, true, false),
            // Permanent (not transient, not retryable)
            (PeError::GraphRecursion { limit: 25 }, false, false),
            (
                PeError::GraphInterrupt {
                    reason: "paused".into(),
                },
                false,
                false,
            ),
            (
                PeError::NodeInterrupt {
                    reason: "paused".into(),
                },
                false,
                false,
            ),
            (
                PeError::InvalidUpdate {
                    details: "bad field".into(),
                },
                false,
                false,
            ),
            (
                PeError::EmptyChannel {
                    channel: "msgs".into(),
                },
                false,
                false,
            ),
            (
                PeError::GraphValue {
                    details: "no edges".into(),
                },
                false,
                false,
            ),
            (
                PeError::UnreachableNode {
                    node: "orphan".into(),
                },
                false,
                false,
            ),
            (PeError::EmptyInput, false, false),
            (
                PeError::MultipleSubgraphs {
                    details: "conflict".into(),
                },
                false,
                false,
            ),
            (
                PeError::AgentNotFound {
                    agent_id: "x".into(),
                },
                false,
                false,
            ),
            (
                PeError::AgentUnreachable {
                    agent_id: "x".into(),
                    reason: "no bus".into(),
                },
                false,
                false,
            ),
            (
                PeError::HandoffCycle {
                    path: "a->b->a".into(),
                },
                false,
                false,
            ),
            (PeError::MaxHandoffs { max: 10 }, false, false),
            (
                PeError::PermissionDenied {
                    action: "write".into(),
                },
                false,
                false,
            ),
            (
                PeError::ToolDenied {
                    tool: "rm".into(),
                    reason: "blocked".into(),
                },
                false,
                false,
            ),
            (
                PeError::CommunicationBlocked {
                    target: "agent-b".into(),
                },
                false,
                false,
            ),
            (
                PeError::ApprovalDenied {
                    action: "tool:shell_exec".into(),
                    reason: "host denied".into(),
                },
                false,
                false,
            ),
            (
                PeError::ApprovalRequired {
                    action: "tool:shell_exec".into(),
                },
                false,
                false,
            ),
            (
                PeError::GuardrailViolation {
                    guardrail: "safety".into(),
                    details: "toxic".into(),
                },
                false,
                false,
            ),
            (
                PeError::WriteGovernanceViolation {
                    destination: "db".into(),
                    reason: "denied".into(),
                },
                false,
                false,
            ),
            (
                PeError::InspectionDenied {
                    root: ".".into(),
                    reason: "blocked".into(),
                },
                false,
                false,
            ),
            (
                PeError::InspectionFailed {
                    path: "missing.txt".into(),
                    reason: "not found".into(),
                },
                false,
                false,
            ),
            (
                PeError::ToolNotFound {
                    tool: "missing".into(),
                },
                false,
                false,
            ),
            (
                PeError::ToolAlreadyRegistered {
                    tool: "search".into(),
                },
                false,
                false,
            ),
            (
                PeError::EmbeddingDimension {
                    expected: 768,
                    actual: 512,
                },
                false,
                false,
            ),
            (
                PeError::StructuredOutput {
                    details: "parse fail".into(),
                },
                false,
                false,
            ),
            (
                PeError::CheckpointNotFound {
                    thread_id: "t1".into(),
                },
                false,
                false,
            ),
            (
                PeError::NegotiationInterrupted {
                    reason: "timeout".into(),
                },
                false,
                false,
            ),
            (
                PeError::BudgetExceeded {
                    budget_type: "tokens".into(),
                },
                false,
                false,
            ),
            (PeError::InvalidAgent("bad config".into()), false, false),
            (PeError::ManifestLoad("not found".into()), false, false),
            (PeError::ManifestParse("invalid yaml".into()), false, false),
            (
                PeError::CyclicDelegation {
                    chain: vec!["a".into(), "b".into()],
                    attempted: "a".into(),
                },
                false,
                false,
            ),
            (
                PeError::ResumePointMismatch {
                    expected: "x".into(),
                    actual: "y".into(),
                },
                false,
                false,
            ),
            (PeError::MissingHumanInput, false, false),
            (
                PeError::MatrixDimensionMismatch {
                    expected: 3,
                    actual: 5,
                },
                false,
                false,
            ),
            (
                PeError::NodeNotFound {
                    node: "ghost".into(),
                },
                false,
                false,
            ),
            (
                PeError::ConstraintViolation {
                    constraint: "C4".into(),
                    detail: "sum > 1".into(),
                },
                false,
                false,
            ),
            (
                PeError::CompositionError {
                    reason: "incompatible".into(),
                },
                false,
                false,
            ),
            (
                PeError::InvalidPayload {
                    reason: "negative probability".into(),
                },
                false,
                false,
            ),
            (
                PeError::CognitiveBudgetExhausted {
                    agent_id: "agent-1".into(),
                    tokens_used: 2000,
                    limit: 2000,
                },
                false,
                false,
            ),
            (
                PeError::CognitiveSignalVeto {
                    agent_id: "agent-1".into(),
                    lobe: "safety".into(),
                    reason: "dangerous".into(),
                },
                false,
                false,
            ),
            (
                PeError::LobeActivationFailed {
                    lobe: "critic".into(),
                    reason: "model unavailable".into(),
                },
                false,
                false,
            ),
            (
                PeError::Internal {
                    details: "bug".into(),
                },
                false,
                false,
            ),
        ]
    }

    #[test]
    fn test_is_transient_exhaustive() {
        for (error, expected_transient, _) in classify_all_variants() {
            assert_eq!(
                error.is_transient(),
                expected_transient,
                "Wrong is_transient() for: {error}"
            );
        }
    }

    #[test]
    fn test_is_retryable_exhaustive() {
        for (error, _, expected_retryable) in classify_all_variants() {
            assert_eq!(
                error.is_retryable(),
                expected_retryable,
                "Wrong is_retryable() for: {error}"
            );
        }
    }

    #[test]
    fn test_retryable_is_subset_of_transient() {
        for (error, _, _) in classify_all_variants() {
            if error.is_retryable() {
                assert!(
                    error.is_transient(),
                    "Retryable error should also be transient: {error}"
                );
            }
        }
    }

    #[test]
    fn test_transient_errors_are_retryable_or_bus() {
        let transient = vec![
            PeError::Timeout { seconds: 30.0 },
            PeError::LlmProvider {
                details: "500".into(),
            },
            PeError::LlmEmpty,
            PeError::ToolExecution {
                tool: "api".into(),
                reason: "timeout".into(),
            },
            PeError::Storage {
                details: "conn reset".into(),
            },
        ];
        for err in transient {
            assert!(err.is_transient(), "Expected transient: {err}");
            assert!(err.is_retryable(), "Expected retryable: {err}");
        }
    }

    #[test]
    fn test_permanent_errors_are_not_retryable() {
        let permanent = vec![
            PeError::GraphRecursion { limit: 25 },
            PeError::AgentNotFound {
                agent_id: "x".into(),
            },
            PeError::PermissionDenied {
                action: "write".into(),
            },
            PeError::Internal {
                details: "bug".into(),
            },
        ];
        for err in permanent {
            assert!(!err.is_transient(), "Expected permanent: {err}");
            assert!(!err.is_retryable(), "Expected not retryable: {err}");
        }
    }
}