leankg 0.19.1

Lightweight Knowledge Graph for AI-Assisted Development
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
#![allow(dead_code)]
use serde::{Deserialize, Serialize};

fn default_env_local() -> String {
    "local".to_string()
}

#[allow(dead_code)]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum RelationshipType {
    Imports,
    Calls,
    References,
    DocumentedBy,
    TestedBy,
    Tests,
    Contains,
    Defines,
    Implements,
    Implementations,
    Extends,
    HasMethod,
    HasProperty,
    Accesses,
    MemberOf,
    Decorates,
    Wraps,
    BelongsTo,
    MethodOverrides,
    MethodImplements,
    Queries,
    EntryPointOf,
    StepInProcess,
    ServiceCalls,
    DefinesWidget,
    ContainsChild,
    OnClickHandler,
    BindsView,
    ViewbindingProperty,
    SyntheticBinding,
    AssociatedWith,
    ReferencesClass,
    UsesString,
    UsesColor,
    UsesDimen,
    UsesDrawable,
    UsesStyle,
    Annotates,
    InflatesLayout,
    UsesViewBinding,
    DependsOnModule,
    UsesLibrary,
    NavigatesTo,
    NavAction,
    ProvidesArg,
    RequiresArg,
    DeepLink,
    Presents,
    HiltBindsInterface,
    ViewModelOwnsRepository,
    UsesDispatcher,
    WorkManagerWorksOn,
    LifecycleObserves,
    RoomDaoMethod,
    ViewbindingUsed,
    CausedIncident,
    ResolvedBy,
    ConflictsWith,
    DeployedTo,
    Supersedes,
    // Phase 1 structural parity (PRD: prd-structural-parity-cbm.md)
    HttpCalls,
    Emits,
    ListensOn,
    SimilarTo,
    CrossRepoSimilar,
    RoutesTo,
    DefinesRoute,
}

