symforge 8.16.0

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
//! Deterministic repository-mental-model projections over one published generation.

use std::collections::{BTreeMap, BTreeSet};

use crate::domain::FileDisposition;
use crate::knowledge::guard_hit;
use crate::live_index::PublishedGeneration;
use crate::live_index::graph::SymbolId;
use crate::live_index::knowledge_authority::{
    AuthorityDomain, KnowledgeAuthorityRecord, KnowledgeVoice,
};
use crate::live_index::knowledge_bridge::{
    BridgeResolution, CodeAnchorId, DerivedCoverage, KnowledgeCard, KnowledgeLinkResolution,
    KnowledgeRole, RoleEvidence,
};

type CardCandidate<'a> = (
    &'a KnowledgeCard,
    &'a RoleEvidence,
    Option<&'a KnowledgeAuthorityRecord>,
);

pub(crate) fn render_code_knowledge_context(
    published: &PublishedGeneration,
    target: &CodeAnchorId,
    include_when_empty: bool,
) -> Option<String> {
    let mut selected = BTreeSet::new();
    if let Some(indices) = published.bridge.reverse_exact.get(target) {
        selected.extend(indices.iter().copied());
    }
    let target_path = match target {
        CodeAnchorId::File { path } => path.as_str(),
        CodeAnchorId::Symbol { symbol, .. } => symbol.path.as_str(),
    };
    for index in &published.bridge.ownership_selectors {
        let Some(link) = published.bridge.forward.get(*index as usize) else {
            continue;
        };
        let Some(selector) = evidence_text(published, &link.evidence) else {
            continue;
        };
        if ownership_selector_matches(selector.trim(), target_path) {
            selected.insert(*index);
        }
    }

    let mut ambiguous = 0usize;
    for (index, link) in published.bridge.forward.iter().enumerate() {
        if let BridgeResolution::Ambiguous {
            bounded_samples, ..
        } = &link.resolution
            && bounded_samples.iter().any(|sample| &sample.id == target)
        {
            ambiguous += 1;
            selected.insert(u32::try_from(index).unwrap_or(u32::MAX));
        }
    }
    let missing = 0_usize;
    if selected.is_empty() && ambiguous == 0 && missing == 0 && !include_when_empty {
        return None;
    }

    let mut links = selected
        .iter()
        .filter_map(|index| {
            published
                .bridge
                .forward
                .get(*index as usize)
                .map(|link| (*index, link))
        })
        .collect::<Vec<_>>();
    links.sort_by(|left, right| {
        (
            left.1.evidence.path.as_str(),
            left.1.evidence.byte_range.start,
            &left.1.id,
        )
            .cmp(&(
                right.1.evidence.path.as_str(),
                right.1.evidence.byte_range.start,
                &right.1.id,
            ))
    });
    let total = links.len();
    let shown = total.min(5);
    let overflow = total.saturating_sub(shown);

    let source = published.source.as_deref();
    let mut lines = vec!["Knowledge evidence:".to_string()];
    lines.push(format!(
        "  source={} publication={} content={} target={}",
        source.map_or("unknown", |value| value.source_id.as_str()),
        published.publication_generation,
        published.content_generation,
        code_anchor_id_label(target),
    ));
    lines.push(format!(
        "  counts total={} shown={} overflow={} ambiguous={} missing={}",
        total, shown, overflow, ambiguous, missing,
    ));
    lines.push(format!(
        "  coverage bridge={} authority={}",
        derived_coverage_label(&published.bridge.coverage),
        derived_coverage_label(&published.authority.coverage),
    ));

    for (ordinal, (index, link)) in links.into_iter().take(5).enumerate() {
        let authority = authority_for_evidence(published, &link.evidence);
        lines.push(format!(
            "  {}. {}:{} bytes={}..{} content_hash={} source={} generation={} link_id={} bridge_index={} resolution={} lifecycle={} voice={}",
            ordinal + 1,
            link.evidence.path,
            link.evidence.line_range.start,
            link.evidence.byte_range.start,
            link.evidence.byte_range.end,
            link.evidence.content_hash,
            link.evidence.source.source_id.as_str(),
            link.evidence.content_generation,
            link.id.0,
            index,
            bridge_resolution_label(&link.resolution),
            authority.map_or("unknown".to_string(), |record| snake_debug(
                &record.lifecycle
            )),
            authority.map_or("unknown", |record| voice_label(record.voice)),
        ));
    }

    let rendered = lines.join("\n");
    match guard_hit(&rendered, &[rendered.as_str()]) {
        Ok(safe) => Some(safe.into_inner().clone()),
        Err(failure) => Some(format!(
            "Knowledge evidence withheld by secret policy v{} ({} finding(s)).",
            failure.policy_version, failure.finding_count
        )),
    }
}

