mrapids 0.1.31

Your OpenAPI, but executable
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
// Operation Cards - The keystone for agent retrieval
// Deterministic, hashable representation of API operations

#![allow(dead_code)]

use anyhow::Result;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;

use crate::core::parser::{
    ParameterLocation, SchemaType, SecurityRequirement, UnifiedOperation, UnifiedParameter,
    UnifiedRequestBody, UnifiedSchema, UnifiedSpec,
};

/// Normalized parameter for deterministic serialization
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct CardParameter {
    pub name: String,
    pub location: String, // "path", "query", "header", "cookie"
    pub required: bool,
    pub param_type: String,
    pub format: Option<String>,
    pub description: Option<String>,
    pub enum_values: Option<Vec<String>>,
}

impl CardParameter {
    pub fn from_unified(param: &UnifiedParameter) -> Self {
        let location = match param.location {
            ParameterLocation::Path => "path",
            ParameterLocation::Query => "query",
            ParameterLocation::Header => "header",
            ParameterLocation::Cookie => "cookie",
        };

        Self {
            name: param.name.clone(),
            location: location.to_string(),
            required: param.required,
            param_type: param.schema.schema_type.to_string(),
            format: param.schema.format.clone(),
            description: param.description.clone(),
            enum_values: param.schema.enum_values.as_ref().map(|vals| {
                vals.iter()
                    .filter_map(|v| v.as_str().map(|s| s.to_string()))
                    .collect()
            }),
        }
    }

    pub fn to_text(&self) -> String {
        let mut parts = vec![format!("{} ({})", self.name, self.param_type)];

        if self.required {
            parts.push("required".to_string());
        }

        if let Some(desc) = &self.description {
            parts.push(desc.clone());
        }

        if let Some(enums) = &self.enum_values {
            parts.push(format!("values: {}", enums.join(", ")));
        }

        parts.join(" - ")
    }
}

