symforge 11.12.0

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
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
//! The stdio front handler: answers the MCP handshake before the project
//! runtime exists.
//!
//! The stdio adapter used to open its daemon session (or build its local index)
//! before the transport came up, so `initialize` sat unread until the project
//! was loaded. On a large repository that is minutes, far past a harness's
//! connect timeout, and the server was reported failed. This handler goes onto
//! the transport first. Its static surfaces (`initialize`, `discover`, and the
//! tool/resource/prompt lists) come from a shell [`SymForgeServer`], whose list
//! surfaces are the same static code the real server runs. Everything that
//! touches a project goes to the real server once the startup task publishes
//! it.
//!
//! A tool call, resource read or prompt that arrives while the project is
//! still opening, or a tool call while its index is still loading, waits here
//! for up to [`TOOL_READINESS_WAIT`] so small and medium repositories never
//! surface the condition. Past that it is answered with the initial-indexing
//! notice, typed as not executed, never with an empty answer. `status` and
//! `health` never wait: they report the loading state at once.

use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};

use parking_lot::Mutex;
use rmcp::model::{
    CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, GetPromptRequestParams,
    GetPromptResponse, ListPromptsResult, ListResourceTemplatesResult, ListResourcesResult,
    ListToolsResult, PaginatedRequestParams, ProgressNotificationParam, ProtocolVersion,
    ReadResourceRequestParams, ReadResourceResponse, ServerConfig,
};
use rmcp::service::{NotificationContext, RequestContext};
use rmcp::{ErrorData, RoleServer, ServerHandler};
use tokio::sync::watch;

use super::SymForgeServer;
use super::format::INDEXING_IN_PROGRESS;
use super::result_status::{
    OutcomeClass, PROJECT_EVIDENCE_META_KEY, ResultStatus, attach_project_evidence_meta,
};

/// How long a request waits server-side for the project to become ready
/// before answering not-ready. Kept below common harness tool timeouts.
pub const TOOL_READINESS_WAIT: Duration = Duration::from_secs(25);
/// How often a waiting call re-checks readiness when nothing was published.
const READINESS_POLL: Duration = Duration::from_millis(500);
/// How often a waiting call that carried a progress token reports progress.
const PROGRESS_INTERVAL: Duration = Duration::from_secs(5);

/// How far the stdio startup task has got.
#[derive(Clone)]
pub enum StdioStartup {
    /// The project runtime is still being opened or built.
    Starting,
    /// The runtime exists; every request goes to it.
    Ready(Arc<SymForgeServer>),
    /// Startup failed; nothing will become ready in this process.
    Failed(Arc<str>),
}

/// Held by the startup task. If the task ends while the front still says
/// `Starting`, by a panic or by an exit that published nothing, dropping this
/// publishes a failure, so waiting requests end instead of waiting for a
/// runtime that is never coming. The second field is the shutdown signal: a
/// task that stopped because the client left has no failure to report.
pub struct StartupGuard(
    pub Arc<watch::Sender<StdioStartup>>,
    pub watch::Receiver<bool>,
);

impl Drop for StartupGuard {
    fn drop(&mut self) {
        if *self.1.borrow() {
            return;
        }
        self.0.send_if_modified(|state| {
            let starting = matches!(state, StdioStartup::Starting);
            if starting {
                *state = StdioStartup::Failed(
                    "the startup task stopped before the project runtime came up. This is a \
                     symforge bug; a panic message, if there was one, is on symforge's stderr"
                        .into(),
                );
            }
            starting
        });
    }
}

#[derive(Clone)]
pub struct DeferredStdioServer {
    /// Serves only the static surfaces. It is never bound to a project and
    /// never runs a tool.
    shell: Arc<SymForgeServer>,
    project_root: Arc<str>,
    project_name: Arc<str>,
    /// When this process began opening the project: the only clock the
    /// not-ready answers report, because it is the only one observed here.
    opened_at: Instant,
    readiness_wait: Duration,
    startup: watch::Receiver<StdioStartup>,
    /// Set once a probe saw the runtime's index ready; later calls dispatch
    /// without probing first.
    index_seen_ready: Arc<std::sync::atomic::AtomicBool>,
}

