sinter-io 0.57.1

Persistent, evidence-backed code graph for coding agents
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
//! `sinter show <symbol>`: the "I found it, now orient me" card — grouped,
//! capped, evidence-tagged. One bounded screen, never a BFS dump.

use std::collections::BTreeMap;
use std::path::Path;

use anyhow::Result;
use serde_json::{Value, json};
use sinter_core::{Edge, Evidence, Node, Relation};
use sinter_resolve::qualified_of;
use sinter_store::{EdgeFilter, Store};

use crate::lookup::{ensure_snapshot, open_store, resolve_symbol_in, short_list};
use crate::render::{ellipsize, line_of, location, node_json, site_json, site_location};

/// Rows shown per relation group before collapsing to `… (+N)`.
pub const DEFAULT_LIMIT: usize = 20;

/// Lines of source printed by `--body` when `--context-lines` is absent.
pub const DEFAULT_BODY_LINES: usize = 10;

/// A bounded source excerpt plus how much of the span it left out, so a
/// cut is never silent: the card says "N more lines" and the JSON carries
/// `excerpt_truncated`/`excerpt_total_lines`.
pub(crate) struct Excerpt {
    pub text: String,
    /// Lines in the whole span, shown or not.
    pub total_lines: usize,
    pub truncated: bool,
}

/// Set `excerpt`, `excerpt_truncated` and `excerpt_total_lines` on a
/// `show` envelope. The one writer for CLI `--json` and MCP `show`, so the
/// two stay byte-identical.
pub(crate) fn excerpt_json(out: &mut Value, body: &Excerpt) {
    out["excerpt"] = json!(body.text);
    out["excerpt_truncated"] = json!(body.truncated);
    out["excerpt_total_lines"] = json!(body.total_lines);
}

/// [`excerpt`] that also reports whether `lines` cut the span short.
pub(crate) fn excerpt_lines(
    repo: &Path,
    file: &str,
    start: u64,
    end: u64,
    lines: usize,
) -> Option<Excerpt> {
    let source = std::fs::read_to_string(repo.join(file)).ok()?;
    let start = (start as usize).min(source.len());
    let end = (end as usize).min(source.len()).max(start);
    let body = source.get(start..end)?;
    let all: Vec<&str> = body.lines().collect();
    let total_lines = all.len();
    Some(Excerpt {
        text: all[..lines.min(total_lines)].join("\n"),
        total_lines,
        truncated: total_lines > lines,
    })
}

/// The symbol's edges after `--relations` / `--scope`: outgoing first,
/// incoming second. Scope applies to the far end of each edge; contains
/// edges survive only when no relation restriction was given.
pub fn edges(store: &Store, node: &Node, filter: &EdgeFilter) -> Result<(Vec<Edge>, Vec<Edge>)> {
    let scopes = store.scope_index()?;
    let keep = |e: &Edge, other: &str| {
        filter
            .relations
            .as_ref()
            .is_none_or(|set| set.contains(&e.relation))
            && filter.scopes.as_ref().is_none_or(|set| {
                let file = other.split_once('#').map_or(other, |(f, _)| f);
                set.contains(&scopes.scope_of_id(other, file))
            })
    };
    let out = store
        .out_edges(&node.id)?
        .into_iter()
        .filter(|e| keep(e, e.dst.as_str()))
        .collect();
    let inn = store
        .in_edges(&node.id)?
        .into_iter()
        .filter(|e| keep(e, e.src.as_str()))
        .collect();
    Ok((out, inn))
}

