1use std::collections::{BTreeMap, BTreeSet};
4use std::fmt::Write as _;
5
6use code_system_graph_model::{
7 Edge, EdgeId, Evidence, EvidenceId, Node, NodeId, Provenance, RepoFreshnessState, RepoId
8};
9use schemars::{JsonSchema, schema_for};
10use serde::{Deserialize, Serialize};
11use thiserror::Error;
12
13use crate::{
14 ChangeImpactReport, ChangeRequest, ImpactReport, ImpactRequest, PullRequestInspection, SearchReport, SearchRequest, TraversalReport, TraversalRequest
15};
16
17mod contracts;
18
19pub use contracts::{
20 CONTRACT_NODE_KINDS, ContractAction, ContractCompatibility, ContractCompatibilitySummary, ContractDifference, ContractFinding, ContractIssue, ContractIssueSeverity, ContractLink, ContractReport, ContractRequest, ContractView, inspect_contracts
21};
22
23pub const INTERFACE_SCHEMA_VERSION: u32 = 2;
25pub const INTERFACE_RESULT_VERSION: u32 = 2;
27pub const DELIVERY_METADATA_VERSION: u32 = 2;
29pub const MAX_EXPORT_NODES: usize = 100_000;
31pub const MAX_EXPORT_EDGES: usize = 1_000_000;
33const DEFAULT_EXPORT_NODES: usize = 10_000;
34const DEFAULT_EXPORT_EDGES: usize = 50_000;
35
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
40pub struct EvidenceMetadata {
41 pub id: EvidenceId,
43 pub repo_id: Option<RepoId>,
45 pub file_path: Option<String>,
47 pub start_line: Option<u32>,
49 pub end_line: Option<u32>,
51 pub extractor: String,
53 pub extractor_version: String,
55 pub provenance: Provenance,
57 pub confidence: f32,
59 pub observed_at_commit: Option<String>,
61 pub content_hash: Option<String>,
63}
64
65impl From<&Evidence> for EvidenceMetadata {
66 fn from(value: &Evidence) -> Self {
67 Self {
68 id: value.id.clone(),
69 repo_id: value.repo_id.clone(),
70 file_path: value.file_path.clone(),
71 start_line: value.start_line,
72 end_line: value.end_line,
73 extractor: value.extractor.clone(),
74 extractor_version: value.extractor_version.clone(),
75 provenance: value.provenance,
76 confidence: value.confidence,
77 observed_at_commit: value.observed_at_commit.clone(),
78 content_hash: value.content_hash.clone(),
79 }
80 }
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
85#[serde(rename_all = "snake_case")]
86pub enum ExportFormat {
87 Json,
89 GraphMl,
91 Markdown,
93}
94
95#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
97pub struct ExportRequest {
98 pub format: ExportFormat,
100 pub max_nodes: usize,
102 pub max_edges: usize,
104}
105
106impl Default for ExportRequest {
107 fn default() -> Self {
108 Self {
109 format: ExportFormat::Json,
110 max_nodes: DEFAULT_EXPORT_NODES,
111 max_edges: DEFAULT_EXPORT_EDGES,
112 }
113 }
114}
115
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
118pub struct ExportReport {
119 pub schema_version: u32,
121 pub result_version: u32,
123 pub format: ExportFormat,
125 pub content: String,
127 pub exported_nodes: usize,
129 pub exported_edges: usize,
131 pub omitted_nodes: usize,
133 pub omitted_edges: usize,
135 pub truncated: bool,
137 pub warnings: Vec<Warning>,
139}
140
141#[derive(
143 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
144)]
145#[serde(rename_all = "snake_case")]
146pub enum DoctorCategory {
147 Schema,
149 Integrity,
151 Freshness,
153 Provider,
155 Config,
157}
158
159#[derive(
161 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
162)]
163#[serde(rename_all = "snake_case")]
164pub enum DoctorStatus {
165 Healthy,
167 Degraded,
169 Failed,
171 Unknown,
173}
174
175#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
177pub struct SchemaDoctorInput {
178 pub name: String,
180 pub expected_schema: String,
182 pub actual_schema: Option<String>,
184 pub metadata_consistent: Option<bool>,
186}
187
188#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
190pub struct IntegrityDoctorInput {
191 pub name: String,
193 pub passed: Option<bool>,
195 pub detail: Option<String>,
197}
198
199#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
201pub struct FreshnessDoctorInput {
202 pub repo_id: RepoId,
204 pub state: RepoFreshnessState,
206 pub detail: Option<String>,
208}
209
210#[derive(
212 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
213)]
214#[serde(rename_all = "snake_case")]
215pub enum ProviderDoctorStatus {
216 Available,
218 IndexMissing,
220 Stale,
222 Unavailable,
224 Incompatible,
226 InvalidResponse,
228 TimedOut,
230}
231
232#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
234pub struct ProviderDoctorInput {
235 pub name: String,
237 pub status: ProviderDoctorStatus,
239 pub detail: Option<String>,
241}
242
243#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
245pub struct ConfigDoctorInput {
246 pub name: String,
248 pub valid: Option<bool>,
250 pub detail: Option<String>,
252}
253
254#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
256pub struct DoctorRequest {
257 pub schema: Vec<SchemaDoctorInput>,
259 pub integrity: Vec<IntegrityDoctorInput>,
261 pub freshness: Vec<FreshnessDoctorInput>,
263 pub providers: Vec<ProviderDoctorInput>,
265 pub config: Vec<ConfigDoctorInput>,
267}
268
269#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
271pub struct DoctorCheck {
272 pub category: DoctorCategory,
274 pub name: String,
276 pub status: DoctorStatus,
278 pub summary: String,
280 pub remediation: Option<String>,
282}
283
284#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
286pub struct DoctorReport {
287 pub schema_version: u32,
289 pub result_version: u32,
291 pub status: DoctorStatus,
293 pub checks: Vec<DoctorCheck>,
295 pub complete: bool,
297 pub healthy_checks: usize,
299 pub degraded_checks: usize,
301 pub failed_checks: usize,
303 pub unknown_checks: usize,
305}
306
307#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
309pub struct Pagination {
310 pub version: u32,
312 pub offset: usize,
314 pub limit: usize,
316 pub total: usize,
318 pub returned: usize,
320 pub has_more: bool,
322}
323
324#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
326pub struct Summary {
327 pub version: u32,
329 pub code: String,
331 pub title: String,
333 pub detail: String,
335 pub complete: bool,
337}
338
339#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
341pub struct Ambiguity {
342 pub version: u32,
344 pub code: String,
346 pub message: String,
348 pub candidates: Vec<String>,
350 pub remediation: String,
352}
353
354#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
356pub struct Warning {
357 pub version: u32,
359 pub code: String,
361 pub message: String,
363}
364
365#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
367pub struct NextAction {
368 pub version: u32,
370 pub code: String,
372 pub reason: String,
374 pub command: Option<String>,
376}
377
378#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
380pub struct Page<T> {
381 pub schema_version: u32,
383 pub result_version: u32,
385 pub items: Vec<T>,
387 pub pagination: Pagination,
389 pub summary: Summary,
391 pub ambiguities: Vec<Ambiguity>,
393 pub warnings: Vec<Warning>,
395 pub next_actions: Vec<NextAction>,
397}
398
399#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
401pub struct PublicSchema {
402 pub name: String,
404 pub version: u32,
406 pub schema: serde_json::Value,
408}
409
410#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
412pub struct PublicSchemaCatalog {
413 pub schema_version: u32,
415 pub result_version: u32,
417 pub schemas: Vec<PublicSchema>,
419}
420
421#[derive(
423 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
424)]
425#[serde(rename_all = "snake_case")]
426pub enum DomainErrorKind {
427 InvalidInput,
429 NotFound,
431 Ambiguous,
433 Conflict,
435 Partial,
437 Unavailable,
439 Timeout,
441 Cancelled,
443 Internal,
445}
446
447#[derive(
449 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
450)]
451#[repr(u8)]
452#[serde(rename_all = "snake_case")]
453pub enum ExitCode {
454 Success = 0,
456 InvalidInput = 2,
458 NotFound = 3,
460 Ambiguous = 4,
462 Conflict = 5,
464 Partial = 6,
466 Unavailable = 7,
468 Timeout = 8,
470 Internal = 70,
472 Cancelled = 130,
474}
475
476impl ExitCode {
477 #[must_use]
479 pub const fn value(self) -> u8 {
480 self as u8
481 }
482}
483
484#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Error)]
486#[serde(tag = "kind", rename_all = "snake_case")]
487pub enum InterfaceError {
488 #[error("contract action `{action:?}` requires `{field}`")]
490 MissingContractField {
491 action: ContractAction,
493 field: String,
495 },
496 #[error("graph entity `{0}` was not found")]
498 NotFound(String),
499 #[error("duplicate {entity} identifier `{id}`")]
501 DuplicateIdentity {
502 entity: String,
504 id: String,
506 },
507 #[error("requested {name} bound {value} is outside 1..={maximum}")]
509 InvalidBound {
510 name: String,
512 value: usize,
514 maximum: usize,
516 },
517 #[error("failed to serialize `{0}`")]
519 Serialization(String),
520}
521
522pub fn export_graph(
532 nodes: &[Node],
533 edges: &[Edge],
534 evidence: &[Evidence],
535 request: &ExportRequest,
536) -> Result<ExportReport, InterfaceError> {
537 validate_bound("node export", request.max_nodes, MAX_EXPORT_NODES)?;
538 validate_bound("edge export", request.max_edges, MAX_EXPORT_EDGES)?;
539 let node_index = index_nodes(nodes)?;
540 let _ = index_edges(edges)?;
541 let evidence_index = index_evidence(evidence)?;
542 let mut ordered_nodes = nodes.iter().collect::<Vec<_>>();
543 ordered_nodes.sort_by(|left, right| {
544 left.stable_key
545 .cmp(&right.stable_key)
546 .then_with(|| left.id.cmp(&right.id))
547 });
548 let selected_nodes = ordered_nodes
549 .into_iter()
550 .take(request.max_nodes)
551 .cloned()
552 .collect::<Vec<_>>();
553 let selected_ids = selected_nodes
554 .iter()
555 .map(|node| node.id.clone())
556 .collect::<BTreeSet<_>>();
557 let mut warnings = Vec::new();
558 let mut eligible_edges = edges
559 .iter()
560 .filter(|edge| selected_ids.contains(&edge.source) && selected_ids.contains(&edge.target))
561 .collect::<Vec<_>>();
562 for edge in edges {
563 if !node_index.contains_key(&edge.source) || !node_index.contains_key(&edge.target) {
564 warnings.push(warning(
565 "export.dangling_edge",
566 &format!(
567 "Edge `{}` was omitted because an endpoint is missing.",
568 edge.id.as_str()
569 ),
570 ));
571 }
572 for evidence_id in &edge.evidence {
573 if !evidence_index.contains_key(evidence_id) {
574 warnings.push(warning(
575 "export.evidence_not_observed",
576 &format!(
577 "Evidence `{}` referenced by edge `{}` was not observed.",
578 evidence_id.as_str(),
579 edge.id.as_str()
580 ),
581 ));
582 }
583 }
584 }
585 eligible_edges.sort_by(|left, right| left.id.cmp(&right.id));
586 let selected_edges = eligible_edges
587 .into_iter()
588 .take(request.max_edges)
589 .map(|edge| ExportEdge {
590 edge: edge.clone(),
591 evidence: evidence_for_edge(edge, &evidence_index),
592 })
593 .collect::<Vec<_>>();
594 warnings.sort_by(|left, right| {
595 left.code
596 .cmp(&right.code)
597 .then_with(|| left.message.cmp(&right.message))
598 });
599 warnings.dedup();
600 let content = match request.format {
601 ExportFormat::Json => render_json(&selected_nodes, &selected_edges)?,
602 ExportFormat::GraphMl => render_graphml(&selected_nodes, &selected_edges),
603 ExportFormat::Markdown => render_markdown(&selected_nodes, &selected_edges),
604 };
605 let omitted_nodes = nodes.len().saturating_sub(selected_nodes.len());
606 let omitted_edges = edges.len().saturating_sub(selected_edges.len());
607 Ok(ExportReport {
608 schema_version: INTERFACE_SCHEMA_VERSION,
609 result_version: INTERFACE_RESULT_VERSION,
610 format: request.format,
611 content,
612 exported_nodes: selected_nodes.len(),
613 exported_edges: selected_edges.len(),
614 omitted_nodes,
615 omitted_edges,
616 truncated: omitted_nodes > 0 || omitted_edges > 0,
617 warnings,
618 })
619}
620
621#[must_use]
626pub fn doctor(request: &DoctorRequest) -> DoctorReport {
627 let mut checks = Vec::new();
628 append_schema_checks(&request.schema, &mut checks);
629 append_integrity_checks(&request.integrity, &mut checks);
630 append_freshness_checks(&request.freshness, &mut checks);
631 append_provider_checks(&request.providers, &mut checks);
632 append_config_checks(&request.config, &mut checks);
633 checks.sort_by(|left, right| {
634 left.category
635 .cmp(&right.category)
636 .then_with(|| left.name.cmp(&right.name))
637 .then_with(|| left.summary.cmp(&right.summary))
638 });
639 let healthy_checks = count_status(&checks, DoctorStatus::Healthy);
640 let degraded_checks = count_status(&checks, DoctorStatus::Degraded);
641 let failed_checks = count_status(&checks, DoctorStatus::Failed);
642 let unknown_checks = count_status(&checks, DoctorStatus::Unknown);
643 let status = if failed_checks > 0 {
644 DoctorStatus::Failed
645 } else if unknown_checks > 0 {
646 DoctorStatus::Unknown
647 } else if degraded_checks > 0 {
648 DoctorStatus::Degraded
649 } else {
650 DoctorStatus::Healthy
651 };
652 DoctorReport {
653 schema_version: INTERFACE_SCHEMA_VERSION,
654 result_version: INTERFACE_RESULT_VERSION,
655 status,
656 checks,
657 complete: unknown_checks == 0,
658 healthy_checks,
659 degraded_checks,
660 failed_checks,
661 unknown_checks,
662 }
663}
664
665pub fn paginate<T: Clone>(
672 items: &[T],
673 offset: usize,
674 limit: usize,
675 summary: Summary,
676) -> Result<Page<T>, InterfaceError> {
677 validate_bound("page", limit, MAX_EXPORT_NODES)?;
678 let start = offset.min(items.len());
679 let page_items = items
680 .iter()
681 .skip(start)
682 .take(limit)
683 .cloned()
684 .collect::<Vec<_>>();
685 let returned = page_items.len();
686 Ok(Page {
687 schema_version: INTERFACE_SCHEMA_VERSION,
688 result_version: INTERFACE_RESULT_VERSION,
689 items: page_items,
690 pagination: Pagination {
691 version: DELIVERY_METADATA_VERSION,
692 offset,
693 limit,
694 total: items.len(),
695 returned,
696 has_more: start.saturating_add(returned) < items.len(),
697 },
698 summary,
699 ambiguities: Vec::new(),
700 warnings: Vec::new(),
701 next_actions: Vec::new(),
702 })
703}
704
705pub fn public_schema_catalog() -> Result<PublicSchemaCatalog, InterfaceError> {
711 let mut schemas = vec![
712 public_schema::<ChangeImpactReport>("ChangeImpactReport")?,
713 public_schema::<ChangeRequest>("ChangeRequest")?,
714 public_schema::<ContractReport>("ContractReport")?,
715 public_schema::<ContractRequest>("ContractRequest")?,
716 public_schema::<DoctorReport>("DoctorReport")?,
717 public_schema::<DoctorRequest>("DoctorRequest")?,
718 public_schema::<ExportReport>("ExportReport")?,
719 public_schema::<ExportRequest>("ExportRequest")?,
720 public_schema::<ImpactReport>("ImpactReport")?,
721 public_schema::<ImpactRequest>("ImpactRequest")?,
722 public_schema::<Page<ContractView>>("PageContractView")?,
723 public_schema::<PullRequestInspection>("PullRequestInspection")?,
724 public_schema::<SearchReport>("SearchReport")?,
725 public_schema::<SearchRequest>("SearchRequest")?,
726 public_schema::<TraversalReport>("TraversalReport")?,
727 public_schema::<TraversalRequest>("TraversalRequest")?,
728 ];
729 schemas.sort_by(|left, right| left.name.cmp(&right.name));
730 Ok(PublicSchemaCatalog {
731 schema_version: INTERFACE_SCHEMA_VERSION,
732 result_version: INTERFACE_RESULT_VERSION,
733 schemas,
734 })
735}
736
737#[must_use]
739pub const fn classify_exit_code(kind: DomainErrorKind) -> ExitCode {
740 match kind {
741 DomainErrorKind::InvalidInput => ExitCode::InvalidInput,
742 DomainErrorKind::NotFound => ExitCode::NotFound,
743 DomainErrorKind::Ambiguous => ExitCode::Ambiguous,
744 DomainErrorKind::Conflict => ExitCode::Conflict,
745 DomainErrorKind::Partial => ExitCode::Partial,
746 DomainErrorKind::Unavailable => ExitCode::Unavailable,
747 DomainErrorKind::Timeout => ExitCode::Timeout,
748 DomainErrorKind::Cancelled => ExitCode::Cancelled,
749 DomainErrorKind::Internal => ExitCode::Internal,
750 }
751}
752
753#[must_use]
755pub const fn classify_interface_error(error: &InterfaceError) -> ExitCode {
756 match error {
757 InterfaceError::MissingContractField { .. } | InterfaceError::InvalidBound { .. } => {
758 ExitCode::InvalidInput
759 }
760 InterfaceError::NotFound(_) => ExitCode::NotFound,
761 InterfaceError::DuplicateIdentity { .. } => ExitCode::Conflict,
762 InterfaceError::Serialization(_) => ExitCode::Internal,
763 }
764}
765
766#[derive(Debug, Clone, PartialEq, Serialize)]
767struct ExportEdge {
768 edge: Edge,
769 evidence: Vec<EvidenceMetadata>,
770}
771
772#[derive(Serialize)]
773struct JsonExport<'a> {
774 schema_version: u32,
775 result_version: u32,
776 nodes: &'a [Node],
777 edges: &'a [ExportEdge],
778}
779
780fn validate_bound(name: &str, value: usize, maximum: usize) -> Result<(), InterfaceError> {
781 if value == 0 || value > maximum {
782 Err(InterfaceError::InvalidBound {
783 name: name.to_owned(),
784 value,
785 maximum,
786 })
787 } else {
788 Ok(())
789 }
790}
791
792fn index_nodes(nodes: &[Node]) -> Result<BTreeMap<NodeId, &Node>, InterfaceError> {
793 let mut index = BTreeMap::new();
794 for node in nodes {
795 if index.insert(node.id.clone(), node).is_some() {
796 return Err(InterfaceError::DuplicateIdentity {
797 entity: "node".to_owned(),
798 id: node.id.as_str().to_owned(),
799 });
800 }
801 }
802 Ok(index)
803}
804
805fn index_edges(edges: &[Edge]) -> Result<BTreeMap<EdgeId, &Edge>, InterfaceError> {
806 let mut index = BTreeMap::new();
807 for edge in edges {
808 if index.insert(edge.id.clone(), edge).is_some() {
809 return Err(InterfaceError::DuplicateIdentity {
810 entity: "edge".to_owned(),
811 id: edge.id.as_str().to_owned(),
812 });
813 }
814 }
815 Ok(index)
816}
817
818fn index_evidence(
819 evidence: &[Evidence],
820) -> Result<BTreeMap<EvidenceId, &Evidence>, InterfaceError> {
821 let mut index = BTreeMap::new();
822 for item in evidence {
823 if index.insert(item.id.clone(), item).is_some() {
824 return Err(InterfaceError::DuplicateIdentity {
825 entity: "evidence".to_owned(),
826 id: item.id.as_str().to_owned(),
827 });
828 }
829 }
830 Ok(index)
831}
832
833fn evidence_for_edge(
834 edge: &Edge,
835 evidence: &BTreeMap<EvidenceId, &Evidence>,
836) -> Vec<EvidenceMetadata> {
837 let mut selected = edge
838 .evidence
839 .iter()
840 .filter_map(|id| evidence.get(id).copied())
841 .map(EvidenceMetadata::from)
842 .collect::<Vec<_>>();
843 selected.sort_by(|left, right| left.id.cmp(&right.id));
844 selected
845}
846
847fn render_json(nodes: &[Node], edges: &[ExportEdge]) -> Result<String, InterfaceError> {
848 serde_json::to_string_pretty(&JsonExport {
849 schema_version: INTERFACE_SCHEMA_VERSION,
850 result_version: INTERFACE_RESULT_VERSION,
851 nodes,
852 edges,
853 })
854 .map_err(|_| InterfaceError::Serialization("graph export".to_owned()))
855}
856
857fn render_graphml(nodes: &[Node], edges: &[ExportEdge]) -> String {
858 let mut output = String::from(
859 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
860 <graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\">\n\
861 <key id=\"kind\" for=\"all\" attr.name=\"kind\" attr.type=\"string\"/>\n\
862 <key id=\"stable_key\" for=\"node\" attr.name=\"stable_key\" attr.type=\"string\"/>\n\
863 <key id=\"label\" for=\"node\" attr.name=\"label\" attr.type=\"string\"/>\n\
864 <key id=\"status\" for=\"edge\" attr.name=\"status\" attr.type=\"string\"/>\n\
865 <key id=\"confidence\" for=\"edge\" attr.name=\"confidence\" attr.type=\"float\"/>\n\
866 <key id=\"evidence\" for=\"edge\" attr.name=\"evidence\" attr.type=\"string\"/>\n\
867 <graph id=\"code-system-graph\" edgedefault=\"directed\">\n",
868 );
869 for node in nodes {
870 let _ = writeln!(
871 output,
872 "<node id=\"{}\"><data key=\"kind\">{}</data><data key=\"stable_key\">{}</data><data key=\"label\">{}</data></node>",
873 escape_xml(node.id.as_str()),
874 escape_xml(&enum_name(node.kind)),
875 escape_xml(&node.stable_key),
876 escape_xml(&node.label)
877 );
878 }
879 for item in edges {
880 let locations = item
881 .evidence
882 .iter()
883 .map(evidence_location)
884 .collect::<Vec<_>>()
885 .join("; ");
886 let _ = writeln!(
887 output,
888 "<edge id=\"{}\" source=\"{}\" target=\"{}\"><data key=\"kind\">{}</data><data key=\"status\">{}</data><data key=\"confidence\">{}</data><data key=\"evidence\">{}</data></edge>",
889 escape_xml(item.edge.id.as_str()),
890 escape_xml(item.edge.source.as_str()),
891 escape_xml(item.edge.target.as_str()),
892 escape_xml(&enum_name(item.edge.kind)),
893 escape_xml(&enum_name(item.edge.status)),
894 item.edge.confidence,
895 escape_xml(&locations)
896 );
897 }
898 output.push_str("</graph>\n</graphml>\n");
899 output
900}
901
902fn render_markdown(nodes: &[Node], edges: &[ExportEdge]) -> String {
903 let mut output = String::from(
904 "# Code System Graph graph export\n\n## Nodes\n\n| ID | Kind | Stable key | Label |\n|---|---|---|---|\n",
905 );
906 for node in nodes {
907 let _ = writeln!(
908 output,
909 "| {} | {} | {} | {} |",
910 escape_markdown(node.id.as_str()),
911 escape_markdown(&enum_name(node.kind)),
912 escape_markdown(&node.stable_key),
913 escape_markdown(&node.label)
914 );
915 }
916 output.push_str("\n## Edges\n\n| ID | Source | Target | Kind | Status | Confidence | Evidence |\n|---|---|---|---|---|---:|---|\n");
917 for item in edges {
918 let locations = item
919 .evidence
920 .iter()
921 .map(evidence_location)
922 .collect::<Vec<_>>()
923 .join("; ");
924 let _ = writeln!(
925 output,
926 "| {} | {} | {} | {} | {} | {} | {} |",
927 escape_markdown(item.edge.id.as_str()),
928 escape_markdown(item.edge.source.as_str()),
929 escape_markdown(item.edge.target.as_str()),
930 escape_markdown(&enum_name(item.edge.kind)),
931 escape_markdown(&enum_name(item.edge.status)),
932 item.edge.confidence,
933 escape_markdown(&locations)
934 );
935 }
936 output
937}
938
939fn evidence_location(evidence: &EvidenceMetadata) -> String {
940 let path = evidence.file_path.as_deref().unwrap_or("<unknown>");
941 match (evidence.start_line, evidence.end_line) {
942 (Some(start), Some(end)) => format!("{path}:{start}-{end}"),
943 (Some(start), None) => format!("{path}:{start}"),
944 _ => path.to_owned(),
945 }
946}
947
948fn enum_name<T: Serialize>(value: T) -> String {
949 serde_json::to_value(value)
950 .ok()
951 .and_then(|value| value.as_str().map(str::to_owned))
952 .unwrap_or_else(|| "unknown".to_owned())
953}
954
955fn escape_xml(value: &str) -> String {
956 let mut escaped = String::with_capacity(value.len());
957 for character in value.chars() {
958 match character {
959 '&' => escaped.push_str("&"),
960 '<' => escaped.push_str("<"),
961 '>' => escaped.push_str(">"),
962 '"' => escaped.push_str("""),
963 '\'' => escaped.push_str("'"),
964 '\t' | '\n' | '\r' => escaped.push(character),
965 character if character.is_control() => escaped.push('\u{fffd}'),
966 character => escaped.push(character),
967 }
968 }
969 escaped
970}
971
972fn escape_markdown(value: &str) -> String {
973 let mut escaped = String::with_capacity(value.len());
974 for character in value.chars() {
975 match character {
976 '\r' | '\n' | '\t' => escaped.push(' '),
977 character if character.is_control() => escaped.push('\u{fffd}'),
978 '\\' | '`' | '*' | '_' | '{' | '}' | '[' | ']' | '(' | ')' | '#' | '+' | '-' | '.'
979 | '!' | '|' | '>' => {
980 escaped.push('\\');
981 escaped.push(character);
982 }
983 character => escaped.push(character),
984 }
985 }
986 escaped
987}
988
989fn append_schema_checks(inputs: &[SchemaDoctorInput], checks: &mut Vec<DoctorCheck>) {
990 if inputs.is_empty() {
991 checks.push(missing_doctor_category(DoctorCategory::Schema));
992 }
993 for input in inputs {
994 let (status, summary, remediation) =
995 match (input.actual_schema.as_deref(), input.metadata_consistent) {
996 (Some(actual), Some(true)) if actual == input.expected_schema => (
997 DoctorStatus::Healthy,
998 "Schema identity matches this binary and metadata is consistent.".to_owned(),
999 None,
1000 ),
1001 (Some(actual), _) if actual != input.expected_schema => (
1002 DoctorStatus::Failed,
1003 format!(
1004 "Schema identity `{actual}` does not match `{}`.",
1005 input.expected_schema
1006 ),
1007 Some("Remove the local database and run a full scan.".to_owned()),
1008 ),
1009 (Some(_), Some(false)) => (
1010 DoctorStatus::Failed,
1011 "Schema metadata is inconsistent.".to_owned(),
1012 Some("Remove the local database and run a full scan.".to_owned()),
1013 ),
1014 _ => (
1015 DoctorStatus::Unknown,
1016 "Schema state was not fully observed.".to_owned(),
1017 Some("Open the store and validate its exact schema metadata.".to_owned()),
1018 ),
1019 };
1020 checks.push(DoctorCheck {
1021 category: DoctorCategory::Schema,
1022 name: input.name.clone(),
1023 status,
1024 summary,
1025 remediation,
1026 });
1027 }
1028}
1029
1030fn append_integrity_checks(inputs: &[IntegrityDoctorInput], checks: &mut Vec<DoctorCheck>) {
1031 if inputs.is_empty() {
1032 checks.push(missing_doctor_category(DoctorCategory::Integrity));
1033 }
1034 for input in inputs {
1035 let (status, fallback, remediation) = match input.passed {
1036 Some(true) => (DoctorStatus::Healthy, "Integrity check passed.", None),
1037 Some(false) => (
1038 DoctorStatus::Failed,
1039 "Integrity check failed.",
1040 Some("Restore the last verified backup before rebuilding state.".to_owned()),
1041 ),
1042 None => (
1043 DoctorStatus::Unknown,
1044 "Integrity check did not complete.",
1045 Some("Run the bounded integrity check before trusting stored results.".to_owned()),
1046 ),
1047 };
1048 checks.push(DoctorCheck {
1049 category: DoctorCategory::Integrity,
1050 name: input.name.clone(),
1051 status,
1052 summary: input.detail.clone().unwrap_or_else(|| fallback.to_owned()),
1053 remediation,
1054 });
1055 }
1056}
1057
1058fn append_freshness_checks(inputs: &[FreshnessDoctorInput], checks: &mut Vec<DoctorCheck>) {
1059 if inputs.is_empty() {
1060 checks.push(missing_doctor_category(DoctorCategory::Freshness));
1061 }
1062 for input in inputs {
1063 let (status, fallback, remediation) = match input.state {
1064 RepoFreshnessState::Fresh => (DoctorStatus::Healthy, "Snapshot is fresh.", None),
1065 RepoFreshnessState::WorkingTreeChanged
1066 | RepoFreshnessState::CommitsBehind
1067 | RepoFreshnessState::ConfigChanged
1068 | RepoFreshnessState::ExtractorChanged
1069 | RepoFreshnessState::CodegraphPending => (
1070 DoctorStatus::Degraded,
1071 "Snapshot is stale relative to a known input.",
1072 Some(
1073 "Run an explicit incremental scan before relying on safety claims.".to_owned(),
1074 ),
1075 ),
1076 RepoFreshnessState::Corrupt => (
1077 DoctorStatus::Failed,
1078 "Snapshot is marked corrupt.",
1079 Some(
1080 "Restore a verified snapshot or rebuild after integrity diagnosis.".to_owned(),
1081 ),
1082 ),
1083 RepoFreshnessState::Partial
1084 | RepoFreshnessState::Unknown
1085 | RepoFreshnessState::Unavailable => (
1086 DoctorStatus::Unknown,
1087 "Repository freshness is incomplete or unavailable.",
1088 Some("Restore repository access and complete a bounded scan.".to_owned()),
1089 ),
1090 };
1091 checks.push(DoctorCheck {
1092 category: DoctorCategory::Freshness,
1093 name: input.repo_id.as_str().to_owned(),
1094 status,
1095 summary: input.detail.clone().unwrap_or_else(|| fallback.to_owned()),
1096 remediation,
1097 });
1098 }
1099}
1100
1101fn append_provider_checks(inputs: &[ProviderDoctorInput], checks: &mut Vec<DoctorCheck>) {
1102 if inputs.is_empty() {
1103 checks.push(missing_doctor_category(DoctorCategory::Provider));
1104 }
1105 for input in inputs {
1106 let (status, fallback, remediation) = match input.status {
1107 ProviderDoctorStatus::Available => {
1108 (DoctorStatus::Healthy, "Provider is available.", None)
1109 }
1110 ProviderDoctorStatus::IndexMissing | ProviderDoctorStatus::Stale => (
1111 DoctorStatus::Degraded,
1112 "Provider index is missing or stale.",
1113 Some(
1114 "Initialize or refresh the provider index explicitly if enrichment is needed."
1115 .to_owned(),
1116 ),
1117 ),
1118 ProviderDoctorStatus::Unavailable | ProviderDoctorStatus::TimedOut => (
1119 DoctorStatus::Unknown,
1120 "Provider availability could not be established.",
1121 Some(
1122 "Verify the provider binary and rerun its bounded compatibility probe."
1123 .to_owned(),
1124 ),
1125 ),
1126 ProviderDoctorStatus::Incompatible | ProviderDoctorStatus::InvalidResponse => (
1127 DoctorStatus::Failed,
1128 "Provider public contract is incompatible or invalid.",
1129 Some(
1130 "Use a tested provider version or disable the incompatible adapter.".to_owned(),
1131 ),
1132 ),
1133 };
1134 checks.push(DoctorCheck {
1135 category: DoctorCategory::Provider,
1136 name: input.name.clone(),
1137 status,
1138 summary: input.detail.clone().unwrap_or_else(|| fallback.to_owned()),
1139 remediation,
1140 });
1141 }
1142}
1143
1144fn append_config_checks(inputs: &[ConfigDoctorInput], checks: &mut Vec<DoctorCheck>) {
1145 if inputs.is_empty() {
1146 checks.push(missing_doctor_category(DoctorCategory::Config));
1147 }
1148 for input in inputs {
1149 let (status, fallback, remediation) = match input.valid {
1150 Some(true) => (DoctorStatus::Healthy, "Configuration is valid.", None),
1151 Some(false) => (
1152 DoctorStatus::Failed,
1153 "Configuration is invalid.",
1154 Some(
1155 "Correct the reported field without discarding unrelated settings.".to_owned(),
1156 ),
1157 ),
1158 None => (
1159 DoctorStatus::Unknown,
1160 "Configuration validation did not complete.",
1161 Some("Load and validate every effective configuration layer.".to_owned()),
1162 ),
1163 };
1164 checks.push(DoctorCheck {
1165 category: DoctorCategory::Config,
1166 name: input.name.clone(),
1167 status,
1168 summary: input.detail.clone().unwrap_or_else(|| fallback.to_owned()),
1169 remediation,
1170 });
1171 }
1172}
1173
1174fn missing_doctor_category(category: DoctorCategory) -> DoctorCheck {
1175 DoctorCheck {
1176 category,
1177 name: "not_observed".to_owned(),
1178 status: DoctorStatus::Unknown,
1179 summary: "No input was supplied for this required doctor category.".to_owned(),
1180 remediation: Some(
1181 "Collect the category check before claiming a healthy system.".to_owned(),
1182 ),
1183 }
1184}
1185
1186fn count_status(checks: &[DoctorCheck], status: DoctorStatus) -> usize {
1187 checks.iter().filter(|check| check.status == status).count()
1188}
1189
1190fn warning(code: &str, message: &str) -> Warning {
1191 Warning {
1192 version: DELIVERY_METADATA_VERSION,
1193 code: code.to_owned(),
1194 message: message.to_owned(),
1195 }
1196}
1197
1198fn public_schema<T: JsonSchema>(name: &str) -> Result<PublicSchema, InterfaceError> {
1199 let schema = serde_json::to_value(schema_for!(T))
1200 .map_err(|_| InterfaceError::Serialization(format!("schema {name}")))?;
1201 Ok(PublicSchema {
1202 name: name.to_owned(),
1203 version: INTERFACE_SCHEMA_VERSION,
1204 schema,
1205 })
1206}
1207
1208#[cfg(test)]
1209mod tests {
1210 use code_system_graph_model::{EdgeKind, EpistemicStatus, EvidenceId, NodeKind};
1211
1212 use super::*;
1213 use crate::{CompatibilityFinding, CompatibilityReport, CompatibilityStatus};
1214
1215 fn node(id: &str, kind: NodeKind, stable_key: &str) -> Node {
1216 Node {
1217 id: NodeId::new(id),
1218 kind,
1219 repo_id: Some(RepoId::new("repo:test")),
1220 stable_key: stable_key.to_owned(),
1221 label: stable_key.to_owned(),
1222 }
1223 }
1224
1225 fn evidence(id: &str, path: &str) -> Evidence {
1226 Evidence {
1227 id: EvidenceId::new(id),
1228 repo_id: Some(RepoId::new("repo:test")),
1229 file_path: Some(path.to_owned()),
1230 start_line: Some(3),
1231 end_line: Some(5),
1232 extractor: "test".to_owned(),
1233 extractor_version: "1.0.0".to_owned(),
1234 provenance: Provenance::Extracted,
1235 confidence: 1.0,
1236 observed_at_commit: Some("abc".to_owned()),
1237 content_hash: Some("hash".to_owned()),
1238 note: Some("LEAK_ME_SOURCE_BODY".to_owned()),
1239 }
1240 }
1241
1242 fn edge(id: &str, source: &str, target: &str, evidence: &[&str]) -> Edge {
1243 Edge {
1244 id: EdgeId::new(id),
1245 source: NodeId::new(source),
1246 target: NodeId::new(target),
1247 kind: EdgeKind::CallsRemote,
1248 confidence: 1.0,
1249 status: EpistemicStatus::Confirmed,
1250 evidence: evidence.iter().map(|id| EvidenceId::new(*id)).collect(),
1251 }
1252 }
1253
1254 fn request(action: ContractAction) -> ContractRequest {
1255 ContractRequest {
1256 action,
1257 contract: None,
1258 related_contract: None,
1259 limit: 100,
1260 }
1261 }
1262
1263 fn report_or_panic(result: Result<ContractReport, InterfaceError>) -> ContractReport {
1264 match result {
1265 Ok(report) => report,
1266 Err(error) => panic!("unexpected contract error: {error}"),
1267 }
1268 }
1269
1270 fn export_or_panic(result: Result<ExportReport, InterfaceError>) -> ExportReport {
1271 match result {
1272 Ok(report) => report,
1273 Err(error) => panic!("unexpected export error: {error}"),
1274 }
1275 }
1276
1277 fn json_or_panic<T: Serialize>(value: &T) -> String {
1278 match serde_json::to_string(value) {
1279 Ok(json) => json,
1280 Err(error) => panic!("unexpected JSON error: {error}"),
1281 }
1282 }
1283
1284 fn healthy_doctor_request() -> DoctorRequest {
1285 DoctorRequest {
1286 schema: vec![SchemaDoctorInput {
1287 name: "store".to_owned(),
1288 expected_schema: "schema:test".to_owned(),
1289 actual_schema: Some("schema:test".to_owned()),
1290 metadata_consistent: Some(true),
1291 }],
1292 integrity: vec![IntegrityDoctorInput {
1293 name: "sqlite".to_owned(),
1294 passed: Some(true),
1295 detail: None,
1296 }],
1297 freshness: vec![FreshnessDoctorInput {
1298 repo_id: RepoId::new("repo:test"),
1299 state: RepoFreshnessState::Fresh,
1300 detail: None,
1301 }],
1302 providers: vec![ProviderDoctorInput {
1303 name: "codegraph".to_owned(),
1304 status: ProviderDoctorStatus::Available,
1305 detail: None,
1306 }],
1307 config: vec![ConfigDoctorInput {
1308 name: "workspace".to_owned(),
1309 valid: Some(true),
1310 detail: None,
1311 }],
1312 }
1313 }
1314
1315 fn summary() -> Summary {
1316 Summary {
1317 version: DELIVERY_METADATA_VERSION,
1318 code: "test".to_owned(),
1319 title: "Test".to_owned(),
1320 detail: "Test page".to_owned(),
1321 complete: true,
1322 }
1323 }
1324
1325 #[test]
1326 fn contract_list_is_deterministic() {
1327 let nodes = vec![
1328 node("node:b", NodeKind::HttpOperation, "z"),
1329 node("node:a", NodeKind::RpcMethod, "a"),
1330 ];
1331 let first = report_or_panic(inspect_contracts(
1332 &nodes,
1333 &[],
1334 &[],
1335 &[],
1336 &request(ContractAction::List),
1337 ));
1338 let mut reversed = nodes;
1339 reversed.reverse();
1340 let second = report_or_panic(inspect_contracts(
1341 &reversed,
1342 &[],
1343 &[],
1344 &[],
1345 &request(ContractAction::List),
1346 ));
1347
1348 assert_eq!(first.contracts, second.contracts);
1349 }
1350
1351 #[test]
1352 fn contract_list_excludes_non_contract_nodes() {
1353 let nodes = vec![
1354 node("node:service", NodeKind::Service, "service"),
1355 node("node:http", NodeKind::HttpOperation, "http"),
1356 ];
1357 let report = report_or_panic(inspect_contracts(
1358 &nodes,
1359 &[],
1360 &[],
1361 &[],
1362 &request(ContractAction::List),
1363 ));
1364
1365 assert_eq!(report.contracts.len(), 1);
1366 }
1367
1368 #[test]
1369 fn contract_list_applies_limit() {
1370 let nodes = vec![
1371 node("node:a", NodeKind::HttpOperation, "a"),
1372 node("node:b", NodeKind::HttpOperation, "b"),
1373 ];
1374 let mut input = request(ContractAction::List);
1375 input.limit = 1;
1376 let report = report_or_panic(inspect_contracts(&nodes, &[], &[], &[], &input));
1377
1378 assert!(report.truncated && report.contracts.len() == 1);
1379 }
1380
1381 #[test]
1382 fn contract_list_should_not_validate_relationship_certainty() {
1383 let nodes = vec![
1384 node("node:a", NodeKind::HttpOperation, "a"),
1385 node("node:b", NodeKind::HttpOperation, "b"),
1386 ];
1387 let mut unresolved = edge("edge:1", "node:a", "node:b", &[]);
1388 unresolved.status = EpistemicStatus::Inferred;
1389 unresolved.confidence = 0.75;
1390
1391 let report = report_or_panic(inspect_contracts(
1392 &nodes,
1393 &[unresolved],
1394 &[],
1395 &[],
1396 &request(ContractAction::List),
1397 ));
1398
1399 assert!(report.complete);
1400 assert_eq!(report.issues.len(), 0);
1401 }
1402
1403 #[test]
1404 fn contract_validation_should_bound_issues_by_the_request_limit() {
1405 let nodes = (0..4)
1406 .map(|index| node(&format!("node:{index}"), NodeKind::HttpOperation, "http"))
1407 .collect::<Vec<_>>();
1408 let edges = (0..3)
1409 .map(|index| {
1410 let mut unresolved = edge(
1411 &format!("edge:{index}"),
1412 &format!("node:{index}"),
1413 &format!("node:{}", index + 1),
1414 &[],
1415 );
1416 unresolved.status = EpistemicStatus::Inferred;
1417 unresolved
1418 })
1419 .collect::<Vec<_>>();
1420 let mut input = request(ContractAction::Validate);
1421 input.limit = 2;
1422
1423 let report = report_or_panic(inspect_contracts(&nodes, &edges, &[], &[], &input));
1424
1425 assert_eq!(report.issues.len(), 2);
1426 assert!(report.truncated);
1427 assert_eq!(report.valid, Some(false));
1428 }
1429
1430 #[test]
1431 fn contract_validation_prioritizes_errors_before_unknowns_when_truncated() {
1432 let nodes = vec![
1433 node("node:a", NodeKind::HttpOperation, "a"),
1434 node("node:b", NodeKind::HttpOperation, "b"),
1435 ];
1436 let mut unresolved = edge("edge:unknown", "node:a", "node:b", &[]);
1437 unresolved.status = EpistemicStatus::Inferred;
1438 let mut invalid = edge("edge:error", "node:a", "node:b", &[]);
1439 invalid.confidence = 2.0;
1440 let mut input = request(ContractAction::Validate);
1441 input.limit = 1;
1442
1443 let report = report_or_panic(inspect_contracts(
1444 &nodes,
1445 &[unresolved, invalid],
1446 &[],
1447 &[],
1448 &input,
1449 ));
1450
1451 assert_eq!(report.issues.len(), 1);
1452 assert_eq!(report.issues[0].severity, ContractIssueSeverity::Error);
1453 assert_eq!(report.issues[0].entity_id.as_deref(), Some("edge:error"));
1454 }
1455
1456 #[test]
1457 fn scoped_contract_validation_keeps_invalid_incident_evidence() {
1458 let nodes = vec![
1459 node("node:a", NodeKind::HttpOperation, "a"),
1460 node("node:b", NodeKind::HttpOperation, "b"),
1461 node("node:c", NodeKind::HttpOperation, "c"),
1462 ];
1463 let edges = vec![
1464 edge("edge:related", "node:a", "node:b", &["evidence:related"]),
1465 edge(
1466 "edge:unrelated",
1467 "node:b",
1468 "node:c",
1469 &["evidence:unrelated"],
1470 ),
1471 ];
1472 let mut related_evidence = evidence("evidence:related", "src/a.rs");
1473 related_evidence.confidence = 2.0;
1474 let mut unrelated_evidence = evidence("evidence:unrelated", "src/c.rs");
1475 unrelated_evidence.confidence = 2.0;
1476 let mut input = request(ContractAction::Validate);
1477 input.contract = Some(NodeId::new("node:a"));
1478
1479 let report = report_or_panic(inspect_contracts(
1480 &nodes,
1481 &edges,
1482 &[related_evidence, unrelated_evidence],
1483 &[],
1484 &input,
1485 ));
1486
1487 assert!(report.issues.iter().any(|issue| {
1488 issue.code == "contract.invalid_evidence_confidence"
1489 && issue.entity_id.as_deref() == Some("evidence:related")
1490 }));
1491 assert!(
1492 report
1493 .issues
1494 .iter()
1495 .all(|issue| issue.entity_id.as_deref() != Some("evidence:unrelated"))
1496 );
1497 assert_eq!(report.valid, Some(false));
1498 }
1499
1500 #[test]
1501 fn contract_show_should_omit_issues_from_unrelated_contracts() {
1502 let nodes = vec![
1503 node("node:a", NodeKind::HttpOperation, "a"),
1504 node("node:b", NodeKind::HttpOperation, "b"),
1505 node("node:c", NodeKind::HttpOperation, "c"),
1506 ];
1507 let mut related = edge("edge:related", "node:a", "node:b", &[]);
1508 related.status = EpistemicStatus::Inferred;
1509 let mut unrelated = edge("edge:unrelated", "node:b", "node:c", &[]);
1510 unrelated.status = EpistemicStatus::Inferred;
1511 let mut input = request(ContractAction::Show);
1512 input.contract = Some(NodeId::new("node:a"));
1513
1514 let report = report_or_panic(inspect_contracts(
1515 &nodes,
1516 &[related, unrelated],
1517 &[],
1518 &[],
1519 &input,
1520 ));
1521
1522 assert!(
1523 report
1524 .issues
1525 .iter()
1526 .any(|issue| issue.entity_id.as_deref() == Some("edge:related"))
1527 );
1528 assert!(
1529 report
1530 .issues
1531 .iter()
1532 .all(|issue| issue.entity_id.as_deref() != Some("edge:unrelated"))
1533 );
1534 }
1535
1536 #[test]
1537 fn contract_show_omits_evidence_note() {
1538 let nodes = vec![
1539 node("node:a", NodeKind::HttpOperation, "a"),
1540 node("node:b", NodeKind::HttpOperation, "b"),
1541 ];
1542 let edges = vec![edge("edge:1", "node:a", "node:b", &["evidence:1"])];
1543 let evidence = vec![evidence("evidence:1", "src/<api>.rs")];
1544 let mut input = request(ContractAction::Show);
1545 input.contract = Some(NodeId::new("node:a"));
1546 let report = report_or_panic(inspect_contracts(&nodes, &edges, &evidence, &[], &input));
1547
1548 assert!(!json_or_panic(&report).contains("LEAK_ME_SOURCE_BODY"));
1549 }
1550
1551 #[test]
1552 fn contract_show_rejects_unknown_contract() {
1553 let mut input = request(ContractAction::Show);
1554 input.contract = Some(NodeId::new("node:missing"));
1555 let result = inspect_contracts(&[], &[], &[], &[], &input);
1556
1557 assert!(matches!(result, Err(InterfaceError::NotFound(_))));
1558 }
1559
1560 #[test]
1561 fn contract_show_requires_contract_field() {
1562 let result = inspect_contracts(&[], &[], &[], &[], &request(ContractAction::Show));
1563
1564 assert!(matches!(
1565 result,
1566 Err(InterfaceError::MissingContractField { .. })
1567 ));
1568 }
1569
1570 #[test]
1571 fn contract_validate_detects_dangling_edge() {
1572 let nodes = vec![node("node:a", NodeKind::HttpOperation, "a")];
1573 let edges = vec![edge("edge:1", "node:a", "node:missing", &[])];
1574 let report = report_or_panic(inspect_contracts(
1575 &nodes,
1576 &edges,
1577 &[],
1578 &[],
1579 &request(ContractAction::Validate),
1580 ));
1581
1582 assert_eq!(report.valid, Some(false));
1583 }
1584
1585 #[test]
1586 fn contract_validate_preserves_unknown_evidence() {
1587 let nodes = vec![
1588 node("node:a", NodeKind::HttpOperation, "a"),
1589 node("node:b", NodeKind::HttpOperation, "b"),
1590 ];
1591 let edges = vec![edge("edge:1", "node:a", "node:b", &["evidence:missing"])];
1592 let report = report_or_panic(inspect_contracts(
1593 &nodes,
1594 &edges,
1595 &[],
1596 &[],
1597 &request(ContractAction::Validate),
1598 ));
1599
1600 assert_eq!(report.valid, Some(false));
1601 }
1602
1603 #[test]
1604 fn contract_diff_omits_compatibility_evidence_text() {
1605 let nodes = vec![
1606 node("node:a", NodeKind::HttpOperation, "a"),
1607 node("node:b", NodeKind::HttpOperation, "b"),
1608 ];
1609 let compatibility = vec![ContractCompatibility {
1610 contract_id: NodeId::new("node:a"),
1611 report: CompatibilityReport {
1612 status: CompatibilityStatus::Breaking,
1613 before_fingerprint: "before".to_owned(),
1614 after_fingerprint: "after".to_owned(),
1615 findings: vec![CompatibilityFinding {
1616 code: "removed".to_owned(),
1617 path: "GET /a".to_owned(),
1618 status: CompatibilityStatus::Breaking,
1619 factors: vec!["operation removed".to_owned()],
1620 evidence: vec!["LEAK_ME_SOURCE_BODY".to_owned()],
1621 recommended_validations: vec!["run contract tests".to_owned()],
1622 }],
1623 },
1624 }];
1625 let mut input = request(ContractAction::Diff);
1626 input.contract = Some(NodeId::new("node:a"));
1627 input.related_contract = Some(NodeId::new("node:b"));
1628 let report = report_or_panic(inspect_contracts(&nodes, &[], &[], &compatibility, &input));
1629
1630 assert!(!json_or_panic(&report).contains("LEAK_ME_SOURCE_BODY"));
1631 }
1632
1633 #[test]
1634 fn contract_diff_reports_structural_fields() {
1635 let nodes = vec![
1636 node("node:a", NodeKind::HttpOperation, "a"),
1637 node("node:b", NodeKind::RpcMethod, "b"),
1638 ];
1639 let mut input = request(ContractAction::Diff);
1640 input.contract = Some(NodeId::new("node:a"));
1641 input.related_contract = Some(NodeId::new("node:b"));
1642 let report = report_or_panic(inspect_contracts(&nodes, &[], &[], &[], &input));
1643
1644 assert!(report.differences.iter().any(|item| item.field == "kind"));
1645 }
1646
1647 #[test]
1648 fn explain_link_returns_direct_edge() {
1649 let nodes = vec![
1650 node("node:a", NodeKind::HttpOperation, "a"),
1651 node("node:b", NodeKind::RpcMethod, "b"),
1652 ];
1653 let edges = vec![edge("edge:1", "node:a", "node:b", &[])];
1654 let mut input = request(ContractAction::ExplainLink);
1655 input.contract = Some(NodeId::new("node:a"));
1656 input.related_contract = Some(NodeId::new("node:b"));
1657 let report = report_or_panic(inspect_contracts(&nodes, &edges, &[], &[], &input));
1658
1659 assert_eq!(report.links.len(), 1);
1660 }
1661
1662 #[test]
1663 fn explain_link_marks_absence_unknown() {
1664 let nodes = vec![
1665 node("node:a", NodeKind::HttpOperation, "a"),
1666 node("node:b", NodeKind::RpcMethod, "b"),
1667 ];
1668 let mut input = request(ContractAction::ExplainLink);
1669 input.contract = Some(NodeId::new("node:a"));
1670 input.related_contract = Some(NodeId::new("node:b"));
1671 let report = report_or_panic(inspect_contracts(&nodes, &[], &[], &[], &input));
1672
1673 assert!(
1674 !report.complete
1675 && report
1676 .issues
1677 .iter()
1678 .any(|issue| issue.severity == ContractIssueSeverity::Unknown)
1679 );
1680 }
1681
1682 #[test]
1683 fn json_export_is_deterministic() {
1684 let nodes = vec![
1685 node("node:b", NodeKind::HttpOperation, "b"),
1686 node("node:a", NodeKind::HttpOperation, "a"),
1687 ];
1688 let first = export_or_panic(export_graph(&nodes, &[], &[], &ExportRequest::default()));
1689 let mut reversed = nodes;
1690 reversed.reverse();
1691 let second = export_or_panic(export_graph(&reversed, &[], &[], &ExportRequest::default()));
1692
1693 assert_eq!(first.content, second.content);
1694 }
1695
1696 #[test]
1697 fn json_export_omits_evidence_note() {
1698 let nodes = vec![
1699 node("node:a", NodeKind::HttpOperation, "a"),
1700 node("node:b", NodeKind::HttpOperation, "b"),
1701 ];
1702 let edges = vec![edge("edge:1", "node:a", "node:b", &["evidence:1"])];
1703 let report = export_or_panic(export_graph(
1704 &nodes,
1705 &edges,
1706 &[evidence("evidence:1", "api.rs")],
1707 &ExportRequest::default(),
1708 ));
1709
1710 assert!(!report.content.contains("LEAK_ME_SOURCE_BODY"));
1711 }
1712
1713 #[test]
1714 fn export_applies_node_bound() {
1715 let nodes = vec![
1716 node("node:a", NodeKind::HttpOperation, "a"),
1717 node("node:b", NodeKind::HttpOperation, "b"),
1718 ];
1719 let report = export_or_panic(export_graph(
1720 &nodes,
1721 &[],
1722 &[],
1723 &ExportRequest {
1724 max_nodes: 1,
1725 ..ExportRequest::default()
1726 },
1727 ));
1728
1729 assert!(report.truncated && report.exported_nodes == 1);
1730 }
1731
1732 #[test]
1733 fn export_applies_edge_bound() {
1734 let nodes = vec![
1735 node("node:a", NodeKind::HttpOperation, "a"),
1736 node("node:b", NodeKind::HttpOperation, "b"),
1737 ];
1738 let edges = vec![
1739 edge("edge:1", "node:a", "node:b", &[]),
1740 edge("edge:2", "node:b", "node:a", &[]),
1741 ];
1742 let report = export_or_panic(export_graph(
1743 &nodes,
1744 &edges,
1745 &[],
1746 &ExportRequest {
1747 max_edges: 1,
1748 ..ExportRequest::default()
1749 },
1750 ));
1751
1752 assert!(report.truncated && report.exported_edges == 1);
1753 }
1754
1755 #[test]
1756 fn graphml_escapes_xml_text() {
1757 let nodes = vec![node(
1758 "node:<a>&\"'",
1759 NodeKind::HttpOperation,
1760 "<script>&\"'",
1761 )];
1762 let report = export_or_panic(export_graph(
1763 &nodes,
1764 &[],
1765 &[],
1766 &ExportRequest {
1767 format: ExportFormat::GraphMl,
1768 ..ExportRequest::default()
1769 },
1770 ));
1771
1772 assert!(
1773 report.content.contains("<script>&"'")
1774 && !report.content.contains("<script>")
1775 );
1776 }
1777
1778 #[test]
1779 fn markdown_escapes_table_and_markup_text() {
1780 let nodes = vec![node("node:a", NodeKind::HttpOperation, "a|**unsafe**\nrow")];
1781 let report = export_or_panic(export_graph(
1782 &nodes,
1783 &[],
1784 &[],
1785 &ExportRequest {
1786 format: ExportFormat::Markdown,
1787 ..ExportRequest::default()
1788 },
1789 ));
1790
1791 assert!(report.content.contains(r"a\|\*\*unsafe\*\* row"));
1792 }
1793
1794 #[test]
1795 fn export_rejects_zero_bound() {
1796 let result = export_graph(
1797 &[],
1798 &[],
1799 &[],
1800 &ExportRequest {
1801 max_nodes: 0,
1802 ..ExportRequest::default()
1803 },
1804 );
1805
1806 assert!(matches!(result, Err(InterfaceError::InvalidBound { .. })));
1807 }
1808
1809 #[test]
1810 fn export_warns_and_omits_dangling_edge() {
1811 let nodes = vec![node("node:a", NodeKind::HttpOperation, "a")];
1812 let edges = vec![edge("edge:1", "node:a", "node:missing", &[])];
1813 let report = export_or_panic(export_graph(&nodes, &edges, &[], &ExportRequest::default()));
1814
1815 assert!(report.exported_edges == 0 && !report.warnings.is_empty());
1816 }
1817
1818 #[test]
1819 fn doctor_reports_healthy_complete_input() {
1820 let report = doctor(&healthy_doctor_request());
1821
1822 assert!(report.status == DoctorStatus::Healthy && report.complete);
1823 }
1824
1825 #[test]
1826 fn doctor_failed_check_dominates_unknown() {
1827 let mut input = DoctorRequest::default();
1828 input.config.push(ConfigDoctorInput {
1829 name: "workspace".to_owned(),
1830 valid: Some(false),
1831 detail: None,
1832 });
1833 let report = doctor(&input);
1834
1835 assert_eq!(report.status, DoctorStatus::Failed);
1836 }
1837
1838 #[test]
1839 fn doctor_unknown_dominates_degraded() {
1840 let mut input = healthy_doctor_request();
1841 input.providers[0].status = ProviderDoctorStatus::Stale;
1842 input.integrity[0].passed = None;
1843 let report = doctor(&input);
1844
1845 assert_eq!(report.status, DoctorStatus::Unknown);
1846 }
1847
1848 #[test]
1849 fn doctor_partial_freshness_is_unknown() {
1850 let mut input = healthy_doctor_request();
1851 input.freshness[0].state = RepoFreshnessState::Partial;
1852 let report = doctor(&input);
1853
1854 assert_eq!(report.status, DoctorStatus::Unknown);
1855 }
1856
1857 #[test]
1858 fn doctor_missing_categories_are_unknown() {
1859 let report = doctor(&DoctorRequest::default());
1860
1861 assert!(report.status == DoctorStatus::Unknown && report.unknown_checks == 5);
1862 }
1863
1864 #[test]
1865 fn doctor_check_order_is_deterministic() {
1866 let mut first_input = healthy_doctor_request();
1867 first_input.config.push(ConfigDoctorInput {
1868 name: "alpha".to_owned(),
1869 valid: Some(true),
1870 detail: None,
1871 });
1872 let mut second_input = first_input.clone();
1873 second_input.config.reverse();
1874 let first = doctor(&first_input);
1875 let second = doctor(&second_input);
1876
1877 assert_eq!(first, second);
1878 }
1879
1880 #[test]
1881 fn schema_catalog_is_deterministic() {
1882 let first = public_schema_catalog();
1883 let second = public_schema_catalog();
1884
1885 assert_eq!(first, second);
1886 }
1887
1888 #[test]
1889 fn schema_catalog_contains_core_interface_types() {
1890 let catalog = match public_schema_catalog() {
1891 Ok(catalog) => catalog,
1892 Err(error) => panic!("unexpected catalog error: {error}"),
1893 };
1894
1895 assert!(
1896 [
1897 "ContractRequest",
1898 "ContractReport",
1899 "ExportRequest",
1900 "DoctorReport"
1901 ]
1902 .iter()
1903 .all(|name| catalog.schemas.iter().any(|schema| schema.name == *name))
1904 );
1905 }
1906
1907 #[test]
1908 fn generated_request_schema_has_object_shape() {
1909 let catalog = match public_schema_catalog() {
1910 Ok(catalog) => catalog,
1911 Err(error) => panic!("unexpected catalog error: {error}"),
1912 };
1913 let request_schema = catalog
1914 .schemas
1915 .iter()
1916 .find(|schema| schema.name == "ContractRequest");
1917
1918 assert!(request_schema.is_some_and(|schema| schema.schema.get("properties").is_some()));
1919 }
1920
1921 #[test]
1922 fn pagination_has_no_duplicates_across_pages() {
1923 let items = vec![1, 2, 3, 4];
1924 let first = paginate(&items, 0, 2, summary());
1925 let second = paginate(&items, 2, 2, summary());
1926 let combined = first
1927 .ok()
1928 .into_iter()
1929 .flat_map(|page| page.items)
1930 .chain(second.ok().into_iter().flat_map(|page| page.items))
1931 .collect::<BTreeSet<_>>();
1932
1933 assert_eq!(combined, BTreeSet::from([1, 2, 3, 4]));
1934 }
1935
1936 #[test]
1937 fn pagination_reports_unknown_offset_without_panicking() {
1938 let page = match paginate(&[1, 2], 100, 10, summary()) {
1939 Ok(page) => page,
1940 Err(error) => panic!("unexpected pagination error: {error}"),
1941 };
1942
1943 assert!(page.items.is_empty() && !page.pagination.has_more);
1944 }
1945
1946 #[test]
1947 fn pagination_rejects_zero_limit() {
1948 let result = paginate(&[1], 0, 0, summary());
1949
1950 assert!(matches!(result, Err(InterfaceError::InvalidBound { .. })));
1951 }
1952
1953 #[test]
1954 fn exit_code_mapping_is_stable() {
1955 let values = [
1956 classify_exit_code(DomainErrorKind::InvalidInput).value(),
1957 classify_exit_code(DomainErrorKind::NotFound).value(),
1958 classify_exit_code(DomainErrorKind::Ambiguous).value(),
1959 classify_exit_code(DomainErrorKind::Conflict).value(),
1960 classify_exit_code(DomainErrorKind::Partial).value(),
1961 classify_exit_code(DomainErrorKind::Unavailable).value(),
1962 classify_exit_code(DomainErrorKind::Timeout).value(),
1963 classify_exit_code(DomainErrorKind::Internal).value(),
1964 classify_exit_code(DomainErrorKind::Cancelled).value(),
1965 ];
1966
1967 assert_eq!(values, [2, 3, 4, 5, 6, 7, 8, 70, 130]);
1968 }
1969
1970 #[test]
1971 fn contract_action_uses_stable_kebab_case() {
1972 assert_eq!(
1973 json_or_panic(&ContractAction::ExplainLink),
1974 "\"explain-link\""
1975 );
1976 }
1977}