clawft-core 0.8.3

Core engine for clawft (agent loop, message bus, context management)
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
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
//! Application bootstrap and dependency wiring.
//!
//! Provides [`AppContext`], a convenience struct that initializes all
//! core components from a [`Config`] and a [`Platform`], then produces
//! an [`AgentLoop`] ready to run.
//!
//! # Usage
//!
//! ```rust,ignore
//! use clawft_core::bootstrap::AppContext;
//! use clawft_platform::NativePlatform;
//! use clawft_types::config::Config;
//!
//! let config = Config::default();
//! let platform = Arc::new(NativePlatform::new());
//! let ctx = AppContext::new(config, platform).await?;
//! let agent_loop = ctx.into_agent_loop();
//! agent_loop.run().await?;
//! ```

use std::sync::Arc;

use tracing::{debug, info};

use clawft_platform::Platform;
use clawft_types::config::Config;
use clawft_types::routing::RoutingConfig;

use crate::agent::context::ContextBuilder;
use crate::agent::loop_core::{AgentLoop, AutoDelegation};
use crate::agent::memory::MemoryStore;
use crate::agent::skills::SkillsLoader;
use crate::bus::MessageBus;
use crate::pipeline::assembler::TokenBudgetAssembler;
use crate::pipeline::classifier::KeywordClassifier;
use crate::pipeline::cost_tracker::CostTracker;
use crate::pipeline::rate_limiter::RateLimiter;
use crate::pipeline::router::StaticRouter;
use crate::pipeline::tiered_router::TieredRouter;
use crate::pipeline::traits::{ModelRouter, Pipeline, PipelineRegistry};
use crate::pipeline::transport::OpenAiCompatTransport;
use crate::session::SessionManager;
use crate::tools::registry::ToolRegistry;

/// Fully initialized application context.
///
/// Holds all dependencies needed to run the agent loop. Created via
/// [`AppContext::new`] and consumed via [`AppContext::into_agent_loop`].
///
/// The generic parameter `P` is the platform implementation (e.g.
/// [`NativePlatform`](clawft_platform::NativePlatform) for native,
/// a WASM platform for browser environments).
pub struct AppContext<P: Platform> {
    /// Root configuration.
    config: Config,

    /// Platform abstraction.
    platform: Arc<P>,

    /// Message bus for inbound/outbound message routing.
    bus: Arc<MessageBus>,

    /// Session manager for conversation persistence.
    sessions: Arc<SessionManager<P>>,

    /// Tool registry with registered tools.
    tools: Arc<ToolRegistry>,

    /// Pipeline registry with all 6 stages wired.
    pipeline: PipelineRegistry,

    /// Context builder for assembling LLM prompts.
    context: ContextBuilder<P>,

    /// Shared memory store reference (for external access).
    memory: Arc<MemoryStore<P>>,

    /// Shared skills loader reference (for external access).
    skills: Arc<SkillsLoader<P>>,

    /// Optional auto-delegation router for pre-LLM routing.
    auto_delegation: Option<Arc<dyn AutoDelegation>>,

    /// Optional inbound-message → agent router.
    ///
    /// Routes incoming [`InboundMessage`](clawft_types::event::InboundMessage)s
    /// to a specific agent persona based on channel/user rules. Not
    /// used by the single-agent CLI flow today; consumed by the
    /// daemon's multi-agent dispatcher when set.
    agent_router: Option<Arc<crate::agent_routing::AgentRouter>>,

    /// Optional agent-to-agent message bus.
    ///
    /// Provides per-agent inboxes with TTL enforcement and
    /// inbox-scoped delivery. The CLI runs a single agent so doesn't
    /// need it, but multi-agent hosts (the daemon's spawn manager)
    /// register each spawned agent and route IPC through the bus.
    #[cfg(feature = "native")]
    agent_bus: Option<Arc<crate::agent_bus::AgentBus>>,

    /// Global (system-wide) routing used as the PermissionResolver ceiling.
    ///
    /// When set via [`AppContext::with_routing_layers`], this is the
    /// unmerged global layer from the config loader. When `None`,
    /// `config.routing` is used as the sole routing source (legacy /
    /// single-tenant path with no workspace ceiling).
    global_routing: Option<RoutingConfig>,

    /// Workspace overlay routing for PermissionResolver (WEFT-10).
    ///
    /// When `Some`, `PermissionResolver::new(global, Some(workspace))`
    /// runs `enforce_workspace_ceiling` so elevated workspace grants
    /// are clamped to system-wide bounds.
    workspace_routing: Option<RoutingConfig>,
}

impl<P: Platform> AppContext<P> {
    /// Initialize all components from configuration and platform.
    ///
    /// This is the primary constructor. It:
    /// 1. Creates the [`MessageBus`]
    /// 2. Initializes the [`SessionManager`] (discovers/creates sessions dir)
    /// 3. Initializes the [`MemoryStore`] (discovers memory dir)
    /// 4. Initializes the [`SkillsLoader`] (discovers skills dir)
    /// 5. Creates the [`ContextBuilder`]
    /// 6. Creates an empty [`ToolRegistry`] (caller registers tools after)
    /// 7. Wires the default Level 0 pipeline (keyword classifier, static
    ///    router, token budget assembler, stub transport, noop scorer,
    ///    noop learner)
    ///
    /// # Errors
    ///
    /// Returns [`ClawftError`] if the home directory cannot be determined
    /// or the sessions directory cannot be created.
    pub async fn new(config: Config, platform: Arc<P>) -> clawft_types::Result<Self> {
        info!("bootstrapping application context");

        // 1. Message bus
        let bus = Arc::new(MessageBus::new());
        debug!("message bus created");

        // 2. Session manager
        let sessions = SessionManager::new(platform.clone()).await?;
        debug!("session manager initialized");

        // 3. Memory store — WEFT-79: route through workspace overlay
        //    when present (.clawft/ in cwd or ancestor) so kernel
        //    persists into the workspace's `.clawft/memory/` instead
        //    of the global `~/.clawft/workspace/memory/`. Mirrors the
        //    cwd-relative config overlay (Layer 3).
        let memory = match crate::workspace::discover_workspace() {
            Some(ws_root) if ws_root.join(".clawft").is_dir() => {
                debug!(
                    workspace = %ws_root.display(),
                    "routing memory through workspace overlay"
                );
                Arc::new(MemoryStore::for_workspace(&ws_root, platform.clone()))
            }
            _ => Arc::new(MemoryStore::new(platform.clone())?),
        };
        debug!(
            memory_path = %memory.memory_path().display(),
            "memory store initialized"
        );

        // 4. Skills loader — same workspace-overlay routing as memory.
        let mut skills_loader = match crate::workspace::discover_workspace() {
            Some(ws_root) if ws_root.join(".clawft").is_dir() => {
                debug!(
                    workspace = %ws_root.display(),
                    "routing skills through workspace overlay"
                );
                SkillsLoader::for_workspace(&ws_root, platform.clone())
            }
            _ => SkillsLoader::new(platform.clone())?,
        };

        // Also scan extra `skills/` directories if they exist:
        // - workspace/skills/  (from config workspace path)
        // - ./skills/          (current working directory)
        for candidate in [
            config.workspace_path().join("skills"),
            std::env::current_dir().unwrap_or_default().join("skills"),
        ] {
            if candidate.is_dir() {
                skills_loader.add_extra_dir(candidate);
            }
        }

        let skills = Arc::new(skills_loader);
        debug!(
            skills_dir = %skills.skills_dir().display(),
            "skills loader initialized"
        );

        // 5. Context builder
        let context = ContextBuilder::new(
            config.agents.clone(),
            memory.clone(),
            skills.clone(),
            platform.clone(),
        );
        debug!("context builder created");

        // 6. Tool registry (empty -- caller adds tools)
        let tools = Arc::new(ToolRegistry::new());

        // 7. Default Level 0 pipeline
        let pipeline = build_default_pipeline(&config);
        debug!("default pipeline wired");

        info!("bootstrap complete");

        Ok(Self {
            config,
            platform,
            bus,
            sessions: Arc::new(sessions),
            tools,
            pipeline,
            context,
            memory,
            skills,
            auto_delegation: None,
            agent_router: None,
            #[cfg(feature = "native")]
            agent_bus: None,
            global_routing: None,
            workspace_routing: None,
        })
    }

