symforge 11.18.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
//! Full content selection through shared admission, rendering, and session engines.
use super::activation::ProjectSourceAuthority;
use super::embed_query::{Budget, EmbeddedQuerySnapshot, validate_path};
use super::embed_session::QuerySession;
use super::guidance::{file_read, read_contract, read_gate};
use crate::embed::parity::read::*;
use crate::embed::parity::{QueryObservation, QueryOutput, QueryRefusalKind};
use crate::lifecycle_identity::PublicationIdentity;
use crate::live_index::{IndexedFile, search::ContentContext};

fn authority_refusal(refusal: super::authority::AuthorityRefusal) -> QueryRefusalKind {
    match refusal {
        super::authority::AuthorityRefusal::PublicationIdentityMismatch { .. } => {
            QueryRefusalKind::StalePublication
        }
        super::authority::AuthorityRefusal::PhaseNotCurrent { .. }
        | super::authority::AuthorityRefusal::PhysicalRootReplaced
        | super::authority::AuthorityRefusal::BindingRevoked { .. } => {
            QueryRefusalKind::SourceUnavailable
        }
        _ => QueryRefusalKind::AdmissionUnavailable,
    }
}

fn input(
    request: &FileContentRequest,
) -> Result<read_contract::GetFileContentInput, QueryRefusalKind> {
    let mut value: read_contract::GetFileContentInput =
        serde_json::from_value(serde_json::to_value(request).expect("read request serializes"))
            .map_err(|_| QueryRefusalKind::InvalidRequest)?;
    read_contract::normalize_file_content_aliases(&mut value)
        .map_err(|_| QueryRefusalKind::InvalidRequest)?;
    Ok(value)
}
pub(super) fn validate(request: &FileContentRequest) -> Result<(), QueryRefusalKind> {
    validate_path(&request.path, false)?;
    if request.max_tokens == Some(0) {
        return Err(QueryRefusalKind::InvalidRequest);
    }
    let input = input(request)?;
    read_contract::file_content_options_from_input(&input)
        .map_err(|_| QueryRefusalKind::InvalidRequest)?;
    Ok(())
}
pub(super) fn validate_page(request: &SourcePageRequest) -> Result<(), QueryRefusalKind> {
    validate_path(&request.path, false)?;
    if request.offset > 0 && request.expected_publication.is_none() {
        return Err(QueryRefusalKind::InvalidRequest);
    }
    Ok(())
}
fn refuse_scope(path: &str) -> Result<(), QueryRefusalKind> {
    if read_gate::hard_scope_refusal(path).is_some() {
        return Err(QueryRefusalKind::AdmissionUnavailable);
    }
    Ok(())
}
pub(super) fn admit(
    snapshot: &EmbeddedQuerySnapshot,
    path: &str,
    bytes: Option<&[u8]>,
    budget: &mut Budget,
) -> Result<(), QueryRefusalKind> {
    admit_in(
        &snapshot.generation.live,
        &snapshot.authority,
        Some(snapshot.authority_publication),
        path,
        bytes,
        budget,
    )
}

/// Read bounded bytes beneath the admitted root, bound to `expected` when the
/// caller holds a publication and to the root anchor alone when it does not.
fn read_beneath(
    authority: &ProjectSourceAuthority,
    expected: Option<PublicationIdentity>,
    path: &str,
) -> Result<Option<Vec<u8>>, super::authority::AuthorityRefusal> {
    let relative = std::path::Path::new(path);
    let max = crate::knowledge::SECRET_SCAN_MAX_BYTES;
    match expected {
        Some(expected) => authority.read_regular_beneath_expected(expected, relative, max),
        None => authority.read_regular_beneath_anchor(relative, max),
    }
}

