rdar 0.6.2

radar - the repository cartographer for AI agents: compiles a repo into tiny committed MAP.md routers, with measured token benchmarks
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
//! MAP.md model and deterministic emitter.
//!
//! Determinism contract: identical inputs render byte-identical maps;
//! re-emitting over an unchanged map rewrites nothing (`stamped` means last
//! CONTENT change). Slot interiors are owned by humans/LLMs and preserved
//! verbatim across re-emits (augment-don't-clobber).

use std::collections::BTreeMap;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

use crate::cache::ScanCache;
use crate::extract::{Symbol, Vis};
use crate::frontmatter::{self, Frontmatter};
use crate::graph::Ranking;
use crate::place::Placement;

/// Body-byte budgets per tier.
pub const BUDGET_ROOT: usize = 2400;
pub const BUDGET_INNER: usize = 1600;
pub const BUDGET_LEAF: usize = 1200;

/// Worst-case routed lookup: root + 3 hops ≤ this many BODY bytes total
/// (~1.8k tokens × 4 bytes/token - the static half of the 4× rule, §10).
pub const CHAIN_BYTE_CAP: usize = 7200;

/// One planned map, ready to render.
#[derive(Clone, Debug)]
pub struct MapPlan {
    /// Root-relative scope dir ("" = repo root).
    pub scope: String,
    pub parent: Option<String>,
    pub children: Vec<String>,
    /// Scopes whose public symbols this scope references (forward deps,
    /// heaviest first, ≤ USES_MAX). Root as a target is skipped - it is
    /// always loaded anyway.
    pub uses: Vec<String>,
    pub api_hash: String,
    pub kids_hash: Option<String>,
    /// Ranked public symbols per file (rel path → rows), pre-packed.
    pub api: Vec<(String, Vec<Symbol>)>,
    /// Omitted symbol count after budget packing.
    pub api_tail: usize,
    /// Names of omitted symbols (rendered compactly - a needle symbol must
    /// never be invisible to routing; benchmark-driven fix).
    pub api_tail_names: Vec<String>,
    /// Jump rows: (symbol name, referencing files, called symbols).
    /// Callees are span-attributed (refs inside the symbol's own lines) and
    /// cross-scope only - a truthful 1-hop ego-graph slice (RepoGraph).
    pub jumps: Vec<(String, Vec<String>, Vec<String>)>,
    /// Root map only: one routing line per descendant scope -
    /// (scope, top-symbol glue anchor). B+-tree-interior-node pattern:
    /// pointers only, never API rows; glue anchors let needle queries skip
    /// the leaf-map hop entirely (research pass: DNS glue / LocAgent).
    pub routes: Vec<(String, String)>,
    /// Dense scope-only rendering used when full route rows exceed the root
    /// budget. Glue remains available in route_find and child maps.
    compact_routes: bool,
    /// Routes omitted only when even the dense list cannot fit. The complete
    /// topology remains available through frontmatter and `radar tree`.
    route_tail: usize,
    /// Test files in scope.
    pub tests: Vec<String>,
}

/// Result of emitting one map.
#[derive(Debug, PartialEq, Eq)]
pub enum Emit {
    Written,
    Unchanged,
}

pub fn map_path(root: &Path, scope: &str) -> PathBuf {
    if scope.is_empty() {
        root.join("MAP.md")
    } else {
        root.join(scope).join("MAP.md")
    }
}

/// Approximate token count for a map body. Code-calibrated: source-heavy
/// text runs ~3.3 chars/token, not the prose rule-of-thumb of 4.
pub fn approx_tokens(bytes: usize) -> usize {
    (bytes * 3).div_ceil(10)
}

/// Cap on `uses:` forward-dependency entries (heaviest referenced scopes).
const USES_MAX: usize = 6;

/// Routes-table prefix factoring fires only when repeated enough to pay:
/// at least this many routes sharing at least this long a directory prefix.
const ROUTES_PREFIX_MIN_ROUTES: usize = 4;
const ROUTES_PREFIX_MIN_LEN: usize = 8;

