symforge 8.22.8

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
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
//! Gate I public-contract coverage for `search_knowledge`.

#![cfg(feature = "server")]

use std::fs;
use std::sync::Arc;

use parking_lot::Mutex;
use serde_json::json;
use symforge::live_index::LiveIndex;
use symforge::protocol::SymForgeServer;
use symforge::watcher::WatcherInfo;
use tempfile::TempDir;

struct KnowledgeFixture {
    _dir: TempDir,
    server: SymForgeServer,
}

impl KnowledgeFixture {
    fn new() -> Self {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path().to_path_buf();
        fs::create_dir_all(root.join("docs")).expect("docs dir");
        fs::write(
            root.join("docs/recovery.md"),
            "# Recovery\n## Persistence boundaries\nShutdown is not a safe persistence boundary.\n",
        )
        .expect("recovery fixture");
        fs::create_dir_all(root.join("docs/design")).expect("design dir");
        fs::write(
            root.join("docs/design/intent.md"),
            "# Intent\nA future checkpoint may stream snapshots.\n",
        )
        .expect("intent fixture");
        fs::create_dir_all(root.join("docs/archive")).expect("archive dir");
        fs::write(
            root.join("docs/archive/history.md"),
            "# History\nAn earlier snapshot used a shutdown hook.\n",
        )
        .expect("history fixture");
        fs::write(
            root.join("docs/a-tie.md"),
            "# Tie A\nDeterministic ranking is mandatory.\n",
        )
        .expect("first tie fixture");
        fs::write(
            root.join("docs/z-tie.md"),
            "# Tie Z\nDeterministic ranking is mandatory.\n",
        )
        .expect("second tie fixture");
        fs::write(
            root.join("docs/broken.md"),
            "# Broken current implementation\ncode_path = \"src/missing.rs\"\nBudget-failed suppression evidence.\n",
        )
        .expect("suppressed authority fixture");
        for (path, content) in [
            ("docs/rank-exact.md", "# Other\nalpha beta rule\n"),
            (
                "docs/rank-heading.md",
                "# Alpha gamma beta\nheading-ranked evidence\n",
            ),
            (
                "docs/rank-distinct.md",
                "# Other\nalpha separated from beta\n",
            ),
            ("docs/rank-single.md", "# Other\nalpha alone\n"),
        ] {
            fs::write(root.join(path), content).expect("ranking fixture");
        }
        fs::create_dir_all(root.join("src")).expect("source dir");
        fs::write(root.join("src/lib.rs"), "pub fn checkpoint_anchor() {}\n")
            .expect("bridge code fixture");
        fs::write(
            root.join("docs/linked.md"),
            "# Linked recovery\ncode_path = \"src/lib.rs\"\nCall `checkpoint_anchor`.\nLinked checkpoint anchor evidence.\n",
        )
        .expect("bridge knowledge fixture");

        let index = LiveIndex::load(&root).expect("LiveIndex::load knowledge fixture");
        let server = SymForgeServer::new(
            index,
            "search_knowledge_test".to_string(),
            Arc::new(Mutex::new(WatcherInfo::default())),
            Some(root),
            None,
        );
        Self { _dir: dir, server }
    }
}

fn assert_budgeted_knowledge_context(output: &str, require_trust: bool) {
    if require_trust {
        assert!(output.contains("Trust:"), "trust header missing: {output}");
    }
    assert!(
        output.contains("source="),
        "source provenance missing: {output}"
    );
    assert!(
        output.contains("publication=") && output.contains("content="),
        "generation provenance missing: {output}"
    );
    assert!(
        output.contains("counts total=")
            && output.contains("overflow=")
            && output.contains("ambiguous=")
            && output.contains("missing="),
        "complete bridge counts missing: {output}"
    );
    assert!(
        output.contains("coverage bridge=") && output.contains("authority="),
        "coverage provenance missing: {output}"
    );
    for line in output.lines().filter(|line| {
        line.trim_start()
            .split_once('.')
            .is_some_and(|(ordinal, _)| ordinal.parse::<usize>().is_ok())
    }) {
        for marker in [
            "bytes=",
            "content_hash=",
            "source=",
            "generation=",
            "link_id=",
            "bridge_index=",
            "resolution=",
            "lifecycle=",
            "voice=",
        ] {
            assert!(
                line.contains(marker),
                "budget emitted a partial knowledge anchor ({marker} missing): {line}\n{output}"
            );
        }
    }
}