impl RelationshipType {
    pub fn as_str(&self) -> &'static str {
        match self {
            RelationshipType::Imports => "imports",
            RelationshipType::Calls => "calls",
            RelationshipType::References => "references",
            RelationshipType::DocumentedBy => "documented_by",
            RelationshipType::TestedBy => "tested_by",
            RelationshipType::Tests => "tests",
            RelationshipType::Contains => "contains",
            RelationshipType::Defines => "defines",
            RelationshipType::Implements => "implements",
            RelationshipType::Implementations => "implementations",
            RelationshipType::Extends => "extends",
            RelationshipType::HasMethod => "has_method",
            RelationshipType::HasProperty => "has_property",
            RelationshipType::Accesses => "accesses",
            RelationshipType::MemberOf => "member_of",
            RelationshipType::Decorates => "decorates",
            RelationshipType::Wraps => "wraps",
            RelationshipType::BelongsTo => "belongs_to",
            RelationshipType::MethodOverrides => "method_overrides",
            RelationshipType::MethodImplements => "method_implements",
            RelationshipType::Queries => "queries",
            RelationshipType::EntryPointOf => "entry_point_of",
            RelationshipType::StepInProcess => "step_in_process",
            RelationshipType::ServiceCalls => "service_calls",
            RelationshipType::DefinesWidget => "defines_widget",
            RelationshipType::ContainsChild => "contains_child",
            RelationshipType::OnClickHandler => "on_click_handler",
            RelationshipType::BindsView => "binds_view",
            RelationshipType::ViewbindingProperty => "viewbinding_property",
            RelationshipType::SyntheticBinding => "synthetic_binding",
            RelationshipType::AssociatedWith => "associated_with",
            RelationshipType::ReferencesClass => "references_class",
            RelationshipType::UsesString => "uses_string",
            RelationshipType::UsesColor => "uses_color",
            RelationshipType::UsesDimen => "uses_dimen",
            RelationshipType::UsesDrawable => "uses_drawable",
            RelationshipType::UsesStyle => "uses_style",
            RelationshipType::Annotates => "annotates",
            RelationshipType::InflatesLayout => "inflates_layout",
            RelationshipType::UsesViewBinding => "uses_viewbinding",
            RelationshipType::DependsOnModule => "depends_on_module",
            RelationshipType::UsesLibrary => "uses_library",
            RelationshipType::NavigatesTo => "navigates_to",
            RelationshipType::NavAction => "nav_action",
            RelationshipType::ProvidesArg => "provides_arg",
            RelationshipType::RequiresArg => "requires_arg",
            RelationshipType::DeepLink => "deep_link",
            RelationshipType::Presents => "presents",
            RelationshipType::HiltBindsInterface => "hilt_binds_interface",
            RelationshipType::ViewModelOwnsRepository => "viewmodel_owns_repository",
            RelationshipType::UsesDispatcher => "uses_dispatcher",
            RelationshipType::WorkManagerWorksOn => "workmanager_works_on",
            RelationshipType::LifecycleObserves => "lifecycle_observes",
            RelationshipType::RoomDaoMethod => "room_dao_method",
            RelationshipType::ViewbindingUsed => "viewbinding_used",
            RelationshipType::CausedIncident => "caused_incident",
            RelationshipType::ResolvedBy => "resolved_by",
            RelationshipType::ConflictsWith => "conflicts_with",
            RelationshipType::DeployedTo => "deployed_to",
            RelationshipType::Supersedes => "supersedes",
            RelationshipType::HttpCalls => "http_calls",
            RelationshipType::Emits => "emits",
            RelationshipType::ListensOn => "listens_on",
            RelationshipType::SimilarTo => "similar_to",
            RelationshipType::CrossRepoSimilar => "cross_repo_similar",
            RelationshipType::RoutesTo => "routes_to",
            RelationshipType::DefinesRoute => "defines_route",
        }
    }

    #[allow(dead_code)]
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "imports" => Some(RelationshipType::Imports),
            "calls" => Some(RelationshipType::Calls),
            "references" => Some(RelationshipType::References),
            "documented_by" => Some(RelationshipType::DocumentedBy),
            "tested_by" => Some(RelationshipType::TestedBy),
            "tests" => Some(RelationshipType::Tests),
            "contains" => Some(RelationshipType::Contains),
            "defines" => Some(RelationshipType::Defines),
            "implements" => Some(RelationshipType::Implements),
            "implementations" => Some(RelationshipType::Implementations),
            "extends" => Some(RelationshipType::Extends),
            "has_method" => Some(RelationshipType::HasMethod),
            "has_property" => Some(RelationshipType::HasProperty),
            "accesses" => Some(RelationshipType::Accesses),
            "member_of" => Some(RelationshipType::MemberOf),
            "decorates" => Some(RelationshipType::Decorates),
            "wraps" => Some(RelationshipType::Wraps),
            "belongs_to" => Some(RelationshipType::BelongsTo),
            "method_overrides" => Some(RelationshipType::MethodOverrides),
            "method_implements" => Some(RelationshipType::MethodImplements),
            "queries" => Some(RelationshipType::Queries),
            "entry_point_of" => Some(RelationshipType::EntryPointOf),
            "step_in_process" => Some(RelationshipType::StepInProcess),
            "service_calls" => Some(RelationshipType::ServiceCalls),
            "defines_widget" => Some(RelationshipType::DefinesWidget),
            "contains_child" => Some(RelationshipType::ContainsChild),
            "on_click_handler" => Some(RelationshipType::OnClickHandler),
            "binds_view" => Some(RelationshipType::BindsView),
            "viewbinding_property" => Some(RelationshipType::ViewbindingProperty),
            "synthetic_binding" => Some(RelationshipType::SyntheticBinding),
            "associated_with" => Some(RelationshipType::AssociatedWith),
            "references_class" => Some(RelationshipType::ReferencesClass),
            "uses_string" => Some(RelationshipType::UsesString),
            "uses_color" => Some(RelationshipType::UsesColor),
            "uses_dimen" => Some(RelationshipType::UsesDimen),
            "uses_drawable" => Some(RelationshipType::UsesDrawable),
            "uses_style" => Some(RelationshipType::UsesStyle),
            "annotates" => Some(RelationshipType::Annotates),
            "inflates_layout" => Some(RelationshipType::InflatesLayout),
            "uses_viewbinding" => Some(RelationshipType::UsesViewBinding),
            "depends_on_module" => Some(RelationshipType::DependsOnModule),
            "uses_library" => Some(RelationshipType::UsesLibrary),
            "navigates_to" => Some(RelationshipType::NavigatesTo),
            "nav_action" => Some(RelationshipType::NavAction),
            "provides_arg" => Some(RelationshipType::ProvidesArg),
            "requires_arg" => Some(RelationshipType::RequiresArg),
            "deep_link" => Some(RelationshipType::DeepLink),
            "presents" => Some(RelationshipType::Presents),
            "hilt_binds_interface" => Some(RelationshipType::HiltBindsInterface),
            "viewmodel_owns_repository" => Some(RelationshipType::ViewModelOwnsRepository),
            "uses_dispatcher" => Some(RelationshipType::UsesDispatcher),
            "workmanager_works_on" => Some(RelationshipType::WorkManagerWorksOn),
            "lifecycle_observes" => Some(RelationshipType::LifecycleObserves),
            "room_dao_method" => Some(RelationshipType::RoomDaoMethod),
            "viewbinding_used" => Some(RelationshipType::ViewbindingUsed),
            "caused_incident" => Some(RelationshipType::CausedIncident),
            "resolved_by" => Some(RelationshipType::ResolvedBy),
            "conflicts_with" => Some(RelationshipType::ConflictsWith),
            "deployed_to" => Some(RelationshipType::DeployedTo),
            "supersedes" | "supercedes" => Some(RelationshipType::Supersedes),
            "http_calls" => Some(RelationshipType::HttpCalls),
            "emits" => Some(RelationshipType::Emits),
            "listens_on" => Some(RelationshipType::ListensOn),
            "similar_to" => Some(RelationshipType::SimilarTo),
            "cross_repo_similar" => Some(RelationshipType::CrossRepoSimilar),
            "routes_to" => Some(RelationshipType::RoutesTo),
            "defines_route" => Some(RelationshipType::DefinesRoute),
            _ => None,
        }
    }
}

