symforge 11.5.1

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
//! The binary's whole dispatcher, hoisted from `src/main.rs` (Feature 020
//! Slice 4, C5 prep): the exposure flip retired the raw `symforge::*`
//! module surface the binary consumed, so the dispatch logic lives in the
//! crate and the binary is a shim over `server_api::run`, which wires here.

use parking_lot::Mutex;
use std::sync::Arc;

use crate::live_index::persist;
use crate::{
    cli, daemon, discovery, live_index, observability, protocol, server, sidecar, version_registry,
    watcher,
};
use clap::Parser;
use rmcp::{serve_server, transport};
use std::ffi::OsString;

/// How a completed dispatch ended, for the `server_api::run` mapping. The
/// serve refusal is a DISTINCT success-shaped exit (the cli-serve contract
/// maps it to process exit code 2), not an error: the server declined to
/// come up and reported that as its outcome.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MainExit {
    /// The dispatched command completed successfully.
    Success,
    /// `symforge serve` refused to start (secure-default startup checks).
    ServeRefusedToStart,
}

/// Run the symforge CLI with `args` (`argv\[0\]` included), exactly as the
/// binary's `main` always has.
pub fn run_main(args: Vec<OsString>) -> anyhow::Result<MainExit> {
    // Record this binary's path+version so a stale durable binary can be
    // detected later (see `version_registry`). Best-effort and read-mostly;
    // runs before the `--version` fast path so the npm-installed binary
    // registers itself when the user verifies an update with `symforge --version`.
    version_registry::record_self_default();

    if cli::version::is_version_request(&args) {
        return cli::version::run_version().map(|()| MainExit::Success);
    }

    let cli = cli::Cli::parse_from(args);
    let completed = match cli.command {
        Some(cli::Commands::Analytics { command }) => cli::analytics::run_analytics(&command),
        Some(cli::Commands::Init {
            client,
            scan,
            apply,
            serve_url,
            serve_key,
        }) => {
            if scan {
                cli::init::run_scan(apply, serve_url, serve_key)
            } else {
                cli::init::run_init(client)
            }
        }
        Some(cli::Commands::Daemon) => run_daemon(),
        Some(cli::Commands::Serve(args)) => return run_serve(args),
        Some(cli::Commands::Setup(args)) => cli::setup::run(args),
        Some(cli::Commands::Admin(args)) => cli::admin::run(args),
        Some(cli::Commands::Hook { subcommand }) => cli::hook::run_hook(subcommand.as_ref()),
        Some(cli::Commands::Trust { subcommand }) => cli::trust::run_trust(&subcommand),
        Some(cli::Commands::Update) => cli::update::run_update(),
        None => run_mcp_server(),
    };
    completed.map(|()| MainExit::Success)
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum StartupPlan {
    Daemon { root: std::path::PathBuf },
    LocalAutoIndex { root: std::path::PathBuf },
    LocalEmpty { reason: String },
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum StartupIndexLogView {
    Ready {
        file_count: usize,
        symbol_count: usize,
        parsed_count: usize,
        partial_parse_count: usize,
        failed_count: usize,
        duration_ms: u64,
    },
    Degraded {
        summary: String,
    },
}

fn startup_index_log_view(
    published: &live_index::PublishedIndexState,
) -> Option<StartupIndexLogView> {
    match published.status {
        live_index::PublishedIndexStatus::Ready => Some(StartupIndexLogView::Ready {
            file_count: published.file_count,
            symbol_count: published.symbol_count,
            parsed_count: published.parsed_count,
            partial_parse_count: published.partial_parse_count,
            failed_count: published.failed_count,
            duration_ms: published.load_duration.as_millis() as u64,
        }),
        live_index::PublishedIndexStatus::Degraded => Some(StartupIndexLogView::Degraded {
            summary: published
                .degraded_summary
                .clone()
                .unwrap_or_else(|| "circuit breaker tripped".to_string()),
        }),
        live_index::PublishedIndexStatus::Empty | live_index::PublishedIndexStatus::Loading => None,
    }
}

fn local_empty_reason(should_auto_index: bool) -> &'static str {
    if !should_auto_index {
        "SYMFORGE_AUTO_INDEX=false — starting with empty index"
    } else {
        "no safe project root found — starting with empty index"
    }
}

fn startup_plan(
    should_auto_index: bool,
    resolved_root: Option<std::path::PathBuf>,
    daemon_available: bool,
) -> StartupPlan {
    match (resolved_root, daemon_available) {
        (Some(root), true) => StartupPlan::Daemon { root },
        (Some(root), false) => StartupPlan::LocalAutoIndex { root },
        (None, _) => StartupPlan::LocalEmpty {
            reason: local_empty_reason(should_auto_index).to_string(),
        },
    }
}

// V11 callbacks census (Feature 020 Slice 4, C3b): ProjectStateDir checkpoint
// writes only (permit-free StateWriteAuthorized per the frozen contract) — it
// snapshots the published index and mutates no repository-source bytes, so it
// holds no source-observation or publication authority.
fn spawn_periodic_checkpoint(
    index: live_index::SharedIndex,
    root: std::path::PathBuf,
    state_placement: crate::domain::StatePlacement,
    interval: std::time::Duration,
) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        loop {
            tokio::time::sleep(interval).await;
            let checkpoint_index = Arc::clone(&index);
            let checkpoint_root = root.clone();
            let checkpoint_placement = state_placement.clone();
            match tokio::task::spawn_blocking(move || {
                persist::checkpoint_shared_index(
                    &checkpoint_index,
                    &checkpoint_root,
                    &checkpoint_placement,
                )
            })
            .await
            {
                Ok(Ok(report)) => tracing::info!(
                    bytes = report.bytes,
                    files = report.files,
                    path = %report.path.display(),
                    "periodic checkpoint wrote .symforge/index.bin"
                ),
                Ok(Err(error)) => tracing::warn!(
                    interval_secs = interval.as_secs(),
                    "periodic checkpoint failed: {error}"
                ),
                Err(join_error) => tracing::warn!(
                    interval_secs = interval.as_secs(),
                    "periodic checkpoint task panicked: {join_error}"
                ),
            }
        }
    })
}

