symforge 10.3.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
//! Whole mutation authority for the V11 index lifecycle (T024).
//!
//! Every identity here is drawn from one process-global monotonic counter, so no
//! identity is ever reused and no two identities of different kinds can collide.
//! Identities are diagnostics for ordering only: nothing in this module grants a
//! mutation because a counter compared equal. A mutation is authorized by a
//! sealed [`CurrentMutationGrantAuthority`] that was consumed from an exact live
//! `Current` publication, or it is refused.

use std::num::NonZeroU64;
use std::sync::atomic::{AtomicU64, Ordering};

/// Process-global monotonic identity source. Never restarts, never reuses.
static NEXT_IDENTITY: AtomicU64 = AtomicU64::new(1);

fn next_identity() -> NonZeroU64 {
    let raw = NEXT_IDENTITY.fetch_add(1, Ordering::Relaxed);
    NonZeroU64::new(raw).expect("identity counter starts at 1 and only increases")
}

macro_rules! identity_newtype {
    ($(#[$meta:meta])* $name:ident) => {
        $(#[$meta])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        pub struct $name(NonZeroU64);

        impl $name {
            /// Mint a fresh never-reused identity.
            pub fn fresh() -> Self {
                Self(next_identity())
            }
        }
    };
}

identity_newtype!(
    /// Identity of a source binding to one physical root.
    BindingIdentity
);
identity_newtype!(
    /// Stable identity of a filesystem observer registration.
    ObserverToken
);
identity_newtype!(
    /// Identity of an in-progress candidate build.
    CandidateIdentity
);
identity_newtype!(
    /// Identity of a promoted generation's authority.
    GenerationIdentity
);
identity_newtype!(
    /// Identity of one publication of source runtime state.
    PublicationIdentity
);
identity_newtype!(
    /// Identity of an untrusted on-disk snapshot seed.
    SnapshotIdentity
);

/// Monotonic per-source mutation epoch. An ordering aid, never an authorization.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct MutationEpoch(u64);

impl MutationEpoch {
    /// The epoch a source occupies before any mutation has ever been granted.
    pub const fn initial() -> Self {
        Self(0)
    }

    fn advanced(self) -> Self {
        Self(self.0 + 1)
    }

    /// Diagnostic value. Callers must not derive permission from it.
    pub const fn get(self) -> u64 {
        self.0
    }
}

/// Authority binding one source to exactly one physical root.
///
/// Cloneable: a binding is a description of which root is authoritative, not a
/// consumable permission. Equality is exact on both the binding identity and the
/// root lease identity, so a rebind never compares equal to its predecessor.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BindingAuthority {
    identity: BindingIdentity,
    physical_root: crate::live_index::index_lifecycle::physical_root::PhysicalRootIdentity,
}

impl BindingAuthority {
    /// Bind a source to a physical root under a fresh never-reused identity.
    pub fn bind(
        physical_root: crate::live_index::index_lifecycle::physical_root::PhysicalRootIdentity,
    ) -> Self {
        Self {
            identity: BindingIdentity::fresh(),
            physical_root,
        }
    }

    /// The binding's identity.
    pub fn identity(&self) -> BindingIdentity {
        self.identity
    }

    /// The physical root this binding authorizes, and no other.
    pub fn physical_root(
        &self,
    ) -> crate::live_index::index_lifecycle::physical_root::PhysicalRootIdentity {
        self.physical_root
    }
}

/// Authority for one in-progress candidate build.
///
/// A candidate is never a mutation grant: it has not published, so it cannot
/// authorize a source-disk side effect.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CandidateAuthority {
    identity: CandidateIdentity,
    binding: BindingAuthority,
    observer_cut: ObserverToken,
}

impl CandidateAuthority {
    /// Open a candidate under a binding at an observer cut.
    pub fn open(binding: BindingAuthority, observer_cut: ObserverToken) -> Self {
        Self {
            identity: CandidateIdentity::fresh(),
            binding,
            observer_cut,
        }
    }

