symforge 11.20.2

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
//! The `detect_impact` blast-radius computation, shared by the MCP handler
//! and the embedded query lane. Callers own repository access, the read gate
//! sink and rendering; the change seed, the graph walk and the risk ordering
//! live here once.

use std::collections::HashMap;

use crate::live_index::LiveIndex;
use crate::live_index::graph::{CallEdgeEvidence, RiskTier, SymbolId};

/// Maximum depth accepted before `detect_impact` clamps + warns
/// (contracts/detect-impact.md § Risk tiers / error catalog: "depth capped").
pub(crate) const DETECT_IMPACT_MAX_DEPTH: u8 = 5;

/// ponytail: fixed safety cap on EACH list (`changed_files`, `changed_symbols`,
/// `blast_radius`) returned per call — the bound that stops the 54 MB / 291K-symbol
/// dump seen on a large repo. The frozen contract's `pagination` envelope has no
/// `offset`/`limit` input field to page past it — add one if a real need for
/// deeper paging shows up. `risk_summary` is always counted over the full set.
pub(crate) const DETECT_IMPACT_MAX_RETURNED: usize = 200;
pub(crate) const DETECT_IMPACT_MAX_EVIDENCE_BYTES: usize = 256 * 1024;

/// The interpreted `detect_impact` options.
pub(crate) struct ImpactRequest<'a> {
    pub base_branch: Option<&'a str>,
    pub since: Option<&'a str>,
    pub depth: u8,
    /// `scope=files` aggregates blast nodes per file; otherwise per symbol.
    pub files_scope: bool,
    pub include_untracked: bool,
    pub include_data: bool,
    pub paths: Option<&'a [String]>,
}

/// The complete, uncapped blast radius. `blast_entries` is ordered most severe
/// first, then nearest hop, then name, so any prefix keeps the worst nodes.
pub(crate) struct ImpactReport {
    pub changed_files: Vec<String>,
    pub changed_symbols: Vec<SymbolId>,
    pub blast_entries: Vec<ImpactBlastEntry>,
    pub include_data: bool,
    pub source_filtered_out: usize,
    pub requested_depth: u8,
    pub effective_depth: u8,
    pub base_disclosure: Option<String>,
    pub staleness_note: Option<String>,
}

pub(crate) struct ImpactBlastEntry {
    pub symbol: String,
    pub hop: u32,
    pub risk: RiskTier,
    /// A complete shortest chain when every selected edge has source evidence.
    pub evidence: Option<Vec<CallEdgeEvidence>>,
}

/// Convert the graph index's inclusive source rows to a half-open, zero-based
/// public line span.
pub(crate) fn impact_evidence_line_range(range: (u32, u32)) -> [usize; 2] {
    [range.0 as usize, range.1.saturating_add(1) as usize]
}

impl ImpactReport {
    /// Risk counts over the FULL blast set, never the capped list.
    pub(crate) fn risk_counts(&self) -> HashMap<&'static str, u32> {
        let mut risk_counts: HashMap<&'static str, u32> = HashMap::new();
        for entry in &self.blast_entries {
            *risk_counts.entry(entry.risk.as_str()).or_insert(0) += 1;
        }
        risk_counts
    }
}

/// An admitted git-object read: `(ref, path)` to gated text.
pub(crate) type GitTextRead<'a> = dyn FnMut(&str, &str) -> Result<Option<String>, String> + 'a;
/// An admitted working-tree read: `path` to gated text.
pub(crate) type WorktreeTextRead<'a> = dyn FnMut(&str) -> Result<Option<String>, String> + 'a;

