hexser 0.4.7

Zero-boilerplate hexagonal architecture with graph-based introspection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! AI context structure for machine-readable architecture representation.
//!
//! Defines structured format for exporting architecture metadata to AI agents.
//! Includes components, relationships, constraints, and suggestions.
//! Follows JSON Schema for validation and tooling integration.
//!
//! Revision History
//! - 2025-10-10T20:28:00Z @AI: Add MethodInfo to ComponentInfo for capturing method signatures and documentation.
//! - 2025-10-02T18:00:00Z @AI: Initial AI context structure.
//! - 2025-10-06T17:59:00Z @AI: Add to_json() serializer and tests; ensure ai feature includes serde.

/// Machine-readable architecture context for AI agents
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct AIContext {
  /// Architecture pattern used
  pub architecture: String,

  /// Crate version
  pub version: String,

  /// All components in the architecture
  pub components: Vec<ComponentInfo>,

  /// Relationships between components
  pub relationships: Vec<RelationshipInfo>,

  /// Architectural constraints and rules
  pub constraints: ConstraintSet,

  /// AI suggestions for improvements
  pub suggestions: Vec<Suggestion>,

  /// Metadata about the export
  pub metadata: ContextMetadata,
}

/// Information about a single component
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct ComponentInfo {
  /// Fully qualified type name
  pub type_name: String,

  /// Architectural layer
  pub layer: String,

  /// Component role
  pub role: String,

  /// Module path
  pub module_path: String,

  /// Brief description of purpose
  pub purpose: Option<String>,

  /// Dependencies on other components
  pub dependencies: Vec<String>,

  /// Public methods and their documentation
  pub methods: Vec<MethodInfo>,
}

/// Information about a method within a component
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct MethodInfo {
  /// Method name
  pub name: String,

  /// Method signature (full declaration)
  pub signature: String,

  /// Documentation comment for the method
  pub documentation: Option<String>,

  /// Method parameters with types and descriptions
  pub parameters: Vec<ParameterInfo>,

  /// Return type information
  pub return_type: Option<String>,

  /// Whether this method is public
  pub is_public: bool,

  /// Whether this method is async
  pub is_async: bool,
}

/// Information about a method parameter
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct ParameterInfo {
  /// Parameter name
  pub name: String,

  /// Parameter type
  pub param_type: String,

  /// Parameter description from documentation
  pub description: Option<String>,
}

/// Information about component relationships
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct RelationshipInfo {
  /// Source component
  pub from: String,

  /// Target component
  pub to: String,

  /// Relationship type
  pub relationship_type: String,

  /// Whether this relationship is valid per architecture rules
  pub is_valid: bool,

  /// Explanation if invalid
  pub validation_message: Option<String>,
}

/// Set of architectural constraints
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct ConstraintSet {
  /// Dependency rules between layers
  pub dependency_rules: Vec<DependencyRule>,

  /// Layer boundary rules
  pub layer_boundaries: Vec<LayerBoundary>,

  /// Naming conventions
  pub naming_conventions: Vec<NamingConvention>,

  /// Required patterns
  pub required_patterns: Vec<String>,
}

/// Rule about layer dependencies
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct DependencyRule {
  /// Source layer
  pub from_layer: String,

  /// Target layer
  pub to_layer: String,

  /// Whether dependency is allowed
  pub allowed: bool,

  /// Explanation
  pub reason: String,
}

/// Layer boundary definition
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct LayerBoundary {
  /// Layer name
  pub layer: String,

  /// What this layer can depend on
  pub can_depend_on: Vec<String>,

  /// What can depend on this layer
  pub dependents_allowed: Vec<String>,

  /// Purpose of this layer
  pub purpose: String,
}

/// Naming convention rule
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct NamingConvention {
  /// What the convention applies to
  pub applies_to: String,

  /// Pattern or rule
  pub pattern: String,

  /// Example
  pub example: String,
}

/// AI suggestion for improvement
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct Suggestion {
  /// Suggestion type
  pub suggestion_type: SuggestionType,

  /// Component this applies to
  pub component: Option<String>,

  /// Description
  pub description: String,

  /// Priority
  pub priority: Priority,

  /// Code example if applicable
  pub code_example: Option<String>,
}

/// Type of suggestion
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum SuggestionType {
  /// Missing implementation
  MissingImplementation,

  /// Architectural violation
  ArchitecturalViolation,

  /// Improvement opportunity
  Improvement,

  /// Best practice recommendation
  BestPractice,

  /// Potential issue
  PotentialIssue,
}

/// Suggestion priority
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
#[serde(rename_all = "lowercase")]
pub enum Priority {
  Low,
  Medium,
  High,
  Critical,
}