/// Preserve the indivisible provenance/count contract for an explicit
/// `sections=["knowledge"]` read. Generic line truncation can otherwise keep a
/// long symbol identity while dropping coverage, which is neither a complete
/// anchor nor a complete provenance-only fallback.
pub(crate) fn render_budgeted_code_knowledge_only(
    published: &PublishedGeneration,
    rendered: Option<&str>,
    max_tokens: Option<u64>,
) -> String {
    let source = published.source.as_deref();
    let fallback = format!(
        "Knowledge evidence:\n  source={} publication={} content={} target=unresolved\n  counts total=0 shown=0 overflow=0 ambiguous=0 missing=0\n  coverage bridge={} authority={}",
        source.map_or("unknown", |value| value.source_id.as_str()),
        published.publication_generation,
        published.content_generation,
        derived_coverage_label(&published.bridge.coverage),
        derived_coverage_label(&published.authority.coverage),
    );
    let rendered = rendered.unwrap_or(&fallback);
    let normal = format!(
        "Trust: exact source evidence | publication {} | content {} | current\nScope: requested code anchor\nEvidence: reverse knowledge bridge\n\n{rendered}",
        published.publication_generation, published.content_generation,
    );
    let Some(max_tokens) = max_tokens.filter(|value| *value > 0) else {
        return normal;
    };
    if normal.len() <= (max_tokens as usize).saturating_mul(4) {
        return normal;
    }

    let counts = rendered
        .lines()
        .find(|line| line.trim_start().starts_with("counts "))
        .map(str::trim_start)
        .unwrap_or("counts total=0 shown=0 overflow=0 ambiguous=0 missing=0");
    let coverage = rendered
        .lines()
        .find(|line| line.trim_start().starts_with("coverage "))
        .map(str::trim_start)
        .unwrap_or("coverage bridge=unknown authority=unknown");
    let compact = format!(
        "Trust: exact source evidence | current | output_coverage=degraded\nIdentity: source={} publication={} content={}\nScope: requested code anchor\nEvidence: reverse knowledge bridge\n\nKnowledge evidence:\n  {counts}\n  {coverage}",
        source.map_or("unknown", |value| value.source_id.as_str()),
        published.publication_generation,
        published.content_generation,
    );
    if compact.len() <= (max_tokens as usize).saturating_mul(4) {
        compact
    } else {
        let minimum_tokens = compact.len().div_ceil(4);
        format!(
            "Error: max_tokens is too small for atomic knowledge provenance; minimum_tokens={minimum_tokens}."
        )
    }
}

/// Apply a caller budget without allowing the code portion of a combined
/// context response to consume the entire budget and erase the required
/// knowledge provenance. If generic truncation cannot retain the indivisible
/// source/count/coverage block, the response degrades to that block alone.
pub(crate) fn enforce_budgeted_code_context_with_knowledge(
    published: &PublishedGeneration,
    assembled: String,
    rendered: Option<&str>,
    max_tokens: Option<u64>,
) -> (String, bool) {
    let (budgeted, truncated) =
        crate::protocol::format::enforce_token_budget_flagged(assembled, max_tokens);
    if !truncated || rendered.is_none() {
        return (budgeted, truncated);
    }

    let complete_provenance =
        budgeted
            .split_once("Knowledge evidence:")
            .is_some_and(|(_, section)| {
                section.contains("source=")
                    && section.contains("publication=")
                    && section.contains("content=")
                    && section.contains("counts total=")
                    && section.contains("overflow=")
                    && section.contains("ambiguous=")
                    && section.contains("missing=")
                    && section.contains("coverage bridge=")
                    && section.contains("authority=")
            });
    if complete_provenance {
        (budgeted, true)
    } else {
        (
            render_budgeted_code_knowledge_only(published, rendered, max_tokens),
            true,
        )
    }
}