/// Longest common directory prefix of all route scopes, or "" when below
/// the pay-off gate. Factored once into the Routes header so deep-monorepo
/// roots don't repeat `services/api/internal/` on every row - plain
/// relative notation under a stated base, not opaque aliases (no legend
/// lookup for the reader, no conflict namespace).
fn common_route_prefix(routes: &[(String, String)]) -> String {
    // Test-only escape for A/B benchmarking (matches the RADAR_TEST_* hooks).
    if std::env::var_os("RADAR_TEST_NO_ROUTE_PREFIX").is_some() {
        return String::new();
    }
    if routes.len() < ROUTES_PREFIX_MIN_ROUTES {
        return String::new();
    }
    let mut prefix = routes[0].0.clone();
    for (scope, _) in &routes[1..] {
        while !scope.starts_with(prefix.as_str()) {
            prefix.pop();
        }
        if prefix.is_empty() {
            return prefix;
        }
    }
    match prefix.rfind('/') {
        Some(i) => prefix.truncate(i + 1),
        None => return String::new(),
    }
    if prefix.len() < ROUTES_PREFIX_MIN_LEN {
        return String::new();
    }
    prefix
}

fn budget_for(scope: &str, has_children: bool) -> usize {
    if scope.is_empty() {
        BUDGET_ROOT
    } else if has_children {
        BUDGET_INNER
    } else {
        BUDGET_LEAF
    }
}

/// Relative link from `from_scope`'s dir to `to_scope`'s MAP.md.
fn rel_link(from_scope: &str, to_scope: &str) -> String {
    let from: Vec<&str> = if from_scope.is_empty() {
        vec![]
    } else {
        from_scope.split('/').collect()
    };
    let to: Vec<&str> = if to_scope.is_empty() {
        vec![]
    } else {
        to_scope.split('/').collect()
    };
    let common = from.iter().zip(&to).take_while(|(a, b)| a == b).count();
    let mut parts: Vec<String> = vec!["..".to_string(); from.len() - common];
    parts.extend(to[common..].iter().map(|s| s.to_string()));
    parts.push("MAP.md".to_string());
    parts.join("/")
}

/// Canonical public-signature hash for a scope.
///
/// Lines are `{kind} {name} {sig}` - no paths, no line numbers - sorted and
/// newline-joined, so file moves within the scope and member reordering
/// never change the hash. blake3, first 16 hex chars.
pub fn api_hash(symbols: impl Iterator<Item = Symbol>) -> String {
    let mut lines: Vec<String> = symbols
        .filter(|s| s.vis == Vis::Pub)
        .map(|s| format!("{} {} {}", s.kind.name(), s.name, s.sig))
        .collect();
    lines.sort();
    lines.dedup();
    let digest = blake3::hash(lines.join("\n").as_bytes());
    digest.to_hex()[..16].to_string()
}

/// All public symbols belonging to a scope (own files, not descendants').
pub fn scope_symbols<'c>(
    cache: &'c ScanCache,
    placement: &'c Placement,
    scope: &'c str,
) -> impl Iterator<Item = (&'c String, &'c Symbol)> {
    cache.files.iter().flat_map(move |(rel, entry)| {
        let owned = placement.owner.get(rel).is_some_and(|s| s == scope);
        let symbols = if owned
            && let Some(lang) = entry.lang
            && let Some(x) = cache.parses.get(&(lang, entry.hash))
        {
            x.defs.as_slice()
        } else {
            &[]
        };
        symbols.iter().map(move |s| (rel, s))
    })
}