    /// The candidate's identity.
    pub fn identity(&self) -> CandidateIdentity {
        self.identity
    }

    /// The binding this candidate was opened under.
    pub fn binding(&self) -> &BindingAuthority {
        &self.binding
    }

    /// The observer cut this candidate is building through.
    pub fn observer_cut(&self) -> ObserverToken {
        self.observer_cut
    }
}

/// Generation-bound mutation authority.
///
/// Carries the exact generation, binding, and epoch a mutation is bound to. It
/// is produced only from a consumed [`CurrentMutationGrantAuthority`] and is
/// validated as a whole: no consumer may compare one field and infer the rest.
#[derive(Debug, PartialEq, Eq)]
pub struct MutationAuthority {
    generation: GenerationIdentity,
    binding: BindingAuthority,
    epoch: MutationEpoch,
    publication: PublicationIdentity,
}

impl MutationAuthority {
    /// The generation this authority is bound to.
    pub fn generation(&self) -> GenerationIdentity {
        self.generation
    }

    /// The binding this authority is bound to.
    pub fn binding(&self) -> &BindingAuthority {
        &self.binding
    }

    /// The mutation epoch this authority was granted at.
    pub fn epoch(&self) -> MutationEpoch {
        self.epoch
    }

    /// The exact `Current` publication this authority was consumed from.
    pub fn publication(&self) -> PublicationIdentity {
        self.publication
    }
}

/// Proof that the granting source published a non-`Current` state.
///
/// The permit refuses every source-disk side effect until it holds one of these,
/// so a side effect can never precede the publication that makes the source
/// non-queryable.
#[derive(Debug, PartialEq, Eq)]
pub struct NonCurrentPublicationProof {
    publication: PublicationIdentity,
    epoch: MutationEpoch,
}

impl NonCurrentPublicationProof {
    /// The non-`Current` publication that was actually stored.
    pub fn publication(&self) -> PublicationIdentity {
        self.publication
    }

    /// The epoch that publication carried.
    pub fn epoch(&self) -> MutationEpoch {
        self.epoch
    }
}

/// Sealed, non-cloneable authority to grant exactly one mutation permit.
///
/// Constructible only inside this module, and only by
/// [`SourceRuntime::request_mutation_grant`] after it has validated an exact live
/// `Current` publication and published non-`Current`.
#[derive(Debug)]
pub struct CurrentMutationGrantAuthority {
    authority: MutationAuthority,
    published_non_current: NonCurrentPublicationProof,
}

impl CurrentMutationGrantAuthority {
    /// The whole generation-bound authority this grant carries.
    pub fn authority(&self) -> &MutationAuthority {
        &self.authority
    }

    /// Proof the source was published non-`Current` before this grant existed.
    pub fn published_non_current(&self) -> &NonCurrentPublicationProof {
        &self.published_non_current
    }

    /// Consume the grant, yielding its parts. Consumption is by move, so a grant
    /// can authorize at most one permit.
    pub(crate) fn into_parts(self) -> (MutationAuthority, NonCurrentPublicationProof) {
        (self.authority, self.published_non_current)
    }
}

/// The live `Current` publication of a source.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurrentPublication {
    publication: PublicationIdentity,
    generation: GenerationIdentity,
    binding: BindingAuthority,
    observer_cut: ObserverToken,
}

impl CurrentPublication {
    /// Promote a verified generation to `Current` under a fresh publication.
    pub fn promote(binding: BindingAuthority, observer_cut: ObserverToken) -> Self {
        Self {
            publication: PublicationIdentity::fresh(),
            generation: GenerationIdentity::fresh(),
            binding,
            observer_cut,
        }
    }

    /// The publication identity a mutation grant must name exactly.
    pub fn publication(&self) -> PublicationIdentity {
        self.publication
    }

    /// The generation this publication makes queryable.
    pub fn generation(&self) -> GenerationIdentity {
        self.generation
    }

    /// The binding this publication was promoted under.
    pub fn binding(&self) -> &BindingAuthority {
        &self.binding
    }