    /// Attach split routing layers for PermissionResolver ceiling (WEFT-10).
    ///
    /// Call after [`AppContext::new`] when the config loader returned
    /// separate global / workspace layers. `global` is the system-wide
    /// ceiling; `workspace` is the optional overlay that will be clamped.
    pub fn with_routing_layers(
        mut self,
        global: RoutingConfig,
        workspace: Option<RoutingConfig>,
    ) -> Self {
        if let Some(ref ws) = workspace {
            let violations =
                crate::pipeline::permissions::PermissionResolver::validate_workspace_ceiling(
                    &global, ws,
                );
            if !violations.is_empty() {
                tracing::warn!(
                    violations = ?violations,
                    "workspace routing exceeds global permission ceiling; \
                     elevated grants will be silently clamped at resolve time"
                );
            }
        }
        self.global_routing = Some(global);
        self.workspace_routing = workspace;
        self
    }

    /// Consume the context and produce a running [`AgentLoop`].
    ///
    /// All dependencies are moved into the agent loop. After this call,
    /// the `AppContext` is consumed and cannot be reused.
    pub fn into_agent_loop(self) -> AgentLoop<P>
    where
        P: 'static,
    {
        // WEFT-10: prefer split layers so enforce_workspace_ceiling runs.
        // Fall back to config.routing alone (no ceiling) when the caller
        // did not attach layers — preserves single-tenant / test behaviour.
        let global = self
            .global_routing
            .as_ref()
            .unwrap_or(&self.config.routing);
        let resolver = crate::pipeline::permissions::PermissionResolver::new(
            global,
            self.workspace_routing.as_ref(),
        );
        // M3 store collapse (design §D4): the in-process / no-daemon path
        // gets a real durable sink instead of the no-op `InMemorySink`
        // default. `LocalFileSink` reads and writes the **same**
        // `~/.clawft/workspace/sessions/{key}.jsonl` files `SessionManager`
        // used — reusing the directory `SessionManager` already discovered —
        // so the collapse keeps in-process durability through one store with
        // zero migration. The daemon path attaches its substrate-backed sink
        // via `build_daemon_agent_loop`.
        let sink = Arc::new(crate::agent::local_file_sink::LocalFileSink::with_dir(
            self.platform.clone(),
            self.sessions.sessions_dir().clone(),
        ));
        let mut agent = AgentLoop::new(
            self.config.agents,
            self.platform,
            self.bus,
            self.pipeline,
            self.tools.clone(),
            self.context,
            resolver,
        )
        .with_sink(sink);
        if let Some(delegation) = self.auto_delegation {
            agent = agent.with_auto_delegation(delegation);
        }
        agent
    }

    /// Get a reference to the root configuration.
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// Get a reference to the platform.
    pub fn platform(&self) -> &Arc<P> {
        &self.platform
    }

    /// Get a reference to the message bus.
    ///
    /// Channel adapters should clone the inbound sender from here
    /// before the context is consumed by [`into_agent_loop`].
    pub fn bus(&self) -> &Arc<MessageBus> {
        &self.bus
    }

    /// Get a mutable reference to the tool registry.
    ///
    /// Call this to register tools before converting to an agent loop.
    ///
    /// # Panics
    ///
    /// Panics if Arc clones have already been taken (e.g. via `tools_arc()`).
    /// Always call `tools_mut()` for registration *before* sharing the registry.
    pub fn tools_mut(&mut self) -> &mut ToolRegistry {
        Arc::get_mut(&mut self.tools)
            .expect("tools already shared -- register tools before cloning Arc")
    }

    /// Get a reference to the tool registry.
    pub fn tools(&self) -> &Arc<ToolRegistry> {
        &self.tools
    }

    /// Get a clone of the `Arc<ToolRegistry>` for sharing with other components.
    pub fn tools_arc(&self) -> Arc<ToolRegistry> {
        self.tools.clone()
    }

    /// Get a reference to the session manager.
    pub fn sessions(&self) -> &Arc<SessionManager<P>> {
        &self.sessions
    }

    /// Get a reference to the shared memory store.
    pub fn memory(&self) -> &Arc<MemoryStore<P>> {
        &self.memory
    }

    /// Get a reference to the shared skills loader.
    pub fn skills(&self) -> &Arc<SkillsLoader<P>> {
        &self.skills
    }

