nexo-core 0.2.1

Agent runtime: event bus, sessions, plugin trait, heartbeat, A2A delegation.
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
//! Boot dispatcher for `EXPOSABLE_TOOLS`.
//!
//! Each named entry maps to a small `boot_*` helper that constructs
//! the tool from handles in `McpServerBootContext`. Missing handles
//! become `BootResult::SkippedInfraMissing` so the rest of the
//! catalog still boots.

use std::sync::Arc;

use nexo_config::types::mcp_exposable::{lookup_exposable, BootKind};
use nexo_llm::ToolDef;

use super::context::McpServerBootContext;
use crate::agent::tool_registry::ToolHandler;

/// Outcome of a single per-tool boot attempt.
pub enum BootResult {
    /// Tool was constructed and is ready to register.
    Registered(ToolDef, Arc<dyn ToolHandler>),
    /// Tool name appears in `EXPOSABLE_TOOLS` but is hard-denied.
    SkippedDenied { reason: &'static str },
    /// Tool name appears but boot wiring is deferred.
    SkippedDeferred {
        phase: &'static str,
        reason: &'static str,
    },
    /// Tool name is feature-gated and the gate is off.
    SkippedFeatureGated { feature: &'static str },
    /// Tool requires a handle that the boot context didn't carry.
    SkippedInfraMissing { handle: &'static str },
    /// Tool name is not in `EXPOSABLE_TOOLS` at all.
    UnknownName,
}

impl BootResult {
    pub fn skip_reason(&self) -> &'static str {
        match self {
            BootResult::Registered(..) => "registered",
            BootResult::SkippedDenied { .. } => "denied_by_policy",
            BootResult::SkippedDeferred { .. } => "deferred",
            BootResult::SkippedFeatureGated { .. } => "feature_gate_off",
            BootResult::SkippedInfraMissing { .. } => "infra_missing",
            BootResult::UnknownName => "unknown_name",
        }
    }
}

/// Boot a single named tool against the catalog.
pub fn boot_exposable(name: &str, ctx: &McpServerBootContext) -> BootResult {
    let entry = match lookup_exposable(name) {
        Some(e) => e,
        None => return BootResult::UnknownName,
    };
    match entry.boot_kind {
        BootKind::Always => boot_always(name, ctx),
        BootKind::DeniedByPolicy { reason } => BootResult::SkippedDenied { reason },
        BootKind::Deferred { phase, reason } => BootResult::SkippedDeferred { phase, reason },
        BootKind::FeatureGated => boot_feature_gated(name, entry, ctx),
    }
}

#[allow(unused_variables)]
fn boot_feature_gated(
    name: &str,
    entry: &nexo_config::types::mcp_exposable::ExposableToolEntry,
    ctx: &McpServerBootContext,
) -> BootResult {
    #[cfg(feature = "config-self-edit")]
    if name == "Config" {
        return boot_config_tool(ctx);
    }
    BootResult::SkippedFeatureGated {
        feature: entry.feature_gate.unwrap_or("unknown"),
    }
}

#[cfg(feature = "config-self-edit")]
fn boot_config_tool(ctx: &McpServerBootContext) -> BootResult {
    use crate::agent::config_tool::ConfigTool;

    // Every handle must be present. Missing one → labelled
    // SkippedInfraMissing pointing at the operator-visible knob.
    let applier = match ctx.config_yaml_applier.as_ref() {
        Some(a) => Arc::clone(a),
        None => {
            return BootResult::SkippedInfraMissing {
                handle: "config_yaml_applier",
            }
        }
    };
    let denylist = match ctx.config_denylist_checker.as_ref() {
        Some(d) => Arc::clone(d),
        None => {
            return BootResult::SkippedInfraMissing {
                handle: "config_denylist_checker",
            }
        }
    };
    let redactor = match ctx.config_secret_redactor.as_ref() {
        Some(r) => Arc::clone(r),
        None => {
            return BootResult::SkippedInfraMissing {
                handle: "config_secret_redactor",
            }
        }
    };
    let correlator = match ctx.config_approval_correlator.as_ref() {
        Some(c) => Arc::clone(c),
        None => {
            return BootResult::SkippedInfraMissing {
                handle: "config_approval_correlator",
            }
        }
    };
    let reload = match ctx.config_reload_trigger.as_ref() {
        Some(r) => Arc::clone(r),
        None => {
            return BootResult::SkippedInfraMissing {
                handle: "config_reload_trigger",
            }
        }
    };
    let policy = match ctx.config_tool_policy.as_ref() {
        Some(p) => p.clone(),
        None => {
            return BootResult::SkippedInfraMissing {
                handle: "config_tool_policy",
            }
        }
    };
    let proposals_dir = match ctx.config_proposals_dir.as_ref() {
        Some(p) => p.clone(),
        None => {
            return BootResult::SkippedInfraMissing {
                handle: "config_proposals_dir",
            }
        }
    };
    let changes_store = match ctx.config_changes_store.as_ref() {
        Some(s) => Arc::clone(s),
        None => {
            return BootResult::SkippedInfraMissing {
                handle: "config_changes_store",
            }
        }
    };

    // Synthetic actor for mcp-server origin. The audit log surfaces
    // every mutation as `(channel="mcp", account_id=<server-name>)`
    // so operators see who touched the YAML.
    let actor_origin = crate::agent::config_tool::ActorOrigin {
        channel: "mcp".to_string(),
        account_id: ctx.agent_id.clone(),
        sender_id: "server".to_string(),
    };

    let cfg_tool = ConfigTool {
        agent_id: ctx.agent_id.clone(),
        binding_id: format!("mcp:{}", ctx.agent_id),
        allowed_paths: policy.allowed_paths.clone(),
        approval_timeout_secs: policy.approval_timeout_secs,
        proposals_dir,
        actor_origin,
        applier,
        denylist,
        redactor,
        changes_store,
        correlator,
        reload,
        pending_receivers: Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new())),
    };
    BootResult::Registered(ConfigTool::tool_def(), Arc::new(cfg_tool))
}

