gobby-code 1.3.2

Fast Rust CLI for Gobby's code index — AST-aware search, symbol navigation, and dependency graph
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
//! Per-page content pass for the curated navigation layer.
//!
//! The structure pass ([`super::concepts`]) names concepts and narrative
//! chapters and gives each a one-line summary. That alone renders thin (a
//! sentence wrapped in provenance). This module runs a second, per-page LLM
//! pass that expands each page into a grounded, multi-section body, with a
//! deterministic structural fallback so `--ai off` and generation failures
//! still produce real structure rather than a bare summary (#853).
//!
//! It is deliberately decoupled from the `ConceptModule`/`NarrativePage`
//! structs: callers pass the primitive member lists, and we hand back a body
//! string. That keeps `concepts.rs` under the 1,000-line rule while this file
//! owns the content-pass + fallback logic.

use std::collections::BTreeMap;
use std::fmt::Write as _;

use super::super::*;

/// Cap on key-symbol evidence rows fed into one content prompt. Bounds prompt
/// size; the structural fallback table reuses the same cap.
const MAX_PAGE_SYMBOL_ROWS: usize = 12;

/// Which curated page voice to generate. Selects the system prompt and the
/// prompt builder: concept pages are reference explainers, narrative pages are
/// guided-tour chapters.
#[derive(Clone, Copy)]
pub(crate) enum CuratedPageKind {
    Concept,
    Narrative,
}

/// Outcome of the per-page content pass.
pub(crate) struct CuratedBody {
    /// The multi-section page body, ready to drop in after the page title.
    /// `None` only when the page has no member content to describe at all.
    pub(crate) body: Option<String>,
    /// True when a content-pass generation was attempted and failed, so the
    /// page fell back to the structural body. Recorded honestly rather than
    /// hidden behind fallback prose (review #1). `false` for `--ai off` skips,
    /// where the structural body is the intended, non-degraded output.
    pub(crate) degraded: bool,
    pub(crate) verify_notes: Vec<VerifyNote>,
}

/// Run the content pass for one curated page.
///
/// `spans` are the page-specific spans used to ground the generated prose
/// (concept item spans / narrative spans), never the whole-input span set.
#[allow(clippy::too_many_arguments)]
pub(crate) fn curated_page_body(
    kind: CuratedPageKind,
    title: &str,
    summary: &str,
    member_modules: &[String],
    member_files: &[String],
    module_lookup: &BTreeMap<&str, &ModuleDoc>,
    file_lookup: &BTreeMap<&str, &FileDoc>,
    leading_chunks: &BTreeMap<String, LeadingChunk>,
    spans: &[SourceSpan],
    generate: &mut Option<&mut TextGenerator<'_>>,
    verify: &mut Option<&mut TextVerifier<'_>>,
) -> CuratedBody {
    let members = member_evidence_rows(member_modules, member_files, module_lookup, file_lookup);
    let symbols = symbol_evidence_rows(member_files, file_lookup);
    if members.is_empty() && symbols.is_empty() {
        return CuratedBody {
            body: None,
            degraded: false,
            verify_notes: Vec::new(),
        };
    }

    let excerpt_take = match kind {
        CuratedPageKind::Concept => prompts::CONCEPT_PAGE_SOURCE_EXCERPTS,
        CuratedPageKind::Narrative => prompts::NARRATIVE_PAGE_SOURCE_EXCERPTS,
    };
    let member_file_docs = member_files
        .iter()
        .filter_map(|file| file_lookup.get(file.as_str()).copied());
    let sources = ranked_source_excerpts(member_file_docs, leading_chunks, excerpt_take);

    let prompt = match kind {
        CuratedPageKind::Concept => {
            prompts::concept_page_prompt(title, summary, &members, &symbols, &sources)
        }
        CuratedPageKind::Narrative => {
            prompts::narrative_page_prompt(title, summary, &members, &symbols, &sources)
        }
    };
    let system = match kind {
        CuratedPageKind::Concept => prompts::CONCEPT_PAGE_SYSTEM,
        CuratedPageKind::Narrative => prompts::NARRATIVE_PAGE_SYSTEM,
    };

    match maybe_generate(generate, &prompt, system, PromptTier::Aggregate) {
        Generation::Generated(text) => {
            // Grounded verification leaves prose intact and records unsupported
            // claims as frontmatter-only notes.
            // Curated pages carry no per-file relationship facts; the verifier
            // audits them against members/symbols/source excerpts only.
            let verification_evidence =
                verifier_evidence_rows(members.iter().chain(symbols.iter()));
            let (text, verify_notes) = match verify_with_notes(
                verify,
                &text,
                &verification_evidence,
                &sources,
                &RelationshipFacts::default(),
            ) {
                VerifyOutcome::Skipped => (text, Vec::new()),
                VerifyOutcome::Verified { text, notes } => (text, notes),
            };
            let grounded = ground_text(&text, spans, None);
            if grounded.trim().is_empty() {
                CuratedBody {
                    body: Some(structural_body(kind, title, &members, &symbols)),
                    degraded: true,
                    verify_notes: Vec::new(),
                }
            } else {
                CuratedBody {
                    body: Some(grounded),
                    degraded: false,
                    verify_notes,
                }
            }
        }
        Generation::Failed => CuratedBody {
            body: Some(structural_body(kind, title, &members, &symbols)),
            degraded: true,
            verify_notes: Vec::new(),
        },
        Generation::Skipped => CuratedBody {
            body: Some(structural_body(kind, title, &members, &symbols)),
            degraded: false,
            verify_notes: Vec::new(),
        },
    }
}