/// [`admit`] over the admission state of `live`, the latest published
/// generation, which MCP's disk lane also consults while not Ready.
fn admit_in(
    live: &crate::live_index::LiveIndex,
    authority: &ProjectSourceAuthority,
    expected: Option<PublicationIdentity>,
    path: &str,
    bytes: Option<&[u8]>,
    budget: &mut Budget,
) -> Result<(), QueryRefusalKind> {
    refuse_scope(path)?;
    let mut record = |meta| budget.withheld = Some(meta);
    if read_gate::refuse_by_policy_with(live, path, &mut record).is_some() {
        // Recorded content demotion has no positions in the manifest. Recover
        // only redacted findings from an original-anchor bounded re-read, using
        // the same rule-set comparison as the MCP read gate. Failure to enrich
        // keeps the policy refusal and never authorizes rendering source bytes.
        if budget.withheld.is_none()
            && let Some(crate::domain::FileDisposition::MetadataOnly {
                reason: crate::domain::MetadataOnlyReason::SensitiveContent { rule_ids, .. },
            }) = live.capture_file_disposition(path)
        {
            budget.withheld = Some(WithheldMeta::unscanned(path));
            if let Ok(Some(bytes)) = read_beneath(authority, expected, path) {
                let (_, findings) =
                    read_gate::recorded_finding_evidence_from_bytes(path, &bytes, rule_ids);
                if !findings.is_empty() {
                    budget.withheld = Some(WithheldMeta::from_content_findings(path, &findings));
                }
            }
        }
        return Err(QueryRefusalKind::AdmissionUnavailable);
    }
    let mut record = |meta| budget.withheld = Some(meta);
    if bytes.is_some_and(|bytes| {
        read_gate::classify_admitted_bytes_with(live, path, bytes, &mut record).is_some()
    }) {
        return Err(QueryRefusalKind::AdmissionUnavailable);
    }
    Ok(())
}
fn selected_range(file: &IndexedFile, context: &ContentContext) -> Result<(), QueryRefusalKind> {
    selection_refusal(file_read::content_selection(
        Some(file),
        &file.content,
        context,
    ))
}

/// Check the exact admitted file before reusing indexed source or session output.
/// A changed observation is withheld until the source worker publishes it.
fn verify_indexed_content(
    snapshot: &EmbeddedQuerySnapshot,
    path: &str,
    indexed: &IndexedFile,
) -> Result<(), QueryRefusalKind> {
    use std::io::Read;
    let matches = snapshot
        .authority
        .with_regular_file_beneath_expected(
            snapshot.authority_publication,
            std::path::Path::new(path),
            |opened| {
                let Ok(before) = opened.metadata() else {
                    return Ok(false);
                };
                if before.len() != indexed.content.len() as u64 {
                    return Ok(false);
                }
                let mut buffer = [0u8; 8192];
                for expected in indexed.content.chunks(buffer.len()) {
                    let target = &mut buffer[..expected.len()];
                    if opened.read_exact(target).is_err() || target != expected {
                        return Ok(false);
                    }
                }
                let Ok(after) = opened.metadata() else {
                    return Ok(false);
                };
                Ok(after.len() == before.len() && after.modified().ok() == before.modified().ok())
            },
        )
        .map_err(|_| QueryRefusalKind::SourceUnavailable)?;
    if matches == Some(true) {
        Ok(())
    } else {
        Err(QueryRefusalKind::StalePublication)
    }
}

fn selected_content_range(
    content: &[u8],
    context: &ContentContext,
) -> Result<(), QueryRefusalKind> {
    selection_refusal(file_read::content_selection(None, content, context))
}

/// The shared selection outcome as this lane's typed refusal.
fn selection_refusal(
    selection: Result<(), file_read::ContentSelectionMiss>,
) -> Result<(), QueryRefusalKind> {
    selection.map_err(|miss| match miss {
        file_read::ContentSelectionMiss::NotFound => QueryRefusalKind::NotFound,
        file_read::ContentSelectionMiss::Ambiguous => QueryRefusalKind::AmbiguousSymbol,
        file_read::ContentSelectionMiss::Invalid => QueryRefusalKind::InvalidRequest,
    })
}
/// MCP `validate_file_syntax`'s authoritative disk-parse lane: the file is
/// unindexed, or its freshen did not publish. The bytes on disk right now are
/// read through the original-root capability, admitted by the same policy and
/// classification as every other read (a refusal carries the same withheld
/// findings), and parsed exactly as MCP parses them.
pub(super) fn observe_for_syntax(
    snapshot: &EmbeddedQuerySnapshot,
    path: &str,
    budget: &mut Budget,
) -> Result<IndexedFile, QueryRefusalKind> {
    observe_syntax_in(
        &snapshot.generation.live,
        &snapshot.authority,
        Some(snapshot.authority_publication),
        path,
        budget,
    )
}

/// The disk parse behind [`observe_for_syntax`]. With `expected = None` the
/// read binds the admitted root anchor only and claims no publication.
pub(super) fn observe_syntax_in(
    live: &crate::live_index::LiveIndex,
    authority: &ProjectSourceAuthority,
    expected: Option<PublicationIdentity>,
    path: &str,
    budget: &mut Budget,
) -> Result<IndexedFile, QueryRefusalKind> {
    refuse_scope(path)?;
    let extension = std::path::Path::new(path)
        .extension()
        .and_then(|extension| extension.to_str())
        .unwrap_or("");
    let language = crate::domain::LanguageId::from_extension(extension)
        .ok_or(QueryRefusalKind::UnsupportedOption)?;
    let relative = std::path::Path::new(path);
    let spelled = match expected {
        Some(expected) => authority.verify_exact_spelling_expected(expected, relative),
        None => authority.verify_exact_spelling_anchor(relative),
    };
    if !spelled.map_err(authority_refusal)? {
        return Err(budget.refuse_with(QueryRefusalKind::NotFound, file_read::not_found_file(path)));
    }
    admit_in(live, authority, expected, path, None, budget)?;
    let Some(bytes) = read_beneath(authority, expected, path).map_err(authority_refusal)? else {
        return Err(budget.refuse_with(QueryRefusalKind::NotFound, file_read::not_found_file(path)));
    };
    admit_in(live, authority, expected, path, Some(&bytes), budget)?;
    let result = crate::parsing::process_file_with_classification(
        path,
        &bytes,
        language,
        crate::domain::FileClassification::for_code_path(path),
    );
    Ok(IndexedFile::from_parse_result(result, bytes))
}