fn boot_always(name: &str, ctx: &McpServerBootContext) -> BootResult {
    use crate::agent::config_changes_tail_tool::ConfigChangesTailTool;
    use crate::agent::cron_tool::{
        CronCreateTool, CronDeleteTool, CronListTool, CronPauseTool, CronResumeTool,
    };
    use crate::agent::followup_tool::{CancelFollowupTool, CheckFollowupTool, StartFollowupTool};
    use crate::agent::mcp_router_tool::{ListMcpResourcesTool, ReadMcpResourceTool};
    use crate::agent::memory_checkpoint_tool::MemoryCheckpointTool;
    use crate::agent::memory_history_tool::MemoryHistoryTool;
    use crate::agent::memory_snapshot_tool::MemorySnapshotTool;
    use crate::agent::notebook_edit_tool::NotebookEditTool;
    use crate::agent::plan_mode_tool::{EnterPlanModeTool, ExitPlanModeTool, PlanModeResolveTool};
    use crate::agent::synthetic_output_tool::SyntheticOutputTool;
    use crate::agent::taskflow_tool::TaskFlowTool;
    use crate::agent::todo_write_tool::TodoWriteTool;
    use crate::agent::tool_search_tool::ToolSearchTool;
    use crate::agent::web_fetch_tool::WebFetchTool;
    // Phase 95 — WebSearchTool import removed; subprocess plugin serves it.

    match name {
        // --- handle-free tools (no infra handles needed) ---
        "EnterPlanMode" => {
            BootResult::Registered(EnterPlanModeTool::tool_def(), Arc::new(EnterPlanModeTool))
        }
        "ExitPlanMode" => {
            BootResult::Registered(ExitPlanModeTool::tool_def(), Arc::new(ExitPlanModeTool))
        }
        "ToolSearch" => {
            BootResult::Registered(ToolSearchTool::tool_def(), Arc::new(ToolSearchTool::new()))
        }
        "TodoWrite" => BootResult::Registered(TodoWriteTool::tool_def(), Arc::new(TodoWriteTool)),
        "SyntheticOutput" => BootResult::Registered(
            SyntheticOutputTool::tool_def(),
            Arc::new(SyntheticOutputTool),
        ),
        "NotebookEdit" => {
            BootResult::Registered(NotebookEditTool::tool_def(), Arc::new(NotebookEditTool))
        }

        // --- cron_* (require ctx.cron_store) ---
        "cron_create" => match ctx.cron_store.as_ref() {
            Some(s) => BootResult::Registered(
                CronCreateTool::tool_def(),
                Arc::new(CronCreateTool::new(Arc::clone(s))),
            ),
            None => BootResult::SkippedInfraMissing {
                handle: "cron_store",
            },
        },
        "cron_list" => match ctx.cron_store.as_ref() {
            Some(s) => BootResult::Registered(
                CronListTool::tool_def(),
                Arc::new(CronListTool::new(Arc::clone(s))),
            ),
            None => BootResult::SkippedInfraMissing {
                handle: "cron_store",
            },
        },
        "cron_delete" => match ctx.cron_store.as_ref() {
            Some(s) => BootResult::Registered(
                CronDeleteTool::tool_def(),
                Arc::new(CronDeleteTool::new(Arc::clone(s))),
            ),
            None => BootResult::SkippedInfraMissing {
                handle: "cron_store",
            },
        },
        "cron_pause" => match ctx.cron_store.as_ref() {
            Some(s) => BootResult::Registered(
                CronPauseTool::tool_def(),
                Arc::new(CronPauseTool::new(Arc::clone(s))),
            ),
            None => BootResult::SkippedInfraMissing {
                handle: "cron_store",
            },
        },
        "cron_resume" => match ctx.cron_store.as_ref() {
            Some(s) => BootResult::Registered(
                CronResumeTool::tool_def(),
                Arc::new(CronResumeTool::new(Arc::clone(s))),
            ),
            None => BootResult::SkippedInfraMissing {
                handle: "cron_store",
            },
        },

        // --- mcp_router (handle-free; reads ctx.mcp at call time) ---
        "ListMcpResources" => match ctx.mcp_runtime.as_ref() {
            Some(_) => BootResult::Registered(
                ListMcpResourcesTool::tool_def(),
                Arc::new(ListMcpResourcesTool),
            ),
            None => BootResult::SkippedInfraMissing {
                handle: "mcp_runtime",
            },
        },
        "ReadMcpResource" => match ctx.mcp_runtime.as_ref() {
            Some(_) => BootResult::Registered(
                ReadMcpResourceTool::tool_def(),
                Arc::new(ReadMcpResourceTool),
            ),
            None => BootResult::SkippedInfraMissing {
                handle: "mcp_runtime",
            },
        },

        // --- config_changes_tail ---
        "config_changes_tail" => match ctx.config_changes_store.as_ref() {
            Some(s) => BootResult::Registered(
                ConfigChangesTailTool::tool_def(),
                Arc::new(ConfigChangesTailTool::new(Arc::clone(s))),
            ),
            None => BootResult::SkippedInfraMissing {
                handle: "config_changes_store",
            },
        },

        // --- web_search + web_fetch ---
        // Phase 95 — web_search is served by the standalone
        // `nexo-rs-plugin-web-search` subprocess plugin. MCP bridge
        // dispatch no longer registers it in-process; if a session
        // calls `web_search`, the daemon's RemoteToolHandler routes
        // through the subprocess via `tool.invoke` JSON-RPC.
        // Returning `SkippedExtensionDispatch` mirrors how
        // operator-extended tools are surfaced.
        "web_search" => BootResult::SkippedInfraMissing {
            handle: "web_search_subprocess_plugin",
        },
        "web_fetch" => {
            BootResult::Registered(WebFetchTool::tool_def(), Arc::new(WebFetchTool::new()))
        }

        // --- Gap A — workspace-git audit log ---
        "forge_memory_checkpoint" => match ctx.memory_git.as_ref() {
            Some(g) => BootResult::Registered(
                MemoryCheckpointTool::tool_def(),
                Arc::new(MemoryCheckpointTool::new(Arc::clone(g))),
            ),
            None => BootResult::SkippedInfraMissing {
                handle: "memory_git",
            },
        },
        "memory_history" => match ctx.memory_git.as_ref() {
            Some(g) => BootResult::Registered(
                MemoryHistoryTool::tool_def(),
                Arc::new(MemoryHistoryTool::new(Arc::clone(g))),
            ),
            None => BootResult::SkippedInfraMissing {
                handle: "memory_git",
            },
        },
        "memory_snapshot" => match ctx.memory_snapshotter.as_ref() {
            Some(s) => BootResult::Registered(
                MemorySnapshotTool::tool_def(),
                Arc::new(MemorySnapshotTool::new(Arc::clone(s))),
            ),
            None => BootResult::SkippedInfraMissing {
                handle: "memory_snapshotter",
            },
        },

        // --- Gap A — taskflow ---
        "taskflow" => match ctx.taskflow_manager.as_ref() {
            Some(m) => BootResult::Registered(
                TaskFlowTool::tool_def(),
                Arc::new(TaskFlowTool::new((**m).clone())),
            ),
            None => BootResult::SkippedInfraMissing {
                handle: "taskflow_manager",
            },
        },
        "start_followup" => match ctx.long_term_memory.as_ref() {
            Some(mem) => BootResult::Registered(
                StartFollowupTool::tool_def(),
                Arc::new(StartFollowupTool::new(Arc::clone(mem))),
            ),
            None => BootResult::SkippedInfraMissing {
                handle: "long_term_memory",
            },
        },
        "check_followup" => match ctx.long_term_memory.as_ref() {
            Some(mem) => BootResult::Registered(
                CheckFollowupTool::tool_def(),
                Arc::new(CheckFollowupTool::new(Arc::clone(mem))),
            ),
            None => BootResult::SkippedInfraMissing {
                handle: "long_term_memory",
            },
        },
        "cancel_followup" => match ctx.long_term_memory.as_ref() {
            Some(mem) => BootResult::Registered(
                CancelFollowupTool::tool_def(),
                Arc::new(CancelFollowupTool::new(Arc::clone(mem))),
            ),
            None => BootResult::SkippedInfraMissing {
                handle: "long_term_memory",
            },
        },

        // --- Gap A — plan_mode_resolve (no separate handle; reads
        // ctx.plan_approval_registry which AgentContext::new
        // already initialises) ---
        "plan_mode_resolve" => BootResult::Registered(
            PlanModeResolveTool::tool_def(),
            Arc::new(PlanModeResolveTool),
        ),

        // --- 79.M.b — Lsp ---
        // C2 — `LspTool::new` no longer takes `policy`; the handler
        // pulls the per-call `LspPolicy` from `ctx.effective_policy()`
        // so a hot-reload of `lsp.languages` is observed on the next
        // call without re-registration.
        "Lsp" => match ctx.lsp_manager.as_ref() {
            Some(mgr) => {
                use crate::agent::lsp_tool::LspTool;
                let workspace_root = if ctx.agent_context.config.workspace.is_empty() {
                    std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."))
                } else {
                    std::path::PathBuf::from(&ctx.agent_context.config.workspace)
                };
                let tool = LspTool::new(Arc::clone(mgr), workspace_root);
                BootResult::Registered(LspTool::tool_def_static(), Arc::new(tool))
            }
            None => BootResult::SkippedInfraMissing {
                handle: "lsp_manager",
            },
        },

        // --- 79.M.d.1 — TeamList + TeamStatus (read-only) ---
        // Construction needs a `TeamTools` shared inner. The router
        // is constructed unspawned because read-only ops never
        // touch DM channels. Mutating Team* tools stay deferred —
        // they need a spawned router + a real `current_goal_id`.
        "TeamList" => match ctx.team_store.as_ref() {
            Some(s) => {
                use crate::agent::team_tools::{TeamListTool, TeamTools};
                use crate::team_message_router::TeamMessageRouter;
                let router = TeamMessageRouter::new(Arc::new(ctx.broker.clone()));
                let tools = TeamTools::new(
                    Arc::clone(s),
                    router,
                    ctx.broker.clone(),
                    ctx.agent_id.clone(),
                    ctx.agent_id.clone(),
                );
                BootResult::Registered(TeamListTool::tool_def(), Arc::new(TeamListTool::new(tools)))
            }
            None => BootResult::SkippedInfraMissing {
                handle: "team_store",
            },
        },
        "TeamStatus" => match ctx.team_store.as_ref() {
            Some(s) => {
                use crate::agent::team_tools::{TeamStatusTool, TeamTools};
                use crate::team_message_router::TeamMessageRouter;
                let router = TeamMessageRouter::new(Arc::new(ctx.broker.clone()));
                let tools = TeamTools::new(
                    Arc::clone(s),
                    router,
                    ctx.broker.clone(),
                    ctx.agent_id.clone(),
                    ctx.agent_id.clone(),
                );
                BootResult::Registered(
                    TeamStatusTool::tool_def(),
                    Arc::new(TeamStatusTool::new(tools)),
                )
            }
            None => BootResult::SkippedInfraMissing {
                handle: "team_store",
            },
        },

        // --- 79.M.d.2 — Team* mutating (Create/Delete/SendMessage) ---
        // Same TeamTools shared inner. Router is constructed via
        // `Arc::new(ctx.broker.clone())` and the caller is expected
        // to spawn the router subscriber out-of-band (run_mcp_server
        // does this when any Team* mutating tool is requested).
        "TeamCreate" => match ctx.team_store.as_ref() {
            Some(s) => {
                use crate::agent::team_tools::{TeamCreateTool, TeamTools};
                use crate::team_message_router::TeamMessageRouter;
                let router = TeamMessageRouter::new(Arc::new(ctx.broker.clone()));
                let tools = TeamTools::new(
                    Arc::clone(s),
                    router,
                    ctx.broker.clone(),
                    ctx.agent_id.clone(),
                    ctx.agent_id.clone(),
                );
                BootResult::Registered(
                    TeamCreateTool::tool_def(),
                    Arc::new(TeamCreateTool::new(tools)),
                )
            }
            None => BootResult::SkippedInfraMissing {
                handle: "team_store",
            },
        },
        "TeamDelete" => match ctx.team_store.as_ref() {
            Some(s) => {
                use crate::agent::team_tools::{TeamDeleteTool, TeamTools};
                use crate::team_message_router::TeamMessageRouter;
                let router = TeamMessageRouter::new(Arc::new(ctx.broker.clone()));
                let tools = TeamTools::new(
                    Arc::clone(s),
                    router,
                    ctx.broker.clone(),
                    ctx.agent_id.clone(),
                    ctx.agent_id.clone(),
                );
                BootResult::Registered(
                    TeamDeleteTool::tool_def(),
                    Arc::new(TeamDeleteTool::new(tools)),
                )
            }
            None => BootResult::SkippedInfraMissing {
                handle: "team_store",
            },
        },
        "TeamSendMessage" => match ctx.team_store.as_ref() {
            Some(s) => {
                use crate::agent::team_tools::{TeamSendMessageTool, TeamTools};
                use crate::team_message_router::TeamMessageRouter;
                let router = TeamMessageRouter::new(Arc::new(ctx.broker.clone()));
                let tools = TeamTools::new(
                    Arc::clone(s),
                    router,
                    ctx.broker.clone(),
                    ctx.agent_id.clone(),
                    ctx.agent_id.clone(),
                );
                BootResult::Registered(
                    TeamSendMessageTool::tool_def(),
                    Arc::new(TeamSendMessageTool::new(tools)),
                )
            }
            None => BootResult::SkippedInfraMissing {
                handle: "team_store",
            },
        },

        // Catalog has the entry as Always but no boot helper exists yet —
        // should never trigger if EXPOSABLE_TOOLS and this match stay in
        // sync. Fail loud at runtime so a missing arm shows up in tests.
        other => BootResult::SkippedInfraMissing {
            handle: leak_arm(other),
        },
    }
}

