lean-ctx 3.12.4

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported proxy integrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
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
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
// SPDX-License-Identifier: Apache-2.0
//! HTTP server combining Streamable-HTTP MCP transport, REST APIs, and
//! optional local HTTP surfaces.
//!
//! # Pillar mapping
//!
//! - **Engine:** HTTP MCP transport, Context OS event bus (SSE), A2A handoffs,
//!   agent registry, capabilities/manifest/openapi endpoints.

use std::net::SocketAddr;
use std::sync::Arc;

use anyhow::{Context, Result};
use axum::{
    Router,
    extract::Json,
    extract::Query,
    extract::State,
    http::{Request, StatusCode, header},
    middleware::{self, Next},
    response::sse::{Event as SseEvent, KeepAlive, Sse},
    response::{IntoResponse, Response},
    routing::get,
};
use futures::Stream;
use rmcp::transport::StreamableHttpService;
use serde::Deserialize;
use serde_json::Value;
use tokio::sync::broadcast;
use tokio::time::{Duration, Instant};

use lean_ctx::core::a2a::relay::RelayPeerTableV1;
use lean_ctx::core::context_os::ContextOsMetrics;
use lean_ctx_server::engine::ContextEngine;
use lean_ctx_server::tools::LeanCtxServer;

mod config;
mod discovery;
mod handlers;
mod local_service;
mod relay_rate;
mod relay_replay;
mod relay_replay_async;
#[cfg(test)]
mod relay_tls_tests;
mod remote_replay;
mod scoped_delivery;
mod task_control;
#[cfg(test)]
mod task_control_tests;
#[cfg(test)]
mod work_graph_delivery_tests;
#[allow(clippy::wildcard_imports)]
use handlers::*;

pub mod kernel_api;

pub use config::HttpServerConfig;
use config::sanitize_id;
pub use relay_rate::{RelayQuota, RelayQuotaConfig};

/// Wrapper stream that calls `record_sse_disconnect` on drop.
use std::pin::Pin;

pub(crate) struct SseDisconnectGuard<I> {
    pub(crate) inner: Pin<Box<dyn Stream<Item = I> + Send>>,
    pub(crate) metrics: Arc<ContextOsMetrics>,
}

impl<I> Stream for SseDisconnectGuard<I> {
    type Item = I;

    fn poll_next(
        mut self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        self.inner.as_mut().poll_next(cx)
    }
}

impl<I> Drop for SseDisconnectGuard<I> {
    fn drop(&mut self) {
        self.metrics.record_sse_disconnect();
    }
}

type RequestConcurrencyLease = Arc<tokio::sync::OwnedSemaphorePermit>;

#[derive(Clone)]
struct AppState {
    token: Option<String>,
    a2a_signing_key: Option<String>,
    a2a_recipient_id: Option<String>,
    a2a_tenant_id: Option<String>,
    a2a_project_id: Option<String>,
    a2a_peers: Arc<RelayPeerTableV1>,
    relay_quotas: Option<Arc<tokio::sync::Mutex<relay_rate::RelayQuotaState>>>,
    /// Configured Ed25519 peer trust and capability grants. Sender-provided
    /// capability claims are never authority; only this policy is.
    a2a_task_authority: Arc<lean_ctx::core::a2a::task::TaskAuthorityConfigV1>,
    concurrency: Arc<tokio::sync::Semaphore>,
    rate: Arc<RateLimiter>,
    remote_replays: Arc<remote_replay::RemoteReplayGuard>,
    project_root: String,
    timeout: Duration,
    server: LeanCtxServer,
    /// Serving the local daemon socket: a tool call may name its project.
    local_ipc: bool,
    project_servers: Arc<ProjectServers>,
}

/// One server per project a CLI call named, so a call from project B never
/// runs in the session of project A (a CLI `knowledge recall` in B answered
/// with A's facts, 24.10.). Bounded: past [`ProjectServers::KEPT`] projects
/// the oldest servers are dropped and rebuilt on their next call.
struct ProjectServers {
    servers: tokio::sync::Mutex<Vec<(std::path::PathBuf, LeanCtxServer)>>,
    factory: Box<dyn Fn(&str) -> LeanCtxServer + Send + Sync>,
}

impl ProjectServers {
    const KEPT: usize = 32;

    /// For a test state: no server built yet, each named project gets a
    /// plain server.
    #[cfg(test)]
    pub(crate) fn for_tests() -> Arc<Self> {
        Arc::new(Self {
            servers: tokio::sync::Mutex::new(Vec::new()),
            factory: Box::new(|root| {
                LeanCtxServer::new_shared_with_context(root, "default", "default")
            }),
        })
    }

    /// The server for `root`, or why `root` may not be served: it must be an
    /// existing directory, not a broad root (home, `/`), and inside the
    /// Workspace when one confines this machine (#2120).
    async fn for_root(
        &self,
        root: &str,
        default_root: &str,
        default: &LeanCtxServer,
    ) -> Result<LeanCtxServer, &'static str> {
        let root = std::path::Path::new(root)
            .canonicalize()
            .map_err(|_| "project root unavailable")?;
        // A canonical filesystem root has no parent: `/`, and on Windows the
        // verbatim drive root `\\?\C:\`, which `is_broad_or_unsafe_root`
        // does not spell out.
        if !root.is_dir()
            || root.parent().is_none()
            || lean_ctx::core::pathutil::is_broad_or_unsafe_root(&root)
        {
            return Err("project root is not a project");
        }
        if !lean_ctx::core::workspace_authority::root_authorized(&root) {
            return Err("project root is outside the workspace");
        }
        if std::path::Path::new(default_root)
            .canonicalize()
            .ok()
            .as_deref()
            == Some(root.as_path())
        {
            return Ok(default.clone());
        }
        let mut servers = self.servers.lock().await;
        if let Some((_, server)) = servers.iter().find(|(known, _)| *known == root) {
            return Ok(server.clone());
        }
        if servers.len() >= Self::KEPT {
            servers.remove(0);
        }
        let server = (self.factory)(&root.to_string_lossy());
        servers.push((root, server.clone()));
        Ok(server)
    }
}

