greentic-aw-runtime 1.2.2

Enterprise Agentic Worker runtime — Plan-Act-Observe loop, Redis state, tool dispatch via greentic-ext-runtime
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
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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
//! Scripted-LLM unit tests for the Plan-Act-Observe loop.
//! Uses test-mock backends — no Redis, no network.

#![cfg(feature = "test-mock")]

use std::sync::Arc;
use std::time::Duration;

use greentic_aw_runtime::config::{MemoryProviderRef, MemorySettings};
use greentic_aw_runtime::cost::MockTokenMeter;
use greentic_aw_runtime::error::{AgentError, TerminationReason};
use greentic_aw_runtime::llm::LlmResponse;
use greentic_aw_runtime::long_term::RecalledFact;
use greentic_aw_runtime::mock::{
    MockAgentStateStore, MockConfigProvider, MockLlmBackend, MockLongTermMemory, MockTelemetry,
    NoopToolLedger,
};
use greentic_aw_runtime::state::ToolCallRecord;
use greentic_aw_runtime::tenant::TenantContext;
use greentic_aw_runtime::{
    AgentConfig, AgentInput, AgentLimits, AgentRuntime, AgentStep, LlmProviderRef, ToolRef,
};

fn cfg(max_iter: u32, timeout_ms: u64, tools: Vec<ToolRef>, cap: Option<u32>) -> AgentConfig {
    AgentConfig {
        agent_id: "a".into(),
        system_prompt: "sys".into(),
        tools,
        guardrails: vec![],
        llm: LlmProviderRef {
            provider: "mock".into(),
            model: "m".into(),
            credential_ref: None,
        },
        limits: AgentLimits {
            max_iter,
            timeout: Duration::from_millis(timeout_ms),
            daily_token_cap_per_tenant: cap,
            ..AgentLimits::default()
        },
        memory: None,
        knowledge: None,
        conversational: false,
        opening_message: None,
        on_text_while_parked: Default::default(),
    }
}

fn final_reply(text: &str) -> LlmResponse {
    LlmResponse {
        content: Some(text.into()),
        tool_calls: vec![],
        tokens_in: 5,
        tokens_out: 5,
    }
}

fn tool_call(call_id: &str, ext: &str, tool: &str) -> LlmResponse {
    LlmResponse {
        content: None,
        tool_calls: vec![ToolCallRecord {
            call_id: call_id.into(),
            extension_id: ext.into(),
            tool_name: tool.into(),
            args: serde_json::json!({}),
        }],
        tokens_in: 5,
        tokens_out: 5,
    }
}

fn build_runtime(
    llm_script: Vec<Result<LlmResponse, greentic_aw_runtime::error::LlmError>>,
    cfg_inner: AgentConfig,
    token_used: u64,
) -> (AgentRuntime, Arc<MockTelemetry>, TenantContext) {
    let llm = Arc::new(MockLlmBackend::new(llm_script));
    let store = Arc::new(MockAgentStateStore::new());
    let telemetry = Arc::new(MockTelemetry::new());
    let cp = MockConfigProvider::new();
    let tc = TenantContext::new("acme", "prod");
    cp.insert(&tc, "a", cfg_inner);
    let cp = Arc::new(cp);
    let token_meter = Arc::new(MockTokenMeter::new(token_used));
    let ledger = Arc::new(NoopToolLedger);
    let ext = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
    let rt = AgentRuntime::new(
        cp,
        store,
        ext,
        llm,
        telemetry.clone(),
        token_meter,
        ledger,
        None,
    );
    (rt, telemetry, tc)
}

#[tokio::test]
async fn happy_path_one_iteration() {
    let (rt, tel, tc) = build_runtime(vec![Ok(final_reply("hi"))], cfg(8, 60_000, vec![], None), 0);
    let out = rt
        .step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "hello".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(out.reply, "hi");
    assert_eq!(out.terminated_by, TerminationReason::FinalReply);
    assert_eq!(tel.recorded.lock().unwrap()[0].iterations, 1);
}