/// `outgoing`/`incoming` arrays capped at `limit` per relation, plus
/// `totals` and (only when something was cut) `truncated` per group —
/// the same convention as `affected`. Shared by the CLI and MCP `show`.
pub fn edges_json(
    repo: &Path,
    store: &Store,
    node: &Node,
    filter: &EdgeFilter,
    limit: usize,
) -> Result<Value> {
    let (out, inn) = edges(store, node, filter)?;
    let mut totals = json!({});
    let mut truncated = json!({});
    let mut direction = |name: &str, edges: &[Edge], other: fn(&Edge) -> &str| -> Vec<Value> {
        let mut seen: BTreeMap<&str, usize> = BTreeMap::new();
        let mut rows = Vec::new();
        for e in edges {
            let n = seen.entry(e.relation.as_str()).or_default();
            *n += 1;
            if *n <= limit {
                rows.push(json!({
                    "symbol": qualified_of(other(e)),
                    "relation": e.relation.as_str(),
                    "evidence": e.evidence.as_str(),
                    "site": site_json(repo, e),
                }));
            }
        }
        for (rel, n) in seen {
            totals[name][rel] = json!(n);
            if n > limit {
                truncated[name][rel] = json!(n - limit);
            }
        }
        rows
    };
    let outgoing = direction("outgoing", &out, |e| e.dst.as_str());
    let incoming = direction("incoming", &inn, |e| e.src.as_str());
    let mut v = json!({"outgoing": outgoing, "incoming": incoming, "totals": totals});
    if truncated.as_object().is_some_and(|m| !m.is_empty()) {
        v["truncated"] = truncated;
    }
    Ok(v)
}

/// Join `shown` exemplars and collapse the rest to `… (+N) · --limit`.
fn listed(shown: Vec<String>, total: usize) -> String {
    let mut out = shown.join(", ");
    if total > shown.len() {
        out.push_str(&format!(", … (+{}) · --limit", total - shown.len()));
    }
    out
}

fn short(id: &str) -> &str {
    let q = qualified_of(id);
    q.rsplit("::").next().unwrap_or(q)
}

fn names(edges: &[&Edge], end: fn(&Edge) -> &str, limit: usize) -> String {
    listed(
        edges
            .iter()
            .take(limit)
            .map(|e| short(end(e)).to_string())
            .collect(),
        edges.len(),
    )
}

fn evidence_tally(edges: &[&Edge]) -> String {
    let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
    for e in edges {
        *counts.entry(e.evidence.as_str()).or_default() += 1;
    }
    counts
        .iter()
        .map(|(k, v)| format!("{k} {v}"))
        .collect::<Vec<_>>()
        .join(" · ")
}