#[derive(Debug)]
struct RateLimiter {
    max_rps: f64,
    burst: f64,
    state: tokio::sync::Mutex<RateState>,
}

#[derive(Debug, Clone, Copy)]
struct RateState {
    tokens: f64,
    last: Instant,
}

impl RateLimiter {
    fn new(max_rps: u32, burst: u32) -> Self {
        let now = Instant::now();
        Self {
            max_rps: (max_rps.max(1)) as f64,
            burst: (burst.max(1)) as f64,
            state: tokio::sync::Mutex::new(RateState {
                tokens: (burst.max(1)) as f64,
                last: now,
            }),
        }
    }

    async fn allow(&self) -> bool {
        let mut s = self.state.lock().await;
        let now = Instant::now();
        let elapsed = now.saturating_duration_since(s.last);
        let refill = elapsed.as_secs_f64() * self.max_rps;
        s.tokens = (s.tokens + refill).min(self.burst);
        s.last = now;
        if s.tokens >= 1.0 {
            s.tokens -= 1.0;
            true
        } else {
            false
        }
    }
}

async fn auth_middleware(
    State(state): State<AppState>,
    req: Request<axum::body::Body>,
    next: Next,
) -> Response {
    if state.token.is_none() {
        return next.run(req).await;
    }

    // Relay deliveries authenticate against their selected peer channel; the
    // general server bearer must not become a second singleton authority.
    if req.uri().path() == "/a2a/deliver" && !state.a2a_peers.peers.is_empty() {
        return next.run(req).await;
    }

    if req.uri().path() == "/health" {
        return next.run(req).await;
    }

    let expected = state.token.as_deref().unwrap_or("");
    let Some(h) = req.headers().get(header::AUTHORIZATION) else {
        return json_error(
            StatusCode::UNAUTHORIZED,
            "unauthorized",
            "missing Authorization header",
        );
    };
    let Ok(s) = h.to_str() else {
        return json_error(
            StatusCode::UNAUTHORIZED,
            "unauthorized",
            "malformed Authorization header",
        );
    };
    let Some(token) = s
        .strip_prefix("Bearer ")
        .or_else(|| s.strip_prefix("bearer "))
    else {
        return json_error(
            StatusCode::UNAUTHORIZED,
            "unauthorized",
            "Authorization must use the Bearer scheme",
        );
    };
    if !constant_time_eq(token.as_bytes(), expected.as_bytes()) {
        return json_error(
            StatusCode::UNAUTHORIZED,
            "unauthorized",
            "invalid bearer token",
        );
    }

    next.run(req).await
}

/// Structured REST error envelope: `{ "error": <human message>, "error_code": <stable code> }`.
///
/// `error_code` is the stable, machine-readable string SDKs switch on; `error` carries the
/// human-facing message. Used for every REST (non-A2A) error so clients branch on a code
/// instead of parsing prose. The A2A JSON-RPC surface keeps its own `-32xxx` envelope.
pub(crate) fn json_error(status: StatusCode, error_code: &str, message: &str) -> Response {
    (
        status,
        Json(serde_json::json!({ "error": message, "error_code": error_code })),
    )
        .into_response()
}

fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    use subtle::ConstantTimeEq;
    if a.len() != b.len() {
        return false;
    }
    bool::from(a.ct_eq(b))
}

async fn rate_limit_middleware(
    State(state): State<AppState>,
    req: Request<axum::body::Body>,
    next: Next,
) -> Response {
    if is_diagnostic_path(req.uri().path()) {
        return next.run(req).await;
    }
    if !state.rate.allow().await {
        lean_ctx::core::request_ledger::refused();
        return StatusCode::TOO_MANY_REQUESTS.into_response();
    }
    next.run(req).await
}

/// Health routes answer from counters, never from the work queue: they must
/// stay reachable exactly when every request slot is taken (#2197).
fn is_diagnostic_path(path: &str) -> bool {
    matches!(path, "/health" | "/v1/health")
}

async fn concurrency_middleware(
    State(state): State<AppState>,
    mut req: Request<axum::body::Body>,
    next: Next,
) -> Response {
    if is_diagnostic_path(req.uri().path()) {
        return next.run(req).await;
    }
    let Ok(permit) = state.concurrency.clone().try_acquire_owned() else {
        lean_ctx::core::request_ledger::refused();
        return StatusCode::TOO_MANY_REQUESTS.into_response();
    };
    let permit = Arc::new(permit);
    req.extensions_mut().insert(permit.clone());
    let resp = next.run(req).await;
    drop(permit);
    resp
}

async fn health() -> impl IntoResponse {
    (StatusCode::OK, "ok\n")
}

/// `GET /v1/health`: liveness plus the request ledger (#2197) — counters,
/// the oldest pending request's method, stage and age, and the last tool
/// completion. Method names only; no arguments, paths or content.
async fn v1_health() -> impl IntoResponse {
    let snapshot = lean_ctx::core::request_ledger::snapshot()
        .with_ages(lean_ctx::core::request_ledger::epoch_ms());
    Json(serde_json::json!({ "status": "ok", "requests": snapshot }))
}

/// Persist queued observations and remove the published request snapshot
/// (#2196, #2197). Blocking work, so it runs off the async workers.
async fn finish_serving() {
    let _ = tokio::task::spawn_blocking(|| {
        lean_ctx::core::request_ledger::finish_serving(Duration::from_secs(5));
    })
    .await;
}