/// Metadata about the context export
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct ContextMetadata {
  /// When context was generated
  pub generated_at: String,

  /// hex version used
  pub hex_version: String,

  /// Total component count
  pub total_components: usize,

  /// Total relationship count
  pub total_relationships: usize,

  /// Schema version
  pub schema_version: String,
}

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

  #[test]
  fn test_ai_context_serialization() {
    let context = AIContext {
      architecture: String::from("hexagonal"),
      version: String::from("0.3.0"),
      components: vec![],
      relationships: vec![],
      constraints: ConstraintSet {
        dependency_rules: vec![],
        layer_boundaries: vec![],
        naming_conventions: vec![],
        required_patterns: vec![],
      },
      suggestions: vec![],
      metadata: ContextMetadata {
        generated_at: String::from("2025-10-02T18:00:00Z"),
        hex_version: String::from("0.3.0"),
        total_components: 0,
        total_relationships: 0,
        schema_version: String::from("1.0.0"),
      },
    };

    let json = serde_json::to_string(&context).unwrap();
    assert!(json.contains("hexagonal"));
    assert!(json.contains("schema_version"));
  }

  #[test]
  fn test_component_info_serialization() {
    let component = ComponentInfo {
      type_name: String::from("User"),
      layer: String::from("Domain"),
      role: String::from("Entity"),
      module_path: String::from("domain::user"),
      purpose: Some(String::from("Represents a user")),
      methods: vec![],
      dependencies: vec![],
    };

    let json = serde_json::to_string(&component).unwrap();
    assert!(json.contains("User"));
    assert!(json.contains("Domain"));
  }

  #[test]
  fn test_suggestion_serialization() {
    let suggestion = Suggestion {
      suggestion_type: SuggestionType::MissingImplementation,
      component: Some(String::from("UserRepository")),
      description: String::from("Port missing adapter implementation"),
      priority: Priority::High,
      code_example: Some(String::from("impl UserRepository for PostgresUserRepo")),
    };

    let json = serde_json::to_string(&suggestion).unwrap();
    assert!(json.contains("missing_implementation"));
    assert!(json.contains("high"));
  }

  #[test]
  fn test_method_info_serialization() {
    // Test: Validates MethodInfo structure serializes correctly with method details
    // Justification: New feature for capturing method-level documentation
    let method = MethodInfo {
      name: String::from("save"),
      signature: String::from("fn save(&mut self, entity: T) -> HexResult<()>"),
      documentation: Some(String::from("Saves an entity to the repository")),
      parameters: vec![
        ParameterInfo {
          name: String::from("self"),
          param_type: String::from("&mut self"),
          description: None,
        },
        ParameterInfo {
          name: String::from("entity"),
          param_type: String::from("T"),
          description: Some(String::from("The entity to save")),
        },
      ],
      return_type: Some(String::from("HexResult<()>")),
      is_public: true,
      is_async: false,
    };

    let json = serde_json::to_string(&method).unwrap();
    assert!(json.contains("save"));
    assert!(json.contains("HexResult"));
    assert!(json.contains("\"is_public\":true"));
  }

  #[test]
  fn test_component_with_methods() {
    // Test: Validates ComponentInfo with methods field serializes correctly
    // Justification: Integration test for new methods feature
    let component = ComponentInfo {
      type_name: String::from("UserRepository"),
      layer: String::from("Port"),
      role: String::from("Repository"),
      module_path: String::from("ports::user_repository"),
      purpose: Some(String::from("Manages user persistence")),
      methods: vec![MethodInfo {
        name: String::from("find_by_id"),
        signature: String::from("fn find_by_id(&self, id: &str) -> HexResult<Option<User>>"),
        documentation: Some(String::from("Finds a user by their ID")),
        parameters: vec![ParameterInfo {
          name: String::from("id"),
          param_type: String::from("&str"),
          description: Some(String::from("User identifier")),
        }],
        return_type: Some(String::from("HexResult<Option<User>>")),
        is_public: true,
        is_async: false,
      }],
      dependencies: vec![],
    };

    let json = serde_json::to_string(&component).unwrap();
    assert!(json.contains("UserRepository"));
    assert!(json.contains("find_by_id"));
    assert!(json.contains("Finds a user"));
  }
}

impl AIContext {
  /// Serialize this AIContext to a JSON string.
  ///
  /// Returns a String on success, or an error message on failure.
  /// Uses serde_json with a stable field order as defined by this struct.
  pub fn to_json(&self) -> Result<String, String> {
    match serde_json::to_string(self) {
      Ok(s) => Ok(s),
      Err(e) => Err(format!("Serialization error: {}", e)),
    }
  }
}

#[cfg(test)]
mod tests_to_json {
  #[test]
  fn test_ai_context_to_json_method() {
    let ctx = super::AIContext {
      architecture: String::from("hexagonal"),
      version: String::from("0.3.0"),
      components: Vec::new(),
      relationships: Vec::new(),
      constraints: super::ConstraintSet {
        dependency_rules: Vec::new(),
        layer_boundaries: Vec::new(),
        naming_conventions: Vec::new(),
        required_patterns: Vec::new(),
      },
      suggestions: Vec::new(),
      metadata: super::ContextMetadata {
        generated_at: String::from("2025-10-06T17:59:00Z"),
        hex_version: String::from("0.3.0"),
        total_components: 0,
        total_relationships: 0,
        schema_version: String::from("1.0.0"),
      },
    };

    let json = ctx.to_json().unwrap();
    assert!(json.contains("\"schema_version\""));
    assert!(json.contains("\"hexagonal\""));
  }
}