    /// The observer cut this publication is complete through.
    pub fn observer_cut(&self) -> ObserverToken {
        self.observer_cut
    }
}

/// What a caller presents when asking for a mutation grant.
///
/// Only [`MutationGrantInput::LiveCurrent`] naming the exact live publication can
/// ever be accepted. Every other shape is a source of authority that has not
/// published a queryable generation, and is refused by construction rather than
/// by inspecting its contents.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MutationGrantInput {
    /// The publication the caller believes is live and `Current`.
    LiveCurrent(PublicationIdentity),
    /// An in-progress candidate build.
    Candidate(CandidateIdentity),
    /// An untrusted on-disk snapshot seed.
    Snapshot(SnapshotIdentity),
    /// A generation retained by a non-`Current` state for recovery or accounting.
    RetainedGeneration(GenerationIdentity),
    /// A publication that was `Current` at some earlier point.
    StalePublication(PublicationIdentity),
}

impl MutationGrantInput {
    fn provenance(&self) -> Provenance {
        match self {
            Self::LiveCurrent(_) => Provenance::LiveCurrent,
            Self::Candidate(_) => Provenance::Candidate,
            Self::Snapshot(_) => Provenance::Snapshot,
            Self::RetainedGeneration(_) => Provenance::RetainedGeneration,
            Self::StalePublication(_) => Provenance::StalePublication,
        }
    }
}

/// Named provenance of a refused grant input, for refusal reporting.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Provenance {
    /// A publication claimed to be the live `Current` one.
    LiveCurrent,
    /// An in-progress candidate.
    Candidate,
    /// An on-disk snapshot seed.
    Snapshot,
    /// A generation retained by a non-`Current` state.
    RetainedGeneration,
    /// A previously-`Current` publication.
    StalePublication,
}

/// Named source phase, for refusal reporting.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PhaseName {
    /// No generation retained, none queryable.
    Loading,
    /// Exactly one generation queryable.
    Current,
    /// One generation retained, none queryable.
    Refreshing,
    /// Zero or one generation retained for recovery, none queryable.
    Blocked,
    /// Revoked; zero or one generation retained for accounting.
    Stopping,
}

/// The live runtime phase of one source.
#[derive(Debug)]
enum SourcePhase {
    Loading,
    Current(CurrentPublication),
    Refreshing {
        retained: GenerationIdentity,
        binding: BindingAuthority,
        publication: PublicationIdentity,
    },
    Blocked {
        retained: Option<GenerationIdentity>,
    },
    Stopping {
        retained: Option<GenerationIdentity>,
    },
}

impl SourcePhase {
    fn name(&self) -> PhaseName {
        match self {
            Self::Loading => PhaseName::Loading,
            Self::Current(_) => PhaseName::Current,
            Self::Refreshing { .. } => PhaseName::Refreshing,
            Self::Blocked { .. } => PhaseName::Blocked,
            Self::Stopping { .. } => PhaseName::Stopping,
        }
    }
}

/// Why an authority request was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthorityRefusal {
    /// The source is not `Current`, so no queryable generation exists to grant from.
    PhaseNotCurrent {
        /// The phase actually observed.
        phase: PhaseName,
    },
    /// The presented input is not a live `Current` publication.
    ProvenanceNotLiveCurrent {
        /// The provenance actually presented.
        provenance: Provenance,
    },
    /// The named publication is not the one that is live.
    PublicationIdentityMismatch {
        /// The publication the caller named.
        presented: PublicationIdentity,
        /// The publication that is actually live.
        live: PublicationIdentity,
    },
    /// The permit's pinned physical root is no longer installed.
    PhysicalRootReplaced,
    /// The permit has already reached a terminal state.
    PermitAlreadyTerminal,
    /// A side effect was attempted on a permit that is already in flight.
    SideEffectAlreadyInFlight,
    /// The authority presented does not match the live source as a whole.
    WholeAuthorityMismatch,
    /// A transition was attempted while a permit was still outstanding.
    OutstandingPermit,
}

