sinter-io 0.52.2

sinter command-line interface
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
//! Coverage contract for graph traversals. Positive and negative answers
//! describe the same indexed snapshot, filters, evidence tiers, and gaps so
//! a non-empty syntax-only result is never mistaken for an exhaustive one.

use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use std::process::Command;

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use sinter_core::{Confidence, Evidence, Relation, UnresolvedReason, UnresolvedReference};
use sinter_store::{EdgeFilter, Store};

/// Evidence represented by one traversal answer. `possible` means inferred
/// graph edges, not a confirmed runtime dependency. `unresolved` is evidence
/// observed by extraction but not bound to a graph target.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct TraversalEvidence {
    pub certain: usize,
    pub possible: usize,
    pub unresolved: usize,
}

impl TraversalEvidence {
    pub fn from_confidences(
        confidences: impl IntoIterator<Item = Confidence>,
        unresolved: usize,
    ) -> Self {
        let mut evidence = Self {
            unresolved,
            ..Self::default()
        };
        for confidence in confidences {
            match confidence {
                Confidence::Certain => evidence.certain += 1,
                Confidence::Inferred => evidence.possible += 1,
            }
        }
        evidence
    }
}

#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct GraphHealth {
    syntax_error_files: BTreeSet<String>,
    failed_files: BTreeMap<String, String>,
}

fn health_path(repo: &Path) -> std::path::PathBuf {
    repo.join(".sinter").join("health.json")
}

fn read_health(repo: &Path) -> GraphHealth {
    std::fs::read(health_path(repo))
        .ok()
        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
        .unwrap_or_default()
}

/// Update extraction health incrementally. Failed files are retried on the
/// next build because their hash stamp is not committed; a later success
/// removes the persisted failure.
pub fn record_health(
    repo: &Path,
    touched: &[&str],
    removed: &[String],
    syntax_errors: &[String],
    failures: &[(String, String)],
) -> Result<()> {
    let mut health = read_health(repo);
    for file in touched
        .iter()
        .copied()
        .chain(removed.iter().map(String::as_str))
    {
        health.syntax_error_files.remove(file);
        health.failed_files.remove(file);
    }
    health
        .syntax_error_files
        .extend(syntax_errors.iter().cloned());
    health.failed_files.extend(failures.iter().cloned());

    let path = health_path(repo);
    let bytes = serde_json::to_vec_pretty(&health)?;
    if std::fs::read(&path).ok().as_deref() == Some(bytes.as_slice()) {
        return Ok(());
    }
    let tmp = path.with_extension("json.tmp");
    std::fs::write(&tmp, bytes).with_context(|| format!("write {}", tmp.display()))?;
    std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
    Ok(())
}

fn git_output(repo: &Path, args: &[&str]) -> Option<String> {
    let output = Command::new("git")
        .arg("-C")
        .arg(repo)
        .args(args)
        .output()
        .ok()?;
    output
        .status
        .success()
        .then(|| String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// What an unresolved reference most likely means, and whether anything
/// in this repository can be done about it. `reason` records how the miss
/// happened; the category says what it is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UnresolvedCategory {
    /// Nothing in the corpus defines the name: standard library, a
    /// dependency, or a shell builtin. Not a graph gap.
    LikelyExternal,
    /// A compiler index would settle it, and the file's language has one
    /// Sinter can run; the index is missing or stale.
    MissingCompilerIndex,
    /// A member call whose receiver type syntax extraction could not see;
    /// the name exists in the corpus.
    MissingReceiverType,
    /// The bare name is defined in several places and nothing picked one.
    AmbiguousInternalTarget,
    /// The reference site itself is not an identifier, or sits in a file
    /// indexed from a partial syntax tree.
    UnsupportedSyntax,
    /// Evidence anchored the reference inside the corpus and the target was
    /// still not found: a real gap worth a look.
    ActionableAnchoredMiss,
}

impl UnresolvedCategory {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::LikelyExternal => "likely_external",
            Self::MissingCompilerIndex => "missing_compiler_index",
            Self::MissingReceiverType => "missing_receiver_type",
            Self::AmbiguousInternalTarget => "ambiguous_internal_target",
            Self::UnsupportedSyntax => "unsupported_syntax",
            Self::ActionableAnchoredMiss => "actionable_anchored_miss",
        }
    }

    /// Categories a maintainer of this repository can act on.
    pub const fn is_actionable(self) -> bool {
        matches!(
            self,
            Self::MissingReceiverType
                | Self::AmbiguousInternalTarget
                | Self::ActionableAnchoredMiss
        )
    }
}