    /// Start a [`SkillWatcher`](crate::agent::skill_watcher::start_watching)
    /// over the same directories the [`SkillsLoader`] scans.
    ///
    /// Returns a handle that the caller MUST keep alive for the
    /// duration of the agent loop — dropping it stops the watcher.
    /// Returns `None` when the underlying file-system watcher could
    /// not be started (e.g. inotify quota exhausted); the agent loop
    /// still runs, just without hot-reload.
    ///
    /// The watcher is opt-in: bootstrap does NOT start it
    /// automatically because the agent loop's existing reads go
    /// through `SkillsLoader` which is already responsive to disk
    /// changes on the cold path. Hot-reload via this watcher reflects
    /// changes into a parallel `SkillRegistry` (v2) that's
    /// non-disruptively available for callers that want it.
    ///
    /// Native-only: the `notify` crate doesn't compile to wasm.
    #[cfg(feature = "native")]
    pub async fn start_skill_watcher(
        &self,
    ) -> Option<crate::agent::skill_watcher::SkillWatcherHandle> {
        use std::sync::Arc as ArcAlias;
        use tokio::sync::RwLock;

        use crate::agent::skill_watcher::{SkillWatcherConfig, start_watching};
        use crate::agent::skills_v2::SkillRegistry;

        let workspace_dir = Some(self.skills.skills_dir().clone());
        let registry = match SkillRegistry::discover(workspace_dir.as_deref(), None, vec![]).await {
            Ok(r) => ArcAlias::new(RwLock::new(r)),
            Err(e) => {
                tracing::warn!(error = %e, "skill watcher: initial discover failed; not starting");
                return None;
            }
        };

        let config = SkillWatcherConfig {
            workspace_dir: workspace_dir.clone(),
            user_dir: None,
            extra_dirs: Vec::new(),
            debounce: std::time::Duration::from_millis(500),
            builtin_skills: Vec::new(),
            trust_workspace: true,
        };

        match start_watching(config, registry) {
            Ok(handle) => {
                tracing::info!(
                    skills_dir = %self.skills.skills_dir().display(),
                    "skill hot-reload watcher started"
                );
                Some(handle)
            }
            Err(e) => {
                tracing::warn!(error = %e, "failed to start skill watcher");
                None
            }
        }
    }

    /// Set an auto-delegation router for pre-LLM routing.
    ///
    /// When set, inbound messages are checked against delegation rules
    /// before the local LLM is invoked. Matching messages are routed
    /// directly to `delegate_task`.
    pub fn set_auto_delegation(&mut self, delegation: Arc<dyn AutoDelegation>) {
        self.auto_delegation = Some(delegation);
    }

    /// Attach an [`AgentRouter`](crate::agent_routing::AgentRouter)
    /// for inbound-message-to-agent routing. Multi-agent dispatchers
    /// (e.g. the daemon) consume this; the single-agent CLI flow
    /// ignores it.
    pub fn set_agent_router(&mut self, router: Arc<crate::agent_routing::AgentRouter>) {
        self.agent_router = Some(router);
    }

    /// Borrow the optional agent router. `None` means there's no
    /// multi-agent routing layer in front of the loop.
    pub fn agent_router(&self) -> Option<&Arc<crate::agent_routing::AgentRouter>> {
        self.agent_router.as_ref()
    }

    /// Attach a shared [`AgentBus`](crate::agent_bus::AgentBus). The
    /// daemon's agent supervisor registers each spawned agent with
    /// this bus so A2A messaging is inbox-scoped.
    #[cfg(feature = "native")]
    pub fn set_agent_bus(&mut self, bus: Arc<crate::agent_bus::AgentBus>) {
        self.agent_bus = Some(bus);
    }

    /// Construct and attach an [`AgentBus`](crate::agent_bus::AgentBus)
    /// if one is not already set (WEFT-185 production wiring).
    ///
    /// Uses `capacity` when provided; otherwise the bus default (256).
    /// Returns a clone of the live bus handle so callers can spawn
    /// worker loops or build a [`SwarmCoordinator`](crate::agent_bus::SwarmCoordinator).
    #[cfg(feature = "native")]
    pub fn enable_agent_bus(&mut self, capacity: Option<usize>) -> Arc<crate::agent_bus::AgentBus> {
        if let Some(bus) = self.agent_bus.as_ref() {
            return bus.clone();
        }
        let bus = Arc::new(match capacity {
            Some(c) => crate::agent_bus::AgentBus::with_capacity(c),
            None => crate::agent_bus::AgentBus::new(),
        });
        self.agent_bus = Some(bus.clone());
        info!(
            capacity = bus.inbox_capacity(),
            "agent bus enabled (WEFT-185)"
        );
        bus
    }

    /// Borrow the optional agent bus. `None` means A2A messaging is
    /// disabled (single-agent process).
    #[cfg(feature = "native")]
    pub fn agent_bus(&self) -> Option<&Arc<crate::agent_bus::AgentBus>> {
        self.agent_bus.as_ref()
    }

    /// Replace the pipeline registry with a custom one.
    ///
    /// Use this to inject a transport backed by a real LLM provider
    /// or to register specialized pipelines for specific task types.
    pub fn set_pipeline(&mut self, pipeline: PipelineRegistry) {
        self.pipeline = pipeline;
    }

    /// Active pipeline [`TrajectoryLearner`](crate::pipeline::learner::TrajectoryLearner)
    /// when stage 6 is trajectory mode (WEFT-66).
    ///
    /// Call before [`Self::into_agent_loop`] so skill autogen can share the
    /// same ring buffer the pipeline records into.
    pub fn trajectory_learner(
        &self,
    ) -> Option<Arc<crate::pipeline::learner::TrajectoryLearner>> {
        self.pipeline.trajectory_learner().cloned()
    }

    /// Shared last-N pipeline routing decision history (WEFT-40).
    ///
    /// Pass the same `Arc` into the admin API state so
    /// `GET /api/admin/routing/decisions` reflects live gateway traffic.
    pub fn decision_history(
        &self,
    ) -> Arc<crate::pipeline::decision_history::RoutingDecisionHistory> {
        self.pipeline.decision_history().clone()
    }

    /// Replace the pipeline with a live LLM-backed pipeline.
    ///
    /// Convenience method that calls [`build_live_pipeline`] and sets it
    /// as the active pipeline, enabling real LLM calls through the
    /// `clawft-llm` provider resolved from configuration.
    ///
    /// Only available with the `native` feature.
    #[cfg(feature = "native")]
    pub fn enable_live_llm(&mut self) {
        let pipeline = build_live_pipeline(&self.config);
        self.set_pipeline(pipeline);
    }
}