fn member_evidence_rows(
    member_modules: &[String],
    member_files: &[String],
    module_lookup: &BTreeMap<&str, &ModuleDoc>,
    file_lookup: &BTreeMap<&str, &FileDoc>,
) -> Vec<prompts::PageEvidenceRow> {
    let mut rows = Vec::new();
    for module in member_modules {
        if let Some(doc) = module_lookup.get(module.as_str()) {
            rows.push(prompts::PageEvidenceRow {
                name: doc.module.clone(),
                kind: "module".to_string(),
                citation: span_citation(&doc.source_spans, &doc.module),
                summary: doc.summary.clone(),
            });
        }
    }
    for file in member_files {
        if let Some(doc) = file_lookup.get(file.as_str()) {
            rows.push(prompts::PageEvidenceRow {
                name: doc.path.clone(),
                kind: "file".to_string(),
                citation: span_citation(&doc.source_spans, &doc.path),
                summary: doc.summary.clone(),
            });
        }
    }
    rows
}

fn symbol_evidence_rows(
    member_files: &[String],
    file_lookup: &BTreeMap<&str, &FileDoc>,
) -> Vec<prompts::PageEvidenceRow> {
    let mut rows = Vec::new();
    for file in member_files {
        if let Some(doc) = file_lookup.get(file.as_str()) {
            for symbol in &doc.symbols {
                rows.push(prompts::PageEvidenceRow {
                    name: symbol.symbol.name.clone(),
                    kind: symbol.symbol.kind.clone(),
                    citation: symbol.source_span.citation(),
                    summary: symbol.purpose.clone(),
                });
            }
        }
    }
    // Most important first (most defined symbols → most central), stable on ties.
    rows.sort_by(|a, b| a.name.cmp(&b.name));
    rows.truncate(MAX_PAGE_SYMBOL_ROWS);
    rows
}

fn verifier_evidence_rows<'a>(
    rows: impl Iterator<Item = &'a prompts::PageEvidenceRow>,
) -> Vec<prompts::SymbolSummary> {
    rows.enumerate()
        .map(|(index, row)| {
            let (line_start, line_end) = citation_line_range(&row.citation).unwrap_or((1, 1));
            prompts::SymbolSummary {
                name: row.name.clone(),
                kind: row.kind.clone(),
                component_id: format!("curated-evidence-{}", index + 1),
                component_label: row.citation.clone(),
                line_start,
                line_end,
                purpose: row.summary.clone(),
            }
        })
        .collect()
}