/// Repository facts the classifier needs once, not per reference.
pub struct Classifier {
    /// Definition count per bare name across the corpus, for every name
    /// that appears unresolved.
    definitions: std::collections::HashMap<String, usize>,
    syntax_error_files: BTreeSet<String>,
    /// A compiler index is missing or stale for these languages.
    unindexed_languages: Vec<String>,
}

impl Classifier {
    pub fn new(repo: &Path, store: &Store, refs: &[UnresolvedReference]) -> Result<Self> {
        let mut definitions = std::collections::HashMap::new();
        for item in refs {
            let name = item.reference.name.as_str();
            if !definitions.contains_key(name) {
                let count = store.nodes_named(name)?.len();
                definitions.insert(name.to_owned(), count);
            }
        }
        let unindexed_languages = match crate::scip::staleness(repo) {
            crate::scip::Staleness::Fresh => Vec::new(),
            _ => crate::scip::indexable_languages(repo),
        };
        Ok(Self {
            definitions,
            syntax_error_files: read_health(repo).syntax_error_files,
            unindexed_languages,
        })
    }

    pub fn classify(&self, item: &UnresolvedReference) -> UnresolvedCategory {
        let reference = &item.reference;
        let is_identifier = reference
            .name
            .chars()
            .all(|c| c.is_alphanumeric() || c == '_' || c == '$');
        if !is_identifier || self.syntax_error_files.contains(&reference.file) {
            return UnresolvedCategory::UnsupportedSyntax;
        }
        let defined = self
            .definitions
            .get(reference.name.as_str())
            .copied()
            .unwrap_or(0);
        if item.reason == UnresolvedReason::CompilerUnresolved || defined == 0 {
            return UnresolvedCategory::LikelyExternal;
        }
        let has_receiver = reference.path.as_deref().is_some_and(|path| {
            path.trim_end_matches(reference.name.as_str())
                .ends_with(['.', ':', '>'])
        });
        if item.reason == UnresolvedReason::SyntaxAnchoredMiss && !has_receiver {
            // Already anchored inside the corpus; an index would only
            // confirm what a reader can check now.
            return UnresolvedCategory::ActionableAnchoredMiss;
        }
        let language = sinter_extract::spec_for_path(&reference.file).map(|spec| spec.name);
        if language.is_some_and(|lang| self.unindexed_languages.iter().any(|l| l == lang)) {
            return UnresolvedCategory::MissingCompilerIndex;
        }
        if reference.relation == Relation::Calls && has_receiver {
            UnresolvedCategory::MissingReceiverType
        } else if item.reason == UnresolvedReason::SyntaxAnchoredMiss {
            UnresolvedCategory::ActionableAnchoredMiss
        } else {
            // defined >= 1 here; one definition with no anchor is still a
            // choice resolution declined to make.
            UnresolvedCategory::AmbiguousInternalTarget
        }
    }
}

/// Count per category, every category present so consumers need no
/// defaulting.
pub fn category_counts(
    classifier: &Classifier,
    refs: &[UnresolvedReference],
) -> BTreeMap<&'static str, usize> {
    let mut counts = BTreeMap::new();
    for item in refs {
        *counts
            .entry(classifier.classify(item).as_str())
            .or_default() += 1;
    }
    counts
}