fn run_daemon() -> anyhow::Result<()> {
    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        // Default worker_threads = num_cpus. Tool handlers that acquire
        // std::sync::RwLock are wrapped in spawn_blocking (see daemon.rs
        // call_tool_handler), so they run on the blocking thread pool
        // (up to 512 threads) and don't starve async workers.
        .build()?
        .block_on(async {
            observability::init_tracing()?;
            daemon::run_daemon_until_shutdown("127.0.0.1").await
        })
}

fn run_serve(args: cli::serve::ServeCliArgs) -> anyhow::Result<MainExit> {
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()?;
    let result = runtime.block_on(async {
        observability::init_tracing()?;
        // Secure-startup checks (key resolution, loopback, refuse-to-start) run
        // inside `server::serve::run` before any bind; on a permitted config it
        // mounts `/mcp` and runs until shutdown. Map only the tracing-init error
        // to anyhow here; the serve result stays a typed `ServeError` so
        // refuse-to-start can map to exit code 2 in the shim.
        Ok::<Result<(), server::serve::ServeError>, anyhow::Error>(
            server::serve::run(args.into_serve_args()).await,
        )
    })?;

    match result {
        Ok(()) => Ok(MainExit::Success),
        // Secure-default refuse-to-start is exit code 2 (cli-serve contract):
        // distinct from a generic failure so operators/CI can detect a refused
        // bind specifically. Print the cause; the typed exit carries the code
        // through server_api::run to the binary shim (C5: the lib no longer
        // exits the process itself).
        Err(server::serve::ServeError::Startup(err)) => {
            eprintln!("error: {err}");
            Ok(MainExit::ServeRefusedToStart)
        }
        Err(other) => Err(anyhow::Error::from(other)),
    }
}

fn run_mcp_server() -> anyhow::Result<()> {
    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()?
        .block_on(async { run_mcp_server_async().await })
}