fn citation_line_range(citation: &str) -> Option<(usize, usize)> {
    let inner = citation.strip_prefix('[')?.strip_suffix(']')?;
    let (_file, range) = inner.rsplit_once(':')?;
    let (start, end) = match range.split_once('-') {
        Some((start, end)) => (start.parse().ok()?, end.parse().ok()?),
        None => {
            let line = range.parse().ok()?;
            (line, line)
        }
    };
    Some((start, end))
}

fn span_citation(spans: &[SourceSpan], fallback: &str) -> String {
    spans
        .first()
        .map(SourceSpan::citation)
        .unwrap_or_else(|| fallback.to_string())
}

/// Deterministic multi-section fallback body: a real `## Purpose`, a
/// `## Key components` table grounded in symbol citations, and a member list.
/// Mirrors `structural_file_summary` so `--ai off` and content-pass failures
/// still yield structure, not a bare summary.
fn structural_body(
    kind: CuratedPageKind,
    title: &str,
    members: &[prompts::PageEvidenceRow],
    symbols: &[prompts::PageEvidenceRow],
) -> String {
    let mut body = String::new();
    match kind {
        CuratedPageKind::Concept => {
            write_section(
                &mut body,
                "Purpose",
                &format!(
                    "{title} groups the related modules and files listed below; \
                     read the key components for the grounded detail."
                ),
            );
        }
        CuratedPageKind::Narrative => {
            write_section(
                &mut body,
                "Why this matters",
                &format!(
                    "{title} walks through the modules and files listed below; \
                     follow the key components in order, then continue to the linked pages."
                ),
            );
        }
    }

    body.push_str("## Key components\n\n");
    if symbols.is_empty() {
        body.push_str("- No indexed symbols.\n\n");
    } else {
        write_markdown_table_header(&mut body, &["Symbol", "Kind", "Source", "Role"]);
        for row in symbols {
            write_markdown_table_row(
                &mut body,
                [
                    row.name.clone(),
                    row.kind.clone(),
                    row.citation.clone(),
                    row.summary.clone(),
                ],
            );
        }
        body.push('\n');
    }

    if !members.is_empty() {
        body.push_str("## Members\n\n");
        for row in members {
            let _ = writeln!(body, "- `{}` ({}) {}", row.name, row.kind, row.citation);
        }
        body.push('\n');
    }
    body
}

/// Renders the "Start here — guided tour" block shared by the front page and
/// the concept index: a "new to this codebase" callout, the dependency-ordered
/// narrative chapters numbered 1..N, and a one-line pointer to ask/search the
/// same vault. Navigation only — no new generation. Takes `(slug, title)`
/// pairs so it stays decoupled from the `NarrativePage` struct.
pub(crate) fn append_guided_tour(doc: &mut String, chapters: &[(&str, &str)]) {
    doc.push_str("## Start here — guided tour\n\n");
    if let Some((slug, title)) = chapters.first() {
        let _ = writeln!(
            doc,
            "New to this codebase? Begin with [[code/narrative/{slug}|{title}]].\n"
        );
    }
    for (index, (slug, title)) in chapters.iter().enumerate() {
        let _ = writeln!(doc, "{}. [[code/narrative/{slug}|{title}]]", index + 1);
    }
    doc.push('\n');
    append_ask_hint(doc);
}

/// One-line pointer to the conversational/search leg over the same vault.
pub(crate) fn append_ask_hint(doc: &mut String) {
    doc.push_str(
        "Ask questions across this vault with `gwiki ask \"...\"`, or find pages with `gwiki search \"...\"`.\n\n",
    );
}

