symforge 11.2.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
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
//! Embedded registration, sole-handle ownership, and engine-only source workers.
//!
//! The embed feature deliberately excludes the server's notify-based watcher. An
//! embedded source therefore owns a small metadata-scouting worker which builds and
//! refreshes the same [`crate::live_index::store::SharedIndex`] used by the other
//! surfaces. The worker enters through the process admission/runtime seams and is
//! joined synchronously when its source or owning process runtime closes.
//!
//! The ownership rule is *sole handle*: one open source has exactly one handle,
//! and that handle is the only thing that can close it. Two handles to one source
//! would let one close while the other still believes it holds an open source —
//! the shape where a caller reads from something already torn down.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Condvar};
use std::time::Duration;

use super::registry::ProjectKey;
use crate::domain::{FreshnessStatus, RootBinding, StatePlacement};

const EMBED_OBSERVER_POLL: Duration = Duration::from_millis(200);
const REFRESHING_VISIBILITY_WINDOW: Duration = Duration::from_millis(25);

/// Identity of one embedded open. Never reused, including across reopen.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EmbeddedIdentity(std::num::NonZeroU64);

static NEXT_EMBEDDED: AtomicU64 = AtomicU64::new(1);

impl EmbeddedIdentity {
    /// Mint a fresh never-reused embedded identity.
    pub fn fresh() -> Self {
        let raw = NEXT_EMBEDDED.fetch_add(1, Ordering::Relaxed);
        Self(std::num::NonZeroU64::new(raw).expect("embedded counter starts at 1"))
    }

    /// Raw counter value, crate-only, for the embed boundary's kind-prefixed
    /// rendering and nothing else.
    pub(crate) fn raw(&self) -> u64 {
        self.0.get()
    }
}

/// Why an embedded request was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EmbedRefusal {
    /// This source already has a live handle; there is only ever one.
    SourceAlreadyOpen {
        /// The identity currently holding it.
        held_by: EmbeddedIdentity,
    },
    /// Closing here would wait on the thread doing the closing.
    ///
    /// Returned instead of deadlocking. A finalizer that closes the source it is
    /// finalizing is waiting for itself, and blocking would hang the embedder's
    /// thread with no diagnosis.
    WouldSelfWait,
    /// The handle has already closed.
    AlreadyClosed,
}

/// What a close actually did.
///
/// Records whether THIS call performed the shutdown or joined one already done,
/// so a caller cannot mistake a coalesced close for having been the one that
/// tore the source down.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CloseReceipt {
    identity: EmbeddedIdentity,
    performed_shutdown: bool,
    was_final_owner: bool,
}

impl CloseReceipt {
    /// The source that was closed.
    pub fn identity(&self) -> EmbeddedIdentity {
        self.identity
    }

    /// Whether this call performed the shutdown, rather than joining one that
    /// had already happened.
    pub fn performed_shutdown(&self) -> bool {
        self.performed_shutdown
    }

    /// Whether this was the last open source in the registration.
    pub fn was_final_owner(&self) -> bool {
        self.was_final_owner
    }
}

thread_local! {
    /// Which source this thread is finalizing, if any, so a close attempted
    /// from inside that source's own finalizer can refuse rather than wait on
    /// itself.
    ///
    /// The identity is the whole point. A bare `bool` refused ANY close made
    /// from inside ANY finalizer, so `a.finalize(|| b.close())` reported that
    /// closing `b` would wait on itself — a diagnosis naming something that did
    /// not happen, while `b` was left open.
    static FINALIZING: std::cell::Cell<Option<EmbeddedIdentity>> =
        const { std::cell::Cell::new(None) };
}

/// Mints embedded source handles, and is the only thing that can.
///
/// Named by the frozen `ORACLE-EMBED-FOUNDATION` seam. Construction of a handle
/// is private to this type, which is what makes "one incarnation owns at most
/// one handle" enforceable rather than advisory.
#[derive(Debug, Default)]
pub struct EmbeddedSourceFactory {
    open: std::sync::Mutex<HashMap<ProjectKey, OpenEmbeddedSource>>,
    shutdown: AtomicBool,
}

#[derive(Debug)]
struct OpenEmbeddedSource {
    identity: EmbeddedIdentity,
    binding: Option<Arc<EmbeddedBinding>>,
}