pub(crate) fn resolve_symbol_code_anchor(
    published: &PublishedGeneration,
    path: &str,
    name: &str,
    kind: Option<&str>,
    symbol_line: Option<u32>,
) -> Option<CodeAnchorId> {
    let file = published.live.files.get(path)?;
    let mut matches = file.symbols.iter().filter(|symbol| {
        symbol.name == name
            && kind.is_none_or(|kind| symbol.kind.to_string().eq_ignore_ascii_case(kind))
            && symbol_line.is_none_or(|line| symbol.line_range.0.saturating_add(1) == line)
    });
    let symbol = matches.next()?;
    if matches.next().is_some() {
        return None;
    }
    Some(CodeAnchorId::Symbol {
        symbol: SymbolId {
            path: path.to_string(),
            name: symbol.name.clone(),
            kind: symbol.kind,
        },
        start_line: symbol.line_range.0.saturating_add(1),
    })
}

fn evidence_text<'a>(
    published: &'a PublishedGeneration,
    evidence: &crate::live_index::knowledge_bridge::KnowledgeAnchor,
) -> Option<&'a str> {
    let file = published.live.files.get(&evidence.path)?;
    let start = usize::try_from(evidence.byte_range.start).ok()?;
    let end = usize::try_from(evidence.byte_range.end).ok()?;
    std::str::from_utf8(file.content.get(start..end)?).ok()
}

fn ownership_selector_matches(selector: &str, path: &str) -> bool {
    let mut pattern = selector.trim_start_matches('/').replace('\\', "/");
    if pattern.ends_with('/') {
        pattern.push_str("**");
    }
    if !pattern.contains('/') {
        pattern = format!("**/{pattern}");
    }
    let Ok(glob) = globset::GlobBuilder::new(&pattern)
        .literal_separator(true)
        .backslash_escape(false)
        .build()
    else {
        return false;
    };
    glob.compile_matcher().is_match(path)
}

fn authority_for_evidence<'a>(
    published: &'a PublishedGeneration,
    evidence: &crate::live_index::knowledge_bridge::KnowledgeAnchor,
) -> Option<&'a KnowledgeAuthorityRecord> {
    published.authority.records.iter().find(|record| {
        record.unit.source == evidence.source
            && record.unit.path == evidence.path
            && record.unit.content_hash == evidence.content_hash
            && record.unit.byte_range.start <= evidence.byte_range.start
            && record.unit.byte_range.end >= evidence.byte_range.end
    })
}

fn code_anchor_id_label(target: &CodeAnchorId) -> String {
    match target {
        CodeAnchorId::File { path } => format!("file:{path}"),
        CodeAnchorId::Symbol { symbol, start_line } => format!(
            "symbol:{}:{}:{}:{}",
            symbol.path, symbol.name, symbol.kind, start_line
        ),
    }
}

fn bridge_resolution_label(resolution: &BridgeResolution) -> String {
    match resolution {
        BridgeResolution::ResolvedExact(_) => "resolved_exact".to_string(),
        BridgeResolution::ResolvedDeclaredSet { matched_count, .. } => {
            format!("resolved_declared_set({matched_count})")
        }
        BridgeResolution::Ambiguous {
            candidate_count,
            bounded_samples,
        } => format!(
            "ambiguous({candidate_count},samples=[{}])",
            bounded_samples
                .iter()
                .map(|sample| code_anchor_id_label(&sample.id))
                .collect::<Vec<_>>()
                .join(";")
        ),
        BridgeResolution::Missing => "missing".to_string(),
    }
}

