navi-core 0.1.0

Local agentic engine and terminal-first coding agent.
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
766
use super::*;
use crate::model::ModelResponse;
use crate::tool::{Tool, ToolDefinition, ToolKind, ToolMetadata};
use crate::{ModelStream, SecurityConfig, SecurityPolicy, ToolInvocation, ToolResult};
use async_trait::async_trait;
use futures_util::stream;
use serde_json::json;
use std::path::PathBuf;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;

struct MockTool;
#[async_trait]
impl Tool for MockTool {
    fn definition(&self) -> ToolDefinition {
        ToolDefinition {
            name: "test_tool".to_string(),
            description: "mock tool".to_string(),
            kind: ToolKind::Custom,
            input_schema: json!({}),
            metadata: Default::default(),
        }
    }
    async fn invoke(&self, invocation: ToolInvocation) -> Result<ToolResult> {
        Ok(ToolResult {
            invocation_id: invocation.id,
            ok: true,
            output: json!({ "result": "mock ok" }),
        })
    }
}

#[derive(Clone, Default)]
struct ParallelProbe {
    active: Arc<AtomicUsize>,
    max_active: Arc<AtomicUsize>,
}

impl ParallelProbe {
    fn enter(&self) {
        let active = self.active.fetch_add(1, Ordering::SeqCst) + 1;
        loop {
            let current = self.max_active.load(Ordering::SeqCst);
            if active <= current
                || self
                    .max_active
                    .compare_exchange(current, active, Ordering::SeqCst, Ordering::SeqCst)
                    .is_ok()
            {
                break;
            }
        }
    }

    fn exit(&self) {
        self.active.fetch_sub(1, Ordering::SeqCst);
    }

    fn max_active(&self) -> usize {
        self.max_active.load(Ordering::SeqCst)
    }
}

struct SleepingTool {
    name: String,
    metadata: ToolMetadata,
    probe: ParallelProbe,
}

impl SleepingTool {
    fn shared(name: &str, probe: ParallelProbe) -> Self {
        Self {
            name: name.to_string(),
            metadata: ToolMetadata::reader("test", &["parallel", "read"]),
            probe,
        }
    }

    fn exclusive(name: &str, probe: ParallelProbe) -> Self {
        let mut metadata = ToolMetadata::reader("test", &["exclusive"]);
        metadata.is_read_only = false;
        metadata.is_concurrency_safe = false;
        Self {
            name: name.to_string(),
            metadata,
            probe,
        }
    }
}

#[async_trait]
impl Tool for SleepingTool {
    fn definition(&self) -> ToolDefinition {
        ToolDefinition {
            name: self.name.clone(),
            description: "sleeping probe tool".to_string(),
            kind: ToolKind::Read,
            input_schema: json!({}),
            metadata: self.metadata.clone(),
        }
    }

    async fn invoke(&self, invocation: ToolInvocation) -> Result<ToolResult> {
        self.probe.enter();
        tokio::time::sleep(Duration::from_millis(30)).await;
        self.probe.exit();
        Ok(ToolResult {
            invocation_id: invocation.id,
            ok: true,
            output: json!({ "result": "ok" }),
        })
    }
}

struct MockProvider {
    calls: Mutex<usize>,
}

#[async_trait]
impl ModelProvider for MockProvider {
    fn stream(&self, _request: ModelRequest) -> ModelStream {
        let mut calls = self.calls.lock().unwrap();
        *calls += 1;
        let call_count = *calls;
        if call_count == 1 {
            Box::pin(stream::iter(vec![
                Ok(ModelStreamEvent::ToolCall(ToolInvocation {
                    id: "call-1".to_string(),
                    tool_name: "test_tool".to_string(),
                    input: json!({}),
                })),
                Ok(ModelStreamEvent::ToolCall(ToolInvocation {
                    id: "call-2".to_string(),
                    tool_name: "test_tool".to_string(),
                    input: json!({}),
                })),
                Ok(ModelStreamEvent::Done),
            ]))
        } else {
            Box::pin(stream::iter(vec![
                Ok(ModelStreamEvent::TextDelta {
                    text: "done".to_string(),
                }),
                Ok(ModelStreamEvent::Done),
            ]))
        }
    }

    async fn complete(&self, request: ModelRequest) -> Result<ModelResponse> {
        ModelProvider::complete(self, request).await
    }
}