/// Build all map plans for the repo (deterministic).
pub fn plan_maps(cache: &ScanCache, placement: &Placement, ranking: &Ranking) -> Vec<MapPlan> {
    // Per-scope api hashes first (children hashes feed parents).
    let mut hashes: BTreeMap<&str, String> = BTreeMap::new();
    for scope in &placement.anchors {
        let h = api_hash(
            scope_symbols(cache, placement, scope)
                .filter(|(_, s)| s.vis == Vis::Pub)
                .map(|(_, s)| s.clone()),
        );
        hashes.insert(scope, h);
    }

    // Per-scope top-ranked public symbol (glue anchors for the Routes table).
    let mut top_symbol: BTreeMap<&str, (String, String)> = BTreeMap::new();
    for scope in &placement.anchors {
        let mut best: Option<(u64, &String, &Symbol)> = None;
        let mut second_score = 0u64;
        for (rel, sym) in scope_symbols(cache, placement, scope) {
            if sym.vis != Vis::Pub {
                continue;
            }
            let score = ranking.name_refs.get(&sym.name).copied().unwrap_or(0);
            let better = match &best {
                None => true,
                Some((s, r, b)) => score > *s || (score == *s && (rel, sym.line) < (*r, b.line)),
            };
            if better {
                if let Some((s, _, _)) = &best {
                    second_score = second_score.max(*s);
                }
                best = Some((score, rel, sym));
            } else {
                second_score = second_score.max(score);
            }
        }
        // Glue only when the hub is DISTINCTIVE: uniform-score scopes emit
        // no glue (a wall of identical anchors is noise, not routing).
        if let Some((score, rel, sym)) = best
            && score > 0
            && score > second_score
        {
            top_symbol.insert(scope, (rel.clone(), sym.name.clone()));
        }
    }

    // name → owning scope for public symbols (callee-edge resolution;
    // first definer wins deterministically via BTree order).
    let mut pub_owner: BTreeMap<&str, &str> = BTreeMap::new();
    for (rel, entry) in &cache.files {
        let (Some(lang), Some(owner)) = (entry.lang, placement.owner.get(rel)) else {
            continue;
        };
        let Some(x) = cache.parses.get(&(lang, entry.hash)) else {
            continue;
        };
        for d in &x.defs {
            if d.vis == Vis::Pub {
                pub_owner.entry(&d.name).or_insert(owner.as_str());
            }
        }
    }

    placement
        .anchors
        .iter()
        .map(|scope| {
            let children: Vec<String> = placement
                .children_of(scope)
                .iter()
                .map(|s| s.to_string())
                .collect();
            let kids_hash = if children.is_empty() {
                None
            } else {
                let mut ks: Vec<&str> = children
                    .iter()
                    .filter_map(|c| hashes.get(c.as_str()).map(|s| s.as_str()))
                    .collect();
                ks.sort();
                let digest = blake3::hash(ks.join("\n").as_bytes());
                Some(digest.to_hex()[..16].to_string())
            };

            // Forward deps: scopes whose public symbols this scope's files
            // reference (call + import edges), heaviest first. Direct-import
            // topology is the highest-value routing signal after signatures
            // (HCP level-1 result; RepoGraph reference edges).
            let mut use_counts: BTreeMap<&str, u64> = BTreeMap::new();
            for (rel, entry) in &cache.files {
                if placement.owner.get(rel).is_none_or(|s| s != scope) {
                    continue;
                }
                let Some(lang) = entry.lang else { continue };
                let Some(x) = cache.parses.get(&(lang, entry.hash)) else {
                    continue;
                };
                for r in &x.refs {
                    if let Some(owner) = pub_owner.get(r.name.as_str())
                        && !owner.is_empty()
                        && *owner != scope.as_str()
                    {
                        *use_counts.entry(owner).or_insert(0) += 1;
                    }
                }
            }
            let mut uses: Vec<(&str, u64)> = use_counts.into_iter().collect();
            uses.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(b.0)));
            let uses: Vec<String> = uses
                .into_iter()
                .take(USES_MAX)
                .map(|(s, _)| s.to_string())
                .collect();

            // Ranked public symbols: score = repo-wide name refs, ties by
            // (file, line) for determinism. The GLOBAL rank order is what
            // the budget packer must cut on (review finding: regrouping by
            // file before packing made cuts keep alphabetically-first files
            // instead of highest-ranked symbols).
            let mut scored: Vec<(u64, String, Symbol)> = scope_symbols(cache, placement, scope)
                .filter(|(_, s)| s.vis == Vis::Pub)
                .map(|(rel, s)| {
                    let score = ranking.name_refs.get(&s.name).copied().unwrap_or(0);
                    (score, rel.clone(), s.clone())
                })
                .collect();
            scored.sort_by(|a, b| {
                b.0.cmp(&a.0)
                    .then_with(|| a.1.cmp(&b.1))
                    .then_with(|| a.2.line.cmp(&b.2.line))
            });
            let ranked: Vec<(String, Symbol)> =
                scored.into_iter().map(|(_, rel, s)| (rel, s)).collect();

            // Jump rows: top cross-referenced symbols of this scope.
            let mut jump_syms: Vec<(u64, String)> = ranked
                .iter()
                .map(|(_, s)| {
                    (
                        ranking.name_refs.get(&s.name).copied().unwrap_or(0),
                        s.name.clone(),
                    )
                })
                .filter(|(score, _)| *score > 0)
                .collect();
            jump_syms.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
            jump_syms.dedup_by(|a, b| a.1 == b.1);
            // Pub-symbol name → owning scope (for cross-scope callee edges).
            let jumps: Vec<(String, Vec<String>, Vec<String>)> = jump_syms
                .into_iter()
                .take(3)
                .map(|(_, name)| {
                    // Heaviest external referencers first (A8 index - no
                    // per-symbol rescan of every file).
                    let mut users: Vec<(u64, &String)> = ranking
                        .name_users
                        .get(&name)
                        .map(|files| {
                            files
                                .iter()
                                .filter(|(rel, _)| {
                                    placement.owner.get(*rel).is_some_and(|s| s != scope)
                                })
                                .map(|(rel, n)| (*n, rel))
                                .collect()
                        })
                        .unwrap_or_default();
                    users.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(b.1)));
                    let users: Vec<String> = users
                        .into_iter()
                        .take(2)
                        .map(|(_, rel)| rel.clone())
                        .collect();
                    // Callees: Call-kind refs inside this symbol's span that
                    // resolve to a public definer in ANOTHER scope. Refs in
                    // nested (non-extracted) defs attribute to the enclosing
                    // extracted def - an accepted approximation.
                    let calls: Vec<String> = ranked
                        .iter()
                        .find(|(_, s)| s.name == name)
                        .map(|(rel, s)| {
                            let mut out: Vec<String> = Vec::new();
                            if let Some(entry) = cache.files.get(rel)
                                && let Some(lang) = entry.lang
                                && let Some(x) = cache.parses.get(&(lang, entry.hash))
                            {
                                for r in &x.refs {
                                    if r.kind == crate::extract::RefKind::Call
                                        && r.line >= s.line
                                        && r.line <= s.end_line
                                        && r.name != name
                                        && pub_owner
                                            .get(r.name.as_str())
                                            .is_some_and(|o| *o != scope.as_str())
                                        && !out.contains(&r.name)
                                    {
                                        out.push(r.name.clone());
                                    }
                                    if out.len() >= 3 {
                                        break;
                                    }
                                }
                            }
                            out
                        })
                        .unwrap_or_default();
                    (name, users, calls)
                })
                .filter(|(_, users, calls)| !users.is_empty() || !calls.is_empty())
                .collect();

            let tests: Vec<String> = cache
                .files
                .keys()
                .filter(|rel| placement.owner.get(*rel).is_some_and(|s| s == scope))
                .filter(|rel| {
                    let name = rel.rsplit('/').next().unwrap_or(rel);
                    name.contains("test") || name.contains("spec")
                })
                .cloned()
                .collect();

            // Routes: root map lists EVERY descendant scope with a glue
            // anchor (pointers only - the routing table that turns worst
            // 4-hop lookups into 2 hops).
            let routes: Vec<(String, String)> = if scope.is_empty() {
                placement
                    .anchors
                    .iter()
                    .filter(|a| !a.is_empty())
                    .map(|a| {
                        let glue = top_symbol
                            .get(a.as_str())
                            .map(|(rel, name)| format!("{rel}#{name}"))
                            .unwrap_or_default();
                        (a.clone(), glue)
                    })
                    .collect()
            } else {
                Vec::new()
            };

            let scope_api_hash = hashes.get(scope.as_str()).cloned().unwrap_or_else(|| {
                api_hash(
                    scope_symbols(cache, placement, scope)
                        .filter(|(_, symbol)| symbol.vis == Vis::Pub)
                        .map(|(_, symbol)| symbol.clone()),
                )
            });
            MapPlan {
                scope: scope.clone(),
                parent: placement.parent_scope(scope).map(|s| s.to_string()),
                children,
                uses,
                api_hash: scope_api_hash,
                kids_hash,
                api: Vec::new(),
                api_tail: 0,
                api_tail_names: Vec::new(),
                tests,
                jumps,
                routes,
                compact_routes: false,
                route_tail: 0,
            }
            .packed(&ranked)
        })
        .collect()
}