pub(crate) fn render_repository_knowledge_map(published: &PublishedGeneration) -> String {
    let record_by_unit = published
        .authority
        .records
        .iter()
        .map(|record| (record.unit.id.clone(), record))
        .collect::<BTreeMap<_, _>>();
    let mut current = BTreeMap::<KnowledgeRole, Vec<CardCandidate<'_>>>::new();
    let mut intent = BTreeMap::<KnowledgeRole, Vec<CardCandidate<'_>>>::new();
    let mut present_roles = BTreeSet::new();

    for card in &published.bridge.cards {
        let record = record_by_unit.get(&card.anchor.id).copied();
        for (role, evidence) in &card.roles {
            present_roles.insert(*role);
            match record.map(|record| record.authority_domain) {
                Some(AuthorityDomain::CurrentImplementation | AuthorityDomain::Operations) => {
                    current
                        .entry(*role)
                        .or_default()
                        .push((card, evidence, record));
                }
                Some(
                    AuthorityDomain::NormativeIntent
                    | AuthorityDomain::Decision
                    | AuthorityDomain::Governance,
                ) => {
                    intent
                        .entry(*role)
                        .or_default()
                        .push((card, evidence, record));
                }
                Some(AuthorityDomain::HistoricalRecord | AuthorityDomain::Unknown) | None => {}
            }
        }
    }

    let source = published.source.as_deref();
    let source_version = published.source_version.as_deref();
    let manifest = published.manifest.as_deref();
    let mut lines = vec!["Repository knowledge:".to_string()];
    lines.push(format!(
        "  source={} repository={} publication={} content={} project={}",
        source.map_or("unknown", |value| value.source_id.as_str()),
        source.map_or("unknown", |value| value.repository_id.as_str()),
        published.publication_generation,
        published.content_generation,
        published.project_generation,
    ));
    lines.push(format!(
        "  version branch={} commit={} working_tree={}",
        source_version
            .and_then(|value| value.branch.as_deref())
            .unwrap_or("unknown"),
        source_version
            .and_then(|value| value.commit.as_deref())
            .unwrap_or("unknown"),
        source_version.map_or("unknown".to_string(), |value| snake_debug(
            &value.working_tree
        )),
    ));

    render_role_lane(&mut lines, "Current roles", &mut current);
    render_role_lane(&mut lines, "Intent roles", &mut intent);

    let all_roles = [
        KnowledgeRole::Architecture,
        KnowledgeRole::OwnershipGovernance,
        KnowledgeRole::DecisionInvariant,
        KnowledgeRole::SchemaContract,
        KnowledgeRole::Operations,
        KnowledgeRole::TestingSecurity,
        KnowledgeRole::PlanHandoff,
        KnowledgeRole::Other,
    ];
    let missing = all_roles
        .iter()
        .filter(|role| !present_roles.contains(role))
        .map(role_label)
        .collect::<Vec<_>>();
    lines.push(format!(
        "Missing roles: {}",
        if missing.is_empty() {
            "none".to_string()
        } else {
            format!("{} (unknown/no declared evidence)", missing.join(", "))
        }
    ));

    let voice_count = |voice| {
        published
            .authority
            .records
            .iter()
            .filter(|record| record.voice == voice)
            .count()
    };
    lines.push(format!(
        "Hygiene: needs_review={} history_only={} suppressed={}",
        voice_count(KnowledgeVoice::NeedsReview),
        voice_count(KnowledgeVoice::HistoryOnly),
        voice_count(KnowledgeVoice::Suppressed),
    ));

    let ambiguous = published
        .bridge
        .forward
        .iter()
        .filter(|link| matches!(link.resolution, BridgeResolution::Ambiguous { .. }))
        .count();
    let missing_code = published
        .bridge
        .forward
        .iter()
        .filter(|link| matches!(link.resolution, BridgeResolution::Missing))
        .count();
    let missing_knowledge = published
        .bridge
        .knowledge_links
        .iter()
        .filter(|link| matches!(link.resolution, KnowledgeLinkResolution::Missing))
        .count();
    let unknown_records = published
        .authority
        .records
        .iter()
        .filter(|record| {
            record.authority_domain == AuthorityDomain::Unknown
                || record.voice == KnowledgeVoice::Unknown
        })
        .count();
    let (withheld, unreadable) = manifest.map_or((0, 0), |manifest| {
        manifest
            .entries
            .iter()
            .fold((0, 0), |(withheld, unreadable), entry| {
                match entry.disposition {
                    FileDisposition::MetadataOnly { .. } | FileDisposition::HardSkip { .. } => {
                        (withheld + 1, unreadable)
                    }
                    FileDisposition::Unreadable { .. }
                    | FileDisposition::UnstableDuringRead
                    | FileDisposition::AbortedCircuitBreaker => (withheld, unreadable + 1),
                    FileDisposition::Indexed { .. } => (withheld, unreadable),
                }
            })
    });
    lines.push(format!(
        "Uncertainty: unknown_records={} ambiguous_anchors={} missing_anchors={} withheld={} unreadable={}",
        unknown_records,
        ambiguous,
        missing_code.saturating_add(missing_knowledge),
        withheld,
        unreadable,
    ));
    lines.push(format!(
        "Coverage: manifest={} bridge={} authority={} temporal_complete_to_root={} temporal_limitations={} freshness={}",
        manifest.map_or("unknown".to_string(), |value| snake_debug(&value.coverage)),
        derived_coverage_label(&published.bridge.coverage),
        derived_coverage_label(&published.authority.coverage),
        published.code_signals.coverage.complete_to_root,
        published.code_signals.coverage.limitations.len(),
        snake_debug(published.freshness.as_ref()),
    ));
    lines.push(format!(
        "Digests: manifest={} policy={}",
        manifest.map_or("unknown", |value| value.digest.as_str()),
        published.authority.policy_digest,
    ));

    let rendered = lines.join("\n");
    match guard_hit(&rendered, &[rendered.as_str()]) {
        Ok(safe) => safe.into_inner().clone(),
        Err(failure) => format!(
            "Repository knowledge withheld by secret policy v{} ({} finding(s)).",
            failure.policy_version, failure.finding_count
        ),
    }
}