#[tokio::test]
async fn exact_hit_and_complete_no_match_preserve_captured_provenance() {
    let fixture = KnowledgeFixture::new();
    let hit = fixture
        .server
        .dispatch_tool_for_tests(
            "search_knowledge",
            json!({
                "query": "shutdown is not a safe persistence boundary",
                "path_prefix": "docs/",
                "source_scope": "current",
                "authority_scope": "default",
                "limit": 10,
                "max_tokens": 2500
            }),
        )
        .await;

    assert!(hit.contains("docs/recovery.md:3"), "exact path/line: {hit}");
    assert!(
        hit.contains("Recovery > Persistence boundaries"),
        "heading breadcrumb: {hit}"
    );
    assert!(
        hit.contains("Shutdown is not a safe persistence boundary."),
        "exact excerpt: {hit}"
    );
    for field in [
        "source=current",
        "source_version=",
        "publication=",
        "content=",
        "content_hash=",
        "manifest_digest=",
        "coverage=complete",
        "authority:",
        "finding_ids=",
        "provenance_ids=",
        "bridge_previews=",
    ] {
        assert!(hit.contains(field), "missing `{field}` in: {hit}");
    }

    let no_match = fixture
        .server
        .dispatch_tool_for_tests(
            "search_knowledge",
            json!({"query": "orbital zebra lattice", "source_scope": "current"}),
        )
        .await;
    assert!(
        no_match.contains("no_evidence_complete"),
        "complete no-match class: {no_match}"
    );
}

#[tokio::test]
async fn bom_crlf_and_multibyte_hit_uses_original_one_based_half_open_lines() {
    let dir = tempfile::tempdir().expect("tempdir");
    let root = dir.path().to_path_buf();
    fs::create_dir_all(root.join("docs")).expect("docs dir");
    fs::write(
        root.join("docs/bytes.md"),
        "\u{feff}# Ünicode\r\n## Résumé\r\nβeta persistence boundary",
    )
    .expect("byte fixture");
    let index = LiveIndex::load(&root).expect("load byte fixture");
    let server = SymForgeServer::new(
        index,
        "search_knowledge_bytes".to_string(),
        Arc::new(Mutex::new(WatcherInfo::default())),
        Some(root),
        None,
    );

    let output = server
        .dispatch_tool_for_tests(
            "search_knowledge",
            json!({"query": "βeta persistence boundary", "source_scope": "current"}),
        )
        .await;
    assert!(output.contains("docs/bytes.md:3"), "exact line: {output}");
    assert!(
        output.contains("line_range=2..4"),
        "enclosing knowledge-unit range must be one-based and half-open: {output}"
    );
    assert!(
        output.contains("Ünicode > Résumé") && output.contains("βeta persistence boundary"),
        "multibyte heading/evidence: {output}"
    );
    assert!(
        !output.contains('\u{feff}'),
        "the retained BOM must not be rendered in a visible hit field: {output}"
    );
}

#[tokio::test]
async fn validation_refuses_empty_traversal_unsupported_scope_and_selector_conflicts() {
    let fixture = KnowledgeFixture::new();

    let empty = fixture
        .server
        .dispatch_tool_for_tests("search_knowledge", json!({"query": "   "}))
        .await;
    assert!(empty.contains("query must be non-empty"), "empty: {empty}");

    let traversal = fixture
        .server
        .dispatch_tool_for_tests(
            "search_knowledge",
            json!({"query": "shutdown", "path_prefix": "../outside"}),
        )
        .await;
    assert!(
        traversal.contains("invalid path_prefix"),
        "traversal: {traversal}"
    );

    // `worktrees`/`local_refs`/`all` are supported scopes (Gate L). This
    // single-worktree fixture publishes no P1 sources, so a P1 scope composes
    // to a typed empty-scope readiness result, never a false complete-absence.
    let empty_scope = fixture
        .server
        .dispatch_tool_for_tests(
            "search_knowledge",
            json!({"query": "shutdown", "source_scope": "worktrees"}),
        )
        .await;
    assert!(
        empty_scope.contains("no_sources_in_scope"),
        "empty worktrees scope: {empty_scope}"
    );

    let conflict = fixture
        .server
        .dispatch_tool_for_tests(
            "search_knowledge",
            json!({
                "query": "shutdown",
                "project": "one",
                "projects": ["two"]
            }),
        )
        .await;
    assert!(
        conflict.contains("project") && conflict.contains("mutually exclusive"),
        "selector conflict: {conflict}"
    );

    for (field, value) in [("source_scope", "unknown"), ("authority_scope", "future")] {
        let mut request = json!({"query": "shutdown"});
        request[field] = json!(value);
        let invalid = fixture
            .server
            .dispatch_tool_for_tests("search_knowledge", request)
            .await;
        assert!(
            invalid.contains("invalid tool parameters") && invalid.contains("unknown variant"),
            "invalid {field} must be a typed schema error: {invalid}"
        );
    }

    let empty_projects = fixture
        .server
        .dispatch_tool_for_tests(
            "search_knowledge",
            json!({"query": "shutdown", "projects": []}),
        )
        .await;
    assert!(
        empty_projects.contains("projects must not be empty"),
        "empty selector set: {empty_projects}"
    );

    let mixed_wildcard = fixture
        .server
        .dispatch_tool_for_tests(
            "search_knowledge",
            json!({"query": "shutdown", "projects": ["*", "one"]}),
        )
        .await;
    assert!(
        mixed_wildcard.contains("wildcard must be the sole selector"),
        "mixed wildcard selector: {mixed_wildcard}"
    );

    let tiny_budget = fixture
        .server
        .dispatch_tool_for_tests(
            "search_knowledge",
            json!({
                "query": "orbital zebra lattice",
                "max_tokens": 1
            }),
        )
        .await;
    assert!(
        tiny_budget.contains("max_tokens") && tiny_budget.contains("minimum"),
        "a budget too small for provenance must fail validation: {tiny_budget}"
    );
    assert!(
        !tiny_budget.contains("no_evidence_complete"),
        "a budget failure must never become false complete absence: {tiny_budget}"
    );
}