impl MapPlan {
    /// Budget packing on the GLOBALLY rank-ordered symbol list: binary
    /// search for the largest kept prefix that fits (§7.3); the overflow
    /// becomes a counted tail. Grouping by file happens only for display,
    /// after the cut.
    ///
    /// Packing reserves the WORST-CASE purpose-slot length (160 chars), not
    /// the fallback text - otherwise a filled sentence longer than the
    /// fallback would push an already-packed map over its budget (found by
    /// dogfooding radar on itself).
    fn packed(mut self, ranked: &[(String, Symbol)]) -> MapPlan {
        let budget = budget_for(&self.scope, !self.children.is_empty());
        let total = ranked.len();
        let reserve = "x".repeat(crate::slots::PURPOSE_MAX_CHARS);
        if !self.routes.is_empty() && self.render_body(&reserve).len() > budget {
            self.compact_routes = true;
            if self.render_body(&reserve).len() > budget {
                let all_routes = self.routes.clone();
                let mut lo = 0usize;
                let mut hi = all_routes.len();
                while lo < hi {
                    let mid = lo + (hi - lo).div_ceil(2);
                    let mut probe = self.clone();
                    probe.routes = all_routes[..mid].to_vec();
                    probe.route_tail = all_routes.len() - mid;
                    if probe.render_body(&reserve).len() <= budget {
                        lo = mid;
                    } else {
                        hi = mid - 1;
                    }
                }
                self.routes = all_routes[..lo].to_vec();
                self.route_tail = all_routes.len() - lo;
            }
        }
        let fits = |k: usize| -> bool {
            self.trimmed(ranked, k, total).render_body(&reserve).len() <= budget
        };
        if fits(total) {
            return self.trimmed(ranked, total, total);
        }
        let (mut lo, mut hi) = (0usize, total);
        while lo < hi {
            let mid = lo + (hi - lo).div_ceil(2);
            if fits(mid) {
                lo = mid;
            } else {
                hi = mid - 1;
            }
        }
        self.trimmed(ranked, lo, total)
    }