async fn run_mcp_server_async() -> anyhow::Result<()> {
    observability::init_tracing()?;

    // V11 bootstrap (Feature 020 Slice 4, T030, C4b): the stdio surface runs
    // the process activation ceremony before the transport comes up — both
    // the daemon-proxied and local paths below serve only afterwards.
    live_index::index_lifecycle::activation::activate_surface(
        live_index::index_lifecycle::process_runtime::SurfaceKind::Stdio,
    );

    // INFR-02: Auto-index on startup (configurable via SYMFORGE_AUTO_INDEX)
    let should_auto_index = std::env::var("SYMFORGE_AUTO_INDEX")
        .map(|v| v != "false")
        .unwrap_or(true);

    let resolved_root = if should_auto_index {
        discovery::find_project_root()
    } else {
        None
    };

    let use_daemon = std::env::var("SYMFORGE_NO_DAEMON")
        .map(|v| v == "0" || v.is_empty())
        .unwrap_or(true);

    // 012 D4-B (defer launch pin): the launch-CWD bind fires ONLY when
    // `find_project_root()` resolved a usable root (env override or a safe CWD
    // walk). That is the single-harness happy path — a found root pins the
    // daemon session, which now opens BEHIND the transport: the deferred front
    // answers the handshake while the session (or the local fallback index) is
    // built, because building it can take minutes on a large repository.
    //
    // When `resolved_root` is `None` (home-CWD launchers such as Cursor, or a
    // forbidden/too-broad CWD) we deliberately do NOT pin anything: we fall
    // through to the local empty-index startup. A legacy-lifecycle client's
    // declared `roots` then bind the workspace at `on_initialized`
    // (`bind_workspace_from_client_roots`); a modern 2026-07-28
    // discover-lifecycle client never sends `notifications/initialized`, so it
    // binds via `index_folder` instead, with the residual unbound case
    // disclosed through `_meta` project evidence (spec 025 FR-319). Eagerly
    // pinning a home/forbidden CWD is exactly the wrong-repo binding C4 fixes,
    // so deferring on `None` is the fix, not a regression.
    match startup_plan(should_auto_index, resolved_root, use_daemon) {
        StartupPlan::Daemon { root } => {
            run_deferred_mcp_server_async(root, true, should_auto_index).await
        }
        StartupPlan::LocalAutoIndex { root } => {
            run_deferred_mcp_server_async(root, false, should_auto_index).await
        }
        StartupPlan::LocalEmpty { .. } => {
            run_local_mcp_server_async(should_auto_index, None, StdioServe::Direct).await
        }
    }
}

/// Where a built stdio server goes.
enum StdioServe {
    /// Straight onto the stdio transport, served until the client leaves.
    Direct,
    /// Into the deferred front that is already serving stdio; returns once the
    /// front has shut down.
    Deferred {
        startup: Arc<tokio::sync::watch::Sender<protocol::deferred_stdio::StdioStartup>>,
        shutdown: tokio::sync::watch::Receiver<bool>,
    },
}

async fn serve_stdio(server: protocol::SymForgeServer, serve: StdioServe) -> anyhow::Result<()> {
    match serve {
        StdioServe::Direct => {
            let service = serve_server(server, transport::stdio()).await?;
            // Wait for either MCP server shutdown (stdin EOF) or Ctrl+C/SIGTERM.
            tokio::select! {
                result = service.waiting() => { result?; }
                _ = tokio::signal::ctrl_c() => {
                    tracing::info!("Ctrl+C received, shutting down");
                }
            }
        }
        StdioServe::Deferred {
            startup,
            mut shutdown,
        } => {
            startup.send_replace(protocol::deferred_stdio::StdioStartup::Ready(Arc::new(
                server,
            )));
            // An error means the front dropped its sender: it is gone either way.
            let _ = shutdown.wait_for(|stop| *stop).await;
        }
    }
    Ok(())
}