#[tokio::test]
async fn max_iterations_terminates_loop() {
    // LLM keeps emitting tool calls for a NON-allowed tool (empty allow-list)
    // → each blocked → loop exhausts at max_iter=3.
    let script = vec![
        Ok(tool_call("c1", "http", "fetch")),
        Ok(tool_call("c2", "http", "fetch")),
        Ok(tool_call("c3", "http", "fetch")),
    ];
    let (rt, tel, tc) = build_runtime(script, cfg(3, 60_000, vec![], None), 0);
    let out = rt
        .step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "go".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(out.terminated_by, TerminationReason::MaxIterations);
    assert_eq!(tel.recorded.lock().unwrap()[0].iterations, 3);
}

#[tokio::test]
async fn timeout_terminates_loop() {
    // timeout=0ms → the iteration-start timeout check fires immediately.
    let (rt, tel, tc) = build_runtime(vec![Ok(final_reply("never"))], cfg(8, 0, vec![], None), 0);
    let out = rt
        .step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "x".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(out.terminated_by, TerminationReason::Timeout);
    assert_eq!(tel.recorded.lock().unwrap()[0].iterations, 1);
}

#[tokio::test]
async fn tool_not_allowed_becomes_observation_then_reply() {
    // First response: tool call for a tool NOT in the (empty) allow-list →
    // blocked observation. Second response: final reply.
    let script = vec![
        Ok(tool_call("c1", "http", "fetch")),
        Ok(final_reply("ok done")),
    ];
    let (rt, _tel, tc) = build_runtime(script, cfg(4, 60_000, vec![], None), 0);
    let out = rt
        .step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "go".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(out.terminated_by, TerminationReason::FinalReply);
    assert_eq!(out.reply, "ok done");
    assert!(
        out.trail
            .iter()
            .any(|s| matches!(s, AgentStep::ToolCallBlocked { .. }))
    );
}

#[tokio::test]
async fn tool_dispatch_error_becomes_observation_then_reply() {
    // Tool IS allowed, but for_test ExtensionRuntime has no extensions →
    // invoke_tool returns NotFound → dispatch error becomes an observation
    // (spec §6), loop continues, second response is the final reply.
    let allowed = vec![ToolRef {
        extension_id: "http".into(),
        tool_name: "fetch".into(),
        description: None,
        input_schema: None,
        usage_note: None,
    }];
    let script = vec![
        Ok(tool_call("c1", "http", "fetch")),
        Ok(final_reply("recovered")),
    ];
    let (rt, _tel, tc) = build_runtime(script, cfg(4, 60_000, allowed, None), 0);
    let out = rt
        .step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "go".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(out.terminated_by, TerminationReason::FinalReply);
    assert_eq!(out.reply, "recovered");
    // The failed tool call appears in the trail as a ToolCall with an error result.
    assert!(
        out.trail
            .iter()
            .any(|s| matches!(s, AgentStep::ToolCall { .. }))
    );
}

#[tokio::test]
async fn tool_call_trail_carries_args_and_duration() {
    // The trail records the model's tool arguments (input) and a wall-clock
    // duration alongside each tool call, so a caller (e.g. the demo trace) can
    // show WHAT was requested and how long it took — not just the tool name.
    let allowed = vec![ToolRef {
        extension_id: "http".into(),
        tool_name: "fetch".into(),
        description: None,
        input_schema: None,
        usage_note: None,
    }];
    let sent_args = serde_json::json!({ "url": "https://example.com", "method": "GET" });
    let script = vec![
        Ok(tool_call_with_args(
            "c1",
            "http",
            "fetch",
            sent_args.clone(),
        )),
        Ok(final_reply("done")),
    ];
    let (rt, _tel, tc) = build_runtime(script, cfg(4, 60_000, allowed, None), 0);
    let out = rt
        .step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "go".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    let (args, _duration_ms) = out
        .trail
        .iter()
        .find_map(|s| match s {
            AgentStep::ToolCall {
                call_id,
                args,
                duration_ms,
                ..
            } if call_id == "c1" => Some((args.clone(), *duration_ms)),
            _ => None,
        })
        .expect("tool call c1 recorded in trail");
    assert_eq!(
        args, sent_args,
        "trail carries the model's tool args verbatim"
    );
}