impl DeferredStdioServer {
    /// A front handler for `project_root`, plus the sender the startup task
    /// publishes the real server (or its failure) through.
    pub fn new(project_root: &Path) -> (Self, watch::Sender<StdioStartup>) {
        let (sender, startup) = watch::channel(StdioStartup::Starting);
        let shell = SymForgeServer::new(
            crate::live_index::LiveIndex::empty(),
            "project".to_string(),
            Arc::new(Mutex::new(crate::watcher::WatcherInfo::default())),
            None,
            None,
        );
        let project_name = project_root
            .file_name()
            .map(|name| name.to_string_lossy().into_owned())
            .unwrap_or_else(|| project_root.display().to_string());
        let front = Self {
            shell: Arc::new(shell),
            project_root: project_root.display().to_string().into(),
            project_name: project_name.into(),
            opened_at: Instant::now(),
            readiness_wait: TOOL_READINESS_WAIT,
            startup,
            index_seen_ready: Arc::default(),
        };
        (front, sender)
    }

    #[cfg(test)]
    fn with_readiness_wait(mut self, wait: Duration) -> Self {
        self.readiness_wait = wait;
        self
    }

    /// The initial-indexing notice with the one progress figure observed here.
    fn indexing_line(&self) -> String {
        format!(
            "symforge: {}: {INDEXING_IN_PROGRESS}. {}s since this symforge process began \
             opening it; tool calls wait up to {}s for it.",
            self.project_name,
            self.opened_at.elapsed().as_secs(),
            self.readiness_wait.as_secs()
        )
    }

    fn not_ready_text(&self, waited: Duration) -> String {
        format!(
            "Index is loading... {} This call waited {}s and was not executed. Nothing is wrong: \
             retry the same call, and do not read this as an error or an empty result.",
            self.indexing_line(),
            waited.as_secs()
        )
    }

    fn failed_text(&self, reason: &str) -> String {
        format!(
            "Error: symforge failed to start for {}: {reason}",
            self.project_root
        )
    }

    fn not_ready_result(&self, waited: Duration) -> CallToolResponse {
        front_answer(
            ResultStatus::new(OutcomeClass::InternalFailure)
                .into_call_tool_result(self.not_ready_text(waited)),
        )
    }

    /// The real server for a resource read or prompt, waiting for it as a
    /// tool call does. Still starting after the wait is an explicit,
    /// retryable not-ready error.
    async fn ready_server(&self) -> Result<Arc<SymForgeServer>, ErrorData> {
        let started = Instant::now();
        let mut startup = self.startup.clone();
        let _ = tokio::time::timeout(
            self.readiness_wait,
            startup.wait_for(|state| !matches!(state, StdioStartup::Starting)),
        )
        .await;
        let phase = self.startup.borrow().clone();
        match phase {
            StdioStartup::Ready(server) => Ok(server),
            StdioStartup::Failed(reason) => {
                Err(ErrorData::internal_error(self.failed_text(&reason), None))
            }
            StdioStartup::Starting => {
                let waited = started.elapsed();
                Err(ErrorData::internal_error(
                    self.not_ready_text(waited),
                    Some(serde_json::json!({
                        "retryable": true,
                        "waited_ms": waited.as_millis() as u64,
                    })),
                ))
            }
        }
    }
}

/// An answer the front built itself. No project is bound behind it yet, so it
/// carries the explicit evidence-unavailable marker every tool result must
/// carry (FR-319) rather than no evidence at all.
fn front_answer(mut result: CallToolResult) -> CallToolResponse {
    attach_project_evidence_meta(&mut result.meta);
    CallToolResponse::Complete(result)
}

/// A loading-guard refusal. Every guard returns it before its tool body
/// runs, so the call can be repeated without repeating any effect.
fn is_loading_refusal(response: &CallToolResponse) -> bool {
    let CallToolResponse::Complete(result) = response else {
        return false;
    };
    crate::protocol::result_status::observed_outcome_class(result.meta.as_ref())
        == Some(OutcomeClass::InternalFailure)
        && reports_loading(result)
}

/// Whether the runtime's index is still loading, asked through `status`. It
/// answers while loading and records nothing, so a call waits here without
/// ever dispatching a tool whose loading refusal would still be recorded: the
/// `symforge` facade writes a ledger row for every call, and its refusal is
/// wrapped in an envelope no text check can see. An unanswerable probe says
/// not loading, and the tool itself then answers.
async fn index_loading(server: &SymForgeServer, context: &RequestContext<RoleServer>) -> bool {
    match server
        .call_tool(CallToolRequestParams::new("status"), context.clone())
        .await
    {
        Ok(CallToolResponse::Complete(result)) => reports_loading(&result),
        _ => false,
    }
}

/// Whether the project evidence the server attached observed a loading index.
fn reports_loading(result: &CallToolResult) -> bool {
    result
        .meta
        .as_ref()
        .and_then(|meta| meta.0.get(PROJECT_EVIDENCE_META_KEY))
        .and_then(|evidence| evidence.get("index_state"))
        .and_then(|state| state.as_str())
        == Some("Loading")
}