pub(super) fn page(
    snapshot: &EmbeddedQuerySnapshot,
    request: &SourcePageRequest,
    budget: &mut Budget,
) -> Result<QueryOutput, QueryRefusalKind> {
    if request
        .expected_publication
        .as_ref()
        .is_some_and(|expected| expected != &snapshot.serving_publication_identity)
    {
        return Err(QueryRefusalKind::StalePublication);
    }
    admit(snapshot, &request.path, None, budget)?;
    let file = snapshot
        .generation
        .live
        .get_file(&request.path)
        .ok_or(QueryRefusalKind::NotFound)?;
    let offset = usize::try_from(request.offset).map_err(|_| QueryRefusalKind::InvalidRequest)?;
    if offset > file.content.len() {
        return Err(QueryRefusalKind::InvalidRequest);
    }
    let hash = crate::hash::digest_hex(&file.content);
    budget.required(request.path.len() + hash.len())?;
    if offset < file.content.len() && budget.remaining_bytes() == 0 {
        return Err(QueryRefusalKind::BudgetTooSmall);
    }
    let bytes = budget.source(&file.content[offset..]);
    let end = offset + bytes.len();
    Ok(QueryOutput::SourcePage(SourcePage {
        path: request.path.clone(),
        content_hash: hash,
        byte_start: request.offset,
        total_bytes: file.content.len() as u64,
        bytes,
        next_offset: (end < file.content.len()).then_some(end as u64),
    }))
}
pub(super) fn content(
    snapshot: &EmbeddedQuerySnapshot,
    request: &FileContentRequest,
    session: Option<&QuerySession>,
    budget: &mut Budget,
    observations: &mut Vec<QueryObservation>,
) -> Result<QueryOutput, QueryRefusalKind> {
    let input = input(request)?;
    let options = read_contract::file_content_options_from_input(&input)
        .map_err(|_| QueryRefusalKind::InvalidRequest)?;
    refuse_scope(&input.path)?;
    let indexed = snapshot.generation.live.get_file(&input.path);
    if indexed.is_none()
        && !snapshot
            .authority
            .verify_exact_spelling_expected(
                snapshot.authority_publication,
                std::path::Path::new(&input.path),
            )
            .map_err(authority_refusal)?
    {
        return Err(budget.refuse_with(
            QueryRefusalKind::NotFound,
            file_read::not_found_file(&input.path),
        ));
    }
    if input.estimate == Some(true) {
        let (size, lines, authority) = if let Some(file) = indexed {
            (
                file.content.len() as u64,
                Some(file.content.iter().filter(|&&b| b == b'\n').count() as u64),
                ReadAuthority::PublishedGeneration,
            )
        } else {
            let size = snapshot
                .authority
                .regular_file_size_beneath_expected(
                    snapshot.authority_publication,
                    std::path::Path::new(&input.path),
                )
                .map_err(authority_refusal)?
                .ok_or(QueryRefusalKind::NotFound)?;
            (size, None, ReadAuthority::DiskObservation)
        };
        budget.required(input.path.len() + 32)?;
        return Ok(QueryOutput::FileReadEstimate(FileReadEstimate {
            path: input.path,
            approximate_tokens: crate::stel::handler::estimate_tokens_from_bytes(size),
            approximate_lines: lines,
            authority,
        }));
    }
    admit(snapshot, &input.path, None, budget)?;
    let annotation = match (
        &options.content_context.mode_name,
        options.content_context.mode_explicit,
    ) {
        (Some(mode), true) => format!("── mode: {mode} (explicit) ──\n"),
        _ => String::new(),
    };
    let first_line = options.content_context.start_line.unwrap_or(1);
    let numbered = options.content_context.show_line_numbers
        || options.content_context.around_line.is_some()
        || options.content_context.around_match.is_some()
        || options.content_context.around_symbol.is_some()
        || options.content_context.chunk_index.is_some();
    // FR-024: only an explicit `max_tokens` budgets the output; the byte cap is the
    // hard limit. MCP finishes a refused selection's text exactly as an answer.
    let finish = |body: &str, content: &[u8]| {
        file_read::finish_file_content(
            format!("{annotation}{body}"),
            &input.path,
            first_line,
            numbered,
            content,
            input.max_tokens,
        )
    };
    let (rendered, hash, authority, content) = if let Some(file) = indexed {
        verify_indexed_content(snapshot, &input.path, file)?;
        // A selection MCP cannot serve is answered with the shared renderer's text.
        selected_range(file, &options.content_context).map_err(|kind| {
            let text = file_read::file_content_from_indexed_file_with_context(
                file,
                options.content_context.clone(),
            );
            budget.refuse_with(kind, finish(&text, &file.content).1)
        })?;
        if let Some(session) = session
            && let Some((handle, body)) =
                session.file_content_cache_hit(snapshot, request, budget.limits())
        {
            let content_hash = crate::hash::digest_hex(&file.content);
            budget.charge_bytes(
                input.path.len() + content_hash.len() + "PublishedGeneration".len(),
            )?;
            let rendered = budget.text(&body)?;
            budget.reused_handle = Some(handle);
            return Ok(QueryOutput::FileContent(FileContent {
                path: input.path,
                content_hash,
                approximate_tokens: crate::stel::handler::estimate_tokens_from_bytes(
                    rendered.len() as u64,
                ),
                rendered,
                cache_hit: true,
                authority: ReadAuthority::PublishedGeneration,
            }));
        }
        let output = file_read::file_content_from_indexed_file_with_context(
            file,
            options.content_context.clone(),
        );
        (
            output,
            crate::hash::digest_hex(&file.content),
            ReadAuthority::PublishedGeneration,
            std::borrow::Cow::Borrowed(&file.content[..]),
        )
    } else {
        let bytes = snapshot
            .authority
            .read_regular_beneath_expected(
                snapshot.authority_publication,
                std::path::Path::new(&input.path),
                crate::knowledge::SECRET_SCAN_MAX_BYTES,
            )
            .map_err(authority_refusal)?
            .ok_or(QueryRefusalKind::NotFound)?;
        admit(snapshot, &input.path, Some(&bytes), budget)?;
        if let Some(name) = options.content_context.around_symbol.as_deref() {
            // An unindexed file has no symbols (MCP's text).
            let text = file_read::unindexed_symbol_not_found(&input.path, name);
            return Err(budget.refuse_with(QueryRefusalKind::NotFound, finish(&text, &bytes).1));
        }
        selected_content_range(&bytes, &options.content_context).map_err(|kind| {
            let text = file_read::render_file_content_bytes(
                &input.path,
                &bytes,
                options.content_context.clone(),
            );
            budget.refuse_with(kind, finish(&text, &bytes).1)
        })?;
        let body = file_read::render_file_content_bytes(
            &input.path,
            &bytes,
            options.content_context.clone(),
        );
        let hash = crate::hash::digest_hex(&bytes);
        observations.push(QueryObservation {
            kind: "disk_observation".into(),
            identity: input.path.clone(),
            content_hash: hash.clone(),
        });
        (
            body,
            hash,
            ReadAuthority::DiskObservation,
            std::borrow::Cow::Owned(bytes),
        )
    };
    let file_capped = annotation.len() + rendered.len() > file_read::GET_FILE_CONTENT_MAX_BYTES;
    let (warned, mut rendered, token_capped) = finish(&rendered, &content);
    if input.force_refresh == Some(true)
        && let Some(prior) = session.and_then(|session| {
            session.prior_file_content_fetch(snapshot, request, budget.limits())
        })
    {
        rendered = file_read::append_dedup_hint_footer(
            rendered,
            "file",
            prior.fetched_at.elapsed().as_secs(),
            prior.approx_tokens,
        );
    }
    let full = FileContent {
        path: input.path,
        content_hash: hash,
        approximate_tokens: crate::stel::handler::estimate_tokens_from_bytes(warned.len() as u64),
        rendered: warned,
        cache_hit: false,
        authority,
    };
    budget.charge_bytes(
        full.path.len()
            + full.content_hash.len()
            + match authority {
                ReadAuthority::PublishedGeneration => "PublishedGeneration".len(),
                ReadAuthority::DiskObservation => "DiskObservation".len(),
            },
    )?;
    budget.cache_output = Some(QueryOutput::FileContent(full.clone()));
    budget.cache_truncated = file_capped;
    budget.truncated |= file_capped || token_capped;
    let mut served = full;
    served.rendered = budget.text(&rendered)?;
    served.approximate_tokens =
        crate::stel::handler::estimate_tokens_from_bytes(served.rendered.len() as u64);
    Ok(QueryOutput::FileContent(served))
}