#[tokio::test]
async fn token_budget_exceeded_returns_error() {
    // Daily cap 10, already-used 100 → gate trips before any LLM call.
    let (rt, _tel, tc) = build_runtime(
        vec![Ok(final_reply("hi"))],
        cfg(8, 60_000, vec![], Some(10)),
        100,
    );
    let err = rt
        .step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "x".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap_err();
    assert!(matches!(err, AgentError::TokenBudgetExceeded));
}

#[tokio::test]
async fn mixed_text_and_tool_calls_executes_tool_discards_text() {
    // First response: BOTH content and a tool_call (allowed). tool_calls win:
    // content is discarded, the tool dispatches (fails → observation), loop
    // continues. Second response: the real final reply.
    let allowed = vec![ToolRef {
        extension_id: "http".into(),
        tool_name: "fetch".into(),
        description: None,
        input_schema: None,
        usage_note: None,
    }];
    let mixed = LlmResponse {
        content: Some("internal reasoning".into()),
        tool_calls: vec![ToolCallRecord {
            call_id: "c1".into(),
            extension_id: "http".into(),
            tool_name: "fetch".into(),
            args: serde_json::json!({}),
        }],
        tokens_in: 5,
        tokens_out: 5,
    };
    let script = vec![Ok(mixed), Ok(final_reply("the real answer"))];
    let (rt, _tel, tc) = build_runtime(script, cfg(4, 60_000, allowed, None), 0);
    let out = rt
        .step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "go".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(out.reply, "the real answer");
    assert_ne!(out.reply, "internal reasoning");
}

#[tokio::test]
async fn llm_provider_unavailable_after_retries_returns_error() {
    use greentic_aw_runtime::error::LlmError;
    use greentic_aw_runtime::llm::LlmBackend;

    // Scripted backend returns ServiceUnavailable 3 times; the loop applies
    // the agent's `llm_retry_attempts` (default 3) itself, exhausts all
    // retries → loop returns LlmProviderUnavailable.
    let inner = MockLlmBackend::new(vec![
        Err(LlmError::ServiceUnavailable),
        Err(LlmError::ServiceUnavailable),
        Err(LlmError::ServiceUnavailable),
    ]);
    let llm: Arc<dyn LlmBackend> = Arc::new(inner);

    let store = Arc::new(MockAgentStateStore::new());
    let telemetry = Arc::new(MockTelemetry::new());
    let cp = MockConfigProvider::new();
    let tc = TenantContext::new("acme", "prod");
    let mut config = cfg(8, 60_000, vec![], None);
    config.limits.llm_retry_backoff = Duration::from_millis(1);
    cp.insert(&tc, "a", config);
    let cp = Arc::new(cp);
    let token_meter = Arc::new(MockTokenMeter::new(0));
    let ledger = Arc::new(NoopToolLedger);
    let ext = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
    let rt = AgentRuntime::new(cp, store, ext, llm, telemetry, token_meter, ledger, None);

    let err = rt
        .step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "x".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap_err();
    assert!(matches!(err, AgentError::LlmProviderUnavailable));
}

fn fact(text: &str) -> RecalledFact {
    RecalledFact {
        fact: text.into(),
        relation: "about".into(),
        valid_at: None,
        invalid_at: None,
        source_episode_ids: vec![],
    }
}

fn cfg_with_long_term(max_iter: u32) -> AgentConfig {
    let mut c = cfg(max_iter, 60_000, vec![], None);
    c.memory = Some(MemorySettings {
        short_term: None,
        long_term: Some(MemoryProviderRef {
            provider: "provider.memory.chronicle".into(),
            capability: "cap://memory/long-term".into(),
            params: serde_json::Map::new(),
            credential_ref: None,
        }),
    });
    c
}

