omnicoach 0.3.0

Lightweight, high-signal static analysis and command linter for Python and Rust
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
//! Alpha / experimental Layer L3 text renderers (`AnnotatedStubs` and `CompactBi`).
//!
//! Maps [`AbstractionGraph`] onto the two agent-facing formats selected in
//! `docs/dev/abstraction_graph/08_stage_c_agent_formats.md`.

use super::model::{
    AbstractionGraph, DeclarationKind, DeclarationNode, EdgeReason, GroupKind, GroupNode, NodeId,
    ReflexionStatus,
};
use crate::code_lint::ast::{FindingFact, RelationKind, Visibility};
use std::collections::BTreeMap;
use std::fmt::Write as _;

/// Alpha status banner included in rendered `# Scope:` headers.
const ALPHA_BANNER: &str =
    "[ALPHA — experimental, under active investigation & design; format may change at any time]";

/// Supported text output formats for `omnicoach graph`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OutputFormat {
    /// Code-stub hybrid combining language signatures and fields with `[Lk]` layers, ownership,
    /// and bidirectional edges (Stage C `F3`, default).
    #[default]
    AnnotatedStubs,
    /// Token-dense bidirectional (`-> uses` and `<- used_by`) graph DSL with `:start..end` spans
    /// without signature lines (Stage C `F2`, `--no-signatures`).
    CompactBi,
}

/// Serializes `graph` into `format`.
#[must_use]
pub(super) fn render_graph(graph: &AbstractionGraph, format: OutputFormat) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "# Scope: {} {ALPHA_BANNER}", graph.title());
    let idx = GraphEdgeIndex::build(graph);

    if graph.groups().is_empty() {
        for decl in graph.declarations() {
            write_decl(&mut out, decl, 0, true, format, &idx);
        }
    } else {
        for group in graph
            .groups()
            .iter()
            .filter(|group| graph.parent_of(&group.id).is_none())
        {
            write_group(&mut out, group, 0, false, format, &idx);
        }
    }
    out
}

const METHOD_KIND: &str = "method";
const TYPE_KIND: &str = "type";
const CALL_REASON: &str = "call";
const CTOR_TAG: &str = " [ctor]";

struct GraphEdgeIndex<'a> {
    decl_by_id: BTreeMap<&'a NodeId, &'a DeclarationNode>,
    group_by_id: BTreeMap<&'a NodeId, &'a GroupNode>,
    group_out_edges: BTreeMap<&'a NodeId, Vec<String>>,
    group_in_edges: BTreeMap<&'a NodeId, Vec<String>>,
    decl_out_edges: BTreeMap<&'a NodeId, Vec<String>>,
    decl_in_edges: BTreeMap<&'a NodeId, Vec<String>>,
}

