symforge 8.22.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
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
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
//! Engine-internal base+overlay index primitive (Feature 012 de-risk spike).
//!
//! This module generalizes the existing `ArcSwap<LiveIndex>` snapshot into a
//! read surface = an immutable shared **base** (`Arc<LiveIndex>`, the existing
//! snapshot, UNCHANGED) + an optional per-consumer copy-on-write **overlay** of
//! dirty/uncommitted deltas. See `specs/012-harness-agnostic-mcp/{spec,research,
//! data-model,quickstart}.md` (D1 base+overlay, D2 generation-fence
//! invalidation, D3 embed-facade boundary).
//!
//! SEMVER: these types are intentionally **NOT** part of the frozen `embed`
//! contract (`src/embed.rs` `contract` module). They are reachable by embedders
//! only via the deep-path re-export `symforge::embed::live_index::view::*` and
//! are explicitly UNSTABLE (overlay-invalidation internals may churn at MINOR).
//! Do not add them to `embed.rs` or its contract test (D3 / SC-011).
//!
//! Invariants:
//! * `LiveIndex` is unchanged; the commit identity lives on [`IndexBase`], never
//!   inside `LiveIndex` (avoids touching the frozen `LiveIndex` contract).
//! * An [`IndexBase`] is immutable once published; a new commit produces a NEW
//!   `IndexBase` (new key + incremented `base_generation`), never a mutation.
//! * An [`Overlay`] is owned by exactly one consumer; isolation (SC-003) is an
//!   ownership invariant, not a runtime check.
//! * `base_generation` is a NEW counter distinct from
//!   `SharedIndexHandle::project_generation` (project identity vs commit
//!   identity, research D2).

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use crate::domain::{ReferenceKind, ReferenceRecord};

use super::search::{
    DEFAULT_MAX_PER_FILE, PathScope, SymbolMatchTier, SymbolSearchOptions, TextSearchError,
    TextSearchOptions, TextSearchResult, browse_kind_rank, compute_test_ranges,
    current_code_search_keeps_file, search_symbols_with_options, search_text_with_options,
    truncate_display_line,
};
use super::store::{IndexedFile, LiveIndex};
use crate::live_index::query::is_filtered_name;
use crate::live_index::query::{SearchFilesHit, SearchFilesView};

/// The commit identity component of a [`BaseKey`].
///
/// `Sha` carries `head_sha` (`git.rs:403`); `Dirtyless` is the sentinel used
/// when the canonical root is not a git repository (so a non-git tree still has
/// a stable, shareable base identity).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum CommitId {
    /// Resolved git HEAD sha for the canonical root.
    Sha(String),
    /// Sentinel for a non-git canonical root.
    Dirtyless,
}

/// Identity of an immutable set of repository facts.
///
/// Two consumers with an equal `BaseKey` MUST share one [`IndexBase`]
/// allocation (SC-002). Different worktrees of one logical repo have different
/// `canonical_root`s and therefore distinct keys (no cross-state contamination,
/// User Story 3 edge case).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct BaseKey {
    /// The declared, canonicalized workspace root.
    pub canonical_root: PathBuf,
    /// `head_sha` or [`CommitId::Dirtyless`] when not a git repo.
    pub commit: CommitId,
}

impl BaseKey {
    pub fn new(canonical_root: impl Into<PathBuf>, commit: CommitId) -> Self {
        Self {
            canonical_root: canonical_root.into(),
            commit,
        }
    }
}

/// Wraps the existing immutable snapshot with a sharable identity + fence token.
///
/// The base payload type is `Arc<LiveIndex>` — already contracted in `embed.rs`
/// — so the base layer needs zero facade change (D3 / SC-011). `base_generation`
/// is a NEW monotonic counter, distinct from `project_generation`.
#[derive(Clone)]
pub struct IndexBase {
    /// Sharable identity `(canonical_root, commit)`.
    pub key: BaseKey,
    /// The existing immutable snapshot, shared by `Arc` across consumers.
    ///
    /// STALENESS (documented limitation): this is a SNAPSHOT frozen at the
    /// instant the base was interned/opened — the `Arc<LiveIndex>` handle taken
    /// from the project's `ArcSwap` at intern time. It is NOT live: the project's
    /// background watcher keeps swapping a NEW `Arc<LiveIndex>` into the project's
    /// `ArcSwap` as files change on disk, but those swaps do NOT rewrite this
    /// already-interned handle. So a cross-project read served from this base goes
    /// stale after ANY watcher-picked-up change to the project (edit, add, delete
    /// on disk) — NOT only after a git commit. `base_generation` advances only
    /// when a NEW base is published (a fresh intern), which today does not
    /// re-trigger on watcher reloads of an already-interned base. Re-interning a
    /// base on watcher-observed change so a long-lived cross-project session
    /// tracks current repository state (the live-freshness rebase) is the deferred
    /// Phase 4 work; until then a session should re-open (retarget / additive
    /// re-add) a project to pick up a fresh base.
    pub index: Arc<LiveIndex>,
    /// Monotonic fence token, bumped when a NEW base is published (a fresh intern,
    /// e.g. a new commit producing a new `BaseKey`). See the `index` field's
    /// STALENESS note: this generation does NOT advance for watcher reloads of an
    /// already-interned base, so it is a publish-identity token, not a
    /// live-freshness signal.
    pub base_generation: u64,
}

impl IndexBase {
    /// Publish a base for `key` at `base_generation` wrapping `index`.
    pub fn new(key: BaseKey, index: Arc<LiveIndex>, base_generation: u64) -> Self {
        Self {
            key,
            index,
            base_generation,
        }
    }
}

/// A single consumer's copy-on-write change to one file relative to its base.
#[derive(Clone)]
pub enum FileDelta {
    /// The overlay's version of a file shadows the base (added or edited).
    Upsert(Arc<IndexedFile>),
    /// The file is deleted in the overlay; it is hidden from the base.
    Tombstone,
}

/// A single consumer's copy-on-write deltas over one [`IndexBase`].
///
/// Holds ONLY dirty/uncommitted files; an absent key means "see base". An
/// overlay is owned by exactly one consumer and is never shared or read by
/// another consumer's [`IndexView`] (isolation, SC-003).
#[derive(Clone)]
pub struct Overlay {
    /// The base this overlay was derived against (identity half of the fence).
    pub base_key: BaseKey,
    /// The base generation this overlay was derived against (fence token).
    pub base_generation: u64,
    /// Dirty/uncommitted deltas, keyed by forward-slash relative path.
    pub deltas: HashMap<String, FileDelta>,
}

impl Overlay {
    /// A fresh, empty overlay fenced to `base`.
    pub fn fresh(base: &IndexBase) -> Self {
        Self {
            base_key: base.key.clone(),
            base_generation: base.base_generation,
            deltas: HashMap::new(),
        }
    }

    /// Number of live deltas (the dirty-set size K).
    pub fn delta_count(&self) -> usize {
        self.deltas.len()
    }

    /// Validity check against a base (D2): an overlay is valid iff its key and
    /// generation both match the base it is read against.
    pub fn is_valid_against(&self, base: &IndexBase) -> bool {
        self.base_key == base.key && self.base_generation == base.base_generation
    }
}

/// Error returned when an [`Overlay`] is read against a base it is not fenced to.
///
/// Carries the expected (base) and actual (overlay) generations for diagnostics.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StaleOverlay {
    pub base_generation: u64,
    pub overlay_generation: u64,
}

impl std::fmt::Display for StaleOverlay {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "stale overlay: base generation {} != overlay generation {}",
            self.base_generation, self.overlay_generation
        )
    }
}

impl std::error::Error for StaleOverlay {}

/// The read surface: an immutable base plus an optional per-consumer overlay.
///
/// `overlay: None` is byte-for-byte today's behavior (the migration seam, D1).
/// Resolution: the overlay shadows the base on a key collision; a
/// [`FileDelta::Tombstone`] hides a base file.
pub struct IndexView<'a> {
    base: &'a LiveIndex,
    overlay: Option<&'a Overlay>,
}

impl<'a> IndexView<'a> {
    /// Build a view over `base`, optionally applying `overlay`.
    ///
    /// Returns `Err(StaleOverlay)` if the overlay's fence does not match the
    /// base's `base_generation` (never serve stale; D2). `overlay: None` always
    /// succeeds and reproduces today's base-only behavior.
    pub fn new(base: &'a IndexBase, overlay: Option<&'a Overlay>) -> Result<Self, StaleOverlay> {
        if let Some(ov) = overlay {
            // Fence on generation (the data-model constructor rule). Key
            // mismatch is also invalid, but generation is the monotonic token
            // the spike asserts on; a key change always rides a generation bump.
            if ov.base_generation != base.base_generation || ov.base_key != base.key {
                return Err(StaleOverlay {
                    base_generation: base.base_generation,
                    overlay_generation: ov.base_generation,
                });
            }
        }
        Ok(Self {
            base: base.index.as_ref(),
            overlay,
        })
    }