/// Renders the reciprocal `Previous`/`Next` chapter navigation at the foot of a
/// narrative page. The links double as reciprocal wikilinks between adjacent
/// chapters, so the guided tour also strengthens backlinks (#853D).
pub(crate) fn append_tour_nav(
    doc: &mut String,
    prev: Option<(&str, &str)>,
    next: Option<(&str, &str)>,
) {
    if prev.is_none() && next.is_none() {
        return;
    }
    doc.push_str("## Continue the tour\n\n");
    if let Some((slug, title)) = prev {
        let _ = writeln!(doc, "- ← Previous: [[code/narrative/{slug}|{title}]]");
    }
    if let Some((slug, title)) = next {
        let _ = writeln!(doc, "- Next →: [[code/narrative/{slug}|{title}]]");
    }
    doc.push('\n');
}

/// One resolved stage of a curated page's behavior flow.
struct FlowComponent {
    /// Normalized match keys (module name / file stem) used to align this stage
    /// with a documented `A -> B -> C` data-flow chain in the evidence.
    keys: Vec<String>,
    label: String,
    role: Option<String>,
}

/// Bounded source-excerpt budget (chars per file) scanned for a documented
/// data-flow chain. Keeps the hint grounded in real excerpts without pulling
/// whole files into the scan.
const FLOW_HINT_EXCERPT_CHARS: usize = 600;
/// Word cap on a stage's role phrase so node labels stay legible.
const FLOW_ROLE_WORDS: usize = 8;

/// Build the conceptual-behavior flow diagram for a curated concept/narrative
/// page. Grounded strictly in the page's member modules/files: each stage is a
/// real member, its role phrase comes from that member's grounded summary, and
/// the stage order follows a documented data flow — an `A -> B -> C` arrow chain
/// found in the member summaries or bounded source excerpts (e.g. a CLAUDE.md
/// "Data Flow" section indexed into the evidence) — when present, otherwise the
/// member declaration order. Returns `None` when there are fewer than two
/// members to chain, so callers can simply omit the section. When a stage lacks
/// a grounded role the diagram shows it by name only and its caption carries an
/// honest degradation note. Works for repos without curated docs because
/// module/file summaries are always available from indexing.
pub(crate) fn curated_flow_diagram(
    member_modules: &[String],
    member_files: &[String],
    module_lookup: &BTreeMap<&str, &ModuleDoc>,
    file_lookup: &BTreeMap<&str, &FileDoc>,
    leading_chunks: &BTreeMap<String, LeadingChunk>,
) -> Option<String> {
    let mut components = flow_components(member_modules, member_files, module_lookup, file_lookup);
    if components.len() < 2 {
        return None;
    }

    let hint = flow_hint_text(
        member_modules,
        member_files,
        module_lookup,
        file_lookup,
        leading_chunks,
    );
    let ordered_from_docs = order_components_by_hint(&mut components, &hint);
    let degraded = components.iter().any(|component| component.role.is_none());

    let steps = components
        .iter()
        .enumerate()
        .map(
            |(index, component)| architecture_diagrams::ConceptualFlowStep {
                id: format!("s{index}"),
                label: component.label.clone(),
                role: component.role.clone(),
            },
        )
        .collect::<Vec<_>>();

    architecture_diagrams::render_conceptual_flow(&steps, ordered_from_docs, degraded)
}

/// Resolve the page's members into flow stages. Modules are the subsystem unit;
/// files only flesh out the flow when there are too few modules to chain on
/// their own.
fn flow_components(
    member_modules: &[String],
    member_files: &[String],
    module_lookup: &BTreeMap<&str, &ModuleDoc>,
    file_lookup: &BTreeMap<&str, &FileDoc>,
) -> Vec<FlowComponent> {
    let mut components: Vec<FlowComponent> = Vec::new();
    for module in member_modules {
        if let Some(doc) = module_lookup.get(module.as_str()) {
            components.push(component_from(&doc.module, &doc.summary));
        }
    }
    if components.len() < 2 {
        for file in member_files {
            if let Some(doc) = file_lookup.get(file.as_str()) {
                components.push(component_from(&doc.path, &doc.summary));
            }
        }
    }
    components
}

