symbi-runtime 1.21.1

Agent Runtime System for the Symbi platform
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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
//! Core types for the reasoning loop
//!
//! Defines observations, proposed actions, loop configuration, state,
//! and recovery strategies for the observe-reason-gate-act cycle.

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::time::Duration;

use crate::reasoning::conversation::Conversation;
use crate::reasoning::inference::{ToolDefinition, Usage};
use crate::types::AgentId;

/// An observation that feeds into the reasoning step.
///
/// Observations come from tool results, environment state, policy feedback,
/// or external events. The loop collects them before each reasoning step.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Observation {
    /// Source of the observation (e.g., tool name, "policy_gate", "environment").
    pub source: String,
    /// The observation content.
    pub content: String,
    /// Whether this observation indicates an error.
    pub is_error: bool,
    /// The tool call ID that produced this observation.
    /// When present, used as the `tool_use_id` in conversation messages
    /// to correlate tool results with the originating tool_use block.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub call_id: Option<String>,
    /// Metadata for logging and auditing.
    #[serde(default)]
    pub metadata: HashMap<String, String>,
}

impl Observation {
    /// Set by the runtime after dispatch, never inferred from tool text.
    pub fn has_unconfirmed_effect(&self) -> bool {
        self.metadata
            .get("effect_outcome")
            .is_some_and(|value| value == "unknown")
    }

    pub(crate) fn mark_unconfirmed_effect(&mut self) {
        self.is_error = true;
        self.metadata
            .insert("effect_outcome".into(), "unknown".into());
    }
    /// Create a tool result observation.
    pub fn tool_result(tool_name: impl Into<String>, content: impl Into<String>) -> Self {
        Self {
            source: tool_name.into(),
            content: content.into(),
            is_error: false,
            call_id: None,
            metadata: HashMap::new(),
        }
    }

    /// Create a tool error observation.
    pub fn tool_error(tool_name: impl Into<String>, error: impl Into<String>) -> Self {
        Self {
            source: tool_name.into(),
            content: error.into(),
            is_error: true,
            call_id: None,
            metadata: HashMap::new(),
        }
    }

    /// Create a policy denial observation.
    pub fn policy_denial(reason: impl Into<String>) -> Self {
        Self {
            source: "policy_gate".into(),
            content: reason.into(),
            is_error: true,
            call_id: None,
            metadata: HashMap::new(),
        }
    }

    /// Attach a tool call ID to this observation.
    pub fn with_call_id(mut self, call_id: impl Into<String>) -> Self {
        self.call_id = Some(call_id.into());
        self
    }
}

/// An action proposed by the reasoning step, pending policy evaluation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ProposedAction {
    /// Call a tool with the given name and arguments.
    ToolCall {
        /// Unique call identifier.
        call_id: String,
        /// Tool name.
        name: String,
        /// JSON-encoded arguments.
        arguments: String,
    },
    /// Delegate work to another agent.
    Delegate {
        /// Unique call identifier — the id of the `delegate` tool call this
        /// action was converted from. Delegation results are returned to the
        /// model as a `tool_result` correlated by this id.
        call_id: String,
        /// Target agent identifier or name.
        target: String,
        /// Message to send.
        message: String,
    },
    /// Respond to the user/caller with content (text or structured).
    Respond {
        /// Response content.
        content: String,
    },
    /// Terminate the loop (agent has finished its task).
    Terminate {
        /// Reason for termination.
        reason: String,
        /// Final output.
        output: String,
    },
}

/// The policy gate's decision for a proposed action.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LoopDecision {
    /// Allow the action to proceed.
    Allow,
    /// Deny the action with a reason (fed back as observation).
    Deny { reason: String },
    /// Allow with modifications (e.g., parameter redaction).
    Modify {
        modified_action: Box<ProposedAction>,
        reason: String,
    },
}