#[derive(Debug)]
pub(crate) enum EmbeddedOpenError {
    SourceAlreadyOpen,
    AdmissionUnavailable,
    WorkerUnavailable,
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct EmbeddedShutdownReport {
    pub closed_sources: u64,
    pub joined_workers: u64,
}

#[derive(Debug, Clone)]
struct EmbeddedRuntimeState {
    phase: super::public_api::SourceRuntimePhase,
    current_publication_identity: Option<String>,
    observer_epoch: u64,
    source_version: u64,
}

#[derive(Debug, Default)]
struct WorkerControl {
    stop: bool,
    refresh_requested: bool,
}

struct EmbeddedBinding {
    identity: EmbeddedIdentity,
    key: ProjectKey,
    root: PathBuf,
    state_placement: StatePlacement,
    runtime: super::activation::ProjectRuntimeHandle,
    state: std::sync::Mutex<EmbeddedRuntimeState>,
    control: std::sync::Mutex<WorkerControl>,
    wake: Condvar,
    worker: std::sync::Mutex<Option<std::thread::JoinHandle<()>>>,
    shutdown_started: AtomicBool,
}

impl std::fmt::Debug for EmbeddedBinding {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("EmbeddedBinding")
            .field("identity", &self.identity)
            .field("root", &self.root)
            .field("state", &self.state.lock().expect("embedded state mutex"))
            .finish_non_exhaustive()
    }
}

impl EmbeddedBinding {
    fn new(
        identity: EmbeddedIdentity,
        key: ProjectKey,
        root: PathBuf,
        state_placement: StatePlacement,
        runtime: super::activation::ProjectRuntimeHandle,
    ) -> Arc<Self> {
        Arc::new(Self {
            identity,
            key,
            root,
            state_placement,
            runtime,
            state: std::sync::Mutex::new(EmbeddedRuntimeState {
                phase: super::public_api::SourceRuntimePhase::Loading,
                current_publication_identity: None,
                observer_epoch: 0,
                source_version: 0,
            }),
            control: std::sync::Mutex::new(WorkerControl::default()),
            wake: Condvar::new(),
            worker: std::sync::Mutex::new(None),
            shutdown_started: AtomicBool::new(false),
        })
    }

    fn start(self: &Arc<Self>) -> std::io::Result<()> {
        let worker_binding = Arc::clone(self);
        let worker = std::thread::Builder::new()
            .name(format!("symforge-embed-{}", self.identity.raw()))
            .spawn(move || worker_binding.run())?;
        *self.worker.lock().expect("embedded worker mutex") = Some(worker);
        Ok(())
    }

    fn run(&self) {
        {
            let mut state = self.state.lock().expect("embedded state mutex");
            state.observer_epoch = 1;
        }

        let mut observed_fingerprint = self.reload_and_publish();
        loop {
            let mut control = self.control.lock().expect("embedded control mutex");
            let (next, _) = self
                .wake
                .wait_timeout(control, EMBED_OBSERVER_POLL)
                .expect("embedded control mutex");
            control = next;
            if control.stop {
                break;
            }
            let explicit_refresh = std::mem::take(&mut control.refresh_requested);
            drop(control);

            let next_fingerprint = self.observe_fingerprint();
            let disk_changed = match (&observed_fingerprint, &next_fingerprint) {
                (Some(previous), Some(current)) => previous != current,
                (None, Some(_)) | (Some(_), None) => true,
                (None, None) => false,
            };
            let blocked = self.state.lock().expect("embedded state mutex").phase
                == super::public_api::SourceRuntimePhase::Blocked;
            if explicit_refresh || disk_changed || blocked {
                self.set_phase(super::public_api::SourceRuntimePhase::Refreshing);
                if self.wait_refresh_visibility_or_stop() {
                    break;
                }
                observed_fingerprint = self.reload_and_publish();
            } else {
                observed_fingerprint = next_fingerprint;
            }
        }
        self.set_phase(super::public_api::SourceRuntimePhase::Stopped);
    }

    fn wait_refresh_visibility_or_stop(&self) -> bool {
        let control = self.control.lock().expect("embedded control mutex");
        let (control, _) = self
            .wake
            .wait_timeout(control, REFRESHING_VISIBILITY_WINDOW)
            .expect("embedded control mutex");
        control.stop
    }

    fn reload_and_publish(&self) -> Option<String> {
        let exclusions = crate::discovery::SourceExclusions::for_state_placement(
            &self.root,
            &self.state_placement,
        );
        let result = self
            .runtime
            .data_plane()
            .reload_for_binding_with_exclusions(
                &self.root,
                self.state_placement.directory().cloned(),
                exclusions,
            );
        if result.is_err() {
            self.set_blocked();
            return None;
        }

        let Some(fingerprint) = self.observe_fingerprint() else {
            self.set_blocked();
            return None;
        };
        let published = self.runtime.data_plane().published_generation();
        if !matches!(published.freshness.as_ref(), FreshnessStatus::Current) {
            self.set_blocked();
            return Some(fingerprint);
        }
        let mut state = self.state.lock().expect("embedded state mutex");
        state.source_version = state.source_version.saturating_add(1).max(1);
        state.current_publication_identity = Some(format!(
            "embed-publication-{}-{}",
            self.identity.raw(),
            published.publication_generation
        ));
        state.phase = super::public_api::SourceRuntimePhase::Current;
        Some(fingerprint)
    }