#[tokio::test]
async fn ranking_is_canonical_and_byte_deterministic_for_one_captured_generation() {
    let fixture = KnowledgeFixture::new();
    let request = json!({
        "query": "deterministic ranking",
        "source_scope": "current",
        "authority_scope": "default"
    });
    let first = fixture
        .server
        .dispatch_tool_for_tests("search_knowledge", request.clone())
        .await;
    let second = fixture
        .server
        .dispatch_tool_for_tests("search_knowledge", request)
        .await;

    assert_eq!(
        first, second,
        "same captured generation must format identically"
    );
    let a = first.find("docs/a-tie.md").expect("canonical a tie");
    let z = first.find("docs/z-tie.md").expect("canonical z tie");
    assert!(a < z, "canonical path must break equal-rank ties: {first}");

    let ranked = fixture
        .server
        .dispatch_tool_for_tests("search_knowledge", json!({"query": "alpha beta"}))
        .await;
    let exact = ranked
        .find("docs/rank-exact.md")
        .expect("exact phrase rank");
    let heading = ranked.find("docs/rank-heading.md").expect("heading rank");
    let distinct = ranked
        .find("docs/rank-distinct.md")
        .expect("distinct-term rank");
    let single = ranked
        .find("docs/rank-single.md")
        .expect("single-term rank");
    assert!(
        exact < heading && heading < distinct && distinct < single,
        "phrase, heading, and distinct-term ranking chain: {ranked}"
    );
}

#[tokio::test]
async fn bridge_preview_carries_stable_link_id_without_full_bridge_record() {
    let fixture = KnowledgeFixture::new();
    let first = fixture
        .server
        .dispatch_tool_for_tests(
            "search_knowledge",
            json!({
                "query": "linked checkpoint anchor evidence",
                "authority_scope": "all"
            }),
        )
        .await;
    let second = fixture
        .server
        .dispatch_tool_for_tests(
            "search_knowledge",
            json!({
                "query": "linked checkpoint anchor evidence",
                "authority_scope": "all"
            }),
        )
        .await;
    assert_eq!(first, second, "bridge IDs/previews must be stable");
    assert!(
        first.contains("docs/linked.md:4")
            && first.contains("bridge_previews=[")
            && first.contains("src/lib.rs"),
        "linked hit must carry a bounded exact bridge preview: {first}"
    );
    assert!(
        !first.contains("candidate_code_anchors") && !first.contains("evidence_records"),
        "search output must not duplicate full bridge/evidence arrays: {first}"
    );
}

#[tokio::test]
async fn authority_scopes_are_distinct_and_filtered_matches_are_not_false_absence() {
    let fixture = KnowledgeFixture::new();
    let server = &fixture.server;
    let call = |scope: &'static str| async move {
        server
            .dispatch_tool_for_tests(
                "search_knowledge",
                json!({"query": "snapshot", "authority_scope": scope}),
            )
            .await
    };

    let default = call("default").await;
    assert!(
        default.contains("docs/design/intent.md"),
        "default: {default}"
    );
    assert!(
        !default.contains("docs/archive/history.md"),
        "default excludes history: {default}"
    );

    let current = server
        .dispatch_tool_for_tests(
            "search_knowledge",
            json!({"query": "stream snapshots", "authority_scope": "current"}),
        )
        .await;
    assert!(
        current.contains("evidence_noncurrent"),
        "filtered intent is not complete absence: {current}"
    );

    let intent = call("intent").await;
    assert!(intent.contains("docs/design/intent.md"), "intent: {intent}");
    assert!(
        !intent.contains("docs/archive/history.md"),
        "intent excludes history: {intent}"
    );

    let history = call("history").await;
    assert!(
        history.contains("docs/archive/history.md"),
        "history: {history}"
    );
    assert!(
        !history.contains("docs/design/intent.md"),
        "history excludes intent: {history}"
    );

    let all = call("all").await;
    assert!(all.contains("docs/design/intent.md"), "all intent: {all}");
    assert!(
        all.contains("docs/archive/history.md"),
        "all history: {all}"
    );

    for scope in ["default", "current"] {
        let filtered = server
            .dispatch_tool_for_tests(
                "search_knowledge",
                json!({
                    "query": "budget-failed suppression evidence",
                    "authority_scope": scope
                }),
            )
            .await;
        assert!(
            filtered.contains("filtered_suppressed=1") && !filtered.contains("docs/broken.md:3"),
            "suppressed evidence must stay out of {scope}: {filtered}"
        );
    }
    for scope in ["history", "all"] {
        let visible = server
            .dispatch_tool_for_tests(
                "search_knowledge",
                json!({
                    "query": "budget-failed suppression evidence",
                    "authority_scope": scope
                }),
            )
            .await;
        assert!(
            visible.contains("docs/broken.md:3") && visible.contains("voice=suppressed"),
            "suppressed evidence must remain inspectable in {scope}: {visible}"
        );
    }
}