    /// The degenerate base-only view (the migration seam; no fence needed).
    pub fn base_only(base: &'a LiveIndex) -> Self {
        Self {
            base,
            overlay: None,
        }
    }

    /// Resolve a file by relative path: overlay shadows base; a tombstone hides
    /// the base file (returns `None`).
    pub fn get_file(&self, relative_path: &str) -> Option<&IndexedFile> {
        if let Some(ov) = self.overlay
            && let Some(delta) = ov.deltas.get(relative_path)
        {
            return match delta {
                FileDelta::Upsert(file) => Some(file.as_ref()),
                FileDelta::Tombstone => None,
            };
        }
        self.base.get_file(relative_path)
    }

    /// Iterate all resolved `(path, file)` pairs: base files not shadowed by an
    /// overlay delta, plus overlay upserts; tombstoned base files are excluded.
    ///
    /// Allocates a result `Vec` because resolution merges two maps; this is a
    /// convenience iterator, not a hot path. The single-consumer path
    /// (`overlay: None`) returns base files directly with no overlay work.
    pub fn all_files(&self) -> Vec<(String, &IndexedFile)> {
        match self.overlay {
            None => self.base.all_files().map(|(p, f)| (p.clone(), f)).collect(),
            Some(ov) => {
                let mut out: Vec<(String, &IndexedFile)> = Vec::new();
                // Base files, minus any shadowed/tombstoned by the overlay.
                for (path, file) in self.base.all_files() {
                    match ov.deltas.get(path) {
                        Some(FileDelta::Tombstone) => continue,
                        Some(FileDelta::Upsert(_)) => continue, // emitted below
                        None => out.push((path.clone(), file)),
                    }
                }
                // Overlay upserts (added files + edited shadows).
                for (path, delta) in &ov.deltas {
                    if let FileDelta::Upsert(file) = delta {
                        out.push((path.clone(), file.as_ref()));
                    }
                }
                out
            }
        }
    }