    fn observe_fingerprint(&self) -> Option<String> {
        let exclusions = crate::discovery::SourceExclusions::for_state_placement(
            &self.root,
            &self.state_placement,
        );
        crate::discovery::scout_repository_with_exclusions(&self.root, &exclusions)
            .ok()
            .map(|plan| crate::hash::digest_hex(format!("{plan:?}").as_bytes()))
    }

    fn set_phase(&self, phase: super::public_api::SourceRuntimePhase) {
        self.state.lock().expect("embedded state mutex").phase = phase;
    }

    fn set_blocked(&self) {
        let mut state = self.state.lock().expect("embedded state mutex");
        state.phase = super::public_api::SourceRuntimePhase::Blocked;
        state.current_publication_identity = None;
    }

    fn runtime_view(&self) -> super::public_api::SourceRuntimeView {
        let state = self.state.lock().expect("embedded state mutex").clone();
        super::public_api::SourceRuntimeView {
            binding_identity: format!("source-{}", self.identity.raw()),
            current_publication_identity: state.current_publication_identity,
            observer_epoch: state.observer_epoch,
            phase: state.phase,
            source_version: state.source_version,
        }
    }

    fn current_claim(
        &self,
        operation: crate::lifecycle_identity::OperationKind,
        normalized_arguments: &[u8],
    ) -> Result<CurrentEmbedClaim, super::public_api::EmbedSourceRefusal> {
        let state = self.state.lock().expect("embedded state mutex");
        if state.phase != super::public_api::SourceRuntimePhase::Current {
            let retry = match state.phase {
                super::public_api::SourceRuntimePhase::Blocked => {
                    crate::lifecycle_identity::RetryAdvice::Operator
                }
                super::public_api::SourceRuntimePhase::Stopped
                | super::public_api::SourceRuntimePhase::Stopping => {
                    crate::lifecycle_identity::RetryAdvice::Never
                }
                _ => crate::lifecycle_identity::RetryAdvice::OnEvent,
            };
            return Err(super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                operation,
                retry,
                normalized_arguments,
            ));
        }
        let publication_identity = state
            .current_publication_identity
            .clone()
            .expect("Current embedded source has a publication identity");
        Ok(CurrentEmbedClaim {
            binding_identity: format!("source-{}", self.identity.raw()),
            publication_identity,
            source_version: state.source_version,
        })
    }

    fn request_refresh(&self) -> Option<u64> {
        let state = self.state.lock().expect("embedded state mutex");
        if matches!(
            state.phase,
            super::public_api::SourceRuntimePhase::Stopped
                | super::public_api::SourceRuntimePhase::Stopping
        ) {
            return None;
        }
        let version = state.source_version;
        drop(state);
        let mut control = self.control.lock().expect("embedded control mutex");
        control.refresh_requested = true;
        self.wake.notify_all();
        Some(version)
    }

    fn shutdown(&self) -> (u64, u64) {
        if self.shutdown_started.swap(true, Ordering::AcqRel) {
            let version = self
                .state
                .lock()
                .expect("embedded state mutex")
                .source_version;
            return (version, 0);
        }
        self.set_phase(super::public_api::SourceRuntimePhase::Stopping);
        {
            let mut control = self.control.lock().expect("embedded control mutex");
            control.stop = true;
            self.wake.notify_all();
        }
        let joined = self
            .worker
            .lock()
            .expect("embedded worker mutex")
            .take()
            .map(|worker| {
                let _ = worker.join();
                1
            })
            .unwrap_or(0);
        self.set_phase(super::public_api::SourceRuntimePhase::Stopped);
        if let Err(refusal) = super::activation::process_project_registry().stop(&self.key) {
            tracing::debug!(?refusal, "embedded admission stop refused");
        }
        let version = self
            .state
            .lock()
            .expect("embedded state mutex")
            .source_version;
        (version, joined)
    }
}

struct CurrentEmbedClaim {
    binding_identity: String,
    publication_identity: String,
    source_version: u64,
}