/// Compute the git blast radius. `read_git(ref, path)` and `read_worktree(path)`
/// must be admitted reads (the shared read gate); a refusal is treated as "no
/// content", the conservative seed. `Err` carries the caller-ready message.
pub(crate) fn compute_detect_impact(
    live: &LiveIndex,
    repo: &crate::git::GitRepo,
    request: &ImpactRequest<'_>,
    read_git: &mut GitTextRead<'_>,
    read_worktree: &mut WorktreeTextRead<'_>,
) -> Result<ImpactReport, String> {
    let requested_depth = request.depth;
    let effective_depth = requested_depth.min(DETECT_IMPACT_MAX_DEPTH);

    // contracts/detect-impact.md § Input: `base_branch` defaults to `main`
    // when the caller supplies neither `base_branch` nor `since`. Without
    // this, the STEL-upgraded path (`route_impact` plans only
    // `{"scope":"files"}`) would silently fall through to uncommitted-only
    // and return an empty blast radius on a clean tree with committed-but-
    // unmerged work — the silent no-op the depth-default already guards
    // against. A repo with no `main` branch degrades to the "Invalid git
    // ref" error below (git2 ref resolution fails), never a panic; pass an
    // explicit `base_branch`/`since` for non-`main` default branches.
    //
    // Wave-1 defect fix (2026-07-02, contracts/detect-impact.md § 2026-07-02
    // addendum): the DEFAULT substitution now prefers `origin/main` over
    // local `main`. A local `main` that lags the remote (e.g. 83 commits
    // behind) produces a confidently-wrong blast radius against a stale base;
    // the shared remote ref is the intended comparison. An EXPLICIT
    // caller-passed `base_branch:"main"` still means local `main` (unchanged).
    // The resolved ref (and any staleness) is disclosed in the response
    // header so the output is self-describing.
    let mut staleness_note: Option<String> = None;
    let base_branch: Option<String> = if request.base_branch.is_none() && request.since.is_none() {
        if request.paths.is_some() {
            None
        } else {
            let origin = repo.resolve_ref_commit("origin/main");
            let local = repo.resolve_ref_commit("main");
            let resolved = match (origin, local) {
                (Some(origin_oid), Some(local_oid)) => {
                    if origin_oid != local_oid {
                        // Direction-aware disclosure (Wave 1 Fix 3): behind is the
                        // motivating stale-local case; ahead means unpushed local
                        // work landed in the base; both means diverged. `ahead` =
                        // commits in local not in origin; `behind` = the reverse.
                        staleness_note = Some(match repo.ahead_behind(local_oid, origin_oid) {
                            Some((ahead, behind)) if behind > 0 && ahead == 0 => {
                                "local main is behind origin/main; using origin/main".to_string()
                            }
                            Some((ahead, behind)) if ahead > 0 && behind == 0 => {
                                "local main is ahead of origin/main (unpushed commits); using \
                                 origin/main — the blast radius includes your unpushed work \
                                 relative to the shared base"
                                    .to_string()
                            }
                            Some((ahead, behind)) if ahead > 0 && behind > 0 => {
                                "local main and origin/main have diverged; using origin/main"
                                    .to_string()
                            }
                            // No common ancestor (or the unreachable both-zero given
                            // origin != local): fall back to the direction-neutral note.
                            _ => {
                                "local main differs from origin/main; using origin/main".to_string()
                            }
                        });
                    }
                    "origin/main"
                }
                (Some(_), None) => "origin/main",
                // No origin/main (or neither ref exists): fall back to local
                // `main`. When neither exists, merge_git_changed_paths surfaces
                // the existing "Invalid git ref" error below, unchanged.
                (None, _) => "main",
            };
            Some(resolved.to_string())
        }
    } else {
        request.base_branch.map(str::to_owned)
    };
    // The base ref disclosed in the response header: the resolved default or
    // the explicit caller value; `None` when only `since` was supplied.
    let base_disclosure: Option<String> = base_branch.clone();

    let since_trimmed = request.since.map(str::trim).filter(|s| !s.is_empty());
    let (changed_files, seed_base_ref) = if let Some(explicit_paths) = request.paths {
        let seed_base_ref = match since_trimmed {
            Some("WORKTREE") => "HEAD".to_string(),
            Some(since_ref) => since_ref.to_string(),
            None => base_branch.as_deref().unwrap_or("HEAD").to_string(),
        };
        (explicit_paths.to_vec(), seed_base_ref)
    } else {
        let (mut paths, seed_base_ref) = match since_trimmed {
            Some("WORKTREE") => (
                repo.merge_git_changed_paths(None, Some("WORKTREE"), request.include_untracked)
                    .map_err(|e| format!("Error: Invalid git ref: {e}"))?,
                "HEAD".to_string(),
            ),
            Some(since_ref) => {
                let range = repo
                    .comparison_range_between_refs(since_ref, "HEAD")
                    .map_err(|e| format!("Error: Invalid git ref: {e}"))?;
                let mut paths = repo
                    .changed_paths_for_comparison(&range)
                    .map_err(|e| format!("Error: Invalid git ref: {e}"))?;
                if request.include_untracked {
                    paths.extend(
                        repo.uncommitted_paths()
                            .map_err(|e| format!("Error: Invalid git ref: {e}"))?,
                    );
                }
                (paths, range.base_commit.to_string())
            }
            None => {
                if let Some(base) = base_branch.as_deref() {
                    let range = repo
                        .comparison_range_between_refs(base, "HEAD")
                        .map_err(|e| format!("Error: Invalid git ref: {e}"))?;
                    let mut paths = repo
                        .changed_paths_for_comparison(&range)
                        .map_err(|e| format!("Error: Invalid git ref: {e}"))?;
                    if request.include_untracked {
                        paths.extend(
                            repo.uncommitted_paths()
                                .map_err(|e| format!("Error: Invalid git ref: {e}"))?,
                        );
                    }
                    (paths, range.base_commit.to_string())
                } else {
                    (Vec::new(), "HEAD".to_string())
                }
            }
        };
        paths.sort();
        paths.dedup();
        (paths, seed_base_ref)
    };

    // US1 (018) FR-001/FR-002: source-focus the impact seed by default so
    // non-source data files (e.g. untracked JSON) and their key-symbols
    // don't drive the blast radius. `include_data=true` restores the prior
    // inclusive changed-set. language=None never errors, so keep the seed
    // on the impossible Err rather than silently emptying the blast radius.
    let include_data = request.include_data;
    let unfiltered_changed_total = changed_files.len();
    let changed_files = if include_data {
        changed_files
    } else {
        super::changes::filter_paths_by_prefix_and_language(changed_files.clone(), None, None, true)
            .unwrap_or(changed_files)
    };
    // Recovered finding #1: disclose how many changed paths the source-focus
    // default removed, so an empty/shrunken blast radius is self-describing.
    let source_filtered_out = unfiltered_changed_total.saturating_sub(changed_files.len());

    // PART A (019): the seed is a BODY delta, not every symbol of a changed
    // file. Reparse each changed file's BASE blob and its CURRENT working
    // tree with the same extractor `diff_symbols` uses
    // (`extract_symbols_for_diff` -> name+body-hash pairs), then seed only
    // the symbols whose body was added, modified, or removed. A 1-line edit
    // in a 20-symbol file now seeds 1 symbol, not 20; a comment/whitespace
    // shift that leaves every body byte-identical seeds 0.
    //
    // Base ref: use the same resolved merge base as the three-dot changed-path
    // set above. This matters for divergent `since`/base refs: comparing file
    // bodies against the supplied ref tip could disagree with the reported
    // changed paths. `WORKTREE` compares from `HEAD`, then reads the worktree.
    let (changed_symbols, blast_radius) = {
        // Render from the SAME captured bundle the receipt names (D16).
        let guard = live;
        let mut changed_symbols: Vec<crate::live_index::graph::SymbolId> = Vec::new();
        for path in &changed_files {
            let before_len = changed_symbols.len();
            // Kind lookup for the CURRENT symbols comes from the live index;
            // removed symbols (absent from current) default to Function to
            // match the graph's own entry-point default.
            let kind_by_name: HashMap<&str, crate::domain::SymbolKind> = guard
                .files
                .get(path)
                .map(|f| {
                    f.symbols
                        .iter()
                        .map(|s| (s.name.as_str(), s.kind))
                        .collect()
                })
                .unwrap_or_default();

            // Gated (D8 closed): the git-object store is a disclosure lane
            // exactly like the working tree below. A refusal collapses to
            // "no base content", the same conservative seed as the worktree
            // arm — withheld beats disclosed for a demoted file's symbols.
            let base_content = read_git(&seed_base_ref, path)
                .unwrap_or_default()
                .unwrap_or_default();
            // Gated: a refusal collapses to "no current content", which
            // seeds conservatively from the index rather than disclosing
            // the demoted file's current symbol names or signatures.
            let current_content = read_worktree(path).unwrap_or_default().unwrap_or_default();

            // Unsupported/config languages return None from the extractor;
            // we cannot body-diff them, so fall back to seeding every
            // indexed symbol of the file (the old conservative behavior)
            // rather than silently seeding nothing.
            let base_syms = crate::parsing::extract_symbols_for_diff(&base_content, path);
            let current_syms = crate::parsing::extract_symbols_for_diff(&current_content, path);
            let (Some(base_syms), Some(current_syms)) = (base_syms, current_syms) else {
                if let Some(file) = guard.files.get(path) {
                    for sym in &file.symbols {
                        changed_symbols.push(crate::live_index::graph::SymbolId {
                            path: path.clone(),
                            name: sym.name.clone(),
                            kind: sym.kind,
                        });
                    }
                }
                continue;
            };

            // ponytail: name-keyed body-hash maps, matching `diff_symbols`'
            // own name-keyed comparison. Same-name overloads in one file
            // collapse to their last body hash; a resolver-aware seed
            // (C-S2-001) would key on a stable symbol id instead.
            let base_by_name: HashMap<&str, &str> = base_syms
                .iter()
                .map(|(n, h)| (n.as_str(), h.as_str()))
                .collect();
            let current_by_name: HashMap<&str, &str> = current_syms
                .iter()
                .map(|(n, h)| (n.as_str(), h.as_str()))
                .collect();

            let mut seed = |name: &str| {
                changed_symbols.push(crate::live_index::graph::SymbolId {
                    path: path.clone(),
                    name: name.to_string(),
                    kind: kind_by_name
                        .get(name)
                        .copied()
                        .unwrap_or(crate::domain::SymbolKind::Function),
                });
            };

            // Seeds follow source order, each name once: iterating the maps
            // themselves listed the same change in a different order on
            // every call.
            // Added (in current, not base) or modified (body hash differs).
            let mut seen = std::collections::HashSet::new();
            for (name, _) in &current_syms {
                let name = name.as_str();
                if !seen.insert(name) {
                    continue;
                }
                match base_by_name.get(name) {
                    None => seed(name),
                    Some(base_hash) if Some(base_hash) != current_by_name.get(name) => seed(name),
                    _ => {}
                }
            }
            // Removed (in base, not current) — seeded so downstream callers
            // of a deleted symbol still appear in the blast radius.
            let mut seen = std::collections::HashSet::new();
            for (name, _) in &base_syms {
                let name = name.as_str();
                if seen.insert(name) && !current_by_name.contains_key(name) {
                    seed(name);
                }
            }
            if request.paths.is_some()
                && changed_symbols.len() == before_len
                && let Some(file) = guard.files.get(path)
            {
                for sym in &file.symbols {
                    changed_symbols.push(crate::live_index::graph::SymbolId {
                        path: path.clone(),
                        name: sym.name.clone(),
                        kind: sym.kind,
                    });
                }
            }
        }
        let graph = crate::live_index::graph::GraphProjection::from_index(guard);
        let blast_radius = crate::live_index::graph::compute_impact_with_evidence(
            &graph,
            &changed_symbols,
            effective_depth as u32,
        );
        (changed_symbols, blast_radius)
    };

    // scope=files aggregates per-symbol blast nodes to file granularity
    // (nearest hop / matching risk wins per file); scope=symbols (default)
    // keeps one entry per symbol.
    let mut blast_entries: Vec<ImpactBlastEntry> = match request.files_scope {
        false => blast_radius
            .into_iter()
            // PART C (019): carry disambiguating identity. Two blast nodes
            // that share a bare name remain distinct `path::name` entries.
            .map(|entry| ImpactBlastEntry {
                symbol: format!("{}::{}", entry.node.symbol.path, entry.node.symbol.name),
                hop: entry.node.hop,
                risk: entry.node.risk,
                evidence: Some(entry.steps),
            })
            .collect(),
        true => {
            let mut by_file: HashMap<String, ImpactBlastEntry> = HashMap::new();
            for entry in blast_radius {
                let path = entry.node.symbol.path.clone();
                let candidate = ImpactBlastEntry {
                    symbol: path.clone(),
                    hop: entry.node.hop,
                    risk: entry.node.risk,
                    evidence: Some(entry.steps),
                };
                let replace = match by_file.get(&path) {
                    Some(current) => candidate.hop < current.hop,
                    None => true,
                };
                if replace {
                    by_file.insert(path, candidate);
                }
            }
            by_file.into_values().collect()
        }
    };
    // Fix 1 (Wave 1, 2026-07-02): keep the most severe blast nodes when the
    // list is capped — sort by risk severity desc, then hop asc, then name.
    blast_entries.sort_by(|a, b| {
        b.risk
            .severity_rank()
            .cmp(&a.risk.severity_rank())
            .then(a.hop.cmp(&b.hop))
            .then_with(|| a.symbol.cmp(&b.symbol))
    });

    Ok(ImpactReport {
        changed_files,
        changed_symbols,
        blast_entries,
        include_data,
        source_filtered_out,
        requested_depth,
        effective_depth,
        base_disclosure,
        staleness_note,
    })
}

#[cfg(test)]
mod tests {
    use super::impact_evidence_line_range;

    #[test]
    fn impact_evidence_line_range_is_zero_based_and_half_open() {
        assert_eq!(impact_evidence_line_range((3, 3)), [3, 4]);
        assert_eq!(impact_evidence_line_range((3, 5)), [3, 6]);
    }
}