Skip to main content

knot/models/
entity.rs

1use std::sync::Arc;
2
3use serde::{Deserialize, Serialize};
4use uuid::Uuid;
5
6use super::{ImportScope, ReferenceIntent, RelationshipType};
7
8/// Namespace UUID for knot entity generation.
9/// All entity UUIDs are derived from this namespace using UUID v5.
10/// This ensures deterministic, reproducible UUIDs across indexing runs.
11pub const NAMESPACE_KNOT: Uuid = Uuid::from_bytes([
12    0x6b, 0x6e, 0x6f, 0x74, 0x2d, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x65, 0x72, 0x2d, 0x76, 0x35, 0x00,
13]);
14
15/// The kind of code entity extracted from the AST.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(rename_all = "lowercase")]
18pub enum EntityKind {
19    Class,
20    Interface,
21    Method,
22    Function,
23    Constant,
24    Enum,
25    // Kotlin-specific entities
26    KotlinClass,           // class declarations
27    KotlinInterface,       // interface declarations
28    KotlinObject,          // object declarations (singletons)
29    KotlinCompanionObject, // companion object declarations
30    KotlinFunction,        // top-level and extension functions
31    KotlinMethod,          // methods inside classes
32    KotlinProperty,        // properties (val/var)
33    KotlinEnum,            // enum class declarations
34    // HTML/Web Components entities
35    HtmlElement, // Custom elements like <app-profile>, <web-component>
36    HtmlId,      // id="..." attributes
37    HtmlClass,   // class="..." or className="..." attributes
38    // CSS entities
39    CssClass,    // .my-class
40    CssId,       // #my-id
41    CssVariable, // --my-var (CSS Custom Properties)
42    // SCSS entities
43    ScssVariable, // $my-var
44    ScssMixin,    // @mixin my-mixin()
45    ScssFunction, // @function my-function()
46    // Rust entities
47    RustStruct,      // struct definitions
48    RustEnum,        // enum definitions
49    RustUnion,       // union definitions
50    RustTrait,       // trait definitions
51    RustImpl,        // impl blocks (inherent and trait)
52    RustFunction,    // top-level functions
53    RustMethod,      // methods inside impl blocks
54    RustMacroDef,    // macro_rules! definitions
55    RustTypeAlias,   // type aliases
56    RustConstant,    // const definitions
57    RustStatic,      // static variable definitions
58    RustModule,      // module declarations
59    RustMacroInvoke, // macro invocations
60    // Python entities
61    PythonClass,    // class definitions
62    PythonFunction, // top-level functions
63    PythonMethod,   // methods inside classes
64    PythonModule,   // module-level entities (docstrings, constants)
65    PythonConstant, // module-level constants (UPPER_CASE)
66    // C/C++ entities
67    CStruct,         // struct definitions
68    CFunction,       // top-level functions
69    CppClass,        // class definitions
70    CppMethod,       // methods inside classes
71    CppNamespace,    // namespace definitions
72    MacroDefinition, // #define macros
73    // C# entities
74    CSharpClass,         // class declarations
75    CSharpInterface,     // interface declarations
76    CSharpStruct,        // struct declarations
77    CSharpRecord,        // record class / record struct declarations
78    CSharpEnum,          // enum declarations
79    CSharpMethod,        // methods inside types
80    CSharpConstructor,   // constructor declarations
81    CSharpProperty,      // property declarations (get/set/init)
82    CSharpField,         // field declarations
83    CSharpConstant,      // const fields
84    CSharpDelegate,      // delegate declarations
85    CSharpEvent,         // event / event field declarations
86    CSharpIndexer,       // this[...] indexer declarations
87    CSharpOperator,      // operator overloads
88    CSharpNamespace,     // namespace declarations (block + file-scoped)
89    CSharpLocalFunction, // local functions inside method bodies
90    // Build Systems & CI/CD entities
91    BuildDependency, // Maven/Gradle dependency (groupId:artifactId:version)
92    BuildPlugin,     // Maven/Gradle build plugin
93    BuildTask,       // Gradle task definition
94    PipelineStage,   // Jenkins pipeline stage
95    PipelineStep,    // Jenkins pipeline step inside a stage
96    // Groovy specific entities (beyond build scripts)
97    GroovyClass,     // class declarations
98    GroovyInterface, // interface declarations
99    GroovyTrait,     // trait declarations
100    GroovyMethod,    // methods inside classes/traits
101    GroovyFunction,  // top-level methods/closures in scripts
102    GroovyEnum,      // enum declarations
103    GroovyProperty,  // fields/variables
104    // Cargo (Rust build system)
105    CargoPackage,    // [package] metadata (name, version, edition)
106    CargoFeature,    // [features] flag definitions
107    WorkspaceMember, // [workspace.members] entries
108    // Configuration entities
109    ConfigProperty, // key=value leaf in .properties, YAML, or JSON config files
110    // Kubernetes entities
111    K8sDeployment, // kind: Deployment
112    K8sService,    // kind: Service
113    K8sConfigMap,  // kind: ConfigMap
114    K8sSecret,     // kind: Secret
115    K8sIngress,    // kind: Ingress
116    K8sNamespace,  // kind: Namespace
117    K8sResource,   // Catch-all for other K8s kinds
118    // Helm entities
119    HelmChart,       // Chart.yaml metadata
120    HelmValue,       // values.yaml key-value pairs
121    HelmTemplateVar, // {{ .Values.x }} template variable usage
122    // Cross-repo linking
123    ProjectIdentity, // Build file project declaration (Maven GAV, Cargo package, npm name)
124    // Varnish VCL entities
125    VclVersion,        // vcl 4.1;
126    VclSubroutine,     // sub my_helper { }
127    VclBuiltinSub,     // sub vcl_recv { }   (multi-part)
128    VclBackend,        // backend default { }
129    VclProbe,          // probe healthcheck { }
130    VclAcl,            // acl localnetwork { }
131    VclImport,         // import std;  /  import std as s;
132    VclObjectInstance, // new cluster = directors.round_robin();
133    // Varnish VTC entities
134    VtcTestCase,        // varnishtest "..." / vtest "..."
135    VtcServer,          // server s1 { }
136    VtcClient,          // client c1 { }
137    VtcVarnishInstance, // varnish v1 { }
138    VtcLogexpect,       // logexpect l1 { }
139    VtcBarrier,         // barrier b1 cond 2
140    // Varnish VCC entities
141    VccModule,   // $Module cookie 3 "..."
142    VccFunction, // $Function VOID parse(STRING)
143    VccObject,   // $Object counter(STRING, INT)
144    VccMethod,   // $Method VOID .incr(INT)
145    // Markdown entities
146    MarkdownDocument, // A full Markdown file or frontmatter
147    MarkdownSection,  // A section under a Markdown heading
148    // HTTP endpoints served by JVM web frameworks (JAX-RS, Spring MVC)
149    HttpEndpoint, // GET /items/{id}
150    // HTTP calls made by declarative JVM clients (OpenFeign, MicroProfile, @HttpExchange)
151    HttpClientCall, // GET /api/items/{id}
152}
153
154const KIND_LABELS: &[(EntityKind, &str)] = &[
155    (EntityKind::Class, "class"),
156    (EntityKind::Interface, "interface"),
157    (EntityKind::Method, "method"),
158    (EntityKind::Function, "function"),
159    (EntityKind::Constant, "constant"),
160    (EntityKind::Enum, "enum"),
161    (EntityKind::KotlinClass, "kotlin_class"),
162    (EntityKind::KotlinInterface, "kotlin_interface"),
163    (EntityKind::KotlinObject, "kotlin_object"),
164    (EntityKind::KotlinCompanionObject, "kotlin_companion_object"),
165    (EntityKind::KotlinFunction, "kotlin_function"),
166    (EntityKind::KotlinMethod, "kotlin_method"),
167    (EntityKind::KotlinProperty, "kotlin_property"),
168    (EntityKind::KotlinEnum, "kotlin_enum"),
169    (EntityKind::HtmlElement, "html_element"),
170    (EntityKind::HtmlId, "html_id"),
171    (EntityKind::HtmlClass, "html_class"),
172    (EntityKind::CssClass, "css_class"),
173    (EntityKind::CssId, "css_id"),
174    (EntityKind::CssVariable, "css_variable"),
175    (EntityKind::ScssVariable, "scss_variable"),
176    (EntityKind::ScssMixin, "scss_mixin"),
177    (EntityKind::ScssFunction, "scss_function"),
178    (EntityKind::RustStruct, "rust_struct"),
179    (EntityKind::RustEnum, "rust_enum"),
180    (EntityKind::RustUnion, "rust_union"),
181    (EntityKind::RustTrait, "rust_trait"),
182    (EntityKind::RustImpl, "rust_impl"),
183    (EntityKind::RustFunction, "rust_function"),
184    (EntityKind::RustMethod, "rust_method"),
185    (EntityKind::RustMacroDef, "rust_macro_def"),
186    (EntityKind::RustTypeAlias, "rust_type_alias"),
187    (EntityKind::RustConstant, "rust_constant"),
188    (EntityKind::RustStatic, "rust_static"),
189    (EntityKind::RustModule, "rust_module"),
190    (EntityKind::RustMacroInvoke, "rust_macro_invoke"),
191    (EntityKind::PythonClass, "python_class"),
192    (EntityKind::PythonFunction, "python_function"),
193    (EntityKind::PythonMethod, "python_method"),
194    (EntityKind::PythonModule, "python_module"),
195    (EntityKind::PythonConstant, "python_constant"),
196    (EntityKind::BuildDependency, "build_dependency"),
197    (EntityKind::BuildPlugin, "build_plugin"),
198    (EntityKind::BuildTask, "build_task"),
199    (EntityKind::PipelineStage, "pipeline_stage"),
200    (EntityKind::PipelineStep, "pipeline_step"),
201    (EntityKind::GroovyClass, "groovy_class"),
202    (EntityKind::GroovyInterface, "groovy_interface"),
203    (EntityKind::GroovyTrait, "groovy_trait"),
204    (EntityKind::GroovyMethod, "groovy_method"),
205    (EntityKind::GroovyFunction, "groovy_function"),
206    (EntityKind::GroovyEnum, "groovy_enum"),
207    (EntityKind::GroovyProperty, "groovy_property"),
208    (EntityKind::CStruct, "c_struct"),
209    (EntityKind::CFunction, "c_function"),
210    (EntityKind::CppClass, "cpp_class"),
211    (EntityKind::CppMethod, "cpp_method"),
212    (EntityKind::CppNamespace, "cpp_namespace"),
213    (EntityKind::MacroDefinition, "macro_definition"),
214    (EntityKind::CSharpClass, "csharp_class"),
215    (EntityKind::CSharpInterface, "csharp_interface"),
216    (EntityKind::CSharpStruct, "csharp_struct"),
217    (EntityKind::CSharpRecord, "csharp_record"),
218    (EntityKind::CSharpEnum, "csharp_enum"),
219    (EntityKind::CSharpMethod, "csharp_method"),
220    (EntityKind::CSharpConstructor, "csharp_constructor"),
221    (EntityKind::CSharpProperty, "csharp_property"),
222    (EntityKind::CSharpField, "csharp_field"),
223    (EntityKind::CSharpConstant, "csharp_constant"),
224    (EntityKind::CSharpDelegate, "csharp_delegate"),
225    (EntityKind::CSharpEvent, "csharp_event"),
226    (EntityKind::CSharpIndexer, "csharp_indexer"),
227    (EntityKind::CSharpOperator, "csharp_operator"),
228    (EntityKind::CSharpNamespace, "csharp_namespace"),
229    (EntityKind::CSharpLocalFunction, "csharp_local_function"),
230    (EntityKind::CargoPackage, "cargo_package"),
231    (EntityKind::CargoFeature, "cargo_feature"),
232    (EntityKind::WorkspaceMember, "workspace_member"),
233    (EntityKind::ConfigProperty, "config_property"),
234    (EntityKind::K8sDeployment, "k8s_deployment"),
235    (EntityKind::K8sService, "k8s_service"),
236    (EntityKind::K8sConfigMap, "k8s_configmap"),
237    (EntityKind::K8sSecret, "k8s_secret"),
238    (EntityKind::K8sIngress, "k8s_ingress"),
239    (EntityKind::K8sNamespace, "k8s_namespace"),
240    (EntityKind::K8sResource, "k8s_resource"),
241    (EntityKind::HelmChart, "helm_chart"),
242    (EntityKind::HelmValue, "helm_value"),
243    (EntityKind::HelmTemplateVar, "helm_template_var"),
244    (EntityKind::ProjectIdentity, "project_identity"),
245    (EntityKind::VclVersion, "vcl_version"),
246    (EntityKind::VclSubroutine, "vcl_subroutine"),
247    (EntityKind::VclBuiltinSub, "vcl_builtin_sub"),
248    (EntityKind::VclBackend, "vcl_backend"),
249    (EntityKind::VclProbe, "vcl_probe"),
250    (EntityKind::VclAcl, "vcl_acl"),
251    (EntityKind::VclImport, "vcl_import"),
252    (EntityKind::VclObjectInstance, "vcl_object_instance"),
253    (EntityKind::VtcTestCase, "vtc_test_case"),
254    (EntityKind::VtcServer, "vtc_server"),
255    (EntityKind::VtcClient, "vtc_client"),
256    (EntityKind::VtcVarnishInstance, "vtc_varnish_instance"),
257    (EntityKind::VtcLogexpect, "vtc_logexpect"),
258    (EntityKind::VtcBarrier, "vtc_barrier"),
259    (EntityKind::VccModule, "vcc_module"),
260    (EntityKind::VccFunction, "vcc_function"),
261    (EntityKind::VccObject, "vcc_object"),
262    (EntityKind::VccMethod, "vcc_method"),
263    (EntityKind::MarkdownDocument, "markdown_document"),
264    (EntityKind::MarkdownSection, "markdown_section"),
265    (EntityKind::HttpEndpoint, "http_endpoint"),
266    (EntityKind::HttpClientCall, "http_client_call"),
267];
268
269impl std::fmt::Display for EntityKind {
270    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
271        // The label table covers every variant; a miss falls back to the
272        // derived `Debug` name so a future variant can never render empty.
273        match KIND_LABELS.iter().find(|(k, _)| k == self) {
274            Some((_, label)) => f.write_str(label),
275            None => write!(f, "{self:?}"),
276        }
277    }
278}
279
280impl EntityKind {
281    /// Every wire-format label, for exhaustiveness checks.
282    pub fn all_wire_kinds() -> impl Iterator<Item = &'static str> {
283        KIND_LABELS.iter().map(|(_, label)| *label)
284    }
285}
286
287/// A raw entity extracted from the AST before embedding.
288///
289/// Created in Stage 2 (parse) and enriched with a UUID in Stage 3 (prepare).
290#[derive(Debug, Clone, Serialize, Deserialize)]
291pub struct ParsedEntity {
292    /// Unique identifier — bridges Qdrant and Neo4j records.
293    pub uuid: Uuid,
294
295    /// Human-readable name (class name, method name, function name).
296    pub name: String,
297
298    /// The kind of code construct this entity represents.
299    pub kind: EntityKind,
300
301    /// Fully qualified name for disambiguation.
302    /// - For Java: `com.example.connector.AlternativeConnectorService.proxyManager`
303    /// - For TypeScript: `ClassName.methodName` or just `functionName` for top-level functions
304    /// - For classes/interfaces: `com.example.connector.AlternativeConnectorService`
305    pub fqn: String,
306
307    /// Full signature string for methods/functions (e.g. `public void foo(int x)`).
308    /// `None` for class/interface entities.
309    pub signature: Option<String>,
310
311    /// Associated documentation: Javadoc, JSDoc, or preceding comments found
312    /// immediately before this node in the source file.
313    /// This captures comment blocks that directly precede declarations.
314    pub docstring: Option<String>,
315
316    /// Inline comments found within this entity's body.
317    /// For classes: comments inside the class body but outside any methods.
318    /// For methods/functions: comments inside the method/function body.
319    /// These provide implementation context and are associated with the containing entity.
320    pub inline_comments: Vec<String>,
321
322    /// Decorators and annotations applied to this entity.
323    /// Examples: `@Override`, `@OnEvent('foo')`, `@GetMapping("/path")`, etc.
324    /// Populated during the parse stage for methods, functions, classes, and constants.
325    pub decorators: Vec<String>,
326
327    /// For Rust: list of attributes/decorators
328    /// e.g., vec!["derive(Clone)", "tokio::main"]
329    pub rust_attributes: Option<Vec<String>>,
330
331    /// For Rust `impl` blocks: the trait being implemented (if any)
332    /// e.g., Some("Debug") for `impl Debug for MyStruct`
333    pub impl_trait: Option<String>,
334
335    /// For Rust `impl` blocks: the target type being implemented for
336    /// e.g., "MyStruct" for `impl MyStruct { ... }`
337    pub impl_target: Option<String>,
338
339    /// For Rust generic types: the full generic signature
340    /// e.g., "<T: Clone, U: Default>" or "<'a, T>"
341    pub generics: Option<String>,
342
343    /// For Rust: lifetime parameters
344    /// e.g., vec!["'a", "'b"]
345    pub lifetimes: Option<Vec<String>>,
346
347    /// For JS/TS import aliases: if this entity is a `require()` or `import` alias,
348    /// the relative module path (e.g., "./ResolveCache", "../util/fs").
349    /// Used during resolution to follow cross-file aliases to the original definition.
350    pub alias_module_path: Option<String>,
351
352    /// For TS named imports: the original export name in the target module.
353    /// E.g., `import { MyTsTarget as MyTsAlias }` → Some("MyTsTarget").
354    /// Used by the alias resolver to look up the correct entity in the target file.
355    pub original_export_name: Option<String>,
356
357    /// For JS/TS module-level entities (`<module>`): the name exported as default
358    /// (e.g., `module.exports = ResolveCache`). Used by the alias resolver
359    /// to resolve bare module imports to the correct entity within the target file.
360    pub default_export: Option<String>,
361
362    /// Source language (`"java"` or `"typescript"`).
363    pub language: String,
364
365    /// Absolute path of the source file containing this entity.
366    pub file_path: String,
367
368    /// 1-based line number where the entity declaration starts.
369    pub start_line: usize,
370
371    /// 1-based line number where the entity declaration ends.
372    /// Used to determine if an orphaned reference is contained within this entity.
373    pub end_line: usize,
374
375    /// Enclosing class name for methods. Used to resolve local calls.
376    /// `None` for class/interface entities and top-level functions.
377    pub enclosing_class: Option<String>,
378
379    /// Fully qualified name of the enclosing class for CONTAINS disambiguation.
380    /// When set, the Neo4j CONTAINS auto-link uses this FQN to match the exact
381    /// parent entity instead of matching by bare `name`, which can collide
382    /// when multiple entities share the same class name (e.g. fixtures vs real).
383    /// Populated by language-specific qualifier passes; `None` for non-Rust or
384    /// when the enclosing class FQN is unknown.
385    pub enclosing_class_fqn: Option<String>,
386
387    /// Logical repository name for multi-repository isolation.
388    /// Used to separate entities from different codebases in shared databases.
389    /// Example: "my-java-repo", "my-typescript-repo", "my-microservice"
390    pub repo_name: String,
391
392    /// `true` when this entity lives under a Rust `#[cfg(test)]` module
393    /// (or any nesting depth of such modules). Surfaced as a Neo4j property
394    /// so MCP consumers can distinguish callers/callees that come from
395    /// test code (living documentation) versus production code.
396    /// Always `false` for non-Rust languages.
397    pub is_test_context: bool,
398
399    /// Package and imports of the entity's file (Java, Kotlin), shared by
400    /// every entity of that file. Only call/type resolution reads it, so it
401    /// is neither persisted nor serialized.
402    #[serde(skip)]
403    pub import_scope: Option<Arc<ImportScope>>,
404
405    /// Raw reference intents extracted from this entity.
406    /// Populated during the parse stage; may be empty if no references were found.
407    /// These are resolved to UUIDs during the ingest stage and converted to graph relationships.
408    pub reference_intents: Vec<ReferenceIntent>,
409
410    /// UUIDs of entities this entity directly calls / depends on.
411    /// **DEPRECATED:** Use `relationships` instead for typed edges.
412    /// Populated during the ingest stage based on reference_intents resolution.
413    /// Kept for backward compatibility.
414    pub calls: Vec<Uuid>,
415
416    /// Typed relationships to other entities.
417    /// Each edge includes the target UUID and the relationship type (CALLS, EXTENDS, IMPLEMENTS, REFERENCES).
418    /// Populated during the ingest stage based on reference_intents resolution.
419    pub relationships: Vec<(Uuid, RelationshipType)>,
420
421    /// The text that will be fed to the embedding model.
422    /// Constructed in Stage 3 (prepare) from `name`, `signature`, and `docstring`.
423    pub embed_text: String,
424}
425
426/// Minimal representation of an entity for relationship resolution.
427///
428/// Retains only the fields necessary to match reference intents to UUIDs,
429/// allowing the heavy `embed_text`, `docstring`, and `vector` to be freed.
430#[derive(Debug, Clone)]
431pub struct ResolutionEntity {
432    pub uuid: Uuid,
433    pub name: String,
434    pub fqn: String,
435    pub file_path: String,
436    pub kind: EntityKind,
437    pub enclosing_class: Option<String>,
438    pub enclosing_class_fqn: Option<String>,
439    pub signature: Option<String>,
440    pub reference_intents: Vec<ReferenceIntent>,
441    pub relationships: Vec<(Uuid, RelationshipType)>,
442    pub alias_module_path: Option<String>,
443    pub original_export_name: Option<String>,
444    pub default_export: Option<String>,
445    pub is_test_context: bool,
446    pub import_scope: Option<Arc<ImportScope>>,
447}
448
449impl From<&ParsedEntity> for ResolutionEntity {
450    fn from(entity: &ParsedEntity) -> Self {
451        Self {
452            uuid: entity.uuid,
453            name: entity.name.clone(),
454            fqn: entity.fqn.clone(),
455            file_path: entity.file_path.clone(),
456            kind: entity.kind.clone(),
457            enclosing_class: entity.enclosing_class.clone(),
458            enclosing_class_fqn: entity.enclosing_class_fqn.clone(),
459            signature: entity.signature.clone(),
460            reference_intents: entity.reference_intents.clone(),
461            relationships: Vec::new(),
462            alias_module_path: entity.alias_module_path.clone(),
463            original_export_name: entity.original_export_name.clone(),
464            default_export: entity.default_export.clone(),
465            is_test_context: entity.is_test_context,
466            import_scope: entity.import_scope.clone(),
467        }
468    }
469}
470
471impl From<&EmbeddedEntity> for ResolutionEntity {
472    fn from(ee: &EmbeddedEntity) -> Self {
473        ResolutionEntity::from(&ee.entity)
474    }
475}
476
477impl ParsedEntity {
478    /// Create a new entity with a deterministic UUID v5.
479    ///
480    /// The base UUID is derived from the entity's unique identity (`{repo_name}:{file_path}:{fqn}:{start_line}`)
481    /// to ensure the same entity receives the same UUID across indexing runs.
482    ///
483    /// If multiple entities within a single file share the same base UUID identity,
484    /// a collision-only disambiguation pass (`disambiguate_entity_uuids`) is run to assign
485    /// deterministic UUIDs to colliding members. Non-first members sharing a base identity receive:
486    /// `Uuid::new_v5(&NAMESPACE_KNOT, "{base identity}:{kind label}:{name}#{n}")`, where `n` is its
487    /// 1-based rank among the members sharing that same `(kind, name)`.
488    #[expect(
489        clippy::too_many_arguments,
490        reason = "Entity constructor requires many fields"
491    )]
492    pub fn new(
493        name: impl Into<String>,
494        kind: EntityKind,
495        fqn: impl Into<String>,
496        signature: Option<String>,
497        docstring: Option<String>,
498        language: impl Into<String>,
499        file_path: impl Into<String>,
500        start_line: usize,
501        end_line: usize,
502        enclosing_class: Option<String>,
503        repo_name: impl Into<String>,
504    ) -> Self {
505        let name = name.into();
506        let fqn = fqn.into();
507        let file_path = file_path.into();
508        let repo_name = repo_name.into();
509
510        // Generate deterministic UUID from unique identity
511        let identity = format!("{}:{}:{}:{}", repo_name, file_path, fqn, start_line);
512        let uuid = Uuid::new_v5(&NAMESPACE_KNOT, identity.as_bytes());
513
514        Self {
515            uuid,
516            name,
517            kind,
518            fqn,
519            signature,
520            docstring,
521            language: language.into(),
522            file_path,
523            start_line,
524            end_line,
525            enclosing_class,
526            repo_name,
527            reference_intents: Vec::new(),
528            calls: Vec::new(),
529            relationships: Vec::new(),
530            inline_comments: Vec::new(),
531            decorators: Vec::new(),
532            rust_attributes: None,
533            impl_trait: None,
534            impl_target: None,
535            generics: None,
536            lifetimes: None,
537            alias_module_path: None,
538            original_export_name: None,
539            default_export: None,
540            enclosing_class_fqn: None,
541            is_test_context: false,
542            import_scope: None,
543            embed_text: String::new(),
544        }
545    }
546}
547
548#[cfg(test)]
549mod tests {
550    //! §10.1 unit tests — UUID stability across machines.
551    //!
552    //! Spec requirement (`docs/specs/relative_file_paths.md` §10.1
553    //! `test_uuid_stable_across_machines`): the same `(repo, relative_path,
554    //! fqn, line)` triple must produce the same UUID regardless of the
555    //! indexing machine. This is enforced by storing `file_path` as the
556    //! canonical relative path — the UUID is then a pure function of the
557    //! triple above.
558
559    use super::*;
560
561    #[test]
562    fn test_display_labels() {
563        // KIND_LABELS pairs every variant with its snake-case label; these
564        // spot-checks cover the families and the exception-prone cases.
565        let cases = [
566            (EntityKind::Class, "class"),
567            (EntityKind::Interface, "interface"),
568            (EntityKind::KotlinCompanionObject, "kotlin_companion_object"),
569            (EntityKind::HtmlId, "html_id"),
570            (EntityKind::CssVariable, "css_variable"),
571            (EntityKind::ScssMixin, "scss_mixin"),
572            (EntityKind::RustTypeAlias, "rust_type_alias"),
573            (EntityKind::CppMethod, "cpp_method"),
574            (EntityKind::CStruct, "c_struct"),
575            (EntityKind::CSharpLocalFunction, "csharp_local_function"),
576            (EntityKind::CSharpClass, "csharp_class"),
577            (EntityKind::GroovyTrait, "groovy_trait"),
578            (EntityKind::CargoPackage, "cargo_package"),
579            (EntityKind::K8sConfigMap, "k8s_configmap"),
580            (EntityKind::K8sDeployment, "k8s_deployment"),
581            (EntityKind::HelmTemplateVar, "helm_template_var"),
582            (EntityKind::ProjectIdentity, "project_identity"),
583            (EntityKind::VtcVarnishInstance, "vtc_varnish_instance"),
584            (EntityKind::VccMethod, "vcc_method"),
585            (EntityKind::MarkdownSection, "markdown_section"),
586        ];
587        for (kind, label) in cases {
588            assert_eq!(kind.to_string(), label);
589        }
590    }
591
592    #[test]
593    fn test_uuid_stable_across_machines() {
594        let a = ParsedEntity::new(
595            "Config",
596            EntityKind::Class,
597            "mycrate::config::Config",
598            None,
599            None,
600            "rust",
601            "src/config.rs",
602            1,
603            10,
604            None,
605            "mycrate",
606        );
607        let b = ParsedEntity::new(
608            "Config",
609            EntityKind::Class,
610            "mycrate::config::Config",
611            None,
612            None,
613            "rust",
614            "src/config.rs",
615            1,
616            10,
617            None,
618            "mycrate",
619        );
620        assert_eq!(
621            a.uuid, b.uuid,
622            "UUIDs must be deterministic for the same triple (repo, path, fqn, line)"
623        );
624
625        // Explicitly assert against the backward-compatible Uuid::new_v5 formula
626        let expected_uuid = Uuid::new_v5(
627            &NAMESPACE_KNOT,
628            "mycrate:src/config.rs:mycrate::config::Config:1".as_bytes(),
629        );
630        assert_eq!(
631            a.uuid, expected_uuid,
632            "UUID must match legacy v5 identity formula for non-colliding entities"
633        );
634
635        // The mirror: two different absolute prefixes in `file_path` MUST NOT
636        // produce the same UUID (they are different identities). The spec's
637        // stability contract only holds for relative paths.
638        let c = ParsedEntity::new(
639            "Config",
640            EntityKind::Class,
641            "mycrate::config::Config",
642            None,
643            None,
644            "rust",
645            "/home/alice/work/mycrate/src/config.rs",
646            1,
647            10,
648            None,
649            "mycrate",
650        );
651        let d = ParsedEntity::new(
652            "Config",
653            EntityKind::Class,
654            "mycrate::config::Config",
655            None,
656            None,
657            "rust",
658            "/var/lib/knot/repos/mycrate/src/config.rs",
659            1,
660            10,
661            None,
662            "mycrate",
663        );
664        assert_ne!(
665            c.uuid, d.uuid,
666            "different absolute prefixes must yield different UUIDs (regression marker)"
667        );
668    }
669}
670
671/// An entity that has been embedded and is ready for dual-write ingestion.
672///
673/// Produced by Stage 4 (embed) and consumed by Stage 5 (ingest).
674#[derive(Debug, Clone)]
675pub struct EmbeddedEntity {
676    /// The original parsed entity with all metadata.
677    pub entity: ParsedEntity,
678
679    /// High-dimensional vector produced by the embedding model.
680    pub vector: Vec<f32>,
681}