mockforge-intelligence 0.3.145

AI-powered behavior, response generation, and behavioral cloning for MockForge
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! Schema correction proposal generator
//!
//! This module generates JSON Patch (RFC 6902) files for correcting contract specifications
//! based on detected mismatches and recommendations.

use super::types::{CorrectionProposal, Mismatch, PatchOperation, Recommendation};
use mockforge_openapi::OpenApiSpec;
use serde_json::{json, Value};
use std::collections::HashMap;

/// Correction proposal generator
pub struct CorrectionProposer;

impl CorrectionProposer {
    /// Generate correction proposals from mismatches and recommendations
    pub fn generate_proposals(
        mismatches: &[Mismatch],
        recommendations: &[Recommendation],
        spec: &OpenApiSpec,
    ) -> Vec<CorrectionProposal> {
        let mut proposals = Vec::new();

        // Group recommendations by mismatch
        let mut rec_by_mismatch: HashMap<String, Vec<&Recommendation>> = HashMap::new();
        for rec in recommendations {
            rec_by_mismatch.entry(rec.mismatch_id.clone()).or_default().push(rec);
        }

        // Generate proposals for each mismatch
        for (idx, mismatch) in mismatches.iter().enumerate() {
            let mismatch_id = format!("mismatch_{}", idx);
            let recommendations_for_mismatch =
                rec_by_mismatch.get(&mismatch_id).map(|v| v.as_slice()).unwrap_or(&[]);

            let proposals_for_mismatch =
                Self::generate_proposals_for_mismatch(mismatch, recommendations_for_mismatch, spec);

            proposals.extend(proposals_for_mismatch);
        }

        proposals
    }

    /// Generate correction proposals for a specific mismatch
    fn generate_proposals_for_mismatch(
        mismatch: &Mismatch,
        recommendations: &[&Recommendation],
        spec: &OpenApiSpec,
    ) -> Vec<CorrectionProposal> {
        let mut proposals = Vec::new();

        match mismatch.mismatch_type {
            super::types::MismatchType::MissingRequiredField => {
                if let Some(proposal) = Self::propose_add_required_field(mismatch, spec) {
                    proposals.push(proposal);
                }
            }
            super::types::MismatchType::TypeMismatch => {
                if let Some(proposal) = Self::propose_fix_type(mismatch, spec) {
                    proposals.push(proposal);
                }
            }
            super::types::MismatchType::UnexpectedField => {
                if let Some(proposal) = Self::propose_remove_field(mismatch, spec) {
                    proposals.push(proposal);
                } else if let Some(proposal) = Self::propose_add_optional_field(mismatch, spec) {
                    // If field is being sent but not in spec, maybe it should be added as optional
                    proposals.push(proposal);
                }
            }
            super::types::MismatchType::FormatMismatch => {
                if let Some(proposal) = Self::propose_add_format(mismatch, spec) {
                    proposals.push(proposal);
                }
            }
            super::types::MismatchType::EndpointNotFound => {
                if let Some(proposal) = Self::propose_add_endpoint(mismatch, spec) {
                    proposals.push(proposal);
                }
            }
            _ => {
                // Generic proposal for other mismatch types
                if let Some(proposal) = Self::propose_generic_fix(mismatch, recommendations, spec) {
                    proposals.push(proposal);
                }
            }
        }

        proposals
    }

    /// Extract the existing schema definition for an endpoint field from the spec
    fn extract_field_from_spec(
        spec: &OpenApiSpec,
        request_path: &str,
        method: Option<&str>,
        field_name: &str,
    ) -> Value {
        // Navigate: spec.paths[path][method].requestBody.content["application/json"].schema.properties[field]
        let path_item = spec.spec.paths.paths.get(request_path).and_then(|p| p.as_item());

        let operation = path_item.and_then(|item| {
            let m = method.unwrap_or("get");
            match m.to_uppercase().as_str() {
                "GET" => item.get.as_ref(),
                "POST" => item.post.as_ref(),
                "PUT" => item.put.as_ref(),
                "DELETE" => item.delete.as_ref(),
                "PATCH" => item.patch.as_ref(),
                _ => None,
            }
        });

        if let Some(op) = operation {
            // Try request body schema
            if let Some(openapiv3::ReferenceOr::Item(ref body_item)) = op.request_body {
                if let Some(media) = body_item.content.get("application/json") {
                    if let Some(ref schema) = media.schema {
                        if let Ok(schema_val) = serde_json::to_value(schema) {
                            if let Some(field_val) =
                                schema_val.pointer(&format!("/item/properties/{}", field_name))
                            {
                                return field_val.clone();
                            }
                            // Also try without the item wrapper
                            if let Some(field_val) =
                                schema_val.pointer(&format!("/properties/{}", field_name))
                            {
                                return field_val.clone();
                            }
                        }
                    }
                }
            }

            // Try response schema (200)
            if let Some(openapiv3::ReferenceOr::Item(ref resp_item)) =
                op.responses.responses.get(&openapiv3::StatusCode::Code(200))
            {
                if let Some(media) = resp_item.content.get("application/json") {
                    if let Some(ref schema) = media.schema {
                        if let Ok(schema_val) = serde_json::to_value(schema) {
                            if let Some(field_val) =
                                schema_val.pointer(&format!("/item/properties/{}", field_name))
                            {
                                return field_val.clone();
                            }
                            if let Some(field_val) =
                                schema_val.pointer(&format!("/properties/{}", field_name))
                            {
                                return field_val.clone();
                            }
                        }
                    }
                }
            }
        }

        json!(null)
    }

