meerkat-core 0.5.2

Core agent logic for Meerkat (no I/O deps)
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
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
//! Agent builder.

use crate::budget::{Budget, BudgetLimits};
use crate::config::{AgentConfig, CallTimeoutOverride, HookRunOverrides};
use crate::hooks::HookEngine;
use crate::model_defaults::ModelOperationalDefaultsResolver;
use crate::ops::ConcurrencyLimits;
#[cfg(not(target_arch = "wasm32"))]
use crate::prompt::SystemPromptConfig;
use crate::retry::RetryPolicy;
use crate::session::{SESSION_TOOL_VISIBILITY_STATE_KEY, Session, SessionToolVisibilityState};
use crate::state::LoopState;
#[cfg(target_arch = "wasm32")]
use crate::tokio;
use crate::tool_catalog::{ToolCatalogDeferredEligibility, ToolCatalogMode, ToolPlaneClass};
use crate::tool_scope::{
    EXTERNAL_TOOL_FILTER_METADATA_KEY, INHERITED_TOOL_FILTER_METADATA_KEY, ToolFilter, ToolScope,
};
use crate::types::{Message, OutputSchema};
use serde_json::Value;
use std::sync::Arc;
use tokio::sync::mpsc;

use super::{
    Agent, AgentLlmClient, AgentSessionStore, AgentToolDispatcher, CommsRuntime,
    select_tool_catalog_mode,
};

/// Builder for creating an Agent
#[derive(Default)]
pub struct AgentBuilder {
    pub(super) config: AgentConfig,
    pub(super) system_prompt: Option<String>,
    pub(super) budget_limits: Option<BudgetLimits>,
    pub(super) retry_policy: RetryPolicy,
    pub(super) session: Option<Session>,
    pub(super) concurrency_limits: ConcurrencyLimits,
    pub(super) depth: u32,
    pub(super) comms_runtime: Option<Arc<dyn CommsRuntime>>,
    pub(super) hook_engine: Option<Arc<dyn HookEngine>>,
    pub(super) hook_run_overrides: HookRunOverrides,
    pub(super) compactor: Option<Arc<dyn crate::compact::Compactor>>,
    pub(super) memory_store: Option<Arc<dyn crate::memory::MemoryStore>>,
    pub(super) skill_engine: Option<Arc<crate::skills::SkillRuntime>>,
    pub(super) checkpointer: Option<Arc<dyn crate::checkpoint::SessionCheckpointer>>,
    pub(super) blob_store: Option<Arc<dyn crate::BlobStore>>,
    pub(super) silent_comms_intents: Vec<String>,
    pub(super) ops_lifecycle: Option<Arc<dyn crate::ops_lifecycle::OpsLifecycleRegistry>>,
    pub(super) completion_feed: Option<Arc<dyn crate::completion_feed::CompletionFeed>>,
    pub(super) completion_enrichment:
        Option<Arc<dyn crate::completion_feed::CompletionEnrichmentProvider>>,
    pub(super) max_inline_peer_notifications: Option<i32>,
    pub(super) event_tap: Option<crate::event_tap::EventTap>,
    pub(super) default_event_tx: Option<mpsc::Sender<crate::event::AgentEvent>>,
    pub(super) model_defaults_resolver: Option<Arc<dyn ModelOperationalDefaultsResolver>>,
    pub(super) call_timeout_override: CallTimeoutOverride,
    pub(super) epoch_cursor_state: Option<Arc<crate::runtime_epoch::EpochCursorState>>,
}

impl AgentBuilder {
    /// Create a new agent builder with default config
    pub fn new() -> Self {
        Self {
            config: AgentConfig::default(),
            system_prompt: None,
            budget_limits: None,
            retry_policy: RetryPolicy::default(),
            session: None,
            concurrency_limits: ConcurrencyLimits::default(),
            depth: 0,
            comms_runtime: None,
            hook_engine: None,
            hook_run_overrides: HookRunOverrides::default(),
            compactor: None,
            memory_store: None,
            skill_engine: None,
            checkpointer: None,
            blob_store: None,
            silent_comms_intents: Vec::new(),
            ops_lifecycle: None,
            completion_feed: None,
            completion_enrichment: None,
            max_inline_peer_notifications: None,
            event_tap: None,
            default_event_tx: None,
            model_defaults_resolver: None,
            call_timeout_override: CallTimeoutOverride::default(),
            epoch_cursor_state: None,
        }
    }