/// Build a runtime with a long-term backend attached, returning the captured
/// LLM mock (for prompt assertions) and the tenant.
fn build_lt_runtime(
    llm_script: Vec<Result<LlmResponse, greentic_aw_runtime::error::LlmError>>,
    cfg_inner: AgentConfig,
    mem: Arc<MockLongTermMemory>,
) -> (AgentRuntime, Arc<MockLlmBackend>, TenantContext) {
    let llm = Arc::new(MockLlmBackend::new(llm_script));
    let cp = MockConfigProvider::new();
    let tc = TenantContext::new("acme", "prod");
    cp.insert(&tc, "a", cfg_inner);
    let ext = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
    let rt = AgentRuntime::new(
        Arc::new(cp),
        Arc::new(MockAgentStateStore::new()),
        ext,
        llm.clone(),
        Arc::new(MockTelemetry::new()),
        Arc::new(MockTokenMeter::new(0)),
        Arc::new(NoopToolLedger),
        None,
    )
    .with_long_term_memory(mem);
    (rt, llm, tc)
}

#[tokio::test]
async fn long_term_facts_are_injected_into_system_prompt() {
    let mem = Arc::new(MockLongTermMemory::new(vec![fact(
        "Alice prefers dark mode",
    )]));
    let (rt, llm, tc) = build_lt_runtime(vec![Ok(final_reply("hi"))], cfg_with_long_term(8), mem);
    rt.step(
        tc,
        "s",
        "a",
        AgentInput {
            text: "what do I like?".into(),
            conversational: false,
            resume_payload: None,
            ..Default::default()
        },
    )
    .await
    .unwrap();
    let prompts = llm.seen_system_prompts.lock().unwrap();
    assert!(prompts[0].contains("<long_term_memory>"));
    assert!(prompts[0].contains("Alice prefers dark mode"));
}

#[tokio::test]
async fn no_injection_when_long_term_disabled() {
    // Provider attached but the agent has no long-term binding -> inactive.
    let mem = Arc::new(MockLongTermMemory::new(vec![fact("should not appear")]));
    let (rt, llm, tc) = build_lt_runtime(
        vec![Ok(final_reply("hi"))],
        cfg(8, 60_000, vec![], None),
        mem,
    );
    rt.step(
        tc,
        "s",
        "a",
        AgentInput {
            text: "hi".into(),
            conversational: false,
            resume_payload: None,
            ..Default::default()
        },
    )
    .await
    .unwrap();
    let prompts = llm.seen_system_prompts.lock().unwrap();
    assert_eq!(prompts[0], "sys");
    assert!(!prompts[0].contains("<long_term_memory>"));
}

#[tokio::test]
async fn turn_is_ingested_as_episode_in_background() {
    let mem = Arc::new(MockLongTermMemory::new(vec![]));
    let (rt, _llm, tc) = build_lt_runtime(
        vec![Ok(final_reply("you like dark mode"))],
        cfg_with_long_term(8),
        mem.clone(),
    );
    let out = rt
        .step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "what do I like?".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(out.reply, "you like dark mode");

    // Ingest is fire-and-forget; await it deterministically.
    mem.wait_for_ingests(1).await;
    let episodes = mem.ingested();
    assert_eq!(episodes.len(), 1);
    assert!(episodes[0].body.contains("what do I like?"));
    assert!(episodes[0].body.contains("you like dark mode"));
}

#[tokio::test]
async fn no_ingest_when_long_term_disabled() {
    let mem = Arc::new(MockLongTermMemory::new(vec![]));
    let (rt, _llm, tc) = build_lt_runtime(
        vec![Ok(final_reply("hi"))],
        cfg(8, 60_000, vec![], None),
        mem.clone(),
    );
    rt.step(
        tc,
        "s",
        "a",
        AgentInput {
            text: "hi".into(),
            conversational: false,
            resume_payload: None,
            ..Default::default()
        },
    )
    .await
    .unwrap();
    // Give any erroneously-spawned task a chance to run, then assert none did.
    tokio::task::yield_now().await;
    assert!(mem.ingested().is_empty());
}

#[tokio::test]
async fn recall_memory_tool_advertised_when_active() {
    let mem = Arc::new(MockLongTermMemory::new(vec![]));
    let (rt, llm, tc) = build_lt_runtime(vec![Ok(final_reply("hi"))], cfg_with_long_term(8), mem);
    rt.step(
        tc,
        "s",
        "a",
        AgentInput {
            text: "hi".into(),
            conversational: false,
            resume_payload: None,
            ..Default::default()
        },
    )
    .await
    .unwrap();
    let tools = llm.seen_tool_names.lock().unwrap();
    assert!(tools[0].iter().any(|n| n == "recall_memory"));
}