/// Serve stdio on the deferred front handler while the project runtime is
/// built behind it: a daemon session when `use_daemon`, else (or when the
/// daemon cannot be reached) the local index. `initialize` never waits on it.
async fn run_deferred_mcp_server_async(
    root: std::path::PathBuf,
    use_daemon: bool,
    should_auto_index: bool,
) -> anyhow::Result<()> {
    let (front, startup) = protocol::deferred_stdio::DeferredStdioServer::new(&root);
    let publish = Arc::new(startup);
    let (shutdown, shutdown_signal) = tokio::sync::watch::channel(false);
    let runtime = tokio::spawn(async move {
        let _unpublished =
            protocol::deferred_stdio::StartupGuard(Arc::clone(&publish), shutdown_signal.clone());
        let mut client_left = shutdown_signal.clone();
        let serve = StdioServe::Deferred {
            startup: Arc::clone(&publish),
            shutdown: shutdown_signal,
        };
        let result = if use_daemon {
            // The daemon may take minutes to open the project; a client that
            // leaves meanwhile must not hold this process open for it.
            let connected = tokio::select! {
                connected = daemon::connect_or_spawn_session(
                    &root,
                    "mcp-stdio",
                    Some(std::process::id()),
                ) => connected,
                _ = client_left.wait_for(|stop| *stop) => return Ok(()),
            };
            match connected {
                Ok(session) => {
                    daemon::run_then_close_session(session.clone(), async |slot| {
                        run_remote_mcp_server_async(session, serve, slot).await
                    })
                    .await
                }
                Err(error) => {
                    tracing::warn!(
                        root = %root.display(),
                        "daemon-backed startup failed, falling back to local mode: {error}"
                    );
                    run_local_mcp_server_async(should_auto_index, Some(root), serve).await
                }
            }
        } else {
            run_local_mcp_server_async(should_auto_index, Some(root), serve).await
        };
        // A runtime that never came up must say so; one that was already
        // serving keeps its Ready state for the rest of the shutdown.
        if let Err(error) = &result {
            publish.send_if_modified(|state| {
                let starting = matches!(state, protocol::deferred_stdio::StdioStartup::Starting);
                if starting {
                    *state =
                        protocol::deferred_stdio::StdioStartup::Failed(format!("{error:#}").into());
                }
                starting
            });
        }
        result
    });

    tracing::info!("serving MCP on stdio while the project runtime starts");
    let service = match serve_server(front, transport::stdio()).await {
        Ok(service) => service,
        Err(error) => {
            // The runtime task may already hold a daemon session; let it
            // close that before the process goes, exactly as on a normal exit.
            let _ = shutdown.send(true);
            let _ = runtime.await;
            return Err(error.into());
        }
    };
    let served = tokio::select! {
        result = service.waiting() => result.map(|_| ()).map_err(anyhow::Error::from),
        _ = tokio::signal::ctrl_c() => {
            tracing::info!("Ctrl+C received, shutting down");
            Ok(())
        }
    };
    // The runtime tears down (daemon session close, index snapshot, sidecar)
    // only after the front is done with it.
    let _ = shutdown.send(true);
    let runtime = runtime.await;
    served?;
    runtime?
}

/// Serves one daemon-backed stdio session. Closing that session is the
/// caller's job (`daemon::run_then_close_session`), so it happens on every
/// exit path, `?` returns included; this fn only publishes the slot the
/// current session lives in.
async fn run_remote_mcp_server_async(
    session: daemon::DaemonSessionClient,
    serve: StdioServe,
    current_session: &mut Option<daemon::SessionSlot>,
) -> anyhow::Result<()> {
    let control_state_dir = crate::paths::process_control_state_placement()
        .directory()
        .cloned();
    if let (Some(port), Some(state_dir)) = (session.port(), control_state_dir.as_ref()) {
        // Task 8: one atomic per-adapter descriptor instead of the fixed
        // port/pid/session files — a second adapter on the same root can no
        // longer be overwritten or deleted by this one.
        sidecar::port_file::write_session_descriptor(
            state_dir,
            port,
            Some(session.session_id()),
            session.project_root(),
            session.daemon_started_at(),
        )?;
    }

    let state_placement = session.project_root().and_then(|root| {
        match discovery::resolve_root_candidate(
            root,
            crate::domain::RootCandidateSource::LaunchCwd,
            crate::domain::RootRequestMode::Automatic,
        ) {
            crate::domain::RootResolution::Bound(binding) => {
                Some(discovery::resolve_state_placement(&binding))
            }
            crate::domain::RootResolution::Unbound { .. } => None,
        }
    });
    let project_state_dir = state_placement
        .as_ref()
        .and_then(|placement| placement.directory())
        .cloned();
    let mut server = protocol::SymForgeServer::new_daemon_proxy_with_state_placement(
        session.clone(),
        state_placement,
    );
    // Reconnect lifecycle fence: the heartbeat must beat the CURRENT session
    // (read from the server's shared slot each tick), not a stale clone of the
    // original — otherwise the old session is kept alive while the NEW session
    // is never heartbeated and eventually reaped. The descriptor context lets
    // the proxy republish this adapter's descriptor with the new session id
    // after a reconnect.
    if let Some(state_dir) = control_state_dir.as_ref() {
        server.set_descriptor_state_dir(state_dir.clone());
    }
    let heartbeat_slot = server.daemon_client_slot();
    *current_session = heartbeat_slot.clone();
    let heartbeat_task = tokio::spawn(async move {
        loop {
            tokio::time::sleep(std::time::Duration::from_secs(15)).await;
            let Some(slot) = heartbeat_slot.as_ref() else {
                continue;
            };
            let current = slot.read().await.clone();
            let _ = current.heartbeat().await;
        }
    });

    // Feature 013 US1 (T021): the DEFAULT operator stdio is daemon-backed, and
    // the `symforge` compact tool — the ONLY tool that records STEL economics
    // ledger events (via `finalize_symforge_with_ledger`) — executes on THIS
    // proxy server, NOT on the daemon worker. The daemon worker's
    // `execute_tool_call` (daemon.rs) dispatches only the primitive tools +
    // `status`; it has no `symforge` arm. The proxy fetches served data FROM the
    // daemon (each primitive proxies via `proxy_tool_call`), but the economics
    // capture + durable write-through stays on the proxy. So durable accumulation
    // in the daemon-default deployment requires attaching the durable store
    // HERE, on the proxy — mirroring the local-stdio attach (T020) and serve.rs.
    // The proxy and its durable ledger share one already-resolved typed project
    // state owner. A dir/open failure degrades to `Disabled` inside `open`
    // (logged, in-memory, FR-003). This deliberately does not touch the
    // privileged daemon worker.
    //
    // Observability (D2-ROOT): `status` IS proxied to the daemon worker, which
    // owns the index but has an empty ledger + no durable store — but the proxy
    // OWNS the ledger + this store, so `status_stel_tool` overlays ALL of the
    // proxy's OWN ledger/store-derived lines (`ledger_events`, `last_ledger_*`,
    // `durable_ledger`, the `calibration` section) onto the proxied body
    // (`overlay_proxy_status_lines`). The operator therefore sees this proxy's
    // real accumulation + calibration verdict, not the worker's blind
    // `0`/`none`/`unavailable`/`deferred`. If the proxy ALSO has no store /
    // empty ledger, the lines stay truthfully `0`/`none`/`unavailable`/`deferred`.
    if let Some(state_dir) = project_state_dir.as_ref() {
        let store = crate::stel::ledger_store::StelLedgerStore::open(
            state_dir,
            format!("stdio-daemon-{}", std::process::id()),
        );
        server = server.with_stel_ledger_store(Arc::new(store));
    }

    tracing::info!(
        project_id = %session.project_id(),
        session_id = %session.session_id(),
        "starting daemon-backed MCP server on stdio transport"
    );
    // Feature 032 (F3): stdio serves exactly one client per process, so this
    // server instance IS the session — the one lane the repeat tracker may
    // attribute a run to. Declared here, at the transport, so a lane that does
    // not say so stays inert instead of sharing a count across clients.
    let served = serve_stdio(server.with_stdio_transport_lane(), serve).await;

    heartbeat_task.abort();
    // Task 8: remove ONLY this adapter's descriptor; sibling adapters on the
    // same root keep theirs.
    if let Some(state_dir) = control_state_dir.as_ref() {
        sidecar::port_file::cleanup_own_descriptor(state_dir);
    }
    served?;
    tracing::info!("daemon-backed MCP server shut down cleanly");
    Ok(())
}

