aprender-orchestrate 0.31.2

Sovereign AI orchestration: autonomous agents, ML serving, code analysis, and transpilation pipelines
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
//! Display and formatting functions for PMAT Query results.

use crate::ansi_colors::Colorize;

use super::pmat_query_fusion::{compute_quality_summary, format_summary_line};
use super::pmat_query_types::{FusedResult, PmatQueryResult};
use crate::cli::oracle::types::OracleOutputFormat;

/// Parse `pmat query` JSON output into structured results.
pub(super) fn parse_pmat_query_output(json: &str) -> anyhow::Result<Vec<PmatQueryResult>> {
    let results: Vec<PmatQueryResult> = serde_json::from_str(json)
        .map_err(|e| anyhow::anyhow!("Failed to parse pmat query output: {e}"))?;
    Ok(results)
}

/// Invoke `pmat query` and return parsed results.
pub(super) fn run_pmat_query(
    opts: &super::pmat_query_types::PmatQueryOptions,
) -> anyhow::Result<Vec<PmatQueryResult>> {
    use super::pmat_query_cache::{load_cached_results, save_cache};

    // Check cache first
    if let Some(cached) = load_cached_results(&opts.query, opts.project_path.as_deref()) {
        eprintln!("  {} hit \u{2014} using cached results", "[   cache]".dimmed());
        return Ok(cached);
    }

    let limit_str = opts.limit.to_string();
    let mut args: Vec<&str> = vec!["query", &opts.query, "--format", "json", "--limit", &limit_str];

    let grade_val;
    if let Some(ref grade) = opts.min_grade {
        grade_val = grade.clone();
        args.push("--min-grade");
        args.push(&grade_val);
    }

    let complexity_str;
    if let Some(max) = opts.max_complexity {
        complexity_str = max.to_string();
        args.push("--max-complexity");
        args.push(&complexity_str);
    }

    if opts.include_source {
        args.push("--include-source");
    }

    let working_dir = opts.project_path.as_ref().map(std::path::Path::new);
    let output = crate::tools::run_tool("pmat", &args, working_dir)?;
    let results = parse_pmat_query_output(&output)?;

    // Save to cache
    save_cache(&opts.query, opts.project_path.as_deref(), &results);

    Ok(results)
}

/// Grade badge with color.
pub(super) fn grade_badge(grade: &str) -> String {
    match grade {
        "A" => format!("[{}]", "A".bright_green().bold()),
        "B" => format!("[{}]", "B".green()),
        "C" => format!("[{}]", "C".bright_yellow()),
        "D" => format!("[{}]", "D".yellow()),
        "F" => format!("[{}]", "F".bright_red().bold()),
        other => format!("[{}]", other.dimmed()),
    }
}

/// Score bar for TDG score (0-100 scale).
pub(super) fn tdg_score_bar(score: f64, width: usize) -> String {
    let filled = ((score / 100.0) * width as f64).round() as usize;
    let empty = width.saturating_sub(filled);
    format!("{}{} {:.1}", "\u{2588}".repeat(filled), "\u{2591}".repeat(empty), score)
}

/// Print quality summary line in text mode.
fn print_quality_summary(results: &[PmatQueryResult]) {
    if results.is_empty() {
        return;
    }
    let summary = compute_quality_summary(results);
    println!("{}: {}", "Summary".bright_yellow().bold(), format_summary_line(&summary));
    println!();
}

/// Format results as colored text.
fn pmat_format_results_text(query_text: &str, results: &[PmatQueryResult]) {
    println!("{}: {}", "PMAT Query".bright_cyan(), query_text);
    println!("{}", "\u{2500}".repeat(50).dimmed());
    println!();

    for (i, r) in results.iter().enumerate() {
        let badge = grade_badge(&r.tdg_grade);
        let score_bar = tdg_score_bar(r.tdg_score, 10);
        let project_prefix =
            r.project.as_ref().map(|p| format!("[{}] ", p.bright_blue())).unwrap_or_default();
        println!(
            "{}. {} {}{}:{}  {}          {}",
            i + 1,
            badge,
            project_prefix,
            r.file_path.cyan(),
            r.start_line,
            r.function_name.bright_yellow(),
            score_bar
        );
        if !r.signature.is_empty() {
            println!("   {}", r.signature.dimmed());
        }
        println!("   Complexity: {} | Big-O: {} | SATD: {}", r.complexity, r.big_o, r.satd_count);
        if let Some(ref doc) = r.doc_comment {
            let preview: String = doc.chars().take(120).collect();
            println!("   {}", preview.dimmed());
        }
        if !r.rag_backlinks.is_empty() {
            println!("   {} {}", "See also:".bright_green(), r.rag_backlinks.join(", ").dimmed());
        }
        if let Some(ref src) = r.source {
            println!("   {}", "\u{2500}".repeat(40).dimmed());
            for line in src.lines().take(10) {
                #[cfg(feature = "syntect")]
                crate::cli::syntax::print_highlighted_line(
                    line,
                    crate::cli::syntax::Language::Rust,
                    "   ",
                );
                #[cfg(not(feature = "syntect"))]
                println!("   {}", line);
            }
            if src.lines().count() > 10 {
                println!("   {}", "...".dimmed());
            }
        }
        println!();
    }

    print_quality_summary(results);
}

