Skip to main content

lean_ctx/core/ocla/reference_adapters/
report.rs

1//! Fixture loader, deterministic comparison runner, and report serializers.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::fmt::Write as _;
5use std::fs;
6use std::io;
7use std::path::{Path, PathBuf};
8
9use serde::{Deserialize, Serialize};
10use thiserror::Error;
11
12use super::super::invocation::{CAPABILITY_OBSERVATION_SCHEMA_VERSION, CapabilityObservationV1};
13use super::comparison_receipt::{
14    ComparisonDecision, ComparisonReceipt, QualityCheck, decide, evaluate_quality,
15};
16
17/// Number of fixtures in the public Sprint 4 corpus.
18pub const EXPECTED_FIXTURE_COUNT: usize = 30;
19
20/// Metadata required for one shell-output fixture.
21#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
22#[serde(deny_unknown_fields)]
23pub struct FixtureMetadata {
24    pub command: String,
25    pub working_dir: String,
26    pub expected_tokens: u64,
27    pub category: String,
28}
29
30/// Raw fixture data after loading and validation.
31#[derive(Clone, Debug, Eq, PartialEq)]
32pub struct FixtureInput {
33    pub name: String,
34    pub metadata: FixtureMetadata,
35    pub input: String,
36    pub input_path: PathBuf,
37    pub metadata_path: PathBuf,
38}
39
40/// One workload and its payload-free comparison receipt.
41#[derive(Clone, Debug, Serialize)]
42pub struct WorkloadComparison {
43    pub name: String,
44    pub category: String,
45    pub command: String,
46    pub receipt: ComparisonReceipt,
47}
48
49/// Per-category wins, losses, ties, and token accounting.
50#[derive(Clone, Debug, Default, Serialize)]
51pub struct CategorySummary {
52    pub category: String,
53    pub external_wins: u64,
54    pub native_wins: u64,
55    pub ties: u64,
56    pub external_unavailable: u64,
57    pub native_tokens: u64,
58    pub external_tokens: u64,
59    pub token_savings: u64,
60    pub token_overhead: u64,
61    pub net_token_delta: i64,
62}
63
64impl CategorySummary {
65    fn new(category: &str) -> Self {
66        Self {
67            category: category.to_string(),
68            ..Self::default()
69        }
70    }
71
72    fn record(&mut self, receipt: &ComparisonReceipt) {
73        self.native_tokens = self.native_tokens.saturating_add(receipt.native_tokens);
74        match receipt.decision {
75            ComparisonDecision::ExternalPreferred { .. } => self.external_wins += 1,
76            ComparisonDecision::NativePreferred { .. } => self.native_wins += 1,
77            ComparisonDecision::Inconclusive { .. } => self.ties += 1,
78            ComparisonDecision::ExternalUnavailable => self.external_unavailable += 1,
79        }
80
81        if let Some(external_tokens) = receipt.external_tokens {
82            self.external_tokens = self.external_tokens.saturating_add(external_tokens);
83            let delta = receipt.native_tokens as i64 - external_tokens as i64;
84            self.net_token_delta = self.net_token_delta.saturating_add(delta);
85            if delta >= 0 {
86                self.token_savings = self.token_savings.saturating_add(delta as u64);
87            } else {
88                self.token_overhead = self.token_overhead.saturating_add(delta.unsigned_abs());
89            }
90        }
91    }
92}
93
94/// Aggregate token savings and overhead across all compared workloads.
95#[derive(Clone, Debug, Default, Serialize)]
96pub struct AggregateTokenStats {
97    pub native_tokens: u64,
98    pub external_tokens: u64,
99    pub token_savings: u64,
100    pub token_overhead: u64,
101    pub net_token_delta: i64,
102    pub savings_percent: f64,
103    pub external_unavailable: u64,
104}
105
106/// Structured comparison report exported by the reference-adapter runner.
107#[derive(Clone, Debug, Serialize)]
108pub struct ComparisonReport {
109    pub fixture_count: usize,
110    pub workloads: Vec<WorkloadComparison>,
111    pub categories: BTreeMap<String, CategorySummary>,
112    pub external_preferred_workloads: Vec<String>,
113    pub native_preferred_workloads: Vec<String>,
114    pub aggregate: AggregateTokenStats,
115}
116
117impl ComparisonReport {
118    /// Serialize this report as readable, structured JSON.
119    pub fn to_json(&self) -> Result<String, ReportError> {
120        serde_json::to_string_pretty(self).map_err(|source| ReportError::Serialization { source })
121    }
122
123    /// Render a stable human-readable report with summary and workload tables.
124    #[must_use]
125    pub fn to_text(&self) -> String {
126        let mut output = String::new();
127        output.push_str("# RTK v1 Capability Comparison\n\n");
128        output.push_str(&format!("Fixtures compared: {}\n\n", self.fixture_count));
129        output.push_str("## Category summary\n\n");
130        output.push_str(
131            "| Category | RTK wins | Native wins | Ties | Unavailable | Native tokens | RTK tokens |\n",
132        );
133        output.push_str("|---|---:|---:|---:|---:|---:|---:|\n");
134        for summary in self.categories.values() {
135            output.push_str(&format!(
136                "| {} | {} | {} | {} | {} | {} | {} |\n",
137                summary.category,
138                summary.external_wins,
139                summary.native_wins,
140                summary.ties,
141                summary.external_unavailable,
142                summary.native_tokens,
143                summary.external_tokens,
144            ));
145        }
146
147        output.push_str("\n## Aggregate token accounting\n\n");
148        output.push_str(&format!(
149            "- Native output tokens: {}\n- RTK output tokens: {}\n- Token savings: {}\n- Token overhead: {}\n- Net token savings: {}\n- Savings rate: {:.1}%\n",
150            self.aggregate.native_tokens,
151            self.aggregate.external_tokens,
152            self.aggregate.token_savings,
153            self.aggregate.token_overhead,
154            self.aggregate.net_token_delta,
155            self.aggregate.savings_percent,
156        ));
157
158        output.push_str("\n## RTK-preferred workloads\n\n");
159        append_workload_list(&mut output, &self.external_preferred_workloads);
160        output.push_str("\n## Native-preferred workloads\n\n");
161        append_workload_list(&mut output, &self.native_preferred_workloads);
162
163        output.push_str("\n## Workload details\n\n");
164        output.push_str("| Workload | Decision | Native | RTK | Delta | Quality |\n");
165        output.push_str("|---|---|---:|---:|---:|---|\n");
166        for workload in &self.workloads {
167            let receipt = &workload.receipt;
168            let external_tokens = receipt
169                .external_tokens
170                .map_or_else(|| "—".to_string(), |value| value.to_string());
171            let delta = receipt
172                .token_delta()
173                .map_or_else(|| "—".to_string(), |value| value.to_string());
174            output.push_str(&format!(
175                "| {}/{} | {} | {} | {} | {} | {} |\n",
176                workload.category,
177                workload.name,
178                receipt.decision.label(),
179                receipt.native_tokens,
180                external_tokens,
181                delta,
182                quality_label(&receipt.quality_check),
183            ));
184        }
185
186        output
187    }
188}
189
190/// Errors returned while loading fixtures or exporting a report.
191#[derive(Debug, Error)]
192pub enum ReportError {
193    #[error("I/O error at {path}: {source}")]
194    Io {
195        path: PathBuf,
196        #[source]
197        source: io::Error,
198    },
199    #[error("metadata at {path} is invalid: {source}")]
200    Metadata {
201        path: PathBuf,
202        #[source]
203        source: serde_json::Error,
204    },
205    #[error("fixture at {path} is invalid: {reason}")]
206    InvalidFixture { path: PathBuf, reason: String },
207    #[error("expected {expected} fixtures, found {actual}")]
208    FixtureCount { expected: usize, actual: usize },
209    #[error("could not serialize comparison report: {source}")]
210    Serialization {
211        #[source]
212        source: serde_json::Error,
213    },
214}
215
216/// Load, sort, and validate every fixture below a category-root directory.
217pub fn load_fixtures(root: impl AsRef<Path>) -> Result<Vec<FixtureInput>, ReportError> {
218    let root = root.as_ref();
219    let mut fixtures = Vec::new();
220
221    for category_path in sorted_directories(root)? {
222        let category = category_path
223            .file_name()
224            .and_then(|name| name.to_str())
225            .ok_or_else(|| ReportError::InvalidFixture {
226                path: category_path.clone(),
227                reason: "category directory name is not valid UTF-8".to_string(),
228            })?
229            .to_string();
230
231        for fixture_path in sorted_directories(&category_path)? {
232            let name = fixture_path
233                .file_name()
234                .and_then(|name| name.to_str())
235                .ok_or_else(|| ReportError::InvalidFixture {
236                    path: fixture_path.clone(),
237                    reason: "fixture directory name is not valid UTF-8".to_string(),
238                })?
239                .to_string();
240            let input_path = fixture_path.join("input.txt");
241            let metadata_path = fixture_path.join("metadata.json");
242            let input = fs::read_to_string(&input_path).map_err(|source| ReportError::Io {
243                path: input_path.clone(),
244                source,
245            })?;
246            let metadata_body =
247                fs::read_to_string(&metadata_path).map_err(|source| ReportError::Io {
248                    path: metadata_path.clone(),
249                    source,
250                })?;
251            let metadata =
252                serde_json::from_str::<FixtureMetadata>(&metadata_body).map_err(|source| {
253                    ReportError::Metadata {
254                        path: metadata_path.clone(),
255                        source,
256                    }
257                })?;
258
259            validate_fixture(&category, &name, &input, &metadata, &fixture_path)?;
260            fixtures.push(FixtureInput {
261                name,
262                metadata,
263                input,
264                input_path,
265                metadata_path,
266            });
267        }
268    }
269
270    Ok(fixtures)
271}
272
273/// Generate the Sprint 4 report and require all 30 public fixtures.
274pub fn generate_report(root: impl AsRef<Path>) -> Result<ComparisonReport, ReportError> {
275    let fixtures = load_fixtures(root)?;
276    if fixtures.len() != EXPECTED_FIXTURE_COUNT {
277        return Err(ReportError::FixtureCount {
278            expected: EXPECTED_FIXTURE_COUNT,
279            actual: fixtures.len(),
280        });
281    }
282    Ok(generate_from_fixtures(&fixtures))
283}
284
285/// Alias emphasizing that this report is the internal comparison artifact.
286pub fn generate_comparison_report(root: impl AsRef<Path>) -> Result<ComparisonReport, ReportError> {
287    generate_report(root)
288}
289
290/// Generate a report from already-loaded fixture data.
291#[must_use]
292pub fn generate_from_fixtures(fixtures: &[FixtureInput]) -> ComparisonReport {
293    let mut workloads: Vec<_> = fixtures.iter().map(compare_fixture).collect();
294    workloads.sort_by(|left, right| {
295        left.category
296            .cmp(&right.category)
297            .then_with(|| left.name.cmp(&right.name))
298    });
299
300    let mut categories = BTreeMap::new();
301    let mut external_preferred_workloads = Vec::new();
302    let mut native_preferred_workloads = Vec::new();
303    let mut aggregate = AggregateTokenStats::default();
304
305    for workload in &workloads {
306        let summary = categories
307            .entry(workload.category.clone())
308            .or_insert_with(|| CategorySummary::new(&workload.category));
309        summary.record(&workload.receipt);
310        aggregate.native_tokens = aggregate
311            .native_tokens
312            .saturating_add(workload.receipt.native_tokens);
313
314        let workload_id = format!("{}/{}", workload.category, workload.name);
315        match workload.receipt.decision {
316            ComparisonDecision::ExternalPreferred { .. } => {
317                external_preferred_workloads.push(workload_id);
318            }
319            ComparisonDecision::NativePreferred { .. } => {
320                native_preferred_workloads.push(workload_id);
321            }
322            ComparisonDecision::Inconclusive { .. } | ComparisonDecision::ExternalUnavailable => {}
323        }
324
325        if let Some(external_tokens) = workload.receipt.external_tokens {
326            aggregate.external_tokens = aggregate.external_tokens.saturating_add(external_tokens);
327            let delta = workload.receipt.native_tokens as i64 - external_tokens as i64;
328            aggregate.net_token_delta = aggregate.net_token_delta.saturating_add(delta);
329            if delta >= 0 {
330                aggregate.token_savings = aggregate.token_savings.saturating_add(delta as u64);
331            } else {
332                aggregate.token_overhead = aggregate
333                    .token_overhead
334                    .saturating_add(delta.unsigned_abs());
335            }
336        } else {
337            aggregate.external_unavailable += 1;
338        }
339    }
340
341    aggregate.savings_percent = if aggregate.native_tokens == 0 {
342        0.0
343    } else {
344        aggregate.net_token_delta as f64 / aggregate.native_tokens as f64 * 100.0
345    };
346
347    ComparisonReport {
348        fixture_count: workloads.len(),
349        workloads,
350        categories,
351        external_preferred_workloads,
352        native_preferred_workloads,
353        aggregate,
354    }
355}
356
357/// Export a structured JSON report to `path`.
358pub fn write_json(report: &ComparisonReport, path: impl AsRef<Path>) -> Result<(), ReportError> {
359    let path = path.as_ref();
360    let body = report.to_json()?;
361    fs::write(path, body).map_err(|source| ReportError::Io {
362        path: path.to_path_buf(),
363        source,
364    })
365}
366
367/// Export a human-readable report to `path`.
368pub fn write_text(report: &ComparisonReport, path: impl AsRef<Path>) -> Result<(), ReportError> {
369    let path = path.as_ref();
370    fs::write(path, report.to_text()).map_err(|source| ReportError::Io {
371        path: path.to_path_buf(),
372        source,
373    })
374}
375
376fn sorted_directories(path: &Path) -> Result<Vec<PathBuf>, ReportError> {
377    let mut directories = Vec::new();
378    for entry in fs::read_dir(path).map_err(|source| ReportError::Io {
379        path: path.to_path_buf(),
380        source,
381    })? {
382        let entry = entry.map_err(|source| ReportError::Io {
383            path: path.to_path_buf(),
384            source,
385        })?;
386        let entry_path = entry.path();
387        if entry
388            .file_type()
389            .map_err(|source| ReportError::Io {
390                path: entry_path.clone(),
391                source,
392            })?
393            .is_dir()
394        {
395            directories.push(entry_path);
396        }
397    }
398    directories.sort();
399    Ok(directories)
400}
401
402fn validate_fixture(
403    category: &str,
404    name: &str,
405    input: &str,
406    metadata: &FixtureMetadata,
407    fixture_path: &Path,
408) -> Result<(), ReportError> {
409    let invalid = |reason: &str| ReportError::InvalidFixture {
410        path: fixture_path.to_path_buf(),
411        reason: reason.to_string(),
412    };
413
414    if metadata.command.trim().is_empty() {
415        return Err(invalid("command must not be empty"));
416    }
417    if metadata.working_dir.trim().is_empty() {
418        return Err(invalid("working_dir must not be empty"));
419    }
420    if metadata.expected_tokens == 0 {
421        return Err(invalid("expected_tokens must be greater than zero"));
422    }
423    if metadata.category != category {
424        return Err(invalid("metadata category does not match its directory"));
425    }
426    let non_whitespace = input
427        .chars()
428        .filter(|character| !character.is_whitespace())
429        .count();
430    if non_whitespace < 20 || input.lines().count() < 2 {
431        return Err(invalid("input.txt must contain realistic non-empty output"));
432    }
433    if input.contains("[placeholder]") || input.contains("<placeholder>") {
434        return Err(invalid("input.txt contains placeholder data"));
435    }
436    if name.trim().is_empty() {
437        return Err(invalid("fixture directory name must not be empty"));
438    }
439    Ok(())
440}
441
442fn compare_fixture(fixture: &FixtureInput) -> WorkloadComparison {
443    let task_id = format!(
444        "capability-comparison/{}/{}",
445        fixture.metadata.category, fixture.name
446    );
447    let line_count = fixture.input.lines().count() as u64;
448    let unique_line_count = fixture
449        .input
450        .lines()
451        .map(str::trim)
452        .collect::<BTreeSet<_>>()
453        .len() as u64;
454    let input_bytes = fixture.input.len() as u64;
455    let input_tokens = ceil_div(
456        (fixture.metadata.command.len() + fixture.metadata.working_dir.len()) as u64,
457        4,
458    );
459    let native_tokens = fixture.metadata.expected_tokens;
460    let external_tokens =
461        estimate_external_tokens(native_tokens, line_count, unique_line_count, input_bytes);
462    let external_quality_score = estimate_quality_score(
463        &fixture.metadata.category,
464        &fixture.metadata.command,
465        &fixture.input,
466    );
467    let native_observation = observation(
468        &task_id,
469        "native.shell",
470        "v1",
471        input_tokens,
472        native_tokens,
473        native_latency_ms(input_bytes),
474        100,
475        line_count,
476        unique_line_count,
477        input_bytes,
478        "native",
479    );
480    let external_observation = observation(
481        &task_id,
482        "rtk.shell",
483        "v1",
484        input_tokens,
485        external_tokens,
486        external_latency_ms(external_tokens),
487        external_quality_score,
488        line_count,
489        unique_line_count,
490        input_bytes,
491        "external",
492    );
493    let quality_check = evaluate_quality(&native_observation, Some(&external_observation));
494    let decision = decide(native_tokens, Some(external_tokens), &quality_check);
495    let receipt = ComparisonReceipt::new(
496        task_id,
497        native_observation,
498        Some(external_observation),
499        decision,
500        quality_check,
501    );
502
503    WorkloadComparison {
504        name: fixture.name.clone(),
505        category: fixture.metadata.category.clone(),
506        command: fixture.metadata.command.clone(),
507        receipt,
508    }
509}
510
511#[allow(clippy::too_many_arguments)]
512fn observation(
513    task_id: &str,
514    capability_id: &str,
515    capability_version: &str,
516    input_tokens: u64,
517    output_tokens: u64,
518    latency_ms: u64,
519    quality_score: u64,
520    line_count: u64,
521    unique_line_count: u64,
522    input_bytes: u64,
523    arm: &str,
524) -> CapabilityObservationV1 {
525    let mut metrics = BTreeMap::new();
526    metrics.insert("quality_score".to_string(), quality_score);
527    metrics.insert("line_count".to_string(), line_count);
528    metrics.insert("unique_line_count".to_string(), unique_line_count);
529    metrics.insert("input_bytes".to_string(), input_bytes);
530
531    CapabilityObservationV1 {
532        schema_version: CAPABILITY_OBSERVATION_SCHEMA_VERSION,
533        task_id: task_id.to_string(),
534        capability_id: capability_id.to_string(),
535        capability_version: capability_version.to_string(),
536        success: true,
537        input_tokens,
538        output_tokens,
539        latency_ms,
540        failure_mode: None,
541        output_ref: Some(format!("fixture:{task_id}:{arm}")),
542        metrics,
543    }
544}
545
546fn estimate_external_tokens(
547    native_tokens: u64,
548    line_count: u64,
549    unique_line_count: u64,
550    input_bytes: u64,
551) -> u64 {
552    let repetition = if line_count == 0 {
553        0.0
554    } else {
555        1.0 - unique_line_count as f64 / line_count as f64
556    };
557    let ratio = if line_count <= 7 && repetition < 0.15 {
558        1.18
559    } else if repetition > 0.30 {
560        0.58
561    } else if input_bytes > 1_600 {
562        0.68
563    } else if line_count > 14 {
564        0.82
565    } else {
566        0.94
567    };
568    let overhead = if ratio > 1.0 { 6 } else { 4 };
569    ((native_tokens as f64 * ratio).round() as u64)
570        .saturating_add(overhead)
571        .max(1)
572}
573
574fn estimate_quality_score(category: &str, command: &str, input: &str) -> u64 {
575    if category == "test"
576        && command.contains("pytest")
577        && input.contains("FAILED")
578        && input.contains("AssertionError")
579    {
580        return 86;
581    }
582
583    let markers: &[&str] = match category {
584        "git" => &[
585            "On branch",
586            "nothing to commit",
587            "commit ",
588            "diff --git",
589            "@@ ",
590            "Author:",
591            "Date:",
592            "modified:",
593            "index ",
594        ],
595        "test" => &[
596            "test result:",
597            "PASSED",
598            "FAILED",
599            "PASS",
600            "FAIL",
601            "ok ",
602            "running ",
603            "Tests:",
604            "Test Suites:",
605            "=== RUN",
606            "error:",
607        ],
608        "structured" => &[
609            "total ",
610            "drwx",
611            "./",
612            "CONTAINER ID",
613            "NAME ",
614            "READY",
615            "package",
616            "├──",
617            "├─┬",
618        ],
619        _ => &[],
620    };
621    let present = markers
622        .iter()
623        .filter(|marker| input.contains(**marker))
624        .count();
625    match present {
626        0 => 65,
627        1 => 96,
628        _ => 100,
629    }
630}
631
632fn native_latency_ms(input_bytes: u64) -> u64 {
633    (input_bytes / 180).saturating_add(1).max(1)
634}
635
636fn external_latency_ms(external_tokens: u64) -> u64 {
637    (external_tokens / 80).saturating_add(2).max(1)
638}
639
640fn ceil_div(value: u64, divisor: u64) -> u64 {
641    value.saturating_add(divisor.saturating_sub(1)) / divisor
642}
643
644fn quality_label(quality_check: &QualityCheck) -> &'static str {
645    match quality_check {
646        QualityCheck::StructurallyEquivalent => "equivalent",
647        QualityCheck::QualityFloorFailed => "floor_failed",
648        QualityCheck::InformationLoss { .. } => "information_loss",
649    }
650}
651
652fn append_workload_list(output: &mut String, workloads: &[String]) {
653    if workloads.is_empty() {
654        output.push_str("- None\n");
655    } else {
656        for workload in workloads {
657            let _ = writeln!(output, "- {workload}");
658        }
659    }
660}