struct MalformedToolProvider {
    calls: Mutex<usize>,
}

#[async_trait]
impl ModelProvider for MalformedToolProvider {
    fn stream(&self, _request: ModelRequest) -> ModelStream {
        let mut calls = self.calls.lock().unwrap();
        *calls += 1;
        Box::pin(stream::iter(vec![
            Ok(ModelStreamEvent::ToolCall(ToolInvocation {
                id: format!("call-{}", *calls),
                tool_name: "read".to_string(),
                input: json!({ "raw_arguments": "{\"path\": " }),
            })),
            Ok(ModelStreamEvent::Done),
        ]))
    }

    async fn complete(&self, request: ModelRequest) -> Result<ModelResponse> {
        ModelProvider::complete(self, request).await
    }
}

struct CapturingProvider {
    requests: Arc<Mutex<Vec<ModelRequest>>>,
}

#[async_trait]
impl ModelProvider for CapturingProvider {
    fn stream(&self, request: ModelRequest) -> ModelStream {
        self.requests.lock().unwrap().push(request);
        Box::pin(stream::iter(vec![
            Ok(ModelStreamEvent::TextDelta {
                text: "captured".to_string(),
            }),
            Ok(ModelStreamEvent::Done),
        ]))
    }
}

struct DegenerateOutputProvider;

#[async_trait]
impl ModelProvider for DegenerateOutputProvider {
    fn stream(&self, _request: ModelRequest) -> ModelStream {
        Box::pin(stream::iter(vec![
            Ok(ModelStreamEvent::TextDelta {
                text: "a".repeat(80),
            }),
            Ok(ModelStreamEvent::Done),
        ]))
    }
}

#[tokio::test]
async fn test_turn_loop_with_parallel_tools() {
    let tempdir = tempfile::tempdir().unwrap();
    let security_policy = SecurityPolicy::new(
        tempdir.path().to_path_buf(),
        tempdir.path().to_path_buf(),
        SecurityConfig::default(),
    )
    .unwrap();
    let mut executor = ToolExecutor::new(security_policy);
    executor.register_tool(Arc::new(MockTool));

    let ctx = TurnContext {
        model_provider: Arc::new(std::sync::RwLock::new(Arc::new(MockProvider {
            calls: Mutex::new(0),
        }))),
        tool_executor: Arc::new(executor),
        project_dir: tempdir.path().to_path_buf(),
        data_dir: tempdir.path().join("data"),
        model_name: Arc::new(std::sync::RwLock::new("gpt-4".to_string())),
        event_tx: None,
        approval_resolver: crate::runtime::ApprovalResolver::new_for_test(),
        question_resolver: crate::runtime::QuestionResolver::new_for_test(),
        compact_state: Arc::new(tokio::sync::Mutex::new(CompactState::new(128_000))),
        harness_config: crate::config::HarnessConfig::default(),
        include_tool_prompt_manifest: false,
        context_packets: Arc::new(std::sync::Mutex::new(Vec::new())),
        active_skills: Arc::new(std::sync::Mutex::new(Vec::new())),
        prompt_cache: Arc::new(crate::prompt::PromptCache::new()),
        components: crate::RuntimeComponents::default(),
        cancel_token: CancelToken::new(),
        config: Arc::new(std::sync::RwLock::new(crate::config::NaviConfig::default())),
        memory_injection: None,
        compaction_provider: None,
        compaction_model_name: None,
        session_id: "test-session".to_string(),
        allowed_tool_names: None,
    };

    let mut messages = vec![];
    let policy = crate::harness::policy_for_profile(
        &crate::config::HarnessConfig {
            observation_bytes_small: 1000,
            ..crate::config::HarnessConfig::default()
        },
        crate::config::HarnessProfile::Small,
    );

    let result = run_turn(&ctx, &mut messages, policy).await.unwrap();
    assert_eq!(result, "done");
    let tool_results: Vec<_> = messages
        .iter()
        .filter(|m| m.role == ModelRole::Tool)
        .collect();
    assert_eq!(tool_results.len(), 2);
}