pub(crate) fn repository_coverage(repo: &Path, store: &Store) -> Result<serde_json::Value> {
    let repo = crate::pipeline::discover_root(repo);
    let health = read_health(&repo);
    let head = git_output(&repo, &["rev-parse", "HEAD"]);
    // Sinter's own artifacts must not make the tree look dirty.
    let dirty = git_output(
        &repo,
        &["status", "--porcelain=v1", "--untracked-files=normal"],
    )
    .map(|status| {
        status
            .lines()
            .any(|line| !line.get(3..).unwrap_or("").starts_with(".sinter/"))
    });
    let indexing_projects = crate::scip::indexing_projects(&repo);
    let indexable_languages: BTreeSet<&str> = indexing_projects
        .iter()
        .flat_map(|project| project.languages.iter().map(String::as_str))
        .collect();
    let runnable_indexing = indexing_projects
        .iter()
        .any(|project| project.recommendation.is_some());
    let unavailable_indexing = indexing_projects
        .iter()
        .any(|project| project.status == "indexer_unavailable");
    let unconfigured_languages = crate::scip::unconfigured_indexable_languages(&repo);
    let (scip_state, stale_inputs) = match crate::scip::staleness(&repo) {
        crate::scip::Staleness::Fresh => ("fresh", 0),
        crate::scip::Staleness::Missing => ("missing", 0),
        crate::scip::Staleness::Stale(n) => ("stale", n),
    };
    let unresolved = store.all_unresolved_details()?;
    let mut reasons = BTreeMap::<&str, usize>::new();
    for item in &unresolved {
        *reasons.entry(item.reason.as_str()).or_default() += 1;
    }
    let classifier = Classifier::new(&repo, store, &unresolved)?;
    let categories = category_counts(&classifier, &unresolved);
    let actionable = unresolved
        .iter()
        .filter(|item| classifier.classify(item).is_actionable())
        .count();
    // Refs a compiler index would settle. Not actionable by hand, but
    // the headline must not let `actionable` read as "nearly complete".
    let waiting_on_scip = categories
        .get(UnresolvedCategory::MissingCompilerIndex.as_str())
        .copied()
        .unwrap_or(0);
    let waiting_suffix = if waiting_on_scip > 0 {
        format!(" · {waiting_on_scip} refs waiting on `sinter scip`")
    } else {
        String::new()
    };

    let mut limitations = vec![
        "a missing graph edge is not proof that no runtime path exists".to_string(),
        "dynamic dispatch edges are conservative candidates, not dependency-injection proof"
            .to_string(),
    ];
    if scip_state == "missing" && runnable_indexing {
        limitations.push(format!(
            "compiler index missing for configured {} project(s); run `sinter scip`{waiting_suffix}",
            indexable_languages
                .iter()
                .copied()
                .collect::<Vec<_>>()
                .join(", ")
        ));
    } else if scip_state == "missing" && !indexing_projects.is_empty() {
        limitations.push(
            "compiler index missing for configured projects, but their indexers are unavailable; inspect compiler_index.projects for install guidance"
                .to_string(),
        );
    } else if scip_state == "missing" && !unconfigured_languages.is_empty() {
        limitations.push(format!(
            "compiler index missing for {} source files, but no configured SCIP project was detected; no indexing command is recommended",
            unconfigured_languages.join(", ")
        ));
    } else if scip_state == "stale" && runnable_indexing {
        limitations.push(format!(
            "compiler index is stale ({stale_inputs} newer source/config inputs); run `sinter scip`{waiting_suffix}"
        ));
    } else if scip_state == "stale" && unavailable_indexing {
        limitations.push(format!(
            "compiler index is stale ({stale_inputs} newer source/config inputs), but the required indexers are unavailable; inspect compiler_index.projects for install guidance"
        ));
    } else if scip_state == "stale" {
        limitations.push(format!(
            "compiler index is stale ({stale_inputs} newer source/config inputs), but no configured SCIP project needs a runnable refresh"
        ));
    }
    if !health.failed_files.is_empty() {
        limitations.push("one or more files failed extraction and are unindexed".to_string());
    }
    if !health.syntax_error_files.is_empty() {
        limitations.push("one or more files were indexed from partial syntax trees".to_string());
    }
    if actionable > 0 {
        limitations.push(format!(
            "{actionable} unresolved references point inside this repository; `sinter unresolved` lists them by category"
        ));
    }

    let completeness = if scip_state == "fresh"
        && health.failed_files.is_empty()
        && health.syntax_error_files.is_empty()
        && actionable == 0
    {
        "complete_for_indexed_snapshot"
    } else {
        "partial"
    };
    let available_sources = [
        ("structural", "available", "certain"),
        ("scope", "available", "possible"),
        ("import", "available", "possible"),
        ("dynamic", "available", "possible"),
        (
            "scip",
            if scip_state == "fresh" {
                "available"
            } else {
                scip_state
            },
            "certain",
        ),
    ]
    .into_iter()
    .map(|(kind, status, certainty)| {
        serde_json::json!({
            "kind": kind,
            "status": status,
            "certainty": certainty,
        })
    })
    .collect::<Vec<_>>();

    Ok(serde_json::json!({
        "completeness": completeness,
        "conclusive": false,
        "snapshot": {
            "head": head,
            "dirty": dirty,
            "working_tree_indexed": true,
            "node_id_scope": "snapshot",
            "graph_schema": Store::CURRENT_SCHEMA,
        },
        "compiler_index": {
            "state": scip_state,
            "indexable_languages": indexable_languages.into_iter().collect::<Vec<_>>(),
            "stale_inputs": stale_inputs,
            "projects": indexing_projects,
            "unconfigured_languages": unconfigured_languages,
        },
        "graph": {
            "unresolved_references": unresolved.len(),
            "unresolved_by_reason": reasons,
            "unresolved_by_category": categories,
            "actionable_unresolved": actionable,
            "missing_compiler_index": waiting_on_scip,
            "syntax_error_files": health.syntax_error_files,
            "unindexed_files": health.failed_files.keys().collect::<Vec<_>>(),
            "excluded_derived_roots": crate::corpus::DERIVED_ROOTS,
            "excluded_derived_dirs": crate::corpus::DERIVED_DIRS,
        },
        "available_sources": available_sources,
        "limitations": limitations,
    }))
}