fn normalized_path_prefix(prefix: Option<&str>) -> Option<String> {
    prefix.map(|prefix| {
        prefix
            .replace('\\', "/")
            .trim_start_matches("./")
            .trim_end_matches('/')
            .to_string()
    })
}

fn bounded_preview(line: &str) -> String {
    const MAX_PREVIEW_CHARS: usize = 500;
    let mut chars = line.chars();
    let preview: String = chars.by_ref().take(MAX_PREVIEW_CHARS).collect();
    if chars.next().is_some() {
        format!("{preview}…")
    } else {
        preview
    }
}

impl EmbeddedSourceFactory {
    /// A registration with nothing open.
    pub fn new() -> Arc<Self> {
        Arc::new(Self::default())
    }

    /// Test-internal dark registration retained for the Slice-2 ownership
    /// oracles. Production opens always use [`Self::open_bound`].
    #[cfg(feature = "__test-internals")]
    pub fn open(self: &Arc<Self>, key: ProjectKey) -> Result<EmbeddedSourceHandle, EmbedRefusal> {
        let mut open = self.open.lock().expect("embedded registration mutex");
        if let Some(held_by) = open.get(&key) {
            return Err(EmbedRefusal::SourceAlreadyOpen {
                held_by: held_by.identity,
            });
        }
        let identity = EmbeddedIdentity::fresh();
        open.insert(
            key.clone(),
            OpenEmbeddedSource {
                identity,
                binding: None,
            },
        );
        self.shutdown.store(false, Ordering::Release);
        Ok(EmbeddedSourceHandle {
            identity,
            key,
            registration: Arc::clone(self),
            binding: None,
            closed: AtomicBool::new(false),
            _not_unwind_safe: std::marker::PhantomData,
        })
    }

    /// Open `binding`, yielding the sole handle for it and starting its worker.
    ///
    /// Refuses if a handle is already live for this key. Handing out a second
    /// handle would let one close while the other still believes it holds an
    /// open source.
    pub(crate) fn open_bound(
        self: &Arc<Self>,
        binding: RootBinding,
        state_placement: StatePlacement,
    ) -> Result<EmbeddedSourceHandle, EmbeddedOpenError> {
        let key = ProjectKey::new(&binding.root_id.0);
        let mut open = self.open.lock().expect("embedded registration mutex");
        if open.contains_key(&key) {
            return Err(EmbeddedOpenError::SourceAlreadyOpen);
        }
        let identity = EmbeddedIdentity::fresh();
        let admission = super::activation::admit_project_with_outcome(
            super::process_runtime::SurfaceKind::Embed,
            &binding.canonical_root,
            &binding.root_id.0,
            binding.access_mode,
            &state_placement,
        )
        .map_err(|_| EmbeddedOpenError::AdmissionUnavailable)?;
        let index = crate::live_index::store::LiveIndex::empty();
        let runtime =
            super::activation::ProjectRuntimeHandle::bind_admitted(index, admission.into_slot());
        let source = EmbeddedBinding::new(
            identity,
            key.clone(),
            binding.canonical_root,
            state_placement,
            runtime,
        );
        if source.start().is_err() {
            let _ = super::activation::process_project_registry().stop(&key);
            return Err(EmbeddedOpenError::WorkerUnavailable);
        }
        open.insert(
            key.clone(),
            OpenEmbeddedSource {
                identity,
                binding: Some(Arc::clone(&source)),
            },
        );
        // The factory is serving again, so it is no longer shut down. The flag
        // latched before, which made `has_shut_down()` report `true` while
        // `open_count()` was 1 — a claim about a past moment presented as
        // present state. Cleared under the same lock that records the open, so
        // the two can never disagree.
        self.shutdown.store(false, Ordering::Release);
        Ok(EmbeddedSourceHandle {
            identity,
            key,
            registration: Arc::clone(self),
            binding: Some(source),
            closed: AtomicBool::new(false),
            _not_unwind_safe: std::marker::PhantomData,
        })
    }

    /// How many sources are open.
    pub fn open_count(&self) -> usize {
        self.open.lock().expect("embedded registration mutex").len()
    }

    /// Whether the factory is currently shut down: the final owner closed and
    /// nothing has been opened since.
    pub fn has_shut_down(&self) -> bool {
        self.shutdown.load(Ordering::Acquire)
    }