impl ServerHandler for DeferredStdioServer {
    fn get_info(&self) -> ServerConfig {
        self.shell.get_info()
    }

    fn supported_protocol_versions(&self) -> std::borrow::Cow<'static, [ProtocolVersion]> {
        self.shell.supported_protocol_versions()
    }

    async fn list_tools(
        &self,
        request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, ErrorData> {
        self.shell.list_tools(request, context).await
    }

    async fn list_resources(
        &self,
        request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListResourcesResult, ErrorData> {
        self.shell.list_resources(request, context).await
    }

    async fn list_resource_templates(
        &self,
        request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListResourceTemplatesResult, ErrorData> {
        self.shell.list_resource_templates(request, context).await
    }

    async fn list_prompts(
        &self,
        request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListPromptsResult, ErrorData> {
        self.shell.list_prompts(request, context).await
    }

    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<CallToolResponse, ErrorData> {
        // An off-surface or unknown tool is refused the way the real server
        // refuses it, ready or not: its router is the shell's.
        super::surface_probe::enforce_compact_surface(request.name.as_ref())?;
        if !self.shell.tool_router.has_route(request.name.as_ref()) {
            return Err(ErrorData::invalid_params("tool not found", None));
        }
        let diagnostic = matches!(
            request.name.as_ref(),
            "status" | "health" | "health_compact"
        );
        let started = Instant::now();
        let progress_token = context.meta.get_progress_token();
        let mut next_progress = started;
        let mut startup = self.startup.clone();
        loop {
            let phase = startup.borrow_and_update().clone();
            match phase {
                StdioStartup::Failed(reason) => {
                    return Ok(front_answer(
                        ResultStatus::new(OutcomeClass::InternalFailure)
                            .into_call_tool_result(self.failed_text(&reason)),
                    ));
                }
                StdioStartup::Starting if diagnostic => {
                    let text = format!(
                        "{}\nProject root: {}\nIf a tool call still reports loading after its \
                         wait, retry the same call.",
                        self.indexing_line(),
                        self.project_root,
                    );
                    return Ok(front_answer(CallToolResult::success(vec![
                        ContentBlock::text(text),
                    ])));
                }
                StdioStartup::Starting => {}
                StdioStartup::Ready(server) if diagnostic => {
                    let mut response = server.call_tool(request, context).await?;
                    if let CallToolResponse::Complete(result) = &mut response
                        && reports_loading(result)
                    {
                        result
                            .content
                            .insert(0, ContentBlock::text(self.indexing_line()));
                    }
                    return Ok(response);
                }
                StdioStartup::Ready(server) => {
                    let seen_ready = self.index_seen_ready.load(Ordering::Acquire);
                    if seen_ready || !index_loading(&server, &context).await {
                        self.index_seen_ready.store(true, Ordering::Release);
                        let response = server.call_tool(request.clone(), context.clone()).await?;
                        // A plain guard refusal after the index was seen ready: a
                        // later load, such as a retry, is in flight. Such tools
                        // record nothing, so retrying through dispatch is safe.
                        if !is_loading_refusal(&response) {
                            return Ok(response);
                        }
                    }
                }
            }

            let waited = started.elapsed();
            if waited >= self.readiness_wait {
                return Ok(self.not_ready_result(waited));
            }
            if let Some(token) = &progress_token
                && Instant::now() >= next_progress
            {
                let progress = ProgressNotificationParam::new(token.clone(), waited.as_secs_f64())
                    .with_message(self.indexing_line());
                let _ = context.peer.notify_progress(progress).await;
                next_progress = Instant::now() + PROGRESS_INTERVAL;
            }
            let pause = READINESS_POLL.min(self.readiness_wait - waited);
            tokio::select! {
                _ = context.ct.cancelled() => return Ok(self.not_ready_result(started.elapsed())),
                changed = startup.changed() => {
                    // A dropped sender publishes nothing more; keep polling.
                    if changed.is_err() {
                        tokio::time::sleep(pause).await;
                    }
                }
                _ = tokio::time::sleep(pause) => {}
            }
        }
    }

    async fn read_resource(
        &self,
        request: ReadResourceRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<ReadResourceResponse, ErrorData> {
        self.ready_server()
            .await?
            .read_resource(request, context)
            .await
    }

    async fn get_prompt(
        &self,
        request: GetPromptRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<GetPromptResponse, ErrorData> {
        self.ready_server()
            .await?
            .get_prompt(request, context)
            .await
    }

    /// Ask for client roots immediately; bind once the runtime exists.
    ///
    /// Previously this waited for [`StdioStartup::Ready`] before forwarding
    /// `notifications/initialized`, so `roots/list` sat behind daemon session
    /// open / index load (3.5–5s). The ask now runs at once; the bind still
    /// applies on the real server when it is Ready. Tool calls continue to wait
    /// honestly for readiness via [`Self::ready_server`] / the call_tool path.
    async fn on_initialized(&self, context: NotificationContext<RoleServer>) {
        let mut startup = self.startup.clone();
        tokio::spawn(async move {
            // Fast path: runtime already up — identical to today's forward.
            // Clone out of the watch Ref before any `.await` so the future stays Send.
            let already = startup.borrow().clone();
            if let StdioStartup::Ready(server) = already {
                server.on_initialized(context).await;
                return;
            }

            // Runtime still starting: solicit roots now, in parallel with
            // waiting for the runtime, so session open / index load cannot
            // delay the client's roots/list. Bind when both are done.
            let roots_ask = SymForgeServer::fetch_client_root_uris(&context.peer);
            let runtime = async {
                match startup
                    .wait_for(|state| !matches!(state, StdioStartup::Starting))
                    .await
                {
                    // Clone StdioStartup out of the watch Ref before any later
                    // `.await` so the spawned future stays Send.
                    Ok(state) => Some(state.clone()),
                    Err(_) => None,
                }
            };
            let (uris, phase) = tokio::join!(roots_ask, runtime);
            let Some(StdioStartup::Ready(server)) = phase else {
                return;
            };
            tracing::info!("client initialized");
            server.apply_prefetched_client_roots(uris).await;
        });
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::{Value, json};
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};

    struct Client {
        lines: tokio::io::Lines<BufReader<tokio::io::ReadHalf<tokio::io::DuplexStream>>>,
        writer: tokio::io::WriteHalf<tokio::io::DuplexStream>,
        /// Notifications that arrived while waiting for a reply.
        notifications: Vec<Value>,
    }

    impl Client {
        async fn send(&mut self, message: Value) {
            let mut line = message.to_string();
            line.push('\n');
            self.writer.write_all(line.as_bytes()).await.unwrap();
        }

        async fn request(&mut self, id: u64, method: &str, params: Value) -> Value {
            self.send(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}))
                .await;
            loop {
                let line = tokio::time::timeout(
                    std::time::Duration::from_secs(10),
                    self.lines.next_line(),
                )
                .await
                .expect("the front handler answers within its readiness wait")
                .unwrap()
                .expect("an open transport");
                let message: Value = serde_json::from_str(&line).unwrap();
                if message.get("id").is_none() {
                    self.notifications.push(message);
                    continue;
                }
                assert_eq!(
                    message["id"],
                    json!(id),
                    "reply to the request just sent: {message}"
                );
                return message;
            }
        }

        async fn initialize(&mut self) {
            let init = self
                .request(
                    1,
                    "initialize",
                    json!({
                        "protocolVersion": "2025-06-18",
                        "capabilities": {},
                        "clientInfo": {"name": "deferred-stdio-test", "version": "0"}
                    }),
                )
                .await;
            assert_eq!(init["result"]["serverInfo"]["name"], json!("symforge"));
            self.send(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}))
                .await;
        }

        async fn call(&mut self, id: u64, name: &str, meta: Option<Value>) -> Value {
            self.call_with(id, name, json!({}), meta).await
        }

        async fn call_with(
            &mut self,
            id: u64,
            name: &str,
            arguments: Value,
            meta: Option<Value>,
        ) -> Value {
            let mut params = json!({"name": name, "arguments": arguments});
            if let Some(meta) = meta {
                params["_meta"] = meta;
            }
            self.request(id, "tools/call", params).await
        }
    }

    fn connect<H: ServerHandler>(handler: H) -> Client {
        let (client, server) = tokio::io::duplex(1 << 20);
        tokio::spawn(async move {
            let service = rmcp::serve_server(handler, tokio::io::split(server)).await?;
            service.waiting().await?;
            anyhow::Ok(())
        });
        let (reader, writer) = tokio::io::split(client);
        Client {
            lines: BufReader::new(reader).lines(),
            writer,
            notifications: Vec::new(),
        }
    }

    fn tool_text(reply: &Value) -> &str {
        reply["result"]["content"][0]["text"].as_str().unwrap()
    }

    fn outcome_class(reply: &Value) -> &Value {
        &reply["result"]["_meta"]["symforge/result_status"]["outcome_class"]
    }

    fn server_with(index: crate::live_index::SharedIndex) -> Arc<SymForgeServer> {
        Arc::new(SymForgeServer::new(
            index,
            "project".to_string(),
            Arc::new(Mutex::new(crate::watcher::WatcherInfo::default())),
            None,
            None,
        ))
    }

    fn loading_server() -> Arc<SymForgeServer> {
        let index = crate::live_index::LiveIndex::empty();
        index.mark_bootstrap_loading();
        server_with(index)
    }

    #[test]
    fn loading_refusal_requires_typed_failure_and_loading_evidence() {
        fn response(outcome: OutcomeClass, index_state: Option<&str>) -> CallToolResponse {
            let mut result =
                ResultStatus::new(outcome).into_call_tool_result("Index is loading... source text");
            let mut meta = result.meta.take().expect("typed outcome metadata");
            if let Some(index_state) = index_state {
                meta.0.insert(
                    PROJECT_EVIDENCE_META_KEY.to_string(),
                    json!({ "index_state": index_state }),
                );
            }
            result.meta = Some(meta);
            CallToolResponse::Complete(result)
        }

        assert!(is_loading_refusal(&response(
            OutcomeClass::InternalFailure,
            Some("Loading"),
        )));
        assert!(!is_loading_refusal(&response(
            OutcomeClass::InternalFailure,
            Some("Ready"),
        )));
        assert!(!is_loading_refusal(&response(
            OutcomeClass::Found,
            Some("Loading"),
        )));
        assert!(!is_loading_refusal(&response(
            OutcomeClass::InternalFailure,
            None,
        )));
    }

    /// The regression: `initialize` and the list surfaces must not wait on the
    /// project runtime. A tool call that outlives its readiness wait gets the
    /// initial-indexing notice with the machine-readable outcome, not an empty
    /// answer; `status` answers at once with the same notice.
    #[tokio::test]
    async fn handshake_is_answered_while_the_project_runtime_is_still_starting() {
        let (front, _startup) = DeferredStdioServer::new(Path::new("/work/large-repo"));
        let mut client = connect(front.with_readiness_wait(Duration::from_millis(300)));
        client.initialize().await;

        let tools = client.request(2, "tools/list", json!({})).await;
        assert!(
            !tools["result"]["tools"].as_array().unwrap().is_empty(),
            "tools/list is served from the static surface: {tools}"
        );

        let pending = client.call(3, "search_symbols", None).await;
        assert_eq!(pending["result"]["isError"], json!(true), "{pending}");
        assert_eq!(
            outcome_class(&pending),
            &json!("internal_failure"),
            "{pending}"
        );
        let text = tool_text(&pending);
        assert!(text.starts_with("Index is loading"), "{text}");
        assert!(text.contains(INDEXING_IN_PROGRESS), "{text}");
        assert!(text.contains("large-repo"), "names the project: {text}");
        assert!(text.contains("retry the same call"), "{text}");
        assert_eq!(
            pending["result"]["_meta"]["symforge/project_evidence"]["bound"],
            json!(false),
            "a front answer discloses that no project evidence exists yet: {pending}"
        );

        let status = client.call(4, "status", None).await;
        assert_ne!(status["result"]["isError"], json!(true), "{status}");
        assert!(
            tool_text(&status).contains(INDEXING_IN_PROGRESS),
            "{status}"
        );
        assert_eq!(
            status["result"]["_meta"]["symforge/project_evidence"]["bound"],
            json!(false),
            "{status}"
        );
    }

    /// A call that arrives before the runtime exists waits for it and is then
    /// served by it, so a quick startup never surfaces the condition.
    #[tokio::test]
    async fn a_tool_call_waits_for_the_runtime_and_is_then_served() {
        let (front, startup) = DeferredStdioServer::new(Path::new("/work/medium-repo"));
        let mut client = connect(front.with_readiness_wait(Duration::from_secs(8)));
        client.initialize().await;

        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(300)).await;
            // An empty, not-loading index answers at once with its own guard.
            startup.send_replace(StdioStartup::Ready(server_with(
                crate::live_index::LiveIndex::empty(),
            )));
        });
        let served = client
            .call(2, "search_symbols", Some(json!({"progressToken": "tok-1"})))
            .await;
        assert!(
            !tool_text(&served).contains(INDEXING_IN_PROGRESS),
            "the published server answered after the wait: {served}"
        );
        assert!(
            client.notifications.iter().any(|note| {
                note["method"] == json!("notifications/progress")
                    && note["params"]["progressToken"] == json!("tok-1")
                    && note["params"]["message"]
                        .as_str()
                        .is_some_and(|message| message.contains(INDEXING_IN_PROGRESS))
            }),
            "a waiting call with a progress token reports progress: {:?}",
            client.notifications
        );
    }

    /// Once the runtime exists but its index is still loading, a tool keeps
    /// waiting and then gets the same notice; `health` answers at once and
    /// leads with the notice; a plain-String guard refusal is typed.
    #[tokio::test]
    async fn a_loading_index_behind_a_ready_runtime_gets_the_same_notice() {
        let (front, startup) = DeferredStdioServer::new(Path::new("/work/large-repo"));
        startup.send_replace(StdioStartup::Ready(loading_server()));
        let mut client = connect(front.with_readiness_wait(Duration::from_millis(600)));
        client.initialize().await;

        let loading = client.call(2, "get_repo_map", None).await;
        assert_eq!(loading["result"]["isError"], json!(true), "{loading}");
        assert_eq!(
            outcome_class(&loading),
            &json!("internal_failure"),
            "{loading}"
        );
        assert!(
            tool_text(&loading).contains(INDEXING_IN_PROGRESS),
            "{loading}"
        );

        let health = client.call(3, "health", None).await;
        assert!(
            tool_text(&health).contains(INDEXING_IN_PROGRESS),
            "health leads with the notice while the index loads: {health}"
        );
    }

    #[tokio::test]
    async fn a_failed_startup_is_reported_instead_of_loading_forever() {
        let (front, startup) = DeferredStdioServer::new(Path::new("/work/large-repo"));
        let mut client = connect(front.with_readiness_wait(Duration::from_secs(8)));
        client.initialize().await;

        // Fails while the call is already waiting: the wait ends at once.
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(200)).await;
            startup.send_replace(StdioStartup::Failed("daemon unreachable".into()));
        });
        let started = Instant::now();
        let reply = client.call(2, "search_symbols", None).await;
        assert!(started.elapsed() < Duration::from_secs(5), "no full wait");
        assert_eq!(reply["result"]["isError"], json!(true), "{reply}");
        assert!(
            tool_text(&reply).starts_with("Error: symforge failed to start")
                && tool_text(&reply).contains("daemon unreachable"),
            "{reply}"
        );

        let status = client.call(3, "status", None).await;
        assert!(
            tool_text(&status).contains("daemon unreachable"),
            "{status}"
        );
    }

    fn real_server() -> SymForgeServer {
        SymForgeServer::new(
            crate::live_index::LiveIndex::empty(),
            "project".to_string(),
            Arc::new(Mutex::new(crate::watcher::WatcherInfo::default())),
            None,
            None,
        )
    }

    /// Repository text can begin with the same words as the loading notice.
    /// The adapter must use attached status metadata, not classify source bytes.
    #[tokio::test]
    async fn file_content_starting_with_loading_notice_is_served() {
        let root = tempfile::tempdir().unwrap();
        let notes = root.path().join("notes");
        std::fs::create_dir_all(&notes).unwrap();
        let path = notes.join("loading.txt");
        std::fs::write(&path, "Index is loading... not really\n").unwrap();

        let index = crate::live_index::LiveIndex::load(root.path()).unwrap();
        let server = Arc::new(SymForgeServer::new(
            index,
            "project".to_string(),
            Arc::new(Mutex::new(crate::watcher::WatcherInfo::default())),
            Some(root.path().to_path_buf()),
            None,
        ));
        let (front, startup) = DeferredStdioServer::new(root.path());
        startup.send_replace(StdioStartup::Ready(server));
        let mut client = connect(front.with_readiness_wait(Duration::from_millis(300)));
        client.initialize().await;

        let status = client.call(2, "status", None).await;
        assert!(
            !tool_text(&status).contains(INDEXING_IN_PROGRESS),
            "the runtime is ready before the content read: {status}"
        );

        let reply = client
            .call_with(
                3,
                "get_file_content",
                json!({
                    "path": "notes/loading.txt",
                    "header": false,
                    "show_line_numbers": false,
                    "force_refresh": true
                }),
                None,
            )
            .await;

        assert_ne!(reply["result"]["isError"], json!(true), "{reply}");
        assert_eq!(outcome_class(&reply), &json!("found"), "{reply}");
        assert_eq!(tool_text(&reply), "Index is loading... not really\n");
    }

    /// Everything the front answers from its shell is what the real server
    /// answers: the four lists, and the error for a tool no router has, which
    /// must not be mistaken for a tool that is still loading.
    #[tokio::test]
    async fn the_front_answers_its_static_surfaces_as_the_real_server_does() {
        let (front, _startup) = DeferredStdioServer::new(Path::new("/work/large-repo"));
        let mut front = connect(front.with_readiness_wait(Duration::from_millis(300)));
        let mut real = connect(real_server());
        front.initialize().await;
        real.initialize().await;

        for (id, method) in [
            (2, "tools/list"),
            (3, "resources/list"),
            (4, "resources/templates/list"),
            (5, "prompts/list"),
        ] {
            let ours = front.request(id, method, json!({})).await;
            let theirs = real.request(id, method, json!({})).await;
            assert!(ours.get("result").is_some(), "{method}: {ours}");
            assert_eq!(ours, theirs, "{method}");
        }

        let ours = front.call(6, "no_such_tool", None).await;
        let theirs = real.call(6, "no_such_tool", None).await;
        assert!(
            ours.get("error").is_some(),
            "an unknown tool is an error, not a loading notice: {ours}"
        );
        assert_eq!(ours, theirs);
    }

    /// A resource read waits like a tool call, then says explicitly that it
    /// was not served and can be retried; once the runtime exists it is
    /// served by it.
    #[tokio::test]
    async fn a_resource_read_while_starting_waits_then_is_explicitly_retryable() {
        let (front, startup) = DeferredStdioServer::new(Path::new("/work/large-repo"));
        let mut client = connect(front.with_readiness_wait(Duration::from_millis(300)));
        client.initialize().await;
        let read = json!({"uri": "symforge://repo/health"});

        let started = Instant::now();
        let pending = client.request(2, "resources/read", read.clone()).await;
        assert!(started.elapsed() >= Duration::from_millis(300), "it waited");
        let message = pending["error"]["message"].as_str().unwrap_or_default();
        assert!(
            message.contains(INDEXING_IN_PROGRESS) && message.contains("retry the same call"),
            "{pending}"
        );
        assert_eq!(
            pending["error"]["data"]["retryable"],
            json!(true),
            "{pending}"
        );

        startup.send_replace(StdioStartup::Ready(server_with(
            crate::live_index::LiveIndex::empty(),
        )));
        let served = client.request(3, "resources/read", read).await;
        assert!(
            !served.to_string().contains(INDEXING_IN_PROGRESS),
            "the runtime answered: {served}"
        );
    }

    /// The client's `initialized` reaches the runtime even though it arrived
    /// before the runtime existed: an unbound server asks for the client's
    /// roots from it.
    #[tokio::test]
    async fn initialized_is_replayed_to_the_runtime_once_it_exists() {
        let (front, startup) = DeferredStdioServer::new(Path::new("/work/large-repo"));
        let mut client = connect(front);
        let init = client
            .request(
                1,
                "initialize",
                json!({
                    "protocolVersion": "2025-06-18",
                    "capabilities": {"roots": {"listChanged": true}},
                    "clientInfo": {"name": "deferred-stdio-test", "version": "0"}
                }),
            )
            .await;
        assert!(init.get("result").is_some(), "{init}");
        client
            .send(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}))
            .await;
        // Roots must be asked immediately — not queued behind runtime Ready.
        let asked = tokio::time::timeout(Duration::from_secs(2), async {
            loop {
                let line = client.lines.next_line().await.unwrap().expect("open");
                let message: Value = serde_json::from_str(&line).unwrap();
                if message["method"] == json!("roots/list") {
                    return message;
                }
            }
        })
        .await
        .expect("roots/list must be solicited before the runtime becomes Ready");
        assert!(asked.get("id").is_some(), "{asked}");
        assert!(
            matches!(&*startup.borrow(), StdioStartup::Starting),
            "roots/list must arrive while the project runtime is still Starting"
        );
        // Publish a still-loading runtime after roots were already asked —
        // bind still applies once Ready, but the ask did not wait for it.
        startup.send_replace(StdioStartup::Ready(loading_server()));
    }

    /// Proof (Task A): `roots/list` is sent before the index is ready. The
    /// deferred front must not wait for `StdioStartup::Ready` (daemon session /
    /// index load) before asking the client for its roots.
    #[tokio::test]
    async fn roots_list_is_sent_before_index_ready() {
        let (front, startup) = DeferredStdioServer::new(Path::new("/work/large-repo"));
        let mut client = connect(front);
        let init = client
            .request(
                1,
                "initialize",
                json!({
                    "protocolVersion": "2025-06-18",
                    "capabilities": {"roots": {"listChanged": true}},
                    "clientInfo": {"name": "deferred-stdio-test", "version": "0"}
                }),
            )
            .await;
        assert!(init.get("result").is_some(), "{init}");

        // Runtime stays Starting with no Ready publish: if roots/list were
        // queued behind Ready, this would time out.
        client
            .send(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}))
            .await;

        let asked = tokio::time::timeout(Duration::from_millis(800), async {
            loop {
                let line = client.lines.next_line().await.unwrap().expect("open");
                let message: Value = serde_json::from_str(&line).unwrap();
                if message["method"] == json!("roots/list") {
                    return message;
                }
            }
        })
        .await
        .expect("roots/list must be sent before the index/runtime is ready");

        assert!(asked.get("id").is_some(), "{asked}");
        assert!(
            matches!(&*startup.borrow(), StdioStartup::Starting),
            "startup must still be Starting when roots/list is sent: roots must not wait for Ready"
        );
        // Never published Ready — so no index can be ready behind this front.
        assert!(
            !matches!(&*startup.borrow(), StdioStartup::Ready(_)),
            "index/runtime must not be Ready yet when roots/list is sent"
        );
    }

    /// A startup task that panics must not leave every request waiting on a
    /// runtime that is never coming.
    #[tokio::test]
    async fn a_startup_task_that_panics_is_reported_as_failed() {
        let (front, startup) = DeferredStdioServer::new(Path::new("/work/large-repo"));
        let (_client_present, shutdown) = watch::channel(false);
        let guard = StartupGuard(Arc::new(startup), shutdown);
        let task = tokio::spawn(async move {
            let _guard = guard;
            panic!("startup exploded");
        });
        assert!(task.await.expect_err("the task panicked").is_panic());

        let mut client = connect(front.with_readiness_wait(Duration::from_secs(8)));
        client.initialize().await;
        let started = Instant::now();
        let reply = client.call(2, "search_symbols", None).await;
        assert!(started.elapsed() < Duration::from_secs(5), "no full wait");
        let text = tool_text(&reply);
        assert!(
            text.starts_with("Error: symforge failed to start")
                && text.contains("startup task stopped"),
            "{reply}"
        );
    }

    /// The `symforge` facade wraps a loading refusal in its envelope and
    /// records a ledger row per call. A Ready runtime whose index is loading
    /// must still make it wait and get the notice, without dispatching it.
    #[tokio::test]
    async fn a_facade_call_waits_for_a_loading_index_without_dispatching() {
        let (front, startup) = DeferredStdioServer::new(Path::new("/work/large-repo"));
        startup.send_replace(StdioStartup::Ready(loading_server()));
        let mut client = connect(front.with_readiness_wait(Duration::from_millis(600)));
        client.initialize().await;

        let started = Instant::now();
        let reply = client
            .call_with(
                2,
                "symforge",
                json!({"query": "where is foo defined"}),
                None,
            )
            .await;
        assert!(started.elapsed() >= Duration::from_millis(600), "it waited");
        assert_eq!(outcome_class(&reply), &json!("internal_failure"), "{reply}");
        let text = tool_text(&reply);
        assert!(
            text.starts_with("Index is loading") && text.contains(INDEXING_IN_PROGRESS),
            "{reply}"
        );

        let status = client.call(3, "status", None).await;
        let status = status.to_string();
        assert!(
            status.contains("ledger_events: 0"),
            "the facade was never dispatched: {status}"
        );
    }

    /// The front words every wait the same way and never claims the load is
    /// the project's first; only the guard, which reads the load source, does.
    #[tokio::test]
    async fn the_front_does_not_call_every_load_initial_indexing() {
        let (front, startup) = DeferredStdioServer::new(Path::new("/work/large-repo"));
        startup.send_replace(StdioStartup::Ready(loading_server()));
        let mut client = connect(front.with_readiness_wait(Duration::from_millis(300)));
        client.initialize().await;

        let status = client.call(2, "status", None).await;
        assert!(
            tool_text(&status).contains(INDEXING_IN_PROGRESS),
            "{status}"
        );
        assert!(!status.to_string().contains("initial indexing"), "{status}");
    }

    /// A startup task that stopped because the client left reports nothing.
    #[tokio::test]
    async fn a_startup_task_stopped_by_the_client_leaving_is_not_a_failure() {
        let (front, startup) = DeferredStdioServer::new(Path::new("/work/large-repo"));
        let (client_left, shutdown) = watch::channel(false);
        client_left.send_replace(true);
        drop(StartupGuard(Arc::new(startup), shutdown));
        assert!(matches!(&*front.startup.borrow(), StdioStartup::Starting));
    }
}