/// Build a live pipeline with a real LLM provider from configuration.
///
/// Uses [`ClawftLlmAdapter`](crate::pipeline::llm_adapter::ClawftLlmAdapter)
/// to bridge `clawft-llm` providers into the pipeline's transport layer,
/// enabling real LLM calls.
///
/// This is the production counterpart of [`build_default_pipeline`], which
/// uses a stub transport. All other pipeline stages are identical.
///
/// Only available with the `native` feature (requires clawft-llm HTTP providers).
#[cfg(feature = "native")]
pub fn build_live_pipeline(config: &Config) -> PipelineRegistry {
    crate::pipeline::llm_adapter::build_live_pipeline(config)
}

/// Build the default pipeline from configuration.
///
/// Uses the appropriate router based on `config.routing.mode`:
/// - `"tiered"` -> [`TieredRouter`] with cost tracking and rate limiting
/// - `"static"` (default) -> [`StaticRouter`] from config defaults
///
/// Other stages: [`KeywordClassifier`], [`TokenBudgetAssembler`],
/// [`OpenAiCompatTransport`] wired with [`ServiceLlmAdapter`] against
/// the local llama-server resolved from
/// [`LlmConfig::from_env`](clawft_service_llm::LlmConfig::from_env)
/// (so the agent loop, the daemon's `llm.prompt` RPC, and the chat
/// panel all share one model server), [`NoopScorer`], [`NoopLearner`].
///
/// On `LlmClient` construction failure (e.g. malformed env URL) the
/// transport falls back to the no-provider stub so the rest of the
/// pipeline still wires; the agent will surface a clear error on the
/// first call.
///
/// Browser builds keep the original stubbed transport — service-llm
/// pulls in `reqwest` and is native-only.
fn build_default_pipeline(config: &Config) -> PipelineRegistry {
    let classifier = Arc::new(KeywordClassifier::new());
    let router: Arc<dyn ModelRouter> = build_router_from_config(config);
    let assembler = Arc::new(TokenBudgetAssembler::new(
        config.agents.defaults.max_tokens.max(1) as usize,
    ));
    let transport = build_default_transport();
    let scorer = crate::pipeline::build_scorer(&config.pipeline);
    let (learner, trajectory) = crate::pipeline::build_learner_parts(&config.pipeline);

    let pipeline = Pipeline {
        classifier,
        router,
        assembler,
        transport,
        scorer,
        learner,
    };

    // WEFT-66: keep the concrete TrajectoryLearner handle so skill
    // autogen can share the same trajectory ring buffer.
    let mut registry = PipelineRegistry::new(pipeline);
    if let Some(t) = trajectory {
        registry = registry.with_trajectory_learner(t);
    }
    registry
}

/// Native: wrap a [`ServiceLlmAdapter`] over a freshly-constructed
/// [`LlmClient`] from the env-resolved config. Falls back to the stub
/// transport if the client cannot be built (e.g. invalid base URL).
#[cfg(feature = "native")]
fn build_default_transport() -> Arc<OpenAiCompatTransport> {
    use clawft_service_llm::{LlmClient, LlmConfig};

    use crate::pipeline::service_llm_adapter::ServiceLlmAdapter;
    use crate::pipeline::transport::LlmProvider;

    let llm_config = LlmConfig::from_env();
    match LlmClient::new(llm_config) {
        Ok(client) => {
            let adapter: Arc<dyn LlmProvider> = Arc::new(ServiceLlmAdapter::from_client(client));
            tracing::info!(
                "pipeline: transport wired to clawft-service-llm (LlmClient over llama-server)"
            );
            Arc::new(OpenAiCompatTransport::with_provider(adapter))
        }
        Err(e) => {
            tracing::warn!(
                error = %e,
                "pipeline: failed to construct LlmClient — falling back to stub transport"
            );
            Arc::new(OpenAiCompatTransport::new())
        }
    }
}

/// Browser: stub transport (service-llm pulls reqwest, native-only).
#[cfg(not(feature = "native"))]
fn build_default_transport() -> Arc<OpenAiCompatTransport> {
    Arc::new(OpenAiCompatTransport::new())
}

/// Build a pipeline whose transport is wired to a [`BrowserLlmClient`]
/// via [`BrowserLlmAdapter`](crate::pipeline::browser_llm_adapter::BrowserLlmAdapter).
///
/// All other stages (classifier, router, assembler, scorer, learner)
/// match [`build_default_pipeline`] so the browser path runs through
/// the same 6-stage shape as the native path. Used by the
/// `clawft-wasm` browser entry to wire `AgentLoop<BrowserPlatform>`
/// end-to-end through the pipeline (W-BROWSER P0.1).
#[cfg(feature = "browser")]
pub fn build_browser_pipeline(
    config: &Config,
    client: Arc<clawft_llm::browser_transport::BrowserLlmClient>,
) -> PipelineRegistry {
    use crate::pipeline::browser_llm_adapter::BrowserLlmAdapter;
    use crate::pipeline::transport::LlmProvider;

    let adapter: Arc<dyn LlmProvider> = Arc::new(BrowserLlmAdapter::new(client));
    let transport = Arc::new(OpenAiCompatTransport::with_provider(adapter));
    let classifier = Arc::new(KeywordClassifier::new());
    let router: Arc<dyn ModelRouter> = build_router_from_config(config);
    let assembler = Arc::new(TokenBudgetAssembler::new(
        config.agents.defaults.max_tokens.max(1) as usize,
    ));
    let scorer = crate::pipeline::build_scorer(&config.pipeline);
    let (learner, trajectory) = crate::pipeline::build_learner_parts(&config.pipeline);
    let mut registry = PipelineRegistry::new(Pipeline {
        classifier,
        router,
        assembler,
        transport,
        scorer,
        learner,
    });
    if let Some(t) = trajectory {
        registry = registry.with_trajectory_learner(t);
    }
    registry
}