/// Runtime state of the reasoning loop.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoopState {
    /// Agent identity.
    pub agent_id: AgentId,
    /// Current iteration number (0-indexed).
    pub iteration: u32,
    /// Cumulative token usage.
    pub total_usage: Usage,
    /// The conversation so far.
    pub conversation: Conversation,
    /// Pending observations to process.
    pub pending_observations: Vec<Observation>,
    /// Timestamp when the loop started.
    pub started_at: chrono::DateTime<chrono::Utc>,
    /// Current loop phase for logging.
    pub current_phase: String,
    /// Arbitrary metadata carried across iterations.
    #[serde(default)]
    pub metadata: HashMap<String, serde_json::Value>,
    /// Trusted, runtime-populated context for grounded policy decisions.
    /// Populated ONLY by the runtime/caller (e.g. ticket text, caller
    /// capabilities) — never by model output. Intended to be fed into the
    /// Cedar `Context` by the policy gate for grounded decisions. Distinct
    /// from `metadata` precisely because `metadata` can be written by tool
    /// results and is therefore untrusted.
    #[serde(default)]
    pub trusted_context: HashMap<String, serde_json::Value>,
}

impl LoopState {
    /// Create initial state for a new loop.
    pub fn new(agent_id: AgentId, conversation: Conversation) -> Self {
        Self {
            agent_id,
            iteration: 0,
            total_usage: Usage::default(),
            conversation,
            pending_observations: Vec::new(),
            started_at: chrono::Utc::now(),
            current_phase: "initialized".into(),
            metadata: HashMap::new(),
            trusted_context: HashMap::new(),
        }
    }

    /// Accumulate token usage from an inference response.
    pub fn add_usage(&mut self, usage: &Usage) {
        self.total_usage.prompt_tokens = self
            .total_usage
            .prompt_tokens
            .saturating_add(usage.prompt_tokens);
        self.total_usage.completion_tokens = self
            .total_usage
            .completion_tokens
            .saturating_add(usage.completion_tokens);
        self.total_usage.total_tokens = self
            .total_usage
            .total_tokens
            .saturating_add(usage.total_tokens);
    }

    /// Get elapsed time since loop start.
    pub fn elapsed(&self) -> chrono::Duration {
        chrono::Utc::now() - self.started_at
    }
}

/// Configuration for a reasoning loop instance.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoopConfig {
    /// Maximum iterations before forced termination.
    pub max_iterations: u32,
    /// Maximum total tokens before forced termination.
    pub max_total_tokens: u32,
    /// Runtime-owned root/child accounting. Never accepted from serialized input.
    #[serde(skip)]
    pub shared_budget: Option<super::budget::SharedBudget>,
    /// Maximum wall-clock time for the entire loop.
    pub timeout: Duration,
    /// Default recovery strategy for tool failures.
    pub default_recovery: RecoveryStrategy,
    /// Per-tool timeout for individual tool calls.
    pub tool_timeout: Duration,
    /// Maximum concurrent tool calls during parallel dispatch.
    pub max_concurrent_tools: usize,
    /// Token budget for context window management.
    pub context_token_budget: usize,
    /// Sampling temperature applied to inference calls. 0.0 = deterministic.
    /// Defaults to the same value as `InferenceOptions::default()` to preserve
    /// existing behavior for callers that don't set this explicitly.
    #[serde(default = "default_loop_temperature")]
    pub temperature: f32,
    /// Per-call output-token ceiling; the max_tokens sent to the provider
    /// each turn is min(remaining budget, this).
    #[serde(default = "default_max_output_tokens")]
    pub max_output_tokens: u32,
    /// Maximum delegation nesting depth before a `Delegate` is refused.
    #[serde(default = "default_max_delegation_depth")]
    pub max_delegation_depth: u32,
    /// Current delegation nesting depth (0 at the top level; incremented per hop).
    #[serde(default)]
    pub delegation_depth: u32,
    /// Agent names already on the delegation path, for cycle detection.
    #[serde(default)]
    pub delegation_chain: Vec<String>,
    /// Tool definitions available during this loop run.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tool_definitions: Vec<ToolDefinition>,
    /// Controls whether the model is required to call a tool every
    /// turn. `None` lets the provider use its default (auto). Set to
    /// `Some(ToolChoice::Any)` for iterate-until-done agents where the
    /// loop should never terminate on a plain-text response.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<crate::reasoning::inference::ToolChoice>,
    /// Tool profile for filtering tools visible to the LLM.
    #[cfg(feature = "orga-adaptive")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_profile: Option<crate::reasoning::tool_profile::ToolProfile>,
    /// Per-step iteration limits for stuck loop detection.
    #[cfg(feature = "orga-adaptive")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub step_iteration: Option<crate::reasoning::progress_tracker::StepIterationConfig>,
    /// Pre-hydration configuration for deterministic context pre-fetch.
    #[cfg(feature = "orga-adaptive")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pre_hydration: Option<crate::reasoning::pre_hydrate::PreHydrationConfig>,
}