/// Compact repository-health summary for the orientation card. The complete
/// traversal contract stays private to this module; Map needs only enough
/// evidence to stop a structural inventory from looking exhaustive.
pub(crate) fn orientation_health_json(repo: &Path, store: &Store) -> Result<serde_json::Value> {
    let coverage = repository_coverage(repo, store)?;
    let graph = &coverage["graph"];
    let count = |field: &str| graph[field].as_array().map_or(0, std::vec::Vec::len);
    Ok(serde_json::json!({
        "status": coverage["completeness"].clone(),
        "snapshot": coverage["snapshot"].clone(),
        "compiler_index": {
            "state": coverage["compiler_index"]["state"].clone(),
            "indexable_languages": coverage["compiler_index"]["indexable_languages"].clone(),
            "stale_inputs": coverage["compiler_index"]["stale_inputs"].clone(),
        },
        "graph": {
            "unresolved_references": graph["unresolved_references"].clone(),
            "actionable_unresolved": graph["actionable_unresolved"].clone(),
            "missing_compiler_index": graph["missing_compiler_index"].clone(),
            "syntax_error_files": count("syntax_error_files"),
            "unindexed_files": count("unindexed_files"),
        },
        "limitations": coverage["limitations"].clone(),
    }))
}

fn filter_json(filter: &EdgeFilter) -> serde_json::Value {
    let relation_values = filter
        .relations
        .as_ref()
        .map(|relations| {
            relations
                .iter()
                .map(|relation| relation.as_str())
                .collect::<Vec<_>>()
        })
        .unwrap_or_else(|| {
            [
                Relation::Calls,
                Relation::Uses,
                Relation::Imports,
                Relation::Implements,
                Relation::Extends,
            ]
            .into_iter()
            .map(Relation::as_str)
            .collect()
        });
    let evidence_values = filter
        .evidence
        .as_ref()
        .map(|evidence| {
            evidence
                .iter()
                .map(|item| item.as_str())
                .collect::<Vec<_>>()
        })
        .unwrap_or_else(|| {
            [
                Evidence::Structural,
                Evidence::Scope,
                Evidence::Import,
                Evidence::Scip,
                Evidence::Declared,
                Evidence::Dynamic,
            ]
            .into_iter()
            .map(Evidence::as_str)
            .collect()
        });
    let scope_values = filter
        .scopes
        .as_ref()
        .map(|scopes| {
            scopes
                .iter()
                .map(|scope| scope.as_str())
                .collect::<Vec<_>>()
        })
        .unwrap_or_else(|| {
            sinter_core::CorpusScope::ALL
                .into_iter()
                .map(sinter_core::CorpusScope::as_str)
                .collect()
        });
    serde_json::json!({
        "relations": {
            "mode": if filter.relations.is_some() { "restricted" } else { "all_dependencies" },
            "values": relation_values,
        },
        "evidence": {
            "mode": if filter.evidence.is_some() { "restricted" } else { "all_available" },
            "values": evidence_values,
        },
        "min_confidence": if filter.min_confidence == Some(Confidence::Certain) {
            "certain"
        } else {
            "any"
        },
        "scope": {
            "mode": if filter.scopes.is_some() { "restricted" } else { "all" },
            "values": scope_values,
        },
    })
}

/// What to tell a reader about unresolved references naming the queried
/// symbol: `sinter scip` binds them only while the index is missing or
/// stale; against a fresh index they are macro bodies, unsupported syntax,
/// or external names.
pub fn unresolved_hint(repo: &Path) -> &'static str {
    match crate::scip::staleness(repo) {
        crate::scip::Staleness::Fresh => {
            "macro body / unsupported syntax / external; not bindable by scip"
        }
        _ => "`sinter scip` would bind them",
    }
}

/// Full footer and full `coverage` JSON on demand; the default is the
/// compact agent-facing form. `doctor` is always full.
pub fn verbose() -> bool {
    std::env::var_os("SINTER_VERBOSE_COVERAGE").is_some()
}

