symforge 11.20.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
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
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
//! Feature 036 slice A2: no tool argument is silently ignored (specs/036-tool-reliability,
//! T016-T022, FR-001 to FR-004).
//!
//! Every test drives the production `tools/call` path through a real stdio server, so the
//! refusals under test are the ones a client sees. Every refusal carries an accepting
//! control in the same test: the same call without the bad argument is not refused.
#![cfg(feature = "server")]

mod reliability_support;

use std::io::{BufRead, BufReader, Write};
use std::path::Path;
use std::process::{Child, ChildStdin, Stdio};
use std::time::{Duration, Instant};

use serde_json::{Value, json};
use symforge::protocol::SymForgeServer;
use tempfile::TempDir;

const STATUS_KEY: &str = "symforge/result_status";
const NOTICE_KEY: &str = "symforge/repeat_notice";

struct StdioClient {
    child: Child,
    stdin: ChildStdin,
    stdout: BufReader<std::process::ChildStdout>,
    next_id: u64,
    _home: TempDir,
}

impl StdioClient {
    fn spawn(workspace: &Path) -> Self {
        let home = TempDir::new().expect("isolated symforge home");
        let mut child = symforge::process_util::hidden_command(env!("CARGO_BIN_EXE_symforge"))
            .current_dir(workspace)
            .env("RUST_LOG", "error")
            .env("SYMFORGE_NO_DAEMON", "1")
            .env("SYMFORGE_RECONCILE_INTERVAL", "0")
            .env("SYMFORGE_HOME", home.path())
            .env("SYMFORGE_SURFACE", "full")
            .env("SYMFORGE_WORKSPACE_ROOT", workspace)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .spawn()
            .expect("spawn symforge MCP server");
        let stdin = child.stdin.take().expect("child stdin");
        let stdout = BufReader::new(child.stdout.take().expect("child stdout"));
        let mut client = Self {
            child,
            stdin,
            stdout,
            next_id: 1,
            _home: home,
        };
        let id = client.send(
            "initialize",
            json!({
                "protocolVersion": "2025-06-18",
                "capabilities": {},
                "clientInfo": { "name": "reliability-contract", "version": "0.0.0" }
            }),
        );
        let _ = client.read_until_response(id);
        client.write_message(json!({
            "jsonrpc": "2.0",
            "method": "notifications/initialized",
            "params": {}
        }));
        client
    }

    fn send(&mut self, method: &str, params: Value) -> u64 {
        let id = self.next_id;
        self.next_id += 1;
        self.write_message(json!({
            "jsonrpc": "2.0", "id": id, "method": method, "params": params
        }));
        id
    }

    /// The full `tools/call` result JSON (content, `isError`, `_meta`).
    fn call(&mut self, name: &str, arguments: Value) -> Value {
        let id = self.send(
            "tools/call",
            json!({ "name": name, "arguments": arguments }),
        );
        let response = self.read_until_response(id);
        if let Some(error) = response.get("error") {
            panic!("tool {name} returned a JSON-RPC error instead of a result: {error}");
        }
        response.get("result").expect("tool result").clone()
    }

    fn write_message(&mut self, message: Value) {
        serde_json::to_writer(&mut self.stdin, &message).expect("write message");
        self.stdin.write_all(b"\n").expect("write newline");
        self.stdin.flush().expect("flush");
    }

    fn read_until_response(&mut self, expected_id: u64) -> Value {
        let started = Instant::now();
        loop {
            assert!(
                started.elapsed() < Duration::from_secs(90),
                "timed out waiting for response {expected_id}"
            );
            let mut line = String::new();
            let bytes = self.stdout.read_line(&mut line).expect("read line");
            assert_ne!(bytes, 0, "server closed stdout before responding");
            let message: Value = serde_json::from_str(line.trim())
                .unwrap_or_else(|e| panic!("invalid JSON-RPC line {line:?}: {e}"));
            if message.get("id").and_then(Value::as_u64) == Some(expected_id) {
                return message;
            }
        }
    }
}