#[tokio::test]
async fn recall_memory_tool_absent_when_disabled() {
    let mem = Arc::new(MockLongTermMemory::new(vec![]));
    let (rt, llm, tc) = build_lt_runtime(
        vec![Ok(final_reply("hi"))],
        cfg(8, 60_000, vec![], None),
        mem,
    );
    rt.step(
        tc,
        "s",
        "a",
        AgentInput {
            text: "hi".into(),
            conversational: false,
            resume_payload: None,
            ..Default::default()
        },
    )
    .await
    .unwrap();
    let tools = llm.seen_tool_names.lock().unwrap();
    assert!(!tools[0].iter().any(|n| n == "recall_memory"));
}

#[tokio::test]
async fn recall_memory_call_is_handled_host_side() {
    // First response: a recall_memory tool call (host built-in). Second: reply.
    let mem = Arc::new(MockLongTermMemory::new(vec![fact(
        "Alice prefers dark mode",
    )]));
    let (rt, _llm, tc) = build_lt_runtime(
        vec![
            Ok(tool_call("c1", "host", "recall_memory")),
            Ok(final_reply("you prefer dark mode")),
        ],
        cfg_with_long_term(8),
        mem,
    );
    let out = rt
        .step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "what do I like?".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(out.reply, "you prefer dark mode");
    // The recall was handled host-side (not dispatched to the ext runtime, which
    // would have produced a NotFound error), so the tool result carries the fact.
    let result = out
        .trail
        .iter()
        .find_map(|s| match s {
            AgentStep::ToolCall { name, result, .. } if name == "recall_memory" => {
                Some(result.clone())
            }
            _ => None,
        })
        .expect("recall_memory tool call recorded in trail");
    assert!(result.to_string().contains("Alice prefers dark mode"));
}

// ---------------------------------------------------------------------------
// Short-term memory (working-memory) loop tests
// ---------------------------------------------------------------------------

/// Build a tool-call `LlmResponse` with explicit args (for `remember`/`recall`).
fn tool_call_with_args(
    call_id: &str,
    ext: &str,
    tool: &str,
    args: serde_json::Value,
) -> LlmResponse {
    LlmResponse {
        content: None,
        tool_calls: vec![ToolCallRecord {
            call_id: call_id.into(),
            extension_id: ext.into(),
            tool_name: tool.into(),
            args,
        }],
        tokens_in: 5,
        tokens_out: 5,
    }
}

/// Return an `AgentConfig` with `memory.short_term` set so `short_term_active()` is true.
fn cfg_with_short_term(max_iter: u32) -> AgentConfig {
    let mut c = cfg(max_iter, 60_000, vec![], None);
    c.memory = Some(MemorySettings {
        short_term: Some(MemoryProviderRef {
            provider: "in-memory".into(),
            capability: "cap://memory/short-term".into(),
            params: serde_json::Map::new(),
            credential_ref: None,
        }),
        long_term: None,
    });
    c
}

/// Build a runtime with the in-memory short-term provider attached.
fn build_st_runtime(
    llm_script: Vec<Result<LlmResponse, greentic_aw_runtime::error::LlmError>>,
    cfg_inner: AgentConfig,
) -> (AgentRuntime, Arc<MockLlmBackend>, TenantContext) {
    let llm = Arc::new(MockLlmBackend::new(llm_script));
    let cp = MockConfigProvider::new();
    let tc = TenantContext::new("acme", "prod");
    cp.insert(&tc, "a", cfg_inner);
    let ext = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
    let rt = AgentRuntime::new(
        Arc::new(cp),
        Arc::new(MockAgentStateStore::new()),
        ext,
        llm.clone(),
        Arc::new(MockTelemetry::new()),
        Arc::new(MockTokenMeter::new(0)),
        Arc::new(NoopToolLedger),
        None,
    )
    .with_short_term_memory(Arc::new(
        greentic_aw_runtime::memory::InMemoryMemoryProvider::new(),
    ));
    (rt, llm, tc)
}

