roteiro 1.21.0

Roteiro: a provenance-tagged knowledge graph for your codebase — structure, intent, and context in one queryable store
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
//! `roteiro review`: graph-grounded review context for the current change
//! (Stage 17). The CLI-first surface for a context-aware review — a human or an
//! agent can see, for the working-tree change, *what the graph knows* about each
//! touched symbol (who calls it, what governs it, what it's related to), the
//! authored-layer drift the change introduces, the intent-debt it adds, and the
//! blast radius of dependents to check — rather than reviewing the diff in
//! isolation. The MCP `explain`/`path`/`debt` tools expose the same graph as a
//! bonus; this command needs no server.

use std::collections::BTreeSet;

use rto_graph::{NodeContext, NodeKind, Store, StoreError, build_context, dependents};
use serde::Serialize;

/// Schema tag for the `--json` review report.
pub const REVIEW_SCHEMA: &str = "roteiro.review/v1";

/// A graph-grounded review of the working-tree change.
#[derive(Debug, Serialize)]
pub struct ReviewReport {
    /// Stable schema tag.
    pub schema: &'static str,
    /// Number of changed tracked files reviewed.
    pub changed_files: usize,
    /// Per-file review context.
    pub files: Vec<FileReview>,
    /// Authored-layer violations the change touches (drift to resolve first).
    pub drift: Vec<DriftItem>,
    /// Keys of nodes *outside* the change whose context includes a changed
    /// symbol — the blast radius to check for ripple effects.
    pub impacted: Vec<Impacted>,
}

impl ReviewReport {
    /// Whether the change introduces authored-layer drift (review should resolve
    /// it before merging).
    #[must_use]
    pub fn has_drift(&self) -> bool {
        !self.drift.is_empty()
    }
}

/// The review context for one changed file.
#[derive(Debug, Serialize)]
pub struct FileReview {
    /// Repository-relative path.
    pub path: String,
    /// Change status: currently `"added"`, `"modified"`, or `"deleted"`. This is
    /// an **open set** within `roteiro.review/v1` — consumers must treat an
    /// unrecognised value as a generic change (see `docs/JSON_SCHEMA.md`).
    pub status: &'static str,
    /// Symbols defined in the file, each with its graph neighbourhood.
    pub symbols: Vec<SymbolReview>,
    /// Intent-debt markers present in the file.
    pub debt: Vec<String>,
}

/// One changed symbol and the graph's view of it.
#[derive(Debug, Serialize)]
pub struct SymbolReview {
    /// Node key (`sym:<lang>:<path>#<Name>`).
    pub key: String,
    /// Simple name.
    pub name: String,
    /// Node kind token (`fn`, `struct`, …).
    pub kind: String,
    /// Keys that call this symbol — break these and you break them.
    pub callers: Vec<String>,
    /// Keys this symbol calls.
    pub callees: Vec<String>,
    /// Authored nodes (ADRs / sections) that link to this symbol — the intent
    /// governing it, to keep the change consistent with.
    pub governed_by: Vec<String>,
    /// Inferred (similarity) neighbours, with confidence.
    pub related: Vec<Related>,
}

/// An inferred neighbour of a symbol.
#[derive(Debug, Serialize)]
pub struct Related {
    /// The related node's key.
    pub node: String,
    /// Similarity confidence.
    pub confidence: Option<f64>,
}

/// An authored-layer violation the change touches.
#[derive(Debug, Serialize)]
pub struct DriftItem {
    /// Violation category label.
    pub kind: String,
    /// Human-readable message.
    pub message: String,
}

/// A node outside the change whose context includes a changed symbol.
#[derive(Debug, Serialize)]
pub struct Impacted {
    /// The node's key.
    pub key: String,
    /// Simple name.
    pub name: String,
    /// Node kind token.
    pub kind: String,
}