/// Format results as JSON with query metadata envelope.
fn pmat_format_results_json(query_text: &str, results: &[PmatQueryResult]) -> anyhow::Result<()> {
    let summary = compute_quality_summary(results);
    let json = serde_json::json!({
        "query": query_text,
        "source": "pmat",
        "result_count": results.len(),
        "summary": {
            "grades": summary.grades,
            "avg_complexity": summary.avg_complexity,
            "total_satd": summary.total_satd,
            "complexity_range": [summary.complexity_range.0, summary.complexity_range.1],
        },
        "results": results,
    });
    println!("{}", serde_json::to_string_pretty(&json)?);
    Ok(())
}

/// Format results as a markdown table.
fn pmat_format_results_markdown(query_text: &str, results: &[PmatQueryResult]) {
    println!("## PMAT Query Results\n");
    println!("**Query:** {}\n", query_text);
    println!("| # | Grade | File | Function | TDG | Complexity | Big-O |");
    println!("|---|-------|------|----------|-----|------------|-------|");
    for (i, r) in results.iter().enumerate() {
        println!(
            "| {} | {} | {}:{} | `{}` | {:.1} | {} | {} |",
            i + 1,
            r.tdg_grade,
            r.file_path,
            r.start_line,
            r.function_name,
            r.tdg_score,
            r.complexity,
            r.big_o
        );
    }
    let summary = compute_quality_summary(results);
    println!("\n**Summary:** {}", format_summary_line(&summary));
}

/// Display results in the requested format.
pub(super) fn pmat_display_results(
    query_text: &str,
    results: &[PmatQueryResult],
    format: OracleOutputFormat,
) -> anyhow::Result<()> {
    match format {
        OracleOutputFormat::Json => pmat_format_results_json(query_text, results)?,
        OracleOutputFormat::Markdown => pmat_format_results_markdown(query_text, results),
        OracleOutputFormat::Text => pmat_format_results_text(query_text, results),
        OracleOutputFormat::Code | OracleOutputFormat::CodeSvg => {
            for r in results {
                if let Some(ref src) = r.source {
                    println!("// {}:{} - {}", r.file_path, r.start_line, r.function_name);
                    println!("{}", src);
                    println!();
                }
            }
            if results.iter().all(|r| r.source.is_none()) {
                eprintln!("No source code in results (try --pmat-include-source)");
                std::process::exit(1);
            }
        }
    }
    Ok(())
}

/// Display RRF-fused combined PMAT + RAG results.
pub(super) fn pmat_display_combined(
    query_text: &str,
    pmat_results: &[PmatQueryResult],
    rag_results: &[crate::oracle::rag::RetrievalResult],
    format: OracleOutputFormat,
) -> anyhow::Result<()> {
    use super::pmat_query_fusion::rrf_fuse_results;

    let fused = rrf_fuse_results(pmat_results, rag_results, 20);

    match format {
        OracleOutputFormat::Json => display_combined_json(query_text, pmat_results, &fused)?,
        OracleOutputFormat::Markdown => {
            display_combined_markdown(query_text, pmat_results, &fused);
        }
        OracleOutputFormat::Text => display_combined_text(pmat_results, &fused),
        OracleOutputFormat::Code | OracleOutputFormat::CodeSvg => display_combined_code(&fused),
    }
    Ok(())
}

fn display_combined_json(
    query_text: &str,
    pmat_results: &[PmatQueryResult],
    fused: &[(FusedResult, f64)],
) -> anyhow::Result<()> {
    let summary = compute_quality_summary(pmat_results);
    let json = serde_json::json!({
        "query": query_text,
        "mode": "rrf_fused",
        "k": 60,
        "result_count": fused.len(),
        "summary": {
            "grades": summary.grades,
            "avg_complexity": summary.avg_complexity,
            "total_satd": summary.total_satd,
            "complexity_range": [summary.complexity_range.0, summary.complexity_range.1],
        },
        "results": fused.iter().map(|(item, score)| {
            let mut v = serde_json::to_value(item).unwrap_or_default();
            if let Some(obj) = v.as_object_mut() {
                obj.insert("rrf_score".to_string(), serde_json::json!(score));
            }
            v
        }).collect::<Vec<_>>(),
    });
    println!("{}", serde_json::to_string_pretty(&json)?);
    Ok(())
}