impl Drop for StdioClient {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

fn text_of(result: &Value) -> String {
    result["content"]
        .as_array()
        .map(|blocks| {
            blocks
                .iter()
                .filter_map(|b| b.get("text").and_then(Value::as_str))
                .collect::<Vec<_>>()
                .join("\n")
        })
        .unwrap_or_default()
}

fn outcome_class(result: &Value) -> Option<&str> {
    result["_meta"][STATUS_KEY]["outcome_class"].as_str()
}

/// A bound server over a committed copy of the reliability fixture, indexed.
fn ready_server() -> (TempDir, StdioClient) {
    let dir = reliability_support::committed_fixture_copy();
    let root = dunce::canonicalize(dir.path()).expect("canonical fixture copy");
    let mut client = StdioClient::spawn(&root);
    let started = Instant::now();
    loop {
        let reply = client.call("search_symbols", json!({ "query": "target_fn" }));
        if text_of(&reply).contains("target_fn") {
            break;
        }
        assert!(
            started.elapsed() < Duration::from_secs(60),
            "index never served the fixture: {}",
            text_of(&reply)
        );
        std::thread::sleep(Duration::from_millis(250));
    }
    (dir, client)
}

fn evidence(result: &Value) -> &Value {
    &result["_meta"]["symforge/project_evidence"]
}

fn is_bound(evidence: &Value) -> bool {
    evidence.get("bound").is_none()
        && evidence["project_id"]
            .as_str()
            .is_some_and(|id| id != "unbound")
        && evidence["generation"].as_u64().is_some()
}

/// Wait until the index serves a bound, Ready generation whose evidence no longer moves
/// (the startup republish is over), so a repeat notice can be earned (tests/repeat_notice.rs).
fn stabilize(client: &mut StdioClient) {
    let started = Instant::now();
    loop {
        assert!(
            started.elapsed() < Duration::from_secs(40),
            "index never reached a stable bound Ready generation"
        );
        let health = client.call("health", json!({}));
        let ev = evidence(&health);
        let ready = is_bound(ev)
            && ev["index_state"] == json!("Ready")
            && text_of(&health).contains("Watcher: active");
        if ready {
            let a = evidence(&client.call("status", json!({}))).clone();
            std::thread::sleep(Duration::from_millis(500));
            let b = evidence(&client.call("status", json!({}))).clone();
            let x = client.call("search_symbols", json!({ "query": "short_a" }));
            let y = client.call("search_symbols", json!({ "query": "leaf" }));
            if a == b && is_bound(&a) && evidence(&x) == evidence(&y) && evidence(&x) == &a {
                return;
            }
        }
        std::thread::sleep(Duration::from_millis(250));
    }
}

/// `invalid_request` refusal that names `key`, the tool, and lists valid arguments.
fn assert_unknown_argument_refusal(result: &Value, tool: &str, key: &str, valid_sample: &str) {
    let text = text_of(result);
    assert_eq!(
        result["isError"],
        json!(true),
        "{tool}: not an error: {text}"
    );
    assert_eq!(
        outcome_class(result),
        Some("invalid_request"),
        "{tool}: wrong outcome class: {result}"
    );
    assert!(
        text.starts_with("invalid_request: "),
        "{tool}: refusal text form: {text}"
    );
    assert!(
        result["_meta"].get("symforge/project_evidence").is_some(),
        "{tool}: a refusal names the project like every other result: {result}"
    );
    assert!(
        text.contains(&format!("{tool} does not accept")) && text.contains(key),
        "{tool}: refusal must name the tool and `{key}`: {text}"
    );
    assert!(
        text.contains("Valid arguments:") && text.contains(valid_sample),
        "{tool}: refusal must list valid arguments including `{valid_sample}`: {text}"
    );
}

fn assert_not_refused(result: &Value, label: &str) {
    let text = text_of(result);
    assert!(
        !text.contains("does not accept") && outcome_class(result) != Some("invalid_request"),
        "{label}: an accepted call was refused: {text}"
    );
}

/// Resolve `{placeholder}` string values of a typical call; reports whether any existed.
fn fill_placeholders(value: &mut Value, root: &str) -> bool {
    match value {
        Value::String(s) if s.starts_with('{') && s.ends_with('}') => {
            *s = if s == "{root}" {
                root.to_string()
            } else {
                "x".to_string()
            };
            true
        }
        Value::Array(items) => items
            .iter_mut()
            .fold(false, |any, v| fill_placeholders(v, root) | any),
        Value::Object(map) => map
            .values_mut()
            .fold(false, |any, v| fill_placeholders(v, root) | any),
        _ => false,
    }
}

#[test]
fn every_registered_tool_refuses_an_unknown_argument_and_accepts_the_control() {
    let (dir, mut client) = ready_server();
    let root = dunce::canonicalize(dir.path()).expect("root");
    let root = root.to_string_lossy().into_owned();
    let mut calls = SymForgeServer::typical_calls_for_tests();
    // Calls that rebind or rewrite server state go last so earlier controls see one index.
    calls.sort_by_key(|(tool, _)| matches!(*tool, "index_folder" | "checkpoint_now"));
    assert!(
        calls.len() >= 41,
        "contract table lost tools: {}",
        calls.len()
    );
    for (tool, typical) in calls {
        let mut args: Value = serde_json::from_str(typical).expect("typical call is JSON");
        let placeholders = fill_placeholders(&mut args, &root);

        // A placeholder stands for an earlier call's output, so such a control may be
        // invalid for its own reasons; it must still not be refused for its arguments.
        // The `symforge` facade answers invalid_request on the full surface by design.
        let control = client.call(tool, args.clone());
        if placeholders || tool == "symforge" {
            assert!(
                !text_of(&control).contains("does not accept"),
                "{tool}: control refused for its arguments: {}",
                text_of(&control)
            );
        } else {
            assert_not_refused(&control, &format!("{tool} control"));
        }

        let mut bad = args.clone();
        bad.as_object_mut()
            .expect("typical call is an object")
            .insert("zz_unknown".to_string(), json!(1));
        let refused = client.call(tool, bad);
        let valid_sample = args
            .as_object()
            .and_then(|o| o.keys().next().cloned())
            .unwrap_or_else(|| "Valid arguments:".to_string());
        assert_unknown_argument_refusal(&refused, tool, "zz_unknown", &valid_sample);
    }
}

#[test]
fn a_nested_unknown_key_is_refused_and_the_clean_call_succeeds() {
    let (_dir, mut client) = ready_server();

    let edit = json!({
        "edits": [{
            "path": "src/short.rs", "name": "SHORT_A",
            "operation": { "type": "replace", "new_body": "pub const SHORT_A: u32 = 1;" }
        }],
        "dry_run": true
    });
    let control = client.call("batch_edit", edit.clone());
    assert_not_refused(&control, "batch_edit control");
    assert_eq!(control["isError"], json!(false), "{}", text_of(&control));
    let mut bad = edit;
    bad["edits"][0]["zz_unknown"] = json!(1);
    let refused = client.call("batch_edit", bad);
    assert_unknown_argument_refusal(&refused, "batch_edit", "zz_unknown", "edits");
    assert!(
        text_of(&refused).contains("edits"),
        "nested refusal must locate the key: {}",
        text_of(&refused)
    );

    let targets = json!({ "targets": [{ "path": "src/long.rs", "name": "long_body" }] });
    let control = client.call("get_symbol", targets.clone());
    assert_not_refused(&control, "get_symbol control");
    assert_eq!(control["isError"], json!(false), "{}", text_of(&control));
    let mut bad = targets;
    bad["targets"][0]["zz_unknown"] = json!(1);
    let refused = client.call("get_symbol", bad);
    assert_unknown_argument_refusal(&refused, "get_symbol", "zz_unknown", "targets");
}

#[test]
fn serde_aliases_are_accepted() {
    let (_dir, mut client) = ready_server();
    // `symbol` is an alias of `name`, `body` of `new_body` (src/protocol/edit.rs).
    let by_alias = client.call(
        "replace_symbol_body",
        json!({
            "path": "src/short.rs", "symbol": "SHORT_A",
            "body": "pub const SHORT_A: u32 = 1;", "dry_run": true
        }),
    );
    assert_not_refused(&by_alias, "replace_symbol_body via aliases");
    assert_eq!(by_alias["isError"], json!(false), "{}", text_of(&by_alias));
    let canonical = client.call(
        "replace_symbol_body",
        json!({
            "path": "src/short.rs", "name": "SHORT_A",
            "new_body": "pub const SHORT_A: u32 = 1;", "dry_run": true
        }),
    );
    assert_eq!(text_of(&by_alias), text_of(&canonical));
    // The facade edit tool uses `symbol` and `body` as its own names.
    let facade = client.call(
        "symforge_edit",
        json!({
            "path": "src/short.rs", "symbol": "SHORT_A", "op": "replace",
            "body": "pub const SHORT_A: u32 = 1;"
        }),
    );
    assert_not_refused(&facade, "symforge_edit");
}

#[test]
fn an_argument_the_handler_ignores_is_refused_naming_its_mode() {
    let (_dir, mut client) = ready_server();

    // detail="full" never reads `depth` (tools.rs get_repo_map full branch).
    let refused = client.call("get_repo_map", json!({ "detail": "full", "depth": 1 }));
    let text = text_of(&refused);
    assert_eq!(outcome_class(&refused), Some("invalid_request"), "{text}");
    assert!(
        text.contains("\"depth\"") && text.contains("detail") && text.contains("\"full\""),
        "must name depth, detail and the mode where it is ignored: {text}"
    );
    let control = client.call("get_repo_map", json!({ "detail": "tree", "depth": 1 }));
    assert_not_refused(&control, "get_repo_map tree+depth");

    // A batch `targets` call never reads the top-level name.
    let refused = client.call(
        "get_symbol",
        json!({ "targets": [{ "path": "src/long.rs", "name": "long_body" }], "name": "x" }),
    );
    assert_eq!(outcome_class(&refused), Some("invalid_request"));
    assert!(text_of(&refused).contains("targets"));
    let control = client.call(
        "get_symbol",
        json!({ "targets": [{ "path": "src/long.rs", "name": "long_body" }] }),
    );
    assert_not_refused(&control, "get_symbol targets");
}

#[test]
fn an_empty_sections_list_keeps_its_published_meaning() {
    let (_dir, mut client) = ready_server();
    let with_path = client.call(
        "get_symbol_context",
        json!({ "name": "target_fn", "path": "src/parent/leaf.rs", "sections": [] }),
    );
    assert_not_refused(&with_path, "sections=[] with path");
    assert_eq!(
        with_path["isError"],
        json!(false),
        "{}",
        text_of(&with_path)
    );
    let all = client.call(
        "get_symbol_context",
        json!({ "name": "target_fn", "path": "src/parent/leaf.rs",
                "sections": ["dependents", "siblings", "implementations", "git", "knowledge"] }),
    );
    assert!(
        text_of(&with_path).contains("Callers") || text_of(&all).contains("Callers"),
        "trace mode must name callers: {}",
        text_of(&with_path)
    );

    // Without a path the call is refused as an invalid request that names the argument
    // that is missing AND the mode that needs it, not as an unknown argument.
    let refused = client.call(
        "get_symbol_context",
        json!({ "name": "target_fn", "sections": [] }),
    );
    let text = text_of(&refused);
    assert_eq!(outcome_class(&refused), Some("invalid_request"), "{text}");
    assert!(
        text.contains("path") && text.contains("sections") && text.contains("trace"),
        "must name path, sections and the trace mode: {text}"
    );
    assert!(!text.contains("does not accept"), "{text}");
}

#[test]
fn a_refused_call_does_not_advance_the_repeat_notice_counter() {
    let (_dir, mut client) = ready_server();
    stabilize(&mut client);
    let notice = |result: &Value| result["_meta"].get(NOTICE_KEY).cloned();

    // Control: three plain identical clean calls DO carry the notice, so the absence
    // asserted below is meaningful.
    let control = json!({ "query": "long_body" });
    assert!(notice(&client.call("search_symbols", control.clone())).is_none());
    assert!(notice(&client.call("search_symbols", control.clone())).is_none());
    let third = client.call("search_symbols", control);
    assert_eq!(
        notice(&third).map(|n| n["repeat_count"].clone()),
        Some(json!(3)),
        "control: the third identical clean call must carry the notice: {third}"
    );

    // Two clean calls, a refused call with the same tool and otherwise identical
    // arguments, then the third clean call: the notice appears exactly when it would
    // without the refused call.
    // A query nothing else in this test (or `ready_server`/`stabilize`) has served.
    let good = json!({ "query": "SHORT_C" });
    let bad = json!({ "query": "SHORT_C", "zz_unknown": 1 });
    assert!(notice(&client.call("search_symbols", good.clone())).is_none());
    assert!(notice(&client.call("search_symbols", good.clone())).is_none());
    let refused = client.call("search_symbols", bad.clone());
    assert_unknown_argument_refusal(&refused, "search_symbols", "zz_unknown", "query");
    assert!(notice(&refused).is_none());
    let third = client.call("search_symbols", good);
    assert_eq!(
        notice(&third).map(|n| n["repeat_count"].clone()),
        Some(json!(3)),
        "the refused call must not have disturbed the run: {third}"
    );

    // Repeated refusals never count toward a notice of their own: before the check,
    // the unknown key was ignored and the third identical serve carried one.
    for n in 1..=4 {
        let refused = client.call("search_symbols", bad.clone());
        assert_unknown_argument_refusal(&refused, "search_symbols", "zz_unknown", "query");
        assert!(notice(&refused).is_none(), "refusal {n} carries a notice");
    }
}

fn assert_no_mode_refusal(result: &Value, label: &str) {
    let text = text_of(result);
    assert!(
        !text.contains("applies when")
            && !text.contains("does not apply when")
            && !text.contains("does not accept"),
        "{label}: a valid call was refused: {text}"
    );
}

#[test]
fn calls_the_handlers_read_are_not_refused() {
    let (_dir, mut client) = ready_server();
    // Each of these is read by its handler (or decodes to a valid call): a refusal here is
    // a false refusal. The "0"/"1" strings are lenient booleans and "" is absent (FR-003).
    for (tool, args) in [
        (
            "edit_within_symbol",
            json!({ "path": "src/user.rs", "name": "use_it", "old_text": "target_fn(7)",
                    "new_text": "target_fn(8)", "dry_run": true,
                    "replace_all": "0", "occurrence": 2 }),
        ),
        (
            "edit_within_symbol",
            json!({ "path": "src/user.rs", "name": "use_it", "old_text": "target_fn(7)",
                    "new_text": "target_fn(8)", "dry_run": true,
                    "replace_all": true, "occurrence": 1 }),
        ),
        (
            "search_text",
            json!({ "query": "LONG_FIRST", "follow_refs": "1", "follow_refs_limit": 5 }),
        ),
        (
            "search_text",
            json!({ "query": "LONG_FIRST", "regex": true, "whole_word": true }),
        ),
        (
            "get_symbol_context",
            json!({ "name": "target_fn", "bundle": "0", "file": "src/parent/leaf.rs" }),
        ),
        (
            "get_symbol_context",
            json!({ "name": "target_fn", "path": "src/parent/leaf.rs", "bundle": true,
                    "file": "src/parent/leaf.rs" }),
        ),
        (
            "find_references",
            json!({ "name": "target_fn", "mode": "", "kind": "call" }),
        ),
        (
            "find_references",
            json!({ "name": "target_fn", "mode": "references", "kind": "call" }),
        ),
        (
            "find_references",
            json!({ "name": "target_fn", "mode": "implementations",
                    "path": "src/parent/leaf.rs", "direction": "auto" }),
        ),
        ("get_repo_map", json!({ "detail": "", "depth": 1 })),
        ("get_repo_map", json!({ "detail": "compact", "depth": 3 })),
        ("get_repo_map", json!({ "detail": "tree", "depth": 3 })),
        ("get_repo_map", json!({ "max_files": 50, "depth": 3 })),
        (
            "get_symbol",
            json!({ "targets": [], "name": "long_body", "path": "src/long.rs" }),
        ),
        (
            "review_knowledge",
            json!({ "mode": "summary", "path": "docs/notes.md" }),
        ),
        (
            "review_knowledge",
            json!({ "mode": "remediation", "path": "docs/notes.md" }),
        ),
        (
            "what_changed",
            json!({ "since": 1, "uncommitted": true, "include_symbol_diff": true }),
        ),
        (
            "detect_impact",
            json!({ "base_branch": "main", "since": "HEAD" }),
        ),
        (
            "analyze_file_impact",
            json!({ "path": "src/parent/leaf.rs", "co_changes_limit": 3 }),
        ),
        (
            "search_files",
            json!({ "query": "leaf", "anchor_path": "src/parent/leaf.rs" }),
        ),
    ] {
        let reply = client.call(tool, args.clone());
        assert_no_mode_refusal(&reply, &format!("{tool} {args}"));
        // No server-chosen mode, so no note.
        assert!(!text_of(&reply).contains("\n\nMode: `"), "{tool}");
    }
}

#[test]
fn stringified_arrays_and_elements_are_checked_like_native_ones() {
    let (_dir, mut client) = ready_server();
    let edit = json!({
        "path": "src/short.rs", "name": "SHORT_A",
        "operation": { "type": "replace", "new_body": "pub const SHORT_A: u32 = 1;" }
    });
    let mut bad = edit.clone();
    bad["zz"] = json!(1);
    let shorthand = "src/short.rs::SHORT_A => replace pub const SHORT_A: u32 = 1;";

    // Every valid shape stays accepted.
    for (label, edits) in [
        ("native", json!([edit])),
        ("stringified array", json!(json!([edit]).to_string())),
        ("stringified element", json!([edit.to_string()])),
        ("shorthand element", json!([shorthand])),
    ] {
        let reply = client.call("batch_edit", json!({ "edits": edits, "dry_run": true }));
        assert_not_refused(&reply, label);
        assert_eq!(
            reply["isError"],
            json!(false),
            "{label}: {}",
            text_of(&reply)
        );
    }
    // Every invalid shape is refused, naming the key.
    for (label, edits) in [
        ("native", json!([bad])),
        ("stringified array", json!(json!([bad]).to_string())),
        ("stringified element", json!([bad.to_string()])),
    ] {
        let refused = client.call("batch_edit", json!({ "edits": edits, "dry_run": true }));
        assert_unknown_argument_refusal(&refused, "batch_edit", "zz", "edits");
        assert!(
            text_of(&refused).contains("edits.0.zz"),
            "{label}: must locate the key: {}",
            text_of(&refused)
        );
    }
    // A key inside the operation is located too.
    let mut bad_operation = edit.clone();
    bad_operation["operation"]["zz"] = json!(1);
    let refused = client.call(
        "batch_edit",
        json!({ "edits": [bad_operation], "dry_run": true }),
    );
    assert_unknown_argument_refusal(&refused, "batch_edit", "zz", "edits");
    assert!(
        text_of(&refused).contains("edits.0.operation.zz"),
        "{}",
        text_of(&refused)
    );

    // batch_insert targets, stringified.
    let target = json!({ "path": "src/short.rs", "name": "SHORT_A" });
    let mut bad_target = target.clone();
    bad_target["zz"] = json!(1);
    let insert = |targets: Value| json!({ "content": "// x", "position": "before", "targets": targets, "dry_run": true });
    let ok = client.call("batch_insert", insert(json!(json!([target]).to_string())));
    assert_not_refused(&ok, "batch_insert stringified");
    assert_eq!(ok["isError"], json!(false), "{}", text_of(&ok));
    let refused = client.call(
        "batch_insert",
        insert(json!(json!([bad_target]).to_string())),
    );
    assert_unknown_argument_refusal(&refused, "batch_insert", "zz", "targets");
}

#[test]
fn nested_unknown_fields_keep_their_path_and_hint() {
    let (_dir, mut client) = ready_server();
    let refused = client.call(
        "get_symbol",
        json!({ "targets": [{ "path": "src/long.rs", "name": "long_body", "zz": 1 }] }),
    );
    assert_unknown_argument_refusal(&refused, "get_symbol", "zz", "targets");
    let text = text_of(&refused);
    assert!(text.contains("\"targets.0.zz\""), "{text}");
    assert!(text.contains("Check the fields of \"targets\""), "{text}");
}

#[test]
fn the_probe_relay_applies_the_same_check() {
    let (_dir, mut client) = ready_server();
    let relay = |args: Value| json!({ "query": "x", "_probe_legacy_tool": "search_symbols", "_probe_legacy_args": args });
    let ok = client.call("symforge", relay(json!({ "query": "target_fn" })));
    assert!(text_of(&ok).contains("target_fn"), "{}", text_of(&ok));
    let refused = client.call(
        "symforge",
        relay(json!({ "query": "target_fn", "zz_unknown": 1 })),
    );
    assert_unknown_argument_refusal(&refused, "search_symbols", "zz_unknown", "query");
}

#[test]
fn a_mode_refusal_never_echoes_an_argument_value() {
    let (_dir, mut client) = ready_server();
    let value = "SENSITIVE_VALUE_".repeat(10);
    let refused = client.call("get_repo_map", json!({ "detail": "full", "depth": value }));
    let text = text_of(&refused);
    assert_eq!(outcome_class(&refused), Some("invalid_request"), "{text}");
    assert!(!text.contains("SENSITIVE_VALUE"), "value echoed: {text}");
    let refused = client.call(
        "get_symbol",
        json!({ "targets": [{ "path": "src/long.rs", "name": "long_body" }], "name": value }),
    );
    assert!(
        !text_of(&refused).contains("SENSITIVE_VALUE"),
        "{}",
        text_of(&refused)
    );
    // An over-long unknown KEY is cut, and its value is never echoed.
    let long_key = "k".repeat(300);
    let refused = client.call(
        "search_symbols",
        json!({ "query": "x", (long_key.clone()): value }),
    );
    let text = text_of(&refused);
    assert!(
        !text.contains(&"k".repeat(60)) && !text.contains("SENSITIVE_VALUE"),
        "{text}"
    );
}

/// Spec 036 argument values: a value outside an argument's set or range is refused as an
/// invalid request that names the argument and lists what it accepts, and the same call
/// with a valid value is answered.
#[test]
fn an_out_of_set_value_is_refused_and_a_valid_one_is_answered() {
    let (_dir, mut client) = ready_server();
    let cases: Vec<(&str, Value, &str, Value)> = vec![
        (
            "find_references",
            json!({ "name": "target_fn", "kind": "bogus" }),
            "Valid values: \"call\", \"import\", \"type_usage\", \"macro_use\", \"value_use\", \"all\".",
            json!({ "name": "target_fn", "kind": "call" }),
        ),
        (
            "find_references",
            json!({ "name": "" }),
            "requires a non-empty \"name\"",
            json!({ "name": "target_fn" }),
        ),
        (
            "find_references",
            json!({ "name": "target_fn", "limit": 0 }),
            "\"limit\" = 0. Valid range: 1 or greater.",
            json!({ "name": "target_fn", "limit": 1 }),
        ),
        (
            "find_dependents",
            json!({ "path": "src/parent/leaf.rs", "format": "bogus" }),
            "Valid values: \"text\", \"mermaid\", \"dot\".",
            json!({ "path": "src/parent/leaf.rs", "format": "dot" }),
        ),
        (
            "get_symbol_context",
            json!({ "name": "target_fn", "path": "src/parent/leaf.rs", "verbosity": "bogus" }),
            "\"verbosity\". Valid values: \"full\", \"summary\", \"signature\", \"compact\".",
            json!({ "name": "target_fn", "path": "src/parent/leaf.rs", "verbosity": "summary" }),
        ),
        (
            "get_symbol_context",
            json!({ "name": "target_fn", "path": "src/parent/leaf.rs", "sections": ["bogus"] }),
            "\"sections.0\"",
            json!({ "name": "target_fn", "path": "src/parent/leaf.rs", "sections": ["git"] }),
        ),
        (
            "search_symbols",
            json!({ "query": "target", "kind": "bogus" }),
            "\"kind\". Valid values: \"all\", \"fn\"",
            json!({ "query": "target", "kind": "FN" }),
        ),
        (
            "search_text",
            json!({ "query": "target_fn", "group_by": "bogus" }),
            "\"group_by\". Valid values: \"file\", \"symbol\", \"usage\", \"purpose\", \"names\", \"count\".",
            json!({ "query": "target_fn", "group_by": "count" }),
        ),
        (
            "get_file_content",
            json!({ "path": "src/short.rs", "mode": "bogus" }),
            "\"mode\". Valid values: \"lines\", \"symbol\", \"match\", \"chunk\".",
            json!({ "path": "src/short.rs", "mode": "lines", "start_line": 1, "end_line": 2 }),
        ),
        (
            "get_file_context",
            json!({ "path": "src/short.rs", "max_tokens": 0 }),
            "\"max_tokens\" = 0. Valid range: 1 or greater.",
            json!({ "path": "src/short.rs", "max_tokens": 500 }),
        ),
        (
            "get_repo_map",
            json!({ "detail": "bogus" }),
            "Valid values: \"compact\", \"full\", \"tree\".",
            json!({ "detail": "tree" }),
        ),
        (
            "explore",
            json!({ "query": "target", "depth": 0 }),
            "\"depth\" = 0. Valid range: 1 to 3.",
            json!({ "query": "target", "depth": 3 }),
        ),
        (
            "edit_within_symbol",
            json!({ "path": "src/user.rs", "name": "use_it", "old_text": "target_fn(7)",
                    "new_text": "target_fn(8)", "near_line": 0, "dry_run": true }),
            "\"near_line\" = 0",
            json!({ "path": "src/user.rs", "name": "use_it", "old_text": "target_fn(7)",
                    "new_text": "target_fn(8)", "near_line": 1, "dry_run": true }),
        ),
        (
            "replace_symbol_body",
            json!({ "path": "src/short.rs", "name": "SHORT_A", "kind": "bogus",
                    "new_body": "pub const SHORT_A: u32 = 1;", "dry_run": true }),
            "\"kind\"",
            json!({ "path": "src/short.rs", "name": "SHORT_A", "kind": "const",
                    "new_body": "pub const SHORT_A: u32 = 1;", "dry_run": true }),
        ),
        (
            "batch_edit",
            json!({ "edits": [{ "path": "src/short.rs", "name": "SHORT_A", "symbol_line": 0,
                    "operation": { "type": "replace", "new_body": "pub const SHORT_A: u32 = 1;" } }],
                    "dry_run": true }),
            "\"edits.0.symbol_line\" = 0",
            json!({ "edits": [{ "path": "src/short.rs", "name": "SHORT_A", "symbol_line": 2,
                    "operation": { "type": "replace", "new_body": "pub const SHORT_A: u32 = 1;" } }],
                    "dry_run": true }),
        ),
    ];
    for (tool, bad, names, good) in cases {
        let refused = client.call(tool, bad.clone());
        let text = text_of(&refused);
        assert_eq!(refused["isError"], json!(true), "{tool} {bad}: {text}");
        assert_eq!(
            outcome_class(&refused),
            Some("invalid_request"),
            "{tool} {bad}: {text}"
        );
        assert!(
            text.starts_with(&format!("invalid_request: {tool} ")) && text.contains(names),
            "{tool} {bad}: expected `{names}` in {text}"
        );
        assert!(
            !text.contains("bogus"),
            "{tool}: a string value is never echoed: {text}"
        );
        let answered = client.call(tool, good.clone());
        assert_not_refused(&answered, &format!("{tool} {good}"));
    }
}

/// Spec 036 argument values, review round: a described cap clamps and says so; section
/// names and symbol kinds are matched as the table accepts them; an argument the selected
/// mode ignores is not judged; a padded number is the decoder's to refuse.
#[test]
fn capped_values_are_named_and_accepted_values_reach_the_handler() {
    let (_dir, mut client) = ready_server();
    for (tool, args, note) in [
        (
            "find_references",
            json!({ "name": "target_fn", "limit": 500 }),
            "Note: \"limit\" = 500 is above its maximum of 100; 100 was used.",
        ),
        (
            "get_repo_map",
            json!({ "detail": "tree", "depth": 8 }),
            "Note: \"depth\" = 8 is above its maximum of 5; 5 was used.",
        ),
        (
            "search_knowledge",
            json!({ "query": "zebrafish_quorum", "limit": 200 }),
            "Note: \"limit\" = 200 is above its maximum of 100; 100 was used.",
        ),
    ] {
        let text = text_of(&client.call(tool, args.clone()));
        assert!(text.ends_with(note), "{tool} {args}: {text}");
    }
    // A section named in another letter case is served, knowledge included, with no
    // unknown-section warning (the handlers see it lowercased).
    for sections in [
        json!(["Outline", "KNOWLEDGE"]),
        json!(["outline", "knowledge"]),
    ] {
        let text = text_of(&client.call(
            "get_file_context",
            json!({ "path": "src/short.rs", "sections": sections.clone(), "force_refresh": true }),
        ));
        assert!(
            text.contains("Knowledge evidence") && !text.contains("unknown section"),
            "{sections}: {text}"
        );
    }
    for kind in ["function", "all", "FN"] {
        let text = text_of(&client.call(
            "get_symbol",
            json!({ "path": "src/long.rs", "name": "long_body", "kind": kind }),
        ));
        assert!(
            text.contains("long_body") && !text.starts_with("No symbol"),
            "{kind}: {text}"
        );
    }
    let count = client.call(
        "search_text",
        json!({ "query": "LONG_FIRST", "group_by": "count", "limit": 0 }),
    );
    assert_not_refused(&count, "group_by=count ignores limit");
    let padded = text_of(&client.call(
        "get_file_content",
        json!({ "path": "src/short.rs", "start_line": " 0" }),
    ));
    assert!(
        !padded.contains("Valid range"),
        "the decoder judges a padded number: {padded}"
    );
}

/// Spec 036 delta: a cap note keeps the output's grammar, never follows an error, and is
/// paid for inside the caller's token budget.
#[test]
fn a_cap_note_keeps_the_output_grammar_and_the_budget() {
    let (_dir, mut client) = ready_server();
    let review = text_of(&client.call(
        "review_knowledge",
        json!({ "mode": "summary", "limit": 500 }),
    ));
    assert!(
        review.contains("note=capped argument=limit requested=500 used=100"),
        "{review}"
    );
    // Every line carries key=value fields (the first after a "Review knowledge |" title),
    // and the note is one more such line, last.
    for line in review.lines().filter(|line| !line.trim().is_empty()) {
        assert!(
            line.contains('='),
            "review_knowledge line without key=value: {line:?}"
        );
    }
    assert!(
        review
            .trim_end()
            .ends_with("note=capped argument=limit requested=500 used=100"),
        "{review}"
    );
    let dot = text_of(&client.call(
        "find_dependents",
        json!({ "path": "src/parent/leaf.rs", "format": "dot", "limit": 500 }),
    ));
    let close = dot.rfind('}').expect("dot graph");
    assert!(
        dot[close + 1..]
            .lines()
            .all(|line| line.trim().is_empty() || line.trim_start().starts_with("//")),
        "dot has text after the graph: {dot}"
    );
    assert!(
        dot[close + 1..].contains("// Note: \"limit\" = 500"),
        "{dot}"
    );
    let mermaid = text_of(&client.call(
        "find_dependents",
        json!({ "path": "src/parent/leaf.rs", "format": "mermaid", "limit": 500 }),
    ));
    let last = mermaid
        .lines()
        .rev()
        .find(|line| !line.trim().is_empty())
        .unwrap_or_default();
    assert!(last.starts_with("%% Note: \"limit\" = 500"), "{mermaid}");
    let failed = text_of(&client.call(
        "search_symbols",
        json!({ "query": "x", "limit": 4294967296u64 }),
    ));
    assert!(
        !failed.contains("was used"),
        "a failed call claims a used value: {failed}"
    );
    let budget = 60u64;
    let capped = text_of(&client.call(
        "find_references",
        json!({ "name": "target_fn", "limit": 500, "max_tokens": budget }),
    ));
    assert!(capped.contains("was used"), "{capped}");
    // The same call at the cap: the note was paid for inside the budget, so the capped
    // answer is not the uncapped one plus the note.
    let plain = text_of(&client.call(
        "find_references",
        json!({ "name": "target_fn", "limit": 100, "max_tokens": budget }),
    ));
    let note = capped
        .rsplit(
            "

",
        )
        .next()
        .unwrap_or_default();
    assert!(
        capped.len() < plain.len() + note.len() + 2,
        "the note overran the budget: {} bytes with it, {} without",
        capped.len(),
        plain.len()
    );
}

/// A value list of the shared argument-value table
/// (`src/index_lifecycle/guidance/argument_values.rs`), read from its source so a drift
/// test checks the table itself, not a copy of it.
fn table_values(name: &str) -> Vec<String> {
    let path = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/src/index_lifecycle/guidance/argument_values.rs"
    );
    let source = std::fs::read_to_string(path).expect("argument_values.rs");
    let start = source
        .find(&format!("const {name}: &[&str] = &["))
        .unwrap_or_else(|| panic!("{name} is not in the table"));
    let list = &source[start..];
    let list = &list[..list.find("];").expect("list end")];
    let values: Vec<String> = list
        .split('"')
        .skip(1)
        .step_by(2)
        .map(String::from)
        .collect();
    assert!(!values.is_empty(), "{name} is empty");
    values
}