fn component_from(name: &str, summary: &str) -> FlowComponent {
    let label = flow_label(name);
    let mut keys = vec![normalize_key(name)];
    let label_key = normalize_key(&label);
    if !label_key.is_empty() && !keys.contains(&label_key) {
        keys.push(label_key);
    }
    keys.retain(|key| !key.is_empty());
    FlowComponent {
        keys,
        label,
        role: role_phrase(summary),
    }
}

/// Concatenate the member summaries and bounded leading-chunk excerpts into one
/// scan buffer for documented-data-flow detection.
fn flow_hint_text(
    member_modules: &[String],
    member_files: &[String],
    module_lookup: &BTreeMap<&str, &ModuleDoc>,
    file_lookup: &BTreeMap<&str, &FileDoc>,
    leading_chunks: &BTreeMap<String, LeadingChunk>,
) -> String {
    let mut text = String::new();
    for module in member_modules {
        if let Some(doc) = module_lookup.get(module.as_str()) {
            text.push_str(&doc.summary);
            text.push('\n');
        }
    }
    for file in member_files {
        if let Some(doc) = file_lookup.get(file.as_str()) {
            text.push_str(&doc.summary);
            text.push('\n');
        }
        if let Some(excerpt) = source_excerpt_for_file(file, leading_chunks) {
            let head: String = excerpt
                .excerpt
                .chars()
                .take(FLOW_HINT_EXCERPT_CHARS)
                .collect();
            text.push_str(&head);
            text.push('\n');
        }
    }
    text
}

/// Reorder `components` to follow a documented `A -> B -> C` data-flow chain in
/// `hint` when one references at least two of them. Returns true when the order
/// came from such a chain. Recognises ASCII `->`/`-->` and the Unicode `→`.
fn order_components_by_hint(components: &mut Vec<FlowComponent>, hint: &str) -> bool {
    let chain = parse_flow_chain(hint, components);
    if chain.len() < 2 {
        return false;
    }
    // Chain-matched stages first (documented order), then any remaining members
    // in their original order. Drain into slots so each stage moves exactly once.
    let mut slots: Vec<Option<FlowComponent>> = components.drain(..).map(Some).collect();
    let mut ordered: Vec<FlowComponent> = Vec::with_capacity(slots.len());
    for &index in &chain {
        if let Some(component) = slots[index].take() {
            ordered.push(component);
        }
    }
    for slot in &mut slots {
        if let Some(component) = slot.take() {
            ordered.push(component);
        }
    }
    *components = ordered;
    true
}

/// Find the first arrow-delimited line in `hint` that maps at least two
/// components, returning their indices in documented order.
fn parse_flow_chain(hint: &str, components: &[FlowComponent]) -> Vec<usize> {
    let normalized = hint.replace("-->", "\u{2192}").replace("->", "\u{2192}");
    for line in normalized.lines() {
        if !line.contains('\u{2192}') {
            continue;
        }
        let mut chain: Vec<usize> = Vec::new();
        for segment in line.split('\u{2192}') {
            if let Some(index) = first_component_in(segment, components) {
                push_unique(&mut chain, index);
            }
        }
        if chain.len() >= 2 {
            return chain;
        }
    }
    Vec::new()
}

/// Index of the first component named by any word in `segment`.
fn first_component_in(segment: &str, components: &[FlowComponent]) -> Option<usize> {
    segment
        .split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
        .map(normalize_key)
        .filter(|key| !key.is_empty())
        .find_map(|key| {
            components
                .iter()
                .position(|component| component.keys.contains(&key))
        })
}

fn push_unique(chain: &mut Vec<usize>, index: usize) {
    if !chain.contains(&index) {
        chain.push(index);
    }
}