/// Ok(true) when the symbol resolved (grep-style exit codes).
pub fn run(
    repo: &Path,
    symbol: &str,
    filter: &EdgeFilter,
    limit: usize,
    json: bool,
    if_snapshot: Option<&str>,
    body_lines: Option<usize>,
) -> Result<bool> {
    let repo = repo.canonicalize()?;
    let store = open_store(&repo)?;
    let snapshot = ensure_snapshot(&store, if_snapshot)?;
    let resolved = resolve_symbol_in(&store, symbol, filter.scopes.as_ref())?;
    let node = &resolved.node;
    let scope = store.file_scope(&node.file)?;
    let body = body_lines
        .and_then(|n| excerpt_lines(&repo, &node.file, node.span.start, node.span.end, n));
    if json {
        // Same shape as the MCP `show` tool.
        let mut out = edges_json(&repo, &store, node, filter, limit)?;
        let mut symbol_json = node_json(node);
        symbol_json["scope"] = json!(scope.as_str());
        out["symbol"] = symbol_json;
        out["snapshot"] = json!(snapshot);
        if let Some(body) = &body {
            excerpt_json(&mut out, body);
        }
        crate::agent_protocol::write_json(&out)?;
        return Ok(true);
    }
    let line = line_of(&repo, &node.file, node.span.start);

    // A tie-broken pick is part of the answer, not a stderr aside: say
    // which one won, and hand back the selector that re-resolves to it.
    let selector = resolved.selector();
    if !resolved.ignored.is_empty() {
        println!(
            "resolved: {selector} ({} other{} ignored by {}: {})",
            resolved.ignored.len(),
            if resolved.ignored.len() == 1 { "" } else { "s" },
            resolved.reason,
            short_list(&resolved.ignored)
        );
    }
    println!(
        "{} {}    {} ({}..{}) [{scope}]",
        node.kind.as_str(),
        qualified_of(node.id.as_str()),
        location(&repo, &node.file, line),
        node.span.start,
        node.span.end,
    );
    if let Some(doc) = &node.doc {
        for l in doc.lines().take(3) {
            println!("  /// {l}");
        }
    }
    if !node.signature.is_empty() {
        println!("  {}", ellipsize(&node.signature, 110));
    }
    if let Some(body) = &body {
        for l in body.text.lines() {
            println!("  | {l}");
        }
        if body.truncated {
            println!(
                "  | … {} more lines (--context-lines {} for all)",
                body.total_lines - body.text.lines().count(),
                body.total_lines
            );
        }
    }
    println!();

    let (out, inn) = edges(&store, node, filter)?;

    let group =
        |rel: Relation| -> Vec<&Edge> { out.iter().filter(|e| e.relation == rel).collect() };
    let contains = group(Relation::Contains);
    if !contains.is_empty() {
        println!(
            "contains ({})    {}",
            contains.len(),
            names(&contains, |e| e.dst.as_str(), limit)
        );
    }
    let extends = group(Relation::Extends);
    if !extends.is_empty() {
        println!(
            "extends          {}    [{}]",
            names(&extends, |e| e.dst.as_str(), limit),
            evidence_tally(&extends)
        );
    }
    let imports = group(Relation::Imports);
    if !imports.is_empty() {
        println!(
            "imports ({})     {}    [{}]",
            imports.len(),
            names(&imports, |e| e.dst.as_str(), limit),
            evidence_tally(&imports)
        );
    }

    let implements = group(Relation::Implements);
    if !implements.is_empty() {
        println!(
            "implements       {}    [{}]",
            names(&implements, |e| e.dst.as_str(), limit),
            evidence_tally(&implements)
        );
    }
    // Implementors are the answer to "who is behind this trait", not
    // dependents of it — listed by name, kept out of the used-by tally.
    let implementors: Vec<&Edge> = inn
        .iter()
        .filter(|e| e.relation == Relation::Implements)
        .collect();
    if !implementors.is_empty() {
        println!(
            "implemented by ({})    {}    [{}]",
            implementors.len(),
            names(&implementors, |e| e.src.as_str(), limit),
            evidence_tally(&implementors)
        );
    }

    // used by: incoming non-contains, non-implements edges grouped by
    // source file.
    let dependents: Vec<&Edge> = inn
        .iter()
        .filter(|e| !matches!(e.relation, Relation::Contains | Relation::Implements))
        .collect();
    if !dependents.is_empty() {
        // Per src file: edge count plus one representative call site (the
        // smallest span start — matches the stored representative).
        let mut per_file: BTreeMap<&str, (usize, Option<u64>)> = BTreeMap::new();
        for e in &dependents {
            let file = e
                .src
                .as_str()
                .split_once('#')
                .map_or(e.src.as_str(), |(f, _)| f);
            let entry = per_file.entry(file).or_default();
            entry.0 += 1;
            if let Some(span) = e.site {
                entry.1 = Some(entry.1.map_or(span.start, |s| s.min(span.start)));
            }
        }
        println!(
            "used by ({} files, {} edges)",
            per_file.len(),
            dependents.len()
        );
        let mut rows: Vec<(&str, (usize, Option<u64>))> = per_file.into_iter().collect();
        rows.sort_by(|a, b| b.1.0.cmp(&a.1.0).then_with(|| a.0.cmp(b.0)));
        for (file, (count, site)) in rows.iter().take(limit) {
            let line = site.and_then(|byte| line_of(&repo, file, byte));
            println!("  {}   {count} edges", location(&repo, file, line));
        }
        if rows.len() > limit {
            println!("  … (+{} files) · --limit", rows.len() - limit);
        }
    }

    // Dynamic call edges fan a trait method out to its implementations.
    // Short names collide by construction (every impl is `speak`), so
    // these are listed qualified, apart from the direct calls.
    let dispatches: Vec<&Edge> = out
        .iter()
        .filter(|e| e.relation == Relation::Calls && e.evidence == Evidence::Dynamic)
        .collect();
    if !dispatches.is_empty() {
        let shown = dispatches
            .iter()
            .take(limit)
            .map(|e| qualified_of(e.dst.as_str()).to_string())
            .collect();
        println!(
            "dispatches to ({})    {}",
            dispatches.len(),
            listed(shown, dispatches.len())
        );
    }

    // One row per relation: a `uses` edge (type reference) is never a call.
    for (label, rel) in [("calls", Relation::Calls), ("uses", Relation::Uses)] {
        let edges: Vec<&Edge> = out
            .iter()
            .filter(|e| e.relation == rel && e.evidence != Evidence::Dynamic)
            .collect();
        if edges.is_empty() {
            continue;
        }
        // Exemplars carry their site (`name (file:line)`) so "A calls B"
        // comes with "at file:line" instead of forcing a follow-up grep.
        let shown = edges
            .iter()
            .take(limit)
            .map(|e| {
                let name = short(e.dst.as_str());
                match site_location(&repo, e) {
                    Some(site) => format!("{name} ({site})"),
                    None => name.to_string(),
                }
            })
            .collect();
        println!(
            "{:<16} {}    [{}]",
            format!("{label} ({})", edges.len()),
            listed(shown, edges.len()),
            evidence_tally(&edges)
        );
    }

    println!();
    println!("Next: sinter affected {selector} --max-depth 3");
    Ok(true)
}