    /// Set concurrency limits for delegated branches
    pub fn concurrency_limits(mut self, limits: ConcurrencyLimits) -> Self {
        self.concurrency_limits = limits;
        self
    }

    /// Set the nesting depth for delegated branches
    pub fn depth(mut self, depth: u32) -> Self {
        self.depth = depth;
        self
    }

    /// Set the model to use
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.config.model = model.into();
        self
    }

    /// Set the system prompt
    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.system_prompt = Some(prompt.into());
        self
    }

    /// Set max tokens per turn
    pub fn max_tokens_per_turn(mut self, tokens: u32) -> Self {
        self.config.max_tokens_per_turn = tokens;
        self
    }

    /// Set temperature
    pub fn temperature(mut self, temp: f32) -> Self {
        self.config.temperature = Some(temp);
        self
    }

    /// Set budget limits
    pub fn budget(mut self, limits: BudgetLimits) -> Self {
        self.budget_limits = Some(limits);
        self
    }

    /// Set provider-specific parameters
    pub fn provider_params(mut self, params: Value) -> Self {
        self.config.provider_params = Some(params);
        self
    }

    /// Set provider-native tool defaults (resolved at build time, not persisted).
    pub fn provider_tool_defaults(mut self, defaults: Value) -> Self {
        self.config.provider_tool_defaults = Some(defaults);
        self
    }

    /// Set retry policy for LLM calls
    pub fn retry_policy(mut self, policy: RetryPolicy) -> Self {
        self.retry_policy = policy;
        self
    }

    /// Set output schema for structured output extraction
    pub fn output_schema(mut self, schema: OutputSchema) -> Self {
        self.config.output_schema = Some(schema);
        self
    }

    /// Set the memory store for indexing compaction discards.
    pub fn memory_store(mut self, store: Arc<dyn crate::memory::MemoryStore>) -> Self {
        self.memory_store = Some(store);
        self
    }

    /// Set maximum retries for structured output validation
    pub fn structured_output_retries(mut self, retries: u32) -> Self {
        self.config.structured_output_retries = retries;
        self
    }

    /// Resume from an existing session
    pub fn resume_session(mut self, session: Session) -> Self {
        self.session = Some(session);
        self
    }

    /// Set the comms runtime.
    pub fn with_comms_runtime(mut self, runtime: Arc<dyn CommsRuntime>) -> Self {
        self.comms_runtime = Some(runtime);
        self
    }

    /// Set the hook engine.
    pub fn with_hook_engine(mut self, hook_engine: Arc<dyn HookEngine>) -> Self {
        self.hook_engine = Some(hook_engine);
        self
    }

    /// Set run-scoped hook overrides.
    pub fn with_hook_run_overrides(mut self, overrides: HookRunOverrides) -> Self {
        self.hook_run_overrides = overrides;
        self
    }

    /// Set the context compactor.
    pub fn compactor(mut self, compactor: Arc<dyn crate::compact::Compactor>) -> Self {
        self.compactor = Some(compactor);
        self
    }

    /// Build the agent
    pub async fn build<C, T, S>(
        self,
        client: Arc<C>,
        tools: Arc<T>,
        store: Arc<S>,
    ) -> Agent<C, T, S>
    where
        C: AgentLlmClient + ?Sized,
        T: AgentToolDispatcher + ?Sized,
        S: AgentSessionStore + ?Sized,
    {
        let mut session = self.session.unwrap_or_default();
        let system_context_state = Arc::new(std::sync::Mutex::new(
            session.system_context_state().unwrap_or_default(),
        ));

        // Apply system prompt: use builder's prompt if set, otherwise compose default for new sessions
        let has_system_prompt = matches!(session.messages().first(), Some(Message::System(_)));
        if let Some(prompt) = self.system_prompt {
            session.set_system_prompt(prompt);
        } else if !has_system_prompt {
            // Only set default prompt for new sessions without an existing system prompt
            #[cfg(not(target_arch = "wasm32"))]
            {
                session.set_system_prompt(SystemPromptConfig::new().compose().await);
            }
            #[cfg(target_arch = "wasm32")]
            {
                session.set_system_prompt(String::new());
            }
        }

        let budget = Budget::new(self.budget_limits.unwrap_or_default());
        let catalog_mode = select_tool_catalog_mode(tools.as_ref());
        let (control_tool_names, deferred_tool_names) =
            if tools.tool_catalog_capabilities().exact_catalog {
                let catalog = tools.tool_catalog();
                let control_names = catalog
                    .iter()
                    .filter(|entry| entry.plane == ToolPlaneClass::Control)
                    .map(|entry| entry.tool.name.clone())
                    .collect::<std::collections::HashSet<_>>();
                let deferred_names = if !control_names.is_empty()
                    && matches!(catalog_mode, ToolCatalogMode::Deferred)
                {
                    catalog
                        .iter()
                        .filter(|entry| entry.plane == ToolPlaneClass::Session)
                        .filter(|entry| {
                            matches!(
                                entry.deferred_eligibility,
                                ToolCatalogDeferredEligibility::DeferredEligible { .. }
                            )
                        })
                        .map(|entry| entry.tool.name.clone())
                        .collect()
                } else {
                    std::collections::HashSet::new()
                };
                (control_names, deferred_names)
            } else {
                (
                    std::collections::HashSet::new(),
                    std::collections::HashSet::new(),
                )
            };
        let tool_scope = ToolScope::new_with_projection_names(
            tools.tools(),
            control_tool_names,
            deferred_tool_names,
        );
        let compaction_cadence = crate::agent::compact::load_compaction_cadence(&session);

        let mut agent = Agent {
            config: self.config,
            client,
            tools,
            tool_scope,
            store,
            session,
            budget,
            retry_policy: self.retry_policy,
            state: LoopState::CallingLlm,
            depth: self.depth,
            comms_runtime: self.comms_runtime,
            hook_engine: self.hook_engine,
            hook_run_overrides: self.hook_run_overrides,
            compactor: self.compactor,
            last_input_tokens: 0,
            compaction_cadence,
            memory_store: self.memory_store,
            skill_engine: self.skill_engine,
            pending_skill_references: None,
            pending_fatal_diagnostic: None,
            silent_comms_intents: self.silent_comms_intents,
            checkpointer: self.checkpointer,
            blob_store: self.blob_store,
            event_tap: self
                .event_tap
                .unwrap_or_else(crate::event_tap::new_event_tap),
            system_context_state,
            default_event_tx: self.default_event_tx,
            ops_lifecycle: self.ops_lifecycle,
            // Seed from epoch cursor state if available (runtime-backed surfaces),
            // otherwise fall back to the feed watermark to avoid replaying retained
            // completions from prior agent lifetimes (stop/resume, live reattach).
            // Same pattern as runtime_loop.rs line 276. Computed before move.
            applied_cursor: self
                .epoch_cursor_state
                .as_ref()
                .map(|cs| {
                    cs.agent_applied_cursor
                        .load(std::sync::atomic::Ordering::Acquire)
                })
                .unwrap_or_else(|| self.completion_feed.as_ref().map_or(0, |f| f.watermark())),
            completion_feed: self.completion_feed,
            epoch_cursor_state: self.epoch_cursor_state,
            completion_enrichment: self.completion_enrichment,
            mob_authority_handle: None,
            turn_authority: crate::turn_execution_authority::TurnExecutionAuthority::new(),
            model_defaults_resolver: self.model_defaults_resolver,
            call_timeout_override: self.call_timeout_override,
            extraction_result: None,
            extraction_schema_warnings: None,
            extraction_last_error: None,
            last_hidden_deferred_catalog_names: Default::default(),
            last_pending_catalog_sources: Default::default(),
        };

        let mut visibility_state = agent.session.tool_visibility_state().unwrap_or_default();
        let has_canonical_visibility_state = agent
            .session
            .metadata()
            .contains_key(SESSION_TOOL_VISIBILITY_STATE_KEY);

        if !has_canonical_visibility_state {
            if let Some(raw_filter) = agent
                .session
                .metadata()
                .get(EXTERNAL_TOOL_FILTER_METADATA_KEY)
                .cloned()
            {
                match serde_json::from_value::<ToolFilter>(raw_filter) {
                    Ok(filter) => {
                        visibility_state.active_filter = filter.clone();
                        visibility_state.staged_filter = filter;
                    }
                    Err(err) => {
                        tracing::warn!(
                            error = %err,
                            "failed to parse persisted tool scope filter; ignoring"
                        );
                    }
                }
            }

            if let Some(raw_filter) = agent
                .session
                .metadata()
                .get(INHERITED_TOOL_FILTER_METADATA_KEY)
                .cloned()
            {
                match serde_json::from_value::<ToolFilter>(raw_filter) {
                    Ok(filter) => {
                        visibility_state.inherited_base_filter = filter;
                    }
                    Err(err) => {
                        tracing::warn!(
                            error = %err,
                            "failed to parse inherited tool scope filter; ignoring"
                        );
                    }
                }
            }
        }

        if visibility_state != SessionToolVisibilityState::default()
            || has_canonical_visibility_state
        {
            if let Err(err) = agent
                .tool_scope
                .set_visibility_state(visibility_state.clone())
            {
                tracing::warn!(
                    error = %err,
                    "failed to apply canonical tool visibility state; ignoring"
                );
            } else if let Err(err) = agent.session.set_tool_visibility_state(visibility_state) {
                tracing::warn!(
                    error = %err,
                    "failed to persist canonical tool visibility state during restore"
                );
            } else {
                agent
                    .session
                    .remove_metadata(EXTERNAL_TOOL_FILTER_METADATA_KEY);
                agent
                    .session
                    .remove_metadata(INHERITED_TOOL_FILTER_METADATA_KEY);
            }
        }

        agent
    }

    /// Set the session checkpointer for keep-alive persistence.
    pub fn with_checkpointer(
        mut self,
        cp: Arc<dyn crate::checkpoint::SessionCheckpointer>,
    ) -> Self {
        self.checkpointer = Some(cp);
        self
    }

    /// Set the blob store used to hydrate image refs before execution.
    pub fn with_blob_store(mut self, blob_store: Arc<dyn crate::BlobStore>) -> Self {
        self.blob_store = Some(blob_store);
        self
    }

    /// Set comms intents that should be silently injected into the session
    /// without triggering an LLM turn.
    pub fn with_silent_comms_intents(mut self, intents: Vec<String>) -> Self {
        self.silent_comms_intents = intents;
        self
    }

    /// Set max peer-count threshold for inline peer lifecycle notification injection.
    pub fn with_max_inline_peer_notifications(mut self, threshold: Option<i32>) -> Self {
        self.max_inline_peer_notifications = threshold;
        self
    }

    /// Set the ops lifecycle registry for async operation tracking.
    pub fn with_ops_lifecycle(
        mut self,
        registry: Arc<dyn crate::ops_lifecycle::OpsLifecycleRegistry>,
    ) -> Self {
        self.ops_lifecycle = Some(registry);
        self
    }

    /// Set the completion feed for cursor-based completion delivery.
    pub fn with_completion_feed(
        mut self,
        feed: Arc<dyn crate::completion_feed::CompletionFeed>,
    ) -> Self {
        self.completion_feed = Some(feed);
        self
    }

    /// Set the enrichment provider for completion display details.
    pub fn with_completion_enrichment(
        mut self,
        enrichment: Arc<dyn crate::completion_feed::CompletionEnrichmentProvider>,
    ) -> Self {
        self.completion_enrichment = Some(enrichment);
        self
    }

    /// Set the skill engine for per-turn `/skill-ref` activation.
    pub fn with_skill_engine(mut self, engine: Arc<crate::skills::SkillRuntime>) -> Self {
        self.skill_engine = Some(engine);
        self
    }

    /// Set the event tap for interaction-scoped streaming.
    pub fn with_event_tap(mut self, tap: crate::event_tap::EventTap) -> Self {
        self.event_tap = Some(tap);
        self
    }

    /// Set a default event channel used when run methods are called without
    /// per-call event channels.
    pub fn with_default_event_tx(
        mut self,
        event_tx: mpsc::Sender<crate::event::AgentEvent>,
    ) -> Self {
        self.default_event_tx = Some(event_tx);
        self
    }

    /// Set the model operational defaults resolver for profile-derived call timeouts.
    ///
    /// The resolver is consulted at each LLM call to look up model-specific
    /// operational defaults (e.g., call timeout) for the current effective
    /// model/provider. This enables hot-swap-aware default resolution.
    pub fn with_model_defaults_resolver(
        mut self,
        resolver: Arc<dyn ModelOperationalDefaultsResolver>,
    ) -> Self {
        self.model_defaults_resolver = Some(resolver);
        self
    }

    /// Set the shared epoch cursor state for runtime-backed cursor writeback.
    pub fn with_epoch_cursor_state(
        mut self,
        state: Arc<crate::runtime_epoch::EpochCursorState>,
    ) -> Self {
        self.epoch_cursor_state = Some(state);
        self
    }

    /// Set the explicit call-timeout override from the build/config composition seam.
    ///
    /// - `Inherit`: defer to profile-derived default via the resolver
    /// - `Disabled`: explicitly suppress call timeout
    /// - `Value(d)`: explicitly set call timeout to `d`
    pub fn with_call_timeout_override(mut self, override_value: CallTimeoutOverride) -> Self {
        self.call_timeout_override = override_value;
        self
    }
}