#[tokio::test]
async fn shared_tool_calls_overlap_within_one_model_batch() {
    let tempdir = tempfile::tempdir().unwrap();
    let mut ctx = build_test_ctx(tempdir.path().to_path_buf());
    let probe = ParallelProbe::default();
    Arc::get_mut(&mut ctx.tool_executor)
        .unwrap()
        .register_tool(Arc::new(SleepingTool::shared(
            "shared_probe",
            probe.clone(),
        )));
    let mut messages = Vec::new();
    let mut run_state = AgentRunState::default();
    let policy = crate::harness::policy_for_profile(
        &crate::config::HarnessConfig::default(),
        crate::config::HarnessProfile::Small,
    );

    let output = ModelTurnOutput {
        text: String::new(),
        thinking: String::new(),
        tool_calls: vec![
            ToolInvocation {
                id: "call-1".to_string(),
                tool_name: "shared_probe".to_string(),
                input: json!({}),
            },
            ToolInvocation {
                id: "call-2".to_string(),
                tool_name: "shared_probe".to_string(),
                input: json!({}),
            },
        ],
        harness_stop: None,
    };

    assert!(
        handle_tool_calls(&ctx, &mut messages, &mut run_state, policy, output)
            .await
            .is_none()
    );
    assert_eq!(probe.max_active(), 2);
}

#[tokio::test]
async fn exclusive_tool_call_serializes_a_model_batch() {
    let tempdir = tempfile::tempdir().unwrap();
    let mut ctx = build_test_ctx(tempdir.path().to_path_buf());
    let probe = ParallelProbe::default();
    let executor = Arc::get_mut(&mut ctx.tool_executor).unwrap();
    executor.register_tool(Arc::new(SleepingTool::shared(
        "shared_probe",
        probe.clone(),
    )));
    executor.register_tool(Arc::new(SleepingTool::exclusive(
        "exclusive_probe",
        probe.clone(),
    )));
    let mut messages = Vec::new();
    let mut run_state = AgentRunState::default();
    let policy = crate::harness::policy_for_profile(
        &crate::config::HarnessConfig::default(),
        crate::config::HarnessProfile::Small,
    );

    let output = ModelTurnOutput {
        text: String::new(),
        thinking: String::new(),
        tool_calls: vec![
            ToolInvocation {
                id: "call-1".to_string(),
                tool_name: "shared_probe".to_string(),
                input: json!({}),
            },
            ToolInvocation {
                id: "call-2".to_string(),
                tool_name: "exclusive_probe".to_string(),
                input: json!({}),
            },
            ToolInvocation {
                id: "call-3".to_string(),
                tool_name: "shared_probe".to_string(),
                input: json!({}),
            },
        ],
        harness_stop: None,
    };

    assert!(
        handle_tool_calls(&ctx, &mut messages, &mut run_state, policy, output)
            .await
            .is_none()
    );
    assert_eq!(probe.max_active(), 1);
}

#[tokio::test]
async fn degenerate_streaming_output_stops_the_turn() {
    let tempdir = tempfile::tempdir().unwrap();
    let mut ctx = build_test_ctx(tempdir.path().to_path_buf());
    ctx.model_provider = Arc::new(std::sync::RwLock::new(Arc::new(DegenerateOutputProvider)));
    let mut messages = vec![ModelMessage::user("repeat")];
    let policy = crate::harness::policy_for_profile(
        &crate::config::HarnessConfig::default(),
        crate::config::HarnessProfile::Small,
    );

    let result = run_turn(&ctx, &mut messages, policy).await.unwrap();

    assert!(result.contains("degenerate_model_output"));
    assert!(
        messages
            .iter()
            .any(|message| message.role == ModelRole::Assistant
                && message.content.contains("degenerate_model_output"))
    );
}

#[tokio::test]
async fn system_prompt_includes_session_memory_and_rebuild_context() {
    let tempdir = tempfile::tempdir().unwrap();
    let requests = Arc::new(Mutex::new(Vec::new()));
    let mut ctx = build_test_ctx(tempdir.path().to_path_buf());
    ctx.model_provider = Arc::new(std::sync::RwLock::new(Arc::new(CapturingProvider {
        requests: requests.clone(),
    })));
    ctx.memory_injection = Some("Previous session context: durable session memory".to_string());
    {
        let mut state = ctx.compact_state.lock().await;
        state.rebuild_context =
            Some("=== SESSION CHECKPOINT ===\nDurable rebuild state".to_string());
    }

    let mut messages = vec![ModelMessage::user("continue")];
    let policy = crate::harness::policy_for_profile(
        &crate::config::HarnessConfig::default(),
        crate::config::HarnessProfile::Small,
    );

    let _ = run_turn(&ctx, &mut messages, policy).await.unwrap();

    let requests = requests.lock().unwrap();
    let system = requests[0]
        .messages
        .iter()
        .find(|msg| msg.role == ModelRole::System)
        .expect("system message");
    assert!(system.content.contains("durable session memory"));
    assert!(system.content.contains("Durable rebuild state"));
}