#[cfg(test)]
mod tests {
    use super::excerpt_lines;

    fn fixture(body: &str) -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("a.rs"), body).unwrap();
        dir
    }

    #[test]
    fn excerpt_caps_lines_and_slices_the_span() {
        let dir = fixture("fn a() {\n1\n2\n3\n}\n");
        let got = excerpt_lines(dir.path(), "a.rs", 0, 15, 2)
            .map(|e| e.text)
            .unwrap();
        assert_eq!(got, "fn a() {\n1");
    }

    #[test]
    fn excerpt_lines_reports_the_cut() {
        let dir = fixture("fn a() {\n1\n2\n3\n}\n");
        let cut = excerpt_lines(dir.path(), "a.rs", 0, 17, 2).unwrap();
        assert_eq!((cut.total_lines, cut.truncated), (5, true));
        let whole = excerpt_lines(dir.path(), "a.rs", 0, 17, 5).unwrap();
        assert_eq!((whole.total_lines, whole.truncated), (5, false));
        assert_eq!(whole.text, "fn a() {\n1\n2\n3\n}");
    }

    #[test]
    fn excerpt_clamps_out_of_range_spans() {
        let dir = fixture("fn a() {}\n");
        assert_eq!(
            excerpt_lines(dir.path(), "a.rs", 3, 9_999, 10)
                .map(|e| e.text)
                .unwrap(),
            "a() {}"
        );
        // Reversed span clamps to empty instead of panicking.
        assert_eq!(
            excerpt_lines(dir.path(), "a.rs", 8, 2, 10)
                .map(|e| e.text)
                .unwrap(),
            ""
        );
    }

    #[test]
    fn excerpt_degrades_on_missing_file_and_char_boundaries() {
        let dir = fixture("// \u{e9}\n");
        assert!(
            excerpt_lines(dir.path(), "missing.rs", 0, 4, 10)
                .map(|e| e.text)
                .is_none()
        );
        // Byte 4 lands inside the two-byte \u{e9}.
        assert!(
            excerpt_lines(dir.path(), "a.rs", 0, 4, 10)
                .map(|e| e.text)
                .is_none()
        );
    }
}