#[cfg(test)]
#[allow(clippy::panic)]
mod tests {
    use super::*;
    use crate::LlmStreamResult;
    use crate::error::{AgentError, ToolError};
    use crate::event::AgentEvent;
    use crate::event_tap::EventTapState;
    use crate::types::{AssistantBlock, StopReason, ToolCallView, ToolDef, UserMessage};
    use async_trait::async_trait;
    use std::sync::atomic::AtomicBool;
    use tokio::sync::mpsc;

    struct MockClient;

    #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
    #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
    impl AgentLlmClient for MockClient {
        async fn stream_response(
            &self,
            _messages: &[Message],
            _tools: &[Arc<ToolDef>],
            _max_tokens: u32,
            _temperature: Option<f32>,
            _provider_params: Option<&Value>,
        ) -> Result<LlmStreamResult, AgentError> {
            Ok(LlmStreamResult::new(
                vec![AssistantBlock::Text {
                    text: "Done".to_string(),
                    meta: None,
                }],
                StopReason::EndTurn,
                crate::types::Usage::default(),
            ))
        }

        fn provider(&self) -> &'static str {
            "mock"
        }

        fn model(&self) -> &'static str {
            "mock-model"
        }
    }

    struct MockTools;

    #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
    #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
    impl AgentToolDispatcher for MockTools {
        fn tools(&self) -> Arc<[Arc<ToolDef>]> {
            Arc::new([])
        }

        async fn dispatch(
            &self,
            call: ToolCallView<'_>,
        ) -> Result<crate::ops::ToolDispatchOutcome, ToolError> {
            Err(ToolError::NotFound {
                name: call.name.to_string(),
            })
        }
    }

    struct MockStore;

    #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
    #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
    impl AgentSessionStore for MockStore {
        async fn save(&self, _session: &Session) -> Result<(), AgentError> {
            Ok(())
        }
        async fn load(&self, _id: &str) -> Result<Option<Session>, AgentError> {
            Ok(None)
        }
    }

    /// Regression test: AgentBuilder should apply system_prompt to new sessions
    #[tokio::test]
    async fn test_regression_builder_applies_system_prompt_to_new_session() {
        let client = Arc::new(MockClient);
        let tools = Arc::new(MockTools);
        let store = Arc::new(MockStore);

        let agent = AgentBuilder::new()
            .system_prompt("Custom system prompt")
            .build(client, tools, store)
            .await;

        // Check that the system prompt was applied
        let messages = agent.session().messages();
        assert!(!messages.is_empty(), "Session should have messages");

        match &messages[0] {
            Message::System(sys) => {
                assert_eq!(sys.content, "Custom system prompt");
            }
            other => panic!("First message should be System, got: {other:?}"),
        }
    }

    /// Regression test: AgentBuilder should apply system_prompt to resumed sessions
    /// Previously, system_prompt was ignored when resuming a session.
    #[tokio::test]
    async fn test_regression_builder_applies_system_prompt_to_resumed_session() {
        let client = Arc::new(MockClient);
        let tools = Arc::new(MockTools);
        let store = Arc::new(MockStore);

        // Create a session with an existing system prompt
        let mut existing_session = Session::new();
        existing_session.set_system_prompt("Original system prompt".to_string());
        existing_session.push(Message::User(UserMessage::text("Hello".to_string())));

        // Resume the session with a NEW system prompt
        let agent = AgentBuilder::new()
            .resume_session(existing_session)
            .system_prompt("Updated system prompt")
            .build(client, tools, store)
            .await;

        // Check that the system prompt was UPDATED
        let messages = agent.session().messages();
        assert!(!messages.is_empty(), "Session should have messages");

        match &messages[0] {
            Message::System(sys) => {
                assert_eq!(
                    sys.content, "Updated system prompt",
                    "System prompt should be updated when resuming with a new prompt"
                );
            }
            other => panic!("First message should be System, got: {other:?}"),
        }

        // User message should still be preserved
        assert!(messages.len() >= 2, "Should have system + user messages");
        match &messages[1] {
            Message::User(user) => {
                assert_eq!(user.text_content(), "Hello");
            }
            other => panic!("Second message should be User, got: {other:?}"),
        }
    }

    /// Regression test: Resumed sessions without explicit system_prompt should keep their original
    #[tokio::test]
    async fn test_builder_preserves_existing_system_prompt_on_resume() {
        let client = Arc::new(MockClient);
        let tools = Arc::new(MockTools);
        let store = Arc::new(MockStore);

        // Create a session with an existing system prompt
        let mut existing_session = Session::new();
        existing_session.set_system_prompt("Original system prompt".to_string());

        // Resume WITHOUT specifying a new system prompt
        let agent = AgentBuilder::new()
            .resume_session(existing_session)
            // Note: no .system_prompt() call
            .build(client, tools, store)
            .await;

        // Original system prompt should be preserved
        let messages = agent.session().messages();
        match &messages[0] {
            Message::System(sys) => {
                assert_eq!(
                    sys.content, "Original system prompt",
                    "Original system prompt should be preserved when not overridden"
                );
            }
            other => panic!("First message should be System, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_builder_event_tap_receives_turn_started_without_primary_event_tx() {
        let client = Arc::new(MockClient);
        let tools = Arc::new(MockTools);
        let store = Arc::new(MockStore);

        let tap = crate::event_tap::new_event_tap();
        let (tap_tx, mut tap_rx) = mpsc::channel(128);
        {
            let mut guard = tap.lock();
            *guard = Some(EventTapState {
                tx: tap_tx,
                truncated: AtomicBool::new(false),
            });
        }

        let mut agent = AgentBuilder::new()
            .with_event_tap(tap)
            .build(client, tools, store)
            .await;

        let result = agent.run("hello".to_string().into()).await;
        assert!(result.is_ok());

        let mut saw_turn_started = false;
        while let Ok(event) = tap_rx.try_recv() {
            if matches!(event, AgentEvent::TurnStarted { .. }) {
                saw_turn_started = true;
                break;
            }
        }
        assert!(
            saw_turn_started,
            "tap should receive TurnStarted even without primary event channel"
        );
    }

    /// Regression: agent builder must seed applied_cursor from the feed's
    /// current watermark, not from 0. Starting from 0 replays every retained
    /// completion as new after stop/resume or live reattachment.
    #[tokio::test]
    async fn test_builder_seeds_applied_cursor_from_feed_watermark() {
        use crate::completion_feed::tests::MockCompletionFeed;

        let client = Arc::new(MockClient);
        let tools = Arc::new(MockTools);
        let store = Arc::new(MockStore);

        // Feed already has activity at watermark 42.
        let feed = Arc::new(MockCompletionFeed::with_watermark(42));

        let agent = AgentBuilder::new()
            .with_completion_feed(feed)
            .build(client, tools, store)
            .await;

        assert_eq!(
            agent.applied_cursor, 42,
            "applied_cursor must seed from feed watermark, not 0"
        );
    }

    /// Regression: without a feed, applied_cursor must be 0.
    #[tokio::test]
    async fn test_builder_applied_cursor_zero_without_feed() {
        let client = Arc::new(MockClient);
        let tools = Arc::new(MockTools);
        let store = Arc::new(MockStore);

        let agent = AgentBuilder::new().build(client, tools, store).await;

        assert_eq!(agent.applied_cursor, 0);
    }
}