open-kioku-core 2.0.1

Shared data models and schema types for Open Kioku code intelligence.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
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
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
use chrono::{DateTime, Utc};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;
use std::path::{Path, PathBuf};

macro_rules! id_type {
    ($name:ident) => {
        #[derive(
            Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
        )]
        pub struct $name(pub String);

        impl $name {
            pub fn new(value: impl Into<String>) -> Self {
                Self(value.into())
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(&self.0)
            }
        }
    };
}

id_type!(RepositoryId);
id_type!(FileId);
id_type!(FileVersionId);
id_type!(SymbolId);
id_type!(NodeId);
id_type!(EdgeId);
id_type!(PatchId);
id_type!(EvidenceId);
id_type!(MemoryFactId);
id_type!(ContextHandleId);

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Confidence {
    Low,
    Medium,
    High,
    Exact,
}

impl Confidence {
    pub fn score(self) -> f32 {
        match self {
            Self::Low => 0.35,
            Self::Medium => 0.6,
            Self::High => 0.85,
            Self::Exact => 1.0,
        }
    }

    pub fn from_score(score: f32) -> Self {
        if score >= 0.95 {
            Self::Exact
        } else if score >= 0.75 {
            Self::High
        } else if score >= 0.55 {
            Self::Medium
        } else {
            Self::Low
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ConfidenceBreakdown {
    pub overall_enum: Confidence,
    pub overall_score: f32,
    pub components: Vec<ScoreComponent>,
    pub blockers: Vec<String>,
    pub caveats: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct NegativeEvidence {
    pub query: String,
    pub scope: String,
    pub inspected_sources: Vec<String>,
    pub reason: String,
    pub confidence: f32,
    pub suggested_next_probe: Option<String>,
}

impl Default for ConfidenceBreakdown {
    fn default() -> Self {
        Self {
            overall_enum: Confidence::Low,
            overall_score: 0.0,
            components: Vec::new(),
            blockers: Vec::new(),
            caveats: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Copy, Default)]
pub struct ConfidenceSignalInput {
    pub primary_file_count: usize,
    pub evidence_count: usize,
    pub exact_reference_count: usize,
    pub validation_count: usize,
    pub validation_with_command_count: usize,
    pub negative_evidence_count: usize,
    pub allowed_file_count: usize,
    pub runtime_signal_count: usize,
}

impl ConfidenceBreakdown {
    pub fn from_signals(input: ConfidenceSignalInput) -> Self {
        let mut blockers = Vec::new();
        let mut caveats = Vec::new();

        if input.primary_file_count == 0 {
            blockers.push("no primary context matched the task".into());
        }
        if input.negative_evidence_count > 0 {
            blockers.push(format!(
                "{} negative evidence signal(s) lowered confidence",
                input.negative_evidence_count
            ));
        }
        if input.exact_reference_count == 0 {
            caveats.push("exact symbol/reference evidence is absent".into());
        }
        if input.validation_count == 0 {
            caveats.push("no validation target was selected".into());
        } else if input.validation_with_command_count == 0 {
            caveats.push("validation targets require manual commands".into());
        }
        if input.runtime_signal_count == 0 {
            caveats.push("runtime corroboration is absent".into());
        }
        if input.allowed_file_count == 0 {
            caveats.push("change boundary has no allowed files".into());
        } else if input.allowed_file_count > 8 {
            caveats.push("change boundary is broad".into());
        }

        let evidence_target = input.primary_file_count.max(1) * 2;
        let evidence_density = if input.primary_file_count == 0 {
            0.0
        } else {
            (input.evidence_count as f32 / evidence_target.max(4) as f32).min(1.0)
        };
        if evidence_density < 0.5 {
            caveats.push("evidence density is thin".into());
        }

        let exact_reference = if input.exact_reference_count > 0 {
            1.0
        } else {
            0.25
        };
        let validation_availability = if input.validation_count > 0 { 1.0 } else { 0.2 };
        let negative_evidence = if input.negative_evidence_count == 0 {
            1.0
        } else if input.negative_evidence_count <= 2 {
            0.3
        } else {
            0.1
        };
        let boundary_tightness = if input.primary_file_count == 0 {
            0.0
        } else if input.allowed_file_count == 0 {
            0.3
        } else if input.allowed_file_count <= 3 {
            1.0
        } else if input.allowed_file_count <= 8
            && input.allowed_file_count <= input.primary_file_count.max(1) * 2
        {
            0.85
        } else {
            0.45
        };
        let runtime_corroboration = if input.runtime_signal_count > 0 {
            1.0
        } else {
            0.25
        };
        let test_coverage = if input.validation_count == 0 {
            0.2
        } else if input.validation_with_command_count > 0 {
            1.0
        } else {
            0.6
        };

        let mut components = vec![
            confidence_component(
                "evidence_density",
                evidence_density,
                0.20,
                "amount of independent indexed evidence near the selected context",
            ),
            confidence_component(
                "exact_references",
                exact_reference,
                0.20,
                "explicit exact symbol references or SCIP signals",
            ),
            confidence_component(
                "validation_availability",
                validation_availability,
                0.15,
                "presence of validation targets for the likely change",
            ),
            confidence_component(
                "negative_evidence",
                negative_evidence,
                0.15,
                "absence of low-confidence, missing-anchor, or no-match evidence",
            ),
            confidence_component(
                "boundary_tightness",
                boundary_tightness,
                0.15,
                "how narrowly allowed edit files bound the proposed change",
            ),
            confidence_component(
                "runtime_corroboration",
                runtime_corroboration,
                0.05,
                "runtime traces, incidents, or error signals that support the context",
            ),
            confidence_component(
                "test_coverage",
                test_coverage,
                0.10,
                "selected tests with runnable commands",
            ),
        ];
        components.sort_by(|a, b| a.signal.cmp(&b.signal));
        let mut overall_score = score_component_total(&components).clamp(0.0, 1.0);
        if input.primary_file_count == 0 {
            overall_score = overall_score.min(0.35);
        }
        if input.exact_reference_count == 0
            && input.validation_count == 0
            && input.runtime_signal_count == 0
        {
            overall_score = overall_score.min(0.55);
        }
        if input.negative_evidence_count > 0 {
            overall_score = overall_score.min(0.60);
        }

        blockers.sort();
        blockers.dedup();
        caveats.sort();
        caveats.dedup();
        if !caveats.is_empty() {
            overall_score = overall_score.min(0.94);
        }

        Self {
            overall_enum: Confidence::from_score(overall_score),
            overall_score,
            components,
            blockers,
            caveats,
        }
    }
}

fn confidence_component(
    signal: &'static str,
    value: f32,
    weight: f32,
    rationale: &'static str,
) -> ScoreComponent {
    ScoreComponent::new(
        signal,
        value,
        value,
        weight,
        value * weight,
        Vec::new(),
        rationale,
    )
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct LineRange {
    pub start: u32,
    pub end: u32,
}

impl LineRange {
    pub fn single(line: u32) -> Self {
        Self {
            start: line,
            end: line,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct FileRange {
    pub path: PathBuf,
    pub line_range: Option<LineRange>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum EvidenceSourceType {
    TreeSitter,
    Scip,
    Lsp,
    Regex,
    Lexical,
    Semantic,
    Runtime,
    GitHistory,
    StaticAnalysis,
    ExternalIntegration,
    Heuristic,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Evidence {
    pub id: EvidenceId,
    pub source: String,
    pub source_type: EvidenceSourceType,
    pub file_range: Option<FileRange>,
    pub symbol_id: Option<SymbolId>,
    pub confidence: Confidence,
    pub message: String,
    pub indexed_at: DateTime<Utc>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ScoreComponent {
    pub signal: String,
    pub raw_value: f32,
    pub normalized_value: f32,
    pub weight: f32,
    pub contribution: f32,
    pub evidence_ids: Vec<String>,
    pub rationale: String,
}

impl ScoreComponent {
    pub fn new(
        signal: impl Into<String>,
        raw_value: f32,
        normalized_value: f32,
        weight: f32,
        contribution: f32,
        evidence_ids: Vec<String>,
        rationale: impl Into<String>,
    ) -> Self {
        Self {
            signal: signal.into(),
            raw_value,
            normalized_value,
            weight,
            contribution,
            evidence_ids,
            rationale: rationale.into(),
        }
    }

    pub fn single(
        signal: impl Into<String>,
        score: f32,
        evidence_ids: Vec<String>,
        rationale: impl Into<String>,
    ) -> Self {
        Self::new(
            signal,
            score,
            score.clamp(0.0, 1.0),
            1.0,
            score,
            evidence_ids,
            rationale,
        )
    }

    pub fn adjustment(
        signal: impl Into<String>,
        contribution: f32,
        evidence_ids: Vec<String>,
        rationale: impl Into<String>,
    ) -> Self {
        Self::new(
            signal,
            contribution,
            contribution.clamp(-1.0, 1.0),
            1.0,
            contribution,
            evidence_ids,
            rationale,
        )
    }
}

pub fn score_component_total(components: &[ScoreComponent]) -> f32 {
    components
        .iter()
        .map(|component| component.contribution)
        .sum()
}

pub fn reconcile_score_breakdown(
    score: f32,
    components: &mut Vec<ScoreComponent>,
    fallback_signal: &str,
    evidence_ids: Vec<String>,
    rationale: &str,
) {
    if components.is_empty() {
        components.push(ScoreComponent::single(
            fallback_signal,
            score,
            evidence_ids,
            rationale,
        ));
        return;
    }

    let delta = score - score_component_total(components);
    if delta.abs() > 0.001 {
        components.push(ScoreComponent::adjustment(
            "score_reconciliation",
            delta,
            evidence_ids,
            format!("adjusted component total to match surfaced score: {rationale}"),
        ));
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Repository {
    pub id: RepositoryId,
    pub name: String,
    pub root: PathBuf,
    pub branch: Option<String>,
    pub commit: Option<String>,
    pub indexed_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Commit {
    pub sha: String,
    pub message: Option<String>,
    pub authored_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Branch {
    pub name: String,
    pub head: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Language {
    Rust,
    Java,
    TypeScript,
    JavaScript,
    Python,
    Go,
    Yaml,
    Json,
    Toml,
    Sql,
    Markdown,
    Text,
    Unknown,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct File {
    pub id: FileId,
    pub repository_id: RepositoryId,
    pub path: PathBuf,
    pub language: Language,
    pub size_bytes: u64,
    pub content_hash: String,
    pub is_generated: bool,
    pub is_vendor: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct FileVersion {
    pub id: FileVersionId,
    pub file_id: FileId,
    pub commit: Option<String>,
    pub content_hash: String,
    pub indexed_at: DateTime<Utc>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum SymbolKind {
    Module,
    Package,
    Class,
    Trait,
    Interface,
    Function,
    Method,
    Field,
    Variable,
    Constant,
    Endpoint,
    DatabaseTable,
    Test,
    Unknown,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Symbol {
    pub id: SymbolId,
    pub name: String,
    pub qualified_name: String,
    pub kind: SymbolKind,
    pub file_id: FileId,
    pub range: Option<LineRange>,
    pub language: Language,
    pub confidence: Confidence,
    pub provenance: EvidenceSourceType,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SymbolOccurrence {
    pub symbol_id: SymbolId,
    pub file_id: FileId,
    pub range: Option<LineRange>,
    pub is_definition: bool,
    pub confidence: Confidence,
    pub provenance: EvidenceSourceType,
}

pub type Reference = SymbolOccurrence;
pub type Definition = SymbolOccurrence;

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Import {
    pub file_id: FileId,
    pub imported: String,
    pub range: Option<LineRange>,
    pub confidence: Confidence,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AnalysisFact {
    pub id: String,
    pub file_id: FileId,
    pub symbol_id: Option<SymbolId>,
    pub target: String,
    pub target_kind: GraphNodeType,
    pub edge_type: GraphEdgeType,
    pub range: Option<LineRange>,
    pub confidence: Confidence,
    pub source: String,
    pub source_type: EvidenceSourceType,
    pub message: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CodeChunk {
    pub id: String,
    pub file_id: FileId,
    pub range: LineRange,
    pub language: Language,
    pub text: String,
    pub symbol_id: Option<SymbolId>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Diagnostic {
    pub severity: String,
    pub message: String,
    pub file_range: Option<FileRange>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TestTarget {
    pub id: String,
    pub name: String,
    pub file_id: FileId,
    pub range: Option<LineRange>,
    pub command: Option<String>,
    pub confidence: Confidence,
    pub reason: String,
    #[serde(default)]
    pub evidence_refs: Vec<String>,
    #[serde(default)]
    pub score_breakdown: Vec<ScoreComponent>,
}

impl TestTarget {
    pub fn reconcile_score_breakdown(&mut self) {
        if self.evidence_refs.is_empty() {
            self.evidence_refs.push(format!("test:{}", self.id));
        }
        reconcile_score_breakdown(
            self.confidence.score(),
            &mut self.score_breakdown,
            "test_confidence",
            self.evidence_refs.clone(),
            &self.reason,
        );
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BuildTarget {
    pub id: String,
    pub name: String,
    pub command: String,
    pub files: Vec<FileId>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RuntimeSignal {
    pub id: String,
    pub kind: String,
    pub message: String,
    pub file_range: Option<FileRange>,
    pub occurred_at: Option<DateTime<Utc>>,
    pub confidence: Confidence,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Owner {
    pub name: String,
    pub email: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ArchitectureComponent {
    pub id: String,
    pub name: String,
    pub paths: Vec<String>,
    pub evidence: Vec<Evidence>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct IndexManifest {
    pub repository: Repository,
    pub file_count: usize,
    pub symbol_count: usize,
    pub chunk_count: usize,
    pub indexed_at: DateTime<Utc>,
    pub schema_version: u32,
    #[serde(default)]
    pub quality: IndexQuality,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct IndexQuality {
    pub scip_enabled: bool,
    pub scip_mode: String,
    pub scip_indexes_imported: usize,
    pub scip_symbols: usize,
    pub scip_occurrences: usize,
    pub scip_exact_references: usize,
    pub test_count: usize,
    pub import_count: usize,
    #[serde(default)]
    pub build_systems: Vec<String>,
    #[serde(default)]
    pub codeql_databases: usize,
    #[serde(default)]
    pub coverage_reports: usize,
    #[serde(default)]
    pub junit_reports: usize,
    #[serde(default)]
    pub static_analysis_facts: usize,
    #[serde(default)]
    pub runtime_analysis_facts: usize,
    #[serde(default)]
    pub git_history_facts: usize,
    #[serde(default)]
    pub semantic_provider_notes: Vec<String>,
    pub quality_notes: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum GraphNodeType {
    File,
    Directory,
    Module,
    Package,
    Class,
    Trait,
    Interface,
    Function,
    Method,
    Field,
    Endpoint,
    DatabaseTable,
    Collection,
    Queue,
    Topic,
    ConfigKey,
    Test,
    BuildTarget,
    RuntimeError,
    Ticket,
    PullRequest,
    ArchitectureComponent,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GraphEdgeType {
    Contains,
    Defines,
    References,
    Calls,
    Implements,
    Extends,
    Imports,
    DependsOn,
    ExposesEndpoint,
    CallsEndpoint,
    ReadsConfig,
    WritesConfig,
    ReadsTable,
    WritesTable,
    PublishesEvent,
    ConsumesEvent,
    Tests,
    OwnedBy,
    ChangedBy,
    FailedIn,
    MentionedIn,
    RelatedToTicket,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct GraphNode {
    pub id: NodeId,
    pub node_type: GraphNodeType,
    pub label: String,
    pub file_id: Option<FileId>,
    pub symbol_id: Option<SymbolId>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct GraphEdge {
    pub id: EdgeId,
    pub from: NodeId,
    pub to: NodeId,
    pub edge_type: GraphEdgeType,
    pub evidence: Evidence,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SearchResult {
    pub path: PathBuf,
    pub line_range: Option<LineRange>,
    pub snippet: String,
    pub symbol: Option<Symbol>,
    pub score: f32,
    pub match_reason: String,
    pub evidence: Vec<String>,
    #[serde(default)]
    pub evidence_refs: Vec<String>,
    pub confidence: f32,
    #[serde(default)]
    pub score_breakdown: Vec<ScoreComponent>,
}

impl SearchResult {
    pub fn derived_evidence_ids(&self) -> Vec<String> {
        if !self.evidence_refs.is_empty() {
            return self.evidence_refs.clone();
        }
        search_result_evidence_ids(&self.path, &self.line_range, self.evidence.len())
    }

    pub fn reconcile_score_breakdown(&mut self) {
        if self.evidence_refs.is_empty() {
            self.evidence_refs =
                search_result_evidence_ids(&self.path, &self.line_range, self.evidence.len());
        }
        reconcile_score_breakdown(
            self.score,
            &mut self.score_breakdown,
            "search_score",
            self.evidence_refs.clone(),
            &self.match_reason,
        );
    }

    pub fn add_score_component(&mut self, component: ScoreComponent) {
        self.score_breakdown.push(component);
    }
}

pub fn search_result_evidence_ids(
    path: &Path,
    line_range: &Option<LineRange>,
    evidence_len: usize,
) -> Vec<String> {
    let range = line_range
        .as_ref()
        .map(|range| format!("{}-{}", range.start, range.end))
        .unwrap_or_else(|| "unknown".into());
    let count = evidence_len.max(1);
    (0..count)
        .map(|index| format!("search:{}:{range}:{index}", path.display()))
        .collect()
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct EntityLink {
    pub kind: String,
    pub value: String,
    pub file_range: Option<FileRange>,
    pub confidence: Confidence,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct MemoryFact {
    pub id: MemoryFactId,
    pub text: String,
    pub source: String,
    pub confidence: Confidence,
    pub entities: Vec<EntityLink>,
    pub created_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct MemorySearchResult {
    pub fact: MemoryFact,
    pub score: f32,
    pub match_reason: String,
    pub evidence: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ContextHandle {
    pub id: ContextHandleId,
    pub kind: String,
    pub summary: String,
    pub file_range: Option<FileRange>,
    pub entities: Vec<EntityLink>,
    pub original_tokens_estimate: usize,
    pub compressed_tokens_estimate: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CompressedContextPack {
    pub task: String,
    pub summary: String,
    pub handles: Vec<ContextHandle>,
    pub original_tokens_estimate: usize,
    pub compressed_tokens_estimate: usize,
    pub compression_ratio: f32,
    pub evidence: Vec<Evidence>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RiskReport {
    pub level: String,
    pub score: f32,
    pub reasons: Vec<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct BoundaryFileRule {
    pub path: PathBuf,
    pub reason: String,
    #[serde(default)]
    pub evidence_refs: Vec<String>,
    #[serde(default)]
    pub symbols: Vec<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct BoundaryForbiddenRule {
    pub pattern: String,
    pub reason: String,
    #[serde(default)]
    pub evidence_refs: Vec<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct BoundaryExpansionRequirement {
    pub reason: String,
    #[serde(default)]
    pub required_evidence_refs: Vec<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct BoundarySignalHooks {
    #[serde(default)]
    pub architecture_components: Vec<String>,
    #[serde(default)]
    pub ownership_sources: Vec<String>,
    #[serde(default)]
    pub cochange_sources: Vec<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct ChangeBoundary {
    pub allowed_files: Vec<PathBuf>,
    pub caution_files: Vec<PathBuf>,
    pub forbidden_files: Vec<PathBuf>,
    #[serde(default)]
    pub evidence_refs: Vec<String>,
    #[serde(default)]
    pub allowed_symbols: Vec<String>,
    #[serde(default)]
    pub allowed_rules: Vec<BoundaryFileRule>,
    #[serde(default)]
    pub caution_rules: Vec<BoundaryFileRule>,
    #[serde(default)]
    pub forbidden_rules: Vec<BoundaryForbiddenRule>,
    #[serde(default)]
    pub expansion_requirements: Vec<BoundaryExpansionRequirement>,
    #[serde(default)]
    pub signal_hooks: BoundarySignalHooks,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ValidationPlan {
    pub commands: Vec<String>,
    pub tests: Vec<TestTarget>,
    pub requires_approval: bool,
    pub evidence: Vec<Evidence>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ImpactReport {
    pub target: String,
    pub direct_impacts: Vec<SearchResult>,
    pub indirect_impacts: Vec<SearchResult>,
    pub risk_report: RiskReport,
    pub evidence: Vec<Evidence>,
    #[serde(default)]
    pub score_breakdown: Vec<ScoreComponent>,
}

impl ImpactReport {
    pub fn reconcile_score_breakdown(&mut self) {
        reconcile_score_breakdown(
            self.risk_report.score,
            &mut self.score_breakdown,
            "impact_risk",
            self.evidence
                .iter()
                .map(|evidence| evidence.id.0.clone())
                .collect(),
            "impact risk score",
        );
        for result in &mut self.direct_impacts {
            result.reconcile_score_breakdown();
        }
        for result in &mut self.indirect_impacts {
            result.reconcile_score_breakdown();
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ContextPack {
    pub task: String,
    pub intent: String,
    pub primary_files: Vec<SearchResult>,
    pub primary_symbols: Vec<Symbol>,
    pub supporting_files: Vec<SearchResult>,
    pub dependency_edges: Vec<GraphEdge>,
    pub runtime_signals: Vec<RuntimeSignal>,
    pub test_candidates: Vec<TestTarget>,
    pub risk_report: RiskReport,
    pub recommended_change_boundary: ChangeBoundary,
    pub validation_plan: ValidationPlan,
    pub evidence: Vec<Evidence>,
    #[serde(default)]
    pub negative_evidence: Vec<NegativeEvidence>,
    pub confidence_summary: String,
    #[serde(default)]
    pub confidence_breakdown: ConfidenceBreakdown,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ToolCallRecommendation {
    pub tool: String,
    pub purpose: String,
    pub arguments: serde_json::Value,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PlanReport {
    pub task: String,
    pub summary: String,
    pub primary_context: Vec<SearchResult>,
    pub relevant_symbols: Vec<Symbol>,
    pub impact: ImpactReport,
    pub validation: Vec<TestTarget>,
    pub risk: RiskReport,
    pub recommended_change_boundary: ChangeBoundary,
    pub recommended_next_steps: Vec<String>,
    pub tool_calls: Vec<ToolCallRecommendation>,
    pub memory_facts: Vec<MemorySearchResult>,
    #[serde(default)]
    pub runtime_signals: Vec<RuntimeSignal>,
    pub evidence: Vec<Evidence>,
    #[serde(default)]
    pub evidence_by_section: BTreeMap<String, Vec<String>>,
    #[serde(default)]
    pub negative_evidence: Vec<NegativeEvidence>,
    pub confidence_summary: String,
    #[serde(default)]
    pub confidence_breakdown: ConfidenceBreakdown,
    #[serde(default)]
    pub score_breakdown: Vec<ScoreComponent>,
}

impl PlanReport {
    pub fn reconcile_score_breakdown(&mut self) {
        reconcile_score_breakdown(
            self.risk.score,
            &mut self.score_breakdown,
            "plan_risk",
            self.evidence
                .iter()
                .map(|evidence| evidence.id.0.clone())
                .collect(),
            "plan risk score",
        );
        for result in &mut self.primary_context {
            result.reconcile_score_breakdown();
        }
        self.impact.reconcile_score_breakdown();
        for test in &mut self.validation {
            test.reconcile_score_breakdown();
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PatchPlan {
    pub id: PatchId,
    pub task: String,
    pub allowed_files: Vec<PathBuf>,
    pub caution_files: Vec<PathBuf>,
    pub forbidden_files: Vec<PathBuf>,
    pub change_steps: Vec<String>,
    pub risks: Vec<String>,
    pub assumptions: Vec<String>,
    pub tests: Vec<TestTarget>,
    pub rollback_notes: Vec<String>,
    pub unified_diff: Option<String>,
    pub requires_approval: bool,
    pub evidence: Vec<Evidence>,
}

#[cfg(test)]
mod tests {
    use super::{
        reconcile_score_breakdown, score_component_total, Confidence, ConfidenceBreakdown,
        ConfidenceSignalInput, ScoreComponent,
    };

    #[test]
    fn reconciliation_adds_delta_to_match_surfaced_score() {
        let mut components = vec![ScoreComponent::single(
            "base",
            0.4,
            vec!["ev:base".into()],
            "base signal",
        )];

        reconcile_score_breakdown(
            0.65,
            &mut components,
            "fallback",
            vec!["ev:adjust".into()],
            "test score",
        );

        assert_eq!(components.len(), 2);
        assert!((score_component_total(&components) - 0.65).abs() < 0.001);
        assert_eq!(components[1].signal, "score_reconciliation");
    }

    #[test]
    fn reconciliation_creates_fallback_for_empty_components() {
        let mut components = Vec::new();

        reconcile_score_breakdown(
            0.85,
            &mut components,
            "confidence",
            vec!["test:id".into()],
            "test confidence",
        );

        assert_eq!(components.len(), 1);
        assert_eq!(components[0].signal, "confidence");
        assert!((score_component_total(&components) - 0.85).abs() < 0.001);
    }

    #[test]
    fn confidence_breakdown_is_stable_for_same_signals() {
        let input = ConfidenceSignalInput {
            primary_file_count: 2,
            evidence_count: 8,
            exact_reference_count: 2,
            validation_count: 2,
            validation_with_command_count: 1,
            negative_evidence_count: 0,
            allowed_file_count: 2,
            runtime_signal_count: 1,
        };

        let first = ConfidenceBreakdown::from_signals(input);
        let second = ConfidenceBreakdown::from_signals(input);

        assert_eq!(first.overall_enum, second.overall_enum);
        assert_eq!(first.overall_score, second.overall_score);
        assert_eq!(first.components, second.components);
        assert!(first.caveats.is_empty());
        assert!(first.blockers.is_empty());
    }

    #[test]
    fn confidence_drops_without_exact_tests_or_runtime() {
        let grounded = ConfidenceBreakdown::from_signals(ConfidenceSignalInput {
            primary_file_count: 1,
            evidence_count: 6,
            exact_reference_count: 1,
            validation_count: 1,
            validation_with_command_count: 1,
            negative_evidence_count: 0,
            allowed_file_count: 1,
            runtime_signal_count: 1,
        });
        let thin = ConfidenceBreakdown::from_signals(ConfidenceSignalInput {
            primary_file_count: 1,
            evidence_count: 6,
            exact_reference_count: 0,
            validation_count: 0,
            validation_with_command_count: 0,
            negative_evidence_count: 0,
            allowed_file_count: 1,
            runtime_signal_count: 0,
        });

        assert!(thin.overall_score < grounded.overall_score);
        assert_eq!(thin.overall_enum, Confidence::Medium);
        assert!(thin
            .caveats
            .iter()
            .any(|caveat| caveat.contains("exact symbol/reference")));
        assert!(thin
            .caveats
            .iter()
            .any(|caveat| caveat.contains("no validation")));
        assert!(thin
            .caveats
            .iter()
            .any(|caveat| caveat.contains("runtime corroboration")));
    }

    #[test]
    fn negative_evidence_prevents_false_high_confidence() {
        let breakdown = ConfidenceBreakdown::from_signals(ConfidenceSignalInput {
            primary_file_count: 3,
            evidence_count: 12,
            exact_reference_count: 3,
            validation_count: 3,
            validation_with_command_count: 3,
            negative_evidence_count: 1,
            allowed_file_count: 3,
            runtime_signal_count: 1,
        });

        assert!(breakdown.overall_score <= 0.60);
        assert_ne!(breakdown.overall_enum, Confidence::High);
        assert!(!breakdown.blockers.is_empty());
    }
}