fraiseql-cli 2.0.0-rc.13

CLI tools for FraiseQL v2 - Schema compilation and development utilities
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
//! Output formatting for CLI commands
//!
//! Supports three output modes:
//! - JSON: Machine-readable structured output for agents
//! - Text: Human-readable formatted output
//! - Quiet: No output (exit code only)

use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

/// Formats command output in different modes
#[derive(Debug, Clone)]
pub struct OutputFormatter {
    json_mode:  bool,
    quiet_mode: bool,
}

impl OutputFormatter {
    /// Create a new output formatter
    ///
    /// # Arguments
    /// * `json_mode` - If true, output JSON; otherwise output text
    /// * `quiet_mode` - If true and not in JSON mode, suppress all output
    pub const fn new(json_mode: bool, quiet_mode: bool) -> Self {
        Self {
            json_mode,
            quiet_mode,
        }
    }

    /// Format a command result for output
    pub fn format(&self, result: &CommandResult) -> String {
        match (self.json_mode, self.quiet_mode) {
            // JSON mode always outputs JSON regardless of quiet flag
            (true, _) => serde_json::to_string(result).unwrap_or_else(|_| {
                json!({
                    "status": "error",
                    "command": "unknown",
                    "message": "Failed to serialize response"
                })
                .to_string()
            }),
            // Quiet mode suppresses output
            (false, true) => String::new(),
            // Text mode with output
            (false, false) => Self::format_text(result),
        }
    }

    fn format_text(result: &CommandResult) -> String {
        match result.status.as_str() {
            "success" => {
                let mut output = format!("{} succeeded", result.command);

                if !result.warnings.is_empty() {
                    output.push_str("\n\nWarnings:");
                    for warning in &result.warnings {
                        output.push_str(&format!("\n{warning}"));
                    }
                }

                output
            },
            "validation-failed" => {
                let mut output = format!("{} validation failed", result.command);

                if !result.errors.is_empty() {
                    output.push_str("\n\nErrors:");
                    for error in &result.errors {
                        output.push_str(&format!("\n{error}"));
                    }
                }

                output
            },
            "error" => {
                let mut output = format!("{} error", result.command);

                if let Some(msg) = &result.message {
                    output.push_str(&format!("\n  {msg}"));
                }

                if let Some(code) = &result.code {
                    output.push_str(&format!("\n  Code: {code}"));
                }

                output
            },
            _ => format!("? {} - unknown status: {}", result.command, result.status),
        }
    }
}

/// Result of a CLI command execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandResult {
    /// Status of the command: "success", "error", "validation-failed"
    pub status: String,

    /// Name of the command that was executed
    pub command: String,

    /// Primary data/output from the command
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,

    /// Error message (if status is "error")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,

    /// Error code (if status is "error")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,

    /// Validation errors (if status is "validation-failed")
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub errors: Vec<String>,

    /// Warnings that occurred during execution
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<String>,
}

// ============================================================================
// AI Agent Introspection Types
// ============================================================================

/// Complete CLI help information for AI agents
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CliHelp {
    /// CLI name
    pub name: String,

    /// CLI version
    pub version: String,

    /// CLI description
    pub about: String,

    /// Global options available on all commands
    pub global_options: Vec<ArgumentHelp>,

    /// Available subcommands
    pub subcommands: Vec<CommandHelp>,

    /// Exit codes used by the CLI
    pub exit_codes: Vec<ExitCodeHelp>,
}

/// Help information for a single command
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandHelp {
    /// Command name
    pub name: String,

    /// Command description
    pub about: String,

    /// Positional arguments
    pub arguments: Vec<ArgumentHelp>,

    /// Optional flags and options
    pub options: Vec<ArgumentHelp>,

    /// Nested subcommands (if any)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub subcommands: Vec<CommandHelp>,

    /// Example invocations
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub examples: Vec<String>,
}

/// Help information for a single argument or option
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArgumentHelp {
    /// Argument name
    pub name: String,

    /// Short flag (e.g., "-v")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub short: Option<String>,

    /// Long flag (e.g., "--verbose")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub long: Option<String>,

    /// Help text
    pub help: String,

    /// Whether this argument is required
    pub required: bool,

    /// Default value if any
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_value: Option<String>,

    /// Whether this option takes a value
    pub takes_value: bool,

    /// Possible values (for enums/choices)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub possible_values: Vec<String>,
}

/// Exit code documentation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExitCodeHelp {
    /// Numeric exit code
    pub code: i32,

    /// Name/identifier for the code
    pub name: String,

    /// Description of when this code is returned
    pub description: String,
}

/// Output schema for a command (JSON Schema format)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutputSchema {
    /// Command this schema applies to
    pub command: String,

    /// Schema version
    pub schema_version: String,

    /// Output format (always "json")
    pub format: String,

    /// Schema for successful response
    pub success: serde_json::Value,

    /// Schema for error response
    pub error: serde_json::Value,
}

/// Summary of a command for listing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandSummary {
    /// Command name
    pub name: String,

    /// Brief description
    pub description: String,

    /// Whether this command has subcommands
    pub has_subcommands: bool,
}

