Skip to main content

phi_app/
phi_app.rs

1//! phi_app: unified CLI tool for encoding, storing, routing φ-signals
2//! Run with: cargo run --example phi_app encode <name>
3//!         : cargo run --example phi_app route --input=... --threshold=0.9
4//!         : cargo run --example phi_app list
5//!         : cargo run --example phi_app delete <name>
6//!         : cargo run --example phi_app describe <name>
7//!         : cargo run --example phi_app export <name> --to=file.json
8//!         : cargo run --example phi_app import <name> --from=file.json
9
10use hybrid_phi::quantized_memory::phi_quantized_encode;
11use hybrid_phi::phi_fs::PhiMemoryStore;
12use hybrid_phi::phi_meta::PhiMetadata;
13use hybrid_phi::phi_bundle::PhiBundle;
14use hybrid_phi::phi_router::{phi_similarity, phi_route};
15use std::env;
16use std::fs;
17
18fn parse_input_vec(arg: &str) -> Vec<f64> {
19    arg.split(',').filter_map(|s| s.parse().ok()).collect()
20}
21
22fn main() {
23    let args: Vec<String> = env::args().collect();
24    if args.len() < 2 {
25        eprintln!("Usage:\n  encode <name>\n  route --input=... [--threshold=0.9] [--verbose]\n  list\n  delete <name>\n  describe <name>\n  export <name> --to=file.json\n  import <name> --from=file.json");
26        return;
27    }
28
29    let mode = &args[1];
30    let store = PhiMemoryStore::new(".phi_store");
31    let n = 10;
32    let step = 0.01;
33
34    if mode == "encode" && args.len() >= 3 {
35        let name = &args[2];
36        println!("Encoding input signal for '{}'. Enter comma-separated values:", name);
37        let mut buf = String::new();
38        std::io::stdin().read_line(&mut buf).unwrap();
39        let signal = parse_input_vec(&buf);
40        let encoded: Vec<f64> = signal.iter().map(|&x| phi_quantized_encode(x, n, step)).collect();
41        store.save(name, &encoded).expect("failed to save");
42        let meta = PhiMetadata {
43            n,
44            step,
45            length: encoded.len(),
46            saved_at: chrono::Utc::now(),
47        };
48        meta.save(name, ".phi_store").expect("failed to save metadata");
49        println!("Saved {} values to '{}'.", encoded.len(), name);
50        return;
51    }
52
53    if mode == "route" {
54        let mut input: Option<Vec<f64>> = None;
55        let mut threshold = 0.8;
56        let mut verbose = false;
57
58        for arg in &args[2..] {
59            if let Some(v) = arg.strip_prefix("--input=") {
60                input = Some(parse_input_vec(v));
61            }
62            if let Some(v) = arg.strip_prefix("--threshold=") {
63                threshold = v.parse().unwrap_or(threshold);
64            }
65            if arg == "--verbose" {
66                verbose = true;
67            }
68        }
69
70        let input = input.expect("Missing --input argument");
71        let encoded_input: Vec<f64> = input.iter().map(|&x| phi_quantized_encode(x, n, step)).collect();
72
73        if verbose {
74            println!("Similarity to each stored φ-memory:");
75            for name in store.list().unwrap_or_default() {
76                if let Ok(entry) = store.load(&name) {
77                    let score = phi_similarity(&encoded_input, &entry);
78                    println!("- {}: {:.3}%", name, score * 100.0);
79                }
80            }
81        }
82
83        match phi_route(&encoded_input, &store, threshold) {
84            Some((name, score)) => println!("\nInput routed to '{}', score = {:.3}%", name, score * 100.0),
85            None => println!("\nNo route found (threshold = {:.2})", threshold),
86        }
87        return;
88    }
89
90    if mode == "list" {
91        let entries = store.list().unwrap_or_default();
92        println!("Stored φ-memories:");
93        for name in entries {
94            println!("- {}", name);
95        }
96        return;
97    }
98
99    if mode == "delete" && args.len() >= 3 {
100        let name = &args[2];
101        let _ = fs::remove_file(format!(".phi_store/{}.bin", name));
102        let _ = fs::remove_file(format!(".phi_store/{}.meta.txt", name));
103        println!("Deleted memory '{}'.", name);
104        return;
105    }
106
107    if mode == "describe" && args.len() >= 3 {
108        let name = &args[2];
109        match PhiMetadata::load(name, ".phi_store") {
110            Ok(meta) => {
111                println!("φ-memory '{}':", name);
112                println!("  length   = {}", meta.length);
113                println!("  n        = {}", meta.n);
114                println!("  step     = {:.5}", meta.step);
115                println!("  saved_at = {}", meta.saved_at);
116            }
117            Err(err) => {
118                println!("Failed to load metadata: {}", err);
119            }
120        }
121        return;
122    }
123
124    if mode == "export" && args.len() >= 4 {
125        let name = &args[2];
126        let mut out_path = None;
127        for arg in &args[3..] {
128            if let Some(p) = arg.strip_prefix("--to=") {
129                out_path = Some(p);
130            }
131        }
132        let out_path = out_path.expect("Missing --to=... argument");
133        let bundle = PhiBundle::from_store(name, &store).expect("failed to bundle");
134        bundle.save_json(out_path).expect("failed to save json");
135        println!("Exported '{}' to '{}'.", name, out_path);
136        return;
137    }
138
139    if mode == "import" && args.len() >= 4 {
140        let name = &args[2];
141        let mut in_path = None;
142        for arg in &args[3..] {
143            if let Some(p) = arg.strip_prefix("--from=") {
144                in_path = Some(p);
145            }
146        }
147        let in_path = in_path.expect("Missing --from=... argument");
148        let bundle = PhiBundle::load_json(in_path).expect("failed to load json");
149        bundle.save_to_store(&store).expect("failed to restore");
150        println!("Imported '{}' from '{}'.", name, in_path);
151        return;
152    }
153
154    eprintln!("Unknown mode '{}'. Use 'encode', 'route', 'list', 'delete', 'describe', 'export', or 'import'", mode);
155}