fn default_loop_temperature() -> f32 {
    // Match the InferenceOptions default to preserve existing behavior for
    // callers that don't override this. Eval/test workloads should set 0.0.
    0.3
}

fn default_max_output_tokens() -> u32 {
    // Preserves the previously-hardcoded per-call cap in `produce_output`.
    16384
}

fn default_max_delegation_depth() -> u32 {
    3
}

impl Default for LoopConfig {
    fn default() -> Self {
        Self {
            max_iterations: 25,
            max_total_tokens: 100_000,
            shared_budget: None,
            timeout: Duration::from_secs(300),
            default_recovery: RecoveryStrategy::Retry {
                max_attempts: 2,
                base_delay: Duration::from_millis(500),
            },
            tool_timeout: Duration::from_secs(30),
            max_concurrent_tools: 5,
            context_token_budget: 32_000,
            temperature: default_loop_temperature(),
            max_output_tokens: default_max_output_tokens(),
            max_delegation_depth: default_max_delegation_depth(),
            delegation_depth: 0,
            delegation_chain: Vec::new(),
            tool_definitions: Vec::new(),
            tool_choice: None,
            #[cfg(feature = "orga-adaptive")]
            tool_profile: None,
            #[cfg(feature = "orga-adaptive")]
            step_iteration: None,
            #[cfg(feature = "orga-adaptive")]
            pre_hydration: None,
        }
    }
}

/// Strategy for recovering from tool execution failures.
///
/// By default, recovery is deterministic (retry, fallback, cache, dead letter).
/// LLM-driven recovery is opt-in and rate-limited to prevent failure amplification.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RecoveryStrategy {
    /// Retry with exponential backoff.
    Retry {
        max_attempts: u32,
        base_delay: Duration,
    },
    /// Try alternative tools in order.
    Fallback { alternatives: Vec<String> },
    /// Return a cached result if available and not too stale.
    CachedResult { max_staleness: Duration },
    /// Ask the LLM to propose an alternative approach (opt-in, rate-limited).
    LlmRecovery { max_recovery_attempts: u32 },
    /// Escalate to a human or external system.
    Escalate {
        queue: String,
        context_snapshot: bool,
    },
    /// Send to dead letter queue and continue without the result.
    DeadLetter,
}

/// The final result of a completed reasoning loop.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoopResult {
    /// The final response content.
    pub output: String,
    /// Total iterations executed.
    pub iterations: u32,
    /// Total token usage.
    pub total_usage: Usage,
    /// Aggregate scope usage, including descendants and uncertain reservations.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub budget: Option<super::budget::BudgetSnapshot>,
    /// How the loop terminated.
    pub termination_reason: TerminationReason,
    /// Wall-clock duration.
    pub duration: Duration,
    /// The full conversation history.
    pub conversation: Conversation,
}

/// Why the loop terminated.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TerminationReason {
    /// Agent produced a final response (normal completion).
    Completed,
    /// Hit the maximum iteration limit.
    MaxIterations,
    /// Hit the token budget limit.
    MaxTokens,
    /// Hit the timeout.
    Timeout,
    /// An executed action or child has an unconfirmed outcome. No further
    /// reasoning or actions may retry it without reconciliation.
    UnconfirmedEffects,
    /// Policy denied a critical action with no recovery path.
    PolicyDenial { reason: String },
    /// An unrecoverable error occurred.
    Error { message: String },
}