/// The live runtime of one source: the sole owner of its phase, epoch, and the
/// record of permits it has issued.
#[derive(Debug)]
pub struct SourceRuntime {
    phase: SourcePhase,
    mutation_epoch: MutationEpoch,
    grants_issued: u64,
}

impl SourceRuntime {
    /// Start a source in `Loading` with no queryable generation.
    pub fn loading() -> Self {
        Self {
            phase: SourcePhase::Loading,
            mutation_epoch: MutationEpoch::initial(),
            grants_issued: 0,
        }
    }

    /// Start a source already `Current` on the given publication.
    pub fn current(publication: CurrentPublication) -> Self {
        Self {
            phase: SourcePhase::Current(publication),
            mutation_epoch: MutationEpoch::initial(),
            grants_issued: 0,
        }
    }

    /// Start a source in `Refreshing`, retaining one generation.
    pub fn refreshing(binding: BindingAuthority, retained: GenerationIdentity) -> Self {
        Self {
            phase: SourcePhase::Refreshing {
                retained,
                binding,
                publication: PublicationIdentity::fresh(),
            },
            mutation_epoch: MutationEpoch::initial(),
            grants_issued: 0,
        }
    }

    /// Start a source in `Blocked`.
    pub fn blocked(retained: Option<GenerationIdentity>) -> Self {
        Self {
            phase: SourcePhase::Blocked { retained },
            mutation_epoch: MutationEpoch::initial(),
            grants_issued: 0,
        }
    }

    /// Start a source in `Stopping`.
    pub fn stopping(retained: Option<GenerationIdentity>) -> Self {
        Self {
            phase: SourcePhase::Stopping { retained },
            mutation_epoch: MutationEpoch::initial(),
            grants_issued: 0,
        }
    }

    /// The current phase name.
    pub fn phase(&self) -> PhaseName {
        self.phase.name()
    }

    /// The current mutation epoch. Diagnostic only.
    pub fn mutation_epoch(&self) -> MutationEpoch {
        self.mutation_epoch
    }

    /// How many permits this source has ever issued. A refused request must not
    /// change this.
    pub fn grants_issued(&self) -> u64 {
        self.grants_issued
    }

    /// The generation this phase retains, if any.
    ///
    /// Strict queryability is closed: only `Current` holds a query-granting
    /// generation. `Loading` retains none, `Refreshing` exactly one, and
    /// `Blocked`/`Stopping` zero or one for recovery and accounting. A retained
    /// generation is never queryable — it is reported here for accounting only.
    pub fn retained_generation(&self) -> Option<GenerationIdentity> {
        match &self.phase {
            SourcePhase::Loading => None,
            SourcePhase::Current(publication) => Some(publication.generation()),
            SourcePhase::Refreshing { retained, .. } => Some(*retained),
            SourcePhase::Blocked { retained } | SourcePhase::Stopping { retained } => *retained,
        }
    }

    /// The binding a non-`Current` phase is still bound to, if any.
    pub fn retained_binding(&self) -> Option<&BindingAuthority> {
        match &self.phase {
            SourcePhase::Current(publication) => Some(publication.binding()),
            SourcePhase::Refreshing { binding, .. } => Some(binding),
            SourcePhase::Loading | SourcePhase::Blocked { .. } | SourcePhase::Stopping { .. } => {
                None
            }
        }
    }

    /// The live `Current` publication, if the source is `Current`.
    pub fn live_publication(&self) -> Option<&CurrentPublication> {
        match &self.phase {
            SourcePhase::Current(publication) => Some(publication),
            _ => None,
        }
    }

    /// The identity of the publication this source currently stands on, when it
    /// stands on one.
    ///
    /// `Blocked` and `Stopping` report their immutable phase without inventing a
    /// publication identity they never stored.
    pub fn published_identity(&self) -> Option<PublicationIdentity> {
        match &self.phase {
            SourcePhase::Current(publication) => Some(publication.publication()),
            SourcePhase::Refreshing { publication, .. } => Some(*publication),
            SourcePhase::Loading | SourcePhase::Blocked { .. } | SourcePhase::Stopping { .. } => {
                None
            }
        }
    }