impl<'a> GraphEdgeIndex<'a> {
    fn build(graph: &'a AbstractionGraph) -> Self {
        let decl_by_id: BTreeMap<&'a NodeId, &'a DeclarationNode> = graph
            .declarations()
            .iter()
            .map(|decl| (&decl.id, decl))
            .collect();
        let group_by_id: BTreeMap<&'a NodeId, &'a GroupNode> = graph
            .groups()
            .iter()
            .map(|group| (&group.id, group))
            .collect();

        let mut decl_module_path = BTreeMap::new();
        for decl in graph.declarations() {
            let mut cursor = graph.parent_of(&decl.id);
            while let Some(parent_id) = cursor {
                if let Some(group) = group_by_id.get(parent_id)
                    && let GroupKind::Module { path } = &group.kind
                {
                    decl_module_path.insert(&decl.id, path.as_str());
                    break;
                }
                cursor = graph.parent_of(parent_id);
            }
        }

        let mut group_out_edges: BTreeMap<&'a NodeId, Vec<String>> = BTreeMap::new();
        let mut group_in_edges: BTreeMap<&'a NodeId, Vec<String>> = BTreeMap::new();
        for edge in graph.summary_edges() {
            let higher_label = group_by_id
                .get(&edge.higher)
                .map_or_else(|| edge.higher.as_str(), |group| group.label.as_str());
            let lower_label = group_by_id
                .get(&edge.lower)
                .map_or_else(|| edge.lower.as_str(), |group| group.label.as_str());
            let reflexion_tag = edge.reflexion.map_or_else(String::new, |status| {
                format!(",{}", format_reflexion_status(status))
            });
            let tag = format!(
                "{} x{}{reflexion_tag}",
                format_short_reason(edge.reason),
                edge.count
            );
            group_out_edges
                .entry(&edge.higher)
                .or_default()
                .push(format!("{lower_label}[{tag}]"));
            group_in_edges
                .entry(&edge.lower)
                .or_default()
                .push(format!("{higher_label}[{tag}]"));
        }

        let mut decl_out_edges: BTreeMap<&'a NodeId, Vec<String>> = BTreeMap::new();
        let mut decl_in_edges: BTreeMap<&'a NodeId, Vec<String>> = BTreeMap::new();
        let mut ordering_pairs = std::collections::BTreeSet::new();
        for edge in graph.ordering_edges() {
            ordering_pairs.insert((&edge.higher, &edge.lower));
            let reason = format_short_reason(edge.reason);
            let target_label =
                format_relative_decl(&edge.higher, &edge.lower, &decl_by_id, &decl_module_path);
            let source_label =
                format_relative_decl(&edge.lower, &edge.higher, &decl_by_id, &decl_module_path);
            decl_out_edges
                .entry(&edge.higher)
                .or_default()
                .push(format!("{target_label}[{reason}]"));
            decl_in_edges
                .entry(&edge.lower)
                .or_default()
                .push(format!("{source_label}[{reason}]"));
        }
        for edge in graph.reference_edges() {
            if ordering_pairs.contains(&(&edge.source, &edge.target)) {
                continue;
            }
            let kind = format_short_ref_kind(edge.kind);
            let target_label =
                format_relative_decl(&edge.source, &edge.target, &decl_by_id, &decl_module_path);
            let source_label =
                format_relative_decl(&edge.target, &edge.source, &decl_by_id, &decl_module_path);
            decl_out_edges
                .entry(&edge.source)
                .or_default()
                .push(format!("{target_label}[{kind}]"));
            decl_in_edges
                .entry(&edge.target)
                .or_default()
                .push(format!("{source_label}[{kind}]"));
        }

        Self {
            decl_by_id,
            group_by_id,
            group_out_edges,
            group_in_edges,
            decl_out_edges,
            decl_in_edges,
        }
    }
}

fn write_group(
    out: &mut String,
    group: &GroupNode,
    depth: usize,
    in_module: bool,
    format: OutputFormat,
    idx: &GraphEdgeIndex<'_>,
) {
    let indent = "  ".repeat(depth);
    let now_in_module = in_module || matches!(group.kind, GroupKind::Module { .. });
    match &group.kind {
        GroupKind::Component {
            declared_dependencies,
        } => {
            let deps = format_declared_dependencies(declared_dependencies.as_deref());
            let _ = writeln!(
                out,
                "\n## Component [L{}] {}{deps}",
                group.level, group.label
            );
        }
        GroupKind::Module { path } => {
            let file_suffix =
                find_group_file(group, idx).map_or_else(String::new, |file| format!(" ({file})"));
            let _ = writeln!(out, "\n### Module [L{}] {path}{file_suffix}", group.level);
        }
        _ => {
            let kind = format_group_kind(&group.kind, &idx.decl_by_id);
            match format {
                OutputFormat::AnnotatedStubs => {
                    let _ = writeln!(out, "{indent}// === [L{}] {kind} ===", group.level);
                }
                OutputFormat::CompactBi => {
                    let _ = writeln!(out, "{indent}* [L{}] {kind}", group.level);
                }
            }
        }
    }

    let edge_indent = match &group.kind {
        GroupKind::Component { .. } | GroupKind::Module { .. } => String::new(),
        _ => "  ".repeat(depth + 1),
    };
    let comment_prefix = match format {
        OutputFormat::AnnotatedStubs => "// ",
        OutputFormat::CompactBi => "",
    };
    if let Some(outs) = idx.group_out_edges.get(&group.id) {
        let _ = writeln!(out, "{edge_indent}{comment_prefix}-> {}", outs.join(", "));
    }
    if let Some(ins) = idx.group_in_edges.get(&group.id) {
        let _ = writeln!(out, "{edge_indent}{comment_prefix}<- {}", ins.join(", "));
    }

    let next_depth = match &group.kind {
        GroupKind::Component { .. } | GroupKind::Module { .. } => 0,
        _ => depth + 1,
    };
    for child_id in &group.children {
        if let Some(child_group) = idx.group_by_id.get(child_id) {
            write_group(out, child_group, next_depth, now_in_module, format, idx);
        } else if let Some(decl) = idx.decl_by_id.get(child_id) {
            write_decl(out, decl, next_depth, !now_in_module, format, idx);
        }
    }
}