#[tokio::test]
async fn weak_and_sensitive_queries_are_rejected_without_echo() {
    let fixture = KnowledgeFixture::new();
    let weak = fixture
        .server
        .dispatch_tool_for_tests("search_knowledge", json!({"query": "the and why"}))
        .await;
    assert!(weak.contains("query_too_weak"), "weak query: {weak}");

    let canary = ["runtime", "-", "canary", "-", "segment"].concat();
    let query = format!("token={canary}");
    let rejected = fixture
        .server
        .dispatch_tool_for_tests("search_knowledge", json!({"query": query}))
        .await;
    assert!(
        rejected.contains("sensitive query rejected"),
        "sensitive query must fail closed"
    );
    assert!(
        !rejected.contains(&canary),
        "sensitive query must never be echoed"
    );

    let sensitive_path = format!("docs/token={canary}");
    let rejected_path = fixture
        .server
        .dispatch_tool_for_tests(
            "search_knowledge",
            json!({"query": "checkpoint anchor", "path_prefix": sensitive_path}),
        )
        .await;
    assert!(
        rejected_path.contains("sensitive path_prefix rejected"),
        "sensitive path scope must fail closed"
    );
    assert!(
        !rejected_path.contains(&canary),
        "sensitive path scope must never be echoed"
    );
}

#[tokio::test]
async fn ccr_truncation_withholds_partial_hits_and_round_trips_full_safe_output() {
    let fixture = KnowledgeFixture::new();
    let capped = fixture
        .server
        .dispatch_tool_for_tests(
            "search_knowledge",
            json!({
                "query": "deterministic ranking",
                "limit": 10,
                "max_tokens": 120
            }),
        )
        .await;
    let hash = capped
        .split("hash=\"")
        .nth(1)
        .and_then(|suffix| suffix.split('"').next())
        .expect("over-budget knowledge search must emit a CCR hash");
    for line in capped.lines().filter(|line| line.contains("docs/")) {
        assert!(line.contains("authority:"), "partial hit escaped: {line}");
        assert!(line.contains("finding_ids="), "provenance missing: {line}");
        assert!(
            line.contains("bridge_previews="),
            "bridge preview missing: {line}"
        );
    }

    let full = fixture
        .server
        .dispatch_tool_for_tests("symforge_retrieve", json!({"hash": hash}))
        .await;
    assert!(
        full.len() > capped.len(),
        "CCR must restore the full output"
    );
    assert!(full.contains("docs/a-tie.md"), "first full hit: {full}");
    assert!(full.contains("docs/z-tie.md"), "second full hit: {full}");
    assert!(full.contains("source_version="), "source version: {full}");
    assert!(full.contains("publication="), "publication: {full}");
    assert!(full.contains("content="), "content generation: {full}");

    let evicted = fixture
        .server
        .dispatch_tool_for_tests("symforge_retrieve", json!({"hash": "000000000000"}))
        .await;
    assert!(
        evicted.contains("stale or expired") && evicted.contains("retry"),
        "an unavailable captured CCR generation must be explicit and retryable: {evicted}"
    );
}

#[tokio::test]
async fn ask_routes_explicit_knowledge_intent_without_stealing_code_intent() {
    let fixture = KnowledgeFixture::new();
    let knowledge = fixture
        .server
        .dispatch_tool_for_tests(
            "ask",
            json!({"query": "what do the docs say about persistence boundaries"}),
        )
        .await;
    assert!(
        knowledge.contains("Chosen tool: search_knowledge"),
        "knowledge route: {knowledge}"
    );
    assert!(
        knowledge.contains("docs/recovery.md:2"),
        "knowledge result: {knowledge}"
    );

    let code = fixture
        .server
        .dispatch_tool_for_tests("ask", json!({"query": "where is search_knowledge defined"}))
        .await;
    assert!(
        code.contains("Chosen tool: search_symbols"),
        "code intent must retain code routing: {code}"
    );
    assert!(
        !code.contains("Chosen tool: search_knowledge"),
        "knowledge route stole code intent: {code}"
    );
}