/// Resource URI serving the repository-wide half of a coverage envelope,
/// so a collapsed `ref` can be resolved back to what it names.
pub(crate) const COVERAGE_URI: &str = "sinter://coverage";

/// The half of a traversal envelope that describes the repository rather
/// than the query. Identical for every answer computed from one graph
/// state, and therefore what a long-lived MCP session pays for again on
/// every call.
const SHARED_FIELDS: [&str; 7] = [
    "completeness",
    "conclusive",
    "snapshot",
    "compiler_index",
    "graph",
    "available_sources",
    "limitations",
];

/// Fingerprint of the repository-wide half, `None` when `coverage` is not a
/// traversal envelope. Session-scoped identity only: it must change when
/// the shared half changes, never survive the process.
fn shared_fingerprint(coverage: &serde_json::Value) -> Option<String> {
    use std::hash::{Hash, Hasher};

    let object = coverage.as_object()?;
    if !object.contains_key("completeness") {
        return None;
    }
    let shared: BTreeMap<&str, &serde_json::Value> = SHARED_FIELDS
        .iter()
        .filter_map(|field| object.get(*field).map(|value| (*field, value)))
        .collect();
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    serde_json::to_string(&shared).ok()?.hash(&mut hasher);
    Some(format!("cov-{:016x}", hasher.finish()))
}

/// Stamp every coverage envelope in `data` with its `ref`, and replace the
/// repository-wide half with that reference alone when the caller has
/// already been given it. Returns the fingerprint the answer carries, so a
/// session can decide what the next answer owes.
pub(crate) fn collapse_repeated(
    data: &mut serde_json::Value,
    known: Option<&str>,
) -> Option<String> {
    let mut carried = None;
    collapse_into(data, known, &mut carried);
    carried
}

fn collapse_into(value: &mut serde_json::Value, known: Option<&str>, carried: &mut Option<String>) {
    match value {
        serde_json::Value::Array(items) => {
            for item in items {
                collapse_into(item, known, carried);
            }
        }
        serde_json::Value::Object(object) => {
            if let Some(coverage) = object.get_mut("coverage")
                && let Some(fingerprint) = shared_fingerprint(coverage)
                && let Some(envelope) = coverage.as_object_mut()
            {
                if carried.is_none() {
                    *carried = Some(fingerprint.clone());
                }
                if known == Some(fingerprint.as_str()) {
                    envelope.retain(|field, _| !SHARED_FIELDS.contains(&field.as_str()));
                    envelope.insert(
                        "ref_note".to_string(),
                        serde_json::json!(format!(
                            "repository-wide coverage unchanged since the last full block \
                             in this session; read resource {COVERAGE_URI} for it"
                        )),
                    );
                }
                envelope.insert("ref".to_string(), serde_json::json!(fingerprint));
            }
            for (_, child) in object.iter_mut() {
                collapse_into(child, known, carried);
            }
        }
        _ => {}
    }
}

/// The repository-wide half on its own, shaped exactly as a traversal
/// envelope carries it: what a collapsed `ref` names.
pub(crate) fn shared_document(repo: &Path, store: &Store) -> Result<serde_json::Value> {
    let mut coverage = repository_coverage(repo, store)?;
    if !verbose() {
        slim_for_traversal(&mut coverage);
    }
    if let Some(object) = coverage.as_object_mut() {
        object.retain(|field, _| SHARED_FIELDS.contains(&field.as_str()));
    }
    if let Some(fingerprint) = shared_fingerprint(&coverage) {
        coverage["ref"] = serde_json::json!(fingerprint);
    }
    Ok(coverage)
}

const SYNTAX_ERROR_FILES_SHOWN: usize = 5;

/// Per-query envelope: repository-wide detail (every indexing project,
/// every partial-syntax file) belongs to `doctor`, not to each answer.
fn slim_for_traversal(coverage: &mut serde_json::Value) {
    crate::agent_protocol::slim_compiler_index(coverage);
    let graph = &mut coverage["graph"];
    if let Some(files) = graph["syntax_error_files"].as_array_mut() {
        let total = files.len();
        if total > SYNTAX_ERROR_FILES_SHOWN {
            files.truncate(SYNTAX_ERROR_FILES_SHOWN);
            graph["syntax_error_files_total"] = serde_json::json!(total);
        }
    }
}