fn write_decl(
    out: &mut String,
    decl: &DeclarationNode,
    depth: usize,
    include_file: bool,
    format: OutputFormat,
    idx: &GraphEdgeIndex<'_>,
) {
    let indent = "  ".repeat(depth);
    let visibility_tag = format_short_visibility(decl.visibility);
    let kind_tag = format_short_decl_kind(decl.kind);
    let ctor_tag = if decl.is_constructor { CTOR_TAG } else { "" };
    let span = format_span(decl, include_file);
    let owner_names: Vec<&str> = decl
        .owners
        .iter()
        .map(|owner_id| {
            idx.decl_by_id
                .get(owner_id)
                .map_or_else(|| owner_id.as_str(), |owner| owner.name.as_str())
        })
        .collect();
    let roots = owner_names.join(", ");
    let edge_prefix = match format {
        OutputFormat::AnnotatedStubs => {
            let sig_text = decl.signature.as_deref().unwrap_or(decl.name.as_str());
            let _ = writeln!(
                out,
                "{indent}// [L{} {visibility_tag} {kind_tag}{ctor_tag} {} {span} roots=[{roots}]]",
                decl.level, decl.name
            );
            let _ = writeln!(out, "{indent}{sig_text}");
            format!("{indent}//   ")
        }
        OutputFormat::CompactBi => {
            let _ = writeln!(
                out,
                "{indent}- [L{}] {visibility_tag} {kind_tag}{ctor_tag} {} ({span}, roots=[{roots}])",
                decl.level, decl.name
            );
            "  ".repeat(depth + 1)
        }
    };
    if let Some(outs) = idx.decl_out_edges.get(&decl.id) {
        let _ = writeln!(out, "{edge_prefix}-> {}", outs.join(", "));
    }
    if let Some(ins) = idx.decl_in_edges.get(&decl.id) {
        let _ = writeln!(out, "{edge_prefix}<- {}", ins.join(", "));
    }
    for finding in &decl.findings {
        let _ = writeln!(out, "{edge_prefix}! {}", format_finding(finding));
    }
}

fn format_finding(finding: &FindingFact) -> String {
    let reason = finding.reason.map_or_else(String::new, |reason| {
        format!(" reason={}", format_short_reason(EdgeReason::from(reason)))
    });
    format!(
        "[{}] related={}{reason} anchor={}:{}",
        finding.rule, finding.related, finding.anchor.name, finding.anchor.line
    )
}

fn format_declared_dependencies(declared: Option<&[String]>) -> String {
    declared.map_or_else(String::new, |deps| {
        format!(" (depends_on=[{}])", deps.join(", "))
    })
}

fn format_relative_decl<'a>(
    from_id: &'a NodeId,
    to_id: &'a NodeId,
    decl_by_id: &BTreeMap<&'a NodeId, &'a DeclarationNode>,
    decl_module_path: &BTreeMap<&'a NodeId, &'a str>,
) -> String {
    let target_name = decl_by_id
        .get(to_id)
        .map_or_else(|| to_id.as_str(), |decl| decl.name.as_str());
    let from_mod = decl_module_path.get(from_id).copied();
    let to_mod = decl_module_path.get(to_id).copied();
    if from_mod != to_mod
        && let Some(mod_path) = to_mod
    {
        format!("{mod_path}::{target_name}")
    } else {
        target_name.to_owned()
    }
}

const fn format_short_reason(reason: EdgeReason) -> &'static str {
    match reason {
        EdgeReason::Call => CALL_REASON,
        EdgeReason::Containment => "contain",
        EdgeReason::ImplBehavior => "impl",
        EdgeReason::Encapsulation => "encap",
        EdgeReason::SignatureContract => "sig",
        EdgeReason::CrossModule => "xmod",
    }
}

const fn format_short_ref_kind(kind: RelationKind) -> &'static str {
    match kind {
        RelationKind::Parameter => "ref:param",
        RelationKind::Return => "ref:ret",
        RelationKind::Body => "ref:body",
        RelationKind::Composition => "ref:comp",
        RelationKind::Behavior => "ref:behav",
    }
}