    /// Publish non-`Current`, advancing the mutation epoch, and return the
    /// identity of the publication actually stored.
    ///
    /// Epoch and permit record are carried across, never reset: the epoch is
    /// monotonic for the life of the source, so a reload or rebind cannot rewind
    /// it and let a stale authority compare equal to a later one.
    /// Returns `None` when the phase had nothing to publish.
    ///
    /// `Loading`, `Blocked` and `Stopping` store no publication, so an earlier
    /// version returning a freshly minted identity for them was attesting to a
    /// publication nothing had stored — the same defect this slice already fixed
    /// once. It also advanced the epoch for a freeze that did not happen; it now
    /// leaves the epoch alone on that path too.
    pub fn freeze(&mut self) -> Option<PublicationIdentity> {
        let (retained, binding) = match &self.phase {
            SourcePhase::Current(current) => (current.generation(), current.binding().clone()),
            SourcePhase::Refreshing {
                retained, binding, ..
            } => (*retained, binding.clone()),
            SourcePhase::Loading | SourcePhase::Blocked { .. } | SourcePhase::Stopping { .. } => {
                return None;
            }
        };
        let publication = PublicationIdentity::fresh();
        self.mutation_epoch = self.mutation_epoch.advanced();
        self.phase = SourcePhase::Refreshing {
            retained,
            binding,
            publication,
        };
        Some(publication)
    }

    /// Install a new `Current` publication, preserving the monotonic epoch and
    /// the grant record.
    ///
    /// Deliberately `pub(crate)`: republishing `Current` makes the source
    /// queryable again, and a permit outstanding from the previous freeze would
    /// then be able to act against a queryable source. `transition::apply` is
    /// the only caller, and it reaches this line only after Drain has confirmed
    /// nothing is outstanding.
    pub(crate) fn install(&mut self, publication: CurrentPublication) {
        self.phase = SourcePhase::Current(publication);
    }

    /// Request the one grant that can authorize a mutation permit.
    ///
    /// On refusal, neither the mutation epoch nor the permit record advances and
    /// the phase is unchanged: a rejected request leaves no trace that a later
    /// step could mistake for permission.
    ///
    /// On acceptance, the source publishes `Refreshing` and advances its epoch
    /// *before* the grant exists, so no holder of a grant can perform a source
    /// side effect while the source is still queryable.
    pub fn request_mutation_grant(
        &mut self,
        input: MutationGrantInput,
    ) -> Result<CurrentMutationGrantAuthority, AuthorityRefusal> {
        let live = match &self.phase {
            SourcePhase::Current(publication) => publication.clone(),
            other => {
                return Err(AuthorityRefusal::PhaseNotCurrent {
                    phase: other.name(),
                });
            }
        };

        let presented = match input {
            MutationGrantInput::LiveCurrent(presented) => presented,
            other => {
                return Err(AuthorityRefusal::ProvenanceNotLiveCurrent {
                    provenance: other.provenance(),
                });
            }
        };

        if presented != live.publication() {
            return Err(AuthorityRefusal::PublicationIdentityMismatch {
                presented,
                live: live.publication(),
            });
        }

        // Publish non-Current before the grant exists. Order is the invariant:
        // the source stops being queryable first, then a mutation is authorized.
        // `freeze` performs and records that publication, and the proof below
        // names the identity it actually stored -- not a freshly minted one that
        // nothing published.
        // The phase was matched as `Current` above and nothing between here and
        // there can change it, so `freeze` has something to publish.
        let publication = self
            .freeze()
            .expect("a Current source always has a publication to freeze");
        let epoch = self.mutation_epoch;
        self.grants_issued += 1;

        Ok(CurrentMutationGrantAuthority {
            authority: MutationAuthority {
                generation: live.generation(),
                binding: live.binding().clone(),
                epoch,
                publication: live.publication(),
            },
            published_non_current: NonCurrentPublicationProof { publication, epoch },
        })
    }
}