#[tokio::test]
async fn remember_and_recall_tools_advertised_when_active() {
    // Config has memory.short_term set and the provider is attached → the LLM
    // request must include both "remember" and "recall" tool names.
    let (rt, llm, tc) = build_st_runtime(vec![Ok(final_reply("hi"))], cfg_with_short_term(8));
    rt.step(
        tc,
        "s",
        "a",
        AgentInput {
            text: "hi".into(),
            conversational: false,
            resume_payload: None,
            ..Default::default()
        },
    )
    .await
    .unwrap();
    let tools = llm.seen_tool_names.lock().unwrap();
    assert!(
        tools[0].iter().any(|n| n == "remember"),
        "expected 'remember' in tool list: {:?}",
        tools[0]
    );
    assert!(
        tools[0].iter().any(|n| n == "recall"),
        "expected 'recall' in tool list: {:?}",
        tools[0]
    );
}

#[tokio::test]
async fn short_term_tools_absent_when_disabled() {
    // Provider attached but config has no memory.short_term binding → inactive;
    // neither "remember" nor "recall" should be advertised.
    let (rt, llm, tc) = build_st_runtime(
        vec![Ok(final_reply("hi"))],
        cfg(8, 60_000, vec![], None), // no memory binding
    );
    rt.step(
        tc,
        "s",
        "a",
        AgentInput {
            text: "hi".into(),
            conversational: false,
            resume_payload: None,
            ..Default::default()
        },
    )
    .await
    .unwrap();
    let tools = llm.seen_tool_names.lock().unwrap();
    assert!(
        !tools[0].iter().any(|n| n == "remember"),
        "unexpected 'remember' in tool list: {:?}",
        tools[0]
    );
    assert!(
        !tools[0].iter().any(|n| n == "recall"),
        "unexpected 'recall' in tool list: {:?}",
        tools[0]
    );
}

#[tokio::test]
async fn remember_then_recall_roundtrips_via_tools() {
    // Turn 1: LLM emits `remember {key:"fav", value:"blue"}`.
    // Turn 2: LLM emits `recall {key:"fav"}`.
    // Turn 3: LLM gives a final reply.
    // Assert the recall tool result message content is `{"value":"blue"}`.
    let (rt, _llm, tc) = build_st_runtime(
        vec![
            Ok(tool_call_with_args(
                "c1",
                "host",
                "remember",
                serde_json::json!({ "key": "fav", "value": "blue" }),
            )),
            Ok(tool_call_with_args(
                "c2",
                "host",
                "recall",
                serde_json::json!({ "key": "fav" }),
            )),
            Ok(final_reply("your fav is blue")),
        ],
        cfg_with_short_term(8),
    );
    let out = rt
        .step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "what is my fav color?".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(out.reply, "your fav is blue");
    // Find the recall result in the trail and confirm the stored value came back.
    let recall_result = out
        .trail
        .iter()
        .find_map(|s| match s {
            AgentStep::ToolCall { name, result, .. } if name == "recall" => Some(result.clone()),
            _ => None,
        })
        .expect("recall tool call recorded in trail");
    assert_eq!(
        recall_result.get("value").and_then(|v| v.as_str()),
        Some("blue"),
        "expected value 'blue' in recall result, got: {recall_result}"
    );
}

#[tokio::test]
async fn recall_missing_key_returns_null() {
    // LLM emits `recall {key:"absent"}` for a key that was never stored.
    // Expect the tool result to be `{"value": null}`.
    let (rt, _llm, tc) = build_st_runtime(
        vec![
            Ok(tool_call_with_args(
                "c1",
                "host",
                "recall",
                serde_json::json!({ "key": "absent" }),
            )),
            Ok(final_reply("nothing stored")),
        ],
        cfg_with_short_term(8),
    );
    let out = rt
        .step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "do you know my name?".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(out.reply, "nothing stored");
    let recall_result = out
        .trail
        .iter()
        .find_map(|s| match s {
            AgentStep::ToolCall { name, result, .. } if name == "recall" => Some(result.clone()),
            _ => None,
        })
        .expect("recall tool call recorded in trail");
    assert!(
        recall_result.get("value").is_some_and(|v| v.is_null()),
        "expected null value for missing key, got: {recall_result}"
    );
}