/// Assemble the review report for `changed`, using the already-synced `store`
/// (built from the same working tree) and the authored-layer `violations` the
/// change produced.
///
/// # Errors
/// Returns [`StoreError`] on a store query failure.
pub fn build(
    store: &Store,
    changed: &[rto_graph::ChangedFile],
    violations: &[rto_spec::Violation],
) -> Result<ReviewReport, StoreError> {
    let changed_paths: BTreeSet<&str> = changed.iter().map(|c| c.path.as_str()).collect();
    let mut files = Vec::new();
    let mut changed_keys: Vec<String> = Vec::new();

    for cf in changed {
        if cf.status == rto_graph::ChangeStatus::Deleted {
            files.push(FileReview {
                path: cf.path.clone(),
                status: "deleted",
                symbols: Vec::new(),
                debt: Vec::new(),
            });
            continue;
        }
        let mut symbols = Vec::new();
        let mut debt = Vec::new();
        for node in store.nodes_by_path(&cf.path)? {
            match node.kind {
                // The file node itself carries no reviewable neighbourhood.
                NodeKind::File => continue,
                NodeKind::Marker => {
                    debt.push(node.name.clone());
                    continue;
                }
                _ => {}
            }
            changed_keys.push(node.key.clone());
            let ctx = build_context(store, &node.key)?;
            symbols.push(symbol_review(&node, ctx.as_ref()));
        }
        files.push(FileReview {
            path: cf.path.clone(),
            status: cf.status.as_str(),
            symbols,
            debt,
        });
    }

    // Drift the change touches. A violation belongs to the change when its
    // message names a changed path *or* its subject node lives in a changed file
    // — the latter catches a broken ADR link whose message leads with the ADR's
    // node key (e.g. `adr:0001#decision: …`), not the ADR file path.
    let mut drift = Vec::new();
    for v in violations {
        if violation_touches(store, v, &changed_paths)? {
            drift.push(DriftItem {
                kind: v.kind.label().to_owned(),
                message: v.message.clone(),
            });
        }
    }

    // Blast radius: one-hop dependents of the changed symbols, minus the changed
    // symbols themselves and anything defined in a changed file (already shown).
    let changed_set: BTreeSet<&str> = changed_keys.iter().map(String::as_str).collect();
    let mut impacted = Vec::new();
    for key in dependents(store, &changed_keys)? {
        if changed_set.contains(key.as_str()) {
            continue;
        }
        let Some(node) = store.get_node(&key)? else {
            continue;
        };
        if node
            .path
            .as_deref()
            .is_some_and(|p| changed_paths.contains(p))
        {
            continue;
        }
        impacted.push(Impacted {
            key: node.key,
            name: node.name,
            kind: node.kind.as_str().to_owned(),
        });
    }

    Ok(ReviewReport {
        schema: REVIEW_SCHEMA,
        changed_files: changed.len(),
        files,
        drift,
        impacted,
    })
}

/// Whether an authored-layer `violation` belongs to the change: its message
/// either names a changed path, or its subject node (the key before the first
/// `": "` — node keys carry no colon-space) resolves to a node in a changed file.
fn violation_touches(
    store: &Store,
    violation: &rto_spec::Violation,
    changed_paths: &BTreeSet<&str>,
) -> Result<bool, StoreError> {
    if changed_paths.iter().any(|p| violation.message.contains(p)) {
        return Ok(true);
    }
    if let Some((key, _)) = violation.message.split_once(": ")
        && let Some(node) = store.get_node(key)?
    {
        return Ok(node
            .path
            .as_deref()
            .is_some_and(|p| changed_paths.contains(p)));
    }
    Ok(false)
}

/// Classify a changed node's one-hop context into a reviewer-facing summary.
// `callers`/`callees` are the standard call-graph terms; keep them despite being
// one character apart.
#[allow(clippy::similar_names)]
fn symbol_review(node: &rto_graph::Node, ctx: Option<&NodeContext>) -> SymbolReview {
    let mut callers = Vec::new();
    let mut callees = Vec::new();
    let mut governed_by = Vec::new();
    let mut related = Vec::new();
    if let Some(ctx) = ctx {
        // `related` is specifically the similarity relation (`EdgeKind::Related`),
        // not every inferred edge — inferred `references` etc. would be noise.
        for e in &ctx.incoming {
            if e.kind == "calls" {
                callers.push(e.node.clone());
            }
            if e.provenance == "authored" {
                governed_by.push(e.node.clone());
            }
            if e.kind == "related" {
                related.push(Related {
                    node: e.node.clone(),
                    confidence: e.confidence,
                });
            }
        }
        for e in &ctx.outgoing {
            if e.kind == "calls" {
                callees.push(e.node.clone());
            }
            if e.kind == "related" {
                related.push(Related {
                    node: e.node.clone(),
                    confidence: e.confidence,
                });
            }
        }
    }
    SymbolReview {
        key: node.key.clone(),
        name: node.name.clone(),
        kind: node.kind.as_str().to_owned(),
        callers,
        callees,
        governed_by,
        related,
    }
}