    /// Propose adding a required field to the schema
    fn propose_add_required_field(
        mismatch: &Mismatch,
        spec: &OpenApiSpec,
    ) -> Option<CorrectionProposal> {
        // Extract field path and type from mismatch
        let path_parts: Vec<&str> = mismatch.path.split('/').filter(|s| !s.is_empty()).collect();
        if path_parts.is_empty() {
            return None;
        }

        let field_name = path_parts.last().unwrap();
        let expected_type = mismatch.expected.as_ref()?;

        // Build JSON Patch path (RFC 6902 format with ~1 for / and ~0 for ~)
        let patch_path = Self::build_patch_path(&mismatch.path, mismatch.method.as_deref());

        // Determine field schema based on expected type
        let field_schema = match expected_type.as_str() {
            "string" => json!({
                "type": "string"
            }),
            "integer" => json!({
                "type": "integer"
            }),
            "number" => json!({
                "type": "number"
            }),
            "boolean" => json!({
                "type": "boolean"
            }),
            "array" => json!({
                "type": "array",
                "items": {}
            }),
            "object" => json!({
                "type": "object",
                "properties": {}
            }),
            _ => json!({
                "type": "string"
            }),
        };

        // Extract the current schema state from the spec
        let before = Self::extract_field_from_spec(
            spec,
            &mismatch.path,
            mismatch.method.as_deref(),
            field_name,
        );

        // Get after value (proposed schema)
        let after = field_schema.clone();

        Some(CorrectionProposal {
            id: format!("correction_{}", mismatch.path.replace('/', "_")),
            patch_path: format!("{}/properties/{}", patch_path, field_name),
            operation: PatchOperation::Add,
            value: Some(field_schema),
            from: None,
            confidence: mismatch.confidence,
            description: format!(
                "Add required field '{}' of type '{}' to schema",
                field_name, expected_type
            ),
            reasoning: Some(format!(
                "Front-end consistently sends '{}' but it's not defined in the contract",
                field_name
            )),
            affected_endpoints: mismatch
                .method
                .as_ref()
                .map(|m| vec![format!("{} {}", m, mismatch.path)])
                .unwrap_or_default(),
            before: Some(before),
            after: Some(after),
        })
    }

    /// Propose fixing a type mismatch
    fn propose_fix_type(mismatch: &Mismatch, _spec: &OpenApiSpec) -> Option<CorrectionProposal> {
        let expected_type = mismatch.expected.as_ref()?;
        let actual_type = mismatch.actual.as_ref()?;

        let patch_path = Self::build_patch_path(&mismatch.path, mismatch.method.as_deref());

        // Build new type schema
        let new_type_schema = match expected_type.as_str() {
            "string" => json!({"type": "string"}),
            "integer" => json!({"type": "integer"}),
            "number" => json!({"type": "number"}),
            "boolean" => json!({"type": "boolean"}),
            "array" => json!({"type": "array", "items": {}}),
            "object" => json!({"type": "object", "properties": {}}),
            _ => json!({"type": "string"}),
        };

        let before = json!({"type": actual_type});
        let after = new_type_schema.clone();

        Some(CorrectionProposal {
            id: format!("correction_type_{}", mismatch.path.replace('/', "_")),
            patch_path: format!("{}/type", patch_path),
            operation: PatchOperation::Replace,
            value: Some(Value::String(expected_type.clone())),
            from: None,
            confidence: mismatch.confidence,
            description: format!("Change field type from '{}' to '{}'", actual_type, expected_type),
            reasoning: Some(format!(
                "Front-end sends '{}' as '{}' but contract expects '{}'",
                mismatch.path, actual_type, expected_type
            )),
            affected_endpoints: mismatch
                .method
                .as_ref()
                .map(|m| vec![format!("{} {}", m, mismatch.path)])
                .unwrap_or_default(),
            before: Some(before),
            after: Some(after),
        })
    }