#[tokio::test]
async fn ask_knowledge_secret_guard_runs_before_route_explanation() {
    let fixture = KnowledgeFixture::new();
    let canary = ["runtime", "-", "canary", "-", "segment"].concat();
    let query = format!("search repository knowledge for token={canary}");
    let rejected = fixture
        .server
        .dispatch_tool_for_tests("ask", json!({"query": query}))
        .await;
    assert!(
        rejected.contains("sensitive query rejected"),
        "ask knowledge safety must fail closed"
    );
    assert!(
        !rejected.contains(&canary),
        "ask route explanation must not echo a sensitive query"
    );
}

#[tokio::test]
async fn ask_routes_repository_orientation_to_the_combined_map_without_prose_invention() {
    let fixture = KnowledgeFixture::new();
    let output = fixture
        .server
        .dispatch_tool_for_tests("ask", json!({"query": "orient me in this repository"}))
        .await;

    assert!(output.contains("Chosen tool: get_repo_map"));
    assert!(output.contains("Invocation: get_repo_map(detail=\"compact\")"));
    assert!(output.contains("Index:"));
    assert!(output.contains("Repository knowledge:"));
    assert!(output.contains("Missing roles:"));
    assert!(!output.contains("A future checkpoint may stream snapshots."));
}

#[tokio::test]
async fn repo_map_preserves_topology_and_appends_one_captured_bounded_knowledge_map() {
    let fixture = KnowledgeFixture::new();
    let first = fixture
        .server
        .dispatch_tool_for_tests("get_repo_map", json!({"detail": "compact"}))
        .await;
    let second = fixture
        .server
        .dispatch_tool_for_tests("get_repo_map", json!({"detail": "compact"}))
        .await;

    assert_eq!(first, second);
    assert!(first.contains("Index:"));
    assert!(first.contains("Repository knowledge:"));
    assert!(first.contains("publication="));
    assert!(first.contains("content="));
    assert!(first.contains("Intent roles:"));
    assert!(first.contains("architecture docs/design/intent.md:1"));
    assert!(first.contains("Missing roles:"));
    assert!(first.contains("Hygiene:"));
    assert!(first.contains("Uncertainty:"));
    assert!(first.contains("Coverage:"));
    assert!(!first.contains("A future checkpoint may stream snapshots."));
}

#[tokio::test]
async fn file_context_knowledge_section_preserves_only_default_and_empty_section_modes() {
    let fixture = KnowledgeFixture::new();
    let knowledge_only = fixture
        .server
        .dispatch_tool_for_tests(
            "get_file_context",
            json!({"path": "src/lib.rs", "sections": ["knowledge"]}),
        )
        .await;
    assert!(knowledge_only.contains("Trust:"));
    assert!(knowledge_only.contains("Knowledge evidence:"));
    assert!(
        knowledge_only.contains("docs/linked.md"),
        "{knowledge_only}"
    );
    assert!(!knowledge_only.contains("Symbols:"));

    let omitted = fixture
        .server
        .dispatch_tool_for_tests("get_file_context", json!({"path": "src/lib.rs"}))
        .await;
    assert!(omitted.contains("Knowledge evidence:"));
    assert!(omitted.contains("checkpoint_anchor"));

    let empty = fixture
        .server
        .dispatch_tool_for_tests(
            "get_file_context",
            json!({"path": "src/lib.rs", "sections": []}),
        )
        .await;
    assert!(empty.contains("Knowledge evidence:"));
    assert!(empty.contains("checkpoint_anchor"));
}

#[tokio::test]
async fn symbol_context_knowledge_section_preserves_only_default_empty_and_bundle_modes() {
    let fixture = KnowledgeFixture::new();
    let knowledge_only = fixture
        .server
        .dispatch_tool_for_tests(
            "get_symbol_context",
            json!({
                "path": "src/lib.rs",
                "name": "checkpoint_anchor",
                "sections": ["knowledge"]
            }),
        )
        .await;
    assert!(knowledge_only.contains("Trust:"));
    assert!(knowledge_only.contains("Knowledge evidence:"));
    assert!(knowledge_only.contains("docs/linked.md"));
    assert!(!knowledge_only.contains("pub fn checkpoint_anchor"));

    let omitted = fixture
        .server
        .dispatch_tool_for_tests(
            "get_symbol_context",
            json!({"path": "src/lib.rs", "name": "checkpoint_anchor"}),
        )
        .await;
    assert!(omitted.contains("pub fn checkpoint_anchor"));
    assert!(omitted.contains("Knowledge evidence:"));

    let empty = fixture
        .server
        .dispatch_tool_for_tests(
            "get_symbol_context",
            json!({"path": "src/lib.rs", "name": "checkpoint_anchor", "sections": []}),
        )
        .await;
    assert!(empty.contains("Knowledge evidence:"));

    let bundle = fixture
        .server
        .dispatch_tool_for_tests(
            "get_symbol_context",
            json!({
                "path": "src/lib.rs",
                "name": "checkpoint_anchor",
                "bundle": true
            }),
        )
        .await;
    assert!(bundle.contains("pub fn checkpoint_anchor"));
    assert!(!bundle.contains("Knowledge evidence:"));
}