/// Events emitted during loop execution for observability.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LoopEvent {
    /// Actual final output of an explicitly opted-in improvement run, recorded
    /// after policy processing and cleanup and before its terminal event.
    ImprovementOutput { output: String },
    /// Durable checkpoint before handing one authorized call to an executor.
    /// A missing finish record leaves execution and its effects unconfirmed.
    ToolDispatchStarted {
        dispatch_id: uuid::Uuid,
        run_key: String,
        call_id: String,
        call_fingerprint: String,
        tool_name: String,
    },
    /// A correlated executor result, persisted before it reaches the caller.
    /// An error result does not establish that no external effect occurred.
    ToolDispatchFinished {
        dispatch_id: uuid::Uuid,
        observation_hash: String,
        is_error: bool,
    },
    /// The exact formatted response is authorized and its send is about to start.
    ResponseDeliveryStarted {
        fingerprint: String,
        request_hash: String,
        request_bytes: u64,
    },
    /// A delivery result, recorded before run completion. A start without this
    /// receipt (for example cancellation) leaves delivery unconfirmed.
    ResponseDeliveryFinished {
        fingerprint: String,
        receipt: Option<serde_json::Value>,
        confirmed: bool,
        error: Option<String>,
    },
    /// Durable parent-child link, acknowledged before child inference.
    DelegationStarted {
        run_key: String,
        call_id: String,
        call_fingerprint: String,
        target: String,
        child_agent_id: AgentId,
        audit: super::run_audit::RunAuditReference,
        system_prompt_hash: String,
        message_hash: String,
    },
    /// A returned child result; cancellation can leave only the start link.
    DelegationFinished {
        run_key: String,
        call_id: String,
        audit: super::run_audit::RunAuditReference,
        reason: TerminationReason,
        output_hash: String,
    },
    /// An effect discovered within an exact authorized tool invocation.
    ToolEffect {
        run_key: String,
        call_fingerprint: String,
        effect: super::effect_journal::ToolEffect,
    },
    /// Loop started.
    Started {
        agent_id: AgentId,
        config: Box<LoopConfig>,
        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
        execution_context: HashMap<String, serde_json::Value>,
    },
    /// A fixed-endpoint inference request was durably authorized before send.
    InferenceRequested {
        request_id: String,
        endpoint: String,
        model: String,
        request_hash: String,
        reserved_output_tokens: u64,
    },
    /// The protected inference broker received a complete bounded response.
    InferenceCompleted {
        request_id: String,
        status: u16,
        response_hash: String,
        response_bytes: u64,
    },
    /// A direct DSL provider call. Hashes describe the typed provider contract,
    /// not an HTTP wire payload or authorization of provider-internal effects.
    DirectInferenceRequested {
        call_id: String,
        operation: String,
        provider: String,
        model: String,
        request_hash: String,
        request_bytes: u64,
        recipient: Option<AgentId>,
        recipient_definition_hash: Option<String>,
        communication: Option<serde_json::Value>,
    },
    /// A direct provider call settled, including cancellation and failures.
    DirectInferenceFinished {
        call_id: String,
        reason: TerminationReason,
        response_hash: Option<String>,
        response_bytes: u64,
        finish_reason: Option<crate::reasoning::inference::FinishReason>,
        usage: Usage,
    },
    /// A complete typed response was recorded before any communication reply.
    DirectInferenceResponseReceived {
        call_id: String,
        response_hash: String,
        response_bytes: u64,
    },
    /// Reasoning step completed.
    ReasoningComplete {
        iteration: u32,
        actions: Vec<ProposedAction>,
        usage: Usage,
    },
    /// Policy evaluation completed.
    PolicyEvaluated {
        iteration: u32,
        action_count: usize,
        denied_count: usize,
        /// Exact normalized invocations and contract identities approved at this boundary.
        #[serde(default)]
        approved_calls: Vec<serde_json::Value>,
        #[serde(default)]
        denied_calls: Vec<serde_json::Value>,
    },
    /// Tool dispatch completed.
    ToolsDispatched {
        iteration: u32,
        tool_count: usize,
        duration: Duration,
    },
    /// Results of a governed tool batch, correlated with pre-effect call records.
    ToolBatchCompleted {
        iteration: u32,
        observations: Vec<Observation>,
        duration: Duration,
    },
    /// Observations collected.
    ObservationsCollected {
        iteration: u32,
        observation_count: usize,
    },
    /// Shared scope accounting after inference, child cleanup or cancellation.
    BudgetUpdated {
        budget: super::budget::BudgetSnapshot,
    },
    /// Root-owned durable accounting shared by all descendants.
    BudgetOpened { root_id: uuid::Uuid, limit: u32 },
    BudgetScopeLinked {
        root_id: uuid::Uuid,
        scope: usize,
        root_audit: Option<super::run_audit::RunAuditReference>,
    },
    BudgetReservationStarted {
        reservation: super::budget::journal::InferenceReservation,
    },
    BudgetReservationFinished {
        root_id: uuid::Uuid,
        reservation_id: uuid::Uuid,
        usage: Usage,
        outcome: super::budget::journal::AccountingOutcome,
    },
    /// Loop terminated.
    Terminated {
        reason: TerminationReason,
        iterations: u32,
        total_usage: Usage,
        duration: Duration,
    },
    /// Error recovery triggered.
    RecoveryTriggered {
        iteration: u32,
        tool_name: String,
        strategy: RecoveryStrategy,
        error: String,
    },
    /// A step hit its reattempt limit (emitted by coordinators).
    #[cfg(feature = "orga-adaptive")]
    StepLimitReached {
        step_id: String,
        attempts: u32,
        reason: String,
    },
    /// Pre-hydration phase completed.
    #[cfg(feature = "orga-adaptive")]
    PreHydrationComplete {
        references_found: usize,
        references_resolved: usize,
        references_failed: usize,
        total_tokens: usize,
    },
}