    /// Live overlay deltas, if any (`None` for a base-only view). Used by the
    /// post-filter search paths to identify the small dirty set.
    fn overlay_deltas(&self) -> Option<&'a HashMap<String, FileDelta>> {
        self.overlay.map(|ov| &ov.deltas)
    }

    /// Symbol-name search resolved THROUGH the overlay (research D1: symbol-name
    /// search resolves through the overlay, not via the base's derived indices).
    ///
    /// For a view with NO live deltas (base-only, OR an empty overlay — the US1
    /// cross-project case, since overlays are never written there) this delegates
    /// straight to the engine's option-honoring [`search_symbols_with_options`]
    /// over the base, so the caller's `options` (path scope, language filter,
    /// noise policy, and the `result_limit` ranking) ARE honored on the
    /// cross-project read path (D11 scoping + D14 ranking). When live overlay
    /// deltas ARE present we cannot call the base function (it would scan the
    /// stale base file map), so we scan the OVERLAY-RESOLVED file set
    /// ([`all_files`]) directly with the name-match + tiering rules the engine
    /// uses. Correctness over speed: this is a linear scan of the resolved set.
    ///
    /// `// DEFERRED (D-B0):` the overlay-present scan applies only the name/kind
    /// tiering needed for cross-project attribution; honoring the full option
    /// surface (path scope, language, noise) over the dirty set is the deferred
    /// per-overlay derived-index work. That branch is unreached on the US1
    /// cross-project path (overlays are empty there); until then the overlay
    /// symbol search is a minimal, correct superset.
    ///
    /// [`all_files`]: IndexView::all_files
    pub fn search_symbols(
        &self,
        query: &str,
        kind_filter: Option<&str>,
        options: &SymbolSearchOptions,
    ) -> Vec<ViewSymbolHit> {
        // No live deltas (absent OR empty overlay) -> reuse the engine's
        // option-honoring search verbatim over the base. This IS the US1
        // cross-project path; caller scoping + result_limit ranking are honored.
        let no_deltas = match self.overlay_deltas() {
            None => true,
            Some(deltas) => deltas.is_empty(),
        };
        if no_deltas {
            let result = search_symbols_with_options(self.base, query, kind_filter, options);
            return result
                .hits
                .into_iter()
                .map(|hit| ViewSymbolHit {
                    name: hit.name,
                    path: hit.path,
                    kind: hit.kind,
                    line: hit.line,
                    tier: hit.tier,
                })
                .collect();
        }

        let query_lower = query.to_lowercase();
        // Same browse intent as the base engine (search.rs): an empty/whitespace
        // query WITH a scope filter ranks by importance, not name-match tiers.
        // Keeps the browse-vs-name-match distinction consistent across both
        // `search_symbols` call sites (018 US2).
        let browse = query.trim().is_empty()
            && (kind_filter.is_some() || !matches!(options.path_scope, PathScope::Any));
        // Carry the reverse-reference count alongside each hit for browse ranking
        // (0 on the keyword path). Reference counts come from the base's
        // `reverse_index` — the same source the engine uses.
        let mut hits: Vec<(ViewSymbolHit, usize)> = Vec::new();
        let mut resolved = self.all_files();
        // Stable ordering before tiering so equal-tier ties are deterministic.
        resolved.sort_by(|a, b| a.0.cmp(&b.0));

        for (path, file) in resolved {
            for sym in &file.symbols {
                if let Some(filter) = kind_filter
                    && !filter.eq_ignore_ascii_case("all")
                    && !symbol_kind_matches(filter, &sym.kind)
                {
                    continue;
                }
                let name_lower = sym.name.to_lowercase();
                if !browse && !name_lower.contains(&query_lower) {
                    continue;
                }
                let tier = if name_lower == query_lower {
                    SymbolMatchTier::Exact
                } else if name_lower.starts_with(&query_lower) {
                    SymbolMatchTier::Prefix
                } else {
                    SymbolMatchTier::Substring
                };
                let ref_count = if browse {
                    self.base
                        .reverse_index
                        .get(&sym.name)
                        .map(|refs| refs.len())
                        .unwrap_or(0)
                } else {
                    0
                };
                hits.push((
                    ViewSymbolHit {
                        name: sym.name.clone(),
                        path: path.clone(),
                        kind: sym.kind.to_string(),
                        line: sym.line_range.0 + 1,
                        tier,
                    },
                    ref_count,
                ));
            }
        }

        if browse {
            // Importance order: reference count desc, then a total kind → path →
            // line tie-break (Constitution IV).
            hits.sort_by(|(a, ca), (b, cb)| {
                cb.cmp(ca)
                    .then_with(|| browse_kind_rank(&a.kind).cmp(&browse_kind_rank(&b.kind)))
                    .then_with(|| a.path.cmp(&b.path))
                    .then_with(|| a.line.cmp(&b.line))
            });
        } else {
            hits.sort_by(|(a, _), (b, _)| {
                a.tier
                    .cmp(&b.tier)
                    .then(a.name.cmp(&b.name))
                    .then(a.path.cmp(&b.path))
            });
        }
        hits.into_iter().map(|(hit, _)| hit).collect()
    }

    /// Text search served BASE-ONLY + an overlay POST-FILTER over the dirty set
    /// (research D1 sub-decision).
    ///
    /// `search_text` depends on the base's repo-wide `trigram_index`, which the
    /// overlay does NOT re-derive (that is the DEFERRED per-consumer derived
    /// index). So we:
    /// 1. run the engine [`search_text_with_options`] against the immutable base
    ///    index (honoring the caller's `options` — path scope, language, noise,
    ///    limits — so cross-project text scoping is honored, D11);
    /// 2. DROP every base file-result whose path is a live overlay delta — its
    ///    base content is stale (the consumer edited or deleted that file);
    /// 3. directly SCAN each overlay `Upsert`'s current content for the same
    ///    query and append fresh matches for it.
    ///
    /// The net result reflects the consumer's overlay: a dirty edit's stale base
    /// hit is never returned, and the upserted file's real hits are. Cost is
    /// O(base text search) + O(dirty set scan), never an overlay-wide reindex.
    ///
    /// The overlay scan mirrors the base file-level filtering: each upserted
    /// file is gated by [`current_code_search_keeps_file`] (scope=Code, default
    /// noise policy hiding test/generated files, personal-tooling excluded) so a
    /// dirty test/generated file does not leak hits the base would suppress, and
    /// the per-file scan applies the same `#[cfg(test)]` line suppression,
    /// per-file cap (`DEFAULT_MAX_PER_FILE`), and line truncation. Appended
    /// overlay files are sorted by path for deterministic output (Principle V).
    ///
    /// `// DEFERRED (012 full tier):` a per-overlay trigram index would let the
    /// dirty-file scan use the same accelerated path as the base. Until then the
    /// dirty files are scanned linearly (correct, bounded by the small dirty
    /// set). DOCUMENTED LIMITATION: after the post-filter, `total_matches` is
    /// RECOMPUTED as the sum of the returned files' displayed match lines (each
    /// bounded by `DEFAULT_MAX_PER_FILE`), so it is coherent with `files` but is
    /// NOT the base's pre-cap visible total. Because the merged result differs
    /// from the base result, the base's `overflow_count` and
    /// `suppressed_by_noise` would be STALE; rather than carry misleading base
    /// numbers, the overlay branch sets `overflow_count = 0` (no precise
    /// merged-overflow claim) and `suppressed_by_noise` to the BASE suppression
    /// total PLUS the overlay `#[cfg(test)]` suppressions counted while scanning
    /// the dirty set (the base count still holds for the non-dropped files, so
    /// the zero-hit test-match hint survives a dirty working tree).
    /// Per-consumer derived indices that would make these globally exact are the
    /// deferred work.
    pub fn search_text(
        &self,
        query: Option<&str>,
        terms: Option<&[String]>,
        regex: bool,
        options: &TextSearchOptions,
    ) -> Result<TextSearchResult, TextSearchError> {
        let mut result = search_text_with_options(self.base, query, terms, regex, options)?;

        let Some(deltas) = self.overlay_deltas() else {
            return Ok(result);
        };
        if deltas.is_empty() {
            return Ok(result);
        }

        // (2) Drop base file-results shadowed by ANY live delta (upsert or
        // tombstone): the base content for those paths is stale or removed.
        result.files.retain(|file| !deltas.contains_key(&file.path));

        // (3) Scan each overlay Upsert directly for the same matcher and append
        // its current matches. A Tombstone contributes nothing (file removed).
        //
        // Overlay files are gathered into a vec and SORTED BY PATH before
        // appending so the merged output order is DETERMINISTIC (Principle V/IV);
        // `deltas` is a HashMap whose iteration order is not stable. Each
        // upserted file is first put through the SAME file-level scope+noise gate
        // the base applies (`current_code_search_keeps_file`) so an upserted
        // test/generated/vendor/personal-tooling file does NOT leak hits the base
        // would suppress; then `scan_file_lines` applies the in-file
        // `#[cfg(test)]` suppression, the per-file cap, and line truncation.
        let matcher = overlay_text_matcher(query, terms, regex)?;
        let mut overlay_suppressed = 0usize;
        if let Some(matcher) = matcher {
            let mut appended: Vec<super::search::TextFileMatches> = Vec::new();
            for (path, delta) in deltas {
                let FileDelta::Upsert(file) = delta else {
                    continue;
                };
                // File-level scope+noise gate (mirrors the base's
                // file_matches_text_base_scope + file_hidden_by_search_policy at
                // the default code-search preset).
                if !current_code_search_keeps_file(path, &file.classification) {
                    continue;
                }
                let scan = scan_file_lines(file, &matcher);
                overlay_suppressed += scan.suppressed;
                if !scan.matches.is_empty() {
                    appended.push(super::search::TextFileMatches {
                        path: path.clone(),
                        matches: scan.matches,
                        rendered_lines: None,
                        callers: None,
                    });
                }
            }
            // Deterministic ordering of the appended overlay files.
            appended.sort_by(|a, b| a.path.cmp(&b.path));
            result.files.extend(appended);
        }

        // Recompute `total_matches` to stay COHERENT with the post-filtered
        // `files` set: dropping a base file-result must subtract its matches, and
        // appended overlay scans must add theirs. We recount from the retained +
        // appended `matches` lists rather than incrementally patching the base
        // counter, which would leave it stale after the retain above. NOTE: this
        // makes `total_matches` reflect the displayed match lines (each file's
        // `matches` is bounded by `DEFAULT_MAX_PER_FILE`); it is an honest count
        // of the merged result, not the base's pre-cap visible total. See the
        // DOCUMENTED LIMITATION on this method.
        result.total_matches = result.files.iter().map(|f| f.matches.len()).sum();

        // `overflow_count` and `suppressed_by_noise` from the BASE search
        // described the pre-filter base result; after dropping base files and
        // appending overlay scans they no longer describe the merged result, so
        // carrying the base numbers would be a LIE. We cannot cheaply re-derive a
        // globally exact visible-overflow across the overlay (that is the
        // deferred per-consumer derived index), so we report a COHERENT,
        // honest-but-coarse value instead of stale base numbers:
        //   * overflow_count -> 0 (we do not claim a precise hidden-overflow
        //     count across the merged set);
        //   * suppressed_by_noise -> the BASE suppression total (source-level
        //     `#[cfg(test)]` ranges + whole test files the base counted) PLUS
        //     the overlay `#[cfg(test)]` suppressions we counted while scanning
        //     the dirty set. The base count still describes suppressions in the
        //     files we did NOT drop above (drops are keyed on delta paths, the
        //     only files re-scanned), so adding is coherent — and it keeps the
        //     zero-hit "N match(es) found in test modules" hint from silently
        //     vanishing whenever the working tree is dirty.
        // This keeps every reported field consistent with the result we return.
        result.overflow_count = 0;
        result.suppressed_by_noise = result
            .suppressed_by_noise
            .saturating_add(overlay_suppressed);

        Ok(result)
    }

    /// Reference search served BASE-ONLY + an overlay POST-FILTER over the dirty
    /// set (research D1 sub-decision), mirroring [`search_text`].
    ///
    /// `find_references` depends on the base's repo-wide `reverse_index`, which
    /// the overlay does NOT re-derive (DEFERRED). So we:
    /// 1. collect base references for `name` via `find_references_for_name`;
    /// 2. DROP base hits whose file is a live overlay delta (stale or deleted);
    /// 3. directly scan each overlay `Upsert`'s `references` for `name` and
    ///    append fresh hits for it.
    ///
    /// Returns `(path, ReferenceRecord)` pairs owned by the view's lifetime.
    ///
    /// Like [`search_text`], the overlay scan applies the SAME file-level
    /// scope+noise gate as the base ([`current_code_search_keeps_file`]) so a
    /// dirty test/generated file does not leak references, honors
    /// `include_filtered` (skipping [`is_filtered_name`] references when
    /// `!include_filtered`, mirroring the base), and sorts appended overlay files
    /// by path for deterministic output (Principle V).
    ///
    /// `// DEFERRED (012 full tier):` a per-overlay reverse index would replace
    /// the linear `references` scan of the dirty files. Until then the dirty set
    /// is scanned directly (correct, O(dirty set)). DOCUMENTED LIMITATION: the
    /// overlay scan resolves only the SIMPLE-name match against each upserted
    /// file's `references` (and qualified-name equality); it does not reproduce
    /// the base's alias-map resolution across overlay files. Alias resolution
    /// across dirty files is part of the deferred derived-index work.
    ///
    /// [`search_text`]: IndexView::search_text
    pub fn find_references(
        &self,
        name: &str,
        kind_filter: Option<ReferenceKind>,
        include_filtered: bool,
    ) -> Vec<(String, &'a ReferenceRecord)> {
        let mut out: Vec<(String, &'a ReferenceRecord)> = self
            .base
            .find_references_for_name(name, kind_filter, include_filtered)
            .into_iter()
            .map(|(path, reference)| (path.to_string(), reference))
            .collect();

        let Some(deltas) = self.overlay_deltas() else {
            return out;
        };
        if deltas.is_empty() {
            return out;
        }

        // (2) Drop base hits whose file is dirty (stale or deleted).
        out.retain(|(path, _)| !deltas.contains_key(path));

        // (3) Scan overlay Upserts directly for matching references.
        //
        // Overlay files are gathered and SORTED BY PATH before appending so the
        // merged output order is DETERMINISTIC (Principle V); `deltas` iteration
        // is unordered. Each upserted file is gated by the SAME file-level
        // scope+noise filter as the base (`current_code_search_keeps_file`) so a
        // dirty test/generated/vendor/personal-tooling file does not leak
        // references the base would suppress. We mirror the base's
        // `include_filtered` behavior by skipping `is_filtered_name` references
        // (single-letter generics / language builtins) when `!include_filtered`.
        let is_qualified = name.contains("::") || name.contains('.');
        let mut appended: Vec<(String, &'a ReferenceRecord)> = Vec::new();
        for (path, delta) in deltas {
            let FileDelta::Upsert(file) = delta else {
                continue;
            };
            if !current_code_search_keeps_file(path, &file.classification) {
                continue;
            }
            for reference in &file.references {
                let name_matches = if is_qualified {
                    reference.qualified_name.as_deref() == Some(name)
                } else {
                    reference.name == name
                };
                if !name_matches {
                    continue;
                }
                if let Some(kf) = kind_filter
                    && reference.kind != kf
                {
                    continue;
                }
                // Mirror the base: hide filtered names unless explicitly asked.
                if !include_filtered && is_filtered_name(&reference.name, &file.language) {
                    continue;
                }
                appended.push((path.clone(), reference));
            }
        }
        appended.sort_by(|a, b| a.0.cmp(&b.0));
        out.extend(appended);

        out
    }
}

/// A symbol hit from a single [`IndexView`] search, before project attribution.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ViewSymbolHit {
    pub name: String,
    pub path: String,
    pub kind: String,
    pub line: u32,
    pub tier: SymbolMatchTier,
}