    /// Keep the top-`keep` ranked symbols, grouped by file for display.
    fn trimmed(&self, ranked: &[(String, Symbol)], keep: usize, total: usize) -> MapPlan {
        let mut api: BTreeMap<String, Vec<Symbol>> = BTreeMap::new();
        for (f, s) in ranked.iter().take(keep) {
            api.entry(f.clone()).or_default().push(s.clone());
        }
        let mut tail_names: Vec<String> = ranked
            .iter()
            .skip(keep)
            .map(|(_, s)| s.name.clone())
            .collect();
        tail_names.sort();
        tail_names.dedup();
        MapPlan {
            scope: self.scope.clone(),
            parent: self.parent.clone(),
            children: self.children.clone(),
            uses: self.uses.clone(),
            api_hash: self.api_hash.clone(),
            kids_hash: self.kids_hash.clone(),
            api: api.into_iter().collect(),
            api_tail: total - keep,
            api_tail_names: tail_names,
            jumps: self.jumps.clone(),
            tests: self.tests.clone(),
            routes: self.routes.clone(),
            compact_routes: self.compact_routes,
            route_tail: self.route_tail,
        }
    }

    /// Render the body (everything after the frontmatter). `purpose` is the
    /// slot interior (existing text or deterministic fallback).
    fn render_body(&self, purpose: &str) -> String {
        let title = if self.scope.is_empty() {
            "."
        } else {
            &self.scope
        };
        let mut b = format!("# {title}\n\n");
        b.push_str("<!-- radar:slot purpose max=160 -->\n");
        let fallback;
        let text = if purpose.trim().is_empty() {
            fallback = self.fallback_purpose();
            &fallback
        } else {
            purpose
        };
        b.push_str(text.trim_end());
        b.push_str("\n<!-- /radar:slot -->\n");

        if !self.routes.is_empty() || self.route_tail > 0 {
            let prefix = if self.routes.is_empty() {
                String::new()
            } else {
                common_route_prefix(&self.routes)
            };
            if self.compact_routes {
                if prefix.is_empty() {
                    b.push_str("\n## Routes (append /MAP.md)\n");
                } else {
                    b.push_str(&format!(
                        "\n## Routes (all under {prefix}; append /MAP.md)\n"
                    ));
                }
                let mut column = 0usize;
                for (scope, _) in &self.routes {
                    let scope = scope.strip_prefix(&prefix).unwrap_or(scope);
                    let separator = usize::from(column > 0) * 2;
                    if column > 0 && column + separator + scope.len() > 100 {
                        b.push('\n');
                        column = 0;
                    }
                    if column > 0 {
                        b.push_str(", ");
                        column += 2;
                    }
                    b.push_str(scope);
                    column += scope.len();
                }
                b.push('\n');
                if self.route_tail > 0 {
                    b.push_str(&format!(
                        "+{} more scopes: use `radar tree` or the children frontmatter.\n",
                        self.route_tail
                    ));
                }
            } else if prefix.is_empty() {
                b.push_str("\n## Routes\n");
            } else {
                b.push_str(&format!("\n## Routes (all under {prefix})\n"));
            }
            if !self.compact_routes {
                for (scope, glue) in &self.routes {
                    let scope = scope.strip_prefix(&prefix).unwrap_or(scope);
                    let glue = glue.strip_prefix(&prefix).unwrap_or(glue);
                    if glue.is_empty() {
                        b.push_str(&format!("- {scope}/MAP.md\n"));
                    } else {
                        b.push_str(&format!("- {scope}/MAP.md · {glue}\n"));
                    }
                }
            }
        }

        if !self.api.is_empty() {
            b.push_str("\n## API\n");
            for (file, syms) in &self.api {
                let short = file
                    .strip_prefix(&format!("{}/", self.scope))
                    .unwrap_or(file);
                b.push_str(&format!("{short}\n"));
                for s in syms {
                    b.push_str(&format!("- {}\n", s.sig));
                }
            }
            if self.api_tail > 0 {
                // Names are the minimum routing signal: list as many as fit
                // the reserve; only what overflows becomes a bare count.
                const TAIL_RESERVE: usize = 400;
                let mut listed = Vec::new();
                let mut used = 0usize;
                for name in &self.api_tail_names {
                    if used + name.len() + 2 > TAIL_RESERVE {
                        break;
                    }
                    used += name.len() + 2;
                    listed.push(name.as_str());
                }
                let unlisted = self.api_tail - listed.len().min(self.api_tail);
                if !listed.is_empty() {
                    b.push_str(&format!("- also: {}\n", listed.join(", ")));
                }
                if unlisted > 0 {
                    b.push_str(&format!(
                        "- +{unlisted} more public symbols omitted by the map budget\n"
                    ));
                }
            }
        }

        if !self.jumps.is_empty() {
            b.push_str("\n## Jump\n");
            for (name, users, calls) in &self.jumps {
                let mut row = format!("- {name}");
                if !users.is_empty() {
                    row.push_str(&format!(" ← used by {}", users.join(", ")));
                }
                if !calls.is_empty() {
                    row.push_str(&format!(" · calls {}", calls.join(", ")));
                }
                b.push_str(&row);
                b.push('\n');
            }
        }

        // Routes already lists every descendant - rendering Children too
        // would duplicate 20 pointer lines (accuracy pass: our own
        // no-duplication law applied to ourselves).
        if !self.children.is_empty() && self.routes.is_empty() {
            b.push_str("\n## Children\n");
            for child in &self.children {
                let link = rel_link(&self.scope, child);
                let label = child
                    .strip_prefix(&format!("{}/", self.scope))
                    .unwrap_or(child);
                b.push_str(&format!("- [{label}/]({link})\n"));
            }
        }

        if !self.tests.is_empty() {
            b.push_str("\n## Tests\n");
            for t in &self.tests {
                let short = t.strip_prefix(&format!("{}/", self.scope)).unwrap_or(t);
                b.push_str(&format!("- {short}\n"));
            }
        }
        b
    }