#[tokio::test]
async fn history_sync_continues_after_messages_are_shortened() {
    let tempdir = tempfile::tempdir().unwrap();
    let project_dir = tempdir.path().join("project");
    let data_dir = tempdir.path().join("data");
    std::fs::create_dir_all(&project_dir).unwrap();

    let mut ctx = build_test_ctx(project_dir.clone());
    ctx.data_dir = data_dir.clone();
    ctx.session_id = "history-shortened".to_string();

    let mut messages = vec![
        ModelMessage::system("base prompt"),
        ModelMessage::user("first user"),
        ModelMessage::assistant("first assistant"),
    ];
    sync_messages_to_history(&ctx, &messages).await.unwrap();

    let manager = crate::memory::MemoryManager::new(
        project_dir.clone(),
        data_dir.clone(),
        &ctx.active_config().memory,
    )
    .unwrap();
    assert_eq!(
        manager
            .history
            .get_event_count(&ctx.session_id, "message")
            .unwrap(),
        3
    );

    messages.clear();
    messages.push(ModelMessage::system("rebuilt prompt"));
    messages.push(ModelMessage::user("post rebuild user"));
    sync_messages_to_history(&ctx, &messages).await.unwrap();

    assert_eq!(
        manager
            .history
            .get_event_count(&ctx.session_id, "message")
            .unwrap(),
        5
    );
}

#[tokio::test]
async fn malformed_tool_arguments_stop_the_turn() {
    let tempdir = tempfile::tempdir().unwrap();
    let security_policy = SecurityPolicy::new(
        tempdir.path().to_path_buf(),
        tempdir.path().to_path_buf(),
        SecurityConfig::default(),
    )
    .unwrap();
    let executor = ToolExecutor::new(security_policy);
    let provider = Arc::new(MalformedToolProvider {
        calls: Mutex::new(0),
    });

    let ctx = TurnContext {
        model_provider: Arc::new(std::sync::RwLock::new(provider.clone())),
        tool_executor: Arc::new(executor),
        project_dir: tempdir.path().to_path_buf(),
        data_dir: tempdir.path().join("data"),
        model_name: Arc::new(std::sync::RwLock::new("gpt-4".to_string())),
        event_tx: None,
        approval_resolver: crate::runtime::ApprovalResolver::new_for_test(),
        question_resolver: crate::runtime::QuestionResolver::new_for_test(),
        compact_state: Arc::new(tokio::sync::Mutex::new(CompactState::new(128_000))),
        harness_config: crate::config::HarnessConfig::default(),
        include_tool_prompt_manifest: false,
        context_packets: Arc::new(std::sync::Mutex::new(Vec::new())),
        active_skills: Arc::new(std::sync::Mutex::new(Vec::new())),
        prompt_cache: Arc::new(crate::prompt::PromptCache::new()),
        components: crate::RuntimeComponents::default(),
        cancel_token: CancelToken::new(),
        config: Arc::new(std::sync::RwLock::new(crate::config::NaviConfig::default())),
        memory_injection: None,
        compaction_provider: None,
        compaction_model_name: None,
        session_id: "test-session".to_string(),
        allowed_tool_names: None,
    };
    let policy = crate::harness::policy_for_profile(
        &crate::config::HarnessConfig {
            max_consecutive_malformed_arguments: 2,
            ..crate::config::HarnessConfig::default()
        },
        crate::config::HarnessProfile::Small,
    );
    let mut messages = vec![];

    let result = run_turn(&ctx, &mut messages, policy).await.unwrap();

    assert!(result.contains("consecutive_malformed_arguments"));
    assert_eq!(*provider.calls.lock().unwrap(), 2);
}