impl std::fmt::Display for RelationshipType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CodeElement {
    pub qualified_name: String,
    pub element_type: String,
    pub name: String,
    pub file_path: String,
    pub line_start: u32,
    pub line_end: u32,
    pub language: String,
    pub parent_qualified: Option<String>,
    #[serde(default)]
    pub cluster_id: Option<String>,
    #[serde(default)]
    pub cluster_label: Option<String>,
    #[serde(default)]
    pub metadata: serde_json::Value,
    #[serde(default = "default_env_local")]
    pub env: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Relationship {
    #[serde(skip)]
    #[allow(dead_code)]
    pub id: Option<String>,
    pub source_qualified: String,
    pub target_qualified: String,
    pub rel_type: String,
    pub confidence: f64,
    pub metadata: serde_json::Value,
    #[serde(default = "default_env_local")]
    pub env: String,
}

impl Default for Relationship {
    fn default() -> Self {
        Self {
            id: None,
            source_qualified: String::new(),
            target_qualified: String::new(),
            rel_type: String::new(),
            confidence: 1.0,
            metadata: serde_json::Value::Null,
            env: default_env_local(),
        }
    }
}

/// Information about a dependency (import)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DependencyInfo {
    pub target_qualified: String,
    pub confidence: f64,
}

impl Relationship {
    pub fn severity(&self, depth: u32) -> &'static str {
        if depth == 1 && self.confidence >= 0.85 {
            "WILL BREAK"
        } else if depth == 1 && self.confidence >= 0.60 {
            "LIKELY AFFECTED"
        } else {
            "MAY BE AFFECTED"
        }
    }

    /// US-GF-04 / FR-GF-07..08: Derive the edge provenance label
    /// (`EXTRACTED` / `INFERRED` / `AMBIGUOUS`) from the
    /// `resolution_method` field in metadata. Used by `shortest_path`,
    /// `query_graph`, `explain_node`, and Web UI edge tooltips so agents
    /// can see whether an edge was explicit in source or resolver-derived.
    pub fn confidence_label(&self) -> &'static str {
        let method = self
            .metadata
            .get("resolution_method")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        match method {
            "typed" => "EXTRACTED",
            "name" if self.confidence >= 0.8 => "EXTRACTED",
            "name_file_hint" if self.confidence >= 0.6 => "INFERRED",
            "name" => "INFERRED",
            "unresolved" => "AMBIGUOUS",
            _ if self.confidence >= 0.8 => "EXTRACTED",
            _ if self.confidence >= 0.5 => "INFERRED",
            _ => "AMBIGUOUS",
        }
    }
}