    fn fallback_purpose(&self) -> String {
        if !self.children.is_empty() {
            let kids: Vec<&str> = self
                .children
                .iter()
                .map(|c| c.rsplit('/').next().unwrap_or(c))
                .take(6)
                .collect();
            return format!(
                "Routes {} child unit(s): {}. (radar: fill this slot)",
                self.children.len(),
                kids.join(", ")
            );
        }
        let files = self.api.len();
        let names: Vec<&str> = self
            .api
            .iter()
            .flat_map(|(_, syms)| syms.iter().take(1))
            .map(|s| s.name.as_str())
            .take(4)
            .collect();
        if names.is_empty() {
            format!("Contains {files} source files. (radar: fill this slot)")
        } else {
            format!(
                "Contains {files} files around {}. (radar: fill this slot)",
                names.join(", ")
            )
        }
    }

    /// Emit to disk: preserves existing slot text, skips the write entirely
    /// when nothing but `stamped` would change.
    pub fn emit(&self, root: &Path, now_iso: &str) -> io::Result<Emit> {
        let path = map_path(root, &self.scope);
        let existing = fs::read_to_string(&path).ok();
        let (old_fm, old_slot) = match existing.as_deref().and_then(frontmatter::parse) {
            Some((fm, body)) => (Some(fm), slot_text(body, "purpose")),
            None => (None, None),
        };

        let body = self.render_body(old_slot.as_deref().unwrap_or(""));
        let mut fm = Frontmatter::new();
        // MAP.md is an OKF-compatible concept document: standard Markdown
        // body plus the required, descriptive frontmatter type. Radar keeps
        // its routing metadata as producer-defined extensions.
        fm.set("type", "Code Repository Map");
        fm.set(
            "title",
            if self.scope.is_empty() {
                "."
            } else {
                &self.scope
            },
        );
        fm.set("description", "Radar source-navigation map.");
        fm.set("map", "1");
        fm.set(
            "scope",
            if self.scope.is_empty() {
                "."
            } else {
                &self.scope
            },
        );
        if let Some(parent) = &self.parent {
            fm.set("parent", rel_link(&self.scope, parent));
        }
        if !self.children.is_empty() {
            let links: Vec<String> = self
                .children
                .iter()
                .map(|c| rel_link(&self.scope, c))
                .collect();
            fm.set_list("children", &links);
        }
        if !self.uses.is_empty() {
            fm.set_list("uses", &self.uses);
        }
        fm.set("fidelity", "syntax");
        fm.set("api_hash", &self.api_hash);
        if let Some(kh) = &self.kids_hash {
            fm.set("kids_hash", kh);
        }
        fm.set("tokens", format!("~{}", approx_tokens(body.len())));

        // Unknown keys are hand annotations preserved on round-trip;
        // without this, every rewrite would destroy them.
        // `lang`/`bytes` are retired keys: they stay KNOWN so rewrites shed
        // stale copies instead of preserving them as annotations.
        const KNOWN: [&str; 16] = [
            "type",
            "title",
            "description",
            "map",
            "scope",
            "parent",
            "children",
            "uses",
            "peers",
            "fidelity",
            "lang",
            "api_hash",
            "kids_hash",
            "stamped",
            "bytes",
            "tokens",
        ];
        if let Some(old) = &old_fm {
            let extras: Vec<(String, String)> = old
                .keys()
                .filter(|k| !KNOWN.contains(k))
                .filter_map(|k| old.get(k).map(|v| (k.to_string(), v.to_string())))
                .collect();
            for (k, v) in extras {
                fm.set(&k, v);
            }
        }

        // Unchanged (modulo stamped)? Preserve the old stamp, skip the write.
        if let (Some(old), Some(old_doc)) = (&old_fm, &existing) {
            let old_body = frontmatter::parse(old_doc).map(|(_, b)| b).unwrap_or("");
            let stamp = old.get("stamped").unwrap_or_default().to_string();
            let mut probe = fm.clone();
            probe.set("stamped", stamp);
            if probe_equal(&probe, old) && old_body == body {
                return Ok(Emit::Unchanged);
            }
        }

        fm.set("stamped", now_iso);
        if let Some(dir) = path.parent() {
            fs::create_dir_all(dir)?;
        }
        fs::write(&path, fm.render() + &body)?;
        Ok(Emit::Written)
    }
}