/// Machine-readable trust envelope carried by every traversal answer.
pub fn traversal_json(
    repo: &Path,
    store: &Store,
    filter: &EdgeFilter,
    evidence: TraversalEvidence,
    found: bool,
) -> Result<serde_json::Value> {
    let mut coverage = repository_coverage(repo, store)?;
    coverage["status"] = serde_json::json!(if found { "found" } else { "not_proven" });
    if !verbose() {
        slim_for_traversal(&mut coverage);
    }
    coverage["filters"] = filter_json(filter);
    coverage["evidence"] = serde_json::json!({
        "count_scope": "all_matches_before_limit",
        "certain": {"results": evidence.certain},
        "possible": {"results": evidence.possible},
        "unresolved": {
            "matching_query": evidence.unresolved,
            "repository_total": coverage["graph"]["unresolved_references"],
            "actionable": coverage["graph"]["actionable_unresolved"],
            "missing_compiler_index": coverage["graph"]["missing_compiler_index"],
        },
    });
    Ok(coverage)
}

/// Text footer. Default: one `coverage:` line plus gaps specific to this
/// query (a missing/stale compiler index). `SINTER_VERBOSE_COVERAGE=1`
/// restores filters and every repository-wide limitation.
pub fn print_footer(
    repo: &Path,
    store: &Store,
    filter: &EdgeFilter,
    evidence: TraversalEvidence,
    found: bool,
    snapshot: Option<&str>,
) -> Result<()> {
    let coverage = traversal_json(repo, store, filter, evidence, found)?;
    let verbose = verbose();
    println!("{}", footer_line(&coverage, snapshot));
    if verbose {
        let relations = coverage["filters"]["relations"]["values"]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(serde_json::Value::as_str)
            .collect::<Vec<_>>()
            .join(",");
        println!(
            "  filters: relations={relations} min_confidence={} scope={}",
            coverage["filters"]["min_confidence"]
                .as_str()
                .unwrap_or("any"),
            coverage["filters"]["scope"]["values"]
                .as_array()
                .into_iter()
                .flatten()
                .filter_map(serde_json::Value::as_str)
                .collect::<Vec<_>>()
                .join(",")
        );
    }
    for text in query_gaps(&coverage, verbose) {
        println!("  gap: {text}");
    }
    Ok(())
}

fn footer_line(coverage: &serde_json::Value, snapshot: Option<&str>) -> String {
    let n = |v: &serde_json::Value| v.as_u64().unwrap_or(0);
    let mut line = format!(
        "  coverage: {} · {} certain · {} possible · {} unresolved naming query",
        coverage["completeness"].as_str().unwrap_or("partial"),
        n(&coverage["evidence"]["certain"]["results"]),
        n(&coverage["evidence"]["possible"]["results"]),
        n(&coverage["evidence"]["unresolved"]["matching_query"]),
    );
    if let Some(snapshot) = snapshot {
        line.push_str(&format!(" · snapshot {snapshot}"));
    }
    line
}