#[tokio::test]
async fn knowledge_only_context_budget_preserves_provenance_counts_and_atomic_anchors() {
    let fixture = KnowledgeFixture::new();
    let file = fixture
        .server
        .dispatch_tool_for_tests(
            "get_file_context",
            json!({
                "path": "src/lib.rs",
                "sections": ["knowledge"],
                "max_tokens": 96
            }),
        )
        .await;
    assert_budgeted_knowledge_context(&file, true);

    let symbol = fixture
        .server
        .dispatch_tool_for_tests(
            "get_symbol_context",
            json!({
                "path": "src/lib.rs",
                "name": "checkpoint_anchor",
                "sections": ["knowledge"],
                "max_tokens": 96
            }),
        )
        .await;
    assert_budgeted_knowledge_context(&symbol, true);
}

#[tokio::test]
async fn default_and_empty_context_budgets_keep_atomic_knowledge_provenance() {
    let fixture = KnowledgeFixture::new();
    for request in [
        json!({"path": "src/lib.rs", "max_tokens": 128}),
        json!({"path": "src/lib.rs", "sections": [], "max_tokens": 128}),
    ] {
        let output = fixture
            .server
            .dispatch_tool_for_tests("get_file_context", request)
            .await;
        assert_budgeted_knowledge_context(&output, false);
    }

    for request in [
        json!({
            "path": "src/lib.rs",
            "name": "checkpoint_anchor",
            "max_tokens": 128
        }),
        json!({
            "path": "src/lib.rs",
            "name": "checkpoint_anchor",
            "sections": [],
            "max_tokens": 128
        }),
    ] {
        let output = fixture
            .server
            .dispatch_tool_for_tests("get_symbol_context", request)
            .await;
        assert_budgeted_knowledge_context(&output, false);
    }
}

#[tokio::test]
async fn file_context_repeat_cache_invalidates_after_targeted_publication() {
    let fixture = KnowledgeFixture::new();
    let request = json!({"path": "src/lib.rs", "sections": []});
    let first = fixture
        .server
        .dispatch_tool_for_tests("get_file_context", request.clone())
        .await;
    assert!(first.contains("checkpoint_anchor"), "{first}");

    let path = fixture._dir.path().join("src/lib.rs");
    fs::write(&path, "pub fn replacement_anchor() {}\n").expect("rewrite code fixture");
    filetime::set_file_mtime(
        &path,
        filetime::FileTime::from_system_time(
            std::time::SystemTime::now() + std::time::Duration::from_secs(2),
        ),
    )
    .expect("advance code fixture mtime");

    let second = fixture
        .server
        .dispatch_tool_for_tests("get_file_context", request)
        .await;
    assert!(second.contains("replacement_anchor"), "{second}");
    assert!(!second.contains("checkpoint_anchor"), "{second}");
    assert!(!second.contains("session_repeat_read"), "{second}");
}

#[tokio::test]
async fn deep_read_after_publication_serves_current_bytes() {
    let fixture = KnowledgeFixture::new();
    let request = json!({
        "path": "docs/recovery.md",
        "start_line": 1,
        "end_line": 3
    });

    let first = fixture
        .server
        .dispatch_tool_for_tests("get_file_content", request.clone())
        .await;
    assert!(
        first.contains("Shutdown is not a safe persistence boundary."),
        "initial deep read: {first}"
    );

    let path = fixture._dir.path().join("docs/recovery.md");
    fs::write(
        &path,
        "# Recovery\n## Persistence boundaries\nCheckpoint completion is the persistence boundary.\n",
    )
    .expect("rewrite knowledge fixture");
    filetime::set_file_mtime(
        &path,
        filetime::FileTime::from_system_time(
            std::time::SystemTime::now() + std::time::Duration::from_secs(2),
        ),
    )
    .expect("advance fixture mtime so targeted freshness publishes the rewrite");

    let second = fixture
        .server
        .dispatch_tool_for_tests("get_file_content", request)
        .await;
    assert!(
        second.contains("Checkpoint completion is the persistence boundary."),
        "deep read after publication must serve current bytes: {second}"
    );
    assert!(
        !second.contains("session_repeat_read"),
        "a prior generation must not satisfy the repeat-read cache: {second}"
    );
}