// Stable string label for the "no helper for this Always entry"
// case. Returning a `&'static str` keeps the BootResult variant
// trivially `Copy`-shaped without leaking the missing-name string.
fn leak_arm(_name: &str) -> &'static str {
    "boot_helper_missing"
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::context::AgentContext;
    use crate::config_changes_store::{ConfigChangeRow, ConfigChangesError, ConfigChangesStore};
    use crate::cron_schedule::{CronEntry, CronStore, CronStoreError};
    use async_trait::async_trait;
    use nexo_broker::AnyBroker;

    fn fixture_ctx() -> McpServerBootContext {
        use nexo_config::types::agents::{
            AgentConfig, AgentRuntimeConfig, DreamingYamlConfig, HeartbeatConfig, ModelConfig,
            OutboundAllowlistConfig, WorkspaceGitConfig,
        };
        let cfg = AgentConfig {
            id: "a".into(),
            model: ModelConfig {
                provider: "x".into(),
                model: "y".into(),
            },
            plugins: Vec::new(),
            heartbeat: HeartbeatConfig::default(),
            config: AgentRuntimeConfig::default(),
            system_prompt: String::new(),
            workspace: String::new(),
            skills: Vec::new(),
            skills_dir: "./skills".into(),
            skill_overrides: Default::default(),
            transcripts_dir: String::new(),
            dreaming: DreamingYamlConfig::default(),
            workspace_git: WorkspaceGitConfig::default(),
            tool_rate_limits: None,
            tool_args_validation: None,
            extra_docs: Vec::new(),
            inbound_bindings: Vec::new(),
            allowed_tools: Vec::new(),
            sender_rate_limit: None,
            allowed_delegates: Vec::new(),
            accept_delegates_from: Vec::new(),
            description: String::new(),
            google_auth: None,
            credentials: Default::default(),
            link_understanding: serde_json::Value::Null,
            web_search: serde_json::Value::Null,
            pairing_policy: serde_json::Value::Null,
            language: None,
            locale_prompts: Default::default(),
            outbound_allowlist: OutboundAllowlistConfig::default(),
            context_optimization: None,
            dispatch_policy: Default::default(),
            plan_mode: Default::default(),
            remote_triggers: Vec::new(),
            lsp: nexo_config::types::lsp::LspPolicy::default(),
            config_tool: nexo_config::types::config_tool::ConfigToolPolicy::default(),
            team: nexo_config::types::team::TeamPolicy::default(),
            proactive: Default::default(),
            repl: Default::default(),
            auto_dream: None,
            assistant_mode: None,
            away_summary: None,
            brief: None,
            channels: None,
            auto_approve: false,
            extract_memories: None,
            event_subscribers: Vec::new(),
            tenant_id: None,
            extensions_config: std::collections::BTreeMap::new(),
            active: true,
        };
        let ctx = Arc::new(AgentContext::new(
            "a",
            Arc::new(cfg),
            AnyBroker::local(),
            Arc::new(crate::session::SessionManager::new(
                std::time::Duration::from_secs(60),
                8,
            )),
        ));
        McpServerBootContext::builder("a", AnyBroker::local(), ctx).build()
    }

    /// In-memory CronStore stub for tests.
    struct StubCron;
    #[async_trait]
    impl CronStore for StubCron {
        async fn insert(&self, _e: &CronEntry) -> Result<(), CronStoreError> {
            Ok(())
        }
        async fn list_by_binding(
            &self,
            _binding_id: &str,
        ) -> Result<Vec<CronEntry>, CronStoreError> {
            Ok(Vec::new())
        }
        async fn count_by_binding(&self, _binding_id: &str) -> Result<usize, CronStoreError> {
            Ok(0)
        }
        async fn delete(&self, _id: &str) -> Result<(), CronStoreError> {
            Ok(())
        }
        async fn due_at(&self, _now_unix: i64) -> Result<Vec<CronEntry>, CronStoreError> {
            Ok(Vec::new())
        }
        async fn set_paused(&self, _id: &str, _paused: bool) -> Result<(), CronStoreError> {
            Ok(())
        }
        async fn get(&self, _id: &str) -> Result<CronEntry, CronStoreError> {
            Err(CronStoreError::NotFound("stub".into()))
        }
        async fn advance_after_fire(
            &self,
            _id: &str,
            _new_next_fire_at: i64,
            _last_fired_at: i64,
        ) -> Result<(), CronStoreError> {
            Ok(())
        }
        async fn schedule_one_shot_retry(
            &self,
            _id: &str,
            _retry_next_fire_at: i64,
            _last_fired_at: i64,
        ) -> Result<u32, CronStoreError> {
            Ok(1)
        }
        async fn sweep_missed_entries(
            &self,
            _now_unix: i64,
            _skew_ms: i64,
        ) -> Result<usize, CronStoreError> {
            Ok(0)
        }
        async fn sweep_expired_recurring(
            &self,
            _now_unix: i64,
            _max_age_ms: i64,
        ) -> Result<usize, CronStoreError> {
            Ok(0)
        }
    }

    /// In-memory ConfigChangesStore stub for tests.
    struct StubConfigChanges;
    #[async_trait]
    impl ConfigChangesStore for StubConfigChanges {
        async fn record(&self, _row: &ConfigChangeRow) -> Result<(), ConfigChangesError> {
            Ok(())
        }
        async fn tail(&self, _n: usize) -> Result<Vec<ConfigChangeRow>, ConfigChangesError> {
            Ok(Vec::new())
        }
        async fn get(
            &self,
            _patch_id: &str,
        ) -> Result<Option<ConfigChangeRow>, ConfigChangesError> {
            Ok(None)
        }
    }

    // --- skeleton dispatcher tests (denied / deferred / feature_gate / unknown) ---

    #[tokio::test]
    async fn unknown_name_returns_unknown() {
        let bc = fixture_ctx();
        assert!(matches!(
            boot_exposable("nope", &bc),
            BootResult::UnknownName
        ));
    }

    #[tokio::test]
    async fn delegate_is_denied_by_policy() {
        let bc = fixture_ctx();
        match boot_exposable("delegate", &bc) {
            BootResult::SkippedDenied { reason } => {
                assert!(reason.contains("a2a"));
            }
            other => panic!("expected SkippedDenied, got {}", other.skip_reason()),
        }
    }

    #[tokio::test]
    async fn lsp_skips_without_manager() {
        let bc = fixture_ctx();
        match boot_exposable("Lsp", &bc) {
            BootResult::SkippedInfraMissing { handle } => {
                assert_eq!(handle, "lsp_manager");
            }
            other => panic!("expected SkippedInfraMissing, got {}", other.skip_reason()),
        }
    }

    #[cfg(feature = "config-self-edit")]
    #[tokio::test]
    async fn config_registers_with_full_handles() {
        use crate::agent::approval_correlator::{ApprovalCorrelator, ApprovalCorrelatorConfig};
        use crate::agent::config_tool::{
            DefaultSecretRedactor, DenylistChecker, PatchAppliedError, PatchInfo, ReloadTrigger,
            YamlPatchApplier,
        };
        use std::path::PathBuf;

        // Lightweight stubs so we don't depend on nexo-setup in tests.
        struct StubApplier;
        impl YamlPatchApplier for StubApplier {
            fn read(
                &self,
                _: &str,
                _: &str,
            ) -> Result<Option<serde_yaml::Value>, PatchAppliedError> {
                Ok(None)
            }
            fn apply(&self, _: &PatchInfo) -> Result<(), PatchAppliedError> {
                Ok(())
            }
            fn snapshot(&self) -> Result<Vec<u8>, PatchAppliedError> {
                Ok(Vec::new())
            }
            fn restore(&self, _: &[u8]) -> Result<(), PatchAppliedError> {
                Ok(())
            }
        }
        struct StubDenylist;
        impl DenylistChecker for StubDenylist {
            fn check(&self, _: &str) -> Option<&'static str> {
                None
            }
        }
        struct StubReload;
        #[async_trait]
        impl ReloadTrigger for StubReload {
            async fn reload(&self) -> Result<(), String> {
                Ok(())
            }
        }

        let bc_minimal = fixture_ctx();
        let ctx_arc = bc_minimal.agent_context.clone();
        let bc = McpServerBootContext::builder("a", AnyBroker::local(), ctx_arc)
            .config_changes_store(Arc::new(StubConfigChanges))
            .config_handles(
                Arc::new(StubApplier),
                Arc::new(StubDenylist),
                Arc::new(DefaultSecretRedactor),
                ApprovalCorrelator::new(ApprovalCorrelatorConfig::default()),
                Arc::new(StubReload),
                nexo_config::types::config_tool::ConfigToolPolicy::default(),
                PathBuf::from("/tmp/proposals"),
            )
            .build();
        match boot_exposable("Config", &bc) {
            BootResult::Registered(def, _) => assert_eq!(def.name, "Config"),
            other => panic!("expected Registered, got {}", other.skip_reason()),
        }
    }

    #[tokio::test]
    async fn config_is_feature_gated() {
        let bc = fixture_ctx();
        // When feature is OFF, Config returns SkippedFeatureGated.
        // When feature is ON, the boot helper still returns
        // SkippedInfraMissing because the empty fixture context
        // didn't carry any of the 7 Config handles. Both outcomes
        // confirm the gate is enforced.
        match boot_exposable("Config", &bc) {
            BootResult::SkippedFeatureGated { feature } => {
                assert_eq!(feature, "config-self-edit");
            }
            #[cfg(feature = "config-self-edit")]
            BootResult::SkippedInfraMissing { handle } => {
                assert!(
                    handle.starts_with("config_"),
                    "unexpected handle label: {handle}"
                );
            }
            other => panic!(
                "expected SkippedFeatureGated or SkippedInfraMissing(config_*), got {}",
                other.skip_reason()
            ),
        }
    }

    // --- step 5 — Always entries with no handle ---

    #[tokio::test]
    async fn enter_plan_mode_registers() {
        let bc = fixture_ctx();
        let r = boot_exposable("EnterPlanMode", &bc);
        match r {
            BootResult::Registered(def, _) => assert_eq!(def.name, "EnterPlanMode"),
            other => panic!("expected Registered, got {}", other.skip_reason()),
        }
    }

    #[tokio::test]
    async fn exit_plan_mode_registers() {
        let bc = fixture_ctx();
        let r = boot_exposable("ExitPlanMode", &bc);
        assert!(matches!(r, BootResult::Registered(..)));
    }

    #[tokio::test]
    async fn tool_search_registers() {
        let bc = fixture_ctx();
        let r = boot_exposable("ToolSearch", &bc);
        assert!(matches!(r, BootResult::Registered(..)));
    }

    #[tokio::test]
    async fn todo_write_registers() {
        let bc = fixture_ctx();
        assert!(matches!(
            boot_exposable("TodoWrite", &bc),
            BootResult::Registered(..)
        ));
    }

    #[tokio::test]
    async fn synthetic_output_registers() {
        let bc = fixture_ctx();
        assert!(matches!(
            boot_exposable("SyntheticOutput", &bc),
            BootResult::Registered(..)
        ));
    }

    #[tokio::test]
    async fn notebook_edit_registers() {
        let bc = fixture_ctx();
        assert!(matches!(
            boot_exposable("NotebookEdit", &bc),
            BootResult::Registered(..)
        ));
    }

    // --- step 6 — cron_* ---

    #[tokio::test]
    async fn cron_create_skips_when_no_store() {
        let bc = fixture_ctx();
        match boot_exposable("cron_create", &bc) {
            BootResult::SkippedInfraMissing { handle } => assert_eq!(handle, "cron_store"),
            other => panic!("expected SkippedInfraMissing, got {}", other.skip_reason()),
        }
    }

    #[tokio::test]
    async fn cron_create_registers_with_store() {
        use nexo_config::types::agents::{
            AgentConfig, AgentRuntimeConfig, DreamingYamlConfig, HeartbeatConfig, ModelConfig,
            OutboundAllowlistConfig, WorkspaceGitConfig,
        };
        let cfg = AgentConfig {
            id: "a".into(),
            model: ModelConfig {
                provider: "x".into(),
                model: "y".into(),
            },
            plugins: Vec::new(),
            heartbeat: HeartbeatConfig::default(),
            config: AgentRuntimeConfig::default(),
            system_prompt: String::new(),
            workspace: String::new(),
            skills: Vec::new(),
            skills_dir: "./skills".into(),
            skill_overrides: Default::default(),
            transcripts_dir: String::new(),
            dreaming: DreamingYamlConfig::default(),
            workspace_git: WorkspaceGitConfig::default(),
            tool_rate_limits: None,
            tool_args_validation: None,
            extra_docs: Vec::new(),
            inbound_bindings: Vec::new(),
            allowed_tools: Vec::new(),
            sender_rate_limit: None,
            allowed_delegates: Vec::new(),
            accept_delegates_from: Vec::new(),
            description: String::new(),
            google_auth: None,
            credentials: Default::default(),
            link_understanding: serde_json::Value::Null,
            web_search: serde_json::Value::Null,
            pairing_policy: serde_json::Value::Null,
            language: None,
            locale_prompts: Default::default(),
            outbound_allowlist: OutboundAllowlistConfig::default(),
            context_optimization: None,
            dispatch_policy: Default::default(),
            plan_mode: Default::default(),
            remote_triggers: Vec::new(),
            lsp: nexo_config::types::lsp::LspPolicy::default(),
            config_tool: nexo_config::types::config_tool::ConfigToolPolicy::default(),
            team: nexo_config::types::team::TeamPolicy::default(),
            proactive: Default::default(),
            repl: Default::default(),
            auto_dream: None,
            assistant_mode: None,
            away_summary: None,
            brief: None,
            channels: None,
            auto_approve: false,
            extract_memories: None,
            event_subscribers: Vec::new(),
            tenant_id: None,
            extensions_config: std::collections::BTreeMap::new(),
            active: true,
        };
        let actx = Arc::new(AgentContext::new(
            "a",
            Arc::new(cfg),
            AnyBroker::local(),
            Arc::new(crate::session::SessionManager::new(
                std::time::Duration::from_secs(60),
                8,
            )),
        ));
        let bc = McpServerBootContext::builder("a", AnyBroker::local(), actx)
            .cron_store(Arc::new(StubCron))
            .build();
        match boot_exposable("cron_create", &bc) {
            BootResult::Registered(def, _) => assert_eq!(def.name, "cron_create"),
            other => panic!("expected Registered, got {}", other.skip_reason()),
        }
    }

    #[tokio::test]
    async fn cron_list_skips_when_no_store() {
        let bc = fixture_ctx();
        assert!(matches!(
            boot_exposable("cron_list", &bc),
            BootResult::SkippedInfraMissing {
                handle: "cron_store"
            }
        ));
    }

    #[tokio::test]
    async fn cron_delete_pause_resume_all_skip_without_store() {
        let bc = fixture_ctx();
        for name in ["cron_delete", "cron_pause", "cron_resume"] {
            assert!(
                matches!(
                    boot_exposable(name, &bc),
                    BootResult::SkippedInfraMissing {
                        handle: "cron_store"
                    }
                ),
                "expected skip for {name}"
            );
        }
    }

    // --- step 7 — mcp_router ---

    #[tokio::test]
    async fn mcp_router_skips_without_runtime() {
        let bc = fixture_ctx();
        for name in ["ListMcpResources", "ReadMcpResource"] {
            assert!(
                matches!(
                    boot_exposable(name, &bc),
                    BootResult::SkippedInfraMissing {
                        handle: "mcp_runtime"
                    }
                ),
                "expected skip for {name}"
            );
        }
    }

    // --- step 8 — config_changes_tail ---

    #[tokio::test]
    async fn config_changes_tail_skips_without_store() {
        let bc = fixture_ctx();
        assert!(matches!(
            boot_exposable("config_changes_tail", &bc),
            BootResult::SkippedInfraMissing {
                handle: "config_changes_store"
            }
        ));
    }

    #[tokio::test]
    async fn config_changes_tail_registers_with_store() {
        use nexo_config::types::agents::{
            AgentConfig, AgentRuntimeConfig, DreamingYamlConfig, HeartbeatConfig, ModelConfig,
            OutboundAllowlistConfig, WorkspaceGitConfig,
        };
        let cfg = AgentConfig {
            id: "a".into(),
            model: ModelConfig {
                provider: "x".into(),
                model: "y".into(),
            },
            plugins: Vec::new(),
            heartbeat: HeartbeatConfig::default(),
            config: AgentRuntimeConfig::default(),
            system_prompt: String::new(),
            workspace: String::new(),
            skills: Vec::new(),
            skills_dir: "./skills".into(),
            skill_overrides: Default::default(),
            transcripts_dir: String::new(),
            dreaming: DreamingYamlConfig::default(),
            workspace_git: WorkspaceGitConfig::default(),
            tool_rate_limits: None,
            tool_args_validation: None,
            extra_docs: Vec::new(),
            inbound_bindings: Vec::new(),
            allowed_tools: Vec::new(),
            sender_rate_limit: None,
            allowed_delegates: Vec::new(),
            accept_delegates_from: Vec::new(),
            description: String::new(),
            google_auth: None,
            credentials: Default::default(),
            link_understanding: serde_json::Value::Null,
            web_search: serde_json::Value::Null,
            pairing_policy: serde_json::Value::Null,
            language: None,
            locale_prompts: Default::default(),
            outbound_allowlist: OutboundAllowlistConfig::default(),
            context_optimization: None,
            dispatch_policy: Default::default(),
            plan_mode: Default::default(),
            remote_triggers: Vec::new(),
            lsp: nexo_config::types::lsp::LspPolicy::default(),
            config_tool: nexo_config::types::config_tool::ConfigToolPolicy::default(),
            team: nexo_config::types::team::TeamPolicy::default(),
            proactive: Default::default(),
            repl: Default::default(),
            auto_dream: None,
            assistant_mode: None,
            away_summary: None,
            brief: None,
            channels: None,
            auto_approve: false,
            extract_memories: None,
            event_subscribers: Vec::new(),
            tenant_id: None,
            extensions_config: std::collections::BTreeMap::new(),
            active: true,
        };
        let actx = Arc::new(AgentContext::new(
            "a",
            Arc::new(cfg),
            AnyBroker::local(),
            Arc::new(crate::session::SessionManager::new(
                std::time::Duration::from_secs(60),
                8,
            )),
        ));
        let bc = McpServerBootContext::builder("a", AnyBroker::local(), actx)
            .config_changes_store(Arc::new(StubConfigChanges))
            .build();
        match boot_exposable("config_changes_tail", &bc) {
            BootResult::Registered(def, _) => assert_eq!(def.name, "config_changes_tail"),
            other => panic!("expected Registered, got {}", other.skip_reason()),
        }
    }

    // --- step 9 — web_search + web_fetch ---

    #[tokio::test]
    async fn web_search_skips_without_subprocess_plugin() {
        // Phase 95 — web_search now served by the
        // `nexo-rs-plugin-web-search` subprocess. MCP bridge
        // dispatch surfaces "subprocess not installed" as the
        // missing-infra reason.
        let bc = fixture_ctx();
        assert!(matches!(
            boot_exposable("web_search", &bc),
            BootResult::SkippedInfraMissing {
                handle: "web_search_subprocess_plugin"
            }
        ));
    }

    #[tokio::test]
    async fn web_fetch_registers_standalone() {
        let bc = fixture_ctx();
        match boot_exposable("web_fetch", &bc) {
            BootResult::Registered(def, _) => assert_eq!(def.name, "web_fetch"),
            other => panic!("expected Registered, got {}", other.skip_reason()),
        }
    }
}