async fn v1_shutdown() -> impl IntoResponse {
    tokio::spawn(async {
        tokio::time::sleep(Duration::from_millis(100)).await;
        // `process::exit` runs no destructors or exit hooks.
        finish_serving().await;
        std::process::exit(0);
    });
    (StatusCode::OK, "shutting down\n")
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct IndexEnsureBody {
    root: String,
    #[serde(default)]
    extra_roots: Vec<String>,
}

/// Daemon-side index delegation (#460). A thin-client session POSTs the repo it
/// needs warmed and the daemon — the single long-lived indexer — builds it once
/// in the background (deduped per root). Every other session for the same root
/// then load-shares the on-disk result via the `graph-idx`/`bm25-idx`
/// cross-process locks instead of running its own scan, so N concurrent sessions
/// cost ~one index pass machine-wide instead of N. Returns immediately; the
/// build runs in the orchestrator's own worker thread.
async fn v1_index_ensure(Json(body): Json<IndexEnsureBody>) -> impl IntoResponse {
    if body.root.trim().is_empty() {
        return (StatusCode::BAD_REQUEST, "root is required\n");
    }
    let root = body.root;
    // Under a Workspace this daemon indexes only its roots (#2120).
    if !lean_ctx::core::workspace_authority::root_authorized(std::path::Path::new(&root)) {
        return (
            StatusCode::FORBIDDEN,
            "root is outside this server's Workspace\n",
        );
    }
    let extra: Vec<String> = body
        .extra_roots
        .into_iter()
        .filter(|extra| {
            lean_ctx::core::workspace_authority::root_authorized(std::path::Path::new(extra))
        })
        .collect();
    tokio::task::spawn_blocking(move || {
        lean_ctx::core::index_orchestrator::ensure_all_background(&root);
        if !extra.is_empty() {
            lean_ctx::core::index_orchestrator::ensure_extra_roots_background(&root, &extra);
        }
    });
    (StatusCode::OK, "{\"status\":\"ok\"}\n")
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ToolCallBody {
    name: String,
    #[serde(default)]
    arguments: Option<Value>,
    /// The project the calling CLI process resolved (`--root`,
    /// `LEAN_CTX_PROJECT_ROOT`, its working directory). Honoured only on the
    /// local daemon socket: the call then runs in that project's own server,
    /// never in the session of whichever project the daemon served last.
    #[serde(default)]
    project_root: Option<String>,
    /// The calling session's `LEAN_CTX_RIGHTS_FILE` (process-v1 §9). Honoured
    /// only on the local daemon socket: the call runs under that session's
    /// rights, never under the daemon's own environment.
    #[serde(default)]
    rights_file: Option<String>,
    #[serde(default)]
    _workspace_id: Option<String>,
    #[serde(default)]
    _channel_id: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct EventsQuery {
    #[serde(default)]
    workspace_id: Option<String>,
    #[serde(default)]
    channel_id: Option<String>,
    #[serde(default)]
    since: Option<i64>,
    #[serde(default)]
    limit: Option<usize>,
    /// Comma-separated event kind filter (e.g. `tool_call,session_start`).
    /// When set, only matching events are delivered via SSE.
    #[serde(default)]
    kind: Option<String>,
    /// Agent identity used for directed-event visibility. Without an identity,
    /// SSE exposes broadcast events only.
    #[serde(default)]
    agent_id: Option<String>,
}

async fn v1_manifest(State(state): State<AppState>) -> impl IntoResponse {
    let _ = state;
    let v = lean_ctx::core::mcp_manifest::manifest_value();
    (StatusCode::OK, Json(v))
}

/// `GET /v1/capabilities` — discovery document describing what this instance
/// supports (presets, tools, read modes, features, extensions, contract
/// versions). See `docs/contracts/capabilities-contract-v1.md`.
async fn v1_capabilities(State(state): State<AppState>) -> impl IntoResponse {
    let _ = state;
    (
        StatusCode::OK,
        Json(lean_ctx::core::server_capabilities::capabilities_value()),
    )
}

/// `GET /v1/openapi.json` — OpenAPI 3.0 document for the public `/v1` surface,
/// generated from the in-code endpoint inventory (`core::openapi`).
async fn v1_openapi(State(state): State<AppState>) -> impl IntoResponse {
    let _ = state;
    (
        StatusCode::OK,
        Json(lean_ctx::core::openapi::openapi_value()),
    )
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ToolsQuery {
    #[serde(default)]
    offset: Option<usize>,
    #[serde(default)]
    limit: Option<usize>,
}

async fn v1_tools(State(state): State<AppState>, Query(q): Query<ToolsQuery>) -> impl IntoResponse {
    let _ = state;
    let v = lean_ctx::core::mcp_manifest::manifest_value();
    let tools = v
        .get("tools")
        .and_then(|t| t.get("granular"))
        .cloned()
        .unwrap_or(Value::Array(vec![]));

    let all = tools.as_array().cloned().unwrap_or_default();
    let total = all.len();
    let offset = q.offset.unwrap_or(0).min(total);
    let limit = q.limit.unwrap_or(200).min(500);
    let page = all.into_iter().skip(offset).take(limit).collect::<Vec<_>>();

    (
        StatusCode::OK,
        Json(serde_json::json!({
            "tools": page,
            "total": total,
            "offset": offset,
            "limit": limit,
        })),
    )
}

async fn v1_tool_call(
    State(state): State<AppState>,
    Json(body): Json<ToolCallBody>,
) -> impl IntoResponse {
    let server = match body.project_root.as_deref() {
        None => state.server.clone(),
        // Only the local socket's own user may pick a directory on this host.
        Some(_) if !state.local_ipc => {
            return json_error(
                StatusCode::BAD_REQUEST,
                "project_root_refused",
                "only the local daemon socket names a project root",
            )
            .into_response();
        }
        Some(root) => match state
            .project_servers
            .for_root(root, &state.project_root, &state.server)
            .await
        {
            Ok(server) => server,
            Err(reason) => {
                return json_error(StatusCode::BAD_REQUEST, "project_root_invalid", reason)
                    .into_response();
            }
        },
    };
    if body.rights_file.is_some() && !state.local_ipc {
        return json_error(
            StatusCode::BAD_REQUEST,
            "rights_file_refused",
            "only the local daemon socket names a session's rights file",
        )
        .into_response();
    }
    // Every forwarded call runs under the sender's rights; without a rights
    // file the sender has no session profile (the Instance's rules apply).
    let rights = lean_ctx::core::session_rights::from_file_arg(body.rights_file.as_deref());
    let engine = ContextEngine::from_server(server);
    match tokio::time::timeout(
        state.timeout,
        engine.call_tool_value_with_rights(&body.name, body.arguments, rights),
    )
    .await
    {
        Ok(Ok(v)) => (StatusCode::OK, Json(serde_json::json!({ "result": v }))).into_response(),
        Ok(Err(_)) => {
            // The error carries the tool's message, which can echo content
            // the release point withheld from the reply (AP10-R4).
            tracing::warn!("tool call error (tool_error)");
            json_error(
                StatusCode::BAD_REQUEST,
                "tool_error",
                "tool execution failed",
            )
        }
        Err(_) => json_error(
            StatusCode::GATEWAY_TIMEOUT,
            "request_timeout",
            "tool call timed out",
        ),
    }
}

async fn v1_events(
    State(state): State<AppState>,
    Query(q): Query<EventsQuery>,
) -> Sse<impl Stream<Item = Result<SseEvent, std::convert::Infallible>>> {
    use lean_ctx::core::context_os::{ContextEventV1, RedactionLevel, redact_event_payload};

    let ws = sanitize_id(&q.workspace_id.unwrap_or_else(|| "default".to_string()));
    let ch = sanitize_id(&q.channel_id.unwrap_or_else(|| "default".to_string()));
    let _ = &state.project_root;
    let since = q.since.unwrap_or(0);
    let limit = q.limit.unwrap_or(200).min(1000);
    let redaction = RedactionLevel::RefsOnly;

    let kind_filter: Option<Vec<String>> = q.kind.as_deref().map(|k| {
        k.split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect()
    });
    let agent_id = q
        .agent_id
        .as_deref()
        .map(str::trim)
        .filter(|id| !id.is_empty())
        .map(str::to_string);
    let event_filter = lean_ctx::core::context_os::TopicFilter {
        kinds: kind_filter.as_ref().map(|kinds| {
            kinds
                .iter()
                .map(|kind| lean_ctx::core::context_os::ContextEventKindV1::parse(kind))
                .collect()
        }),
        agent_id: agent_id.clone(),
        include_directed: agent_id.is_some(),
        ..Default::default()
    };

    let rt = lean_ctx::core::context_os::runtime();
    let replay = rt.bus.read(&ws, &ch, since, limit);
    let replay: Vec<_> = replay
        .into_iter()
        .filter(|event| event_filter.matches(event))
        .collect();

    let rx = if let Some(sub) = rt.bus.subscribe_filtered(&ws, &ch, event_filter.clone()) {
        lean_ctx::core::context_os::SubscriptionKind::Filtered(sub)
    } else {
        tracing::warn!("SSE subscriber limit reached for {ws}/{ch}");
        let (_, rx) = broadcast::channel::<ContextEventV1>(1);
        lean_ctx::core::context_os::SubscriptionKind::Unfiltered(rx)
    };

    rt.metrics.record_sse_connect();
    rt.metrics.record_events_replayed(replay.len() as u64);
    rt.metrics.record_workspace_active(&ws);

    let bus = rt.bus.clone();
    let metrics = rt.metrics.clone();
    let pending: std::collections::VecDeque<ContextEventV1> = replay.into();

    let stream = futures::stream::unfold(
        (
            pending,
            rx,
            event_filter,
            ws.clone(),
            ch.clone(),
            since,
            redaction,
            bus,
            metrics,
        ),
        |(mut pending, mut rx, event_filter, ws, ch, mut last_id, redaction, bus, metrics)| async move {
            if let Some(mut ev) = pending.pop_front() {
                last_id = ev.id;
                redact_event_payload(&mut ev, redaction);
                let data = serde_json::to_string(&ev).unwrap_or_else(|_| "{}".to_string());
                let evt = SseEvent::default()
                    .id(ev.id.to_string())
                    .event(ev.kind)
                    .data(data);
                return Some((
                    Ok(evt),
                    (
                        pending,
                        rx,
                        event_filter,
                        ws,
                        ch,
                        last_id,
                        redaction,
                        bus,
                        metrics,
                    ),
                ));
            }

            loop {
                match rx.recv().await {
                    Ok(mut ev) if ev.id > last_id => {
                        last_id = ev.id;
                        if !event_filter.matches(&ev) {
                            continue;
                        }
                        redact_event_payload(&mut ev, redaction);
                        let data = serde_json::to_string(&ev).unwrap_or_else(|_| "{}".to_string());
                        let evt = SseEvent::default()
                            .id(ev.id.to_string())
                            .event(ev.kind)
                            .data(data);
                        return Some((
                            Ok(evt),
                            (
                                pending,
                                rx,
                                event_filter,
                                ws,
                                ch,
                                last_id,
                                redaction,
                                bus,
                                metrics,
                            ),
                        ));
                    }
                    Ok(_) => {}
                    Err(broadcast::error::RecvError::Closed) => return None,
                    Err(broadcast::error::RecvError::Lagged(skipped)) => {
                        let missed = bus.read(&ws, &ch, last_id, skipped as usize);
                        metrics.record_events_replayed(missed.len() as u64);
                        for ev in missed {
                            last_id = last_id.max(ev.id);
                            if event_filter.matches(&ev) {
                                pending.push_back(ev);
                            }
                        }
                    }
                }
            }
        },
    );

    let metrics_ref = rt.metrics.clone();
    let guarded = SseDisconnectGuard {
        inner: Box::pin(stream),
        metrics: metrics_ref,
    };

    Sse::new(guarded).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))
}

#[derive(Debug, Deserialize)]
struct AuditEventsQuery {
    #[serde(default = "default_audit_limit")]
    limit: usize,
}

fn default_audit_limit() -> usize {
    100
}

async fn v1_audit_events(Query(q): Query<AuditEventsQuery>) -> impl IntoResponse {
    let capped = q.limit.min(1000);
    let boundary_events = lean_ctx::core::memory_boundary::load_audit_events(capped);
    let trail_events = lean_ctx::core::audit_trail::load_recent(capped);

    Json(serde_json::json!({
        "cross_project_events": boundary_events,
        "audit_trail": trail_events,
    }))
}

#[derive(Deserialize)]
struct ContextSummaryQuery {
    #[serde(default)]
    workspace_id: Option<String>,
    #[serde(default)]
    limit: Option<usize>,
}

async fn v1_context_summary(
    State(state): State<AppState>,
    Query(q): Query<ContextSummaryQuery>,
) -> impl IntoResponse {
    let ws = sanitize_id(&q.workspace_id.unwrap_or_else(|| "default".to_string()));
    let limit = q.limit.unwrap_or(100).min(1000);
    let rt = lean_ctx::core::context_os::runtime();
    let events = rt.bus.read(&ws, "default", 0, limit);
    let mut counts_by_kind = serde_json::Map::new();
    for ev in &events {
        let counter = counts_by_kind
            .entry(ev.kind.clone())
            .or_insert(serde_json::Value::from(0u64));
        if let Some(n) = counter.as_u64() {
            *counter = serde_json::Value::from(n + 1);
        }
    }
    Json(serde_json::json!({
        "workspaceId": ws,
        "channelId": "default",
        "projectRoot": state.project_root,
        "totalEvents": events.len(),
        "eventCountsByKind": counts_by_kind,
        "limit": limit,
    }))
}

#[derive(Deserialize)]
struct EventsSearchQuery {
    #[serde(default)]
    q: Option<String>,
    #[serde(default)]
    limit: Option<usize>,
}

async fn v1_events_search(Query(q): Query<EventsSearchQuery>) -> impl IntoResponse {
    let query = q.q.unwrap_or_default();
    let limit = q.limit.unwrap_or(50).min(500);
    let rt = lean_ctx::core::context_os::runtime();
    let all_events = rt.bus.read("default", "default", 0, limit * 10);
    let results: Vec<serde_json::Value> = all_events
        .into_iter()
        .filter(|ev| {
            let payload = serde_json::to_string(ev).unwrap_or_default();
            query.is_empty() || payload.contains(&query)
        })
        .take(limit)
        .map(|ev| serde_json::to_value(&ev).unwrap_or_default())
        .collect();
    Json(serde_json::json!({
        "query": query,
        "results": results,
        "count": results.len(),
    }))
}

#[derive(Deserialize)]
struct EventLineageQuery {
    #[serde(default)]
    id: Option<i64>,
    #[serde(default)]
    depth: Option<usize>,
}

async fn v1_events_lineage(Query(q): Query<EventLineageQuery>) -> impl IntoResponse {
    let event_id = q.id.unwrap_or(0);
    let depth = q.depth.unwrap_or(10).min(100);
    let rt = lean_ctx::core::context_os::runtime();
    let events = rt.bus.read("default", "default", 0, depth);
    let chain: Vec<serde_json::Value> = events
        .into_iter()
        .filter(|ev| ev.id >= event_id)
        .take(depth)
        .map(|ev| serde_json::to_value(&ev).unwrap_or_default())
        .collect();
    Json(serde_json::json!({
        "eventId": event_id,
        "depth": depth,
        "chain": chain,
    }))
}

async fn v1_metrics(State(_state): State<AppState>) -> impl IntoResponse {
    let rt = lean_ctx::core::context_os::runtime();
    let snap = rt.metrics.snapshot();
    (
        StatusCode::OK,
        Json(serde_json::to_value(snap).unwrap_or_default()),
    )
}

async fn a2a_jsonrpc(State(state): State<AppState>, Json(body): Json<Value>) -> impl IntoResponse {
    let req: lean_ctx::core::a2a::a2a_compat::JsonRpcRequest = match serde_json::from_value(body) {
        Ok(r) => r,
        Err(e) => {
            tracing::debug!("a2a JSON-RPC parse error: {e}");
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": null,
                    "error": {"code": -32700, "message": "invalid request"}
                })),
            );
        }
    };
    let resp = match lean_ctx::core::a2a::task::TaskStore::scoped_path(&state.project_root) {
        Ok(path) => lean_ctx::core::a2a::a2a_compat::handle_a2a_jsonrpc_at_path(&req, &path),
        Err(error) => {
            tracing::warn!("A2A project scope error: {error}");
            lean_ctx::core::a2a::a2a_compat::JsonRpcResponse::server_error(
                req.id.clone(),
                "task storage unavailable",
            )
        }
    };
    let json = serde_json::to_value(resp).unwrap_or_default();
    (StatusCode::OK, Json(json))
}