#[tokio::test]
#[ignore = "manual Gate I acceptance against the complete repository corpus"]
async fn real_repository_corpus_returns_exact_deterministic_non_fixture_pointers() {
    let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let index = LiveIndex::load(&root).expect("load real repository for knowledge acceptance");
    let server = SymForgeServer::new(
        index,
        "search_knowledge_real_repository".to_string(),
        Arc::new(Mutex::new(WatcherInfo::default())),
        Some(root),
        None,
    );
    let queries = [
        "shutdown is not a persistence boundary",
        "repair_index is intentionally retired",
        "compact surface has three tools",
        "byte exact storage line endings",
        "why embeddings are optional",
        "GGUF or safetensors indexing limits",
        "worktree routing and stale generations",
        "FTS5 planned or deferred",
    ];

    for query in queries {
        let request = json!({
            "query": query,
            "source_scope": "current",
            "limit": 3,
            "max_tokens": 2500
        });
        let first = server
            .dispatch_tool_for_tests("search_knowledge", request.clone())
            .await;
        let second = server
            .dispatch_tool_for_tests("search_knowledge", request)
            .await;
        assert_eq!(first, second, "real-repository output drifted for {query}");
        assert!(
            first.contains("Source: source=current")
                && first.contains("source_version=")
                && first.contains("freshness=")
                && first.contains("overall_coverage="),
            "real-repository result omitted captured source trust for {query}: {first}"
        );

        let pointer = first
            .lines()
            .filter(|line| {
                line.trim_start()
                    .split_once(". ")
                    .is_some_and(|(rank, _)| rank.parse::<usize>().is_ok())
            })
            .find(|line| !line.contains("specs/020-repository-knowledge-index/quickstart.md"))
            .unwrap_or_else(|| panic!("no non-acceptance-fixture pointer for {query}: {first}"));
        let estimated_tokens = first.len().saturating_add(3) / 4;
        println!("{query}\t{estimated_tokens}\t{}", pointer.trim());
    }
}

#[tokio::test]
#[ignore = "manual Gate J acceptance against the complete repository corpus"]
async fn real_repository_orientation_and_review_are_repeatable_and_actionable() {
    let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let index = LiveIndex::load(&root).expect("load real repository for mental-model acceptance");
    let server = SymForgeServer::new(
        index,
        "knowledge_review_real_repository".to_string(),
        Arc::new(Mutex::new(WatcherInfo::default())),
        Some(root),
        None,
    );

    let map_request = json!({"detail": "compact", "max_tokens": 4000});
    let first_map = server
        .dispatch_tool_for_tests("get_repo_map", map_request.clone())
        .await;
    let second_map = server
        .dispatch_tool_for_tests("get_repo_map", map_request)
        .await;
    assert_eq!(first_map, second_map, "repository orientation drifted");
    for marker in [
        "Repository knowledge:",
        "unit_id=",
        "content_hash=",
        "evidence_anchor=",
        "Uncertainty:",
        "Coverage:",
    ] {
        assert!(
            first_map.contains(marker),
            "map missing {marker}: {first_map}"
        );
    }

    let review_request = json!({
        "mode": "remediation",
        "source_scope": "current",
        "limit": 10,
        "max_tokens": 8000
    });
    let first_review = server
        .dispatch_tool_for_tests("review_knowledge", review_request.clone())
        .await;
    let second_review = server
        .dispatch_tool_for_tests("review_knowledge", review_request)
        .await;
    assert_eq!(first_review, second_review, "repository review drifted");
    for marker in [
        "mode=remediation",
        "top_result_hash=",
        "review_hash=",
        "source_id=",
        "branch=",
        "commit=",
        "working_tree=",
        "manifest_digest=",
        "manifest_coverage=",
        "summary.total=",
        "finding_ids=[",
        "action_id=",
        "dossier unit=",
        "content_hash=",
    ] {
        assert!(
            first_review.contains(marker),
            "review missing {marker}: {first_review}"
        );
    }
}

