bamboo-server 2026.9.15

HTTP server and API layer for the Bamboo agent framework
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
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
use super::{AppState, UnconfiguredProvider, DEFAULT_BASE_PROMPT};
use crate::tools::ToolSurface;
use bamboo_agent_core::storage::Storage;
use bamboo_agent_core::tools::{FunctionCall, ToolCall, ToolError};
use bamboo_agent_core::{Session, ToolExecutionContext};
use bamboo_domain::{AgentRuntimeState, AgentStatusState};
use bamboo_llm::{Config, LLMProvider};
use bamboo_metrics::{MetricsStorage, SessionStatus, SqliteMetricsStorage};
use bamboo_plugin_protocol::InMemoryToolEventRecorder;
use bamboo_storage::SessionStoreV2;
use bamboo_tools::permission::config::{PermissionConfig, PermissionRule, PermissionType};
use bamboo_tools::permission::storage::PermissionStorage;
use serde_json::json;
use std::sync::Arc;

fn make_tool_call(name: &str, args: serde_json::Value) -> ToolCall {
    ToolCall {
        id: format!("call_{name}"),
        tool_type: "function".to_string(),
        function: FunctionCall {
            name: name.to_string(),
            arguments: args.to_string(),
        },
    }
}

async fn persist_assigned_project_session(state: &AppState, session_id: &str) {
    let project = state
        .project_store
        .create(format!("Memory test {session_id}"), None)
        .expect("memory test Project should be created");
    let mut session = Session::new(session_id, "test-model");
    session.set_project_id_meta(project.id.to_string());
    state
        .storage
        .save_session(&session)
        .await
        .expect("assigned memory test session should be saved");
    state
        .session_store
        .save_session(&session)
        .await
        .expect("assigned memory test session should be indexed");
}

#[test]
fn default_base_prompt_does_not_unconditionally_require_conclusion_with_options() {
    let normalized = DEFAULT_BASE_PROMPT.to_ascii_lowercase();
    assert!(!normalized.contains("before ending a task, always call conclusion_with_options"));
    assert!(!normalized.contains("do not ask final confirmation in plain assistant text"));
}
#[test]
fn default_base_prompt_prefers_using_injected_context_before_reasking() {
    assert!(DEFAULT_BASE_PROMPT.contains("treat it as available working context"));
    assert!(DEFAULT_BASE_PROMPT.contains("Prefer a minimal verifiable attempt first"));
    assert!(DEFAULT_BASE_PROMPT
        .contains("only ask follow-up questions for information that is still genuinely missing"));
}

#[tokio::test]
async fn test_app_state_creation() {
    let temp_dir = tempfile::tempdir().unwrap();
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");

    // Verify basic fields
    assert!(state.sessions.is_empty());
    assert!(state.config_facade.is_some());
    assert!(bamboo_config::section_layout_is_active(temp_dir.path()).unwrap());
}