async fn v1_a2a_agent_card(State(state): State<AppState>) -> impl IntoResponse {
    let card = lean_ctx::core::a2a::agent_card::build_agent_card(
        &state.project_root,
        state.token.is_some(),
    );
    (
        StatusCode::OK,
        [(header::CONTENT_TYPE, "application/json")],
        Json(card),
    )
}

async fn v1_agents_register(State(state): State<AppState>, Json(body): Json<Value>) -> Response {
    let agent_type = body
        .get("agent_type")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown");
    let role = body.get("role").and_then(|v| v.as_str());
    let project_root = body
        .get("project_root")
        .and_then(|v| v.as_str())
        .unwrap_or(&state.project_root);

    match lean_ctx::core::agents::AgentRegistry::mutate_locked(|registry| {
        registry.register(agent_type, role, project_root, None)
    }) {
        Ok((_, agent_id)) => (
            StatusCode::CREATED,
            Json(serde_json::json!({
                "agent_id": agent_id,
                "status": "registered"
            })),
        )
            .into_response(),
        Err(error) => {
            tracing::warn!(%error, "lean-ctx: agent registration failed");
            (
                StatusCode::SERVICE_UNAVAILABLE,
                Json(serde_json::json!({"error": "agent registry unavailable"})),
            )
                .into_response()
        }
    }
}