#[tokio::test]
async fn review_knowledge_modes_expose_complete_typed_dossiers_and_limit_independent_hashes() {
    let fixture = KnowledgeFixture::new();
    let linked_path = fixture._dir.path().join("docs/linked.md");
    let linked_before = fs::read(&linked_path).expect("linked fixture bytes");
    let policy_path = fixture._dir.path().join(".symforge-knowledge.toml");
    assert!(
        !policy_path.exists(),
        "fixture must start without a policy file"
    );
    let summary = fixture
        .server
        .dispatch_tool_for_tests(
            "review_knowledge",
            json!({"mode": "summary", "source_scope": "current"}),
        )
        .await;
    let document = fixture
        .server
        .dispatch_tool_for_tests(
            "review_knowledge",
            json!({
                "mode": "document",
                "path": "docs/linked.md",
                "source_scope": "current"
            }),
        )
        .await;
    let remediation = fixture
        .server
        .dispatch_tool_for_tests(
            "review_knowledge",
            json!({"mode": "remediation", "source_scope": "current", "limit": 10}),
        )
        .await;
    let limited = fixture
        .server
        .dispatch_tool_for_tests(
            "review_knowledge",
            json!({"mode": "remediation", "source_scope": "current", "limit": 1}),
        )
        .await;

    let field = |output: &str, name: &str| {
        output
            .lines()
            .find_map(|line| line.strip_prefix(&format!("{name}=")))
            .map(str::to_string)
            .unwrap_or_else(|| panic!("missing {name}: {output}"))
    };
    assert!(summary.contains("mode=summary"), "{summary}");
    assert!(summary.contains("summary.total="), "{summary}");
    for required in [
        "finding_ids=[",
        "action_id=",
        "rule_ids=[",
        "code_evidence.consistent_rule_ids=",
        "bridge_records=",
        "timeline.coverage=",
        "exact_code_anchors=[",
        "eligibility.protected_roles=[",
        "proposal.action=",
        "proposal.unmet_preconditions=[",
    ] {
        assert!(
            document.contains(required),
            "missing {required}: {document}"
        );
    }
    assert!(
        !document.contains("Linked checkpoint anchor evidence"),
        "review dossiers must not inline document prose: {document}"
    );
    assert!(remediation.contains("mode=remediation"), "{remediation}");
    assert_eq!(
        field(&remediation, "top_result_hash"),
        field(&limited, "top_result_hash")
    );
    assert_eq!(
        field(&remediation, "review_hash"),
        field(&limited, "review_hash")
    );
    assert!(limited.contains("overflow="), "{limited}");
    assert_eq!(
        fs::read(&linked_path).expect("linked fixture after review"),
        linked_before,
        "read-only review must not mutate repository documents"
    );
    assert!(
        !policy_path.exists(),
        "read-only review must not create repository policy"
    );
}

#[tokio::test]
async fn review_knowledge_tight_budget_returns_only_complete_index_entries_and_degraded_coverage() {
    let fixture = KnowledgeFixture::new();
    let output = fixture
        .server
        .dispatch_tool_for_tests(
            "review_knowledge",
            json!({
                "mode": "remediation",
                "source_scope": "current",
                "limit": 10,
                "max_tokens": 512
            }),
        )
        .await;

    assert!(output.contains("top_result_hash="), "{output}");
    assert!(output.contains("review_hash="), "{output}");
    assert!(output.contains("output_coverage=degraded"), "{output}");
    assert!(output.contains("total_dossiers="), "{output}");
    assert!(output.contains("CCR:"), "{output}");
    assert!(
        !output.lines().any(|line| line.starts_with("dossier ")),
        "a budget summary must not return a partial multi-line dossier: {output}"
    );
    for index in output
        .lines()
        .filter(|line| line.starts_with("review_index "))
    {
        assert!(index.contains("finding_ids=["), "{index}");
        assert!(index.contains("action_id="), "{index}");
        assert!(index.contains("unit="), "{index}");
        assert!(index.contains("evidence_locations=["), "{index}");
    }
}

#[tokio::test]
async fn repository_map_tight_budget_prioritizes_exact_role_cards_and_degraded_coverage() {
    let fixture = KnowledgeFixture::new();
    let output = fixture
        .server
        .dispatch_tool_for_tests(
            "get_repo_map",
            json!({"detail": "compact", "max_tokens": 512}),
        )
        .await;

    assert!(output.contains("output_coverage=degraded"), "{output}");
    assert!(output.contains("Repository knowledge:"), "{output}");
    assert!(output.contains("unit_id="), "{output}");
    assert!(output.contains("content_hash="), "{output}");
    assert!(output.contains("evidence_anchor="), "{output}");
    assert!(output.contains("CCR:"), "{output}");
}

#[tokio::test]
async fn review_knowledge_sensitive_selectors_fail_before_hash_or_echo() {
    let fixture = KnowledgeFixture::new();
    let canary = ["runtime", "-", "canary", "-", "segment"].concat();
    let sensitive_path = format!("docs/token={canary}");
    let rejected = fixture
        .server
        .dispatch_tool_for_tests(
            "review_knowledge",
            json!({"mode": "document", "path": sensitive_path}),
        )
        .await;
    assert!(rejected.contains("sensitive path rejected"), "fail closed");
    assert!(!rejected.contains(&canary), "selector must never be echoed");
    assert!(
        !rejected.contains("review_hash=")
            && !rejected.contains("top_result_hash=")
            && !rejected.contains("hash=\""),
        "rejection must not mint plan or CCR hashes"
    );
}