code_system_graph_model/lib.rs
1//! Stable domain contracts for `Code System Graph`'s federated boundary graph.
2
3use schemars::JsonSchema;
4use semver::Version;
5use serde::{Deserialize, Serialize};
6
7macro_rules! string_id {
8 ($name:ident, $description:literal) => {
9 #[doc = $description]
10 #[derive(
11 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
12 )]
13 #[serde(transparent)]
14 pub struct $name(pub String);
15
16 impl $name {
17 /// Creates an identifier from its canonical representation.
18 #[must_use]
19 pub fn new(value: impl Into<String>) -> Self {
20 Self(value.into())
21 }
22
23 /// Returns the canonical string representation.
24 #[must_use]
25 pub fn as_str(&self) -> &str {
26 &self.0
27 }
28 }
29 };
30}
31
32string_id!(RepoId, "Stable identifier for a registered repository.");
33string_id!(
34 CheckoutId,
35 "Stable identifier for one repository checkout or linked worktree."
36);
37string_id!(
38 WorkspaceId,
39 "Stable identifier for a `Code System Graph` workspace."
40);
41string_id!(NodeId, "Stable identifier for a federated graph node.");
42string_id!(EdgeId, "Stable identifier for a federated graph edge.");
43string_id!(EvidenceId, "Stable identifier for an evidence record.");
44string_id!(
45 CommunityId,
46 "Stable identifier for a detected graph community."
47);
48
49/// Lossless platform encoding used for a native filesystem path.
50#[derive(
51 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
52)]
53#[serde(rename_all = "snake_case")]
54pub enum NativePathEncoding {
55 /// Raw Unix `OsStr` bytes.
56 UnixBytes,
57 /// Little-endian Windows UTF-16 code units.
58 WindowsWide,
59 /// UTF-8 fallback for other targets.
60 Utf8,
61}
62
63/// Lossless native path plus a diagnostic-only display form.
64#[derive(
65 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
66)]
67pub struct NativePath {
68 /// Platform-specific lossless encoding.
69 pub encoding: NativePathEncoding,
70 /// Encoded path bytes; these are not assumed to be UTF-8.
71 pub bytes: Vec<u8>,
72 /// Lossy display form intended only for diagnostics.
73 pub display: String,
74}
75
76/// Deterministic identity and checkout metadata for one registered repository.
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
78pub struct RepositoryRecord {
79 /// Stable repository identity shared by linked worktrees.
80 pub id: RepoId,
81 /// Stable identity of this concrete checkout.
82 pub checkout_id: CheckoutId,
83 /// Unique alias within the workspace.
84 pub alias: String,
85 /// Canonical native checkout path.
86 pub canonical_path: NativePath,
87 /// Canonical Git common directory when the checkout is a Git repository.
88 pub git_common_dir: Option<NativePath>,
89 /// Credential-free normalized remote identity when available.
90 pub normalized_remote: Option<String>,
91 /// Current Git commit when available.
92 pub head_commit: Option<String>,
93 /// Whether Git reports a linked worktree rather than the common checkout.
94 pub is_linked_worktree: bool,
95 /// Whether tracked or untracked working-tree changes were observed.
96 pub working_tree_dirty: bool,
97}
98
99/// Fully validated registry input for one workspace.
100#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
101pub struct WorkspaceRecord {
102 /// Stable workspace identity.
103 pub id: WorkspaceId,
104 /// User-facing workspace name.
105 pub name: String,
106 /// Fingerprint of the exact manifest content.
107 pub manifest_hash: String,
108 /// Canonical lossless workspace manifest path.
109 pub config_path: Option<NativePath>,
110 /// Repositories sorted by alias.
111 pub repositories: Vec<RepositoryRecord>,
112}
113
114/// Freshness state for one repository checkout.
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
116#[serde(rename_all = "snake_case")]
117pub enum RepoFreshnessState {
118 /// Current inputs match the published snapshot.
119 Fresh,
120 /// The working tree changed after the snapshot.
121 WorkingTreeChanged,
122 /// Repository commits advanced after the snapshot.
123 CommitsBehind,
124 /// Workspace or repository configuration changed.
125 ConfigChanged,
126 /// An extractor version changed.
127 ExtractorChanged,
128 /// Local `CodeGraph` freshness is pending.
129 CodegraphPending,
130 /// Only part of the required inputs were scanned.
131 Partial,
132 /// Stored state failed an integrity check.
133 Corrupt,
134 /// Freshness could not be determined.
135 Unknown,
136 /// Repository checkout is unavailable.
137 Unavailable,
138}
139
140/// Snapshot freshness recorded for one repository checkout.
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
142pub struct RepoFreshness {
143 /// Stable repository identity.
144 pub repo_id: RepoId,
145 /// Concrete checkout identity.
146 pub checkout_id: CheckoutId,
147 /// Commit observed by the snapshot.
148 pub head_commit: Option<String>,
149 /// Manifest fingerprint used by the snapshot.
150 pub manifest_hash: String,
151 /// Current freshness classification.
152 pub state: RepoFreshnessState,
153 /// Optional bounded explanation.
154 pub reason: Option<String>,
155}
156
157/// Fingerprint of one extractor-relevant artifact.
158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
159pub struct ArtifactFingerprint {
160 /// Repository containing the artifact.
161 pub repo_id: RepoId,
162 /// Concrete checkout containing the artifact.
163 pub checkout_id: CheckoutId,
164 /// Repository-relative native path.
165 pub path: NativePath,
166 /// Extractor that consumes this artifact.
167 pub extractor: String,
168 /// BLAKE3 content fingerprint.
169 pub content_hash: String,
170 /// Exact file size in bytes.
171 pub size_bytes: u64,
172}
173
174/// Incremental difference from the previous published artifact set.
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
176#[serde(rename_all = "snake_case")]
177pub enum ArtifactChangeKind {
178 /// Artifact did not exist previously.
179 Added,
180 /// Artifact content changed.
181 Modified,
182 /// Artifact is absent from the current scan.
183 Deleted,
184}
185
186/// Planned incremental action for one artifact identity.
187#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
188pub struct ArtifactChange {
189 /// Repository identity.
190 pub repo_id: RepoId,
191 /// Checkout identity.
192 pub checkout_id: CheckoutId,
193 /// Repository-relative path.
194 pub path: NativePath,
195 /// Extractor identity.
196 pub extractor: String,
197 /// Difference classification.
198 pub kind: ArtifactChangeKind,
199}
200
201/// Outcome of one extractor execution.
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
203#[serde(rename_all = "snake_case")]
204pub enum ExtractorRunStatus {
205 /// Extractor completed successfully.
206 Success,
207 /// Inputs were unchanged and reusable.
208 SkippedUnchanged,
209}
210
211/// Persisted metrics for one extractor execution or skip decision.
212#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
213pub struct ExtractorRun {
214 /// Stable run identity.
215 pub id: String,
216 /// Published snapshot identity.
217 pub snapshot_id: String,
218 /// Repository identity.
219 pub repo_id: RepoId,
220 /// Checkout identity.
221 pub checkout_id: CheckoutId,
222 /// Extractor identity.
223 pub extractor: String,
224 /// Extractor semantic version.
225 pub extractor_version: String,
226 /// Run outcome.
227 pub status: ExtractorRunStatus,
228 /// Number of discovered files.
229 pub discovered_files: u64,
230 /// Number of parsed files.
231 pub parsed_files: u64,
232 /// Number of skipped files.
233 pub skipped_files: u64,
234 /// Bounded execution time in milliseconds.
235 pub elapsed_ms: u64,
236}
237
238/// Opaque, versioned output owned by one extractor input.
239///
240/// The payload contains contract observations rather than source text. Its schema is owned by the
241/// extractor identified by [`Self::source`] and [`Self::extractor_version`].
242#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
243pub struct StoredExtractorBatch {
244 /// Fingerprint that identifies and invalidates the source-owned output.
245 pub source: ArtifactFingerprint,
246 /// Semantic version of the extractor payload schema.
247 pub extractor_version: String,
248 /// Canonical fingerprint of the effective extraction budgets.
249 pub budget_fingerprint: String,
250 /// Whether invalid UTF-8 input bytes were decoded lossily for text extraction.
251 pub source_was_lossy: bool,
252 /// Deterministic number of observations encoded in the payload.
253 pub output_count: u64,
254 /// UTF-8 JSON payload encoded as bytes for bounded, lossless persistence.
255 pub payload: Vec<u8>,
256}
257
258/// Produces a deterministic namespaced identifier from a canonical key.
259#[must_use]
260pub fn stable_id(namespace: &str, canonical_key: &str) -> String {
261 stable_id_bytes(namespace, canonical_key.as_bytes())
262}
263
264/// Produces a deterministic namespaced identifier from arbitrary canonical bytes.
265#[must_use]
266pub fn stable_id_bytes(namespace: &str, canonical_key: &[u8]) -> String {
267 let mut hasher = blake3::Hasher::new();
268 hasher.update(namespace.as_bytes());
269 hasher.update(&[0]);
270 hasher.update(canonical_key);
271 format!("{namespace}:{}", hasher.finalize().to_hex())
272}
273
274/// Reports whether untrusted metadata contains control or bidirectional formatting characters.
275///
276/// Source files may legitimately contain such characters, but identifiers, labels, paths, and
277/// diagnostic metadata must reject them before they reach durable state or terminal output.
278#[must_use]
279pub fn contains_unsafe_metadata_characters(value: &str) -> bool {
280 value.chars().any(|character| {
281 character.is_control()
282 || matches!(
283 character,
284 '\u{061c}'
285 | '\u{200e}'
286 | '\u{200f}'
287 | '\u{202a}'..='\u{202e}'
288 | '\u{2066}'..='\u{2069}'
289 | '\u{feff}'
290 )
291 })
292}
293
294/// Rejects repository-relative path display strings that are unsafe for metadata or diagnostics.
295///
296/// # Errors
297///
298/// Returns [`UnsafePathDisplayError`] when `value` contains control or bidirectional characters.
299pub fn validate_safe_path_display(value: &str) -> Result<(), UnsafePathDisplayError> {
300 if contains_unsafe_metadata_characters(value) {
301 Err(UnsafePathDisplayError)
302 } else {
303 Ok(())
304 }
305}
306
307/// Path display string contains unsafe metadata characters.
308#[derive(Debug, Clone, Copy, PartialEq, Eq)]
309pub struct UnsafePathDisplayError;
310
311impl std::fmt::Display for UnsafePathDisplayError {
312 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
313 formatter.write_str("path display contains unsafe control or bidirectional characters")
314 }
315}
316
317impl std::error::Error for UnsafePathDisplayError {}
318
319/// Kind of entity represented in the federated graph.
320#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
321#[serde(rename_all = "snake_case")]
322pub enum NodeKind {
323 /// Registered source repository.
324 Repository,
325 /// Deployable or logical service.
326 Service,
327 /// Package coordinate.
328 Package,
329 /// Boundary-defining artifact.
330 Artifact,
331 /// Lightweight reference to a repository-local symbol.
332 SymbolRef,
333 /// Executable test case in any supported language.
334 TestCase,
335 /// HTTP operation contract.
336 HttpOperation,
337 /// GraphQL operation contract.
338 GraphqlOperation,
339 /// Remote procedure call method.
340 RpcMethod,
341 /// Event topic, queue, or channel.
342 EventChannel,
343 /// Event payload schema.
344 EventSchema,
345 /// Database instance.
346 Database,
347 /// Database table.
348 DatabaseTable,
349 /// Database column.
350 DatabaseColumn,
351 /// Configuration key name.
352 ConfigKey,
353 /// Deployment unit.
354 Deployment,
355 /// Technical document.
356 Document,
357 /// Architecture decision record.
358 Adr,
359 /// Owning person or team.
360 Owner,
361 /// Local or remote change set.
362 ChangeSet,
363 /// Pull request.
364 PullRequest,
365 /// Detected graph community.
366 Community,
367}
368
369/// Kind of relationship represented in the federated graph.
370#[derive(
371 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
372)]
373#[serde(rename_all = "snake_case")]
374pub enum EdgeKind {
375 /// Parent contains child.
376 Contains,
377 /// Source provides target contract.
378 Provides,
379 /// Source consumes target contract.
380 Consumes,
381 /// Source performs a remote call to target.
382 CallsRemote,
383 /// Source publishes target event.
384 Publishes,
385 /// Source subscribes to target event.
386 Subscribes,
387 /// Event channel delivers messages to target subscriber.
388 DeliversTo,
389 /// Source depends on target package.
390 DependsOnPackage,
391 /// Source depends on target repository.
392 DependsOnRepository,
393 /// Source reads target table.
394 ReadsTable,
395 /// Source writes target table.
396 WritesTable,
397 /// Source deploys target.
398 Deploys,
399 /// Source configures target.
400 Configures,
401 /// Source documents target.
402 Documents,
403 /// Source is owned by target.
404 OwnedBy,
405 /// Source is implemented by target.
406 ImplementedBy,
407 /// Source test validates target contract or behavior.
408 Validates,
409 /// Source was changed in target.
410 ChangedIn,
411 /// Source affects target.
412 Affects,
413 /// Source migration is applied before target migration.
414 Precedes,
415 /// Source migration reverses target migration.
416 Reverts,
417 /// Source is compatible with target.
418 CompatibleWith,
419 /// Source is incompatible with target.
420 IncompatibleWith,
421 /// Source belongs to target community.
422 MemberOf,
423 /// User-declared relationship.
424 ManualLink,
425}
426
427/// Origin of a graph assertion.
428#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
429#[serde(rename_all = "snake_case")]
430pub enum Provenance {
431 /// Explicitly declared in a source artifact.
432 Declared,
433 /// Deterministically extracted from a source artifact.
434 Extracted,
435 /// Derived from incomplete or indirect signals.
436 Inferred,
437 /// Explicitly supplied by a user.
438 Manual,
439 /// Observed at runtime.
440 Runtime,
441 /// Returned through a public `CodeGraph` capability.
442 CodeGraph,
443}
444
445/// Confidence state attached to an assertion.
446#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
447#[serde(rename_all = "snake_case")]
448pub enum EpistemicStatus {
449 /// Supported by sufficient direct evidence.
450 Confirmed,
451 /// Derived from indirect evidence.
452 Inferred,
453 /// Multiple plausible interpretations remain.
454 Ambiguous,
455 /// Evidence no longer matches current inputs.
456 Stale,
457 /// Required inputs were unavailable.
458 Incomplete,
459}
460
461/// Auditable evidence supporting a node or edge.
462#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
463pub struct Evidence {
464 /// Stable evidence identifier.
465 pub id: EvidenceId,
466 /// Repository in which the evidence was observed.
467 pub repo_id: Option<RepoId>,
468 /// Repository-relative source path.
469 pub file_path: Option<String>,
470 /// Inclusive first source line.
471 pub start_line: Option<u32>,
472 /// Inclusive last source line.
473 pub end_line: Option<u32>,
474 /// Extractor identifier.
475 pub extractor: String,
476 /// Extractor semantic version.
477 pub extractor_version: String,
478 /// Origin of this evidence.
479 pub provenance: Provenance,
480 /// Normalized confidence in the inclusive range from zero to one.
481 pub confidence: f32,
482 /// Commit at which this evidence was observed.
483 pub observed_at_commit: Option<String>,
484 /// Hash of the relevant source content.
485 pub content_hash: Option<String>,
486 /// Bounded explanatory note without source or secrets.
487 pub note: Option<String>,
488}
489
490/// Entity in the federated graph.
491#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
492pub struct Node {
493 /// Stable node identifier.
494 pub id: NodeId,
495 /// Entity kind.
496 pub kind: NodeKind,
497 /// Owning repository when applicable.
498 pub repo_id: Option<RepoId>,
499 /// Versioned canonical identity key.
500 pub stable_key: String,
501 /// Human-readable label.
502 pub label: String,
503}
504
505/// Relationship in the federated graph.
506#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
507pub struct Edge {
508 /// Stable edge identifier.
509 pub id: EdgeId,
510 /// Source node.
511 pub source: NodeId,
512 /// Target node.
513 pub target: NodeId,
514 /// Relationship kind.
515 pub kind: EdgeKind,
516 /// Normalized confidence in the inclusive range from zero to one.
517 pub confidence: f32,
518 /// Epistemic state.
519 pub status: EpistemicStatus,
520 /// Evidence records supporting this relationship.
521 pub evidence: Vec<EvidenceId>,
522}
523
524/// Outcome of one auditable linker decision.
525#[derive(
526 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
527)]
528#[serde(rename_all = "snake_case")]
529pub enum LinkStatus {
530 /// The selected relationship is confirmed.
531 Confirmed,
532 /// An exact automatic relationship was removed by an explicit declaration.
533 Suppressed,
534 /// Multiple exact candidates prevented a selection.
535 Ambiguous,
536 /// The candidate was explicitly rejected.
537 Rejected,
538}
539
540/// Exact candidate considered but not selected by a linker matcher.
541#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
542#[serde(deny_unknown_fields)]
543pub struct RejectedAlternative {
544 /// Candidate node identity.
545 pub candidate: NodeId,
546 /// Normalized matcher score in the inclusive range from zero to one.
547 pub score: f32,
548 /// Deterministically ordered reasons the candidate was rejected.
549 pub reasons: Vec<String>,
550}
551
552/// Stable reference to evidence used by a linker decision.
553#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
554#[serde(deny_unknown_fields)]
555pub struct EvidenceRef {
556 /// Stable evidence identity.
557 pub id: EvidenceId,
558 /// Origin of the referenced evidence.
559 pub provenance: Provenance,
560}
561
562/// Versioned and explainable record of a linker match or suppression.
563#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
564#[serde(deny_unknown_fields)]
565pub struct LinkDecision {
566 /// Resolved source node.
567 pub source: NodeId,
568 /// Resolved target node.
569 pub target: NodeId,
570 /// Concrete relationship considered by the matcher.
571 pub relation: EdgeKind,
572 /// Stable matcher identifier.
573 pub matcher: String,
574 /// Semantic version of the matcher behavior.
575 #[schemars(with = "String")]
576 pub matcher_version: Version,
577 /// Normalized raw match score in the inclusive range from zero to one.
578 pub score: f32,
579 /// Normalized confidence in the inclusive range from zero to one.
580 pub confidence: f32,
581 /// Deterministically ordered explanations for the decision.
582 pub reasons: Vec<String>,
583 /// Deterministically ordered candidates that were not selected.
584 pub rejected_alternatives: Vec<RejectedAlternative>,
585 /// Deterministically ordered supporting evidence references.
586 pub evidence: Vec<EvidenceRef>,
587 /// Final decision state.
588 pub status: LinkStatus,
589}
590
591/// Overall freshness of data used by a result.
592#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
593#[serde(rename_all = "snake_case")]
594pub enum OverallFreshness {
595 /// All required inputs match their current fingerprints.
596 Fresh,
597 /// At least one relevant input is stale.
598 Stale,
599 /// Required inputs were only partially available.
600 Partial,
601 /// Freshness could not be established.
602 Unknown,
603}
604
605/// Aggregate freshness attached to a public result.
606#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
607pub struct FreshnessSummary {
608 /// Overall freshness classification.
609 pub overall: OverallFreshness,
610 /// Stable repository identifiers known to be stale.
611 pub stale_repositories: Vec<RepoId>,
612 /// Reasons freshness could not be fully established.
613 pub reasons: Vec<String>,
614}
615
616/// A repository-scoped extraction limitation that prevents complete dependency coverage.
617#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
618pub struct RepositoryCoverageGap {
619 /// Repository whose extracted dependency coverage is incomplete.
620 pub repo_id: RepoId,
621 /// Source-free, actionable reason for the gap.
622 pub reason: String,
623}
624
625/// Why an HTTP consumer or test call has no provider edge.
626#[derive(
627 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
628)]
629#[serde(rename_all = "snake_case")]
630pub enum HttpLinkGapReason {
631 /// No workspace provider matches the method and path within the call's scope.
632 NoProvider,
633 /// Several equally specific providers match; the candidates are listed.
634 Ambiguous,
635 /// The call names a host outside the workspace.
636 External,
637}
638
639impl HttpLinkGapReason {
640 /// Stable persisted name.
641 #[must_use]
642 pub const fn as_str(self) -> &'static str {
643 match self {
644 Self::NoProvider => "no_provider",
645 Self::Ambiguous => "ambiguous",
646 Self::External => "external",
647 }
648 }
649
650 /// Parses a persisted name.
651 #[must_use]
652 pub fn parse(value: &str) -> Option<Self> {
653 match value {
654 "no_provider" => Some(Self::NoProvider),
655 "ambiguous" => Some(Self::Ambiguous),
656 "external" => Some(Self::External),
657 _ => None,
658 }
659 }
660}
661
662/// An HTTP consumer or test call that produced no provider edge.
663#[derive(
664 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
665)]
666pub struct HttpLinkGap {
667 /// Consumer boundary or test case node.
668 pub caller: NodeId,
669 /// HTTP method of the call.
670 pub method: String,
671 /// Concrete or templated path of the call.
672 pub path: String,
673 /// Why the call has no provider edge.
674 pub reason: HttpLinkGapReason,
675 /// Equally specific providers of an ambiguous call, in stable order.
676 pub candidates: Vec<NodeId>,
677}
678
679/// Counts of HTTP consumer and test calls by link outcome.
680#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
681pub struct HttpLinkCoverage {
682 /// Calls linked to exactly one provider.
683 pub linked: u64,
684 /// Calls without a matching provider.
685 pub no_provider: u64,
686 /// Calls with several equally specific providers.
687 pub ambiguous: u64,
688 /// Calls to hosts outside the workspace, which are not coverage gaps.
689 pub external: u64,
690}
691
692/// HTTP link outcome of one published graph.
693#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
694pub struct HttpLinkReport {
695 /// Counts of calls by outcome.
696 pub coverage: HttpLinkCoverage,
697 /// Calls without a provider edge, in stable order.
698 pub gaps: Vec<HttpLinkGap>,
699}
700
701/// Status of a public tool result.
702#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
703#[serde(rename_all = "snake_case")]
704pub enum ToolStatus {
705 /// Complete result within requested bounds.
706 Ok,
707 /// Useful result with explicitly missing capabilities or inputs.
708 Degraded,
709 /// Request could not be completed.
710 Error,
711}
712
713/// One ordered segment in a federated trace.
714#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
715pub struct TraceSegment {
716 /// Source node.
717 pub source: Node,
718 /// Traversed relationship.
719 pub edge: Edge,
720 /// Target node.
721 pub target: Node,
722}
723
724/// Bounded and explainable federated trace.
725#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
726pub struct TraceReport {
727 /// Ordered trace segments.
728 pub segments: Vec<TraceSegment>,
729 /// Whether a configured bound truncated traversal.
730 pub truncated: bool,
731 /// Human-readable coverage gaps.
732 pub coverage_gaps: Vec<String>,
733}
734
735/// Community-detection algorithm selected for one reproducible analysis.
736#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
737#[serde(rename_all = "snake_case")]
738pub enum CommunityAlgorithm {
739 /// Maximal regions connected by eligible edges.
740 ConnectedComponents,
741 /// Deterministic weighted label propagation used as a conservative fallback.
742 WeightedClustering,
743 /// Deterministic seeded Louvain modularity optimization.
744 Louvain,
745}
746
747/// Scope over which communities are detected.
748#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
749#[serde(rename_all = "snake_case", tag = "kind", content = "value")]
750pub enum CommunityScope {
751 /// Entire current federated graph.
752 Federated,
753 /// Nodes owned by one repository.
754 Repository(RepoId),
755 /// Nodes associated with one exact service stable key.
756 Service(String),
757 /// Every node in the selected workspace.
758 Workspace,
759}
760
761/// Explicit weight assigned to one relationship kind during community detection.
762#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
763pub struct CommunityEdgeWeight {
764 /// Relationship kind.
765 pub kind: EdgeKind,
766 /// Finite non-negative weight.
767 pub weight: f64,
768}
769
770/// Versioned reproducibility inputs for one community analysis.
771#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
772pub struct CommunityConfig {
773 /// Selected algorithm.
774 pub algorithm: CommunityAlgorithm,
775 /// Analysis scope.
776 pub scope: CommunityScope,
777 /// Seed used to break otherwise equal deterministic choices.
778 pub seed: u64,
779 /// Positive Louvain resolution.
780 pub resolution: f64,
781 /// Minimum accepted edge confidence.
782 pub minimum_confidence: f32,
783 /// Explicit relationship weights; unspecified kinds use weight one.
784 pub edge_weights: Vec<CommunityEdgeWeight>,
785 /// Maximum optimization passes.
786 pub max_iterations: u32,
787}
788
789/// Quantitative properties of one detected community.
790#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
791pub struct CommunityMetrics {
792 /// Number of member nodes.
793 pub size: usize,
794 /// Internal edges divided by possible directed edges.
795 pub density: f64,
796 /// Internal accepted edge weight.
797 pub cohesion: f64,
798 /// Accepted edge weight crossing the community boundary.
799 pub coupling: f64,
800 /// Number of accepted cross-community edges.
801 pub cross_community_edges: usize,
802}
803
804/// Evidence explaining a deterministic community label.
805#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
806pub struct CommunityLabelEvidence {
807 /// Source node whose structure contributed a term.
808 pub node_id: NodeId,
809 /// Bounded normalized term.
810 pub term: String,
811}
812
813/// One versioned and explainable graph community.
814#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
815pub struct Community {
816 /// Stable content-derived community identity.
817 pub id: CommunityId,
818 /// Deterministic structural label.
819 pub label: String,
820 /// Sorted member node identifiers.
821 pub members: Vec<NodeId>,
822 /// Central nodes sorted by descending centrality and stable identity.
823 pub central_nodes: Vec<NodeId>,
824 /// Repository identities represented by members.
825 pub repositories: Vec<RepoId>,
826 /// Service node identities represented by members.
827 pub services: Vec<NodeId>,
828 /// Contract nodes receiving edges from outside the community.
829 pub inbound_contracts: Vec<NodeId>,
830 /// Contract nodes sending edges outside the community.
831 pub outbound_contracts: Vec<NodeId>,
832 /// Quantitative graph metrics.
833 pub metrics: CommunityMetrics,
834 /// Structural evidence used to derive the label.
835 pub label_evidence: Vec<CommunityLabelEvidence>,
836 /// Explicit limitations or incomplete inputs.
837 pub limitations: Vec<String>,
838}
839
840/// Complete community analysis tied to one immutable graph snapshot.
841#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
842pub struct CommunitySnapshot {
843 /// Graph snapshot analyzed.
844 pub snapshot_id: String,
845 /// Community engine semantic version.
846 pub engine_version: String,
847 /// Reproducibility configuration.
848 pub config: CommunityConfig,
849 /// Sorted detected communities.
850 pub communities: Vec<Community>,
851}
852
853/// Material relationship between communities in two snapshots.
854#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
855#[serde(rename_all = "snake_case")]
856pub enum CommunityChangeKind {
857 /// Community exists only in the newer snapshot.
858 Created,
859 /// Community exists only in the older snapshot.
860 Removed,
861 /// One older community materially maps to multiple newer communities.
862 Split,
863 /// Multiple older communities materially map to one newer community.
864 Merged,
865 /// Best matching community retained identity but changed materially.
866 MateriallyChanged,
867}
868
869/// Explainable community change between immutable snapshots.
870#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
871pub struct CommunityChange {
872 /// Classified change.
873 pub kind: CommunityChangeKind,
874 /// Related older community identities.
875 pub before: Vec<CommunityId>,
876 /// Related newer community identities.
877 pub after: Vec<CommunityId>,
878 /// Maximum member Jaccard overlap supporting the classification.
879 pub overlap: f64,
880 /// Bounded deterministic explanation.
881 pub explanation: String,
882}
883
884/// Community delta between two snapshots.
885#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
886pub struct CommunityDelta {
887 /// Older graph snapshot.
888 pub before_snapshot_id: String,
889 /// Newer graph snapshot.
890 pub after_snapshot_id: String,
891 /// Sorted material changes.
892 pub changes: Vec<CommunityChange>,
893}
894
895/// Versioned result envelope shared by CLI and MCP.
896#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
897pub struct ToolEnvelope<T> {
898 /// Public schema version.
899 pub schema_version: u32,
900 /// Result status.
901 pub status: ToolStatus,
902 /// Typed result data.
903 pub data: Option<T>,
904 /// Freshness of inputs used to produce the result.
905 pub freshness: FreshnessSummary,
906 /// Non-fatal warnings.
907 pub warnings: Vec<String>,
908}
909
910#[cfg(test)]
911mod tests {
912 use super::{contains_unsafe_metadata_characters, stable_id};
913
914 #[test]
915 fn stable_id_should_repeat_for_identical_input() {
916 let first = stable_id("repo", "ssh://example.test/team/api");
917 let second = stable_id("repo", "ssh://example.test/team/api");
918
919 assert_eq!(first, second);
920 }
921
922 #[test]
923 fn stable_id_should_separate_namespaces() {
924 let repository = stable_id("repo", "shared-key");
925 let service = stable_id("service", "shared-key");
926
927 assert_ne!(repository, service);
928 }
929
930 #[test]
931 fn unsafe_metadata_should_detect_terminal_and_bidi_controls() {
932 assert!(contains_unsafe_metadata_characters(
933 "trusted\u{202e}txt.exe"
934 ));
935 assert!(contains_unsafe_metadata_characters("line\nbreak"));
936 assert!(!contains_unsafe_metadata_characters(
937 "servicio-áccounts_日本"
938 ));
939 }
940}