fn render_role_lane(
    lines: &mut Vec<String>,
    title: &str,
    roles: &mut BTreeMap<KnowledgeRole, Vec<CardCandidate<'_>>>,
) {
    let role_count = roles.len();
    let card_count = roles.values().map(Vec::len).sum::<usize>();
    lines.push(format!(
        "{title}: roles={} cards={} shown={} overflow={}",
        role_count,
        card_count,
        role_count,
        card_count.saturating_sub(role_count),
    ));
    if roles.is_empty() {
        lines.push("  none".to_string());
        return;
    }
    for (role, candidates) in roles {
        candidates.sort_by(|left, right| card_candidate_key(left).cmp(&card_candidate_key(right)));
        let Some((card, evidence, record)) = candidates.first() else {
            continue;
        };
        let voice = record.map_or("unknown", |record| voice_label(record.voice));
        let evidence_anchor = role_evidence_anchor(evidence);
        lines.push(format!(
            "  {} {}:{} unit_id={}#{}:{} bytes={}..{} content_hash={} source={} generation={} voice={} evidence={} evidence_anchor={}#{}:{}@{}..{} overflow={}",
            role_label(role),
            card.anchor.path,
            card.anchor.line_range.start,
            card.anchor.id.path,
            card.anchor.id.content_hash,
            card.anchor.id.start_byte,
            card.anchor.byte_range.start,
            card.anchor.byte_range.end,
            card.anchor.content_hash,
            card.anchor.source.source_id.as_str(),
            card.anchor.content_generation,
            voice,
            role_evidence_label(evidence),
            evidence_anchor.id.path,
            evidence_anchor.id.content_hash,
            evidence_anchor.id.start_byte,
            evidence_anchor.byte_range.start,
            evidence_anchor.byte_range.end,
            candidates.len().saturating_sub(1),
        ));
    }
}

fn role_evidence_anchor(
    evidence: &RoleEvidence,
) -> &crate::live_index::knowledge_bridge::KnowledgeAnchor {
    match evidence {
        RoleEvidence::DeclaredSpan(anchor)
        | RoleEvidence::HeadingRule { anchor, .. }
        | RoleEvidence::PathConvention { anchor, .. } => anchor,
    }
}