/// A journal entry for durable execution.
///
/// In Phase 2, entries are emitted via the `JournalWriter` trait.
/// The default implementation is `BufferedJournal` which retains entries
/// in a bounded in-memory ring buffer for observability.
/// Phase 5 adds `DurableJournal` backed by SQLite/Postgres.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JournalEntry {
    /// Monotonically increasing sequence number.
    pub sequence: u64,
    /// When this entry was created.
    pub timestamp: chrono::DateTime<chrono::Utc>,
    /// The agent this entry belongs to.
    pub agent_id: AgentId,
    /// The iteration this entry was created in.
    pub iteration: u32,
    /// The event recorded.
    pub event: LoopEvent,
}

/// Trait for writing journal entries.
///
/// Configure a writer explicitly. Production entry points use protected run
/// journals; `BufferedJournal` is an opt-in, non-durable testing/display writer.
#[async_trait::async_trait]
pub trait JournalWriter: Send + Sync {
    /// Optional final-output evidence. Ordinary writers retain their existing
    /// event format; improvement execution explicitly supplies an implementation.
    async fn record_final_output(
        &self,
        _agent_id: AgentId,
        _iteration: u32,
        _output: &str,
    ) -> Result<(), JournalError> {
        Ok(())
    }
    /// Public identity of the protected run, when supplied by its trusted writer.
    fn audit_reference(&self) -> Option<super::run_audit::RunAuditReference> {
        None
    }
    /// Append an entry to the journal.
    async fn append(&self, entry: JournalEntry) -> Result<(), JournalError>;
    /// Get the next sequence number.
    async fn next_sequence(&self) -> u64;
}

/// In-memory journal that retains entries in a bounded ring buffer.
///
/// Provides observability without requiring durable storage. Events are
/// queryable via `entries()` and consumable via `drain()`. When the buffer
/// reaches capacity, the oldest entries are evicted.
pub struct BufferedJournal {
    sequence: std::sync::atomic::AtomicU64,
    capacity: usize,
    buffer: tokio::sync::Mutex<VecDeque<JournalEntry>>,
}

impl Default for BufferedJournal {
    fn default() -> Self {
        Self::new(1000)
    }
}