/// Construct an [`AgentLoop`] suitable for daemon-side hosting via
/// `clawft-service-agent::AgentService`.
///
/// This is a thin factory used by `clawft-weave::daemon` (Phase C2 of
/// `docs/plans/agent-core-v1.md`). It accepts the handles the daemon
/// already has on hand — an `LlmClient`, a populated `ToolRegistry`,
/// an `IdentityLoader`, and a workspace path — and wires the rest
/// (message bus, session manager, context builder, pipeline) with
/// daemon-flavored defaults:
///
/// - `Config::default()` agents config (the daemon's chat path doesn't
///   need the workspace `Config` — `agent.chat`'s temperature/max_tokens
///   come from the wire params).
/// - A pipeline registry whose transport is wired to the supplied
///   [`LlmClient`] via [`ServiceLlmAdapter`](crate::pipeline::service_llm_adapter::ServiceLlmAdapter)
///   so the agent loop, the daemon's `llm.prompt` RPC, and the chat
///   panel all share one model server.
/// - `NullRouter` default (Phase B1). Phase E1 swaps in
///   `LlmClassifierRouter`.
/// - `gate`: caller-supplied [`EffectGate`](crate::agent::gate::EffectGate).
///   `None` falls back to [`NoopGate`](crate::agent::gate::NoopGate)
///   (always-permit, Phase B2 default). Phase D2's daemon construction
///   site passes `Some(KernelEffectGate)` so every tool dispatch in
///   `agent.chat` gets audited via
///   `clawft_kernel::GovernanceGate::check`. See `agent-core-v1.md`
///   Phase D2.
/// - `agent_id`: caller-supplied daemon agent id used by every
///   `gate.check` call when the inbound message has no per-turn
///   `gate_agent_id` metadata. `None` keeps the pre-D2 behaviour of
///   synthesizing `"{channel}:{sender_id}"` from the inbound message.
///   Phase D2's daemon construction site registers a concierge
///   principal in `clawft-kernel::AgentRegistry` at boot and threads
///   the resulting id through here as the single-tenant fallback.
///   WEFT-332 multi-tenant chat stamps a per-caller principal into
///   inbound metadata (via `AgentService::with_caller_registry`),
///   which wins over this boot-time default.
/// - `sink`: caller-supplied [`ConversationSink`](crate::agent::sink::ConversationSink).
///   `None` falls back to the in-memory sink (the C1/C2 default). The
///   C3 daemon construction site passes `Some(SubstrateConversationSink)`
///   so per-turn JSONL lands in substrate; CLI/test bootstrap callers
///   pass `None`. See `agent-core-v1.md` Phase C3.
/// - `identity_provider`: caller-supplied
///   [`IdentityProvider`](crate::agent::identity::IdentityProvider).
///   When `Some`, this factory wraps it in a
///   [`SystemPromptBuilder`](crate::agent::system_prompt::SystemPromptBuilder)
///   and attaches it to the loop so each turn emits an identity-aware
///   leading system message (agent-core-v1 Phase D1). When `None`, the
///   loop falls back to the legacy `ContextBuilder`-only system prompt
///   so existing CLI / test callers see no behaviour change.
/// - `context_router`: caller-supplied
///   [`ContextRouter`](crate::agent::context_router::ContextRouter)
///   (agent-core-v1 Phase E1). When `Some`, the loop consults it
///   *before* the LLM call to nudge classification and surface an
///   archetype label. When `None`, the loop falls back to its
///   `NullRouter` default so v0 behaviour is preserved bit-for-bit.
///   The daemon construction site picks between
///   `Arc::new(NullRouter)` and
///   `Arc::new(LlmClassifierRouter::new(llm))` based on
///   `Config.routing.context_router`.
///
/// The legacy `_identity_loader` argument is retained but unused — the
/// builder consumes `IdentityProvider` directly. Phase F1 will retire
/// the loader entirely once `weaver init` seeds local `.clawft/`.
///
/// Native-only: `NativePlatform` and `LlmClient` are both native-gated.
#[cfg(feature = "native")]
#[allow(clippy::too_many_arguments)]
pub async fn build_daemon_agent_loop(
    llm: clawft_service_llm::SharedLlmClient,
    tools: Arc<ToolRegistry>,
    _identity_loader: Arc<crate::agent::identity::IdentityLoader<clawft_platform::NativePlatform>>,
    workspace: &std::path::Path,
    agent_id: Option<String>,
    context_router: Option<Arc<dyn crate::agent::context_router::ContextRouter>>,
    gate: Option<Arc<dyn crate::agent::gate::EffectGate>>,
    sink: Option<Arc<dyn crate::agent::sink::ConversationSink>>,
    identity_provider: Option<Arc<dyn crate::agent::identity::IdentityProvider>>,
    // Global (system-wide) routing — the PermissionResolver ceiling.
    // When a workspace overlay is also passed, this must be the
    // unmerged global layer so `enforce_workspace_ceiling` can run.
    routing: Option<&clawft_types::routing::RoutingConfig>,
    // Workspace overlay routing (WEFT-10). When `Some`, the resolver
    // applies workspace level overrides then clamps to the global ceiling.
    workspace_routing: Option<&clawft_types::routing::RoutingConfig>,
    graft_provider: Option<Arc<dyn crate::agent::graft::ContextGraftProvider>>,
    // WEFT-330: optional soul-journal writer (grant-gated substrate
    // impl from service-agent, dual-writing `.clawft/SOUL.journal.md`
    // when the daemon supplies a composite). `None` skips journal
    // writes (CLI / test path).
    soul_journal: Option<Arc<dyn crate::agent::soul_journal::SoulJournal>>,
    // WEFT-335: optional router-decision observability log (grant-gated
    // substrate writer under `_derived/agent/routing/recent/`). `None`
    // skips decision logging (CLI / test path).
    routing_log: Option<Arc<dyn crate::agent::routing_log::RouterDecisionLog>>,
) -> Arc<crate::agent::loop_core::AgentLoop<clawft_platform::NativePlatform>> {
    use clawft_platform::NativePlatform;

    use crate::pipeline::service_llm_adapter::ServiceLlmAdapter;
    use crate::pipeline::transport::{LlmProvider, OpenAiCompatTransport};

    // Daemon-side config: pull a Config::default() and stamp the
    // workspace path. The agent.chat wire params override
    // temperature/max_tokens per turn, so the defaults here only
    // matter for fields the wire doesn't carry. The exception is
    // `routing` — the resolver's `channel_overrides` MUST reflect the
    // operator's loaded permissions, not Config::default() (which
    // would force every non-CLI channel to zero_trust). Callers pass
    // their loaded `RoutingConfig` via the `routing` parameter; if
    // `None`, we fall back to defaults (test/dev path only).
    let mut config = Config::default();
    config.agents.defaults.workspace = workspace.display().to_string();
    // Stamp the daemon's actual LLM model into agents.defaults.model so
    // the agent loop's request body matches the upstream the operator
    // configured (`[kernel.llm].model` / `LLM_MODEL` env). Without
    // this, `Config::default()` injects a hardcoded
    // ADR-060 local Hermes default; combined with the panel principal's
    // `model_override: true` permission the tiered router takes that
    // verbatim and the request goes out asking for a model the local
    // llama-server (or any non-deepseek upstream) doesn't host.
    //
    // WEFT-343: read through the shared lock so a post-boot swap is
    // visible on subsequent loop rebuilds; the stamp itself is a
    // one-shot at construction time.
    {
        let upstream_model = llm.read().await.config().model.clone();
        if !upstream_model.is_empty() {
            config.agents.defaults.model = upstream_model;
        }
    }
    if let Some(r) = routing {
        config.routing = r.clone();
    }

    let platform = Arc::new(NativePlatform::new());

    // Build the supporting infrastructure inline (analogous to
    // `AppContext::new` minus the parts the daemon doesn't need
    // — skill watcher, agent router, agent bus). We allow this to
    // be `expect(...)` because the daemon already validated the
    // workspace earlier at boot; a failure here is a hard boot
    // failure rather than a recoverable error.
    let bus = Arc::new(MessageBus::new());

    // M3 store collapse (design §P5): the daemon path's durable session
    // state lives entirely in the substrate-backed `ConversationSink`
    // attached below (`with_sink`). `SessionManager` is no longer
    // constructed here — the loop hydrates each turn from the sink.

    // WEFT-79: route memory + skills through the workspace overlay
    // the daemon already resolved. The daemon hands us the workspace
    // root explicitly, so we never fall back to the global path here —
    // a daemon without a workspace is a misconfiguration, not a soft
    // fallback case.
    let memory = Arc::new(crate::agent::memory::MemoryStore::for_workspace(
        workspace,
        platform.clone(),
    ));
    let skills_loader =
        crate::agent::skills::SkillsLoader::for_workspace(workspace, platform.clone());
    let skills = Arc::new(skills_loader);
    let context = ContextBuilder::new(config.agents.clone(), memory, skills, platform.clone());

    // Pipeline transport: bridge the daemon's already-constructed
    // LlmClient through the ServiceLlmAdapter so the agent loop
    // shares the daemon's single LLM connection.
    let adapter: Arc<dyn LlmProvider> = Arc::new(ServiceLlmAdapter::new(llm));
    let transport = Arc::new(OpenAiCompatTransport::with_provider(adapter));
    let classifier = Arc::new(KeywordClassifier::new());
    let router: Arc<dyn ModelRouter> = build_router_from_config(&config);
    let assembler = Arc::new(TokenBudgetAssembler::new(
        config.agents.defaults.max_tokens.max(1) as usize,
    ));
    let scorer = crate::pipeline::build_scorer(&config.pipeline);
    let (learner, trajectory) = crate::pipeline::build_learner_parts(&config.pipeline);
    let mut pipeline = PipelineRegistry::new(Pipeline {
        classifier,
        router,
        assembler,
        transport,
        scorer,
        learner,
    });
    if let Some(t) = trajectory {
        pipeline = pipeline.with_trajectory_learner(t);
    }

    // WEFT-10: pass split routing layers so enforce_workspace_ceiling
    // clamps elevated workspace grants against the global ceiling.
    // `routing` is the global (or merged-legacy) layer; `workspace_routing`
    // is the optional overlay kept separate by the loader.
    if let (Some(global), Some(ws)) = (routing, workspace_routing) {
        let violations =
            crate::pipeline::permissions::PermissionResolver::validate_workspace_ceiling(
                global, ws,
            );
        if !violations.is_empty() {
            tracing::warn!(
                violations = ?violations,
                "workspace routing exceeds global permission ceiling; \
                 elevated grants will be silently clamped at resolve time"
            );
        }
    }
    let resolver = crate::pipeline::permissions::PermissionResolver::new(
        &config.routing,
        workspace_routing,
    );
    // WEFT-342: capture before moving `config.agents` into AgentLoop.
    let binding_thread_mode = config.agents.binding_thread_mode;
    let mut agent = crate::agent::loop_core::AgentLoop::new(
        config.agents,
        platform,
        bus,
        pipeline,
        tools,
        context,
        resolver,
    )
    // M3 §D5: the daemon's `agent.chat` conv_id already arrives as a
    // globally-unique `chat_id`; use it verbatim so the M3 collapse keys
    // the substrate turn log / forest / tier / `conversation.graph` /
    // subagent child namespace exactly as they do today (no `agent.chat:`
    // prefix, no compounding on nested spawns).
    .with_chat_id_as_conv_id();
    // C3 attaches the caller's sink (substrate-backed at the daemon
    // construction site; falls back to the in-memory default for CLI
    // / non-substrate callers).
    if let Some(s) = sink {
        agent = agent.with_sink(s);
    }
    // D1 attaches the identity-aware system-prompt builder. The
    // builder is wrapped in an Arc so every turn re-uses the same
    // provider (and its cache, in the FileIdentityProvider case)
    // without per-turn re-construction cost.
    if let Some(provider) = identity_provider {
        // WEFT-342: honour agents.binding_thread_mode (default deny).
        let builder = Arc::new(
            crate::agent::system_prompt::SystemPromptBuilder::new(
                provider,
                workspace.to_path_buf(),
            )
            .with_binding_thread_mode(binding_thread_mode),
        );
        agent = agent.with_system_prompt_builder(builder);
    }
    // D2 attaches the kernel-backed gate. When `None`, AgentLoop's
    // `NoopGate` default keeps behaviour identical to the pre-D2
    // path so CLI / test callers see no change. The daemon
    // construction site passes `Some(KernelEffectGate)` so every
    // tool dispatch hits `GovernanceGate::check`.
    if let Some(g) = gate {
        agent = agent.with_gate(g);
    }
    // D2 also threads through the daemon-supplied concierge agent
    // id used by every `gate.check`. Without this, the loop falls
    // back to the per-message `"{channel}:{sender_id}"` synthesis
    // (the CLI / test path).
    if let Some(id) = agent_id {
        agent = agent.with_daemon_agent_id(id);
    }
    // E1 attaches the daemon-supplied ContextRouter (LlmClassifierRouter
    // when Config.routing.context_router == "llm-classifier", NullRouter
    // otherwise — the latter is also AgentLoop's built-in default, so
    // passing `None` keeps the pre-E1 wire byte-identical).
    if let Some(r) = context_router {
        agent = agent.with_context_router(r);
    }
    // ADR-058 Phase 5.1: attach the kernel-backed L2 context-graft provider
    // (the per-conversation SessionTier) so each turn's prompt is augmented with
    // recalled context. `None` (CLI / tests) leaves the loop's NullGraftProvider
    // default — no grafting, byte-identical wire.
    if let Some(gp) = graft_provider {
        agent = agent.with_graft_provider(gp);
    }
    // WEFT-330: agent-side SOUL.journal write path. When attached, the
    // loop appends drift observations after successful turns that
    // fire the documented drift signal. Daemon supplies a
    // grant-gated substrate writer (+ optional file mirror); CLI /
    // tests leave this `None`.
    if let Some(j) = soul_journal {
        agent = agent.with_soul_journal(j);
    }
    // WEFT-335: log every ContextRouter::route decision for the v1→v2
    // promotion gate. Daemon supplies a grant-gated substrate writer;
    // CLI / tests leave this `None`.
    if let Some(rlog) = routing_log {
        agent = agent.with_routing_log(rlog);
    }
    Arc::new(agent)
}