const fn format_short_visibility(visibility: Visibility) -> &'static str {
    match visibility {
        Visibility::Public => "pub",
        Visibility::Private => "priv",
    }
}

const fn format_short_decl_kind(kind: DeclarationKind) -> &'static str {
    match kind {
        DeclarationKind::Callable => "fn",
        DeclarationKind::Method => METHOD_KIND,
        DeclarationKind::Type => TYPE_KIND,
    }
}

fn find_group_file<'a>(group: &'a GroupNode, idx: &GraphEdgeIndex<'a>) -> Option<&'a str> {
    for child_id in &group.children {
        if let Some(decl) = idx.decl_by_id.get(child_id) {
            return Some(decl.location.file.as_str());
        }
        if let Some(child_group) = idx.group_by_id.get(child_id)
            && let Some(found) = find_group_file(child_group, idx)
        {
            return Some(found);
        }
    }
    None
}

fn format_span(decl: &DeclarationNode, include_file: bool) -> String {
    let prefix = if include_file {
        decl.location.file.as_str()
    } else {
        ""
    };
    let (line, end_line) = (decl.location.line, decl.location.end_line);
    if end_line > line {
        format!("{prefix}:{line}..{end_line}")
    } else {
        format!("{prefix}:{line}")
    }
}

fn format_group_kind(kind: &GroupKind, decl_by_id: &BTreeMap<&NodeId, &DeclarationNode>) -> String {
    match kind {
        GroupKind::Component { .. } => "component".to_owned(),
        GroupKind::Module { path } => format!("module:{path}"),
        GroupKind::Owner { root } => {
            let owner_name = decl_by_id
                .get(root)
                .map_or_else(|| root.as_str(), |decl| decl.name.as_str());
            format!("owner:{owner_name}")
        }
        GroupKind::Shared { owners } => {
            let names: Vec<&str> = owners
                .iter()
                .map(|id| {
                    decl_by_id
                        .get(id)
                        .map_or_else(|| id.as_str(), |decl| decl.name.as_str())
                })
                .collect();
            format!("shared:{}", names.join("+"))
        }
        GroupKind::Unowned => "unowned".to_owned(),
        GroupKind::TypeMembers { type_id } => {
            let type_name = decl_by_id
                .get(type_id)
                .map_or_else(|| type_id.as_str(), |decl| decl.name.as_str());
            format!("type_members:{type_name}")
        }
        GroupKind::RecursionGroup { group_id } => format!("recursion_group:{group_id}"),
    }
}

const fn format_reflexion_status(status: ReflexionStatus) -> &'static str {
    match status {
        ReflexionStatus::Convergent => "convergent",
        ReflexionStatus::Absent => "absent",
        ReflexionStatus::Divergent => "divergent",
        ReflexionStatus::Inferred => "inferred",
    }
}

#[cfg(test)]
mod tests {
    use super::super::model::{
        GraphParts, OrderingEdge, ReferenceEdge, SourceLocation, SummaryEdge,
    };
    use super::*;
    use crate::code_lint::ast::{CallClusterRule, OrderingReason, PlacementAnchor};