#[test]
fn think_tag_splitter_moves_inline_thinking_out_of_text() {
    let mut splitter = ThinkTagSplitter::default();

    assert_eq!(
        splitter.push("hello <think>hidden</think> world"),
        vec![
            SplitTextPart::Text("hello ".to_string()),
            SplitTextPart::Thinking("hidden".to_string()),
            SplitTextPart::Text(" world".to_string()),
        ]
    );
}

#[test]
fn think_tag_splitter_handles_tags_split_across_chunks() {
    let mut splitter = ThinkTagSplitter::default();
    let mut parts = Vec::new();

    parts.extend(splitter.push("<thi"));
    parts.extend(splitter.push("nk>hidden</thi"));
    parts.extend(splitter.push("nk>visible"));

    assert_eq!(
        parts,
        vec![
            SplitTextPart::Thinking("hidden".to_string()),
            SplitTextPart::Text("visible".to_string()),
        ]
    );
}

#[test]
fn think_tag_splitter_drops_partial_open_tag_on_drain() {
    let mut splitter = ThinkTagSplitter::default();

    assert!(splitter.push("<thi").is_empty());
    assert!(splitter.drain_pending().is_empty());
}

/// Helper to build a TurnContext pointing at a given project directory.
fn build_test_ctx(project_dir: PathBuf) -> TurnContext {
    let security_policy = SecurityPolicy::new(
        project_dir.clone(),
        project_dir.clone(),
        SecurityConfig::default(),
    )
    .unwrap();
    let mut executor = ToolExecutor::new(security_policy);
    executor.register_tool(Arc::new(MockTool));

    TurnContext {
        model_provider: Arc::new(std::sync::RwLock::new(Arc::new(MockProvider {
            calls: Mutex::new(0),
        }))),
        tool_executor: Arc::new(executor),
        data_dir: project_dir.join("data"),
        project_dir,
        model_name: Arc::new(std::sync::RwLock::new("gpt-4".to_string())),
        event_tx: None,
        approval_resolver: crate::runtime::ApprovalResolver::new_for_test(),
        question_resolver: crate::runtime::QuestionResolver::new_for_test(),
        compact_state: Arc::new(tokio::sync::Mutex::new(CompactState::new(128_000))),
        harness_config: crate::config::HarnessConfig::default(),
        include_tool_prompt_manifest: false,
        context_packets: Arc::new(std::sync::Mutex::new(Vec::new())),
        active_skills: Arc::new(std::sync::Mutex::new(Vec::new())),
        prompt_cache: Arc::new(crate::prompt::PromptCache::new()),
        components: crate::RuntimeComponents::default(),
        cancel_token: CancelToken::new(),
        config: Arc::new(std::sync::RwLock::new(crate::config::NaviConfig::default())),
        memory_injection: None,
        compaction_provider: None,
        compaction_model_name: None,
        session_id: "test-session".to_string(),
        allowed_tool_names: None,
    }
}

#[tokio::test]
async fn test_ensure_system_prompt_reads_agents_md() {
    let tempdir = tempfile::tempdir().unwrap();
    std::fs::write(
        tempdir.path().join("AGENTS.md"),
        "Custom project instructions",
    )
    .unwrap();
    let ctx = build_test_ctx(tempdir.path().to_path_buf());

    let mut messages = vec![];
    ensure_system_prompt(&ctx, &mut messages).await;

    assert_eq!(messages.len(), 1);
    assert_eq!(messages[0].role, ModelRole::System);
    assert!(
        messages[0].content.contains("Custom project instructions"),
        "system prompt should include AGENTS.md content"
    );
    assert!(
        messages[0]
            .content
            .contains("AGENTS.md / Project Instructions"),
        "system prompt should have the AGENTS.md section header"
    );
}

#[tokio::test]
async fn test_ensure_system_prompt_falls_back_without_agents_md() {
    let tempdir = tempfile::tempdir().unwrap();
    // No AGENTS.md written — should use the default fallback.
    let ctx = build_test_ctx(tempdir.path().to_path_buf());

    let mut messages = vec![];
    ensure_system_prompt(&ctx, &mut messages).await;

    assert_eq!(messages.len(), 1);
    assert_eq!(messages[0].role, ModelRole::System);
    assert!(
        messages[0]
            .content
            .contains("Default NAVI base instructions"),
        "system prompt should fall back to default instructions when AGENTS.md is absent"
    );
}