#[tokio::test]
async fn conversational_agent_is_offered_end_conversation_tool() {
    // conversational = true → the LLM request must carry the `end_conversation`
    // tool and the system prompt must carry the accompanying note.
    let llm = Arc::new(MockLlmBackend::new(vec![Ok(final_reply("hi"))]));
    let mut c = cfg(4, 5_000, vec![], None);
    c.conversational = true;
    let cp = MockConfigProvider::new();
    let tc = TenantContext::new("acme", "prod");
    cp.insert(&tc, "a", c);
    let ext = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
    let rt = AgentRuntime::new(
        Arc::new(cp),
        Arc::new(MockAgentStateStore::new()),
        ext,
        llm.clone(),
        Arc::new(MockTelemetry::new()),
        Arc::new(MockTokenMeter::new(0)),
        Arc::new(NoopToolLedger),
        None,
    );
    let out = rt
        .step(
            tc,
            "sess-conv",
            "a",
            AgentInput {
                text: "hello".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(out.terminated_by, TerminationReason::FinalReply); // no tool called here
    let tools = llm.seen_tool_names.lock().unwrap();
    assert!(
        tools[0].iter().any(|t| t == "end_conversation"),
        "expected 'end_conversation' in tool list: {:?}",
        tools[0]
    );
    let prompts = llm.seen_system_prompts.lock().unwrap();
    assert!(
        prompts[0].contains("end_conversation"),
        "expected system prompt to mention 'end_conversation': {:?}",
        prompts[0]
    );
}

#[tokio::test]
async fn non_conversational_agent_has_no_end_conversation_tool() {
    // conversational defaults to false → neither the tool nor the note appear.
    let llm = Arc::new(MockLlmBackend::new(vec![Ok(final_reply("hi"))]));
    let c = cfg(4, 5_000, vec![], None);
    let cp = MockConfigProvider::new();
    let tc = TenantContext::new("acme", "prod");
    cp.insert(&tc, "a", c);
    let ext = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
    let rt = AgentRuntime::new(
        Arc::new(cp),
        Arc::new(MockAgentStateStore::new()),
        ext,
        llm.clone(),
        Arc::new(MockTelemetry::new()),
        Arc::new(MockTokenMeter::new(0)),
        Arc::new(NoopToolLedger),
        None,
    );
    let _ = rt
        .step(
            tc,
            "sess-conv",
            "a",
            AgentInput {
                text: "hello".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    let tools = llm.seen_tool_names.lock().unwrap();
    assert!(
        !tools[0].iter().any(|t| t == "end_conversation"),
        "unexpected 'end_conversation' in tool list: {:?}",
        tools[0]
    );
    let prompts = llm.seen_system_prompts.lock().unwrap();
    assert!(
        !prompts[0].contains("end_conversation"),
        "unexpected 'end_conversation' note in system prompt: {:?}",
        prompts[0]
    );
}

// ---------------------------------------------------------------------------
// `end_conversation` short-circuit termination (SP1, Task 5)
// ---------------------------------------------------------------------------

/// Build an `end_conversation` tool-call `LlmResponse`, mirroring `tool_call(...)`.
/// `final_message` becomes the tool's `args.final_message` (omitted when `None`);
/// `content` is the accompanying assistant text (the fallback source when
/// `final_message` is absent/empty).
fn end_conversation_call(
    call_id: &str,
    final_message: Option<&str>,
    content: Option<&str>,
) -> LlmResponse {
    let args = match final_message {
        Some(m) => serde_json::json!({ "final_message": m }),
        None => serde_json::json!({}),
    };
    LlmResponse {
        content: content.map(str::to_string),
        tool_calls: vec![ToolCallRecord {
            call_id: call_id.into(),
            extension_id: "host".into(),
            tool_name: "end_conversation".into(),
            args,
        }],
        tokens_in: 5,
        tokens_out: 5,
    }
}

#[tokio::test]
async fn end_conversation_terminates_with_final_message() {
    let mut c = cfg(4, 5_000, vec![], None);
    c.conversational = true;
    let (rt, _tel, tc) = build_runtime(
        vec![Ok(end_conversation_call("c1", Some("Goodbye!"), None))],
        c,
        0,
    );
    let out = rt
        .step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "bye".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(out.terminated_by, TerminationReason::ConversationEnded);
    assert_eq!(out.reply, "Goodbye!");
}

#[tokio::test]
async fn end_conversation_falls_back_to_accompanying_content() {
    let mut c = cfg(4, 5_000, vec![], None);
    c.conversational = true;
    let (rt, _tel, tc) = build_runtime(
        vec![Ok(end_conversation_call("c1", None, Some("Take care.")))],
        c,
        0,
    );
    let out = rt
        .step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "bye".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(out.terminated_by, TerminationReason::ConversationEnded);
    assert_eq!(out.reply, "Take care.");
}

#[tokio::test]
async fn end_conversation_empty_reply_when_neither_present() {
    let mut c = cfg(4, 5_000, vec![], None);
    c.conversational = true;
    let (rt, _tel, tc) = build_runtime(vec![Ok(end_conversation_call("c1", None, None))], c, 0);
    let out = rt
        .step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "bye".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(out.terminated_by, TerminationReason::ConversationEnded);
    assert_eq!(out.reply, "");
}

#[tokio::test]
async fn end_conversation_ignored_when_not_conversational() {
    // Non-conversational agent: the tool is not intercepted. The model's call
    // is not in the (empty) allow-list, so it is blocked (not terminated); the
    // second scripted response is the real final reply.
    let script = vec![
        Ok(end_conversation_call("c1", Some("nope"), None)),
        Ok(final_reply("real reply")),
    ];
    let (rt, _tel, tc) = build_runtime(script, cfg(4, 5_000, vec![], None), 0); // conversational = false
    let out = rt
        .step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "hi".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(out.terminated_by, TerminationReason::FinalReply);
    assert_eq!(out.reply, "real reply");
}

#[tokio::test]
async fn a_tool_outcome_is_traced_and_shown_to_the_next_llm_request() {
    // Dispatch fails (for_test runtime has no extensions), which exercises the
    // dispatch-failure trace site. The next request must carry the rebuilt view.
    let allowed = vec![ToolRef {
        extension_id: "http".into(),
        tool_name: "fetch".into(),
        description: None,
        input_schema: None,
        usage_note: None,
    }];
    let llm = Arc::new(MockLlmBackend::new(vec![
        Ok(tool_call_with_args(
            "c1",
            "http",
            "fetch",
            serde_json::json!({ "secret": "TOPSECRET-ARG" }),
        )),
        Ok(final_reply("recovered")),
    ]));
    let cp = MockConfigProvider::new();
    let tc = TenantContext::new("acme", "prod");
    cp.insert(&tc, "a", cfg(4, 60_000, allowed, None));
    let ext = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
    let rt = AgentRuntime::new(
        Arc::new(cp),
        Arc::new(MockAgentStateStore::new()),
        ext,
        llm.clone(),
        Arc::new(MockTelemetry::new()),
        Arc::new(MockTokenMeter::new(0)),
        Arc::new(NoopToolLedger),
        None,
    );
    let trace = Arc::new(greentic_aw_runtime::RunTrace::new());
    greentic_aw_runtime::RunContext::scope(
        greentic_aw_runtime::RunContext::new("acme", trace.clone()),
        rt.step(
            tc,
            "s",
            "a",
            AgentInput {
                text: "go".into(),
                conversational: false,
                resume_payload: None,
                ..Default::default()
            },
        ),
    )
    .await
    .unwrap();
    let events = trace.events();
    assert_eq!(events[0].kind, "tool");
    assert!(
        events[0].summary.starts_with("fetch"),
        "{}",
        events[0].summary
    );
    assert!(!events.iter().any(|e| e.summary.contains("TOPSECRET-ARG")));
    let prompts = llm.seen_system_prompts.lock().unwrap();
    assert!(!prompts[0].contains("<run_context>"));
    assert!(prompts[1].contains("<run_context>"), "{}", prompts[1]);
    assert!(prompts[1].contains("fetch"));
}