/// Normalized request body schema
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CardRequestBody {
    pub content_type: String,
    pub required: bool,
    pub schema_summary: String,
    pub properties: BTreeMap<String, CardProperty>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct CardProperty {
    pub name: String,
    pub prop_type: String,
    pub required: bool,
    pub description: Option<String>,
}

impl CardRequestBody {
    pub fn from_unified(rb: &UnifiedRequestBody) -> Option<Self> {
        // Prefer application/json
        let (content_type, media_type) = rb
            .content
            .get("application/json")
            .map(|mt| ("application/json".to_string(), mt))
            .or_else(|| rb.content.iter().next().map(|(k, v)| (k.clone(), v)))?;

        let schema = &media_type.schema;
        let schema_summary = summarize_schema(schema);

        let mut properties = BTreeMap::new();
        if let Some(props) = &schema.properties {
            let required_fields: Vec<String> = schema.required.clone().unwrap_or_default();

            for (name, prop_schema) in props {
                properties.insert(
                    name.clone(),
                    CardProperty {
                        name: name.clone(),
                        prop_type: prop_schema.schema_type.to_string(),
                        required: required_fields.contains(name),
                        description: prop_schema.description.clone(),
                    },
                );
            }
        }

        Some(Self {
            content_type,
            required: rb.required,
            schema_summary,
            properties,
        })
    }

    pub fn to_text(&self) -> String {
        let mut lines = vec![format!("Body ({})", self.content_type)];

        for (_, prop) in &self.properties {
            let req_marker = if prop.required { "*" } else { "" };
            let desc = prop
                .description
                .as_ref()
                .map(|d| format!(" - {}", d))
                .unwrap_or_default();
            lines.push(format!(
                "  {}{}: {}{}",
                prop.name, req_marker, prop.prop_type, desc
            ));
        }

        lines.join("\n")
    }
}

/// The Operation Card - core unit for agent retrieval
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OperationCard {
    // Identity
    pub spec_id: String,
    pub operation_id: String,
    pub content_hash: String,

    // Endpoint
    pub method: String,
    pub path: String,

    // Documentation
    pub summary: Option<String>,
    pub description: Option<String>,

    // Parameters (sorted by name for determinism)
    pub parameters: Vec<CardParameter>,

    // Request body
    pub request_body: Option<CardRequestBody>,

    // Auth
    pub auth_required: bool,
    pub auth_type: Option<String>,
    pub auth_scopes: Vec<String>,

    // Classification
    pub risk_level: String, // "read" or "write"
    pub tags: Vec<String>,

    // Agent-friendly alias (e.g., "portfolio.listTransactions")
    pub alias: String,

    // Embedding
    pub embedding_text: String,
    pub embedding: Option<Vec<f32>>,
}

impl OperationCard {
    /// Create an OperationCard from a UnifiedOperation
    pub fn from_unified(spec_id: &str, op: &UnifiedOperation, spec: &UnifiedSpec) -> Self {
        // Convert and sort parameters by name
        let mut parameters: Vec<CardParameter> = op
            .parameters
            .iter()
            .map(CardParameter::from_unified)
            .collect();
        parameters.sort_by(|a, b| a.name.cmp(&b.name));

        // Convert request body
        let request_body = op
            .request_body
            .as_ref()
            .and_then(CardRequestBody::from_unified);

        // Determine auth requirements
        let (auth_required, auth_type, auth_scopes) =
            extract_auth_info(op.security.as_ref(), &spec.security_schemes);

        // Classify risk level based on HTTP method
        let risk_level = match op.method.to_uppercase().as_str() {
            "GET" | "HEAD" | "OPTIONS" => "read",
            _ => "write",
        }
        .to_string();

        // Use spec tags if available, otherwise extract from path
        let tags = if op.tags.is_empty() {
            extract_tags_from_path(&op.path)
        } else {
            op.tags.clone()
        };

        // Generate agent-friendly alias
        let alias = generate_alias(&op.summary, &tags, &op.operation_id);

        // Build the card without hash first
        let mut card = Self {
            spec_id: spec_id.to_string(),
            operation_id: op.operation_id.clone(),
            content_hash: String::new(), // Will be computed
            method: op.method.clone(),
            path: op.path.clone(),
            summary: op.summary.clone(),
            description: op.description.clone(),
            parameters,
            request_body,
            auth_required,
            auth_type,
            auth_scopes,
            risk_level,
            tags,
            alias,
            embedding_text: String::new(), // Will be computed
            embedding: None,
        };

        // Generate embedding text
        card.embedding_text = card.generate_embedding_text();

        // Compute content hash
        card.content_hash = card.compute_hash();

        card
    }

    /// Generate deterministic text representation for embeddings
    fn generate_embedding_text(&self) -> String {
        use crate::core::identifier_splitter::split_to_text;

        let mut lines = Vec::new();

        // Operation identity (keep original for exact keyword match)
        lines.push(format!("OPERATION: {}", self.operation_id));
        // Split tokens for semantic matching (e.g., "findPetsByStatus" → "find pets by status")
        let op_tokens = split_to_text(&self.operation_id);
        if !op_tokens.is_empty() {
            lines.push(format!("TOKENS: {}", op_tokens));
        }

        lines.push(format!("ENDPOINT: {} {}", self.method, self.path));
        // Split path tokens (e.g., "/users/{userId}" → "users user id")
        let path_tokens = split_to_text(&self.path);
        if !path_tokens.is_empty() {
            lines.push(format!("PATH_TOKENS: {}", path_tokens));
        }

        // Summary and description
        if let Some(summary) = &self.summary {
            lines.push(format!("SUMMARY: {}", summary));
        }
        if let Some(desc) = &self.description {
            lines.push(format!("DESCRIPTION: {}", desc));
        }

        // Parameters
        if !self.parameters.is_empty() {
            lines.push("PARAMETERS:".to_string());
            for param in &self.parameters {
                lines.push(format!("  - {}", param.to_text()));
            }
            // Split parameter name tokens
            let param_tokens: Vec<String> = self
                .parameters
                .iter()
                .flat_map(|p| crate::core::identifier_splitter::split_identifier(&p.name))
                .collect();
            if !param_tokens.is_empty() {
                lines.push(format!("PARAM_TOKENS: {}", param_tokens.join(" ")));
            }
        }

        // Request body
        if let Some(rb) = &self.request_body {
            lines.push(rb.to_text());
        }

        // Auth
        if self.auth_required {
            let auth_info = self
                .auth_type
                .as_ref()
                .map(|t| t.clone())
                .unwrap_or_else(|| "required".to_string());
            lines.push(format!("AUTH: {}", auth_info));
        }

        // Risk level
        lines.push(format!("RISK: {}", self.risk_level));

        // Tags
        if !self.tags.is_empty() {
            lines.push(format!("TAGS: {}", self.tags.join(", ")));
        }

        lines.join("\n")
    }

    /// Compute SHA256 hash of the card's semantic content
    fn compute_hash(&self) -> String {
        // Create a deterministic representation for hashing
        // Exclude: embedding, content_hash itself
        let hash_content = serde_json::json!({
            "spec_id": self.spec_id,
            "operation_id": self.operation_id,
            "method": self.method,
            "path": self.path,
            "summary": self.summary,
            "description": self.description,
            "parameters": self.parameters,
            "request_body": self.request_body,
            "auth_required": self.auth_required,
            "auth_type": self.auth_type,
            "auth_scopes": self.auth_scopes,
            "risk_level": self.risk_level,
            "tags": self.tags,
        });

        let json_str = serde_json::to_string(&hash_content).unwrap_or_default();
        let mut hasher = Sha256::new();
        hasher.update(json_str.as_bytes());
        let result = hasher.finalize();
        hex::encode(result)
    }

    /// Convert to JSON (deterministic)
    pub fn to_json(&self) -> Result<String> {
        Ok(serde_json::to_string_pretty(self)?)
    }

    /// Convert to compact JSON
    pub fn to_json_compact(&self) -> Result<String> {
        Ok(serde_json::to_string(self)?)
    }
}

/// Extract authentication info from security requirements
fn extract_auth_info(
    security: Option<&Vec<SecurityRequirement>>,
    schemes: &std::collections::HashMap<String, crate::core::parser::SecurityScheme>,
) -> (bool, Option<String>, Vec<String>) {
    let Some(sec_reqs) = security else {
        return (false, None, Vec::new());
    };

    if sec_reqs.is_empty() {
        return (false, None, Vec::new());
    }

    // Get the first security requirement
    let first_req = &sec_reqs[0];
    let scheme_name = &first_req.scheme_name;
    let scopes = first_req.scopes.clone();

    // Look up the scheme type
    let auth_type = schemes
        .get(scheme_name)
        .map(|scheme| match scheme.scheme_type.as_str() {
            "http" => {
                if let Some(s) = &scheme.scheme {
                    match s.as_str() {
                        "bearer" => "Bearer Token".to_string(),
                        "basic" => "Basic Auth".to_string(),
                        _ => s.clone(),
                    }
                } else {
                    "HTTP Auth".to_string()
                }
            }
            "apiKey" => {
                let location = scheme.location.as_deref().unwrap_or("header");
                let name = scheme.name.as_deref().unwrap_or("API-Key");
                format!("API Key ({} in {})", name, location)
            }
            "oauth2" => "OAuth 2.0".to_string(),
            "openIdConnect" => "OpenID Connect".to_string(),
            _ => scheme.scheme_type.clone(),
        });

    (true, auth_type, scopes)
}

/// Extract semantic tags from the URL path
/// Generate an LLM-friendly alias from summary + tags.
///
/// Fallback chain:
///   1. tag.summaryCamelCase  → "portfolio.listTransactions"  (best)
///   2. summaryCamelCase      → "listTransactions"            (no tags)
///   3. operationId as-is     → "get_portfolio_api_..."       (no summary)
fn generate_alias(summary: &Option<String>, tags: &[String], operation_id: &str) -> String {
    let camel = match summary {
        Some(s) if !s.is_empty() => summary_to_camel_case(s),
        _ => return operation_id.to_string(), // fallback 3
    };

    if let Some(tag) = tags.first() {
        let tag_lower = tag.to_lowercase();
        // Skip tag prefix if summary already starts with the tag word
        if camel.to_lowercase().starts_with(&tag_lower) {
            camel
        } else {
            format!("{}.{}", tag_lower, camel)
        }
    } else {
        camel // fallback 2
    }
}

/// Convert a summary string like "List Transactions" → "listTransactions"
///
/// Handles: whitespace, hyphens, slashes, special chars, unicode.
/// Max length: 80 chars (truncated to last complete word boundary).
fn summary_to_camel_case(summary: &str) -> String {
    // Split on whitespace, hyphens, slashes, underscores, and other non-alphanumeric
    let words: Vec<&str> = summary
        .split(|c: char| !c.is_alphanumeric())
        .filter(|s| !s.is_empty())
        .collect();
    if words.is_empty() {
        return String::new();
    }
    let mut result = words[0].to_lowercase();
    for word in &words[1..] {
        let mut chars = word.chars();
        if let Some(first) = chars.next() {
            result.extend(first.to_uppercase());
            result.extend(chars);
        }
    }
    // Truncate to 80 chars at a word boundary (uppercase letter)
    if result.len() > 80 {
        result.truncate(80);
        // Find last uppercase letter to truncate at word boundary
        if let Some(pos) = result.rfind(|c: char| c.is_uppercase()) {
            if pos > 10 {
                result.truncate(pos);
            }
        }
    }
    result
}

fn extract_tags_from_path(path: &str) -> Vec<String> {
    path.split('/')
        .filter(|s| !s.is_empty() && !s.starts_with('{'))
        .map(|s| s.to_lowercase())
        .collect()
}

/// Summarize a schema into a concise string
fn summarize_schema(schema: &UnifiedSchema) -> String {
    match schema.schema_type {
        SchemaType::Object => {
            if let Some(props) = &schema.properties {
                let prop_names: Vec<&String> = props.keys().take(5).collect();
                let more = if props.len() > 5 {
                    format!(" +{} more", props.len() - 5)
                } else {
                    String::new()
                };
                format!(
                    "object {{ {} }}{}",
                    prop_names
                        .iter()
                        .map(|s| s.as_str())
                        .collect::<Vec<_>>()
                        .join(", "),
                    more
                )
            } else {
                "object".to_string()
            }
        }
        SchemaType::Array => {
            if let Some(items) = &schema.items {
                format!("array of {}", summarize_schema(items))
            } else {
                "array".to_string()
            }
        }
        _ => schema.schema_type.to_string(),
    }
}

/// Build operation cards from a spec
pub fn build_cards_from_spec(spec_id: &str, spec: &UnifiedSpec) -> Vec<OperationCard> {
    spec.operations
        .iter()
        .map(|op| OperationCard::from_unified(spec_id, op, spec))
        .collect()
}

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

    #[test]
    fn test_extract_tags_from_path() {
        assert_eq!(
            extract_tags_from_path("/users/{id}/orders"),
            vec!["users", "orders"]
        );
        assert_eq!(
            extract_tags_from_path("/api/v1/products"),
            vec!["api", "v1", "products"]
        );
    }

    #[test]
    fn test_risk_level_classification() {
        // Would need mock UnifiedOperation to test fully
    }

    // ========================================================================
    // summary_to_camel_case tests
    // ========================================================================

    #[test]
    fn test_camel_case_basic() {
        assert_eq!(
            summary_to_camel_case("List Transactions"),
            "listTransactions"
        );
        assert_eq!(summary_to_camel_case("Get Portfolio"), "getPortfolio");
        assert_eq!(summary_to_camel_case("Create User"), "createUser");
    }

    #[test]
    fn test_camel_case_single_word() {
        assert_eq!(summary_to_camel_case("Analyze"), "analyze");
        assert_eq!(summary_to_camel_case("Dashboard"), "dashboard");
    }

    #[test]
    fn test_camel_case_empty() {
        assert_eq!(summary_to_camel_case(""), "");
        assert_eq!(summary_to_camel_case("   "), "");
    }

    #[test]
    fn test_camel_case_special_chars() {
        assert_eq!(
            summary_to_camel_case("List/All Transactions"),
            "listAllTransactions"
        );
        assert_eq!(
            summary_to_camel_case("Get-Single-Resource"),
            "getSingleResource"
        );
        assert_eq!(
            summary_to_camel_case("Create + Update User"),
            "createUpdateUser"
        );
    }

    #[test]
    fn test_camel_case_hyphens() {
        assert_eq!(summary_to_camel_case("Get-All-Users"), "getAllUsers");
        assert_eq!(summary_to_camel_case("health-check"), "healthCheck");
    }

    #[test]
    fn test_camel_case_with_numbers() {
        assert_eq!(summary_to_camel_case("Get V2 Users"), "getV2Users");
        // "API" preserves casing after first char uppercase (A + PI)
        assert_eq!(
            summary_to_camel_case("List API v1 Endpoints"),
            "listAPIV1Endpoints"
        );
    }

    #[test]
    fn test_camel_case_truncation() {
        let long_summary = "Delete All Transactions For Ticker From Portfolio In The Given Time Range With Full Audit Trail And Compliance Checks Across Multiple Jurisdictions";
        let alias = summary_to_camel_case(long_summary);
        assert!(alias.len() <= 80, "Alias too long: {} chars", alias.len());
    }

    // ========================================================================
    // generate_alias tests
    // ========================================================================

    #[test]
    fn test_alias_with_tag_and_summary() {
        let alias = generate_alias(
            &Some("List Transactions".to_string()),
            &["portfolio".to_string()],
            "list_transactions_api_portfolio_transactions_get",
        );
        assert_eq!(alias, "portfolio.listTransactions");
    }

    #[test]
    fn test_alias_summary_starts_with_tag() {
        // Tag is "portfolio", summary starts with "Portfolio" → no prefix
        let alias = generate_alias(
            &Some("Portfolio Summary".to_string()),
            &["portfolio".to_string()],
            "portfolio_summary_get",
        );
        assert_eq!(alias, "portfolioSummary");
    }

    #[test]
    fn test_alias_no_tags() {
        let alias = generate_alias(&Some("Health Check".to_string()), &[], "health_check_get");
        assert_eq!(alias, "healthCheck");
    }

    #[test]
    fn test_alias_no_summary() {
        let alias = generate_alias(&None, &["users".to_string()], "get_users_api_users_get");
        assert_eq!(alias, "get_users_api_users_get"); // falls back to operation_id
    }

    #[test]
    fn test_alias_empty_summary() {
        let alias = generate_alias(
            &Some("".to_string()),
            &["users".to_string()],
            "get_users_api_users_get",
        );
        assert_eq!(alias, "get_users_api_users_get"); // falls back to operation_id
    }
}