/// Build the appropriate router based on `config.routing.mode`.
fn build_router_from_config(config: &Config) -> Arc<dyn ModelRouter> {
    if config.routing.mode == "tiered" {
        let routing = config.routing.clone();
        let cost_tracker = Arc::new(CostTracker::new(routing.cost_budgets.reset_hour_utc));
        let rate_limiter = Arc::new(RateLimiter::new(
            routing.rate_limiting.window_seconds,
            routing.rate_limiting.global_rate_limit_rpm,
        ));
        Arc::new(
            TieredRouter::new(routing)
                .with_cost_tracker(cost_tracker)
                .with_rate_limiter(rate_limiter),
        )
    } else {
        Arc::new(StaticRouter::from_config(&config.agents))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clawft_platform::NativePlatform;
    use clawft_types::config::{AgentDefaults, AgentsConfig};
    use std::sync::Arc;

    fn test_config() -> Config {
        Config {
            agents: AgentsConfig {
                defaults: AgentDefaults {
                    workspace: "~/.clawft/workspace".into(),
                    model: clawft_types::config::DEFAULT_LOCAL_LLM_MODEL_ROUTED.into(),
                    max_tokens: 4096,
                    temperature: 0.7,
                    max_tool_iterations: 10,
                    memory_window: 50,
                },
                ..AgentsConfig::default()
            },
            ..Config::default()
        }
    }

    #[tokio::test]
    async fn new_creates_app_context() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await;
        assert!(ctx.is_ok());
    }

    #[tokio::test]
    async fn config_accessor() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await.unwrap();
        assert_eq!(ctx.config().agents.defaults.model, clawft_types::config::DEFAULT_LOCAL_LLM_MODEL_ROUTED);
        assert_eq!(ctx.config().agents.defaults.max_tokens, 4096);
    }

    #[tokio::test]
    async fn platform_accessor() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await.unwrap();
        let _p = ctx.platform();
    }

    #[tokio::test]
    async fn bus_accessor() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await.unwrap();
        let bus = ctx.bus();
        // Should be able to get an inbound sender
        let _tx = bus.inbound_sender();
    }

    /// WEFT-185: production path constructs an AgentBus via enable_agent_bus.
    #[cfg(feature = "native")]
    #[tokio::test]
    async fn enable_agent_bus_constructs_once() {
        let platform = Arc::new(NativePlatform::new());
        let mut ctx = AppContext::new(test_config(), platform).await.unwrap();
        assert!(ctx.agent_bus().is_none());
        let bus1 = ctx.enable_agent_bus(Some(32));
        assert_eq!(bus1.inbox_capacity(), 32);
        assert!(ctx.agent_bus().is_some());
        let bus2 = ctx.enable_agent_bus(Some(99));
        // Second call returns the existing bus (capacity unchanged).
        assert_eq!(bus2.inbox_capacity(), 32);
        assert!(Arc::ptr_eq(&bus1, &bus2));
    }

    #[tokio::test]
    async fn tools_starts_empty() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await.unwrap();
        assert!(ctx.tools().is_empty());
    }

    #[tokio::test]
    async fn tools_mut_allows_registration() {
        let platform = Arc::new(NativePlatform::new());
        let mut ctx = AppContext::new(test_config(), platform).await.unwrap();

        use crate::tools::registry::Tool;
        use async_trait::async_trait;

        struct DummyTool;

        #[async_trait]
        impl Tool for DummyTool {
            fn name(&self) -> &str {
                "dummy"
            }
            fn description(&self) -> &str {
                "A dummy tool"
            }
            fn parameters(&self) -> serde_json::Value {
                serde_json::json!({"type": "object", "properties": {}})
            }
            async fn execute(
                &self,
                _args: serde_json::Value,
            ) -> Result<serde_json::Value, crate::tools::registry::ToolError> {
                Ok(serde_json::json!({}))
            }
        }

        ctx.tools_mut().register(Arc::new(DummyTool));
        assert_eq!(ctx.tools().len(), 1);
        assert_eq!(ctx.tools().list(), vec!["dummy"]);
    }

    #[tokio::test]
    async fn memory_accessor() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await.unwrap();
        let memory = ctx.memory();
        assert!(memory.memory_path().is_absolute());
    }

    #[tokio::test]
    async fn skills_accessor() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await.unwrap();
        let skills = ctx.skills();
        assert!(skills.skills_dir().is_absolute());
    }

    #[tokio::test]
    async fn with_routing_layers_wires_permission_ceiling() {
        // WEFT-10: AppContext must accept split layers and build a
        // PermissionResolver that clamps elevated workspace grants.
        use clawft_types::routing::{PermissionLevelConfig, PermissionsConfig, RoutingConfig};

        let platform = Arc::new(NativePlatform::new());
        let global = RoutingConfig {
            permissions: PermissionsConfig {
                user: PermissionLevelConfig {
                    level: Some(1),
                    tool_access: Some(vec!["read_file".into()]),
                    cost_budget_daily_usd: Some(5.0),
                    ..Default::default()
                },
                ..Default::default()
            },
            ..Default::default()
        };
        let workspace = RoutingConfig {
            permissions: PermissionsConfig {
                user: PermissionLevelConfig {
                    level: Some(2),
                    tool_access: Some(vec!["read_file".into(), "shell".into()]),
                    cost_budget_daily_usd: Some(999.0),
                    ..Default::default()
                },
                ..Default::default()
            },
            ..Default::default()
        };

        let ctx = AppContext::new(test_config(), platform)
            .await
            .unwrap()
            .with_routing_layers(global.clone(), Some(workspace.clone()));

        // Mirror what into_agent_loop does for the resolver.
        let resolver = crate::pipeline::permissions::PermissionResolver::new(
            ctx.global_routing.as_ref().unwrap(),
            ctx.workspace_routing.as_ref(),
        );
        let perms = resolver.resolve("someone", "telegram", true);
        assert!(
            perms.level <= 1,
            "workspace level elevation must clamp, got {}",
            perms.level
        );
        assert!(
            !perms.tool_access.contains(&"shell".to_string()),
            "workspace-only tool must be filtered"
        );
        assert!(perms.cost_budget_daily_usd <= 5.0);
    }

    #[tokio::test]
    async fn into_agent_loop_produces_valid_loop() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await.unwrap();
        let agent = ctx.into_agent_loop();
        assert_eq!(agent.config().defaults.model, clawft_types::config::DEFAULT_LOCAL_LLM_MODEL_ROUTED);
        assert_eq!(agent.config().defaults.max_tokens, 4096);
    }

    #[tokio::test]
    async fn set_pipeline_replaces_default() {
        let platform = Arc::new(NativePlatform::new());
        let mut ctx = AppContext::new(test_config(), platform).await.unwrap();

        // Build a custom pipeline with a different router
        let custom_pipeline = build_default_pipeline(&test_config());
        ctx.set_pipeline(custom_pipeline);

        // Should still produce a valid agent loop
        let agent = ctx.into_agent_loop();
        assert_eq!(agent.config().defaults.model, clawft_types::config::DEFAULT_LOCAL_LLM_MODEL_ROUTED);
    }

    #[tokio::test]
    async fn default_config_bootstrap() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(Config::default(), platform).await;
        assert!(ctx.is_ok());
    }

    #[test]
    fn build_default_pipeline_creates_registry() {
        let config = test_config();
        let _registry = build_default_pipeline(&config);
        // Should not panic.
    }

    #[test]
    fn build_default_pipeline_with_defaults() {
        let config = Config::default();
        let _registry = build_default_pipeline(&config);
    }

    #[tokio::test]
    async fn bus_clone_survives_into_agent_loop() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await.unwrap();

        // Clone the bus sender before consuming the context
        let tx = ctx.bus().inbound_sender();
        let _agent = ctx.into_agent_loop();

        // The sender should still be usable
        use chrono::Utc;
        use clawft_types::event::InboundMessage;
        use std::collections::HashMap;

        let msg = InboundMessage {
            channel: "test".into(),
            sender_id: "user1".into(),
            chat_id: "chat1".into(),
            content: "hello".into(),
            timestamp: Utc::now(),
            media: vec![],
            metadata: HashMap::new(),
        };
        assert!(tx.send(msg).await.is_ok());
    }

    #[tokio::test]
    async fn app_context_is_send() {
        fn assert_send<T: Send>() {}
        assert_send::<AppContext<NativePlatform>>();
    }

    // ── Integration: build_live_pipeline transport is configured ─────

    #[tokio::test]
    async fn build_live_pipeline_transport_is_configured() {
        use crate::pipeline::traits::{LlmMessage, TaskType, TransportRequest};

        // The live pipeline should have a configured (non-stub) transport.
        // When we call complete() on the stub transport, it returns an error
        // containing "transport not configured". The live pipeline should
        // NOT produce that error -- it should attempt a real HTTP call
        // (which will fail differently without an API key).
        let config = test_config();
        let registry = build_live_pipeline(&config);

        // Access the default pipeline's transport via get() with an unregistered type.
        let pipeline = registry.get(&TaskType::Unknown);

        let transport_req = TransportRequest {
            provider: "anthropic".into(),
            model: "claude-opus-4-5".into(),
            messages: vec![LlmMessage {
                role: "user".into(),
                content: "test".into(),
                tool_call_id: None,
                tool_calls: None,
            }],
            tools: vec![],
            max_tokens: Some(10),
            temperature: Some(0.0),
            tool_choice: None,
        };

        let result = pipeline.transport.complete(&transport_req).await;

        // The live transport IS configured (has a provider), so it should
        // NOT fail with "transport not configured". It will fail with an
        // HTTP/auth error instead because there's no real API key.
        match result {
            Ok(_) => {} // unlikely without API key, but acceptable
            Err(e) => {
                let msg = e.to_string();
                assert!(
                    !msg.contains("transport not configured"),
                    "live pipeline should not use stub transport, but got: {msg}"
                );
            }
        }
    }

    // ── Integration: enable_live_llm replaces the pipeline ──────────

    #[tokio::test]
    async fn app_context_enable_live_llm() {
        let platform = Arc::new(NativePlatform::new());
        let mut ctx = AppContext::new(test_config(), platform).await.unwrap();

        // Before enable_live_llm, the default pipeline uses a stub transport.
        // We cannot directly access ctx.pipeline, but we can verify behavior
        // indirectly: enable_live_llm should not panic and should replace
        // the pipeline such that transport errors no longer say "not configured".

        ctx.enable_live_llm();

        // Convert to agent loop and verify it's still valid.
        let agent = ctx.into_agent_loop();
        assert_eq!(agent.config().defaults.model, clawft_types::config::DEFAULT_LOCAL_LLM_MODEL_ROUTED);
    }

    // ── Integration: default pipeline uses stub (negative test) ─────

    #[test]
    fn default_pipeline_builds_with_service_llm_transport() {
        // The default pipeline now wires a ServiceLlmAdapter over an
        // LlmClient resolved from LlmConfig::from_env (instead of the
        // earlier stubbed transport). We can't fire a request from a
        // unit test — that would hit the network (or wait for a
        // timeout) depending on whether llama-server happens to be
        // running on the test host. Just confirm the build path
        // succeeds; the wiremock-backed round-trip in
        // `pipeline::service_llm_adapter::tests` covers the actual
        // request path end-to-end.
        use crate::pipeline::traits::TaskType;

        let config = test_config();
        let registry = build_default_pipeline(&config);
        // Smoke-check: pipeline is reachable for the default task type.
        let _pipeline = registry.get(&TaskType::Unknown);
    }

    // ── Integration: build_live_pipeline creates a valid registry ────

    #[test]
    fn build_live_pipeline_creates_registry() {
        let config = test_config();
        let registry = build_live_pipeline(&config);
        // Registry should be usable for any task type (falls back to default).
        use crate::pipeline::traits::TaskType;
        let _pipeline = registry.get(&TaskType::Chat);
        let _pipeline = registry.get(&TaskType::CodeGeneration);
        let _pipeline = registry.get(&TaskType::Unknown);
    }
}