async fn v1_agents_heartbeat(Json(body): Json<Value>) -> Response {
    let agent_id = body.get("agent_id").and_then(|v| v.as_str()).unwrap_or("");
    match lean_ctx::core::agents::AgentRegistry::mutate_locked(|registry| {
        registry.update_heartbeat(agent_id)
    })
    .and_then(|(_, result)| result)
    {
        Ok(()) => (StatusCode::OK, Json(serde_json::json!({"status": "ok"}))).into_response(),
        Err(error) => {
            tracing::warn!(%error, agent_id, "lean-ctx: rejected agent heartbeat");
            let (status, message) = if error.starts_with("agent presence '") {
                (StatusCode::NOT_FOUND, "unknown agent id")
            } else {
                (
                    StatusCode::SERVICE_UNAVAILABLE,
                    "agent registry unavailable",
                )
            };
            (
                status,
                Json(serde_json::json!({
                    "error": message,
                    "status": "rejected"
                })),
            )
                .into_response()
        }
    }
}

async fn v1_agents_list() -> impl IntoResponse {
    let registry = lean_ctx::core::agents::AgentRegistry::load_or_create();
    let active = registry.list_active(None);
    Json(serde_json::json!({
        "agents": active.iter().map(|a| serde_json::json!({
            "agent_id": a.agent_id,
            "agent_type": a.agent_type,
            "role": a.role,
            "status": a.status.to_string(),
            "last_active": a.last_active.to_rfc3339(),
        })).collect::<Vec<_>>()
    }))
}