fn probe_equal(a: &Frontmatter, b: &Frontmatter) -> bool {
    let keys: Vec<&str> = a.keys().chain(b.keys()).collect();
    keys.iter().all(|k| a.get(k) == b.get(k))
}

/// Extract the interior of a named slot from a map body.
pub fn slot_text(body: &str, slot: &str) -> Option<String> {
    let open = format!("<!-- radar:slot {slot}");
    let start = body.find(&open)?;
    let after_open = body[start..].find("-->")? + start + 3;
    let close = body[after_open..].find("<!-- /radar:slot -->")? + after_open;
    let text = body[after_open..close].trim();
    if text.ends_with("(radar: fill this slot)") {
        None // fallback text is not user content
    } else {
        Some(text.to_string())
    }
}

/// RFC3339 UTC "now" with second precision - ~20 lines instead of chrono.
pub fn now_iso() -> String {
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::SystemTime::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    let days = secs / 86_400;
    let (h, m, s) = ((secs % 86_400) / 3600, (secs % 3600) / 60, secs % 60);
    // Civil-from-days (Howard Hinnant's algorithm).
    let z = days as i64 + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let mo = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if mo <= 2 { y + 1 } else { y };
    format!("{y:04}-{mo:02}-{d:02}T{h:02}:{m:02}:{s:02}Z")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::extract::SymKind;

    fn sym(name: &str, vis: Vis, line: u32, sig: &str) -> Symbol {
        Symbol {
            line,
            end_line: line + 1,
            name: name.into(),
            kind: SymKind::Fn,
            vis,
            sig: sig.into(),
            terms: Vec::new(),
        }
    }

    #[test]
    fn api_hash_is_order_path_and_line_invariant() {
        let a = vec![
            sym("alpha", Vis::Pub, 10, "def alpha()"),
            sym("beta", Vis::Pub, 20, "def beta()"),
        ];
        let mut b = a.clone();
        b.reverse();
        b[0].line = 99; // moved within the file
        assert_eq!(api_hash(a.into_iter()), api_hash(b.into_iter()));
    }

    #[test]
    fn api_hash_ignores_private_and_detects_pub_changes() {
        let base = vec![sym("alpha", Vis::Pub, 1, "def alpha()")];
        let with_priv = vec![
            sym("alpha", Vis::Pub, 1, "def alpha()"),
            sym("_hidden", Vis::Priv, 2, "def _hidden()"),
        ];
        assert_eq!(
            api_hash(base.clone().into_iter()),
            api_hash(with_priv.into_iter()),
            "private symbols never affect the hash"
        );
        let changed = vec![sym("alpha", Vis::Pub, 1, "def alpha(x)")];
        assert_ne!(
            api_hash(base.into_iter()),
            api_hash(changed.into_iter()),
            "signature change moves the hash"
        );
    }

    #[test]
    fn rel_links_resolve_up_and_down() {
        assert_eq!(rel_link("", "auth"), "auth/MAP.md");
        assert_eq!(rel_link("auth", ""), "../MAP.md");
        assert_eq!(rel_link("auth/jwt", "auth"), "../MAP.md");
        assert_eq!(rel_link("auth", "auth/jwt"), "jwt/MAP.md");
        assert_eq!(rel_link("a/b", "a/c"), "../c/MAP.md");
        assert_eq!(
            rel_link("src/main/java/com/acme", ""),
            "../../../../../MAP.md"
        );
    }

    #[test]
    fn slot_text_extraction_and_fallback_detection() {
        let body =
            "# t\n\n<!-- radar:slot purpose max=160 -->\nReal user text.\n<!-- /radar:slot -->\n";
        assert_eq!(slot_text(body, "purpose"), Some("Real user text.".into()));
        let fallback = "# t\n\n<!-- radar:slot purpose max=160 -->\nContains 3 files. (radar: fill this slot)\n<!-- /radar:slot -->\n";
        assert_eq!(slot_text(fallback, "purpose"), None);
        assert_eq!(slot_text("no slot here", "purpose"), None);
    }

    #[test]
    fn route_prefix_factoring_gates() {
        let deep: Vec<(String, String)> = ["auth", "billing", "orders", "payments"]
            .iter()
            .map(|m| {
                (
                    format!("services/api/internal/{m}"),
                    format!("services/api/internal/{m}/mod.py#{m}_entry"),
                )
            })
            .collect();
        assert_eq!(common_route_prefix(&deep), "services/api/internal/");
        // Too few routes: gate closed even with a long shared prefix.
        assert_eq!(common_route_prefix(&deep[..3]), "");
        // Flat layout: no shared directory prefix.
        let flat: Vec<(String, String)> = ["auth", "billing", "orders", "payments"]
            .iter()
            .map(|m| (m.to_string(), String::new()))
            .collect();
        assert_eq!(common_route_prefix(&flat), "");
        // Short shared prefix stays inline (below pay-off length).
        let short: Vec<(String, String)> = ["src/a", "src/b", "src/c", "src/d"]
            .iter()
            .map(|m| (m.to_string(), String::new()))
            .collect();
        assert_eq!(common_route_prefix(&short), "");
    }

    fn root_with_routes(count: usize) -> MapPlan {
        MapPlan {
            scope: String::new(),
            parent: None,
            children: (0..count).map(|index| format!("p{index:03}")).collect(),
            uses: Vec::new(),
            api_hash: "hash".to_string(),
            kids_hash: None,
            api: Vec::new(),
            api_tail: 0,
            api_tail_names: Vec::new(),
            jumps: Vec::new(),
            routes: (0..count)
                .map(|index| (format!("p{index:03}"), String::new()))
                .collect(),
            compact_routes: false,
            route_tail: 0,
            tests: Vec::new(),
        }
        .packed(&[])
    }

    #[test]
    fn oversized_root_routes_compact_within_budget() {
        let plan = root_with_routes(200);
        let body = plan.render_body("");
        assert!(plan.compact_routes, "dense form selected");
        assert_eq!(plan.route_tail, 0, "all 200 scopes still visible");
        assert!(body.contains("append /MAP.md"), "{body}");
        assert!(body.len() <= BUDGET_ROOT, "{} > {BUDGET_ROOT}", body.len());
    }

    #[test]
    fn enormous_root_routes_emit_an_explicit_tail() {
        let plan = root_with_routes(1000);
        let body = plan.render_body("");
        assert!(plan.route_tail > 0, "overflow is counted");
        assert!(body.contains("more scopes"), "{body}");
        assert!(body.len() <= BUDGET_ROOT, "{} > {BUDGET_ROOT}", body.len());
    }

    #[test]
    fn now_iso_shape() {
        let s = now_iso();
        assert_eq!(s.len(), 20, "{s}");
        assert!(s.ends_with('Z'));
        assert_eq!(&s[4..5], "-");
        assert!(s.starts_with("20"), "sane century: {s}");
    }
}