    /// Close one source. Returns whether this call performed the shutdown.
    fn close_one(&self, key: &ProjectKey, identity: EmbeddedIdentity) -> (bool, bool, u64, u64) {
        let mut open = self.open.lock().expect("embedded registration mutex");
        let matched = open
            .get(key)
            .is_some_and(|source| source.identity == identity);
        let source = open
            .get(key)
            .filter(|source| source.identity == identity)
            .and_then(|source| source.binding.as_ref().map(Arc::clone));
        let (terminal_version, joined_workers) = source
            .as_ref()
            .map(|source| source.shutdown())
            .unwrap_or((0, 0));
        let performed = matched && open.remove(key).is_some();
        let final_owner = performed && open.is_empty();
        if final_owner {
            self.shutdown.store(true, Ordering::Release);
        }
        (performed, final_owner, terminal_version, joined_workers)
    }

    pub(crate) fn shutdown_all(&self) -> EmbeddedShutdownReport {
        let mut open = self.open.lock().expect("embedded registration mutex");
        let mut closed_sources = 0u64;
        let mut joined_workers = 0u64;
        for source in open.values() {
            let joined = source
                .binding
                .as_ref()
                .map(|binding| binding.shutdown().1)
                .unwrap_or(0);
            closed_sources = closed_sources.saturating_add(1);
            joined_workers = joined_workers.saturating_add(joined);
        }
        open.clear();
        self.shutdown.store(true, Ordering::Release);
        EmbeddedShutdownReport {
            closed_sources,
            joined_workers,
        }
    }
}

#[derive(Debug)]
pub(crate) struct EmbeddedRuntimeOwner {
    factory: Arc<EmbeddedSourceFactory>,
}

impl EmbeddedRuntimeOwner {
    pub(crate) fn new() -> Arc<Self> {
        Arc::new(Self {
            factory: EmbeddedSourceFactory::new(),
        })
    }

    pub(crate) fn factory(&self) -> &Arc<EmbeddedSourceFactory> {
        &self.factory
    }

    pub(crate) fn shutdown(&self) -> EmbeddedShutdownReport {
        self.factory.shutdown_all()
    }
}

impl Drop for EmbeddedRuntimeOwner {
    fn drop(&mut self) {
        self.factory.shutdown_all();
    }
}

/// The sole handle to one embedded source.
///
/// Not `Clone`: sole ownership is the invariant, and a clonable handle would
/// mean two owners could each believe they hold the source.
#[derive(Debug)]
pub struct EmbeddedSourceHandle {
    identity: EmbeddedIdentity,
    key: ProjectKey,
    registration: Arc<EmbeddedSourceFactory>,
    binding: Option<Arc<EmbeddedBinding>>,
    closed: AtomicBool,
    // T049: the contract pins the handle NOT UnwindSafe/RefUnwindSafe.
    _not_unwind_safe: super::public_api::NotUnwindSafe,
}

impl EmbeddedSourceHandle {
    /// This open's identity.
    pub fn identity(&self) -> EmbeddedIdentity {
        self.identity
    }

    /// The key it holds open.
    pub fn key(&self) -> &ProjectKey {
        &self.key
    }

    /// Whether this handle is still open.
    pub fn is_open(&self) -> bool {
        !self.closed.load(Ordering::Acquire)
            && self.binding.as_ref().is_none_or(|binding| {
                !matches!(
                    binding.runtime_view().phase,
                    super::public_api::SourceRuntimePhase::Stopped
                        | super::public_api::SourceRuntimePhase::Stopping
                )
            })
    }

    /// Close the source.
    ///
    /// Coalesces with `Drop`: whichever runs first performs the shutdown, and
    /// the other reports that it joined rather than performed it. Refuses with
    /// [`EmbedRefusal::WouldSelfWait`] when called from inside a finalizer,
    /// because waiting there is waiting on the calling thread itself.
    pub fn close(&self) -> Result<CloseReceipt, EmbedRefusal> {
        if FINALIZING.with(std::cell::Cell::get) == Some(self.identity) {
            return Err(EmbedRefusal::WouldSelfWait);
        }
        if self.closed.swap(true, Ordering::AcqRel) {
            return Err(EmbedRefusal::AlreadyClosed);
        }
        let (performed, final_owner, _, _) = self.registration.close_one(&self.key, self.identity);
        Ok(CloseReceipt {
            identity: self.identity,
            performed_shutdown: performed,
            was_final_owner: final_owner,
        })
    }