async fn v1_agents_deregister(Json(body): Json<Value>) -> Response {
    let agent_id = body.get("agent_id").and_then(|v| v.as_str()).unwrap_or("");
    match lean_ctx::core::agents::AgentRegistry::mutate_locked(|registry| {
        registry.set_status(
            agent_id,
            lean_ctx::core::agents::AgentStatus::Finished,
            Some("deregistered via API"),
        )
    })
    .and_then(|(_, result)| result)
    {
        Ok(()) => (
            StatusCode::OK,
            Json(serde_json::json!({"status": "deregistered"})),
        )
            .into_response(),
        Err(error) => {
            tracing::warn!(%error, agent_id, "lean-ctx: rejected agent deregistration");
            let (status, message) = if error.starts_with("agent presence '") {
                (StatusCode::NOT_FOUND, "unknown agent id")
            } else {
                (
                    StatusCode::SERVICE_UNAVAILABLE,
                    "agent registry unavailable",
                )
            };
            (
                status,
                Json(serde_json::json!({
                    "error": message,
                    "status": "rejected"
                })),
            )
                .into_response()
        }
    }
}

async fn v1_agents_events_sse()
-> Sse<impl Stream<Item = Result<SseEvent, std::convert::Infallible>>> {
    let stream = futures::stream::unfold(0usize, |last_count| async move {
        loop {
            tokio::time::sleep(Duration::from_secs(5)).await;
            let registry = lean_ctx::core::agents::AgentRegistry::load_or_create();
            let active = registry.list_active(None);
            let count = active.len();
            if count != last_count {
                let data = serde_json::json!({
                    "type": "agents_changed",
                    "active_count": count,
                    "agents": active.iter().map(|a| &a.agent_id).collect::<Vec<_>>(),
                });
                return Some((
                    Ok::<_, std::convert::Infallible>(SseEvent::default().data(data.to_string())),
                    count,
                ));
            }
        }
    });

    Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))
}

fn build_app_router(
    cfg: &HttpServerConfig,
    receipt_authority: Option<Arc<lean_ctx::core::execution_ledger::host::HostReceiptAuthority>>,
) -> Router {
    build_app_router_with_auth(cfg, true, receipt_authority)
}

#[cfg(test)]
pub(crate) fn build_delivery_test_router(cfg: &HttpServerConfig) -> Router {
    build_app_router_with_auth(cfg, false, None)
}

fn build_app_router_with_auth(
    cfg: &HttpServerConfig,
    require_auth: bool,
    receipt_authority: Option<Arc<lean_ctx::core::execution_ledger::host::HostReceiptAuthority>>,
) -> Router {
    build_router(cfg, require_auth, false, receipt_authority)
}

/// The router of the local daemon socket: tool calls may name their project.
pub(crate) fn build_ipc_router(
    cfg: &HttpServerConfig,
    receipt_authority: Option<Arc<lean_ctx::core::execution_ledger::host::HostReceiptAuthority>>,
) -> Router {
    build_router(cfg, false, true, receipt_authority)
}

