symforge 11.0.13

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
//! detect_impact acceptance — Program 015 S1a (C-S1A-003).
//!
//! `tests/fixtures/cbm_impact` ships without a `.git/` directory (see its
//! README): rather than committing a permanent nested git repo into this
//! repo, each test copies the fixture source into a fresh tempdir and
//! bootstraps a real 2-commit history there, mirroring `git.rs`'s own
//! `make_test_repo` helper (git CLI for repo setup only, never production
//! code).
#![cfg(feature = "server")]

use std::fs;
use std::path::Path;

use serde_json::{Value, json};
use symforge::live_index::LiveIndex;
use symforge::protocol::SymForgeServer;

const FIXTURE_FILES: &[&str] = &[
    "Cargo.toml",
    "src/lib.rs",
    "src/a.rs",
    "src/b.rs",
    "src/c.rs",
    "src/main.rs",
];

fn git(args: &[&str], root: &Path) {
    let output = symforge::process_util::hidden_command("git")
        .args(args)
        .current_dir(root)
        .output()
        .unwrap_or_else(|e| panic!("git {args:?} failed to spawn: {e}"));
    assert!(
        output.status.success(),
        "git {args:?} failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

/// Copy `tests/fixtures/cbm_impact` into a fresh tempdir, commit it, then
/// make a real content edit to `src/a.rs` and commit again — the
/// `commit_2_changes_src_a_rs` scenario from `expected_impact.json`. The edit
/// changes `call_a`'s BODY (so it is a genuine body-delta seed under the
/// PART A (019) body-delta seed) while keeping its `core()` call, so `call_a`'s
/// call-graph edges are untouched and the blast radius is driven purely by who
/// calls `call_a`.
fn bootstrap_fixture() -> tempfile::TempDir {
    let dir = tempfile::tempdir().expect("tempdir");
    let root = dir.path();
    let fixture_src = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/cbm_impact");

    for rel in FIXTURE_FILES {
        let from = fixture_src.join(rel);
        let to = root.join(rel);
        if let Some(parent) = to.parent() {
            fs::create_dir_all(parent).unwrap_or_else(|e| panic!("mkdir for {rel}: {e}"));
        }
        fs::copy(&from, &to).unwrap_or_else(|e| panic!("copy {rel}: {e}"));
    }

    git(&["init"], root);
    git(&["config", "user.email", "test@test.com"], root);
    git(&["config", "user.name", "Test"], root);
    git(&["add", "."], root);
    git(&["commit", "-m", "initial"], root);

    fs::write(
        root.join("src/a.rs"),
        "use cbm_impact_fixture::core;\n\n\
         // S1a fixture bootstrap: real body change, same call graph.\n\
         pub fn call_a() -> u32 {\n    core() + 1\n}\n",
    )
    .expect("rewrite src/a.rs");
    git(&["commit", "-am", "change a"], root);

    dir
}

fn server_over(root: &Path) -> SymForgeServer {
    let shared = LiveIndex::load(root).expect("load index");
    SymForgeServer::new(
        shared,
        "detect_impact_test".to_string(),
        std::sync::Arc::new(parking_lot::Mutex::new(
            symforge::watcher::WatcherInfo::default(),
        )),
        Some(root.to_path_buf()),
        None,
    )
}

/// Extract the embedded `--- impact payload ---` JSON block from a
/// `detect_impact` response body (house convention: tool responses are text,
/// never raw JSON — see `format::detect_impact_result`).
fn impact_payload(body: &str) -> Value {
    const MARKER: &str = "--- impact payload ---\n";
    let start = body
        .find(MARKER)
        .unwrap_or_else(|| panic!("no impact payload marker in:\n{body}"));
    let json_text = &body[start + MARKER.len()..];
    // A depth-cap warning footer (if any) follows a blank line after the JSON.
    let json_text = json_text.split("\n\nWarning:").next().unwrap_or(json_text);
    serde_json::from_str(json_text)
        .unwrap_or_else(|e| panic!("parse impact payload: {e}\n---\n{json_text}"))
}

#[tokio::test]
async fn detect_impact_fixture_blast_matches_expected() {
    let dir = bootstrap_fixture();
    let server = server_over(dir.path());

    let body = server
        .dispatch_tool_for_tests("detect_impact", json!({ "since": "HEAD~1" }))
        .await;
    let payload = impact_payload(&body);

    assert_eq!(payload["changed_files"], json!(["src/a.rs"]));

    let changed_names: Vec<&str> = payload["changed_symbols"]
        .as_array()
        .expect("changed_symbols array")
        .iter()
        .map(|s| s["name"].as_str().expect("symbol name"))
        .collect();
    assert_eq!(
        changed_names,
        vec!["call_a"],
        "src/a.rs defines exactly one symbol: call_a"
    );

    // main() is the only caller of call_a (via the qualified `a::call_a()`)
    // and is itself the entry point, so it lands at hop 1 / risk critical.
    let blast = payload["blast_radius"]
        .as_array()
        .expect("blast_radius array");
    assert_eq!(blast.len(), 1, "unexpected blast radius: {blast:?}");
    // PART C (019): scope=symbols blast entries are path-qualified (`path::name`)
    // so same-name nodes stay distinguishable.
    assert_eq!(blast[0]["symbol"], json!("src/main.rs::main"));
    assert_eq!(blast[0]["hop"], json!(1));
    assert_eq!(blast[0]["risk"], json!("critical"));

    assert_eq!(payload["risk_summary"]["critical"], json!(1));
    assert_eq!(payload["risk_summary"]["high"], json!(0));
    assert_eq!(payload["risk_summary"]["medium"], json!(0));
    assert_eq!(payload["risk_summary"]["low"], json!(0));

    assert_eq!(payload["pagination"]["blast_radius"]["total"], json!(1));
    assert_eq!(payload["pagination"]["blast_radius"]["returned"], json!(1));
    assert_eq!(
        payload["pagination"]["blast_radius"]["truncated"],
        json!(false)
    );
}

/// Contract default (contracts/detect-impact.md § Input): omitting both
/// `base_branch` and `since` must diff against `main`, not silently degrade to
/// an uncommitted-only (empty, on a clean tree) result. Regression guard for
/// the STEL-upgraded path (`route_impact` plans only `{"scope":"files"}`).
#[tokio::test]
async fn detect_impact_defaults_base_branch_to_main_when_unset() {
    let dir = tempfile::tempdir().expect("tempdir");
    let root = dir.path();
    let fixture_src = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/cbm_impact");
    for rel in FIXTURE_FILES {
        let to = root.join(rel);
        if let Some(parent) = to.parent() {
            fs::create_dir_all(parent).unwrap_or_else(|e| panic!("mkdir for {rel}: {e}"));
        }
        fs::copy(fixture_src.join(rel), &to).unwrap_or_else(|e| panic!("copy {rel}: {e}"));
    }

    git(&["init"], root);
    git(&["config", "user.email", "test@test.com"], root);
    git(&["config", "user.name", "Test"], root);
    git(&["add", "."], root);
    git(&["commit", "-m", "initial"], root);
    // Force the default branch name so the test does not depend on the host's
    // `init.defaultBranch`.
    git(&["branch", "-M", "main"], root);

    // A committed-but-unmerged change on a feature branch, clean working tree.
    // Before the fix, no base/since meant "uncommitted-only" → empty result
    // here (nothing uncommitted). With the contract default, the omitted
    // base_branch diffs against `main` and surfaces the committed change.
    git(&["checkout", "-b", "feature"], root);
    fs::write(
        root.join("src/a.rs"),
        "use cbm_impact_fixture::core;\n\n\
         // committed on feature, not merged into main.\n\
         pub fn call_a() -> u32 {\n    core()\n}\n",
    )
    .expect("rewrite src/a.rs");
    git(&["commit", "-am", "change a on feature"], root);

    let server = server_over(root);

    let body = server
        .dispatch_tool_for_tests("detect_impact", json!({}))
        .await;
    let payload = impact_payload(&body);

    assert_eq!(
        payload["changed_files"],
        json!(["src/a.rs"]),
        "omitting base_branch/since must diff against the default `main` branch \
         (a real blast radius), not return an empty uncommitted-only result:\n{body}"
    );
    // Fix 6: with only a local `main` (no origin/main), the default resolves to
    // local `main` and discloses it; no staleness note is emitted.
    assert!(
        body.contains("base: main"),
        "default resolution must disclose the resolved base ref:\n{body}"
    );
    assert!(
        !body.contains("differs from origin/main"),
        "no origin/main → no staleness note:\n{body}"
    );
}

#[tokio::test]
async fn detect_impact_non_git_repo_clear_error() {
    let dir = tempfile::tempdir().expect("tempdir");
    fs::write(dir.path().join("lib.rs"), "pub fn core() {}\n").expect("write fixture file");
    let server = server_over(dir.path());

    let body = server
        .dispatch_tool_for_tests("detect_impact", json!({}))
        .await;

    assert!(
        body.contains("Git unavailable"),
        "expected a clear git-unavailable error, got:\n{body}"
    );
}

/// Fix 6: when local `main` lags `origin/main`, the DEFAULT resolution (no
/// base_branch/since) must diff against `origin/main` — the true delta — not the
/// stale local ref, and disclose the resolved ref + staleness.
#[tokio::test]
async fn detect_impact_default_prefers_origin_main_over_stale_local() {
    let dir = tempfile::tempdir().expect("tempdir");
    let root = dir.path();
    let fixture_src = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/cbm_impact");
    for rel in FIXTURE_FILES {
        let to = root.join(rel);
        if let Some(parent) = to.parent() {
            fs::create_dir_all(parent).unwrap_or_else(|e| panic!("mkdir for {rel}: {e}"));
        }
        fs::copy(fixture_src.join(rel), &to).unwrap_or_else(|e| panic!("copy {rel}: {e}"));
    }

    git(&["init"], root);
    git(&["config", "user.email", "test@test.com"], root);
    git(&["config", "user.name", "Test"], root);
    git(&["add", "."], root);
    git(&["commit", "-m", "C0 initial"], root);
    git(&["branch", "-M", "main"], root);

    // C1 changes src/b.rs — this is the "origin/main" state.
    fs::write(
        root.join("src/b.rs"),
        "pub fn call_b() -> u32 {\n    2\n}\n// C1: on origin/main only.\n",
    )
    .expect("rewrite src/b.rs");
    git(&["commit", "-am", "C1 change b"], root);
    // Record C1 as origin/main, THEN rewind local main to C0 (stale by 1 commit).
    git(&["update-ref", "refs/remotes/origin/main", "main"], root);
    git(&["checkout", "-b", "feature"], root);
    git(&["branch", "-f", "main", "HEAD~1"], root);

    // C2 changes src/a.rs on feature — the true delta vs origin/main (C1).
    fs::write(
        root.join("src/a.rs"),
        "use cbm_impact_fixture::core;\n\n\
         // C2: on feature only.\n\
         pub fn call_a() -> u32 {\n    core()\n}\n",
    )
    .expect("rewrite src/a.rs");
    git(&["commit", "-am", "C2 change a on feature"], root);

    let server = server_over(root);
    let body = server
        .dispatch_tool_for_tests("detect_impact", json!({}))
        .await;
    let payload = impact_payload(&body);

    // origin/main(C1)...HEAD(C2) = src/a.rs only. If it had used the stale local
    // main(C0) the diff would also include src/b.rs (C1) — the confidently-wrong
    // result this fix prevents.
    assert_eq!(
        payload["changed_files"],
        json!(["src/a.rs"]),
        "default must diff against origin/main (true delta), not stale local main:\n{body}"
    );
    assert!(
        body.contains("base: origin/main"),
        "must disclose the resolved base ref:\n{body}"
    );
    assert!(
        body.contains("local main is behind origin/main"),
        "must disclose direction-aware staleness (local behind) vs origin/main:\n{body}"
    );
}

/// Fix 1: a changed-set exceeding the per-list caps must bound every list at 200,
/// disclose the full totals + truncation in `pagination`, and keep `risk_summary`
/// counting the FULL blast set (not the truncated 200).
#[tokio::test]
async fn detect_impact_caps_large_changed_set() {
    let dir = tempfile::tempdir().expect("tempdir");
    let root = dir.path();
    fs::create_dir_all(root.join("src")).expect("mkdir src");
    fs::write(
        root.join("Cargo.toml"),
        "[package]\nname = \"caps_fixture\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
    )
    .expect("write Cargo.toml");

    // changed.rs: core() + 210 standalone pads => 211 changed symbols (> cap).
    let mut changed = String::from("pub fn core() -> u32 {\n    0\n}\n");
    for i in 0..210 {
        changed.push_str(&format!("pub fn pad_{i}() -> u32 {{\n    {i}\n}}\n"));
    }
    fs::write(root.join("src/changed.rs"), &changed).expect("write changed.rs");

    // callers.rs: 210 functions each calling core() => 210 blast nodes (> cap),
    // all hop 1 / risk High. Lives in an UNCHANGED file so the callers are not
    // themselves hop-0 changed symbols (which compute_impact excludes).
    let mut callers = String::new();
    for i in 0..210 {
        callers.push_str(&format!("pub fn caller_{i}() -> u32 {{\n    core()\n}}\n"));
    }
    fs::write(root.join("src/callers.rs"), &callers).expect("write callers.rs");

    git(&["init"], root);
    git(&["config", "user.email", "test@test.com"], root);
    git(&["config", "user.name", "Test"], root);
    git(&["add", "."], root);
    git(&["commit", "-m", "initial"], root);

    // Second commit touches ONLY changed.rs and modifies EVERY symbol's body
    // (not just a comment append), so all 211 symbols are genuine body-delta
    // seeds under the PART A (019) body-delta seed. `core` keeps its name (so
    // the 210 callers still resolve) but its body changes; each `pad_i` body is
    // bumped too.
    let mut changed = String::from("pub fn core() -> u32 {\n    1\n}\n");
    for i in 0..210 {
        changed.push_str(&format!("pub fn pad_{i}() -> u32 {{\n    {}\n}}\n", i + 1));
    }
    fs::write(root.join("src/changed.rs"), &changed).expect("rewrite changed.rs");
    git(&["commit", "-am", "touch changed"], root);

    let server = server_over(root);
    let body = server
        .dispatch_tool_for_tests("detect_impact", json!({ "since": "HEAD~1" }))
        .await;
    let payload = impact_payload(&body);

    // changed_files: exactly one, not truncated.
    assert_eq!(payload["changed_files"], json!(["src/changed.rs"]));
    assert_eq!(payload["pagination"]["changed_files"]["total"], json!(1));
    assert_eq!(
        payload["pagination"]["changed_files"]["truncated"],
        json!(false)
    );

    // changed_symbols: capped at 200, full total disclosed.
    assert_eq!(
        payload["changed_symbols"].as_array().expect("array").len(),
        200,
        "changed_symbols array must be capped at 200:\n{body}"
    );
    assert_eq!(
        payload["pagination"]["changed_symbols"]["total"],
        json!(211)
    );
    assert_eq!(
        payload["pagination"]["changed_symbols"]["returned"],
        json!(200)
    );
    assert_eq!(
        payload["pagination"]["changed_symbols"]["truncated"],
        json!(true)
    );

    // blast_radius: capped at 200, full total disclosed.
    assert_eq!(
        payload["blast_radius"].as_array().expect("array").len(),
        200,
        "blast_radius array must be capped at 200:\n{body}"
    );
    assert_eq!(payload["pagination"]["blast_radius"]["total"], json!(210));
    assert_eq!(
        payload["pagination"]["blast_radius"]["returned"],
        json!(200)
    );
    assert_eq!(
        payload["pagination"]["blast_radius"]["truncated"],
        json!(true)
    );

    // risk_summary counts the FULL blast set (210 high), NOT the truncated 200.
    assert_eq!(
        payload["risk_summary"]["high"],
        json!(210),
        "risk_summary must reflect the full blast set, not the capped list:\n{body}"
    );

    // Human summary discloses truncation with the house marker.
    assert!(
        body.contains("[truncated]"),
        "summary must disclose truncation:\n{body}"
    );
}

#[tokio::test]
async fn detect_impact_depth_cap_at_five() {
    let dir = bootstrap_fixture();
    let server = server_over(dir.path());

    let body = server
        .dispatch_tool_for_tests("detect_impact", json!({ "since": "HEAD~1", "depth": 99 }))
        .await;

    assert!(
        body.contains("depth clamped to 5 (requested 99)"),
        "expected a depth-cap warning, got:\n{body}"
    );
    let payload = impact_payload(&body);
    // The fixture's blast radius terminates at hop 1 regardless of depth, so
    // the clamp is exercised via the warning text above, not the payload shape.
    assert_eq!(payload["changed_files"], json!(["src/a.rs"]));
}

/// US1 (018) FR-001/FR-002 · SC-002: a real committed source edit plus a dirty
/// (untracked) non-source data file. Default `detect_impact` must source-focus
/// the changed-set — the data file and its JSON-key symbols must not seed the
/// impact walk — while `include_data=true` restores the prior inclusive result.
///
/// Fails on pre-fix code: the untracked `data/config.json` (merged via
/// `include_untracked=true`) lands in `changed_files` and its keys become
/// changed_symbols.
#[tokio::test]
async fn detect_impact_default_source_focuses_changed_set() {
    // bootstrap_fixture commits the Rust fixture, then edits src/a.rs in a
    // second commit (the HEAD~1..HEAD delta).
    let dir = bootstrap_fixture();
    let root = dir.path();
    // Dirty, untracked data file whose JSON keys the config extractor turns
    // into first-class symbols — the reported noise source.
    fs::create_dir_all(root.join("data")).expect("mkdir data");
    fs::write(
        root.join("data/config.json"),
        "{\n  \"alpha_key\": 1,\n  \"beta_key\": 2\n}\n",
    )
    .expect("write data file");

    let server = server_over(root);

    // Default: source-focused seed → data file excluded.
    let body = server
        .dispatch_tool_for_tests("detect_impact", json!({ "since": "HEAD~1" }))
        .await;
    let payload = impact_payload(&body);
    assert_eq!(
        payload["changed_files"],
        json!(["src/a.rs"]),
        "default detect_impact must source-focus the seed and drop untracked data files:\n{body}"
    );
    let changed_names: Vec<&str> = payload["changed_symbols"]
        .as_array()
        .expect("changed_symbols array")
        .iter()
        .map(|s| s["name"].as_str().expect("symbol name"))
        .collect();
    assert!(
        !changed_names
            .iter()
            .any(|n| n.contains("alpha_key") || n.contains("beta_key")),
        "no data-file-derived (JSON key) symbols may seed the impact walk: {changed_names:?}\n{body}"
    );

    // Opt-in: include_data=true restores full inclusion (FR-003).
    let body_incl = server
        .dispatch_tool_for_tests(
            "detect_impact",
            json!({ "since": "HEAD~1", "include_data": true }),
        )
        .await;
    let payload_incl = impact_payload(&body_incl);
    let incl_files: Vec<&str> = payload_incl["changed_files"]
        .as_array()
        .expect("changed_files array")
        .iter()
        .map(|f| f.as_str().expect("file path"))
        .collect();
    assert!(
        incl_files.contains(&"data/config.json"),
        "include_data=true must restore the untracked data file in the changed-set: {incl_files:?}\n{body_incl}"
    );
}