fn card_candidate_key<'a>(candidate: &CardCandidate<'a>) -> (u8, &'a str, u32, u32) {
    (
        match candidate.1 {
            RoleEvidence::DeclaredSpan(_) => 0,
            RoleEvidence::HeadingRule { .. } => 1,
            RoleEvidence::PathConvention { .. } => 2,
        },
        candidate.0.anchor.path.as_str(),
        candidate.0.anchor.byte_range.start,
        candidate.0.anchor.byte_range.end,
    )
}

fn role_evidence_label(evidence: &RoleEvidence) -> String {
    match evidence {
        RoleEvidence::DeclaredSpan(_) => "declared_span".to_string(),
        RoleEvidence::HeadingRule { rule_id, .. } => format!("heading:{rule_id}"),
        RoleEvidence::PathConvention { rule_id, .. } => format!("path:{rule_id}"),
    }
}

fn role_label(role: &KnowledgeRole) -> &'static str {
    match role {
        KnowledgeRole::Architecture => "architecture",
        KnowledgeRole::OwnershipGovernance => "ownership_governance",
        KnowledgeRole::DecisionInvariant => "decision_invariant",
        KnowledgeRole::SchemaContract => "schema_contract",
        KnowledgeRole::Operations => "operations",
        KnowledgeRole::TestingSecurity => "testing_security",
        KnowledgeRole::PlanHandoff => "plan_handoff",
        KnowledgeRole::Other => "other",
    }
}

fn voice_label(voice: KnowledgeVoice) -> &'static str {
    match voice {
        KnowledgeVoice::Current => "current",
        KnowledgeVoice::Intent => "intent",
        KnowledgeVoice::NeedsReview => "needs_review",
        KnowledgeVoice::Unknown => "unknown",
        KnowledgeVoice::HistoryOnly => "history_only",
        KnowledgeVoice::Suppressed => "suppressed",
    }
}

fn derived_coverage_label(coverage: &DerivedCoverage) -> String {
    match coverage {
        DerivedCoverage::Complete => "complete".to_string(),
        DerivedCoverage::Truncated { breaches } => format!(
            "truncated({})",
            breaches
                .iter()
                .map(|breach| format!("{}:{}", snake_debug(&breach.kind), breach.omitted))
                .collect::<Vec<_>>()
                .join(",")
        ),
    }
}

fn snake_debug(value: &impl std::fmt::Debug) -> String {
    let debug = format!("{value:?}");
    let mut output = String::with_capacity(debug.len());
    for (index, character) in debug.chars().enumerate() {
        if character.is_ascii_uppercase() {
            if index > 0 {
                output.push('_');
            }
            output.push(character.to_ascii_lowercase());
        } else {
            output.push(character);
        }
    }
    output
}

#[cfg(test)]
mod tests {
    use std::fs;

    use tempfile::TempDir;

    use super::*;
    use crate::live_index::LiveIndex;

    #[test]
    fn repository_map_reports_current_intent_missing_roles_hygiene_and_coverage() {
        let root = TempDir::new().unwrap();
        fs::write(
            root.path().join("README.md"),
            "# Architecture\nCurrent system shape.\n",
        )
        .unwrap();
        fs::create_dir_all(root.path().join("docs/design")).unwrap();
        fs::write(
            root.path().join("docs/design/intent.md"),
            "# Operations\nProposed operating model.\n",
        )
        .unwrap();
        fs::write(
            root.path().join("docs/contributors.md"),
            "# Contributors\nAlice and Bob contributed.\n",
        )
        .unwrap();

        let shared = LiveIndex::load(root.path()).unwrap();
        let published = shared.published_generation();
        let rendered = render_repository_knowledge_map(&published);

        assert!(rendered.contains("Repository knowledge:"));
        assert!(rendered.contains(&format!(
            "publication={} content={}",
            published.publication_generation, published.content_generation
        )));
        assert!(rendered.contains("Current roles:"));
        assert!(rendered.contains("architecture README.md:1"));
        assert!(rendered.contains("cards=1 shown=1 overflow=0"));
        assert!(rendered.contains("unit_id=README.md#"));
        assert!(rendered.contains("bytes="));
        assert!(rendered.contains("content_hash="));
        assert!(rendered.contains("evidence_anchor=README.md#"));
        assert!(rendered.contains("Intent roles:"));
        assert!(rendered.contains("operations docs/design/intent.md:1"));
        assert!(rendered.contains("Missing roles:"));
        assert!(rendered.contains("ownership_governance"));
        assert!(rendered.contains("Hygiene:"));
        assert!(rendered.contains("Coverage:"));
        assert!(!rendered.contains("ownership_governance docs/contributors.md"));
    }