/// Match `filter` (display string or common semantic alias) against a symbol
/// kind. A local mirror of the engine search's `kind_filter_matches` (which is
/// private to `search.rs`); kept minimal and overlay-internal.
fn symbol_kind_matches(filter: &str, kind: &crate::domain::SymbolKind) -> bool {
    if kind.to_string().eq_ignore_ascii_case(filter) {
        return true;
    }
    matches!(
        (filter.to_ascii_lowercase().as_str(), kind),
        ("variable", crate::domain::SymbolKind::Variable)
            | ("function", crate::domain::SymbolKind::Function)
            | ("method", crate::domain::SymbolKind::Method)
            | ("module", crate::domain::SymbolKind::Module)
            | ("constant", crate::domain::SymbolKind::Constant)
    )
}

/// A compiled line matcher used to scan overlay `Upsert` files directly. Mirrors
/// the engine's literal/regex/terms branching at the line level (the overlay
/// post-filter cannot reuse the base's trigram-accelerated path).
enum OverlayTextMatcher {
    /// Any of the literal terms appears in the line (case folded per `fold`).
    Terms { terms: Vec<String>, fold: bool },
    /// The compiled regex matches the line.
    Regex(regex::Regex),
}

impl OverlayTextMatcher {
    fn is_match(&self, line: &str) -> bool {
        match self {
            Self::Terms { terms, fold } => {
                if *fold {
                    let line_lower = line.to_lowercase();
                    terms.iter().any(|t| line_lower.contains(&t.to_lowercase()))
                } else {
                    terms.iter().any(|t| line.contains(t))
                }
            }
            Self::Regex(re) => re.is_match(line),
        }
    }
}

/// Build the overlay line matcher from the same `(query, terms, regex)` inputs
/// the engine `search_text` takes. Returns `Ok(None)` when there is nothing to
/// match (empty query/terms) so the caller skips the dirty-set scan.
fn overlay_text_matcher(
    query: Option<&str>,
    terms: Option<&[String]>,
    regex: bool,
) -> Result<Option<OverlayTextMatcher>, TextSearchError> {
    if regex {
        let pattern = query
            .map(str::trim)
            .filter(|text| !text.is_empty())
            .unwrap_or("");
        if pattern.is_empty() {
            return Err(TextSearchError::EmptyRegexQuery);
        }
        let re = regex::RegexBuilder::new(pattern)
            .case_insensitive(true)
            .build()
            .map_err(|error| TextSearchError::InvalidRegex {
                pattern: pattern.to_string(),
                error: error.to_string(),
            })?;
        return Ok(Some(OverlayTextMatcher::Regex(re)));
    }

    let collected: Vec<String> = match terms {
        Some(raw) if !raw.is_empty() => raw
            .iter()
            .map(|t| t.trim())
            .filter(|t| !t.is_empty())
            .map(ToOwned::to_owned)
            .collect(),
        _ => query
            .map(str::trim)
            .filter(|text| !text.is_empty())
            .map(|text| vec![text.to_string()])
            .unwrap_or_default(),
    };
    if collected.is_empty() {
        return Ok(None);
    }
    Ok(Some(OverlayTextMatcher::Terms {
        terms: collected,
        // Literal search is case-insensitive by default in the engine path
        // (`case_sensitive = regex` => false for literals).
        fold: true,
    }))
}

/// Result of scanning one overlay `Upsert` file for the matcher: the bounded,
/// truncated display matches plus the count of matches suppressed by the
/// in-file Rust `#[cfg(test)]` noise filter.
struct OverlayFileScan {
    matches: Vec<super::search::TextLineMatch>,
    suppressed: usize,
}

/// Scan an overlay file's content line by line, mirroring the base
/// `collect_text_matches` semantics for an upserted dirty file:
/// * line numbers are 1-based, trailing `\r` trimmed;
/// * matches inside Rust `#[cfg(test)]`/`mod tests` ranges are suppressed (and
///   counted) under the default code-search noise policy;
/// * at most [`DEFAULT_MAX_PER_FILE`] visible match lines are RETAINED, each
///   passed through [`truncate_display_line`] so a single huge line cannot
///   detonate the result.
///
/// File-level scope/noise gating (test/generated/vendor/personal-tooling files)
/// is the CALLER's responsibility via [`current_code_search_keeps_file`]; this
/// function assumes the file already passed that gate and only applies the
/// in-file (`#[cfg(test)]`) line suppression + per-file cap + truncation.
fn scan_file_lines(file: &IndexedFile, matcher: &OverlayTextMatcher) -> OverlayFileScan {
    // Rust test-module line ranges, suppressed under the default code-search
    // noise policy (which excludes tests). Non-Rust files have none.
    let test_ranges: Vec<(u32, u32)> = if file.language == crate::domain::LanguageId::Rust {
        compute_test_ranges(file)
    } else {
        Vec::new()
    };

    let content = String::from_utf8_lossy(&file.content);
    let mut matches = Vec::new();
    let mut suppressed = 0usize;
    for (line_idx, line) in content.lines().enumerate() {
        let line = line.trim_end_matches('\r');
        if !matcher.is_match(line) {
            continue;
        }
        // Suppress (and count) matches inside Rust #[cfg(test)] modules.
        if !test_ranges.is_empty() {
            let line_num = line_idx as u32;
            if test_ranges
                .iter()
                .any(|&(start, end)| line_num >= start && line_num <= end)
            {
                suppressed += 1;
                continue;
            }
        }
        // Cap the RETAINED display matches at the base's per-file limit, while
        // still counting (above) every suppressed line. We do not need a visible
        // overflow count here because the overlay branch reports overflow as
        // "unknown across overlay" (see search_text), but bounding the retained
        // lines is required to match base output size.
        if matches.len() < DEFAULT_MAX_PER_FILE {
            matches.push(super::search::TextLineMatch {
                line_number: line_idx + 1,
                line: truncate_display_line(line),
                enclosing_symbol: None,
            });
        }
    }
    OverlayFileScan {
        matches,
        suppressed,
    }
}

/// Selects which projects in a [`WorkingSet`] a cross-project query targets
/// (FR-004 / SC-001).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Targets {
    /// A single project by id.
    One(String),
    /// An explicit subset of project ids.
    Subset(Vec<String>),
    /// Every project in the working set.
    All,
}

impl Targets {
    /// Whether `project_id` is selected by these targets.
    fn selects(&self, project_id: &str) -> bool {
        match self {
            Self::One(id) => id == project_id,
            Self::Subset(ids) => ids.iter().any(|id| id == project_id),
            Self::All => true,
        }
    }
}

/// A query hit tagged with the project it came from (FR-004 / SC-001). Generic
/// over the per-view hit payload so symbol/text/reference queries can all attach
/// source attribution uniformly.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProjectHit<T> {
    /// The id of the working-set project this hit came from.
    pub project_id: String,
    /// The underlying per-view hit.
    pub hit: T,
}

/// One project in a consumer's [`WorkingSet`]: a shared base + a private overlay.
///
/// The `base` is an `Arc<IndexBase>` so two entries (here or in another
/// consumer's working set) at the same `(canonical_root, commit)` share ONE
/// allocation (SC-002). The `overlay` is owned by exactly one entry and is never
/// shared (SC-003 — isolation by ownership).
#[derive(Clone)]
pub struct WorkingSetEntry {
    /// Stable per-consumer project identity (used for hit attribution + targeting).
    pub project_id: String,
    /// The shared immutable base (shared by `Arc` across consumers, SC-002).
    pub base: Arc<IndexBase>,
    /// This consumer's private copy-on-write overlay over `base`.
    pub overlay: Overlay,
}