/// US-GF-04: Canonical edge provenance labels for documentation and tests.
pub mod confidence_labels {
    pub const EXTRACTED: &str = "EXTRACTED";
    pub const INFERRED: &str = "INFERRED";
    pub const AMBIGUOUS: &str = "AMBIGUOUS";
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BusinessLogic {
    #[serde(skip)]
    #[allow(dead_code)]
    pub id: Option<String>,
    pub element_qualified: String,
    pub description: String,
    pub user_story_id: Option<String>,
    pub feature_id: Option<String>,
}

#[allow(dead_code)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BusinessLogicWithDoc {
    pub business_logic: BusinessLogic,
    pub doc_links: Vec<DocLink>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocLink {
    pub doc_qualified: String,
    pub doc_title: String,
    pub context: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceabilityEntry {
    pub element_qualified: String,
    pub description: String,
    pub user_story_id: Option<String>,
    pub feature_id: Option<String>,
    pub doc_links: Vec<DocLink>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceabilityReport {
    pub element_qualified: String,
    pub entries: Vec<TraceabilityEntry>,
    pub count: usize,
}

#[allow(dead_code)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Document {
    #[serde(skip)]
    pub id: Option<String>,
    pub title: String,
    pub content: String,
    pub file_path: String,
    pub generated_from: Vec<String>,
    pub last_updated: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Incident {
    pub id: String,
    #[serde(default = "default_env_local")]
    pub env: String,
    pub title: String,
    pub severity: String,
    pub occurred_at: i64,
    pub resolved_at: Option<i64>,
    pub root_cause: String,
    pub resolution: String,
    pub affected_services: Vec<String>,
    pub trigger_pattern: Option<String>,
    pub prevention: Option<String>,
    pub tags: Vec<String>,
    pub author: String,
    pub linked_ticket: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ContextMetric {
    pub tool_name: String,
    pub timestamp: i64,
    pub project_path: String,
    pub input_tokens: i32,
    pub output_tokens: i32,
    pub output_elements: i32,
    pub execution_time_ms: i32,
    pub baseline_tokens: i32,
    pub baseline_lines_scanned: i32,
    pub tokens_saved: i32,
    pub savings_percent: f64,
    pub correct_elements: Option<i32>,
    pub total_expected: Option<i32>,
    pub f1_score: Option<f64>,
    pub query_pattern: Option<String>,
    pub query_file: Option<String>,
    pub query_depth: Option<i32>,
    pub success: bool,
    #[serde(default)]
    pub is_deleted: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricsSummary {
    pub total_invocations: i64,
    pub total_tokens_saved: i64,
    pub average_savings_percent: f64,
    pub average_correctness_percent: f64,
    pub retention_days: i32,
    pub by_tool: Vec<ToolMetrics>,
    pub by_day: Vec<DailyMetrics>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolMetrics {
    pub tool_name: String,
    pub calls: i64,
    pub avg_savings_percent: f64,
    pub avg_correctness_percent: f64,
    pub total_saved: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DailyMetrics {
    pub date: String,
    pub calls: i64,
    pub savings: i64,
    pub correctness: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum KnowledgeType {
    BusinessKnowledge,
    DomainKnowledge,
    ArchitectureDoc,
    PrdMapping,
    DebuggingNote,
    General,
}

impl KnowledgeType {
    pub fn as_str(&self) -> &'static str {
        match self {
            KnowledgeType::BusinessKnowledge => "business",
            KnowledgeType::DomainKnowledge => "domain",
            KnowledgeType::ArchitectureDoc => "architecture",
            KnowledgeType::PrdMapping => "prd_mapping",
            KnowledgeType::DebuggingNote => "debugging",
            KnowledgeType::General => "general",
        }
    }

    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "business" => Some(KnowledgeType::BusinessKnowledge),
            "domain" => Some(KnowledgeType::DomainKnowledge),
            "architecture" => Some(KnowledgeType::ArchitectureDoc),
            "prd_mapping" => Some(KnowledgeType::PrdMapping),
            "debugging" => Some(KnowledgeType::DebuggingNote),
            "general" => Some(KnowledgeType::General),
            _ => None,
        }
    }
}

impl std::fmt::Display for KnowledgeType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct KnowledgeEntry {
    pub id: String,
    pub knowledge_type: String,
    pub title: String,
    pub content: String,
    pub element_qualified: Option<String>,
    pub user_story_id: Option<String>,
    pub feature_id: Option<String>,
    pub tags: String,
    pub environment: String,
    pub branch: Option<String>,
    pub author: String,
    pub created_at: i64,
    pub updated_at: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum Role {
    Admin,
    Contributor,
    Viewer,
}

impl Role {
    pub fn as_str(&self) -> &'static str {
        match self {
            Role::Admin => "admin",
            Role::Contributor => "contributor",
            Role::Viewer => "viewer",
        }
    }

    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "admin" => Some(Role::Admin),
            "contributor" => Some(Role::Contributor),
            "viewer" => Some(Role::Viewer),
            _ => None,
        }
    }

    pub fn can_write(&self) -> bool {
        matches!(self, Role::Admin | Role::Contributor)
    }

    pub fn can_admin(&self) -> bool {
        matches!(self, Role::Admin)
    }
}

impl std::fmt::Display for Role {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Team member entry with role
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TeamMember {
    pub user_id: String,
    pub role: String,
    pub joined_at: i64,
}

/// Team model for shared graph management
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Team {
    pub id: String,
    pub name: String,
    pub description: String,
    pub owner_id: String,
    pub created_at: i64,
    pub updated_at: i64,
    #[serde(default)]
    pub graph_read_users: Vec<String>,
    #[serde(default)]
    pub graph_write_users: Vec<String>,
    #[serde(default)]
    pub members: Vec<TeamMember>,
}

/// Invite token for team onboarding
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TeamInvite {
    pub token: String,
    pub team_id: String,
    pub email: Option<String>,
    pub role: String,
    pub created_by: String,
    pub created_at: i64,
    pub expires_at: i64,
    pub accepted: bool,
    pub accepted_by: Option<String>,
}

/// Permission scope for graph access
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum GraphPermission {
    Read,
    Write,
    Admin,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthContext {
    pub client_id: String,
    pub role: Role,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ServiceMetadata {
    pub service_name: String,
    #[serde(default = "default_env_local")]
    pub env: String,
    pub team: Option<String>,
    pub on_call: Option<String>,
    pub repo_url: Option<String>,
    pub language: Option<String>,
    pub health_endpoint: Option<String>,
    pub slo_p99_ms: Option<i32>,
    pub incident_count: i32,
    pub last_incident: Option<i64>,
    pub tags: String,
    pub version: Option<String>,
    pub deploy_envs: String,
    pub created_at: i64,
    pub updated_at: i64,
}

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

    #[test]
    fn test_code_element_creation() {
        let elem = CodeElement {
            qualified_name: "src/main.rs::main".to_string(),
            element_type: "function".to_string(),
            name: "main".to_string(),
            file_path: "src/main.rs".to_string(),
            line_start: 1,
            line_end: 5,
            language: "rust".to_string(),
            parent_qualified: None,
            metadata: serde_json::json!({}),
            ..Default::default()
        };
        assert_eq!(elem.name, "main");
    }

    #[test]
    fn test_relationship_creation() {
        let rel = Relationship {
            id: None,
            source_qualified: "a.go".to_string(),
            target_qualified: "b.go".to_string(),
            rel_type: "imports".to_string(),
            confidence: 1.0,
            metadata: serde_json::json!({}),
            ..Default::default()
        };
        assert_eq!(rel.rel_type, "imports");
        assert_eq!(rel.confidence, 1.0);
        assert_eq!(rel.env, "local");
    }

    #[test]
    fn test_relationship_type_display() {
        assert_eq!(RelationshipType::Imports.as_str(), "imports");
        assert_eq!(
            RelationshipType::Implementations.as_str(),
            "implementations"
        );
        assert_eq!(format!("{}", RelationshipType::Calls), "calls");
    }

    #[test]
    fn test_relationship_type_from_str() {
        assert_eq!(
            RelationshipType::from_str("imports"),
            Some(RelationshipType::Imports)
        );
        assert_eq!(
            RelationshipType::from_str("implementations"),
            Some(RelationshipType::Implementations)
        );
        assert_eq!(RelationshipType::from_str("unknown"), None);
    }

    #[test]
    fn test_nav_relationship_types() {
        assert_eq!(RelationshipType::NavigatesTo.as_str(), "navigates_to");
        assert_eq!(RelationshipType::NavAction.as_str(), "nav_action");
        assert_eq!(RelationshipType::ProvidesArg.as_str(), "provides_arg");
        assert_eq!(RelationshipType::RequiresArg.as_str(), "requires_arg");
        assert_eq!(RelationshipType::DeepLink.as_str(), "deep_link");
        assert_eq!(RelationshipType::Presents.as_str(), "presents");
        assert_eq!(
            RelationshipType::from_str("navigates_to"),
            Some(RelationshipType::NavigatesTo)
        );
        assert_eq!(
            RelationshipType::from_str("presents"),
            Some(RelationshipType::Presents)
        );
    }

    #[test]
    fn test_incident_relationship_types() {
        assert_eq!(RelationshipType::CausedIncident.as_str(), "caused_incident");
        assert_eq!(RelationshipType::ResolvedBy.as_str(), "resolved_by");
        assert_eq!(RelationshipType::ConflictsWith.as_str(), "conflicts_with");
        assert_eq!(RelationshipType::DeployedTo.as_str(), "deployed_to");
        assert_eq!(RelationshipType::Supersedes.as_str(), "supersedes");
        assert_eq!(
            RelationshipType::from_str("caused_incident"),
            Some(RelationshipType::CausedIncident)
        );
        assert_eq!(
            RelationshipType::from_str("resolved_by"),
            Some(RelationshipType::ResolvedBy)
        );
        assert_eq!(
            RelationshipType::from_str("conflicts_with"),
            Some(RelationshipType::ConflictsWith)
        );
        assert_eq!(
            RelationshipType::from_str("deployed_to"),
            Some(RelationshipType::DeployedTo)
        );
        assert_eq!(
            RelationshipType::from_str("supersedes"),
            Some(RelationshipType::Supersedes)
        );
        assert_eq!(
            RelationshipType::from_str("supercedes"),
            Some(RelationshipType::Supersedes)
        );
    }

    #[test]
    fn test_incident_creation() {
        let incident = Incident {
            id: "inc-1".to_string(),
            env: "production".to_string(),
            title: "DB outage".to_string(),
            severity: "P0".to_string(),
            occurred_at: 1000,
            resolved_at: Some(2000),
            root_cause: "Connection leak".to_string(),
            resolution: "Restarted pool".to_string(),
            affected_services: vec!["api".to_string(), "db".to_string()],
            trigger_pattern: Some("connection timeout".to_string()),
            prevention: Some("Add monitoring".to_string()),
            tags: vec!["outage".to_string()],
            author: "oncall".to_string(),
            linked_ticket: Some("TICKET-123".to_string()),
        };
        assert_eq!(incident.id, "inc-1");
        assert_eq!(incident.severity, "P0");
        assert_eq!(incident.affected_services.len(), 2);
    }

    #[test]
    fn test_knowledge_type_roundtrip() {
        assert_eq!(KnowledgeType::BusinessKnowledge.as_str(), "business");
        assert_eq!(
            KnowledgeType::from_str("domain"),
            Some(KnowledgeType::DomainKnowledge)
        );
        assert_eq!(KnowledgeType::from_str("unknown"), None);
        assert_eq!(format!("{}", KnowledgeType::PrdMapping), "prd_mapping");
    }

    #[test]
    fn test_role_permissions() {
        assert!(Role::Admin.can_write());
        assert!(Role::Admin.can_admin());
        assert!(Role::Contributor.can_write());
        assert!(!Role::Contributor.can_admin());
        assert!(!Role::Viewer.can_write());
        assert!(!Role::Viewer.can_admin());
        assert_eq!(Role::from_str("admin"), Some(Role::Admin));
        assert_eq!(Role::from_str("viewer"), Some(Role::Viewer));
    }

    #[test]
    fn test_knowledge_entry_creation() {
        let entry = KnowledgeEntry {
            id: "test-id".to_string(),
            knowledge_type: "business".to_string(),
            title: "Test".to_string(),
            content: "Content".to_string(),
            environment: "production".to_string(),
            author: "test".to_string(),
            created_at: 1000,
            updated_at: 1000,
            ..Default::default()
        };
        assert_eq!(entry.id, "test-id");
        assert_eq!(entry.environment, "production");
        assert!(entry.element_qualified.is_none());
    }

    #[test]
    fn test_team_creation() {
        let team = Team {
            id: "team-1".to_string(),
            name: "Platform Team".to_string(),
            description: "Core platform services".to_string(),
            owner_id: "user-1".to_string(),
            created_at: 1000,
            updated_at: 1000,
            graph_read_users: vec!["user-2".to_string()],
            graph_write_users: vec!["user-1".to_string(), "user-2".to_string()],
            members: vec![
                TeamMember {
                    user_id: "user-1".to_string(),
                    role: "admin".to_string(),
                    joined_at: 1000,
                },
                TeamMember {
                    user_id: "user-2".to_string(),
                    role: "contributor".to_string(),
                    joined_at: 1001,
                },
            ],
        };
        assert_eq!(team.id, "team-1");
        assert_eq!(team.members.len(), 2);
        assert!(team.graph_write_users.contains(&"user-1".to_string()));
    }

    #[test]
    fn test_team_invite() {
        let invite = TeamInvite {
            token: "abc123".to_string(),
            team_id: "team-1".to_string(),
            email: Some("new@example.com".to_string()),
            role: "contributor".to_string(),
            created_by: "user-1".to_string(),
            created_at: 1000,
            expires_at: 2000,
            accepted: false,
            accepted_by: None,
        };
        assert_eq!(invite.team_id, "team-1");
        assert!(invite.email.is_some());
        assert!(!invite.accepted);
    }

    // US-GF-04: edge provenance label mapping
    #[test]
    fn typed_resolution_is_extracted() {
        let rel = Relationship {
            confidence: 1.0,
            metadata: serde_json::json!({"resolution_method": "typed"}),
            ..Default::default()
        };
        assert_eq!(rel.confidence_label(), "EXTRACTED");
    }

    #[test]
    fn name_high_confidence_is_extracted() {
        let rel = Relationship {
            confidence: 0.9,
            metadata: serde_json::json!({"resolution_method": "name"}),
            ..Default::default()
        };
        assert_eq!(rel.confidence_label(), "EXTRACTED");
    }

    #[test]
    fn name_low_confidence_is_inferred() {
        let rel = Relationship {
            confidence: 0.5,
            metadata: serde_json::json!({"resolution_method": "name"}),
            ..Default::default()
        };
        assert_eq!(rel.confidence_label(), "INFERRED");
    }

    #[test]
    fn file_hint_is_inferred() {
        let rel = Relationship {
            confidence: 0.7,
            metadata: serde_json::json!({"resolution_method": "name_file_hint"}),
            ..Default::default()
        };
        assert_eq!(rel.confidence_label(), "INFERRED");
    }

    #[test]
    fn unresolved_is_ambiguous() {
        let rel = Relationship {
            confidence: 0.2,
            metadata: serde_json::json!({"resolution_method": "unresolved"}),
            ..Default::default()
        };
        assert_eq!(rel.confidence_label(), "AMBIGUOUS");
    }

    #[test]
    fn unknown_method_falls_back_to_confidence_band() {
        let high = Relationship {
            confidence: 0.95,
            metadata: serde_json::json!({}),
            ..Default::default()
        };
        assert_eq!(high.confidence_label(), "EXTRACTED");
        let mid = Relationship {
            confidence: 0.6,
            metadata: serde_json::json!({}),
            ..Default::default()
        };
        assert_eq!(mid.confidence_label(), "INFERRED");
        let low = Relationship {
            confidence: 0.2,
            metadata: serde_json::json!({}),
            ..Default::default()
        };
        assert_eq!(low.confidence_label(), "AMBIGUOUS");
    }
}