/// Score a candidate reviewer's run against the adjudicated corpus and print the
/// result (Stage 35).
///
/// Needs no graph, no model and no network: the corpus is embedded and the scoring
/// is pure. That is what makes it usable as a regression gate on a reviewer — the
/// numbers can be recomputed on any machine, including CI.
///
/// # Errors
/// If the run document cannot be read or scored, or the corpus override cannot be
/// read or parsed.
pub fn run_score(run_path: &str, corpus_path: Option<&str>, json: bool) -> anyhow::Result<()> {
    use rto_graph::review_corpus::Corpus;
    use rto_graph::review_score::{CandidateRun, score};

    let corpus = match corpus_path {
        Some(path) => {
            let text = std::fs::read_to_string(path)
                .map_err(|e| anyhow::anyhow!("reading corpus {path}: {e}"))?;
            Corpus::parse(&text).map_err(|e| anyhow::anyhow!("{path}: {e}"))?
        }
        None => rto_graph::review_corpus::builtin()?,
    };
    let text = std::fs::read_to_string(run_path)
        .map_err(|e| anyhow::anyhow!("reading run {run_path}: {e}"))?;
    let run = CandidateRun::parse(&text).map_err(|e| anyhow::anyhow!("{run_path}: {e}"))?;
    let scored = score(&corpus, &run)?;

    if json {
        crate::emit_json(&scored)?;
    } else {
        print_score(&scored);
    }
    Ok(())
}

/// Render a score as a per-class table.
///
/// The table is the report. A single headline number is deliberately absent: the
/// question an implementer is asking is *which* defect classes a reviewer can see,
/// and a mean over the classes — most of which hold a single row — answers a
/// question nobody asked while hiding the one they did. The exact denominators are
/// printed beside each rate rather than stated here, so this comment cannot go
/// stale as rows are added.
fn print_score(score: &rto_graph::review_score::Score) {
    println!(
        "scored {} of {} corpus commit(s)",
        score.attempted_shas, score.corpus_shas
    );
    println!("\nrecall by defect class (found/real):");
    for class in &score.per_class {
        if class.real == 0 {
            continue;
        }
        let rate = match class.recall() {
            Some(r) => format!("{:>4.0}%", r * 100.0),
            None => "".to_owned(),
        };
        // `n=1` is printed beside the rate, not left to the caveats, because a
        // reader scanning a column of percentages will otherwise compare 0% of one
        // row against 40% of five as though they weighed the same.
        let weight = if class.real == 1 { "  (n=1)" } else { "" };
        println!(
            "  {rate}  {:>2}/{:<2}  {}{weight}",
            class.found,
            class.real,
            class.class.as_str()
        );
        if class.misclassified > 0 {
            println!(
                "          {} found but labelled as another class",
                class.misclassified
            );
        }
        // The misses are the actionable half of a recall figure — "0/1
        // `cleanup-gap`" tells nobody what to look at. Printed with the anchor and
        // the permalink so the next step is opening a file, not grepping a fixture.
        for miss in &class.missed {
            println!(
                "          miss {}:{}{}",
                miss.path, miss.line, miss.description
            );
            println!("               {}", miss.comment_url);
        }
    }
    println!(
        "\n{}/{} real defect(s) found; {}/{} known-false claim(s) reproduced",
        score.found, score.real_in_scope, score.known_false_reproduced, score.known_false_in_scope
    );
    match score.corpus_precision() {
        Some(p) => println!(
            "precision over adjudicated findings only: {:.0}% \
             ({} unadjudicated finding(s) excluded — see below)",
            p * 100.0,
            score.unadjudicated
        ),
        None => println!(
            "precision: not computable — no finding matched an adjudicated row \
             ({} unadjudicated)",
            score.unadjudicated
        ),
    }
    if score.suppressed_real + score.suppressed_known_false + score.suppressed_unadjudicated > 0 {
        println!(
            "suppression filter withheld: {} real, {} known-false, {} unadjudicated",
            score.suppressed_real, score.suppressed_known_false, score.suppressed_unadjudicated
        );
    }
    let caveats = score.caveats();
    if !caveats.is_empty() {
        println!("\nread these numbers with:");
        for caveat in &caveats {
            println!("  - {caveat}");
        }
    }
}

#[cfg(test)]
mod tests {
    /// Freeze the `--json` schema tags (see `docs/JSON_SCHEMA.md`). These are the
    /// stable, versioned contracts; changing one is a breaking change that must
    /// bump the version deliberately — so a change here is caught in CI.
    #[test]
    fn json_schema_tags_are_frozen() {
        assert_eq!(super::REVIEW_SCHEMA, "roteiro.review/v1");
        assert_eq!(
            rto_graph::review_score::SCORE_SCHEMA,
            "roteiro.review-score/v1"
        );
        assert_eq!(rto_graph::review_score::RUN_SCHEMA, "roteiro.review-run/v1");
        assert_eq!(rto_graph::SCHEMA, "roteiro.query/v1");
        assert_eq!(rto_graph::ARTIFACT_SCHEMA, "roteiro.graph/v1");
        assert_eq!(rto_graph::ORACLE_SCHEMA, "roteiro.oracle/v1");
        assert_eq!(rto_spec::SPEC_SCHEMA, "roteiro.spec/v1");
    }
}