Skip to main content

fallow_types/
semantic.rs

1//! Shared contracts for opt-in TypeScript semantic analysis.
2//!
3//! These types describe project-wide evidence that complements Fallow's
4//! syntactic graph. They do not model TypeScript compiler diagnostics or
5//! generic typed lint findings.
6
7use std::path::PathBuf;
8
9use serde::{Deserialize, Serialize};
10
11use crate::serde_path;
12
13/// Semantic capabilities that can share one TypeScript Program session.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
15#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
16#[serde(rename_all = "kebab-case")]
17pub enum SemanticCapability {
18    /// Confirm exact project-wide symbol use for an existing finding.
19    SymbolUse,
20    /// Explain exact declarations, references, aliases, and re-exports.
21    SymbolTrace,
22    /// Describe package-public signatures and private type leaks.
23    ApiSurface,
24    /// Find exact symbol consumers, affected files, and targeted tests.
25    SymbolImpact,
26    /// Measure project-local public-signature coupling.
27    TypeCoupling,
28}
29
30/// Effective policy applied when semantic evidence is incomplete.
31#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
32#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
33#[serde(rename_all = "kebab-case")]
34pub enum SemanticCompletenessRequirement {
35    /// Keep incomplete semantic evidence advisory.
36    #[default]
37    BestEffort,
38    /// Make incomplete semantic evidence fail the command.
39    Complete,
40}
41
42/// Whether the semantic backend answered every requested query safely.
43#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
44#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
45#[serde(rename_all = "kebab-case")]
46pub enum SemanticCompleteness {
47    /// Every requested query completed without omissions.
48    Complete,
49    /// Some evidence is valid, but bounded or unsupported relations remain.
50    Partial,
51    /// No safe semantic assertion could be made.
52    #[default]
53    Unavailable,
54}
55
56/// Analysis mode stored with baselines, snapshots, audit sides, and impact data.
57#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
58#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
59#[serde(rename_all = "kebab-case")]
60pub enum SemanticAnalysisMode {
61    /// Normal Fallow analysis with no TypeScript semantic backend.
62    #[default]
63    Syntactic,
64    /// Opt-in analysis with one or more semantic capabilities.
65    TypeAware,
66}
67
68/// Compatibility identity for comparing two analysis results.
69#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
70#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
71pub struct SemanticAnalysisIdentity {
72    /// Syntactic or type-aware analysis mode.
73    pub mode: SemanticAnalysisMode,
74    /// Version of the semantic result schema, independent of tool versions.
75    pub semantic_schema_version: u32,
76    /// Sorted capability set requested for the analysis.
77    pub capabilities: Vec<SemanticCapability>,
78    /// Hash of normalized project ownership and compiler configuration.
79    pub project_config_hash: String,
80    /// Backend family, such as `typescript-go`.
81    pub backend_family: String,
82    /// Completeness of the resulting semantic analysis.
83    pub completeness: SemanticCompleteness,
84}
85
86/// Project-config identity used only when no semantic query was needed.
87///
88/// A clean run has no checker evidence whose compatibility depends on a
89/// concrete TypeScript project. Stored comparisons therefore treat this value
90/// as deferred until a later run has an actual semantic candidate.
91pub const DEFERRED_PROJECT_CONFIG_HASH: &str = "deferred:no-semantic-queries";
92
93impl Default for SemanticAnalysisIdentity {
94    fn default() -> Self {
95        Self {
96            mode: SemanticAnalysisMode::Syntactic,
97            semantic_schema_version: 1,
98            capabilities: Vec::new(),
99            project_config_hash: String::new(),
100            backend_family: String::new(),
101            completeness: SemanticCompleteness::Complete,
102        }
103    }
104}
105
106impl SemanticAnalysisIdentity {
107    /// Identity used by legacy and current analyses that did not request the
108    /// optional TypeScript semantic backend.
109    #[must_use]
110    pub fn syntactic() -> Self {
111        Self::default()
112    }
113
114    /// Name the compatibility fields that differ between two stored results.
115    /// Tool, package, protocol, and exact backend versions are provenance and
116    /// therefore intentionally excluded.
117    #[must_use]
118    pub fn incompatible_fields(&self, other: &Self) -> Vec<&'static str> {
119        let mut fields = Vec::new();
120        if self.mode != other.mode {
121            fields.push("mode");
122        }
123        if self.semantic_schema_version != other.semantic_schema_version {
124            fields.push("semantic_schema_version");
125        }
126        if self.capabilities != other.capabilities {
127            fields.push("capabilities");
128        }
129        let project_hash_deferred = self.project_config_hash == DEFERRED_PROJECT_CONFIG_HASH
130            || other.project_config_hash == DEFERRED_PROJECT_CONFIG_HASH;
131        if !project_hash_deferred && self.project_config_hash != other.project_config_hash {
132            fields.push("project_config_hash");
133        }
134        if self.backend_family != other.backend_family {
135            fields.push("backend_family");
136        }
137        if self.completeness != other.completeness {
138            fields.push("completeness");
139        }
140        fields
141    }
142}
143
144/// Value or type namespace for one exact declaration or reference.
145#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
146#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
147#[serde(rename_all = "kebab-case")]
148pub enum SemanticNamespace {
149    /// Runtime value namespace.
150    #[default]
151    Value,
152    /// Type-only namespace.
153    Type,
154}
155
156/// Stable identity for a declaration sent to or returned by the backend.
157#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
158#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
159pub struct SemanticSymbol {
160    /// Project-root-relative declaration path.
161    #[serde(serialize_with = "serde_path::serialize")]
162    pub path: PathBuf,
163    /// Value or type namespace.
164    pub namespace: SemanticNamespace,
165    /// Stable declaration kind, such as `function` or `class-method`.
166    pub declaration_kind: String,
167    /// Name exposed to consumers.
168    pub exported_name: String,
169    /// Local declaration name.
170    pub local_name: String,
171    /// Optional owning class or namespace.
172    #[serde(default, skip_serializing_if = "Option::is_none")]
173    pub owner: Option<String>,
174    /// One-based declaration line.
175    pub line: u32,
176    /// Zero-based UTF-8 byte column.
177    pub col: u32,
178}
179
180/// One project-root-relative source location used as semantic evidence.
181#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
182#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
183pub struct SemanticSourceLocation {
184    /// Project-root-relative source path.
185    #[serde(serialize_with = "serde_path::serialize")]
186    pub path: PathBuf,
187    /// One-based source line.
188    pub line: u32,
189    /// Zero-based UTF-8 byte column.
190    pub col: u32,
191}
192
193/// Stable reason why semantic evidence is partial or unavailable.
194#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
195#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
196#[serde(rename_all = "kebab-case")]
197pub enum SemanticGapReason {
198    /// No selected TypeScript project owns the target.
199    NoProject,
200    /// More than one owning project produced incompatible declaration evidence.
201    AmbiguousProject,
202    /// Structural diagnostics make the selected project unsafe to query.
203    BlockingDiagnostics,
204    /// Named exports from a Svelte virtual module are unavailable without a
205    /// framework-aware TypeScript-Go host.
206    SvelteVirtualModuleExports,
207    /// The exact declaration could not be resolved.
208    UnknownSymbol,
209    /// A requested package-public entry point could not be resolved.
210    UnknownEntryPoint,
211    /// Evidence was truncated at the configured limit.
212    EvidenceLimit,
213    /// Dynamic runtime behavior is outside checker-visible semantics.
214    DynamicBehavior,
215    /// Interface, inherited, or virtual dispatch may reach an implementation
216    /// without referencing that concrete method symbol.
217    VirtualDispatch,
218    /// A computed or reflective member access can address the declaration.
219    DynamicMemberAccess,
220    /// A decorator can consume the declaration outside normal references.
221    DecoratedDeclaration,
222    /// An optional interface or inherited contract makes deletion unsafe.
223    OptionalContract,
224    /// A getter or setter has a paired accessor that must be changed atomically.
225    AccessorPair,
226    /// The declaration participates in a method overload set.
227    OverloadSet,
228    /// Source comments are attached to the declaration and must be reviewed.
229    AttachedComment,
230    /// The candidate itself declares an abstract contract.
231    AbstractDeclaration,
232    /// Not every project that owns the declaration completed the query.
233    IncompleteProjectCoverage,
234    /// An external framework declaration could not be attributed to an exact
235    /// package.
236    FrameworkContractProvenance,
237    /// A configured request or response capacity was reached.
238    Capacity,
239    /// The requested syntax or declaration kind is unsupported.
240    UnsupportedSyntax,
241}
242
243/// Counted omission attached to a partial or unavailable result.
244#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
245#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
246pub struct SemanticOmission {
247    /// Stable omission reason.
248    pub reason_code: SemanticGapReason,
249    /// Number of omitted items or relations.
250    pub count: usize,
251}
252
253/// Conservative outcome for one existing Fallow dead-code candidate.
254#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
255#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
256#[serde(rename_all = "kebab-case")]
257pub enum SemanticCandidateDecisionKind {
258    /// The checker resolved at least one exact static reference.
259    ConfirmedUsed,
260    /// Removing the declaration would change inherited behavior or an implemented contract.
261    ContractPreserved,
262    /// Complete closed-world analysis found no checker-resolved references.
263    ConfirmedNoStaticReferences,
264    /// Analysis deliberately declined a closed-world assertion.
265    RetainedAbstained,
266    /// The exact declaration or owning project could not be resolved.
267    RetainedUnresolved,
268}
269
270/// How a class member participates in an inherited or implemented relation.
271#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
272#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
273#[serde(rename_all = "kebab-case")]
274pub enum SemanticContractRelation {
275    /// A required member declared by an implemented interface.
276    InterfaceImplementation,
277    /// An abstract base member implemented by the candidate.
278    AbstractImplementation,
279    /// A concrete inherited member overridden by the candidate.
280    Override,
281    /// An optional inherited or interface member that still blocks auto-fix.
282    OptionalContract,
283    /// An optional member of an interface or base class that a dependency or
284    /// the platform declares. Code of the dependency can call it as a hook,
285    /// so the contract keeps the declaration.
286    DependencyHook,
287}
288
289/// Exact declaration evidence for an inherited or implemented class-member relation.
290#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
291#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
292pub struct SemanticContractEvidence {
293    /// Contract relation that makes deletion unsafe.
294    pub relation: SemanticContractRelation,
295    /// Exact interface or base-class declaration.
296    pub declaration: SemanticSymbol,
297    /// Whether the source contract marks this member optional.
298    pub optional: bool,
299}
300
301/// Heritage relation used by a framework-owned class-member contract.
302#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
303#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
304#[serde(rename_all = "kebab-case")]
305pub enum SemanticFrameworkRelation {
306    /// The class extends a framework base class.
307    Extends,
308    /// The class implements a framework interface.
309    Implements,
310}
311
312/// Exact framework contract supplied by a detected Fallow plugin.
313#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
314#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
315pub struct SemanticFrameworkContract {
316    /// Fallow plugin that supplied the contract.
317    pub framework: String,
318    /// Package that must own the resolved heritage declaration.
319    pub package: String,
320    /// Exported base class or interface name.
321    pub heritage_symbol: String,
322    /// Syntactic spellings accepted only for surfacing a latent candidate.
323    pub heritage_names: Vec<String>,
324    /// Extends or implements relation.
325    pub relation: SemanticFrameworkRelation,
326    /// Framework-dispatched members covered by this contract.
327    pub members: Vec<String>,
328}
329
330/// Checker-validated evidence that a framework contract preserves a member.
331#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
332#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
333pub struct SemanticFrameworkContractEvidence {
334    /// Fallow plugin that supplied the contract.
335    pub framework: String,
336    /// Exact package that owns the heritage declaration.
337    pub package: String,
338    /// Extends or implements relation.
339    pub relation: SemanticFrameworkRelation,
340    /// Exact framework base class or interface declaration.
341    pub declaration: SemanticSymbol,
342}
343
344/// Exact source span and content hash used to guard semantic source edits.
345#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
346#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
347pub struct SemanticEditGuard {
348    /// Zero-based UTF-8 byte offset where the declaration starts.
349    pub start: usize,
350    /// Exclusive zero-based UTF-8 byte offset where the declaration ends.
351    pub end: usize,
352    /// Lowercase SHA-256 digest of the exact declaration text.
353    pub declaration_sha256: String,
354}
355
356/// Bounded, inspectable decision record for one semantic dead-code candidate.
357#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
358#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
359pub struct SemanticCandidateDecision {
360    /// Query identifier used to correlate low-level query metadata.
361    pub query_id: usize,
362    /// Exact candidate declaration.
363    pub subject: SemanticSymbol,
364    /// Conservative Fallow-owned decision.
365    pub decision: SemanticCandidateDecisionKind,
366    /// Completeness of the supporting semantic evidence.
367    pub status: SemanticCompleteness,
368    /// Every selected TypeScript project that owns the declaration.
369    pub owning_projects: Vec<String>,
370    /// Bounded checker-resolved reference or uncertainty evidence.
371    #[serde(default, skip_serializing_if = "Vec::is_empty")]
372    pub evidence: Vec<SemanticReference>,
373    /// Inherited contract evidence, when present.
374    #[serde(default, skip_serializing_if = "Option::is_none")]
375    pub contract: Option<SemanticContractEvidence>,
376    /// Framework-owned contract evidence, distinct from TypeScript contracts.
377    #[serde(default, skip_serializing_if = "Option::is_none")]
378    pub framework_contract: Option<SemanticFrameworkContractEvidence>,
379    /// Whether this exact decision may enable a guarded class-member fix.
380    pub closed_world_eligible: bool,
381    /// Exact declaration guard required before a source edit.
382    #[serde(default, skip_serializing_if = "Option::is_none")]
383    pub edit_guard: Option<SemanticEditGuard>,
384    /// Primary reason when the candidate remains unresolved or abstained.
385    #[serde(default, skip_serializing_if = "Option::is_none")]
386    pub reason_code: Option<SemanticGapReason>,
387    /// Concise explanation suitable for dry-run and agent output.
388    pub explanation: String,
389    /// Plain next actions.
390    #[serde(default, skip_serializing_if = "Vec::is_empty")]
391    pub actions: Vec<String>,
392    /// Evidence count before bounding.
393    pub total_evidence_count: usize,
394    /// Whether evidence was truncated.
395    pub truncated: bool,
396    /// Counted omissions.
397    #[serde(default, skip_serializing_if = "Vec::is_empty")]
398    pub omissions: Vec<SemanticOmission>,
399}
400
401/// Compact per-query status embedded in run metadata.
402#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
403#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
404pub struct SemanticQuerySummary {
405    /// Stable query identifier within this analysis run.
406    pub query_id: usize,
407    /// Capability that answered the query.
408    pub capability: SemanticCapability,
409    /// Operation-specific assertion, never a generic compiler verdict.
410    pub assertion: String,
411    /// Completeness of this query.
412    pub status: SemanticCompleteness,
413    /// Stable primary gap reason when partial or unavailable.
414    #[serde(default, skip_serializing_if = "Option::is_none")]
415    pub reason_code: Option<SemanticGapReason>,
416    /// Evidence count before bounding.
417    pub total_evidence_count: usize,
418    /// Whether evidence or payload arrays were truncated.
419    pub truncated: bool,
420    /// Counted omissions.
421    #[serde(default, skip_serializing_if = "Vec::is_empty")]
422    pub omissions: Vec<SemanticOmission>,
423    /// Plain next actions.
424    #[serde(default, skip_serializing_if = "Vec::is_empty")]
425    pub actions: Vec<String>,
426}
427
428/// Located semantic reference evidence.
429#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
430#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
431pub struct SemanticReference {
432    /// Project-root-relative reference path.
433    #[serde(serialize_with = "serde_path::serialize")]
434    pub path: PathBuf,
435    /// One-based source line.
436    pub line: u32,
437    /// Zero-based UTF-8 byte column.
438    pub col: u32,
439    /// Reference role, such as `read`, `type`, `alias`, or `re-export`.
440    pub role: String,
441    /// Value or type namespace used at this location.
442    pub namespace: SemanticNamespace,
443    /// Alias and re-export hops between the reference and declaration.
444    #[serde(default, skip_serializing_if = "Vec::is_empty")]
445    pub via: Vec<SemanticAliasHop>,
446}
447
448/// One alias or re-export hop in semantic provenance.
449#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
450#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
451pub struct SemanticAliasHop {
452    /// Project-root-relative hop path.
453    #[serde(serialize_with = "serde_path::serialize")]
454    pub path: PathBuf,
455    /// Name before this hop.
456    pub from_name: String,
457    /// Name exposed after this hop.
458    pub to_name: String,
459    /// Relation, such as `import-alias` or `re-export`.
460    pub relation: String,
461}
462
463/// Typed semantic trace attached to an existing syntactic trace.
464#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
465#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
466pub struct SemanticSymbolTrace {
467    /// Exact target declaration.
468    pub target: SemanticSymbol,
469    /// Semantic mode, capabilities, project selection, and completeness.
470    pub identity: SemanticAnalysisIdentity,
471    /// TypeScript project selected for this symbol.
472    pub selected_project: String,
473    /// Concrete assertion, such as `references-found`.
474    pub assertion: String,
475    /// Completeness of the trace.
476    pub status: SemanticCompleteness,
477    /// Bounded reference evidence.
478    pub references: Vec<SemanticReference>,
479    /// Count before evidence bounding.
480    pub total_reference_count: usize,
481    /// Exact reference locations found by the TypeScript checker.
482    pub checker_evidence_count: usize,
483    /// Alias and re-export hops derived from the semantic graph.
484    pub graph_evidence_count: usize,
485    /// Whether reference evidence was truncated.
486    pub truncated: bool,
487    /// Counted omissions.
488    #[serde(default, skip_serializing_if = "Vec::is_empty")]
489    pub omissions: Vec<SemanticOmission>,
490    /// Plain next actions for a user or automation consumer.
491    #[serde(default, skip_serializing_if = "Vec::is_empty")]
492    pub actions: Vec<String>,
493}
494
495/// One project-local type referenced by a public signature.
496#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
497#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
498pub struct PublicTypeReference {
499    /// Referenced declaration.
500    pub declaration: SemanticSymbol,
501    /// Signature relation, such as return type or generic constraint.
502    pub relation: String,
503}
504
505/// One package-public API entry described by the semantic backend.
506#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
507#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
508pub struct ApiSurfaceEntry {
509    /// Symbol exposed through a package entry point.
510    pub exposed: SemanticSymbol,
511    /// Canonical origin after aliases and re-exports.
512    pub origin: SemanticSymbol,
513    /// Stable normalized signature fingerprint.
514    pub signature_fingerprint: String,
515    /// Project-local types referenced by the signature.
516    pub referenced_types: Vec<PublicTypeReference>,
517}
518
519/// Exact semantic evidence for a private type leak.
520#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
521#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
522pub struct SemanticPrivateTypeLeak {
523    /// Public symbol whose signature exposes the type.
524    pub exposed: SemanticSymbol,
525    /// Project-local declaration that is not package-public.
526    pub private_declaration: SemanticSymbol,
527    /// Signature relation through which the type is exposed.
528    pub relation: String,
529    /// Stable TypeScript diagnostic code used as supporting evidence.
530    #[serde(default, skip_serializing_if = "Option::is_none")]
531    pub diagnostic_code: Option<u32>,
532}
533
534/// Package API surface result shared by inspect and private-leak analysis.
535#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
536#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
537pub struct ApiSurfaceResult {
538    /// Concrete assertion, such as `leak-confirmed`.
539    pub assertion: String,
540    /// Completeness of package-public traversal.
541    pub status: SemanticCompleteness,
542    /// Public API entries.
543    pub entries: Vec<ApiSurfaceEntry>,
544    /// Confirmed private type leaks.
545    pub private_type_leaks: Vec<SemanticPrivateTypeLeak>,
546    /// Counted omissions.
547    #[serde(default, skip_serializing_if = "Vec::is_empty")]
548    pub omissions: Vec<SemanticOmission>,
549    /// Plain next actions.
550    #[serde(default, skip_serializing_if = "Vec::is_empty")]
551    pub actions: Vec<String>,
552}
553
554/// One production file or test reached by exact-symbol impact analysis.
555#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
556#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
557pub struct SemanticImpactPath {
558    /// Project-root-relative affected path.
559    #[serde(serialize_with = "serde_path::serialize")]
560    pub path: PathBuf,
561    /// Relation to the target, such as `direct-value-consumer`.
562    pub relation: String,
563    /// Shortest graph distance from the target.
564    pub distance: usize,
565    /// Located provenance path.
566    #[serde(default, skip_serializing_if = "Vec::is_empty")]
567    #[serde(serialize_with = "serde_path::serialize_vec")]
568    pub via: Vec<PathBuf>,
569}
570
571/// Confidence of exact-symbol impact analysis after known dynamic gaps.
572#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
573#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
574#[serde(rename_all = "kebab-case")]
575pub enum SemanticImpactConfidence {
576    /// All reported static paths are complete within the selected project
577    /// scope.
578    High,
579    /// Static paths are useful, but virtual dispatch or dynamic behavior
580    /// bounds completeness.
581    Bounded,
582    /// Impact analysis could not run.
583    Unavailable,
584}
585
586impl std::fmt::Display for SemanticImpactConfidence {
587    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
588        formatter.write_str(match self {
589            Self::High => "high",
590            Self::Bounded => "bounded",
591            Self::Unavailable => "unavailable",
592        })
593    }
594}
595
596/// Exact-symbol impact and targeted-test recommendation.
597#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
598#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
599pub struct SemanticSymbolImpact {
600    /// Exact target declaration.
601    pub target: SemanticSymbol,
602    /// Semantic mode, capabilities, project selection, and completeness.
603    pub identity: SemanticAnalysisIdentity,
604    /// TypeScript project selected for this symbol.
605    pub selected_project: String,
606    /// Concrete assertion, such as `consumers-found`.
607    pub assertion: String,
608    /// Completeness of impact analysis.
609    pub status: SemanticCompleteness,
610    /// Files that reference the exact symbol directly.
611    pub direct_consumers: Vec<SemanticImpactPath>,
612    /// Direct consumer count before evidence bounding.
613    pub total_direct_consumer_count: usize,
614    /// Transitively affected production files.
615    pub affected_files: Vec<SemanticImpactPath>,
616    /// Transitive affected-file count before evidence bounding.
617    pub total_affected_file_count: usize,
618    /// Directly relevant test entry points.
619    pub targeted_tests: Vec<SemanticImpactPath>,
620    /// Targeted-test count before evidence bounding.
621    pub total_targeted_test_count: usize,
622    /// Confidence after accounting for dynamic behavior.
623    pub confidence: SemanticImpactConfidence,
624    /// Counted omissions, including dynamic behavior.
625    #[serde(default, skip_serializing_if = "Vec::is_empty")]
626    pub omissions: Vec<SemanticOmission>,
627    /// Plain next actions.
628    #[serde(default, skip_serializing_if = "Vec::is_empty")]
629    pub actions: Vec<String>,
630}
631
632/// One project-local public-signature type edge.
633#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
634#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
635pub struct TypeCouplingEdge {
636    /// Public API declaration that owns the signature.
637    pub source: SemanticSymbol,
638    /// Project-local type used by that signature.
639    pub target: SemanticSymbol,
640    /// Signature relation.
641    pub relation: String,
642    /// Source location where the public signature references the target type.
643    pub evidence: SemanticSourceLocation,
644    /// Scope, such as `module-export` or `package-public`.
645    pub scope: String,
646}
647
648/// Per-file project-local public-signature coupling.
649#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
650#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
651pub struct TypeCouplingFile {
652    /// Project-root-relative file path.
653    #[serde(serialize_with = "serde_path::serialize")]
654    pub path: PathBuf,
655    /// Distinct files this file's public API depends on.
656    pub public_api_depends_on: usize,
657    /// Located project files this file's public API depends on.
658    #[serde(default, skip_serializing_if = "Vec::is_empty")]
659    #[serde(serialize_with = "serde_path::serialize_vec")]
660    pub public_api_depends_on_files: Vec<PathBuf>,
661    /// Distinct files whose public types use this file.
662    pub public_types_used_by: usize,
663    /// Located project files whose public types use this file.
664    #[serde(default, skip_serializing_if = "Vec::is_empty")]
665    #[serde(serialize_with = "serde_path::serialize_vec")]
666    pub public_types_used_by_files: Vec<PathBuf>,
667    /// Located public-signature edges.
668    pub edges: Vec<TypeCouplingEdge>,
669}
670
671/// One project-local cycle through public-signature type dependencies.
672#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
673#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
674pub struct TypeCouplingCycle {
675    /// Ordered project-root-relative files, ending at the start file.
676    #[serde(serialize_with = "serde_path::serialize_vec")]
677    pub files: Vec<PathBuf>,
678}
679
680/// Project summary for advisory type coupling.
681#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
682#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
683pub struct TypeCouplingSummary {
684    /// Measurement boundary, currently project-local public signatures.
685    pub scope: String,
686    /// Edge direction, currently directed.
687    pub direction: String,
688    /// Distinct project files in the selected TypeScript projects.
689    pub project_size: usize,
690    /// Distinct project files included in the denominator.
691    pub files_analyzed: usize,
692    /// Files participating in at least one project-local type edge.
693    pub distinct_coupled_files: usize,
694    /// Project-local public-signature edge count before evidence bounding.
695    pub edge_count: usize,
696    /// Percentage of analyzed files participating in a type edge.
697    pub coupled_file_pct: f64,
698    /// Median distinct-file type connections.
699    pub p50_distinct_connections: f64,
700    /// P90 distinct-file type connections.
701    pub p90_distinct_connections: f64,
702    /// P95 incoming distinct-file type coupling.
703    pub p95_public_types_used_by: f64,
704    /// P95 outgoing distinct-file type coupling.
705    pub p95_public_api_depends_on: f64,
706    /// Percentage of files above the adaptive high-coupling threshold.
707    pub high_coupling_pct: f64,
708    /// Share of edge endpoints represented by the top contributors.
709    pub concentration: f64,
710    /// Number of project-local public-signature cycles.
711    pub cycle_count: usize,
712}
713
714/// Advisory project-local public-signature coupling report.
715#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
716#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
717pub struct TypeCouplingReport {
718    /// Semantic mode, capability, project selection, and completeness.
719    pub identity: SemanticAnalysisIdentity,
720    /// Concrete assertion, such as `coupling-found`.
721    pub assertion: String,
722    /// Completeness of coupling traversal.
723    pub status: SemanticCompleteness,
724    /// Project summary. Absent when analysis is unavailable, never a fake zero.
725    #[serde(default, skip_serializing_if = "Option::is_none")]
726    pub summary: Option<TypeCouplingSummary>,
727    /// Per-file coupling details.
728    pub files: Vec<TypeCouplingFile>,
729    /// Highest-degree files contributing to project coupling.
730    #[serde(default, skip_serializing_if = "Vec::is_empty")]
731    pub top_contributors: Vec<TypeCouplingFile>,
732    /// Located project-local type cycles.
733    #[serde(default, skip_serializing_if = "Vec::is_empty")]
734    pub cycles: Vec<TypeCouplingCycle>,
735    /// Counted omissions.
736    #[serde(default, skip_serializing_if = "Vec::is_empty")]
737    pub omissions: Vec<SemanticOmission>,
738    /// Plain next actions.
739    #[serde(default, skip_serializing_if = "Vec::is_empty")]
740    pub actions: Vec<String>,
741}
742
743#[cfg(test)]
744mod tests {
745    use super::*;
746
747    #[test]
748    fn semantic_identity_reports_each_compatibility_dimension() {
749        let syntactic = SemanticAnalysisIdentity::syntactic();
750        assert!(syntactic.incompatible_fields(&syntactic).is_empty());
751
752        let type_aware = SemanticAnalysisIdentity {
753            mode: SemanticAnalysisMode::TypeAware,
754            semantic_schema_version: 2,
755            capabilities: vec![SemanticCapability::SymbolUse],
756            project_config_hash: "sha256:project".to_string(),
757            backend_family: "typescript-go".to_string(),
758            completeness: SemanticCompleteness::Partial,
759        };
760        assert_eq!(
761            syntactic.incompatible_fields(&type_aware),
762            vec![
763                "mode",
764                "semantic_schema_version",
765                "capabilities",
766                "project_config_hash",
767                "backend_family",
768                "completeness",
769            ]
770        );
771
772        let mut deferred = type_aware.clone();
773        deferred.project_config_hash = DEFERRED_PROJECT_CONFIG_HASH.to_string();
774        assert!(
775            deferred
776                .incompatible_fields(&type_aware)
777                .iter()
778                .all(|field| *field != "project_config_hash")
779        );
780    }
781}