    /// V11 (T047, E1 ruling): begin the close INFALLIBLY. The Slice 2 `close`
    /// refuses a self-wait AT CLOSE; the V11 contract relocates that guard to
    /// the WAIT — beginning a close is always legal, and only waiting on your
    /// own close from inside the finalizer refuses. An already-closed source
    /// yields a receipt that joined rather than performed, same as `Drop`
    /// coalescing.
    pub fn begin_close(&self) -> SourceCloseReceipt {
        let performed = if self.closed.swap(true, Ordering::AcqRel) {
            false
        } else {
            let (performed, _final_owner, terminal_version, _joined_workers) =
                self.registration.close_one(&self.key, self.identity);
            return SourceCloseReceipt {
                identity: self.identity,
                performed_shutdown: performed,
                terminal_source_version: terminal_version,
                _not_unwind_safe: std::marker::PhantomData,
            };
        };
        SourceCloseReceipt {
            identity: self.identity,
            performed_shutdown: performed,
            terminal_source_version: self
                .binding
                .as_ref()
                .map(|binding| binding.runtime_view().source_version)
                .unwrap_or(0),
            _not_unwind_safe: std::marker::PhantomData,
        }
    }

    /// Capture the source's lifecycle state atomically.
    pub fn runtime_view(&self) -> super::public_api::SourceRuntimeView {
        self.binding.as_ref().map_or_else(
            || super::public_api::SourceRuntimeView {
                binding_identity: format!("source-{}", self.identity.raw()),
                current_publication_identity: None,
                observer_epoch: 0,
                phase: if self.closed.load(Ordering::Acquire) {
                    super::public_api::SourceRuntimePhase::Stopped
                } else {
                    super::public_api::SourceRuntimePhase::Loading
                },
                source_version: 0,
            },
            |binding| binding.runtime_view(),
        )
    }