impl BufferedJournal {
    /// Create a new buffered journal with the given capacity.
    pub fn new(capacity: usize) -> Self {
        Self {
            sequence: std::sync::atomic::AtomicU64::new(0),
            capacity,
            buffer: tokio::sync::Mutex::new(VecDeque::with_capacity(capacity)),
        }
    }

    /// Return all currently buffered entries (oldest first).
    pub async fn entries(&self) -> Vec<JournalEntry> {
        self.buffer.lock().await.iter().cloned().collect()
    }

    /// Consume and return all buffered entries, emptying the buffer.
    pub async fn drain(&self) -> Vec<JournalEntry> {
        self.buffer.lock().await.drain(..).collect()
    }
}

#[async_trait::async_trait]
impl JournalWriter for BufferedJournal {
    async fn append(&self, entry: JournalEntry) -> Result<(), JournalError> {
        self.sequence
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let mut buf = self.buffer.lock().await;
        if buf.len() >= self.capacity {
            buf.pop_front();
        }
        buf.push_back(entry);
        Ok(())
    }

    async fn next_sequence(&self) -> u64 {
        self.sequence.load(std::sync::atomic::Ordering::Relaxed)
    }
}

/// Errors from the journal system.
#[derive(Debug, thiserror::Error)]
pub enum JournalError {
    #[error("Journal write failed: {0}")]
    WriteFailed(String),
    #[error("Journal read failed: {0}")]
    ReadFailed(String),
    #[error("Journal sequence error: expected {expected}, got {actual}")]
    SequenceError { expected: u64, actual: u64 },
}

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

    #[test]
    fn test_observation_constructors() {
        let tool_result = Observation::tool_result("search", "found 5 results");
        assert_eq!(tool_result.source, "search");
        assert!(!tool_result.is_error);

        let tool_error = Observation::tool_error("search", "timeout");
        assert!(tool_error.is_error);

        let denial = Observation::policy_denial("not authorized");
        assert_eq!(denial.source, "policy_gate");
        assert!(denial.is_error);
    }

    #[test]
    fn test_loop_state_new() {
        let state = LoopState::new(AgentId::new(), Conversation::with_system("test"));
        assert_eq!(state.iteration, 0);
        assert_eq!(state.total_usage.total_tokens, 0);
        assert!(state.pending_observations.is_empty());
    }

    #[test]
    fn test_loop_state_add_usage() {
        let mut state = LoopState::new(AgentId::new(), Conversation::new());
        state.add_usage(&Usage {
            prompt_tokens: 100,
            completion_tokens: 50,
            total_tokens: 150,
        });
        state.add_usage(&Usage {
            prompt_tokens: 200,
            completion_tokens: 80,
            total_tokens: 280,
        });
        assert_eq!(state.total_usage.prompt_tokens, 300);
        assert_eq!(state.total_usage.completion_tokens, 130);
        assert_eq!(state.total_usage.total_tokens, 430);
    }

    #[test]
    fn test_loop_config_default() {
        let config = LoopConfig::default();
        assert_eq!(config.max_iterations, 25);
        assert_eq!(config.max_total_tokens, 100_000);
        assert_eq!(config.max_concurrent_tools, 5);
    }

    #[test]
    fn test_proposed_action_variants() {
        let tc = ProposedAction::ToolCall {
            call_id: "c1".into(),
            name: "search".into(),
            arguments: "{}".into(),
        };
        assert!(matches!(tc, ProposedAction::ToolCall { .. }));

        let respond = ProposedAction::Respond {
            content: "done".into(),
        };
        assert!(matches!(respond, ProposedAction::Respond { .. }));

        let terminate = ProposedAction::Terminate {
            reason: "finished".into(),
            output: "result".into(),
        };
        assert!(matches!(terminate, ProposedAction::Terminate { .. }));
    }

    #[test]
    fn test_recovery_strategy_serde() {
        let retry = RecoveryStrategy::Retry {
            max_attempts: 3,
            base_delay: Duration::from_millis(100),
        };
        let json = serde_json::to_string(&retry).unwrap();
        let _restored: RecoveryStrategy = serde_json::from_str(&json).unwrap();

        let llm = RecoveryStrategy::LlmRecovery {
            max_recovery_attempts: 1,
        };
        let json = serde_json::to_string(&llm).unwrap();
        assert!(json.contains("LlmRecovery"));
    }

    fn make_journal_entry(seq: u64, iteration: u32) -> JournalEntry {
        JournalEntry {
            sequence: seq,
            timestamp: chrono::Utc::now(),
            agent_id: AgentId::new(),
            iteration,
            event: LoopEvent::Started {
                agent_id: AgentId::new(),
                config: Box::new(LoopConfig::default()),
                execution_context: HashMap::new(),
            },
        }
    }

    #[tokio::test]
    async fn test_buffered_journal_retains_entries() {
        let journal = BufferedJournal::new(100);
        assert_eq!(journal.next_sequence().await, 0);

        journal.append(make_journal_entry(0, 0)).await.unwrap();
        journal.append(make_journal_entry(1, 1)).await.unwrap();

        assert_eq!(journal.next_sequence().await, 2);

        let entries = journal.entries().await;
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].sequence, 0);
        assert_eq!(entries[1].sequence, 1);
    }

    #[tokio::test]
    async fn test_buffered_journal_overflow_evicts_oldest() {
        let journal = BufferedJournal::new(3);

        for i in 0..5u64 {
            journal
                .append(make_journal_entry(i, i as u32))
                .await
                .unwrap();
        }

        let entries = journal.entries().await;
        assert_eq!(entries.len(), 3);
        // Oldest two (seq 0, 1) were evicted
        assert_eq!(entries[0].sequence, 2);
        assert_eq!(entries[1].sequence, 3);
        assert_eq!(entries[2].sequence, 4);
    }

    #[tokio::test]
    async fn test_buffered_journal_drain_empties_buffer() {
        let journal = BufferedJournal::new(100);

        journal.append(make_journal_entry(0, 0)).await.unwrap();
        journal.append(make_journal_entry(1, 1)).await.unwrap();

        let drained = journal.drain().await;
        assert_eq!(drained.len(), 2);

        // Buffer is now empty
        let entries = journal.entries().await;
        assert!(entries.is_empty());

        // Sequence counter is not reset by drain
        assert_eq!(journal.next_sequence().await, 2);
    }

    #[tokio::test]
    async fn test_buffered_journal_entries_returns_all() {
        let journal = BufferedJournal::new(100);

        for i in 0..10u64 {
            journal
                .append(make_journal_entry(i, i as u32))
                .await
                .unwrap();
        }

        let entries = journal.entries().await;
        assert_eq!(entries.len(), 10);
        for (idx, entry) in entries.iter().enumerate() {
            assert_eq!(entry.sequence, idx as u64);
        }
    }

    #[test]
    fn test_loop_state_trusted_context_defaults_empty_and_is_settable() {
        let mut state = LoopState::new(AgentId::new(), Conversation::new());
        assert!(state.trusted_context.is_empty());
        state
            .trusted_context
            .insert("ticket_severity".into(), serde_json::json!("critical"));
        assert_eq!(
            state.trusted_context.get("ticket_severity"),
            Some(&serde_json::json!("critical"))
        );
    }

    #[test]
    fn test_loop_event_serde() {
        let event = LoopEvent::Terminated {
            reason: TerminationReason::Completed,
            iterations: 5,
            total_usage: Usage {
                prompt_tokens: 1000,
                completion_tokens: 500,
                total_tokens: 1500,
            },
            duration: Duration::from_secs(10),
        };
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains("Terminated"));
    }

    #[test]
    fn loop_config_default_has_delegation_guards() {
        let c = LoopConfig::default();
        assert_eq!(c.max_delegation_depth, 3);
        assert_eq!(c.delegation_depth, 0);
        assert!(c.delegation_chain.is_empty());
    }

    #[test]
    fn delegation_error_messages_name_the_cause() {
        use crate::reasoning::delegation::DelegationError;
        assert!(DelegationError::UnknownTarget("reviewer".into())
            .to_string()
            .contains("reviewer"));
        assert!(DelegationError::DepthExceeded(3).to_string().contains('3'));
    }
}