    fn fixture_graph() -> AbstractionGraph {
        let entry = DeclarationNode {
            id: NodeId::new("s0:i0:entry"),
            name: "entry".to_owned(),
            signature: Some("pub fn entry(x: usize) -> bool".to_owned()),
            scope_id: 0,
            kind: DeclarationKind::Callable,
            visibility: Visibility::Public,
            is_constructor: false,
            location: SourceLocation {
                file: "src/fixture.rs".to_owned(),
                line: 10,
                column: 1,
                end_line: 18,
            },
            owners: vec![NodeId::new("s0:i0:entry")],
            recursion_group: 1,
            level: 1,
            findings: Vec::new(),
        };
        let helper = DeclarationNode {
            id: NodeId::new("s0:i1:helper"),
            name: "helper".to_owned(),
            signature: Some("fn helper(x: usize) -> bool".to_owned()),
            scope_id: 0,
            kind: DeclarationKind::Callable,
            visibility: Visibility::Private,
            is_constructor: false,
            location: SourceLocation {
                file: "src/fixture.rs".to_owned(),
                line: 20,
                column: 1,
                end_line: 25,
            },
            owners: vec![NodeId::new("s0:i0:entry")],
            recursion_group: 0,
            level: 0,
            findings: vec![FindingFact {
                rule: CallClusterRule::CalleeBeforeCaller,
                related: "entry".to_owned(),
                reason: Some(OrderingReason::Call),
                anchor: PlacementAnchor {
                    name: "entry".to_owned(),
                    line: 18,
                },
            }],
        };
        let owner_group = GroupNode {
            id: NodeId::new("owner:s0:i0:entry"),
            label: "entry".to_owned(),
            kind: GroupKind::Owner {
                root: NodeId::new("s0:i0:entry"),
            },
            recursion_group: 0,
            level: 1,
            children: vec![NodeId::new("s0:i0:entry"), NodeId::new("s0:i1:helper")],
        };
        AbstractionGraph::new(GraphParts {
            title: "src/fixture.rs".to_owned(),
            declarations: vec![entry, helper],
            groups: vec![owner_group],
            ordering_edges: vec![OrderingEdge {
                higher: NodeId::new("s0:i0:entry"),
                lower: NodeId::new("s0:i1:helper"),
                reason: EdgeReason::Call,
            }],
            reference_edges: vec![ReferenceEdge {
                source: NodeId::new("s0:i0:entry"),
                target: NodeId::new("s0:i1:helper"),
                kind: RelationKind::Body,
            }],
            summary_edges: Vec::<SummaryEdge>::new(),
        })
        .expect("valid fixture graph")
    }

    #[test]
    fn compact_bi_adapter_renders_bidirectional_edges_and_end_lines() {
        let graph = fixture_graph();

        let first = render_graph(&graph, OutputFormat::CompactBi);
        let second = render_graph(&graph, OutputFormat::CompactBi);

        assert_eq!(first, second);
        assert!(first.contains(ALPHA_BANNER));
        assert!(first.contains(":10..18"));
        assert!(first.contains("<- entry[call]"));
    }

    #[test]
    fn annotated_stubs_adapter_renders_signatures_and_used_by_edges() {
        let graph = fixture_graph();

        let first = render_graph(&graph, OutputFormat::AnnotatedStubs);
        let second = render_graph(&graph, OutputFormat::AnnotatedStubs);

        assert_eq!(first, second);
        assert!(first.contains(ALPHA_BANNER));
        assert!(first.contains("pub fn entry(x: usize) -> bool"));
        assert!(first.contains("//   <- entry[call]"));
    }

    #[test]
    fn project_renderers_emit_declared_dependencies_and_reflexion_statuses() {
        let comp_high = GroupNode {
            id: NodeId::new("comp:Runner"),
            label: "Runner".to_owned(),
            kind: GroupKind::Component {
                declared_dependencies: Some(vec!["Rules".to_owned()]),
            },
            recursion_group: 1,
            level: 1,
            children: vec![NodeId::new("mod:runner")],
        };
        let comp_low = GroupNode {
            id: NodeId::new("comp:Rules"),
            label: "Rules".to_owned(),
            kind: GroupKind::Component {
                declared_dependencies: Some(Vec::new()),
            },
            recursion_group: 0,
            level: 0,
            children: Vec::new(),
        };
        let mod_runner = GroupNode {
            id: NodeId::new("mod:runner"),
            label: "runner".to_owned(),
            kind: GroupKind::Module {
                path: "runner".to_owned(),
            },
            recursion_group: 0,
            level: 0,
            children: Vec::new(),
        };
        let graph = AbstractionGraph::new(GraphParts {
            title: "project".to_owned(),
            declarations: Vec::new(),
            groups: vec![comp_high, comp_low, mod_runner],
            ordering_edges: Vec::new(),
            reference_edges: Vec::new(),
            summary_edges: vec![SummaryEdge {
                higher: NodeId::new("comp:Runner"),
                lower: NodeId::new("comp:Rules"),
                reason: EdgeReason::CrossModule,
                count: 0,
                reflexion: Some(ReflexionStatus::Absent),
            }],
        })
        .expect("valid project fixture");

        let stubs = render_graph(&graph, OutputFormat::AnnotatedStubs);
        let compact = render_graph(&graph, OutputFormat::CompactBi);

        assert!(stubs.contains("## Component [L1] Runner (depends_on=[Rules])"));
        assert!(stubs.contains("## Component [L0] Rules (depends_on=[])"));
        assert!(stubs.contains("absent"));
        assert!(compact.contains("## Component [L1] Runner (depends_on=[Rules])"));
    }
}