#[tokio::test]
async fn injected_tool_event_publishers_are_isolated_between_app_states() {
    let dir_a = tempfile::tempdir().unwrap();
    let dir_b = tempfile::tempdir().unwrap();
    let recorder_a = Arc::new(InMemoryToolEventRecorder::new(4).unwrap());
    let recorder_b = Arc::new(InMemoryToolEventRecorder::new(4).unwrap());
    let provider: Arc<dyn LLMProvider> = Arc::new(UnconfiguredProvider {
        message: "test provider is intentionally unconfigured".to_string(),
    });
    let state_a = AppState::new_with_provider_and_tool_event_publisher(
        dir_a.path().to_path_buf(),
        Config::default(),
        provider.clone(),
        recorder_a.clone(),
    )
    .await
    .unwrap();
    let state_b = AppState::new_with_provider_and_tool_event_publisher(
        dir_b.path().to_path_buf(),
        Config::default(),
        provider,
        recorder_b.clone(),
    )
    .await
    .unwrap();

    let file_a = dir_a.path().join("state-a.txt");
    let call_a = make_tool_call("Write", json!({"file_path": file_a, "content": "state-a"}));
    let result_a = state_a
        .tools_for(ToolSurface::Base)
        .execute_with_context(
            &call_a,
            ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("state-a-session"),
                root_session_id: Some("state-a-root-session"),
                tool_call_id: &call_a.id,
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .unwrap();
    assert!(result_a.success);
    assert_eq!(tokio::fs::read_to_string(file_a).await.unwrap(), "state-a");
    assert_eq!(recorder_a.try_snapshot().unwrap().len(), 1);
    assert!(recorder_b.try_snapshot().unwrap().is_empty());

    let file_b = dir_b.path().join("state-b.txt");
    let call_b = make_tool_call("Write", json!({"file_path": file_b, "content": "state-b"}));
    let result_b = state_b
        .tools_for(ToolSurface::Base)
        .execute_with_context(
            &call_b,
            ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("state-b-session"),
                root_session_id: Some("state-b-root-session"),
                tool_call_id: &call_b.id,
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .unwrap();
    assert!(result_b.success);
    assert_eq!(tokio::fs::read_to_string(file_b).await.unwrap(), "state-b");

    let events_a = recorder_a.try_snapshot().unwrap();
    let events_b = recorder_b.try_snapshot().unwrap();
    assert_eq!(events_a.len(), 1, "state B must not publish into state A");
    assert_eq!(
        events_b.len(),
        1,
        "state B must publish into its own recorder"
    );
    assert_eq!(events_a[0].context.session_id, "state-a-session");
    assert_eq!(events_a[0].context.root_session_id, "state-a-root-session");
    assert_eq!(events_b[0].context.session_id, "state-b-session");
    assert_eq!(events_b[0].context.root_session_id, "state-b-root-session");
}

#[tokio::test]
async fn app_state_creation_reconciles_stale_running_metrics_from_durable_sessions() {
    let temp_dir = tempfile::tempdir().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    let session_store = SessionStoreV2::new(data_dir.clone())
        .await
        .expect("session store should initialize");
    let mut session = Session::new("startup-stale-session", "test-model");
    let mut runtime_state = AgentRuntimeState::new("run-startup-stale");
    runtime_state.status = AgentStatusState::Suspended;
    session.agent_runtime_state = Some(runtime_state);
    session.metadata.insert(
        "runtime.suspend_reason".to_string(),
        "waiting_for_children".to_string(),
    );
    session_store
        .save_session(&session)
        .await
        .expect("session should save");

    let metrics_storage = SqliteMetricsStorage::new(data_dir.join("metrics.db"));
    metrics_storage
        .init()
        .await
        .expect("metrics storage should initialize");
    metrics_storage
        .upsert_session_start("startup-stale-session", "test-model", session.created_at)
        .await
        .expect("session start metrics should save");

    let state = AppState::new(data_dir)
        .await
        .expect("app state should initialize");

    let sessions = state
        .metrics_service
        .sessions(Default::default())
        .await
        .expect("sessions query should succeed");
    let session_metrics = sessions
        .iter()
        .find(|entry| entry.session_id == "startup-stale-session")
        .expect("startup-stale-session metrics should exist");
    assert_eq!(session_metrics.status, SessionStatus::AwaitingResponse);
    assert!(session_metrics.completed_at.is_some());

    let summary = state
        .metrics_service
        .summary(None, None)
        .await
        .expect("summary query should succeed");
    assert_eq!(summary.active_sessions, 0);
    assert_eq!(summary.awaiting_response_sessions, 1);
    assert_eq!(summary.completed_sessions, 0);
}

#[tokio::test]
async fn root_tools_include_server_overlays_and_session_note() {
    let temp_dir = tempfile::tempdir().unwrap();
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");
    let names: std::collections::HashSet<String> = state
        .get_all_tool_schemas()
        .into_iter()
        .map(|schema| schema.function.name)
        .collect();

    assert!(names.contains("Task"));
    assert!(names.contains("SubAgent"));
    assert!(names.contains("scheduler"));
    assert!(names.contains("session_history"));
    assert!(names.contains("session_control"));
    assert!(names.contains("memory"));
    assert!(names.contains("load_skill"));
    assert!(names.contains("read_skill_resource"));
    assert!(names.contains("session_note"));
}

#[tokio::test]
async fn root_catalog_classifies_exactly_five_callable_core_functions() {
    let temp_dir = tempfile::tempdir().unwrap();
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");

    let full = state.get_all_tool_schemas();
    let core_names = full
        .iter()
        .filter_map(|schema| {
            bamboo_domain::ClassifiedToolIdentity::from_schema_name(&schema.function.name)
        })
        .filter(|identity| identity.loading_class() == bamboo_domain::CapabilityLoadingClass::Core)
        .map(|identity| identity.execution_name().to_string())
        .collect::<std::collections::BTreeSet<_>>();

    assert_eq!(
        core_names,
        std::collections::BTreeSet::from([
            "Bash".to_string(),
            "Edit".to_string(),
            "Grep".to_string(),
            "Read".to_string(),
            "Write".to_string(),
        ])
    );
    assert_eq!(
        bamboo_domain::DISCOVERY_CONTROL_GATEWAY.logical_name(),
        "discover"
    );
    assert!(bamboo_domain::DISCOVERY_CONTROL_GATEWAY.is_initially_visible());
}

#[tokio::test]
async fn child_tools_exclude_scheduler_and_session_history() {
    let temp_dir = tempfile::tempdir().unwrap();
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");
    let names: std::collections::HashSet<String> = state
        .tools_for(ToolSurface::Child)
        .list_tools()
        .into_iter()
        .map(|schema| schema.function.name)
        .collect();

    assert!(!names.contains("scheduler"));
    assert!(!names.contains("sub_session_manager"));
    assert!(!names.contains("session_history"));
    assert!(!names.contains("session_control"));
    assert!(names.contains("memory"));
    assert!(names.contains("load_skill"));
    assert!(names.contains("read_skill_resource"));
    assert!(names.contains("session_note"));
}

#[tokio::test]
async fn overlay_tools_require_session_context() {
    let temp_dir = tempfile::tempdir().unwrap();
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");

    let schedule_result = state
        .tools_for(ToolSurface::Root)
        .execute(&make_tool_call("scheduler", json!({ "action": "list" })))
        .await;
    assert!(matches!(
        schedule_result,
        Err(ToolError::Execution(msg)) if msg.contains("session_id")
    ));

    let inspector_result = state
        .tools_for(ToolSurface::Root)
        .execute(&make_tool_call(
            "session_history",
            json!({ "action": "list" }),
        ))
        .await;
    assert!(matches!(
        inspector_result,
        Err(ToolError::Execution(msg)) if msg.contains("session_id")
    ));

    let memory_result = state
        .tools_for(ToolSurface::Root)
        .execute(&make_tool_call(
            "memory",
            json!({ "action": "inspect", "scope": "global" }),
        ))
        .await;
    assert!(matches!(
        memory_result,
        Err(ToolError::Execution(msg)) if msg.contains("session_id")
    ));

    let sub_agent_result = state
        .tools_for(ToolSurface::Root)
        .execute(&make_tool_call("SubAgent", json!({ "action": "list" })))
        .await;
    assert!(matches!(
        sub_agent_result,
        Err(ToolError::Execution(msg)) if msg.contains("session_id")
    ));
}

#[tokio::test]
async fn memory_tool_merge_action_updates_existing_project_memory() {
    let temp_dir = tempfile::tempdir().unwrap();
    bamboo_config::paths::init_bamboo_dir(temp_dir.path().to_path_buf());
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");

    bamboo_tools::tools::workspace_state::ensure_session_workspace(
        "session-merge",
        Some(temp_dir.path().to_path_buf()),
    );
    persist_assigned_project_session(&state, "session-merge").await;

    let write_target = make_tool_call(
        "memory",
        json!({
            "action": "write",
            "scope": "project",
            "type": "project",
            "title": "Release freeze begins next week",
            "content": "Merge freeze begins on Tuesday.",
            "tags": ["release"]
        }),
    );
    let target_result = state
        .tools_for(ToolSurface::Root)
        .execute_with_context(
            &write_target,
            bamboo_agent_core::tools::ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("session-merge"),
                root_session_id: None,
                tool_call_id: "tool-call-write-target",
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .expect("write target should succeed");
    let target_json: serde_json::Value = serde_json::from_str(&target_result.result).unwrap();
    let target_id = target_json["memory"]["id"].as_str().unwrap().to_string();

    let write_source = make_tool_call(
        "memory",
        json!({
            "action": "write",
            "scope": "project",
            "type": "project",
            "title": "Mobile release note",
            "content": "Stakeholders confirmed freeze applies to mobile release cut.",
            "tags": ["mobile"]
        }),
    );
    let source_result = state
        .tools_for(ToolSurface::Root)
        .execute_with_context(
            &write_source,
            bamboo_agent_core::tools::ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("session-merge"),
                root_session_id: None,
                tool_call_id: "tool-call-write-source",
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .expect("write source should succeed");
    let source_json: serde_json::Value = serde_json::from_str(&source_result.result).unwrap();
    let source_id = source_json["memory"]["id"].as_str().unwrap().to_string();

    let merge_call = make_tool_call(
        "memory",
        json!({
            "action": "merge",
            "id": target_id,
            "content": "Additional confirmation from a later session.",
            "tags": ["confirmed"],
            "source_memory_ids": [source_id]
        }),
    );
    let merge_result = state
        .tools_for(ToolSurface::Root)
        .execute_with_context(
            &merge_call,
            bamboo_agent_core::tools::ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("session-merge"),
                root_session_id: None,
                tool_call_id: "tool-call-merge",
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .expect("merge should succeed");
    let merge_json: serde_json::Value = serde_json::from_str(&merge_result.result).unwrap();
    assert_eq!(merge_json["action"], "merge");
    assert_eq!(merge_json["data"]["appended"], true);
    assert_eq!(
        merge_json["data"]["superseded_ids"][0],
        source_json["memory"]["id"]
    );
}

#[tokio::test]
async fn memory_tool_write_merges_near_identical_restatement_when_enabled() {
    let temp_dir = tempfile::tempdir().unwrap();
    bamboo_config::paths::init_bamboo_dir(temp_dir.path().to_path_buf());
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");

    bamboo_tools::tools::workspace_state::ensure_session_workspace(
        "session-heuristic-merge",
        Some(temp_dir.path().to_path_buf()),
    );
    persist_assigned_project_session(&state, "session-heuristic-merge").await;

    let original = state
        .tools_for(ToolSurface::Root)
        .execute_with_context(
            &make_tool_call(
                "memory",
                json!({
                    "action": "write",
                    "scope": "project",
                    "type": "project",
                    "title": "Prod deploy uses blue-green with a 10 minute soak",
                    "content": "Production deploys use a blue-green strategy with a ten minute soak window.",
                    "tags": ["deploy"],
                    "options": { "allow_merge_if_similar": false }
                }),
            ),
            bamboo_agent_core::tools::ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("session-heuristic-merge"),
                root_session_id: None,
                tool_call_id: "tool-call-write-heuristic-original",
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .expect("original write should succeed");
    let original_json: serde_json::Value = serde_json::from_str(&original.result).unwrap();
    let original_id = original_json["memory"]["id"].as_str().unwrap().to_string();

    let merged = state
        .tools_for(ToolSurface::Root)
        .execute_with_context(
            &make_tool_call(
                "memory",
                json!({
                    "action": "write",
                    "scope": "project",
                    "type": "project",
                    "title": "Prod deploy uses blue-green with a 10 minute soak window",
                    "content": "Production deploy uses blue-green with a 10 minute soak before cutover.",
                    "tags": ["deploy"],
                    "options": { "allow_merge_if_similar": true }
                }),
            ),
            bamboo_agent_core::tools::ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("session-heuristic-merge"),
                root_session_id: None,
                tool_call_id: "tool-call-write-heuristic-merge",
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .expect("heuristic merge write should succeed");
    let merged_json: serde_json::Value = serde_json::from_str(&merged.result).unwrap();
    let merged_id = merged_json["memory"]["id"].as_str().unwrap().to_string();
    assert_eq!(merged_id, original_id);

    let inspect = state
        .tools_for(ToolSurface::Root)
        .execute_with_context(
            &make_tool_call(
                "memory",
                json!({
                    "action": "inspect",
                    "scope": "project"
                }),
            ),
            bamboo_agent_core::tools::ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("session-heuristic-merge"),
                root_session_id: None,
                tool_call_id: "tool-call-inspect-heuristic-merge",
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .expect("inspect should succeed");
    let inspect_json: serde_json::Value = serde_json::from_str(&inspect.result).unwrap();
    assert_eq!(inspect_json["data"]["total_memories"], 1);
}

#[tokio::test]
async fn memory_tool_merge_mode_contradict_marks_memory_contradicted() {
    let temp_dir = tempfile::tempdir().unwrap();
    bamboo_config::paths::init_bamboo_dir(temp_dir.path().to_path_buf());
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");

    bamboo_tools::tools::workspace_state::ensure_session_workspace(
        "session-contradict",
        Some(temp_dir.path().to_path_buf()),
    );
    persist_assigned_project_session(&state, "session-contradict").await;

    let target = state
        .tools_for(ToolSurface::Root)
        .execute_with_context(
            &make_tool_call(
                "memory",
                json!({
                    "action": "write",
                    "scope": "project",
                    "type": "project",
                    "title": "Release freeze begins next week",
                    "content": "Freeze begins on Tuesday."
                }),
            ),
            bamboo_agent_core::tools::ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("session-contradict"),
                root_session_id: None,
                tool_call_id: "tool-call-write-contradict-target",
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .expect("write target should succeed");
    let target_json: serde_json::Value = serde_json::from_str(&target.result).unwrap();
    let target_id = target_json["memory"]["id"].as_str().unwrap().to_string();

    let source = state
        .tools_for(ToolSurface::Root)
        .execute_with_context(
            &make_tool_call(
                "memory",
                json!({
                    "action": "write",
                    "scope": "project",
                    "type": "project",
                    "title": "Updated release note",
                    "content": "Freeze is postponed."
                }),
            ),
            bamboo_agent_core::tools::ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("session-contradict"),
                root_session_id: None,
                tool_call_id: "tool-call-write-contradict-source",
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .expect("write source should succeed");
    let source_json: serde_json::Value = serde_json::from_str(&source.result).unwrap();
    let source_id = source_json["memory"]["id"].as_str().unwrap().to_string();

    let contradict_result = state
        .tools_for(ToolSurface::Root)
        .execute_with_context(
            &make_tool_call(
                "memory",
                json!({
                    "action": "merge",
                    "mode": "contradict",
                    "id": target_id,
                    "content": "newer info conflicts",
                    "reason": "newer release update conflicts",
                    "source_memory_ids": [source_id]
                }),
            ),
            bamboo_agent_core::tools::ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("session-contradict"),
                root_session_id: None,
                tool_call_id: "tool-call-contradict",
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .expect("contradict should succeed");
    let contradict_json: serde_json::Value =
        serde_json::from_str(&contradict_result.result).unwrap();
    assert_eq!(contradict_json["action"], "merge");
    assert_eq!(contradict_json["mode"], "contradict");
    assert_eq!(contradict_json["data"]["changed"], true);
    assert_eq!(
        contradict_json["data"]["contradicted_ids"][0],
        source_json["memory"]["id"]
    );
}

#[tokio::test]
async fn memory_tool_batch_purge_archives_filtered_items() {
    let temp_dir = tempfile::tempdir().unwrap();
    bamboo_config::paths::init_bamboo_dir(temp_dir.path().to_path_buf());
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");

    bamboo_tools::tools::workspace_state::ensure_session_workspace(
        "session-batch-purge",
        Some(temp_dir.path().to_path_buf()),
    );
    persist_assigned_project_session(&state, "session-batch-purge").await;

    let stale_write = state
        .tools_for(ToolSurface::Root)
        .execute_with_context(
            &make_tool_call(
                "memory",
                json!({
                    "action": "write",
                    "scope": "project",
                    "type": "reference",
                    "title": "Old dashboard link",
                    "content": "Legacy dashboard."
                }),
            ),
            bamboo_agent_core::tools::ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("session-batch-purge"),
                root_session_id: None,
                tool_call_id: "tool-call-write-stale",
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .expect("write stale memory should succeed");
    let stale_json: serde_json::Value = serde_json::from_str(&stale_write.result).unwrap();
    let stale_id = stale_json["memory"]["id"].as_str().unwrap().to_string();

    state
        .tools_for(ToolSurface::Root)
        .execute_with_context(
            &make_tool_call(
                "memory",
                json!({
                    "action": "purge",
                    "id": stale_id,
                    "mode": "stale",
                    "reason": "mark stale first"
                }),
            ),
            bamboo_agent_core::tools::ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("session-batch-purge"),
                root_session_id: None,
                tool_call_id: "tool-call-mark-stale",
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .expect("mark stale should succeed");

    state
        .tools_for(ToolSurface::Root)
        .execute_with_context(
            &make_tool_call(
                "memory",
                json!({
                    "action": "write",
                    "scope": "project",
                    "type": "reference",
                    "title": "Current dashboard link",
                    "content": "Current dashboard."
                }),
            ),
            bamboo_agent_core::tools::ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("session-batch-purge"),
                root_session_id: None,
                tool_call_id: "tool-call-write-active",
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .expect("write active memory should succeed");

    let batch_result = state
        .tools_for(ToolSurface::Root)
        .execute_with_context(
            &make_tool_call(
                "memory",
                json!({
                    "action": "purge",
                    "scope": "project",
                    "mode": "archived",
                    "reason": "archive stale references",
                    "filters": {
                        "type": ["reference"],
                        "status": ["stale"]
                    }
                }),
            ),
            bamboo_agent_core::tools::ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("session-batch-purge"),
                root_session_id: None,
                tool_call_id: "tool-call-batch-purge",
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .expect("batch purge should succeed");
    let batch_json: serde_json::Value = serde_json::from_str(&batch_result.result).unwrap();
    assert_eq!(batch_json["action"], "purge");
    assert_eq!(batch_json["data"]["matched_count"], 1);
}

#[tokio::test]
async fn app_state_session_note_and_prompt_share_the_injected_jiandu_store() {
    let temp_dir = tempfile::tempdir().unwrap();
    bamboo_config::paths::init_bamboo_dir(temp_dir.path().to_path_buf());
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");

    state
        .tools_for(ToolSurface::Root)
        .execute_with_context(
            &make_tool_call(
                "session_note",
                json!({
                    "action": "replace",
                    "content": "Shared AppState Jiandu note"
                }),
            ),
            bamboo_agent_core::tools::ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("session-note-injected-store"),
                root_session_id: None,
                tool_call_id: "tool-call-session-note-injected-store",
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .expect("session_note replace should succeed");

    assert_eq!(
        state
            .memory_store
            .read_session_topic("session-note-injected-store", "default")
            .await
            .expect("read note from AppState store")
            .as_deref(),
        Some("Shared AppState Jiandu note")
    );
}

#[tokio::test]
async fn memory_tool_inspect_and_rebuild_expose_observability_fields() {
    let temp_dir = tempfile::tempdir().unwrap();
    bamboo_config::paths::init_bamboo_dir(temp_dir.path().to_path_buf());
    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");

    bamboo_tools::tools::workspace_state::ensure_session_workspace(
        "session-inspect",
        Some(temp_dir.path().to_path_buf()),
    );
    persist_assigned_project_session(&state, "session-inspect").await;

    state
        .tools_for(ToolSurface::Root)
        .execute_with_context(
            &make_tool_call(
                "memory",
                json!({
                    "action": "write",
                    "scope": "project",
                    "type": "reference",
                    "title": "Old dashboard link",
                    "content": "Legacy dashboard."
                }),
            ),
            bamboo_agent_core::tools::ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("session-inspect"),
                root_session_id: None,
                tool_call_id: "tool-call-write-inspect",
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .expect("write memory should succeed");

    let inspect_result = state
        .tools_for(ToolSurface::Root)
        .execute_with_context(
            &make_tool_call(
                "memory",
                json!({
                    "action": "inspect",
                    "scope": "project"
                }),
            ),
            bamboo_agent_core::tools::ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("session-inspect"),
                root_session_id: None,
                tool_call_id: "tool-call-inspect",
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .expect("inspect should succeed");
    let inspect_json: serde_json::Value = serde_json::from_str(&inspect_result.result).unwrap();
    assert_eq!(inspect_json["action"], "inspect");
    assert!(inspect_json["data"]["index_files"].is_array());
    assert!(inspect_json["data"]["state_files"].is_array());
    assert!(inspect_json["data"]["stale_candidate_count"].is_number());
    assert!(inspect_json["data"]["last_reindex_at"].is_string());
    assert!(
        inspect_json["data"]["last_dream_at"].is_null(),
        "a cold Jiandu scope has no Dream snapshot until one is explicitly published"
    );

    let rebuild_result = state
        .tools_for(ToolSurface::Root)
        .execute_with_context(
            &make_tool_call(
                "memory",
                json!({
                    "action": "rebuild",
                    "scope": "project"
                }),
            ),
            bamboo_agent_core::tools::ToolExecutionContext {
                executing_supervisor: None,
                session_id: Some("session-inspect"),
                root_session_id: None,
                tool_call_id: "tool-call-rebuild",
                event_tx: None,
                available_tool_schemas: None,
                bypass_permissions: false,
                auto_approve_permissions: false,
                plan_read_only: false,
                can_async_resume: false,
                bash_completion_sink: None,
                pre_parsed_args: None,
            },
        )
        .await
        .expect("rebuild should succeed");
    let rebuild_json: serde_json::Value = serde_json::from_str(&rebuild_result.result).unwrap();
    assert_eq!(rebuild_json["action"], "rebuild");
    assert!(rebuild_json["data"]["index_files"].is_array());
    assert!(rebuild_json["data"]["state_files"].is_array());
    assert!(rebuild_json["data"]["stale_candidate_count"].is_number());
    assert!(rebuild_json["data"]["last_reindex_at"].is_string());
    assert!(
        rebuild_json["data"]["last_dream_at"].is_null(),
        "rebuilding canonical indexes must not synthesize a Dream snapshot"
    );
}

#[tokio::test]
async fn app_state_uses_persisted_permission_config_in_data_dir() {
    let temp_dir = tempfile::tempdir().unwrap();
    let storage = PermissionStorage::new(temp_dir.path());
    let config = PermissionConfig::new();
    config.set_enabled(true);
    config.add_rule(PermissionRule::new(PermissionType::WriteFile, "*", false));
    storage.save(&config).await.unwrap();

    let state = AppState::new(temp_dir.path().to_path_buf())
        .await
        .expect("app state should initialize");
    let target = temp_dir.path().join("blocked.txt");
    let call = make_tool_call(
        "Write",
        json!({
            "file_path": target,
            "content": "blocked"
        }),
    );

    let result = state.tools_for(ToolSurface::Root).execute(&call).await;
    assert!(matches!(result, Err(ToolError::Execution(_))));
    assert!(!target.exists());
}

// ── config-corruption recovery confirmation gate (#153) ────────────────────

mod config_recovery_gate {
    use super::AppState;
    use crate::{app_state::ConfigUpdateEffects, error::AppError};

    #[tokio::test]
    async fn update_config_refuses_while_recovery_is_pending_and_unconfirmed() {
        let temp_dir = tempfile::tempdir().unwrap();
        // A corrupt config.json (with no .bak) makes AppState::new's load fall
        // back to defaults AND set a pending, unconfirmed recovery status.
        std::fs::write(temp_dir.path().join("config.json"), "}}} broken").unwrap();

        let state = AppState::new(temp_dir.path().to_path_buf())
            .await
            .expect("app state should still initialize (defaults + quarantine)");

        assert!(
            state.config.read().await.recovery_status().is_some(),
            "boot should have picked up the pending recovery from the corrupt config.json"
        );

        let result = state
            .update_config(
                |cfg| {
                    cfg.http_proxy = "http://should-not-be-applied".to_string();
                    Ok(())
                },
                ConfigUpdateEffects::default(),
            )
            .await;

        assert!(
            matches!(result, Err(AppError::ConfigRecoveryPending(_))),
            "settings writes must be refused while a recovery is unconfirmed, got {result:?}"
        );
        // The refusal must happen BEFORE the in-memory mutation runs.
        assert!(
            state.config.read().await.http_proxy.is_empty(),
            "the update closure must never have run"
        );
    }

    #[tokio::test]
    async fn confirm_config_recovery_reject_is_a_no_op() {
        let temp_dir = tempfile::tempdir().unwrap();
        let corrupt_bytes = "}}} broken";
        std::fs::write(temp_dir.path().join("config.json"), corrupt_bytes).unwrap();

        let state = AppState::new(temp_dir.path().to_path_buf())
            .await
            .expect("app state should initialize");

        let resolved = state
            .confirm_config_recovery(false)
            .await
            .expect("rejecting a pending recovery should succeed (it's a no-op)");
        assert!(
            resolved.recovery_status().is_some_and(|s| !s.confirmed),
            "reject must leave the pending flag exactly as it was"
        );
        assert_eq!(
            std::fs::read_to_string(temp_dir.path().join("config.json")).unwrap(),
            corrupt_bytes,
            "reject must not touch config.json at all"
        );

        // A settings write is still refused after a reject.
        let result = state
            .update_config(
                |cfg| {
                    cfg.http_proxy = "http://nope".to_string();
                    Ok(())
                },
                ConfigUpdateEffects::default(),
            )
            .await;
        assert!(matches!(result, Err(AppError::ConfigRecoveryPending(_))));
    }

    #[tokio::test]
    async fn confirm_config_recovery_accept_persists_and_unblocks_future_writes() {
        let temp_dir = tempfile::tempdir().unwrap();
        std::fs::write(
            temp_dir.path().join("config.json"),
            r#"{"http_proxy":"http://salvaged","env_vars":"bad-type"}"#,
        )
        .unwrap();

        let state = AppState::new(temp_dir.path().to_path_buf())
            .await
            .expect("app state should initialize");
        assert!(state.config.read().await.recovery_status().is_some());

        let resolved = state
            .confirm_config_recovery(true)
            .await
            .expect("accepting the pending recovery should succeed");
        assert!(
            resolved.recovery_status().is_none(),
            "accept clears the pending flag once persisted"
        );
        assert!(
            state.config.read().await.recovery_status().is_none(),
            "AppState's in-memory config reflects the cleared flag too"
        );

        let on_disk = std::fs::read_to_string(temp_dir.path().join("config.json")).unwrap();
        assert!(
            on_disk.contains("http://salvaged"),
            "config.json now holds the recovered state"
        );

        // Settings writes work normally again.
        state
            .update_config(
                |cfg| {
                    cfg.http_proxy = "http://after-confirm".to_string();
                    Ok(())
                },
                ConfigUpdateEffects::default(),
            )
            .await
            .expect("writes should succeed once the recovery is confirmed");
    }

    #[tokio::test]
    async fn confirm_config_recovery_errors_when_nothing_pending() {
        let temp_dir = tempfile::tempdir().unwrap();
        let state = AppState::new(temp_dir.path().to_path_buf())
            .await
            .expect("app state should initialize");

        let result = state.confirm_config_recovery(true).await;
        assert!(matches!(result, Err(AppError::BadRequest(_))));
        let result = state.confirm_config_recovery(false).await;
        assert!(matches!(result, Err(AppError::BadRequest(_))));
    }
}

#[path = "session_control_tests.rs"]
mod session_control_tests;