/// Get the standard exit codes used by the CLI
pub fn get_exit_codes() -> Vec<ExitCodeHelp> {
    vec![
        ExitCodeHelp {
            code:        0,
            name:        "success".to_string(),
            description: "Command completed successfully".to_string(),
        },
        ExitCodeHelp {
            code:        1,
            name:        "error".to_string(),
            description: "Command failed with an error".to_string(),
        },
        ExitCodeHelp {
            code:        2,
            name:        "validation_failed".to_string(),
            description: "Validation failed (schema or input invalid)".to_string(),
        },
    ]
}

impl CommandResult {
    /// Create a successful command result with data
    pub fn success(command: &str, data: Value) -> Self {
        Self {
            status:   "success".to_string(),
            command:  command.to_string(),
            data:     Some(data),
            message:  None,
            code:     None,
            errors:   Vec::new(),
            warnings: Vec::new(),
        }
    }

    /// Create a successful command result with warnings
    pub fn success_with_warnings(command: &str, data: Value, warnings: Vec<String>) -> Self {
        Self {
            status: "success".to_string(),
            command: command.to_string(),
            data: Some(data),
            message: None,
            code: None,
            errors: Vec::new(),
            warnings,
        }
    }

    /// Create an error result
    pub fn error(command: &str, message: &str, code: &str) -> Self {
        Self {
            status:   "error".to_string(),
            command:  command.to_string(),
            data:     None,
            message:  Some(message.to_string()),
            code:     Some(code.to_string()),
            errors:   Vec::new(),
            warnings: Vec::new(),
        }
    }
}

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

    #[test]
    fn test_output_formatter_json_mode_success() {
        let formatter = OutputFormatter::new(true, false);

        let result = CommandResult::success(
            "compile",
            json!({
                "files_compiled": 2,
                "output_file": "schema.compiled.json"
            }),
        );

        let output = formatter.format(&result);
        assert!(!output.is_empty());

        // Verify it's valid JSON
        let parsed: serde_json::Value =
            serde_json::from_str(&output).expect("Output must be valid JSON");
        assert_eq!(parsed["status"], "success");
        assert_eq!(parsed["command"], "compile");
    }

    #[test]
    fn test_output_formatter_text_mode_success() {
        let formatter = OutputFormatter::new(false, false);

        let result = CommandResult::success("compile", json!({}));
        let output = formatter.format(&result);

        assert!(!output.is_empty());
        assert!(output.contains("compile"));
        assert!(output.contains(""));
    }

    #[test]
    fn test_output_formatter_quiet_mode() {
        let formatter = OutputFormatter::new(false, true);

        let result = CommandResult::success("compile", json!({}));
        let output = formatter.format(&result);

        assert_eq!(output, "");
    }

    #[test]
    fn test_output_formatter_json_mode_error() {
        let formatter = OutputFormatter::new(true, false);

        let result = CommandResult::error("compile", "Parse error", "PARSE_ERROR");

        let output = formatter.format(&result);
        assert!(!output.is_empty());

        let parsed: serde_json::Value =
            serde_json::from_str(&output).expect("Output must be valid JSON");
        assert_eq!(parsed["status"], "error");
        assert_eq!(parsed["command"], "compile");
        assert_eq!(parsed["code"], "PARSE_ERROR");
    }

    #[test]
    fn test_command_result_preserves_data() {
        let data = json!({
            "count": 42,
            "nested": {
                "value": "test"
            }
        });

        let result = CommandResult::success("test", data.clone());

        // Data should be preserved exactly
        assert_eq!(result.data, Some(data));
    }

    #[test]
    fn test_output_formatter_with_warnings() {
        let formatter = OutputFormatter::new(true, false);

        let result = CommandResult::success_with_warnings(
            "compile",
            json!({ "status": "ok" }),
            vec!["Optimization opportunity: add index to User.id".to_string()],
        );

        let output = formatter.format(&result);
        let parsed: serde_json::Value = serde_json::from_str(&output).expect("Valid JSON");

        assert_eq!(parsed["status"], "success");
        assert!(parsed["warnings"].is_array());
    }

    #[test]
    fn test_text_mode_shows_status() {
        let formatter = OutputFormatter::new(false, false);

        let result = CommandResult::success("compile", json!({}));
        let output = formatter.format(&result);

        // Should contain some indication of success
        assert!(output.to_lowercase().contains("success") || output.contains(""));
    }

    #[test]
    fn test_text_mode_shows_error() {
        let formatter = OutputFormatter::new(false, false);

        let result = CommandResult::error("compile", "File not found", "FILE_NOT_FOUND");
        let output = formatter.format(&result);

        assert!(
            output.to_lowercase().contains("error")
                || output.contains("")
                || output.contains("file")
        );
    }

    #[test]
    fn test_quiet_mode_suppresses_all_output() {
        let formatter = OutputFormatter::new(false, true);

        let success = CommandResult::success("compile", json!({}));
        let error = CommandResult::error("validate", "Invalid", "INVALID");

        assert_eq!(formatter.format(&success), "");
        assert_eq!(formatter.format(&error), "");
    }

    #[test]
    fn test_json_mode_ignores_quiet_flag() {
        // JSON mode should always output JSON, even with quiet=true
        let formatter = OutputFormatter::new(true, true);

        let result = CommandResult::success("compile", json!({}));
        let output = formatter.format(&result);

        // Should still produce JSON
        let parsed: serde_json::Value =
            serde_json::from_str(&output).expect("Should be valid JSON");
        assert_eq!(parsed["status"], "success");
    }
}