/// A single consumer's set of open projects (data-model `WorkingSet`).
///
/// Supports add/remove/get/iter and cross-project query with source-attributed
/// results (FR-004 / SC-001). Mutations affect ONLY this consumer's working set
/// (FR-006). Two consumers' working sets that hold the same `(canonical_root,
/// commit)` base MUST be passed the SAME `Arc<IndexBase>` by the caller so the
/// base allocation is shared (SC-002); see [`WorkingSet::add`].
#[derive(Clone, Default)]
pub struct WorkingSet {
    entries: Vec<WorkingSetEntry>,
}

impl WorkingSet {
    /// An empty working set.
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }

    /// Add (or replace) a project keyed by `project_id`, attaching a fresh empty
    /// overlay fenced to `base`.
    ///
    /// SC-002 CONTRACT: the CALLER owns base sharing. To share one `IndexBase`
    /// allocation across two projects (in this set or across consumers), pass a
    /// clone of the SAME `Arc<IndexBase>` (`Arc::clone`) to each `add`. This
    /// method stores the `Arc` as given; it never deep-copies the base. Adding
    /// the same `(canonical_root, commit)` via distinct `Arc`s would NOT share —
    /// that is a caller error the registry layer (Phase 3) is responsible for
    /// avoiding by interning bases by `BaseKey`. See
    /// [`WorkingSet::shares_base_with`] for an assertion helper.
    ///
    /// Re-adding an existing `project_id` replaces its entry (base + a fresh
    /// overlay), discarding the old overlay's deltas.
    pub fn add(&mut self, project_id: impl Into<String>, base: Arc<IndexBase>) {
        let project_id = project_id.into();
        let overlay = Overlay::fresh(&base);
        let entry = WorkingSetEntry {
            project_id: project_id.clone(),
            base,
            overlay,
        };
        if let Some(slot) = self.entries.iter_mut().find(|e| e.project_id == project_id) {
            *slot = entry;
        } else {
            self.entries.push(entry);
        }
    }

    /// Remove a project by id. Returns the removed entry if present.
    pub fn remove(&mut self, project_id: &str) -> Option<WorkingSetEntry> {
        let pos = self
            .entries
            .iter()
            .position(|e| e.project_id == project_id)?;
        Some(self.entries.remove(pos))
    }

    /// Borrow a project entry by id.
    pub fn get(&self, project_id: &str) -> Option<&WorkingSetEntry> {
        self.entries.iter().find(|e| e.project_id == project_id)
    }

    /// Mutably borrow a project entry by id (e.g. to record overlay deltas).
    pub fn get_mut(&mut self, project_id: &str) -> Option<&mut WorkingSetEntry> {
        self.entries.iter_mut().find(|e| e.project_id == project_id)
    }

    /// Iterate the working-set entries in insertion order.
    pub fn iter(&self) -> impl Iterator<Item = &WorkingSetEntry> {
        self.entries.iter()
    }

    /// Number of open projects.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the working set is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// SC-002 assertion helper: do two projects in THIS working set share one
    /// `IndexBase` allocation (`Arc::ptr_eq`)? `false` if either id is absent.
    /// The registry layer relies on this to verify base interning.
    pub fn shares_base_with(&self, project_a: &str, project_b: &str) -> bool {
        match (self.get(project_a), self.get(project_b)) {
            (Some(a), Some(b)) => Arc::ptr_eq(&a.base, &b.base),
            _ => false,
        }
    }

    /// Build the [`IndexView`] for one entry (base + its private overlay).
    ///
    /// Returns `Err(StaleOverlay)` if the entry's overlay is no longer fenced to
    /// its base (it must rebase first; never serves stale).
    fn view_for<'a>(entry: &'a WorkingSetEntry) -> Result<IndexView<'a>, StaleOverlay> {
        IndexView::new(&entry.base, Some(&entry.overlay))
    }

    /// Cross-project symbol search (FR-004 / SC-001): for each TARGETED entry,
    /// build its [`IndexView`], run the overlay-aware [`IndexView::search_symbols`],
    /// and tag every hit with its source `project_id`.
    ///
    /// Entries whose overlay is stale are skipped (cannot serve stale); the
    /// caller is expected to rebase before querying. Hits are returned grouped
    /// by project in working-set order (each project's hits are internally
    /// tier-sorted by the view search).
    pub fn search_symbols(
        &self,
        targets: &Targets,
        query: &str,
        kind_filter: Option<&str>,
        options: &SymbolSearchOptions,
    ) -> Vec<ProjectHit<ViewSymbolHit>> {
        let mut out = Vec::new();
        for entry in self
            .entries
            .iter()
            .filter(|e| targets.selects(&e.project_id))
        {
            let Ok(view) = Self::view_for(entry) else {
                continue;
            };
            for hit in view.search_symbols(query, kind_filter, options) {
                out.push(ProjectHit {
                    project_id: entry.project_id.clone(),
                    hit,
                });
            }
        }
        out
    }

    /// Cross-project text search (FR-004 / SC-001): per targeted entry, run the
    /// overlay-post-filtered [`IndexView::search_text`] and tag results by
    /// project. A per-project text-search error is propagated (the whole query
    /// fails) so the caller sees an honest error, not a silent partial result.
    pub fn search_text(
        &self,
        targets: &Targets,
        query: Option<&str>,
        terms: Option<&[String]>,
        regex: bool,
        options: &TextSearchOptions,
    ) -> Result<Vec<ProjectHit<TextSearchResult>>, TextSearchError> {
        let mut out = Vec::new();
        for entry in self
            .entries
            .iter()
            .filter(|e| targets.selects(&e.project_id))
        {
            let Ok(view) = Self::view_for(entry) else {
                continue;
            };
            let result = view.search_text(query, terms, regex, options)?;
            out.push(ProjectHit {
                project_id: entry.project_id.clone(),
                hit: result,
            });
        }
        Ok(out)
    }

    /// Cross-project file search (outstanding-work Task 4): per targeted
    /// entry, run the EXISTING per-project ranked file search
    /// ([`LiveIndex::capture_search_files_view_with_noise`]) on the entry's
    /// base index and tag each ranked hit by project. Plain fuzzy-query mode
    /// only — resolve/coupling modes stay single-project. Each project's hits
    /// arrive internally rank-ordered and `per_project_limit`-bounded; the
    /// caller applies the ONE global cross-project cap after merging.
    ///
    /// File-path search reads only the file map (overlays carry content
    /// deltas, not path membership), so the base index is the honest source.
    pub fn search_files(
        &self,
        targets: &Targets,
        query: &str,
        per_project_limit: usize,
        include_vendor: bool,
        include_personal_tooling: bool,
        path_scope: &PathScope,
    ) -> Vec<ProjectHit<SearchFilesHit>> {
        let mut out = Vec::new();
        for entry in self
            .entries
            .iter()
            .filter(|e| targets.selects(&e.project_id))
        {
            let view = entry.base.index.capture_search_files_view_with_noise(
                query,
                per_project_limit,
                None,
                None,
                include_vendor,
                include_personal_tooling,
                path_scope,
            );
            if let SearchFilesView::Found { hits, .. } = view {
                for hit in hits {
                    out.push(ProjectHit {
                        project_id: entry.project_id.clone(),
                        hit,
                    });
                }
            }
        }
        out
    }

    /// Cross-project reference search (FR-004 / SC-001): per targeted entry, run
    /// the overlay-post-filtered [`IndexView::find_references`] and tag each
    /// `(path, ReferenceRecord)` hit by project.
    pub fn find_references(
        &self,
        targets: &Targets,
        name: &str,
        kind_filter: Option<ReferenceKind>,
        include_filtered: bool,
    ) -> Vec<ProjectHit<(String, ReferenceRecord)>> {
        let mut out = Vec::new();
        for entry in self
            .entries
            .iter()
            .filter(|e| targets.selects(&e.project_id))
        {
            let Ok(view) = Self::view_for(entry) else {
                continue;
            };
            for (path, reference) in view.find_references(name, kind_filter, include_filtered) {
                out.push(ProjectHit {
                    project_id: entry.project_id.clone(),
                    hit: (path, reference.clone()),
                });
            }
        }
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::{FileClassification, LanguageId};
    use crate::live_index::store::{IndexedFile, LiveIndex, ParseStatus};
    use std::time::Instant;

    /// Build a minimal synthetic `IndexedFile` for spike tests. All fields are
    /// `pub`; content is the load-bearing bit we assert resolution on.
    fn make_file(path: &str, content: &str) -> IndexedFile {
        IndexedFile {
            relative_path: path.to_string(),
            language: LanguageId::Rust,
            classification: FileClassification::for_code_path(path),
            content: content.as_bytes().to_vec(),
            symbols: Vec::new(),
            parse_status: ParseStatus::Parsed,
            parse_diagnostic: None,
            byte_len: content.len() as u64,
            content_hash: format!("h:{}", content.len()),
            references: Vec::new(),
            alias_map: HashMap::new(),
            mtime_secs: 0,
        }
    }

    /// Build a synthetic base `LiveIndex` of `n` files: `f{0}.rs .. f{n-1}.rs`.
    /// Uses sibling (`super`) access to `empty_live_index()` + the `files` map —
    /// engine-internal, no server/network deps (compiles under `embed`).
    fn synthetic_index(n: usize) -> LiveIndex {
        let mut idx = LiveIndex::empty_live_index();
        idx.is_empty = false;
        idx.loaded_at = Instant::now();
        let mut files: HashMap<String, Arc<IndexedFile>> = HashMap::with_capacity(n);
        for i in 0..n {
            let path = format!("f{i}.rs");
            let file = make_file(&path, &format!("fn f{i}() {{}}"));
            files.insert(path, Arc::new(file));
        }
        idx.files = files;
        idx
    }

    fn base_key(commit: &str) -> BaseKey {
        BaseKey::new("/repo/root", CommitId::Sha(commit.to_string()))
    }

    // ── Proof 1 — SC-002 shared base, no second files-map clone ──────────────
    #[test]
    fn proof1_shared_base_no_clone() {
        let live = synthetic_index(100);
        // Snapshot the strong_count of an inner file Arc BEFORE wrapping.
        let probe = Arc::clone(live.files.get("f0.rs").expect("f0"));
        let inner_count_baseline = Arc::strong_count(&probe);

        let base = Arc::new(IndexBase::new(base_key("c0"), Arc::new(live), 1));

        // Consumer #1 attaches an overlay.
        let overlay_1 = Overlay::fresh(&base);
        // Consumer #2 attaches an overlay over the SAME Arc<IndexBase>.
        let base_2 = Arc::clone(&base);
        let overlay_2 = Overlay::fresh(&base_2);

        // SC-002: the two bases are the SAME allocation.
        assert!(
            Arc::ptr_eq(&base, &base_2),
            "consumers must share one IndexBase allocation"
        );
        // The shared LiveIndex is also the same allocation.
        assert!(Arc::ptr_eq(&base.index, &base_2.index));

        // Building views for both consumers must NOT clone the base files map.
        let _view_1 = IndexView::new(&base, Some(&overlay_1)).expect("v1");
        let _view_2 = IndexView::new(&base_2, Some(&overlay_2)).expect("v2");

        // The inner per-file Arc strong_count must NOT have doubled by adding a
        // second consumer: no second `files` map was cloned (only `&LiveIndex`
        // borrows). The only extra ref to `probe` is `probe` itself.
        let inner_count_after = Arc::strong_count(&probe);
        assert_eq!(
            inner_count_after, inner_count_baseline,
            "adding consumer #2 must not clone the base files map \
             (inner file Arc strong_count must not increase): {inner_count_baseline} -> {inner_count_after}"
        );
    }

    // ── Proof 3 — no forced reload (ArcSwap immutability) ────────────────────
    #[test]
    fn proof3_no_forced_reload() {
        let live = synthetic_index(3);
        let base_v1 = Arc::new(IndexBase::new(base_key("c0"), Arc::new(live), 1));

        // Consumer B holds a view over the v1 snapshot.
        let overlay_b = Overlay::fresh(&base_v1);
        let view_b = IndexView::new(&base_v1, Some(&overlay_b)).expect("B view v1");
        assert_eq!(view_b.get_file("f0.rs").unwrap().content, b"fn f0() {}");

        // Consumer A reindexes -> a NEW IndexBase (new generation) with mutated
        // content. The old Arc<LiveIndex> is immutable and untouched.
        let mut live_v2 = synthetic_index(3);
        // Sibling access: mutate the v2 file map to simulate A's reindex.
        live_v2.files.insert(
            "f0.rs".to_string(),
            Arc::new(make_file("f0.rs", "REINDEXED")),
        );
        let _base_v2 = Arc::new(IndexBase::new(base_key("c1"), Arc::new(live_v2), 2));

        // B's existing view over the PRIOR snapshot still reads the old content:
        // ArcSwap immutability — no forced reload, no interruption.
        assert_eq!(
            view_b.get_file("f0.rs").unwrap().content,
            b"fn f0() {}",
            "B's view over the prior snapshot must be unaffected by A's reindex"
        );
    }

    // ── Proof 4 — stale fence ────────────────────────────────────────────────
    #[test]
    fn proof4_stale_fence() {
        let live = synthetic_index(2);
        let base_v1 = IndexBase::new(base_key("c0"), Arc::new(live), 1);

        // Overlay derived against generation 1.
        let overlay = Overlay::fresh(&base_v1);
        assert!(overlay.is_valid_against(&base_v1));

        // Base advances to generation 2 (new commit) -> SAME index payload but
        // bumped generation. The overlay is now stale.
        let base_v2 = IndexBase::new(
            base_key("c1"),
            Arc::clone(&base_v1.index),
            base_v1.base_generation + 1,
        );

        // IndexView is not Debug (it borrows &LiveIndex), so match explicitly
        // rather than unwrap_err().
        match IndexView::new(&base_v2, Some(&overlay)) {
            Err(err) => assert_eq!(
                err,
                StaleOverlay {
                    base_generation: 2,
                    overlay_generation: 1
                },
                "reading a gen-1 overlay against a gen-2 base must be StaleOverlay"
            ),
            Ok(_) => panic!("expected StaleOverlay, got a valid view"),
        }
        assert!(!overlay.is_valid_against(&base_v2));
    }

    // ─────────────────────────────────────────────────────────────────────────
    // WorkingSet + cross-project query (Phase 2)
    // ─────────────────────────────────────────────────────────────────────────

    use crate::domain::{SymbolKind, SymbolRecord};

    /// Build a synthetic indexed file carrying ONE symbol named `symbol_name`
    /// (so symbol search has something to match) and the given content.
    fn make_file_with_symbol(path: &str, symbol_name: &str, content: &str) -> IndexedFile {
        let mut file = make_file(path, content);
        file.symbols = vec![SymbolRecord {
            name: symbol_name.to_string(),
            kind: SymbolKind::Function,
            depth: 0,
            sort_order: 0,
            byte_range: (0, content.len() as u32),
            line_range: (0, 0),
            doc_byte_range: None,
            item_byte_range: None,
        }];
        file
    }

    /// Build a base `IndexBase` whose single file `f.rs` defines a function
    /// `symbol_name` and contains `content` (used for cross-project search).
    fn base_with_symbol(
        root: &str,
        commit: &str,
        symbol_name: &str,
        content: &str,
    ) -> Arc<IndexBase> {
        let mut idx = LiveIndex::empty_live_index();
        idx.is_empty = false;
        idx.loaded_at = Instant::now();
        let mut files: HashMap<String, Arc<IndexedFile>> = HashMap::new();
        files.insert(
            "f.rs".to_string(),
            Arc::new(make_file_with_symbol("f.rs", symbol_name, content)),
        );
        idx.trigram_index = crate::live_index::trigram::TrigramIndex::build_from_files(&files);
        idx.files = files;
        idx.rebuild_reverse_index();
        Arc::new(IndexBase::new(
            BaseKey::new(root, CommitId::Sha(commit.to_string())),
            Arc::new(idx),
            1,
        ))
    }

    #[test]
    fn working_set_add_remove_get() {
        let mut ws = WorkingSet::new();
        assert!(ws.is_empty());

        let base_a = base_with_symbol("/a", "c0", "alpha_fn", "fn alpha_fn() {}");
        let base_b = base_with_symbol("/b", "c0", "beta_fn", "fn beta_fn() {}");
        ws.add("A", Arc::clone(&base_a));
        ws.add("B", Arc::clone(&base_b));

        assert_eq!(ws.len(), 2);
        assert!(ws.get("A").is_some());
        assert!(ws.get("B").is_some());
        assert!(ws.get("missing").is_none());

        // Remove returns the entry; get then misses.
        let removed = ws.remove("A").expect("A present");
        assert_eq!(removed.project_id, "A");
        assert!(ws.get("A").is_none());
        assert_eq!(ws.len(), 1);

        // Removing an absent id is a clean None.
        assert!(ws.remove("A").is_none());

        // iter yields the surviving entry.
        let ids: Vec<&str> = ws.iter().map(|e| e.project_id.as_str()).collect();
        assert_eq!(ids, vec!["B"]);
    }

    // ── SC-001: cross-project search returns source-attributed hits ───────────
    #[test]
    fn cross_project_search_is_source_attributed() {
        let mut ws = WorkingSet::new();
        // Three projects, each defining a function whose name contains "shared".
        ws.add(
            "A",
            base_with_symbol("/a", "c0", "shared_a", "fn shared_a() {}"),
        );
        ws.add(
            "B",
            base_with_symbol("/b", "c0", "shared_b", "fn shared_b() {}"),
        );
        ws.add(
            "C",
            base_with_symbol("/c", "c0", "shared_c", "fn shared_c() {}"),
        );

        let hits = ws.search_symbols(
            &Targets::All,
            "shared",
            None,
            &SymbolSearchOptions::for_current_code_search(usize::MAX),
        );
        assert_eq!(hits.len(), 3, "one hit per project");

        // Every hit is attributed to its source project, and the project's own
        // symbol is the one returned (no cross-leak).
        let mut by_project: HashMap<&str, &str> = HashMap::new();
        for h in &hits {
            by_project.insert(h.project_id.as_str(), h.hit.name.as_str());
        }
        assert_eq!(by_project.get("A"), Some(&"shared_a"));
        assert_eq!(by_project.get("B"), Some(&"shared_b"));
        assert_eq!(by_project.get("C"), Some(&"shared_c"));
    }

    // ── subset / single targeting ─────────────────────────────────────────────
    #[test]
    fn cross_project_search_respects_targets() {
        let mut ws = WorkingSet::new();
        ws.add(
            "A",
            base_with_symbol("/a", "c0", "shared_a", "fn shared_a() {}"),
        );
        ws.add(
            "B",
            base_with_symbol("/b", "c0", "shared_b", "fn shared_b() {}"),
        );
        ws.add(
            "C",
            base_with_symbol("/c", "c0", "shared_c", "fn shared_c() {}"),
        );

        // Single.
        let one = ws.search_symbols(
            &Targets::One("B".to_string()),
            "shared",
            None,
            &SymbolSearchOptions::for_current_code_search(usize::MAX),
        );
        assert_eq!(one.len(), 1);
        assert_eq!(one[0].project_id, "B");
        assert_eq!(one[0].hit.name, "shared_b");

        // Subset.
        let subset = ws.search_symbols(
            &Targets::Subset(vec!["A".to_string(), "C".to_string()]),
            "shared",
            None,
            &SymbolSearchOptions::for_current_code_search(usize::MAX),
        );
        let projects: std::collections::BTreeSet<&str> =
            subset.iter().map(|h| h.project_id.as_str()).collect();
        assert_eq!(
            projects,
            ["A", "C"]
                .into_iter()
                .collect::<std::collections::BTreeSet<_>>()
        );

        // A target naming a project not in the set yields no hits (the caller
        // layer turns "project not open" into an explicit error; the primitive
        // simply does not match it).
        let none = ws.search_symbols(
            &Targets::One("Z".to_string()),
            "shared",
            None,
            &SymbolSearchOptions::for_current_code_search(usize::MAX),
        );
        assert!(none.is_empty());
    }

    // ── SC-002: two entries on the same base share ONE Arc (ptr_eq) ───────────
    #[test]
    fn working_set_shares_base_arc() {
        let mut ws = WorkingSet::new();
        // Caller shares the SAME Arc<IndexBase> for two projects (e.g. two
        // logical views of one canonical_root+commit).
        let shared = base_with_symbol("/repo", "c0", "f", "fn f() {}");
        ws.add("view1", Arc::clone(&shared));
        ws.add("view2", Arc::clone(&shared));

        let a = ws.get("view1").unwrap();
        let b = ws.get("view2").unwrap();
        assert!(
            Arc::ptr_eq(&a.base, &b.base),
            "two entries on the same shared Arc<IndexBase> must be one allocation (SC-002)"
        );
        assert!(Arc::ptr_eq(&a.base.index, &b.base.index));
        // The helper agrees.
        assert!(ws.shares_base_with("view1", "view2"));

        // A distinct base for a different project does NOT share.
        ws.add("other", base_with_symbol("/other", "c0", "g", "fn g() {}"));
        assert!(!ws.shares_base_with("view1", "other"));
    }

    // ── cross-project text query is source-attributed ────────────────────────
    #[test]
    fn cross_project_text_search_attribution() {
        let mut ws = WorkingSet::new();
        ws.add("A", base_with_symbol("/a", "c0", "f", "let NEEDLE = 1;"));
        ws.add("B", base_with_symbol("/b", "c0", "g", "let other = 2;"));
        ws.add("C", base_with_symbol("/c", "c0", "h", "let NEEDLE = 3;"));

        let results = ws
            .search_text(
                &Targets::All,
                Some("NEEDLE"),
                None,
                false,
                &TextSearchOptions::for_current_code_search(),
            )
            .expect("cross-project text search");
        // Only projects whose content has NEEDLE produce non-empty results, but
        // every targeted project yields a (possibly empty) attributed result.
        let with_matches: Vec<&str> = results
            .iter()
            .filter(|r| r.hit.total_matches > 0)
            .map(|r| r.project_id.as_str())
            .collect();
        assert_eq!(with_matches, vec!["A", "C"]);
    }

    // ── stale-overlay entry is skipped by the working-set query ───────────────
    #[test]
    fn working_set_skips_stale_overlay_entry() {
        let mut ws = WorkingSet::new();
        ws.add(
            "A",
            base_with_symbol("/a", "c0", "shared_a", "fn shared_a() {}"),
        );
        // Forcibly desync A's overlay fence (simulating a base advance without a
        // rebase). The query must SKIP it (never serve stale) rather than panic.
        ws.get_mut("A").unwrap().overlay.base_generation = 999;

        let hits = ws.search_symbols(
            &Targets::All,
            "shared",
            None,
            &SymbolSearchOptions::for_current_code_search(usize::MAX),
        );
        assert!(
            hits.is_empty(),
            "a stale-overlay entry must be skipped, not served"
        );
    }

    /// Build a base from explicit (path, language, symbol_name) tuples, each file
    /// defining one function named `symbol_name`. Used to prove the cross-project
    /// search HONORS caller options (path scope, language, result_limit) on the
    /// empty-overlay path (B1 / D11 + D14).
    fn base_with_files(
        root: &str,
        commit: &str,
        files: &[(&str, LanguageId, &str)],
    ) -> Arc<IndexBase> {
        let mut idx = LiveIndex::empty_live_index();
        idx.is_empty = false;
        idx.loaded_at = Instant::now();
        let mut map: HashMap<String, Arc<IndexedFile>> = HashMap::new();
        for (path, lang, sym) in files {
            let mut file = make_file_with_symbol(path, sym, &format!("fn {sym}() {{}}"));
            file.language = *lang;
            map.insert((*path).to_string(), Arc::new(file));
        }
        idx.trigram_index = crate::live_index::trigram::TrigramIndex::build_from_files(&map);
        idx.files = map;
        idx.rebuild_reverse_index();
        Arc::new(IndexBase::new(
            BaseKey::new(root, CommitId::Sha(commit.to_string())),
            Arc::new(idx),
            1,
        ))
    }

    // ── B1: cross-project search HONORS caller scoping + limit (D11 + D14) ─────
    // These options were previously LOUDLY REFUSED at the daemon guard; now they
    // are threaded through the engine's option-honoring search.
    #[test]
    fn cross_project_search_honors_scoping_options() {
        use crate::live_index::search::PathScope;

        let mut ws = WorkingSet::new();
        // One project; three files all defining `widget`: two Rust (src/, other/)
        // and one Python under src/.
        ws.add(
            "A",
            base_with_files(
                "/a",
                "c0",
                &[
                    ("src/keep.rs", LanguageId::Rust, "widget"),
                    ("other/skip.rs", LanguageId::Rust, "widget"),
                    ("src/also.py", LanguageId::Python, "widget"),
                ],
            ),
        );

        // path_scope = src/ -> the other/ file is EXCLUDED (D11 path scoping).
        let mut scoped = SymbolSearchOptions::for_current_code_search(usize::MAX);
        scoped.path_scope = PathScope::prefix("src");
        let hits = ws.search_symbols(&Targets::All, "widget", None, &scoped);
        let paths: std::collections::BTreeSet<&str> =
            hits.iter().map(|h| h.hit.path.as_str()).collect();
        assert!(
            paths.contains("src/keep.rs") && paths.contains("src/also.py"),
            "src/-scoped search must include the src/ hits: {paths:?}"
        );
        assert!(
            !paths.contains("other/skip.rs"),
            "src/-scoped search must EXCLUDE other/ hits (path scoping honored): {paths:?}"
        );

        // language = Rust -> the Python file is EXCLUDED (D11 language scoping).
        let mut rust_only = SymbolSearchOptions::for_current_code_search(usize::MAX);
        rust_only.language_filter = Some(LanguageId::Rust);
        let rust_hits = ws.search_symbols(&Targets::All, "widget", None, &rust_only);
        let rust_paths: std::collections::BTreeSet<&str> =
            rust_hits.iter().map(|h| h.hit.path.as_str()).collect();
        assert!(
            rust_paths.contains("src/keep.rs") && rust_paths.contains("other/skip.rs"),
            "Rust-filtered search keeps the Rust files: {rust_paths:?}"
        );
        assert!(
            !rust_paths.contains("src/also.py"),
            "Rust-filtered search must EXCLUDE the Python file (language scoping honored): {rust_paths:?}"
        );

        // result_limit = 1 -> the per-project hits are bounded + tier-ranked, not
        // an unbounded usize::MAX dump (D14).
        let bounded = SymbolSearchOptions::for_current_code_search(1);
        let bounded_hits = ws.search_symbols(&Targets::All, "widget", None, &bounded);
        assert_eq!(
            bounded_hits.len(),
            1,
            "result_limit=1 bounds the per-project hits (D14): got {}",
            bounded_hits.len()
        );
    }

    // ── Regression — dirty-tree overlay must PRESERVE the base's test-match
    //    suppression count, else the zero-hit "N match(es) found in test modules"
    //    hint silently vanishes whenever the working tree is dirty (finding #3).
    #[test]
    fn overlay_preserves_base_test_suppression_count() {
        // Base: one Rust source file whose ONLY `needle` match lives inside a
        // `#[cfg(test)] mod tests` block. The base scans it (file is not
        // test-classified), suppresses the in-`cfg(test)` line, and reports
        // suppressed_by_noise = 1 with zero visible source hits.
        let content = "fn real() {}\n#[cfg(test)]\nmod tests {\n    let needle = 1;\n}\n";
        let mut lib = make_file("src/lib.rs", content);
        lib.symbols = vec![SymbolRecord {
            name: "tests".to_string(),
            kind: SymbolKind::Module,
            depth: 0,
            sort_order: 0,
            byte_range: (0, content.len() as u32),
            line_range: (1, 4),
            doc_byte_range: None,
            item_byte_range: None,
        }];
        let mut map: HashMap<String, Arc<IndexedFile>> = HashMap::new();
        map.insert("src/lib.rs".to_string(), Arc::new(lib));
        let mut idx = LiveIndex::empty_live_index();
        idx.is_empty = false;
        idx.loaded_at = Instant::now();
        idx.trigram_index = crate::live_index::trigram::TrigramIndex::build_from_files(&map);
        idx.files = map;
        let base = Arc::new(IndexBase::new(base_key("c0"), Arc::new(idx), 1));
        let opts = TextSearchOptions::for_current_code_search();

        // Sanity: the base-only path already records the suppression.
        let base_view = IndexView::new(&base, None).expect("base view");
        let base_result = base_view
            .search_text(Some("needle"), None, false, &opts)
            .expect("base search");
        assert!(
            base_result.files.is_empty(),
            "no visible source hits in base"
        );
        assert_eq!(
            base_result.suppressed_by_noise, 1,
            "base must count the #[cfg(test)] match as suppressed"
        );

        // Overlay: an unrelated dirty upsert with NO `needle` makes `deltas`
        // non-empty, forcing the overlay merge path — which previously OVERWROTE
        // `suppressed_by_noise` with the (zero) overlay-only count.
        let mut overlay = Overlay::fresh(&base);
        overlay.deltas.insert(
            "src/other.rs".to_string(),
            FileDelta::Upsert(Arc::new(make_file("src/other.rs", "fn other() {}\n"))),
        );
        let view = IndexView::new(&base, Some(&overlay)).expect("overlay view");
        let result = view
            .search_text(Some("needle"), None, false, &opts)
            .expect("overlay search");

        assert!(
            result.files.is_empty(),
            "still no visible source hits after the overlay merge"
        );
        assert!(
            result.suppressed_by_noise >= 1,
            "dirty-tree overlay must preserve the base test-match suppression count, got {}",
            result.suppressed_by_noise
        );
    }

    // ── US2 (018): overlay-path browse ranks by importance too (T014) ─────────
    #[test]
    fn overlay_browse_ranks_referenced_symbol_first() {
        // Base file defines a heavily-referenced function plus generic short
        // names; the base reverse_index gives the referenced symbol its weight.
        let content = "fn important_handler() {}\nfn add() {}\nfn get() {}\n";
        let mut lib = make_file("src/lib.rs", content);
        let mk = |name: &str, line: u32| SymbolRecord {
            name: name.to_string(),
            kind: SymbolKind::Function,
            depth: 0,
            sort_order: 0,
            byte_range: (0, 0),
            line_range: (line, line),
            doc_byte_range: None,
            item_byte_range: None,
        };
        lib.symbols = vec![mk("important_handler", 0), mk("add", 1), mk("get", 2)];
        let mut map: HashMap<String, Arc<IndexedFile>> = HashMap::new();
        map.insert("src/lib.rs".to_string(), Arc::new(lib));
        let mut idx = LiveIndex::empty_live_index();
        idx.is_empty = false;
        idx.loaded_at = Instant::now();
        idx.trigram_index = crate::live_index::trigram::TrigramIndex::build_from_files(&map);
        idx.files = map;
        idx.reverse_index.insert(
            "important_handler".to_string(),
            (0..9u32)
                .map(|i| crate::live_index::store::ReferenceLocation {
                    file_path: "src/lib.rs".to_string(),
                    reference_idx: i,
                })
                .collect(),
        );
        let base = Arc::new(IndexBase::new(base_key("c0"), Arc::new(idx), 1));

        // A dirty delta forces the overlay (with-deltas) branch, not the
        // engine-delegating no-delta path.
        let mut overlay = Overlay::fresh(&base);
        overlay.deltas.insert(
            "src/other.rs".to_string(),
            FileDelta::Upsert(Arc::new(make_file("src/other.rs", "fn other() {}\n"))),
        );
        let view = IndexView::new(&base, Some(&overlay)).expect("overlay view");

        // Browse: empty query + kind scope.
        let opts = SymbolSearchOptions::for_current_code_search(usize::MAX);
        let hits = view.search_symbols("", Some("fn"), &opts);
        let names: Vec<&str> = hits.iter().map(|h| h.name.as_str()).collect();
        assert_eq!(
            names.first().copied(),
            Some("important_handler"),
            "overlay browse must lead with the referenced symbol, got {names:?}"
        );
    }

    // ── Task 4 leftover — cross-project search_files fan-out ─────────────────
    #[test]
    fn cross_project_search_files_attributes_hits_per_target() {
        let mut index_a = synthetic_index(0);
        index_a.files.insert(
            "widget_alpha.rs".to_string(),
            Arc::new(make_file("widget_alpha.rs", "fn a() {}")),
        );
        let mut index_b = synthetic_index(0);
        index_b.files.insert(
            "widget_beta.rs".to_string(),
            Arc::new(make_file("widget_beta.rs", "fn b() {}")),
        );

        let mut set = WorkingSet::new();
        set.add(
            "proj-a",
            Arc::new(IndexBase::new(base_key("ca"), Arc::new(index_a), 1)),
        );
        set.add(
            "proj-b",
            Arc::new(IndexBase::new(base_key("cb"), Arc::new(index_b), 1)),
        );

        // All targets: hits from BOTH projects, each attributed to its source.
        let all = set.search_files(&Targets::All, "widget", 20, false, false, &PathScope::Any);
        let mut attributed: Vec<(&str, &str)> = all
            .iter()
            .map(|hit| (hit.project_id.as_str(), hit.hit.path.as_str()))
            .collect();
        attributed.sort_unstable();
        assert_eq!(
            attributed,
            vec![("proj-a", "widget_alpha.rs"), ("proj-b", "widget_beta.rs")],
            "fan-out must return each project's ranked hit with attribution"
        );

        // One target: only that project's hits.
        let only_b = set.search_files(
            &Targets::One("proj-b".to_string()),
            "widget",
            20,
            false,
            false,
            &PathScope::Any,
        );
        assert_eq!(only_b.len(), 1);
        assert_eq!(only_b[0].project_id, "proj-b");
        assert_eq!(only_b[0].hit.path, "widget_beta.rs");
    }
}