#[tokio::test]
async fn test_ensure_system_prompt_updates_existing_system_message() {
    let tempdir = tempfile::tempdir().unwrap();
    let ctx = build_test_ctx(tempdir.path().to_path_buf());

    let mut messages = vec![ModelMessage::system("stale prompt".to_string())];
    ensure_system_prompt(&ctx, &mut messages).await;

    // Should replace the existing system message, not add a second one.
    assert_eq!(messages.len(), 1);
    assert_eq!(messages[0].role, ModelRole::System);
    assert!(
        messages[0]
            .content
            .contains("Default NAVI base instructions"),
        "existing system message should be replaced"
    );
    assert!(
        !messages[0].content.contains("stale prompt"),
        "old system message content should be gone"
    );
}

#[tokio::test]
async fn test_ensure_system_prompt_inserts_before_non_system_message() {
    let tempdir = tempfile::tempdir().unwrap();
    let ctx = build_test_ctx(tempdir.path().to_path_buf());

    let mut messages = vec![ModelMessage::user("hello".to_string())];
    ensure_system_prompt(&ctx, &mut messages).await;

    assert_eq!(messages.len(), 2);
    assert_eq!(messages[0].role, ModelRole::System);
    assert_eq!(messages[1].role, ModelRole::User);
    assert_eq!(messages[1].content, "hello");
}

#[tokio::test]
async fn test_ensure_system_prompt_uses_loaded_config_profile() {
    let tempdir = tempfile::tempdir().unwrap();
    let ctx = build_test_ctx(tempdir.path().to_path_buf());
    let mut config = crate::config::NaviConfig::default();
    config.harness.profile = crate::config::HarnessProfile::Small;
    *ctx.config.write().unwrap() = config;

    let mut messages = vec![];
    ensure_system_prompt(&ctx, &mut messages).await;

    assert!(
        messages[0].content.contains("Harness profile: small"),
        "system prompt should reflect the loaded_config harness profile, got: {}",
        messages[0].content
    );
}

#[test]
fn test_resolve_approval_delegates_to_resolver() {
    let tempdir = tempfile::tempdir().unwrap();
    let ctx = build_test_ctx(tempdir.path().to_path_buf());

    let mut rx = ctx.approval_resolver.register("approval-1".to_string());

    let decision = crate::event::ApprovalDecision::Approved {
        id: "approval-1".to_string(),
    };
    let resolved = ctx.resolve_approval(decision);
    assert!(
        resolved,
        "resolve_approval should return true for a registered id"
    );

    let received = rx.try_recv().expect("receiver should have the decision");
    assert!(
        matches!(received, crate::event::ApprovalDecision::Approved { id } if id == "approval-1"),
        "receiver should get the approved decision"
    );
}

#[test]
fn test_resolve_approval_returns_false_for_unknown_id() {
    let tempdir = tempfile::tempdir().unwrap();
    let ctx = build_test_ctx(tempdir.path().to_path_buf());

    let decision = crate::event::ApprovalDecision::Approved {
        id: "unknown-id".to_string(),
    };
    let resolved = ctx.resolve_approval(decision);
    assert!(
        !resolved,
        "resolve_approval should return false when no pending approval matches"
    );
}

#[test]
fn test_resolve_approval_denied_delivers_denial() {
    let tempdir = tempfile::tempdir().unwrap();
    let ctx = build_test_ctx(tempdir.path().to_path_buf());

    let mut rx = ctx.approval_resolver.register("approval-2".to_string());

    let decision = crate::event::ApprovalDecision::Denied {
        id: "approval-2".to_string(),
    };
    let resolved = ctx.resolve_approval(decision);
    assert!(resolved);

    let received = rx.try_recv().expect("receiver should have the decision");
    assert!(
        matches!(received, crate::event::ApprovalDecision::Denied { id } if id == "approval-2"),
        "receiver should get the denied decision"
    );
}

#[test]
fn test_cancellation_token_not_requested_by_default() {
    let token = CancelToken::new();
    assert!(!token.is_requested());
}

#[test]
fn test_cancellation_token_reflects_cancel() {
    let token = CancelToken::new();
    token.cancel();
    assert!(token.is_requested());
}