/// Limitations worth a line under this answer. Verbose keeps all of them;
/// the default keeps only compiler-index state, which changes what the
/// query could have seen. The generic disclaimers never print by default.
fn query_gaps(coverage: &serde_json::Value, verbose: bool) -> Vec<&str> {
    coverage["limitations"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(serde_json::Value::as_str)
        .filter(|text| verbose || text.starts_with("compiler index"))
        .collect()
}

/// Aggregate member coverage without flattening away which repository owns
/// a gap. Boundary evidence is declared separately because it comes from the
/// workspace manifest/link store, not a member compiler index.
pub fn workspace_json(
    workspace: &crate::workspace::Workspace,
    filter: &EdgeFilter,
    evidence: TraversalEvidence,
    found: bool,
) -> Result<serde_json::Value> {
    let mut members = serde_json::Map::new();
    let mut gaps = Vec::new();
    let mut partial = false;
    for (name, repo) in &workspace.members {
        let store = Store::open(crate::pipeline::db_path(repo))?;
        let member = repository_coverage(repo, &store)?;
        partial |= member["completeness"] == "partial";
        if let Some(items) = member["limitations"].as_array() {
            gaps.extend(items.iter().filter_map(|item| {
                item.as_str()
                    .map(|text| serde_json::json!({"member": name, "message": text}))
            }));
        }
        members.insert(name.clone(), member);
    }
    Ok(serde_json::json!({
        "status": if found { "found" } else { "not_proven" },
        "completeness": if partial { "partial" } else { "complete_for_indexed_snapshot" },
        "conclusive": false,
        "filters": filter_json(filter),
        "evidence": {
            "count_scope": "all_matches_before_limit",
            "certain": {"results": evidence.certain},
            "possible": {"results": evidence.possible},
            "unresolved": {"matching_query": evidence.unresolved},
        },
        "available_sources": {
            "member_graphs": "available",
            "boundary_imports": "available",
            "declared_manifest_links": "available",
        },
        "members": members,
        "gaps": gaps,
        "limitations": [
            "a workspace graph path is bounded by member extraction/index coverage and declared boundary links",
            "undeclared runtime coupling cannot be inferred as an exhaustive dependency path",
        ],
    }))
}

pub fn print_workspace_traversal(
    workspace: &crate::workspace::Workspace,
    filter: &EdgeFilter,
    evidence: TraversalEvidence,
    found: bool,
) -> Result<()> {
    print_workspace_footer(workspace, filter, evidence, found, None)
}

pub fn print_workspace_footer(
    workspace: &crate::workspace::Workspace,
    filter: &EdgeFilter,
    evidence: TraversalEvidence,
    found: bool,
    snapshot: Option<&str>,
) -> Result<()> {
    let coverage = workspace_json(workspace, filter, evidence, found)?;
    let verbose = verbose();
    println!("{}", footer_line(&coverage, snapshot));
    if let Some(gaps) = coverage["gaps"].as_array() {
        for gap in gaps {
            let message = gap["message"].as_str().unwrap_or("coverage unavailable");
            if !verbose && !message.starts_with("compiler index") {
                continue;
            }
            println!(
                "  gap: {}: {message}",
                gap["member"].as_str().unwrap_or("unknown"),
            );
        }
    }
    Ok(())
}

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

    use sinter_core::{
        Confidence, Evidence, Reference, Relation, Span, UnresolvedReason, UnresolvedReference,
    };
    use sinter_store::{EdgeFilter, Store};

    use super::{
        Classifier, TraversalEvidence, UnresolvedCategory, footer_line, orientation_health_json,
        query_gaps, slim_for_traversal, traversal_json,
    };

    fn item(name: &str, path: Option<&str>, reason: UnresolvedReason) -> UnresolvedReference {
        UnresolvedReference {
            reference: Reference {
                file: "src/lib.rs".into(),
                name: name.into(),
                path: path.map(str::to_owned),
                relation: Relation::Calls,
                span: Span { start: 0, end: 1 },
                enclosing: None,
                alias: None,
            },
            reason,
        }
    }

    fn classifier(defined: &[(&str, usize)], unindexed: &[&str]) -> Classifier {
        Classifier {
            definitions: defined
                .iter()
                .map(|(name, count)| ((*name).to_owned(), *count))
                .collect(),
            syntax_error_files: Default::default(),
            unindexed_languages: unindexed.iter().map(|l| (*l).to_owned()).collect(),
        }
    }

    #[test]
    fn undefined_names_are_external_and_anchored_misses_stay_actionable() {
        let c = classifier(&[("walk", 2), ("run", 1)], &["rust"]);
        assert_eq!(
            c.classify(&item("unwrap", None, UnresolvedReason::SyntaxOnly)),
            UnresolvedCategory::LikelyExternal
        );
        assert_eq!(
            c.classify(&item("walk", None, UnresolvedReason::SyntaxAnchoredMiss)),
            UnresolvedCategory::ActionableAnchoredMiss
        );
        assert_eq!(
            c.classify(&item("walk", None, UnresolvedReason::SyntaxOnly)),
            UnresolvedCategory::MissingCompilerIndex
        );
        assert_eq!(
            c.classify(&item(":", None, UnresolvedReason::SyntaxOnly)),
            UnresolvedCategory::UnsupportedSyntax
        );
    }

    #[test]
    fn receiver_calls_and_bare_names_split_when_no_index_applies() {
        let c = classifier(&[("walk", 2), ("run", 1)], &[]);
        assert_eq!(
            c.classify(&item(
                "run",
                Some("self.job.run"),
                UnresolvedReason::SyntaxOnly
            )),
            UnresolvedCategory::MissingReceiverType
        );
        assert_eq!(
            c.classify(&item("walk", None, UnresolvedReason::SyntaxOnly)),
            UnresolvedCategory::AmbiguousInternalTarget
        );
    }

    #[test]
    fn traversal_evidence_never_folds_possible_into_certain() {
        let evidence = TraversalEvidence::from_confidences(
            [
                Confidence::Certain,
                Confidence::Inferred,
                Confidence::Inferred,
            ],
            4,
        );
        assert_eq!(evidence.certain, 1);
        assert_eq!(evidence.possible, 2);
        assert_eq!(evidence.unresolved, 4);
    }

    #[test]
    fn positive_scip_backed_result_is_certain_but_only_snapshot_complete() {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path();
        std::fs::create_dir_all(repo.join("src")).unwrap();
        std::fs::create_dir_all(repo.join(".sinter")).unwrap();
        std::fs::write(
            repo.join("Cargo.toml"),
            "[package]\nname='fixture'\nversion='0.1.0'\n",
        )
        .unwrap();
        std::fs::write(repo.join("src/lib.rs"), "pub fn source() {}\n").unwrap();
        std::fs::write(repo.join(".sinter/index.scip"), []).unwrap();
        let store = Store::create(repo.join(".sinter/graph.redb")).unwrap();
        let filter = EdgeFilter {
            evidence: Some(BTreeSet::from([Evidence::Scip])),
            min_confidence: Some(Confidence::Certain),
            relations: Some(BTreeSet::from([Relation::Calls])),
            scopes: None,
        };
        let coverage = traversal_json(
            repo,
            &store,
            &filter,
            TraversalEvidence::from_confidences([Confidence::Certain], 0),
            true,
        )
        .unwrap();

        assert_eq!(coverage["status"], "found");
        assert_eq!(coverage["completeness"], "complete_for_indexed_snapshot");
        assert_eq!(coverage["conclusive"], false);
        assert_eq!(coverage["evidence"]["certain"]["results"], 1);
        assert_eq!(coverage["evidence"]["possible"]["results"], 0);
        assert_eq!(coverage["filters"]["evidence"]["values"][0], "scip");
        assert!(
            coverage["available_sources"]
                .as_array()
                .unwrap()
                .iter()
                .any(|source| source["kind"] == "scip" && source["status"] == "available")
        );
    }

    #[test]
    fn orientation_health_is_compact_and_names_complete_snapshot() {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path();
        std::fs::create_dir_all(repo.join("src")).unwrap();
        std::fs::create_dir_all(repo.join(".sinter")).unwrap();
        std::fs::write(
            repo.join("Cargo.toml"),
            "[package]\nname='fixture'\nversion='0.1.0'\n",
        )
        .unwrap();
        std::fs::write(repo.join("src/lib.rs"), "pub fn source() {}\n").unwrap();
        std::fs::write(repo.join(".sinter/index.scip"), []).unwrap();
        let store = Store::create(repo.join(".sinter/graph.redb")).unwrap();

        let health = orientation_health_json(repo, &store).unwrap();

        assert_eq!(health["status"], "complete_for_indexed_snapshot");
        assert_eq!(health["compiler_index"]["state"], "fresh");
        assert_eq!(health["graph"]["actionable_unresolved"], 0);
        assert!(health["compiler_index"].get("projects").is_none());
        assert!(health.get("available_sources").is_none());
    }

    #[test]
    fn compact_footer_is_one_line_and_keeps_only_index_gaps() {
        let coverage = serde_json::json!({
            "completeness": "partial",
            "evidence": {
                "certain": {"results": 10},
                "possible": {"results": 0},
                "unresolved": {"matching_query": 2},
            },
            "limitations": [
                "a missing graph edge is not proof that no runtime path exists",
                "compiler index is stale (3 newer source/config inputs); run `sinter scip`",
                "one or more files were indexed from partial syntax trees",
            ],
        });
        assert_eq!(
            footer_line(&coverage, Some("graph-v12-abc")),
            "  coverage: partial · 10 certain · 0 possible · 2 unresolved naming query · snapshot graph-v12-abc"
        );
        assert_eq!(
            query_gaps(&coverage, false),
            ["compiler index is stale (3 newer source/config inputs); run `sinter scip`"]
        );
        assert_eq!(query_gaps(&coverage, true).len(), 3);
    }

    #[test]
    fn traversal_json_slims_projects_and_caps_syntax_error_files() {
        let files: Vec<String> = (0..8).map(|i| format!("q{i}.sql")).collect();
        let mut coverage = serde_json::json!({
            "compiler_index": {
                "state": "fresh",
                "stale_inputs": 0,
                "projects": [{"freshness": "fresh", "languages": ["rust"], "root": "."}],
            },
            "graph": {"syntax_error_files": files},
        });
        slim_for_traversal(&mut coverage);
        assert!(coverage["compiler_index"].get("projects").is_none());
        assert_eq!(coverage["compiler_index"]["state"], "fresh");
        assert_eq!(
            coverage["graph"]["syntax_error_files"]
                .as_array()
                .unwrap()
                .len(),
            5
        );
        assert_eq!(coverage["graph"]["syntax_error_files_total"], 8);
    }
}