Skip to main content

kobold_data_shim/
diff.rs

1//! KOBOLD.DIFF.1 — structural comparison against a *declared* expected artifact.
2//!
3//! **Doctrine.** KOBOLD.DIFF.1 admits only structural comparison against declared expected artifacts: a
4//! match proves equality to the declared target under the selected comparison rules, **not** business
5//! truth, ledger acceptance, settlement finality, customer approval, or oracle authority. The comparison
6//! target is **never** called an oracle unless its declared `oracle_status` permits it — a diff lets a
7//! bank compare KOBOLD output to a declared artifact without smuggling in *"therefore the old system was
8//! correct."*
9
10/// The declared authority of the comparison target. Default (and safest) is `NotOracle`.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum OracleStatus {
14    NotOracle,
15    DeclaredBaseline,
16    CustomerSuppliedReference,
17    SystemOfRecordExportUnvalidated,
18    AdmittedOracle,
19}
20impl OracleStatus {
21    fn as_str(self) -> &'static str {
22        match self {
23            OracleStatus::NotOracle => "not_oracle",
24            OracleStatus::DeclaredBaseline => "declared_baseline",
25            OracleStatus::CustomerSuppliedReference => "customer_supplied_reference",
26            OracleStatus::SystemOfRecordExportUnvalidated => "system_of_record_export_unvalidated",
27            OracleStatus::AdmittedOracle => "admitted_oracle",
28        }
29    }
30}
31
32/// A declared comparison target. `allowed_comparisons` gates which dimensions are compared.
33pub struct DiffTarget<'a> {
34    pub target_kind: &'a str,
35    pub oracle_status: OracleStatus,
36    /// e.g. `"test-golden" | "customer-supplied" | "system-export" | "previous-run"`.
37    pub source: &'a str,
38    /// any of `"field_values" | "audit_hashes" | "finding_ids" | "control_totals"`.
39    pub allowed_comparisons: &'a [&'a str],
40}
41
42/// One side of a comparison, extracted from a KOBOLD output (actual) or a declared artifact (expected).
43#[derive(Default)]
44pub struct DiffInput {
45    pub fields: Vec<(String, String)>,
46    pub finding_ids: Vec<String>,
47    pub control_totals: Vec<(String, String)>,
48    pub output_hash: Option<String>,
49}
50
51/// The deterministic diff result.
52pub struct DiffReport {
53    pub report_json: String,
54    pub sarif_json: String,
55    pub casefile_json: String,
56    pub findings: Vec<(String, String)>,
57    pub matched: bool,
58}
59
60fn jstr(s: &str) -> String {
61    let mut o = String::from("\"");
62    for c in s.chars() {
63        match c {
64            '"' => o.push_str("\\\""),
65            '\\' => o.push_str("\\\\"),
66            c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)),
67            c => o.push(c),
68        }
69    }
70    o.push('"');
71    o
72}
73
74/// Compare a KOBOLD output (`actual`) against a declared expected artifact (`expected`) under `target`.
75/// Deterministic: findings are sorted; only the `allowed_comparisons` dimensions are checked.
76pub fn diff_artifacts(actual: &DiffInput, expected: &DiffInput, target: &DiffTarget) -> DiffReport {
77    let allowed = |k: &str| target.allowed_comparisons.contains(&k);
78    let mut findings: Vec<(String, String)> = Vec::new();
79
80    if allowed("field_values") {
81        let amap: std::collections::HashMap<&str, &str> = actual
82            .fields
83            .iter()
84            .map(|(k, v)| (k.as_str(), v.as_str()))
85            .collect();
86        let emap: std::collections::HashMap<&str, &str> = expected
87            .fields
88            .iter()
89            .map(|(k, v)| (k.as_str(), v.as_str()))
90            .collect();
91        for (k, ev) in &expected.fields {
92            match amap.get(k.as_str()) {
93                None => findings.push((
94                    "KOBOLD-DIFF-MISSING-FIELD".into(),
95                    format!("field {k:?} present in expected, absent in actual"),
96                )),
97                Some(av) if av != ev => findings.push((
98                    "KOBOLD-DIFF-FIELD-MISMATCH".into(),
99                    format!("field {k:?}: actual {av:?} != expected {ev:?}"),
100                )),
101                _ => {}
102            }
103        }
104        for (k, _) in &actual.fields {
105            if !emap.contains_key(k.as_str()) {
106                findings.push((
107                    "KOBOLD-DIFF-EXTRA-FIELD".into(),
108                    format!("field {k:?} present in actual, not in expected"),
109                ));
110            }
111        }
112    }
113    if allowed("finding_ids") {
114        let aset: std::collections::BTreeSet<&str> =
115            actual.finding_ids.iter().map(String::as_str).collect();
116        let eset: std::collections::BTreeSet<&str> =
117            expected.finding_ids.iter().map(String::as_str).collect();
118        if aset != eset {
119            findings.push((
120                "KOBOLD-DIFF-FINDING-SET-MISMATCH".into(),
121                format!("finding-id set differs: actual {aset:?} != expected {eset:?}"),
122            ));
123        }
124    }
125    if allowed("control_totals") {
126        let emap: std::collections::HashMap<&str, &str> = expected
127            .control_totals
128            .iter()
129            .map(|(k, v)| (k.as_str(), v.as_str()))
130            .collect();
131        let amap: std::collections::HashMap<&str, &str> = actual
132            .control_totals
133            .iter()
134            .map(|(k, v)| (k.as_str(), v.as_str()))
135            .collect();
136        for (k, ev) in &expected.control_totals {
137            if amap.get(k.as_str()) != Some(&ev.as_str()) {
138                findings.push((
139                    "KOBOLD-DIFF-CONTROL-TOTAL-MISMATCH".into(),
140                    format!(
141                        "control total {k:?}: actual {:?} != expected {ev:?}",
142                        amap.get(k.as_str())
143                    ),
144                ));
145            }
146        }
147        for (k, _) in &actual.control_totals {
148            if !emap.contains_key(k.as_str()) {
149                findings.push((
150                    "KOBOLD-DIFF-CONTROL-TOTAL-MISMATCH".into(),
151                    format!("control total {k:?} present in actual, not in expected"),
152                ));
153            }
154        }
155    }
156    if allowed("audit_hashes") && actual.output_hash != expected.output_hash {
157        findings.push((
158            "KOBOLD-DIFF-HASH-MISMATCH".into(),
159            format!(
160                "audit output hash differs: actual {:?} != expected {:?}",
161                actual.output_hash, expected.output_hash
162            ),
163        ));
164    }
165
166    let matched = findings.is_empty();
167    // A non-oracle target that MATCHES must NOT be read as truth — emit a loud refusal note so a match is
168    // never smuggled into 'the old system was correct'.
169    if matched && target.oracle_status != OracleStatus::AdmittedOracle {
170        findings.push(("KOBOLD-DIFF-TARGET-NOT-ORACLE".into(),
171            format!("matched the declared target (oracle_status={}); this proves equality to the target, NOT correctness/oracle authority", target.oracle_status.as_str())));
172    }
173
174    findings.sort();
175    let oracle_authority = target.oracle_status == OracleStatus::AdmittedOracle;
176    let verdict = if matched {
177        "equal_to_declared_target"
178    } else {
179        "differs_from_declared_target"
180    };
181
182    let sarif_results: Vec<String> = findings
183        .iter()
184        .map(|(r, m)| {
185            let level = if r == "KOBOLD-DIFF-TARGET-NOT-ORACLE" {
186                "note"
187            } else {
188                "error"
189            };
190            format!(
191                "{{\"ruleId\":{},\"level\":{},\"message\":{{\"text\":{}}}}}",
192                jstr(r),
193                jstr(level),
194                jstr(m)
195            )
196        })
197        .collect();
198    let sarif_json = format!(
199        concat!(
200            "{{\"version\":\"2.1.0\",\"$schema\":\"https://json.schemastore.org/sarif-2.1.0.json\",",
201            "\"runs\":[{{\"tool\":{{\"driver\":{{\"name\":\"kobold-diff\",\"rules\":[]}}}},\"results\":[{}]}}]}}\n"
202        ),
203        sarif_results.join(",")
204    );
205
206    let allowed_json = target
207        .allowed_comparisons
208        .iter()
209        .map(|c| jstr(c))
210        .collect::<Vec<_>>()
211        .join(",");
212    let find_json = findings
213        .iter()
214        .map(|(r, m)| format!("{{\"ruleId\":{},\"message\":{}}}", jstr(r), jstr(m)))
215        .collect::<Vec<_>>()
216        .join(",");
217    let report_json = format!(
218        concat!(
219            "{{\"schema\":\"kobold-diff-report-v1\",\"court\":\"KOBOLD.DIFF.1\",\"verdict\":{},\"matched\":{},",
220            "\"target\":{{\"schema\":\"kobold-diff-target-v1\",\"target_kind\":{},\"oracle_status\":{},\"source\":{},",
221            "\"allowed_comparisons\":[{}]}},\"oracle_authority_claimed\":{},",
222            "\"truth_layers\":{{\"equal_to_declared_target\":{},\"business_truth\":false,\"ledger_truth\":false,",
223            "\"settlement_truth\":false,\"customer_approval\":false}},",
224            "\"findings\":[{}],",
225            "\"negative_capabilities\":[\"NEG.DIFF.MATCH_NOT_BUSINESS_TRUTH\",\"NEG.DIFF.EXPECTED_OUTPUT_NOT_ORACLE\",",
226            "\"NEG.DIFF.SYSTEM_OF_RECORD_NOT_VALIDATED\",\"NEG.DIFF.NO_LEDGER_ACCEPTANCE\",",
227            "\"NEG.DIFF.NO_SETTLEMENT_FINALITY\",\"NEG.DIFF.NO_CUSTOMER_APPROVAL\"]}}\n"
228        ),
229        jstr(verdict), matched,
230        jstr(target.target_kind), jstr(target.oracle_status.as_str()), jstr(target.source),
231        allowed_json, oracle_authority,
232        matched, find_json,
233    );
234    let casefile_json = report_json.replace(
235        "\"schema\":\"kobold-diff-report-v1\"",
236        "\"schema\":\"kobold-diff-forensic-casefile-v1\"",
237    );
238
239    DiffReport {
240        report_json,
241        sarif_json,
242        casefile_json,
243        findings,
244        matched,
245    }
246}