fn build_router(
    cfg: &HttpServerConfig,
    require_auth: bool,
    local_ipc: bool,
    receipt_authority: Option<Arc<lean_ctx::core::execution_ledger::host::HostReceiptAuthority>>,
) -> Router {
    let project_root = cfg.project_root.to_string_lossy().to_string();
    let service_project_root = project_root.clone();
    let project_authority = receipt_authority.clone();
    let project_factory = move |root: &str| {
        let mut server = LeanCtxServer::new_shared_with_context(root, "default", "default");
        server
            .native_receipt_authority
            .clone_from(&project_authority);
        server
    };
    // REST and Streamable HTTP share the same startup authority snapshot.
    let server_factory = move || {
        let mut server =
            LeanCtxServer::new_shared_with_context(&service_project_root, "default", "default");
        server
            .native_receipt_authority
            .clone_from(&receipt_authority);
        server
    };
    let rest_server = server_factory();
    let service_factory = move || -> Result<LeanCtxServer, std::io::Error> { Ok(server_factory()) };
    let mcp_http = StreamableHttpService::new(
        service_factory,
        Arc::new(
            rmcp::transport::streamable_http_server::session::local::LocalSessionManager::default(),
        ),
        cfg.mcp_http_config(),
    );

    let state = AppState {
        token: if require_auth {
            cfg.effective_auth_token()
        } else {
            None
        },
        a2a_signing_key: cfg.a2a_signing_key.clone(),
        a2a_recipient_id: cfg.a2a_recipient_id.clone(),
        a2a_tenant_id: cfg.a2a_tenant_id.clone(),
        a2a_project_id: cfg.a2a_project_id.clone(),
        a2a_peers: Arc::new(cfg.a2a_peers.clone()),
        relay_quotas: match cfg.relay_quota_state() {
            Ok(state) => state.map(|state| Arc::new(tokio::sync::Mutex::new(state))),
            Err(error) => {
                tracing::error!("relay quota configuration rejected: {error}");
                None
            }
        },
        a2a_task_authority: Arc::new(cfg.a2a_task_authority.clone()),
        concurrency: Arc::new(tokio::sync::Semaphore::new(cfg.max_concurrency.max(1))),
        rate: Arc::new(RateLimiter::new(cfg.max_rps, cfg.rate_burst)),
        remote_replays: Arc::new(remote_replay::RemoteReplayGuard::new(
            &project_root,
            handlers::REMOTE_REPLAY_RETENTION_SECONDS,
        )),
        project_root,
        timeout: Duration::from_millis(cfg.request_timeout_ms.max(1)),
        server: rest_server,
        local_ipc,
        project_servers: Arc::new(ProjectServers {
            servers: tokio::sync::Mutex::new(Vec::new()),
            factory: Box::new(project_factory),
        }),
    };

    let ocla = match (
        state.token.as_ref(),
        state.a2a_tenant_id.as_deref(),
        state.a2a_project_id.as_deref(),
    ) {
        (Some(_), Some(tenant_id), Some(project_id)) => {
            match lean_ctx::core::a2a::dlq::DlqScope::new(tenant_id, project_id) {
                Ok(scope) => lean_ctx::core::ocla::wire_api::ocla_router_with_dlq(scope),
                Err(_) => lean_ctx::core::ocla::wire_api::ocla_router(),
            }
        }
        _ => lean_ctx::core::ocla::wire_api::ocla_router(),
    };

    // Local Service v1 (Local Read routes, live events): the daemon socket
    // only — its 0600 mode is the guard; a TCP server never serves them.
    let local_routes = if local_ipc {
        local_service::router()
    } else {
        Router::new()
    };

    Router::new()
        .route("/health", get(health))
        .route("/v1/health", get(v1_health))
        .route(
            "/ocla/v1/delivery/scoped",
            axum::routing::post(scoped_delivery::execute),
        )
        .route("/v1/shutdown", axum::routing::post(v1_shutdown))
        .route("/v1/index/ensure", axum::routing::post(v1_index_ensure))
        .route("/v1/manifest", get(v1_manifest))
        .route("/v1/capabilities", get(v1_capabilities))
        .route("/v1/openapi.json", get(v1_openapi))
        .route("/v1/cache/stats", get(v1_cache_stats))
        .route("/v1/tools", get(v1_tools))
        .route("/v1/tools/call", axum::routing::post(v1_tool_call))
        .route("/v1/events", get(v1_events))
        .route("/v1/metrics", get(v1_metrics))
        .route("/v1/context/summary", get(v1_context_summary))
        .route("/v1/events/search", get(v1_events_search))
        .route("/v1/events/lineage", get(v1_events_lineage))
        .route("/v1/audit/events", get(v1_audit_events))
        .route("/v1/a2a/handoff", axum::routing::post(v1_a2a_handoff))
        .route("/a2a/deliver", axum::routing::post(handlers::a2a_deliver))
        .route("/v1/a2a/agent-card", get(v1_a2a_agent_card))
        .route("/.well-known/agent.json", get(v1_a2a_agent_card))
        .route(
            "/.well-known/mcp-server.json",
            get(discovery::mcp_server_card),
        )
        .route("/a2a", axum::routing::post(a2a_jsonrpc))
        .route(
            "/v1/agents/register",
            axum::routing::post(v1_agents_register),
        )
        .route(
            "/v1/agents/heartbeat",
            axum::routing::post(v1_agents_heartbeat),
        )
        .route("/v1/agents/list", get(v1_agents_list))
        .route(
            "/v1/agents/deregister",
            axum::routing::post(v1_agents_deregister),
        )
        .route("/v1/agents/events", get(v1_agents_events_sse))
        .route("/v1/kernel/dashboard", get(kernel_api::dashboard))
        .route("/v1/kernel/etpao", get(kernel_api::etpao))
        .route("/v1/kernel/config", get(kernel_api::get_config))
        .route(
            "/v1/kernel/config",
            axum::routing::post(kernel_api::set_config),
        )
        .route("/v1/kernel/evidence", get(kernel_api::evidence))
        .route("/v1/kernel/health", get(kernel_api::health))
        .route("/v1/kernel/report", get(kernel_api::report))
        .route(
            "/v1/kernel/reset",
            axum::routing::post(kernel_api::reset_state),
        )
        .merge(ocla.with_state(()))
        .merge(local_routes)
        .fallback_service(mcp_http)
        .layer(axum::extract::DefaultBodyLimit::max(cfg.max_body_bytes))
        .layer(middleware::from_fn_with_state(
            state.clone(),
            rate_limit_middleware,
        ))
        .layer(middleware::from_fn_with_state(
            state.clone(),
            concurrency_middleware,
        ))
        .layer(middleware::from_fn_with_state(
            state.clone(),
            auth_middleware,
        ))
        .with_state(state)
}