/// Spec 036 drift pins: every accepted value of a closed-set argument reaches its own
/// handler branch (distinct answers), so the table cannot list a name the handler drops
/// to its default, and the handler cannot grow a name the table refuses.
#[test]
fn every_accepted_value_reaches_its_own_handler_branch() {
    let (_dir, mut client) = ready_server();
    // Each value's answer differs from the answer without the argument (the default),
    // except the default value itself, which must equal it.
    let distinct = |client: &mut StdioClient,
                    tool: &str,
                    base: Value,
                    argument: &str,
                    values: &[&str]| {
        let default = text_of(&client.call(tool, base.clone()));
        for (index, value) in values.iter().enumerate() {
            let mut args = base.clone();
            args[argument] = json!(value);
            let text = text_of(&client.call(tool, args));
            assert!(
                !text.starts_with("invalid_request"),
                "{tool} {argument}={value}: {text}"
            );
            assert_eq!(
                index == 0,
                text == default,
                "{tool} {argument}={value}: the first value is the default, every other one must change the answer"
            );
        }
    };
    let leaf = json!({ "name": "target_fn", "path": "src/parent/leaf.rs" });
    distinct(
        &mut client,
        "get_symbol_context",
        leaf.clone(),
        "verbosity",
        &table_values("VERBOSITIES")
            .iter()
            .map(String::as_str)
            .collect::<Vec<_>>(),
    );
    distinct(
        &mut client,
        "get_repo_map",
        json!({}),
        "detail",
        &table_values("REPO_MAP_DETAILS")
            .iter()
            .map(String::as_str)
            .collect::<Vec<_>>(),
    );
    distinct(
        &mut client,
        "find_dependents",
        json!({ "path": "src/parent/leaf.rs" }),
        "format",
        &table_values("DEPENDENT_FORMATS")
            .iter()
            .map(String::as_str)
            .collect::<Vec<_>>(),
    );
    distinct(
        &mut client,
        "find_references",
        json!({ "name": "target_fn" }),
        "mode",
        &table_values("REFERENCE_MODES")
            .iter()
            .map(String::as_str)
            .collect::<Vec<_>>(),
    );
    // The fixture has no trait, so every direction answers alike; each is accepted.
    for direction in table_values("REFERENCE_DIRECTIONS") {
        assert_not_refused(
            &client.call(
                "find_references",
                json!({ "name": "target_fn", "mode": "implementations", "direction": direction }),
            ),
            &direction,
        );
    }
    let sections = |client: &mut StdioClient, tool: &str, base: Value, values: &[&str]| {
        let all = text_of(&client.call(tool, base.clone()));
        for value in values {
            let mut args = base.clone();
            args["sections"] = json!([value]);
            let text = text_of(&client.call(tool, args));
            assert!(
                !text.starts_with("invalid_request"),
                "{tool} {value}: {text}"
            );
            assert_ne!(
                text, all,
                "{tool} sections=[{value}] must narrow the answer"
            );
        }
    };
    sections(
        &mut client,
        "get_file_context",
        json!({ "path": "src/parent/leaf.rs" }),
        &table_values("FILE_CONTEXT_SECTIONS")
            .iter()
            .map(String::as_str)
            .collect::<Vec<_>>(),
    );
    sections(
        &mut client,
        "get_symbol_context",
        leaf,
        &table_values("SYMBOL_CONTEXT_SECTIONS")
            .iter()
            .map(String::as_str)
            .collect::<Vec<_>>(),
    );
}