/// Build the local cold-start index into its `Loading` placeholder in the
/// background. However the load ends, a panic included, the placeholder is
/// settled by the daemon lane's rule and leaves `Loading`.
fn spawn_local_cold_load(
    index: live_index::SharedIndex,
    root: std::path::PathBuf,
    placement: crate::domain::StatePlacement,
) -> tokio::task::JoinHandle<()> {
    tokio::task::spawn_blocking(move || {
        tracing::info!("cold-start indexing in background");
        let result =
            daemon::load_catching_panic(|| index.reload_for_state_placement(&root, &placement));
        if daemon::settle_background_cold_load(&index, &root, result) {
            tracing::info!("background cold-start indexing complete");
        }
    })
}

async fn run_local_mcp_server_async(
    should_auto_index: bool,
    resolved_root: Option<std::path::PathBuf>,
    serve: StdioServe,
) -> anyhow::Result<()> {
    let (index, project_name, watcher_root, state_placement) = if let Some(root) = resolved_root {
        tracing::info!(root = %root.display(), "auto-indexing from project root");

        let binding = match discovery::resolve_root_candidate(
            &root,
            crate::domain::RootCandidateSource::LaunchCwd,
            crate::domain::RootRequestMode::Automatic,
        ) {
            crate::domain::RootResolution::Bound(binding) => binding,
            resolution => anyhow::bail!(
                "resolved local project root no longer satisfies the canonical source guard: {resolution:?}"
            ),
        };
        let state_placement = discovery::resolve_state_placement(&binding);

        // V11 bootstrap (C4b): the local stdio project admits through the
        // process registry before its index is built; a refusal fails the
        // startup honestly.
        live_index::index_lifecycle::activation::admit_project(
            live_index::index_lifecycle::process_runtime::SurfaceKind::Stdio,
            &binding.canonical_root,
            &binding.root_id.0,
            binding.access_mode,
            &state_placement,
        )
        .map_err(|refusal| {
            anyhow::anyhow!(
                "project admission refused for '{}': {refusal:?}",
                binding.root_id.0
            )
        })?;

        // Try loading from persisted snapshot first (fast path: no re-parsing).
        let index = if let Some(snapshot) = persist::load_snapshot(&root, &state_placement) {
            let file_count = snapshot.files.len();
            // Extract mtime map before consuming snapshot
            let snapshot_mtimes: std::collections::HashMap<String, u64> = snapshot
                .files
                .iter()
                .map(|(k, v)| (k.clone(), v.mtime_secs))
                .collect();

            let (live, code_signals) =
                persist::snapshot_to_live_index_with_code_signals(snapshot, &root);
            tracing::info!(
                files = file_count,
                load_source = ?live.load_source(),
                snapshot_verify_state = ?live.snapshot_verify_state(),
                "loaded serialized index from .symforge/index.bin"
            );
            let shared: live_index::SharedIndex =
                live_index::SharedIndexHandle::shared_for_state_placement_with_code_signals(
                    live,
                    &root,
                    &state_placement,
                    code_signals,
                );

            // Spawn background verification to reconcile against current disk state.
            let bg_index = shared.clone();
            let bg_root = root.clone();
            // V11 callbacks census (C3b): carry the observer incarnation
            // current at spawn; a later watcher registration makes it stale
            // and the lane refuses its observations.
            let observer = live_index::index_lifecycle::activation::project_source_authority(&root)
                .active_observer();
            tokio::spawn(async move {
                persist::background_verify(bg_index, bg_root, snapshot_mtimes, observer).await;
            });

            shared
        } else {
            // No snapshot — start with empty index and re-index in background
            // so the MCP server can respond to initialize/tools/list immediately.
            let shared = live_index::LiveIndex::empty();
            shared.mark_bootstrap_loading();
            spawn_local_cold_load(shared.clone(), root.clone(), state_placement.clone());
            shared
        };

        let published = index.published_state();
        match startup_index_log_view(&published) {
            Some(StartupIndexLogView::Ready {
                file_count,
                symbol_count,
                parsed_count,
                partial_parse_count,
                failed_count,
                duration_ms,
            }) => {
                tracing::info!(
                    files = file_count,
                    symbols = symbol_count,
                    parsed = parsed_count,
                    partial = partial_parse_count,
                    failed = failed_count,
                    duration_ms,
                    "LiveIndex ready"
                );
            }
            Some(StartupIndexLogView::Degraded { summary }) => {
                tracing::error!(%summary, "circuit breaker tripped — index degraded");
            }
            None => {}
        }

        let name = root
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("project")
            .to_string();

        (index, name, Some(root), Some(state_placement))
    } else {
        tracing::info!("{}", local_empty_reason(should_auto_index));
        let live = live_index::LiveIndex::empty();
        live.set_local_empty_reason(Some(local_empty_reason(should_auto_index).to_string()));
        (live, "project".to_string(), None, None)
    };

    // Spawn file watcher after initial load (only when auto-index is enabled).
    let watcher_info = Arc::new(Mutex::new(watcher::WatcherInfo::default()));

    if let Some(ref root) = watcher_root {
        let watcher_index = Arc::clone(&index);
        let watcher_root_clone = root.clone();
        let watcher_info_clone = Arc::clone(&watcher_info);
        tokio::spawn(async move {
            watcher::run_watcher(watcher_root_clone, watcher_index, watcher_info_clone).await;
        });
        tracing::info!("file watcher started");
    }

    // Kick off background git temporal analysis (non-blocking).
    if let Some(ref root) = watcher_root {
        let expected_gen = index.current_project_generation();
        live_index::git_temporal::spawn_git_temporal_computation(
            Arc::clone(&index),
            root.clone(),
            expected_gen,
        );
    }

    let periodic_checkpoint = watcher_root
        .as_ref()
        .zip(state_placement.as_ref())
        .and_then(|(root, placement)| {
            persist::checkpoint_interval_from_env().map(|interval| {
                tracing::info!(
                    interval_secs = interval.as_secs(),
                    env = persist::CHECKPOINT_INTERVAL_ENV,
                    "periodic checkpointing enabled"
                );
                spawn_periodic_checkpoint(
                    Arc::clone(&index),
                    root.clone(),
                    placement.clone(),
                    interval,
                )
            })
        });

    // Spawn HTTP sidecar after watcher, before MCP serve.
    // The sidecar shares the same Arc<LiveIndex> so mutations are immediately visible.
    let bind_host =
        std::env::var("SYMFORGE_SIDECAR_BIND").unwrap_or_else(|_| "127.0.0.1".to_string());
    let control_state_dir = crate::paths::process_control_state_placement()
        .directory()
        .cloned();
    let sidecar_handle = sidecar::spawn_sidecar(
        Arc::clone(&index),
        &bind_host,
        watcher_root.clone(),
        control_state_dir,
    )
    .await?;
    tracing::info!(port = sidecar_handle.port, "HTTP sidecar started");

    // Share the sidecar's TokenStats Arc with the MCP server so the health tool
    // can display token savings without an HTTP round-trip. Clone the Arc so
    // `sidecar_handle` remains intact for `shutdown_and_join` below.
    let token_stats = Some(Arc::clone(&sidecar_handle.token_stats));

    // Create MCP server and serve on stdio transport.
    let mut server = protocol::SymForgeServer::new_with_state_placement(
        Arc::clone(&index),
        project_name,
        watcher_info,
        watcher_root.clone(),
        state_placement.clone(),
        token_stats,
    );

    // Feature 013 US1 (T020): attach the durable STEL economics ledger on the
    // LOCAL stdio path so predicted-vs-actual events accumulate ACROSS restarts
    // (FR-001/SC-003), not just in serve mode. Mirrors `serve::build_serve_runtime`:
    // open through the resolved typed project state owner. A dir/open failure
    // degrades to `Disabled` inside `open` (logged, in-memory, FR-003),
    // so stdio never fails to start over a ledger problem. The `symforge` compact
    // tool's `finalize_symforge_with_ledger` write-through then persists each
    // economics row to this store, bringing stdio to parity with serve
    // (Principle VII) for the durable backing.
    if let Some(state_dir) = state_placement
        .as_ref()
        .and_then(|placement| placement.directory())
    {
        let store = crate::stel::ledger_store::StelLedgerStore::open(
            state_dir,
            format!("stdio-{}", std::process::id()),
        );
        server = server.with_stel_ledger_store(Arc::new(store));
    }

    tracing::info!("starting MCP server on stdio transport");
    // Feature 032 (F3): see the daemon-backed path above — stdio is the one
    // transport whose process/client/session identity is observable, so it is
    // the one that declares itself to the repeat tracker.
    serve_stdio(server.with_stdio_transport_lane(), serve).await?;

    tracing::info!("MCP server shut down cleanly");

    if let Some(handle) = periodic_checkpoint {
        handle.abort();
    }

    // Serialize index to disk on clean shutdown.
    // Only serialize when auto-index is enabled (i.e., we have a real project root).
    if let (Some(root), Some(placement)) = (watcher_root.as_ref(), state_placement.as_ref()) {
        match persist::serialize_shared_index(&index, root, placement) {
            Ok(()) => tracing::info!("index serialized to .symforge/index.bin"),
            Err(e) => tracing::warn!("failed to serialize index on shutdown: {e}"),
        }
    }

    // Shutdown the sidecar now that the MCP server has exited.
    sidecar_handle.shutdown_and_join().await;
    tracing::info!("sidecar shutdown complete");

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{
        StartupIndexLogView, StartupPlan, local_empty_reason, spawn_local_cold_load,
        startup_index_log_view, startup_plan,
    };
    use crate::live_index::persist::checkpoint_interval_from_value;
    use crate::live_index::{
        IndexLoadSource, PublishedIndexState, PublishedIndexStatus, SnapshotVerifyState,
    };
    use std::path::PathBuf;
    use std::time::{Duration, SystemTime};

    fn published_state(status: PublishedIndexStatus) -> PublishedIndexState {
        PublishedIndexState {
            generation: 7,
            status,
            degraded_summary: None,
            file_count: 12,
            parsed_count: 10,
            partial_parse_count: 1,
            unexpected_partial_parse_count: 1,
            expected_vendor_partial_parse_count: 0,
            expected_generated_partial_parse_count: 0,
            expected_test_fixture_partial_parse_count: 0,
            expected_template_dsl_partial_parse_count: 0,
            expected_framework_partial_parse_count: 0,
            expected_language_partial_parse_count: 0,
            failed_count: 1,
            partial_parse_files: vec!["src/partial.rs".to_string()],
            unexpected_partial_parse_files: vec!["src/partial.rs".to_string()],
            expected_vendor_partial_parse_files: vec![],
            expected_generated_partial_parse_files: vec![],
            expected_test_fixture_partial_parse_files: vec![],
            expected_template_dsl_partial_parse_files: vec![],
            expected_framework_partial_parse_files: vec![],
            expected_language_partial_parse_files: vec![],
            failed_files: vec![("src/failed.rs".to_string(), "syntax error".to_string())],
            symbol_count: 34,
            loaded_at_system: SystemTime::now(),
            load_duration: Duration::from_millis(42),
            load_source: IndexLoadSource::FreshLoad,
            snapshot_verify_state: SnapshotVerifyState::NotNeeded,
            is_empty: false,
            tier_counts: (0, 0, 0),
            local_empty_reason: None,
            untracked_indexed: 0,
            indexed_root: None,
        }
    }

    #[test]
    fn test_startup_index_log_view_uses_published_ready_counts() {
        let published = published_state(PublishedIndexStatus::Ready);

        assert_eq!(
            startup_index_log_view(&published),
            Some(StartupIndexLogView::Ready {
                file_count: 12,
                symbol_count: 34,
                parsed_count: 10,
                partial_parse_count: 1,
                failed_count: 1,
                duration_ms: 42,
            })
        );
    }

    #[test]
    fn test_startup_index_log_view_uses_published_degraded_summary() {
        let mut published = published_state(PublishedIndexStatus::Degraded);
        published.degraded_summary = Some("circuit breaker tripped: 3/10 files failed".to_string());

        assert_eq!(
            startup_index_log_view(&published),
            Some(StartupIndexLogView::Degraded {
                summary: "circuit breaker tripped: 3/10 files failed".to_string(),
            })
        );
    }

    #[test]
    fn test_startup_plan_prefers_daemon_when_root_exists() {
        let root = PathBuf::from("repo");
        assert_eq!(
            startup_plan(true, Some(root.clone()), true),
            StartupPlan::Daemon { root }
        );
    }

    #[test]
    fn test_startup_plan_falls_back_to_local_auto_index_when_daemon_unavailable() {
        let root = PathBuf::from("repo");
        assert_eq!(
            startup_plan(true, Some(root.clone()), false),
            StartupPlan::LocalAutoIndex { root }
        );
    }

    #[test]
    fn test_startup_plan_reports_disabled_auto_index_reason() {
        assert_eq!(
            startup_plan(false, None, false),
            StartupPlan::LocalEmpty {
                reason: local_empty_reason(false).to_string(),
            }
        );
    }

    #[test]
    fn test_startup_plan_reports_missing_root_reason() {
        assert_eq!(
            startup_plan(true, None, false),
            StartupPlan::LocalEmpty {
                reason: local_empty_reason(true).to_string(),
            }
        );
    }

    #[test]
    fn test_checkpoint_interval_is_opt_in_and_bounded() {
        assert_eq!(checkpoint_interval_from_value(None), None);
        assert_eq!(checkpoint_interval_from_value(Some("0")), None);
        assert_eq!(checkpoint_interval_from_value(Some("false")), None);
        assert_eq!(
            checkpoint_interval_from_value(Some("15")),
            Some(Duration::from_secs(30))
        );
        assert_eq!(
            checkpoint_interval_from_value(Some("120")),
            Some(Duration::from_secs(120))
        );
        assert_eq!(
            checkpoint_interval_from_value(Some("999999")),
            Some(Duration::from_secs(3600))
        );
    }

    /// A local cold start that fails settles its placeholder with the reason
    /// instead of logging and leaving it `Loading` for the process lifetime.
    #[tokio::test(flavor = "multi_thread")]
    async fn a_failed_local_cold_start_does_not_stay_loading() {
        let tmp = tempfile::TempDir::new().expect("tempdir");
        let missing = tmp.path().join("removed-before-the-load");
        let index = crate::live_index::LiveIndex::empty();
        index.mark_bootstrap_loading();
        assert_eq!(
            index.published_state().status,
            PublishedIndexStatus::Loading
        );

        spawn_local_cold_load(
            index.clone(),
            missing,
            crate::domain::StatePlacement::MemoryOnly {
                failures: Vec::new(),
            },
        )
        .await
        .expect("the load task finished");

        let published = index.published_state();
        assert_eq!(published.status, PublishedIndexStatus::Empty);
        assert!(
            published
                .local_empty_reason
                .as_deref()
                .is_some_and(|reason| reason.contains("background index load failed")),
            "{:?}",
            published.local_empty_reason
        );
    }
}