    /// Propose removing an unexpected field
    fn propose_remove_field(
        mismatch: &Mismatch,
        _spec: &OpenApiSpec,
    ) -> Option<CorrectionProposal> {
        let patch_path = Self::build_patch_path(&mismatch.path, mismatch.method.as_deref());

        Some(CorrectionProposal {
            id: format!("correction_remove_{}", mismatch.path.replace('/', "_")),
            patch_path: patch_path.clone(),
            operation: PatchOperation::Remove,
            value: None,
            from: None,
            confidence: mismatch.confidence * 0.8, // Lower confidence for removal
            description: format!("Remove unexpected field '{}' from request", mismatch.path),
            reasoning: Some(format!(
                "Field '{}' is sent by front-end but not defined in contract",
                mismatch.path
            )),
            affected_endpoints: mismatch
                .method
                .as_ref()
                .map(|m| vec![format!("{} {}", m, mismatch.path)])
                .unwrap_or_default(),
            before: Some(json!({"field": mismatch.path})),
            after: Some(json!(null)),
        })
    }

    /// Propose adding an optional field (alternative to removal)
    fn propose_add_optional_field(
        mismatch: &Mismatch,
        spec: &OpenApiSpec,
    ) -> Option<CorrectionProposal> {
        // Similar to add_required_field but with required: false
        Self::propose_add_required_field(mismatch, spec).map(|mut proposal| {
            proposal.operation = PatchOperation::Add;
            proposal.confidence = mismatch.confidence * 0.7; // Lower confidence for optional
            proposal.description = format!(
                "Add optional field '{}' to schema (alternative to removing from request)",
                mismatch.path
            );
            proposal.reasoning = Some(format!(
                "Front-end sends '{}' but it's not in contract. Consider adding as optional field.",
                mismatch.path
            ));
            proposal
        })
    }

    /// Propose adding format constraint
    fn propose_add_format(mismatch: &Mismatch, _spec: &OpenApiSpec) -> Option<CorrectionProposal> {
        // Extract format from context if available
        let format_value =
            mismatch.context.get("format").and_then(|v| v.as_str()).map(|s| s.to_string());

        let format_value_clone = format_value.clone();
        format_value.as_ref()?;

        let patch_path = Self::build_patch_path(&mismatch.path, mismatch.method.as_deref());

        Some(CorrectionProposal {
            id: format!("correction_format_{}", mismatch.path.replace('/', "_")),
            patch_path: format!("{}/format", patch_path),
            operation: PatchOperation::Add,
            value: Some(Value::String(format_value.unwrap())),
            from: None,
            confidence: mismatch.confidence,
            description: format!("Add format constraint to field '{}'", mismatch.path),
            reasoning: Some(format!("Field '{}' should have format validation", mismatch.path)),
            affected_endpoints: mismatch
                .method
                .as_ref()
                .map(|m| vec![format!("{} {}", m, mismatch.path)])
                .unwrap_or_default(),
            before: Some(json!({"format": null})),
            after: Some(json!({"format": format_value_clone})),
        })
    }

    /// Propose adding a missing endpoint
    fn propose_add_endpoint(
        mismatch: &Mismatch,
        _spec: &OpenApiSpec,
    ) -> Option<CorrectionProposal> {
        let method = mismatch.method.as_ref()?;
        let path = &mismatch.path;

        // Build OpenAPI path item structure
        let patch_path = format!("/paths/{}", Self::escape_json_pointer(path));

        let endpoint_schema = json!({
            method.to_lowercase(): {
                "summary": format!("{} {}", method, path),
                "responses": {
                    "200": {
                        "description": "Success"
                    }
                }
            }
        });

        let endpoint_schema_clone = endpoint_schema.clone();

        Some(CorrectionProposal {
            id: format!("correction_endpoint_{}_{}", method, path.replace('/', "_")),
            patch_path,
            operation: PatchOperation::Add,
            value: Some(endpoint_schema),
            from: None,
            confidence: mismatch.confidence,
            description: format!("Add endpoint {} {} to contract", method, path),
            reasoning: Some(format!(
                "Front-end calls {} {} but endpoint is not defined in contract",
                method, path
            )),
            affected_endpoints: vec![format!("{} {}", method, path)],
            before: Some(json!(null)),
            after: Some(endpoint_schema_clone),
        })
    }