    /// Search one pinned current generation and return its claim provenance.
    pub fn search_symbols(
        &self,
        request: &super::public_api::SymbolSearchRequest,
    ) -> Result<
        super::public_api::EmbedClaim<super::public_api::SymbolSearchResult>,
        super::public_api::EmbedSourceRefusal,
    > {
        let normalized = format!(
            "query={:?};path_prefix={:?};limit={}",
            request.query, request.path_prefix, request.limit
        );
        if self.closed.load(Ordering::Acquire) {
            return Err(super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::OperationKind::SearchSymbols,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized.as_bytes(),
            ));
        }
        let Some(binding) = self.binding.as_ref() else {
            return Err(super::public_api::dark_unbound_refusal(
                crate::lifecycle_identity::OperationKind::SearchSymbols,
            ));
        };
        let claim = binding.current_claim(
            crate::lifecycle_identity::OperationKind::SearchSymbols,
            normalized.as_bytes(),
        )?;
        let index = binding.runtime.acquire().map_err(|_| {
            super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::OperationKind::SearchSymbols,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized.as_bytes(),
            )
        })?;
        let live = index.read();
        let query = request.query.as_deref().map(str::to_lowercase);
        let path_prefix = normalized_path_prefix(request.path_prefix.as_deref());
        let mut matches = Vec::new();
        for (path, file) in live.all_files() {
            if path_prefix
                .as_deref()
                .is_some_and(|prefix| !path.starts_with(prefix))
            {
                continue;
            }
            for symbol in &file.symbols {
                if query
                    .as_deref()
                    .is_some_and(|query| !symbol.name.to_lowercase().contains(query))
                {
                    continue;
                }
                matches.push((
                    symbol.sort_order,
                    super::public_api::SymbolMatch {
                        name: symbol.name.clone(),
                        kind: symbol.kind.to_string(),
                        path: path.clone(),
                        start_line: symbol.line_range.0.saturating_add(1),
                        end_line: symbol.line_range.1.saturating_add(1),
                    },
                ));
            }
        }
        matches.sort_by(|(left_order, left), (right_order, right)| {
            left.path
                .cmp(&right.path)
                .then_with(|| left.start_line.cmp(&right.start_line))
                .then_with(|| left_order.cmp(right_order))
                .then_with(|| left.name.cmp(&right.name))
                .then_with(|| left.kind.cmp(&right.kind))
        });
        let limit = request.limit as usize;
        let truncated = matches.len() > limit;
        let matches = matches
            .into_iter()
            .take(limit)
            .map(|(_, value)| value)
            .collect();
        Ok(super::public_api::live_claim(
            super::public_api::SymbolSearchResult { matches, truncated },
            crate::lifecycle_identity::OperationKind::SearchSymbols,
            normalized.as_bytes(),
            &claim.binding_identity,
            &claim.publication_identity,
            claim.source_version,
        ))
    }

    /// Search stored byte-exact file content from one pinned current generation.
    pub fn search_text(
        &self,
        request: &super::public_api::TextSearchRequest,
    ) -> Result<
        super::public_api::EmbedClaim<super::public_api::TextSearchResult>,
        super::public_api::EmbedSourceRefusal,
    > {
        let normalized = format!(
            "query={:?};path_prefix={:?};limit={};case_sensitive={}",
            request.query, request.path_prefix, request.limit, request.case_sensitive
        );
        if request.query.is_empty() {
            return Err(super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::InvalidSelection,
                crate::lifecycle_identity::OperationKind::SearchText,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized.as_bytes(),
            ));
        }
        if self.closed.load(Ordering::Acquire) {
            return Err(super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::OperationKind::SearchText,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized.as_bytes(),
            ));
        }
        let Some(binding) = self.binding.as_ref() else {
            return Err(super::public_api::dark_unbound_refusal(
                crate::lifecycle_identity::OperationKind::SearchText,
            ));
        };
        let claim = binding.current_claim(
            crate::lifecycle_identity::OperationKind::SearchText,
            normalized.as_bytes(),
        )?;
        let matcher = regex::RegexBuilder::new(&regex::escape(&request.query))
            .case_insensitive(!request.case_sensitive)
            .build()
            .map_err(|_| {
                super::public_api::bound_source_refusal(
                    crate::lifecycle_identity::SourceRefusalKind::InvalidSelection,
                    crate::lifecycle_identity::OperationKind::SearchText,
                    crate::lifecycle_identity::RetryAdvice::Never,
                    normalized.as_bytes(),
                )
            })?;
        let index = binding.runtime.acquire().map_err(|_| {
            super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::OperationKind::SearchText,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized.as_bytes(),
            )
        })?;
        let live = index.read();
        let path_prefix = normalized_path_prefix(request.path_prefix.as_deref());
        let limit = request.limit as usize;
        let mut matches = Vec::new();
        let mut truncated = false;
        'files: for (path, file) in live.all_files() {
            if path_prefix
                .as_deref()
                .is_some_and(|prefix| !path.starts_with(prefix))
            {
                continue;
            }
            let Ok(content) = std::str::from_utf8(&file.content) else {
                continue;
            };
            let mut line_start = 0usize;
            for (line_index, line) in content.split_inclusive('\n').enumerate() {
                let searchable = line.strip_suffix('\n').unwrap_or(line);
                for found in matcher.find_iter(searchable) {
                    if matches.len() == limit {
                        truncated = true;
                        break 'files;
                    }
                    let byte_start = line_start.saturating_add(found.start());
                    let byte_end = line_start.saturating_add(found.end());
                    matches.push(super::public_api::TextMatch {
                        path: path.clone(),
                        line: u32::try_from(line_index.saturating_add(1)).unwrap_or(u32::MAX),
                        byte_start: byte_start as u64,
                        byte_end: byte_end as u64,
                        preview: bounded_preview(searchable.trim_end_matches('\r')),
                    });
                }
                line_start = line_start.saturating_add(line.len());
            }
        }
        Ok(super::public_api::live_claim(
            super::public_api::TextSearchResult { matches, truncated },
            crate::lifecycle_identity::OperationKind::SearchText,
            normalized.as_bytes(),
            &claim.binding_identity,
            &claim.publication_identity,
            claim.source_version,
        ))
    }

    /// Queue a refresh on this source's worker.
    pub fn request_refresh(
        &self,
    ) -> Result<super::public_api::EmbedRefreshTicket, super::public_api::EmbedSourceRefusal> {
        let normalized = b"refresh-current-worktree";
        if self.closed.load(Ordering::Acquire) {
            return Err(super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::OperationKind::RefreshSource,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized,
            ));
        }
        let Some(binding) = self.binding.as_ref() else {
            return Err(super::public_api::dark_unbound_refusal(
                crate::lifecycle_identity::OperationKind::RefreshSource,
            ));
        };
        let Some(source_version) = binding.request_refresh() else {
            return Err(super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::OperationKind::RefreshSource,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized,
            ));
        };
        Ok(super::public_api::refresh_ticket(
            normalized,
            source_version,
        ))
    }

    /// Fixture probe for the relocated guard: arms the finalizer for THIS
    /// source and attempts to wait on its own close receipt from inside it —
    /// which must refuse with [`ReceiptWaitError::WouldSelfWait`] rather than
    /// deadlock.
    #[cfg(all(test, feature = "server"))]
    pub fn self_wait_probe_for_test(&self) -> Result<SourceCloseReport, ReceiptWaitError> {
        let receipt = self.begin_close();
        self.finalize(|| receipt.wait_for_test())
    }

    /// Run `finalizer` with self-wait detection armed for THIS source.
    ///
    /// A finalizer that tries to close this source is refused rather than
    /// deadlocked; a finalizer that closes some other source is none of this
    /// source's business and proceeds. The previous value is restored even if
    /// the finalizer panics, so one bad finalizer cannot poison every later
    /// close on this thread, and nesting two finalizers cannot leave the outer
    /// one disarmed.
    pub fn finalize<R>(&self, finalizer: impl FnOnce() -> R) -> R {
        struct Guard(Option<EmbeddedIdentity>);
        impl Drop for Guard {
            fn drop(&mut self) {
                FINALIZING.with(|flag| flag.set(self.0));
            }
        }
        let _guard = Guard(FINALIZING.with(|flag| flag.replace(Some(self.identity))));
        finalizer()
    }
}