/// Short, stable node label for a module name or file path: the last path/`::`
/// segment, with a `.rs` extension trimmed.
fn flow_label(name: &str) -> String {
    name.rsplit(['/', ':'])
        .next()
        .unwrap_or(name)
        .trim_end_matches(".rs")
        .trim()
        .to_string()
}

/// Lowercase alphanumeric match key from the last path/`::` segment (extension
/// dropped), for aligning members with a documented data-flow chain.
fn normalize_key(text: &str) -> String {
    let last = text.rsplit(['/', ':']).next().unwrap_or(text);
    let stem = last.split('.').next().unwrap_or(last);
    stem.chars()
        .filter(|c| c.is_ascii_alphanumeric())
        .flat_map(char::to_lowercase)
        .collect()
}

/// First clause of a member summary, capped to a few words, as the stage's
/// behavior role. `None` for an empty summary so the renderer shows the stage by
/// name only and marks the flow degraded.
fn role_phrase(summary: &str) -> Option<String> {
    let summary = summary.trim();
    if summary.is_empty() {
        return None;
    }
    let clause = summary
        .split_terminator(['.', ';', ':'])
        .next()
        .unwrap_or(summary)
        .trim();
    let phrase = clause
        .split_whitespace()
        .take(FLOW_ROLE_WORDS)
        .collect::<Vec<_>>()
        .join(" ");
    (!phrase.is_empty()).then_some(phrase)
}

#[cfg(test)]
mod flow_tests {
    use super::*;

    fn module_doc(name: &str, summary: &str) -> ModuleDoc {
        ModuleDoc {
            module: name.to_string(),
            summary: summary.to_string(),
            source_spans: Vec::new(),
            direct_files: Vec::new(),
            child_modules: Vec::new(),
            degraded: false,
            degraded_sources: Vec::new(),
            verify_notes: Vec::new(),
            reused_page: None,
        }
    }

    fn file_doc(path: &str, summary: &str) -> FileDoc {
        FileDoc {
            path: path.to_string(),
            module: String::new(),
            summary: summary.to_string(),
            body: String::new(),
            source_spans: Vec::new(),
            symbols: Vec::new(),
            component_ids: Vec::new(),
            degraded: false,
            degraded_sources: Vec::new(),
            verify_notes: Vec::new(),
            reused_page: None,
        }
    }

    fn module_lookup(docs: &[ModuleDoc]) -> BTreeMap<&str, &ModuleDoc> {
        docs.iter().map(|doc| (doc.module.as_str(), doc)).collect()
    }

    fn file_lookup(docs: &[FileDoc]) -> BTreeMap<&str, &FileDoc> {
        docs.iter().map(|doc| (doc.path.as_str(), doc)).collect()
    }