    /// Propose a generic fix based on recommendations
    fn propose_generic_fix(
        mismatch: &Mismatch,
        recommendations: &[&Recommendation],
        _spec: &OpenApiSpec,
    ) -> Option<CorrectionProposal> {
        // Use the first recommendation if available
        let recommendation = recommendations.first()?;

        let patch_path = Self::build_patch_path(&mismatch.path, mismatch.method.as_deref());

        Some(CorrectionProposal {
            id: format!("correction_generic_{}", mismatch.path.replace('/', "_")),
            patch_path,
            operation: PatchOperation::Replace,
            value: recommendation.example.clone(),
            from: None,
            confidence: recommendation.confidence,
            description: recommendation.recommendation.clone(),
            reasoning: recommendation.reasoning.clone(),
            affected_endpoints: mismatch
                .method
                .as_ref()
                .map(|m| vec![format!("{} {}", m, mismatch.path)])
                .unwrap_or_default(),
            before: None,
            after: recommendation.example.clone(),
        })
    }

    /// Build JSON Patch path from request path and method
    fn build_patch_path(request_path: &str, method: Option<&str>) -> String {
        // Convert request path to OpenAPI schema path
        // Example: /api/users -> /paths/~1api~1users/post/requestBody/content/application~1json/schema
        let escaped_path = Self::escape_json_pointer(request_path);

        if let Some(m) = method {
            format!(
                "/paths/{}/{}/requestBody/content/application~1json/schema",
                escaped_path,
                m.to_lowercase()
            )
        } else {
            format!("/paths/{}/schema", escaped_path)
        }
    }

    /// Escape JSON Pointer special characters (RFC 6901)
    fn escape_json_pointer(path: &str) -> String {
        path.replace('~', "~0").replace('/', "~1")
    }

    /// Generate JSON Patch file from correction proposals
    pub fn generate_patch_file(proposals: &[CorrectionProposal], spec_version: &str) -> Value {
        let patch_operations: Vec<Value> = proposals
            .iter()
            .map(|proposal| {
                let mut op = json!({
                    "op": format!("{:?}", proposal.operation).to_lowercase(),
                    "path": proposal.patch_path,
                });

                match proposal.operation {
                    PatchOperation::Add | PatchOperation::Replace => {
                        if let Some(value) = &proposal.value {
                            op["value"] = value.clone();
                        }
                    }
                    PatchOperation::Move | PatchOperation::Copy => {
                        if let Some(from) = &proposal.from {
                            op["from"] = json!(from);
                        }
                    }
                    _ => {}
                }

                // Add metadata
                op["metadata"] = json!({
                    "id": proposal.id,
                    "confidence": proposal.confidence,
                    "description": proposal.description,
                    "reasoning": proposal.reasoning,
                    "affected_endpoints": proposal.affected_endpoints,
                });

                op
            })
            .collect();

        json!({
            "format": "json-patch",
            "spec_version": spec_version,
            "operations": patch_operations,
            "metadata": {
                "generated_at": chrono::Utc::now().to_rfc3339(),
                "total_corrections": proposals.len(),
                "average_confidence": proposals.iter().map(|p| p.confidence).sum::<f64>() / proposals.len() as f64,
            }
        })
    }
}

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

    #[test]
    fn test_extract_field_from_spec_no_match() {
        // With an empty spec, extraction should return null
        let spec = OpenApiSpec {
            spec: openapiv3::OpenAPI::default(),
            file_path: None,
            raw_document: None,
        };
        let result =
            CorrectionProposer::extract_field_from_spec(&spec, "/api/users", Some("POST"), "name");
        assert_eq!(result, json!(null));
    }

    #[test]
    fn test_escape_json_pointer() {
        assert_eq!(CorrectionProposer::escape_json_pointer("/api/users"), "~1api~1users");
        assert_eq!(CorrectionProposer::escape_json_pointer("~test"), "~0test");
    }

    #[test]
    fn test_build_patch_path() {
        let path = CorrectionProposer::build_patch_path("/api/users", Some("POST"));
        assert!(path.contains("~1api~1users"));
        assert!(path.contains("post"));
    }
}