Skip to main content

qualia_cli/handlers/
entity_verify.rs

1//! Handler for `qualia-cli entity-verify`.
2//!
3//! Provides ultra-fast, zero-DOM batch verification for `.10d` living containers
4//! and `.hmc` bundles, allowing autonomous software agents to inspect thousands
5//! of species/models without browser or Node dependencies.
6
7use std::fs;
8use std::path::{Path, PathBuf};
9
10use qualia_core_db::bundle::entity_verifier::{
11    verify_entity_10d, verify_entity_bundle, Entity10dVerification, EntityBundleVerification,
12};
13use serde::{Deserialize, Serialize};
14
15use crate::cli::EntityVerifyArgs;
16
17#[derive(Debug, Serialize, Deserialize)]
18pub enum FileVerificationResult {
19    Container10d {
20        path: String,
21        report: Entity10dVerification,
22    },
23    BundleHmc {
24        path: String,
25        report: EntityBundleVerification,
26    },
27    Error {
28        path: String,
29        error: String,
30    },
31}
32
33#[derive(Debug, Serialize, Deserialize)]
34pub struct BatchVerificationReport {
35    pub total: usize,
36    pub passed: usize,
37    pub failed: usize,
38    pub results: Vec<FileVerificationResult>,
39}
40
41/// Handles the subcommand action.
42pub fn handle(args: &EntityVerifyArgs) -> Result<(), Box<dyn std::error::Error>> {
43    let path = &args.path;
44
45    if !path.exists() {
46        return Err(format!("path does not exist: {:?}", path).into());
47    }
48
49    if path.is_dir() || args.batch {
50        handle_batch(path, args)
51    } else {
52        handle_single_file(path, args)
53    }
54}
55
56fn handle_single_file(path: &Path, args: &EntityVerifyArgs) -> Result<(), Box<dyn std::error::Error>> {
57    let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("");
58    let bytes = fs::read(path)?;
59
60    if ext.eq_ignore_ascii_case("10d") {
61        let rep = verify_entity_10d(&bytes);
62        if args.json {
63            println!("{}", serde_json::to_string_pretty(&rep)?);
64        } else if !args.quiet {
65            print_10d_report(path, &rep);
66        }
67        if !rep.valid {
68            return Err("entity verification failed".into());
69        }
70    } else if ext.eq_ignore_ascii_case("hmc") {
71        let rep = verify_entity_bundle(&bytes);
72        if args.json {
73            println!("{}", serde_json::to_string_pretty(&rep)?);
74        } else if !args.quiet {
75            print_bundle_report(path, &rep);
76        }
77        if !rep.valid {
78            return Err("bundle verification failed".into());
79        }
80    } else {
81        // Sniff by magic bytes
82        if bytes.starts_with(b"10D\0") {
83            let rep = verify_entity_10d(&bytes);
84            if args.json {
85                println!("{}", serde_json::to_string_pretty(&rep)?);
86            } else if !args.quiet {
87                print_10d_report(path, &rep);
88            }
89            if !rep.valid {
90                return Err("entity verification failed".into());
91            }
92        } else if bytes.starts_with(b"HMC1") {
93            let rep = verify_entity_bundle(&bytes);
94            if args.json {
95                println!("{}", serde_json::to_string_pretty(&rep)?);
96            } else if !args.quiet {
97                print_bundle_report(path, &rep);
98            }
99            if !rep.valid {
100                return Err("bundle verification failed".into());
101            }
102        } else {
103            return Err(format!("unrecognized file format for {:?}; expected .10d or .hmc", path).into());
104        }
105    }
106
107    Ok(())
108}
109
110fn handle_batch(dir: &Path, args: &EntityVerifyArgs) -> Result<(), Box<dyn std::error::Error>> {
111    let mut files = Vec::new();
112    collect_files_recursive(dir, &mut files)?;
113
114    if !args.quiet && !args.json {
115        println!("============================================================");
116        println!("🔍 QualiaDB Batch Entity Verification");
117        println!("============================================================");
118        println!("  Target Directory: {:?}", dir);
119        println!("  Candidate Files:  {}", files.len());
120        println!("------------------------------------------------------------");
121    }
122
123    let mut results = Vec::new();
124    let mut passed = 0;
125    let mut failed = 0;
126
127    for file_path in &files {
128        let path_str = file_path.to_string_lossy().to_string();
129        let bytes = match fs::read(file_path) {
130            Ok(b) => b,
131            Err(e) => {
132                failed += 1;
133                results.push(FileVerificationResult::Error {
134                    path: path_str,
135                    error: e.to_string(),
136                });
137                continue;
138            }
139        };
140
141        let ext = file_path.extension().and_then(|s| s.to_str()).unwrap_or("");
142        if ext.eq_ignore_ascii_case("10d") || bytes.starts_with(b"10D\0") {
143            let rep = verify_entity_10d(&bytes);
144            if rep.valid {
145                passed += 1;
146                if !args.quiet && !args.json {
147                    println!("  ✅ [PASS] 10D: {} (verts: {}, tris: {}, surfels: {})",
148                        file_path.file_name().unwrap_or_default().to_string_lossy(),
149                        rep.vertices,
150                        rep.triangles,
151                        rep.surfels.as_ref().map(|s| s.surfel_count).unwrap_or(0)
152                    );
153                }
154            } else {
155                failed += 1;
156                if !args.quiet && !args.json {
157                    println!("  ❌ [FAIL] 10D: {} (violations: {:?})",
158                        file_path.file_name().unwrap_or_default().to_string_lossy(),
159                        rep.violations
160                    );
161                }
162            }
163            results.push(FileVerificationResult::Container10d {
164                path: path_str,
165                report: rep,
166            });
167        } else if ext.eq_ignore_ascii_case("hmc") || bytes.starts_with(b"HMC1") {
168            let rep = verify_entity_bundle(&bytes);
169            if rep.valid {
170                passed += 1;
171                if !args.quiet && !args.json {
172                    println!("  ✅ [PASS] HMC: {} (type: {:?}, entries: {})",
173                        file_path.file_name().unwrap_or_default().to_string_lossy(),
174                        rep.entity_type.as_deref().unwrap_or("unknown"),
175                        rep.entry_count
176                    );
177                }
178            } else {
179                failed += 1;
180                if !args.quiet && !args.json {
181                    println!("  ❌ [FAIL] HMC: {} (violations: {:?})",
182                        file_path.file_name().unwrap_or_default().to_string_lossy(),
183                        rep.violations
184                    );
185                }
186            }
187            results.push(FileVerificationResult::BundleHmc {
188                path: path_str,
189                report: rep,
190            });
191        }
192    }
193
194    let batch_report = BatchVerificationReport {
195        total: files.len(),
196        passed,
197        failed,
198        results,
199    };
200
201    if args.json {
202        println!("{}", serde_json::to_string_pretty(&batch_report)?);
203    } else if !args.quiet {
204        println!("------------------------------------------------------------");
205        println!("  Summary: Total: {}, Passed: {}, Failed: {}", batch_report.total, batch_report.passed, batch_report.failed);
206        println!("============================================================");
207    }
208
209    if failed > 0 {
210        return Err(format!("batch verification completed with {failed} failure(s)").into());
211    }
212
213    Ok(())
214}
215
216fn collect_files_recursive(dir: &Path, out: &mut Vec<PathBuf>) -> std::io::Result<()> {
217    if dir.is_dir() {
218        for entry in fs::read_dir(dir)? {
219            let entry = entry?;
220            let path = entry.path();
221            if path.is_dir() {
222                collect_files_recursive(&path, out)?;
223            } else if let Some(ext) = path.extension().and_then(|s| s.to_str()) {
224                if ext.eq_ignore_ascii_case("10d") || ext.eq_ignore_ascii_case("hmc") {
225                    out.push(path);
226                }
227            }
228        }
229    } else {
230        out.push(dir.to_path_buf());
231    }
232    Ok(())
233}
234
235fn print_10d_report(path: &Path, rep: &Entity10dVerification) {
236    println!("============================================================");
237    println!("📦 QualiaDB .10d Living Container Verification");
238    println!("============================================================");
239    println!("  Path:             {:?}", path);
240    println!("  Status:           {}", if rep.valid { "✅ VALID" } else { "❌ INVALID" });
241    println!("  Header Version:   {}", rep.header_version);
242    println!("  Whole-file CRC:   {}", if rep.crc32c_valid { "Verified" } else { "Mismatch" });
243    println!("  Section Count:    {}", rep.section_count);
244    println!("  Sections Found:   {}", rep.sections_found.join(", "));
245    println!("  Mesh Geometry:    {} vertices, {} triangles", rep.vertices, rep.triangles);
246    if let Some(ref s) = rep.surfels {
247        println!("  Section 20 SURF1: {} surfels (disc radius: {:.3})", s.surfel_count, s.sphere_radius);
248    } else {
249        println!("  Section 20 SURF1: None");
250    }
251    if let Some(ref imp) = rep.impostors {
252        println!("  Section 19 IMPO1: {}x{} grid @ {}x{} resolution", imp.grid_dimension, imp.grid_dimension, imp.view_resolution, imp.view_resolution);
253    } else {
254        println!("  Section 19 IMPO1: None");
255    }
256    if let Some(ref aff) = rep.affordances {
257        println!("  Section 17 EONT1: {} affordances (did hash: 0x{:016x})", aff.affordance_count, aff.entity_did_hash);
258    }
259    println!("  Reverse-LOD:      {}", if rep.reverse_lod_valid { "Verified (SURF1 -> IMPO1 -> Mesh)" } else { "Violation" });
260    println!("  AABB Bounds:      [{:.2}, {:.2}, {:.2}] to [{:.2}, {:.2}, {:.2}]",
261        rep.min_bounds[0], rep.min_bounds[1], rep.min_bounds[2],
262        rep.max_bounds[0], rep.max_bounds[1], rep.max_bounds[2]
263    );
264    if !rep.violations.is_empty() {
265        println!("  Violations:       {:?}", rep.violations);
266    }
267    println!("============================================================");
268}
269
270fn print_bundle_report(path: &Path, rep: &EntityBundleVerification) {
271    println!("============================================================");
272    println!("📦 QualiaDB .hmc Entity Bundle Verification");
273    println!("============================================================");
274    println!("  Path:             {:?}", path);
275    println!("  Status:           {}", if rep.valid { "✅ VALID" } else { "❌ INVALID" });
276    println!("  Bundle CRC-32C:   {}", if rep.bundle_crc32c_valid { "Verified" } else { "Mismatch" });
277    println!("  Entry Count:      {}", rep.entry_count);
278    println!("  CBOR-LD Manifest: {}", if rep.manifest_present { "Present" } else { "Missing" });
279    if let Some(ref id) = rep.credential_id {
280        println!("  Credential ID:    {}", id);
281    }
282    if let Some(ref iss) = rep.issuer_did {
283        println!("  Issuer DID:       {}", iss);
284    }
285    if let Some(ref sub) = rep.subject_id {
286        println!("  Subject ID:       {}", sub);
287    }
288    if let Some(ref cls) = rep.entity_type {
289        println!("  Entity Class:     {}", cls);
290    }
291    if let Some(ref anc) = rep.acoustic_anchors {
292        println!("  Acoustic Anchors: [{} Hz, {} Hz, {} Hz]", anc.low_hz, anc.mid_hz, anc.high_hz);
293    }
294    println!("  Anti-Commodif.:   {}", if rep.anti_commodification_passed { "Passed" } else { "Violated" });
295    println!("  Permissive Commons:{}", if rep.permissive_commons_passed { "Passed (Permissive / SPC)" } else { "Violated" });
296    if let Some(ref cob) = rep.commons_obligation {
297        println!("  Commons Licence:  {}", cob.licence_class);
298        println!(
299            "  Production Cost:  ${:.2} (Accumulated Pool: ${:.2}, Discharged: {})",
300            cob.production_cost_cents as f64 / 100.0,
301            cob.accumulated_pool_cents as f64 / 100.0,
302            if cob.is_discharged { "Yes" } else { "No" }
303        );
304        if !cob.is_discharged {
305            println!(
306                "  Outstanding Cost: ${:.2} (ROI Cap: {}%)",
307                cob.outstanding_cents as f64 / 100.0,
308                cob.roi_cap_percent
309            );
310        }
311        if cob.transaction_cost_per_mib_cents > 0 {
312            println!(
313                "  Carrier Recovery: ${:.4}/MiB (At-cost bandwidth/transport only)",
314                cob.transaction_cost_per_mib_cents as f64 / 100.0
315            );
316        } else {
317            println!("  Carrier Recovery: $0.00/MiB (Zero transaction surcharge)");
318        }
319        println!(
320            "  Perpetual Fees:   {}",
321            if cob.perpetual_fees_prohibited {
322                "Prohibited (Humanitarian ICT Compliance)"
323            } else {
324                "Warning: Not prohibited!"
325            }
326        );
327    }
328    println!("  Geometry Digests: {}", if rep.geometry_digests_match { "Verified" } else { "Mismatch" });
329    println!("  Contained .10d:   {} entity/entities", rep.contained_10d_entities.len());
330    if !rep.violations.is_empty() {
331        println!("  Violations:       {:?}", rep.violations);
332    }
333    println!("============================================================");
334}