/// Waiting on a receipt can refuse; the wait is where the self-wait guard
/// lives in V11, so the error is typed rather than a deadlock.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReceiptWaitError {
    /// The deadline passed before the wait completed. A CONTRACT variant
    /// (T049): dark waits complete immediately, so nothing in Slice 3 can
    /// produce it — Slice 4's real waits can. T047's transcription omitted
    /// it, the same defect class as the invented `ServerExit::Clean`, caught
    /// by the dependent-positive fixture once its feature gate was honest.
    DeadlineElapsed,
    /// The wait was attempted from inside this source's own finalizer:
    /// waiting there is waiting on the calling thread itself.
    WouldSelfWait,
}

// T049: `Display` and `Error` are contract-pinned direct impls on this atom.
impl std::fmt::Display for ReceiptWaitError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::DeadlineElapsed => {
                write!(f, "the deadline passed before the wait completed")
            }
            Self::WouldSelfWait => write!(
                f,
                "waiting on this receipt from inside its own source's finalizer \
                 would wait on the calling thread itself"
            ),
        }
    }
}

impl std::error::Error for ReceiptWaitError {}

/// Receipt for a completed V11 `begin_close`.
#[derive(Debug)]
pub struct SourceCloseReceipt {
    identity: EmbeddedIdentity,
    performed_shutdown: bool,
    terminal_source_version: u64,
    // T049: the contract pins the receipt NOT UnwindSafe/RefUnwindSafe.
    _not_unwind_safe: super::public_api::NotUnwindSafe,
}

impl SourceCloseReceipt {
    /// The contract wait (T049): refuses a self-wait and otherwise returns the
    /// teardown result already observed by synchronous close.
    pub fn wait(
        &self,
        deadline: std::time::Instant,
    ) -> Result<super::public_api::SourceCloseReport, ReceiptWaitError> {
        let _ = deadline;
        if FINALIZING.with(std::cell::Cell::get) == Some(self.identity) {
            return Err(ReceiptWaitError::WouldSelfWait);
        }
        Ok(super::public_api::SourceCloseReport {
            already_terminal: !self.performed_shutdown,
            terminal_source_version: self.terminal_source_version,
        })
    }

    /// Wait for the close to finalize, reporting the INTERNAL observation
    /// record (T047's oracle shape). Refuses a self-wait; completes
    /// immediately otherwise, because the close performed synchronously and
    /// only observed completions may be reported.
    #[cfg(all(test, feature = "server"))]
    pub fn wait_for_test(&self) -> Result<SourceCloseReport, ReceiptWaitError> {
        if FINALIZING.with(std::cell::Cell::get) == Some(self.identity) {
            return Err(ReceiptWaitError::WouldSelfWait);
        }
        Ok(SourceCloseReport {
            finalized: true,
            performed_shutdown: self.performed_shutdown,
        })
    }
}

/// What the close wait OBSERVED.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SourceCloseReport {
    finalized: bool,
    performed_shutdown: bool,
}

impl SourceCloseReport {
    pub fn finalized(&self) -> bool {
        self.finalized
    }

    pub fn performed_shutdown(&self) -> bool {
        self.performed_shutdown
    }
}

impl Drop for EmbeddedSourceHandle {
    fn drop(&mut self) {
        // Coalesce with an explicit close. A handle dropped without closing must
        // still release the source, or the registration would believe a source
        // is open that nothing holds.
        //
        // `Drop` deliberately does NOT consult `FINALIZING`. The self-wait
        // hazard `close` refuses is about WAITING, and `close_one` takes a
        // mutex and returns — it never waits on the finalizer. Refusing here
        // would be worse than the hazard: a `Drop` cannot report a refusal, so
        // the source would simply stay open forever with nothing holding it.
        // This is stated rather than left as an inconsistency between the two
        // paths, which is how it read before: `a.finalize(|| drop(b))` was
        // permitted while `a.finalize(|| b.close())` was refused.
        if !self.closed.swap(true, Ordering::AcqRel) {
            let _ = self.registration.close_one(&self.key, self.identity);
        }
    }
}