    #[test]
    fn repository_map_is_byte_stable_and_caps_each_role_to_one_card() {
        let root = TempDir::new().unwrap();
        fs::write(
            root.path().join("README.md"),
            "# Architecture\nCurrent system shape.\n## Architecture\nSecond shape.\n",
        )
        .unwrap();

        let shared = LiveIndex::load(root.path()).unwrap();
        let published = shared.published_generation();
        let first = render_repository_knowledge_map(&published);
        let second = render_repository_knowledge_map(&published);

        assert_eq!(first, second);
        assert_eq!(first.matches("architecture README.md:").count(), 1);
        assert!(first.contains("overflow=1"));
    }

    #[test]
    fn code_context_caps_exact_and_declared_backlinks_with_complete_counts() {
        let root = TempDir::new().unwrap();
        fs::create_dir_all(root.path().join("src")).unwrap();
        fs::write(root.path().join("src/lib.rs"), "pub fn launch() {}\n").unwrap();
        fs::create_dir_all(root.path().join("docs")).unwrap();
        for ordinal in 0..6 {
            fs::write(
                root.path().join(format!("docs/link-{ordinal}.md")),
                format!("# Link {ordinal}\n[code](../src/lib.rs)\n"),
            )
            .unwrap();
        }
        fs::create_dir_all(root.path().join(".github")).unwrap();
        fs::write(
            root.path().join(".github/CODEOWNERS"),
            "/src/*.rs @runtime-team\n",
        )
        .unwrap();

        let shared = LiveIndex::load(root.path()).unwrap();
        let published = shared.published_generation();
        let target = CodeAnchorId::File {
            path: "src/lib.rs".to_string(),
        };
        let rendered = render_code_knowledge_context(&published, &target, true).unwrap();

        assert!(rendered.contains("Knowledge evidence:"));
        assert!(rendered.contains(&format!(
            "publication={} content={}",
            published.publication_generation, published.content_generation
        )));
        assert!(rendered.contains("total=7 shown=5 overflow=2"));
        assert_eq!(rendered.matches(" link_id=").count(), 5);
        assert!(rendered.contains("lifecycle="));
        assert!(rendered.contains("voice="));
        assert!(rendered.contains("bridge=complete authority=complete"));

        let absent = render_code_knowledge_context(
            &published,
            &CodeAnchorId::File {
                path: "assets/other.bin".to_string(),
            },
            false,
        );
        assert!(absent.is_none());
    }

    #[test]
    fn code_context_renders_ambiguous_bridge_state_with_bounded_exact_samples() {
        let root = TempDir::new().unwrap();
        fs::create_dir_all(root.path().join("src/a")).unwrap();
        fs::create_dir_all(root.path().join("src/b")).unwrap();
        fs::create_dir_all(root.path().join("docs")).unwrap();
        fs::write(root.path().join("src/a/lib.rs"), "pub fn launch() {}\n").unwrap();
        fs::write(root.path().join("src/b/lib.rs"), "pub fn launch() {}\n").unwrap();
        fs::write(root.path().join("docs/link.md"), "# Link\n`launch`\n").unwrap();

        let shared = LiveIndex::load(root.path()).unwrap();
        let published = shared.published_generation();
        let target =
            resolve_symbol_code_anchor(&published, "src/a/lib.rs", "launch", Some("fn"), Some(1))
                .expect("target");
        let rendered = render_code_knowledge_context(&published, &target, true).unwrap();

        assert!(rendered.contains("ambiguous=1"), "{rendered}");
        assert!(rendered.contains("resolution=ambiguous(2"), "{rendered}");
        assert!(
            rendered.contains("samples=[symbol:src/a/lib.rs:launch"),
            "{rendered}"
        );
        assert!(rendered.contains("bytes="), "{rendered}");
        assert!(rendered.contains("content_hash="), "{rendered}");
    }
}