pub async fn serve(cfg: HttpServerConfig) -> Result<()> {
    lean_ctx::core::protocol::set_mcp_context(true);
    cfg.validate()?;
    let receipt_authority =
        lean_ctx_server::server::native_receipts::load_configured_host_authority()
            .map_err(anyhow::Error::msg)?;
    // Observations never block dispatch; the request ledger publishes for
    // `lean-ctx doctor` and `/v1/health` (#2196, #2197).
    lean_ctx::core::request_ledger::start_serving("http");
    // Apply the `LEAN_CTX_KERNEL_*` switches once, so kernel health
    // (`/v1/kernel/health`) reports the configuration this server runs with.
    lean_ctx::core::context_kernel::startup::initialize();

    // Surface any path-jail relaxation inherited from the launch env or config,
    // so a loosened boundary is never silent (GH security audit, finding 3).
    lean_ctx::core::pathjail::warn_if_relaxed();

    // Pre-warm the project indices in the background for this long-lived HTTP
    // server. The stdio path deliberately stays lazy — short-lived respawns must
    // not each pay a full graph + BM25 scan (#453) — but `serve` is a single,
    // persistent process: one background build gives the first heavy/search tool
    // call a warm index instead of racing a cold scan of a large project root
    // against the per-request timeout (the SDK-conformance regression, GL #395).
    // The build is deduped per root and idle CPU settles flat once it completes
    // (the memory guard backs off), so #453 idle hygiene is preserved.
    let warm_root = cfg.project_root.to_string_lossy().to_string();
    // Under a Workspace only one of its roots is warmed (#2120).
    if !warm_root.is_empty()
        && lean_ctx::core::workspace_authority::root_authorized(std::path::Path::new(&warm_root))
    {
        lean_ctx::core::index_orchestrator::ensure_all_background(&warm_root);
    }

    let addr: SocketAddr = format!("{}:{}", cfg.host, cfg.port)
        .parse()
        .context("invalid host/port")?;

    let app = build_app_router(&cfg, receipt_authority);

    let listener = tokio::net::TcpListener::bind(addr)
        .await
        .with_context(|| format!("bind {addr}"))?;

    tracing::info!(
        "lean-ctx Streamable HTTP server listening on http://{addr} (project_root={})",
        cfg.project_root.display()
    );

    let served = axum::serve(listener, app)
        .with_graceful_shutdown(async move {
            let _ = tokio::signal::ctrl_c().await;
        })
        .await
        .context("http server");
    finish_serving().await;
    served
}

/// Serve the daemon over a platform-independent IPC channel (UDS on Unix,
/// Named Pipes on Windows).
pub async fn serve_ipc(cfg: HttpServerConfig, addr: lean_ctx::ipc::DaemonAddr) -> Result<()> {
    cfg.validate()?;
    let receipt_authority =
        lean_ctx_server::server::native_receipts::load_configured_host_authority()
            .map_err(anyhow::Error::msg)?;
    // Observations never block dispatch; the request ledger publishes for
    // `lean-ctx doctor` (#2196, #2197).
    lean_ctx::core::request_ledger::start_serving("daemon");
    lean_ctx::core::context_kernel::startup::initialize();

    lean_ctx::core::telemetry_send::spawn_daemon_telemetry();
    lean_ctx::core::context_admission::receipt_store::retention::maintain_at_startup();
    // One Hive scheduler per machine (the daemon is the singleton).
    lean_ctx_hive::scheduler::spawn(lean_ctx::core::config::Config::load().hive.clone());
    // One Hive bus relay per machine, beside the scheduler.
    lean_ctx_hive::bus::spawn(lean_ctx::core::config::Config::load().hive.clone());

    match addr {
        #[cfg(unix)]
        lean_ctx::ipc::DaemonAddr::Unix(ref path) => {
            let app = build_ipc_router(&cfg, receipt_authority);
            let listener = lean_ctx::ipc::bind_listener(&addr)?;

            tracing::info!(
                "lean-ctx daemon listening on {} (project_root={})",
                path.display(),
                cfg.project_root.display()
            );

            let served = axum::serve(listener, app.into_make_service())
                .with_graceful_shutdown(async move {
                    let _ = tokio::signal::ctrl_c().await;
                })
                .await
                .context("ipc server");
            finish_serving().await;
            served
        }
        #[cfg(windows)]
        lean_ctx::ipc::DaemonAddr::NamedPipe(ref name) => {
            let app = build_ipc_router(&cfg, receipt_authority);
            let listener = lean_ctx::ipc::bind_listener(&addr)?;

            tracing::info!(
                "lean-ctx daemon listening on {} (project_root={})",
                name,
                cfg.project_root.display()
            );

            let served = axum::serve(listener, app.into_make_service())
                .with_graceful_shutdown(async move {
                    let _ = tokio::signal::ctrl_c().await;
                })
                .await
                .context("ipc server");
            finish_serving().await;
            served
        }
    }
}

#[cfg(test)]
mod cancellation_tests;

#[cfg(test)]
mod native_receipt_tests;

#[cfg(test)]
#[path = "main_http_tests.rs"]
mod tests;