fn display_combined_markdown(
    query_text: &str,
    pmat_results: &[PmatQueryResult],
    fused: &[(FusedResult, f64)],
) {
    println!("## Combined PMAT + RAG Results (RRF-fused)\n");
    println!("**Query:** {}\n", query_text);
    println!("| # | Type | Source | Score |");
    println!("|---|------|--------|-------|");
    for (i, (item, score)) in fused.iter().enumerate() {
        match item {
            FusedResult::Function(r) => {
                println!(
                    "| {} | fn | {}:{} `{}` [{}] | {:.3} |",
                    i + 1,
                    r.file_path,
                    r.start_line,
                    r.function_name,
                    r.tdg_grade,
                    score
                );
            }
            FusedResult::Document { component, source, .. } => {
                println!("| {} | doc | [{}] {} | {:.3} |", i + 1, component, source, score);
            }
        }
    }
    let summary = compute_quality_summary(pmat_results);
    println!("\n**Summary (functions):** {}", format_summary_line(&summary));
}

fn display_combined_text(pmat_results: &[PmatQueryResult], fused: &[(FusedResult, f64)]) {
    println!("{} (RRF k=60)", "Combined Search".bright_cyan().bold());
    println!("{}", "\u{2500}".repeat(50).dimmed());
    println!();

    for (i, (item, score)) in fused.iter().enumerate() {
        display_combined_text_item(i, item, *score);
    }

    print_quality_summary(pmat_results);
}

fn display_combined_text_item(i: usize, item: &FusedResult, score: f64) {
    let score_pct = (score * 100.0) as usize;
    let bar_filled = (score * 10.0).round() as usize;
    let bar_empty = 10_usize.saturating_sub(bar_filled);
    let bar = format!(
        "{}{} {:3}%",
        "\u{2588}".repeat(bar_filled),
        "\u{2591}".repeat(bar_empty),
        score_pct,
    );

    match item {
        FusedResult::Function(r) => {
            let badge = grade_badge(&r.tdg_grade);
            let project_prefix =
                r.project.as_ref().map(|p| format!("[{}] ", p.bright_blue())).unwrap_or_default();
            println!(
                "{}. {} {} {}{}:{}  {}  {}",
                i + 1,
                "[fn]".bright_cyan(),
                badge,
                project_prefix,
                r.file_path.cyan(),
                r.start_line,
                r.function_name.bright_yellow(),
                bar,
            );
            println!(
                "   Complexity: {} | Big-O: {} | SATD: {}",
                r.complexity, r.big_o, r.satd_count
            );
            if !r.rag_backlinks.is_empty() {
                println!(
                    "   {} {}",
                    "See also:".bright_green(),
                    r.rag_backlinks.join(", ").dimmed()
                );
            }
        }
        FusedResult::Document { component, source, content, .. } => {
            println!(
                "{}. {} [{}] {} {}",
                i + 1,
                "[doc]".bright_green(),
                component.bright_yellow(),
                source.dimmed(),
                bar,
            );
            if !content.is_empty() {
                let preview: String = content.chars().take(200).collect();
                println!("   {}", preview.dimmed());
            }
        }
    }
    println!();
}

fn display_combined_code(fused: &[(FusedResult, f64)]) {
    for (item, _) in fused {
        if let FusedResult::Function(r) = item {
            if let Some(ref src) = r.source {
                println!("// {}:{} - {}", r.file_path, r.start_line, r.function_name);
                println!("{}", src);
                println!();
            }
        }
    }
    let has_source = fused
        .iter()
        .any(|(item, _)| matches!(item, FusedResult::Function(r) if r.source.is_some()));
    if !has_source {
        eprintln!("No source code in results (try --pmat-include-source)");
        std::process::exit(1);
    }
}

/// Show usage hint when no query is provided.
pub(super) fn show_pmat_query_usage() {
    println!("{}", "Usage: batuta oracle --pmat-query \"your query here\"".dimmed());
    println!();
    println!("{}", "Examples:".bright_yellow());
    println!("  {} {}", "batuta oracle --pmat-query".cyan(), "\"error handling\"".dimmed());
    println!(
        "  {} {}",
        "batuta oracle --pmat-query".cyan(),
        "\"serialize\" --pmat-min-grade A".dimmed()
    );
    println!(
        "  {} {}",
        "batuta oracle --pmat-query".cyan(),
        "\"allocator\" --pmat-include-source --format json".dimmed()
    );
    println!(
        "  {} {}",
        "batuta oracle --pmat-query".cyan(),
        "\"cache\" --rag  # combined RRF-fused search".dimmed()
    );
    println!(
        "  {} {}",
        "batuta oracle --pmat-query".cyan(),
        "\"tokenizer\" --pmat-all-local  # search all projects".dimmed()
    );
}