    #[test]
    fn verifier_evidence_preserves_curated_members_and_symbols() {
        let members = [prompts::PageEvidenceRow {
            name: "walker".to_string(),
            kind: "module".to_string(),
            citation: "[src/walker.rs:10-12]".to_string(),
            summary: "Discovers candidate files.".to_string(),
        }];
        let symbols = [prompts::PageEvidenceRow {
            name: "parse_plan".to_string(),
            kind: "function".to_string(),
            citation: "[src/plan.rs:42]".to_string(),
            summary: "Parses the navigation JSON.".to_string(),
        }];

        let rows = verifier_evidence_rows(members.iter().chain(symbols.iter()));

        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0].name, "walker");
        assert_eq!(rows[0].kind, "module");
        assert_eq!(rows[0].component_label, "[src/walker.rs:10-12]");
        assert_eq!((rows[0].line_start, rows[0].line_end), (10, 12));
        assert_eq!(rows[0].purpose, "Discovers candidate files.");
        assert_eq!(rows[1].name, "parse_plan");
        assert_eq!(rows[1].component_label, "[src/plan.rs:42]");
        assert_eq!((rows[1].line_start, rows[1].line_end), (42, 42));
    }

    #[test]
    fn chains_member_modules_grounded_in_summaries() {
        let modules = [
            module_doc("walker", "Discovers candidate files. Walks the tree."),
            module_doc("parser", "Extracts the AST via tree-sitter."),
        ];
        let member_modules = vec!["walker".to_string(), "parser".to_string()];

        let flow = curated_flow_diagram(
            &member_modules,
            &[],
            &module_lookup(&modules),
            &file_lookup(&[]),
            &BTreeMap::new(),
        );
        let section = flow.expect("flow drawn for two members");

        assert!(section.contains("## Conceptual flow"), "{section}");
        assert!(section.contains("flowchart LR"), "{section}");
        // Real member names only — no fabricated components.
        assert!(
            section.contains("walker — Discovers candidate files"),
            "{section}"
        );
        assert!(
            section.contains("parser — Extracts the AST via tree-sitter"),
            "{section}"
        );
        // Member-declaration order when nothing documents a flow.
        assert!(
            section.contains("in the order these subsystems are grouped"),
            "{section}"
        );
    }

    #[test]
    fn orders_by_documented_data_flow_when_present() {
        // Members are given out of flow order; one summary documents the real
        // pipeline, so the diagram follows it rather than the member order.
        let modules = [
            module_doc(
                "indexer",
                "Writes hub rows. Pipeline: walker -> parser -> chunker -> indexer.",
            ),
            module_doc("walker", "Discovers files."),
            module_doc("parser", "Extracts the AST."),
            module_doc("chunker", "Splits content for search."),
        ];
        let member_modules = vec![
            "indexer".to_string(),
            "walker".to_string(),
            "parser".to_string(),
            "chunker".to_string(),
        ];

        let flow = curated_flow_diagram(
            &member_modules,
            &[],
            &module_lookup(&modules),
            &file_lookup(&[]),
            &BTreeMap::new(),
        );
        let section = flow.expect("flow drawn");

        assert!(
            section.contains("ordered by the data flow documented"),
            "{section}"
        );
        // Documented order walker -> parser -> chunker -> indexer wins.
        assert!(
            section.contains("s0[\"walker — Discovers files\"]"),
            "{section}"
        );
        assert!(section.contains("s3[\"indexer"), "indexer last: {section}");
    }

    #[test]
    fn marks_degraded_when_a_member_summary_is_missing() {
        let modules = [
            module_doc("walker", "Discovers files."),
            module_doc("parser", ""),
        ];
        let member_modules = vec!["walker".to_string(), "parser".to_string()];

        let flow = curated_flow_diagram(
            &member_modules,
            &[],
            &module_lookup(&modules),
            &file_lookup(&[]),
            &BTreeMap::new(),
        );
        let section = flow.expect("flow drawn");

        assert!(section.contains("_Degraded:_"), "{section}");
        assert!(
            section.contains("s1[\"parser\"]"),
            "name-only node: {section}"
        );
    }

    #[test]
    fn omitted_for_a_single_member() {
        let modules = [module_doc("walker", "Discovers files.")];
        let flow = curated_flow_diagram(
            &["walker".to_string()],
            &[],
            &module_lookup(&modules),
            &file_lookup(&[]),
            &BTreeMap::new(),
        );
        assert!(flow.is_none());
    }

    #[test]
    fn falls_back_to_files_without_enough_modules() {
        let files = [
            file_doc("src/bm25.rs", "Runs BM25 keyword search."),
            file_doc("src/rrf.rs", "Fuses ranked results."),
        ];
        let member_files = vec!["src/bm25.rs".to_string(), "src/rrf.rs".to_string()];

        let flow = curated_flow_diagram(
            &[],
            &member_files,
            &module_lookup(&[]),
            &file_lookup(&files),
            &BTreeMap::new(),
        );
        let section = flow.expect("flow drawn from files");

        assert!(
            section.contains("bm25 — Runs BM25 keyword search"),
            "{section}"
        );
        assert!(section.contains("rrf — Fuses ranked results"), "{section}");
    }
}