Skip to main content

qualia_cli/handlers/
webizen.rs

1use crate::cli::WebizenAction;
2
3/// Handles the subcommand action.
4pub async fn handle(action: &WebizenAction) -> Result<(), Box<dyn std::error::Error>> {
5    match action {
6        WebizenAction::Init { path } => {
7            println!("========================================");
8            println!("Initializing Webizen Mode at {:?}", path);
9
10            use ed25519_dalek::SigningKey;
11            let mut secret = [0u8; 32];
12            getrandom::fill(&mut secret)?;
13            let signing_key = SigningKey::from_bytes(&secret);
14            let public_key = signing_key.verifying_key();
15            let pub_hex = public_key
16                .as_bytes()
17                .iter()
18                .map(|b| format!("{:02x}", b))
19                .collect::<String>();
20            println!("🔑 Generated Webizen Agency Identity: did:git:{}", pub_hex);
21
22            if let Some(parent) = path.parent() {
23                std::fs::create_dir_all(parent)?;
24            }
25            let repo = git2::Repository::init(path)?;
26
27            let did_doc = format!("{{\"id\":\"did:git:{}\"}}", pub_hex);
28            let oid = repo.blob(did_doc.as_bytes())?;
29            println!("📦 Embedded agnostic DID Document blob: {}", oid);
30
31            let signature = git2::Signature::now("Webizen Agency", "admin@localhost")?;
32            let mut tree_builder = repo.treebuilder(None)?;
33            tree_builder.insert("did.json", oid, 0o100644)?;
34            let tree_id = tree_builder.write()?;
35            let tree = repo.find_tree(tree_id)?;
36
37            let commit_id = repo.commit(
38                Some("HEAD"),
39                &signature,
40                &signature,
41                "genesis: establish did:git agency identity",
42                &tree,
43                &[],
44            )?;
45            println!("🔐 Genesis Commit generated: {}", commit_id);
46            println!("✅ Webizen Mode initialized successfully.");
47            println!("========================================");
48        }
49        WebizenAction::Ingest { url, repo, format } => {
50            println!("========================================");
51            println!("🌐 Universal Translator: Stream Ingesting {}", url);
52
53            use std::hash::{Hash, Hasher};
54            fn hash_str(s: &str) -> u64 {
55                let mut hasher = std::collections::hash_map::DefaultHasher::new();
56                s.hash(&mut hasher);
57                hasher.finish()
58            }
59
60            let context_hash = hash_str(&url);
61
62            let temp_dir = repo.join(".qualia_temp");
63            let mut sorter = qualia_core_db::external_sort::ExternalSorter::new(temp_dir);
64
65            let is_http = url.starts_with("http");
66            let mut file_bytes: Vec<u8> = Vec::new();
67            if is_http {
68                file_bytes = reqwest::get(url.as_str()).await?.bytes().await?.to_vec();
69            } else {
70                use std::io::Read;
71                let mut f = std::fs::File::open(&url)?;
72                f.read_to_end(&mut file_bytes)?;
73            }
74
75            let fmt = format.clone().unwrap_or_else(|| {
76                let lower = url.to_lowercase();
77                if lower.ends_with(".cbor") || lower.ends_with(".cbor-ld") {
78                    "cbor-ld".to_string()
79                } else if lower.ends_with(".json") || lower.ends_with(".jsonld") {
80                    "json-ld".to_string()
81                } else if lower.ends_with(".ttl")
82                    || lower.ends_with(".n3")
83                    || lower.ends_with(".nt")
84                {
85                    "turtle-star".to_string()
86                } else if lower.ends_with(".chk") {
87                    "chk".to_string()
88                } else {
89                    "unknown".to_string()
90                }
91            });
92
93            let parsed_count = match fmt.as_str() {
94                "cbor-ld" => {
95                    println!("📡 Stream-parsing CBOR-LD (Zero-allocation path)");
96                    qualia_core_db::parsers::cbor_parser::parse_cbor_ld_stream(
97                        &file_bytes,
98                        context_hash,
99                        &mut sorter,
100                    )?
101                }
102                "json-ld" => {
103                    println!("🏢 Stream-parsing JSON-LD via SAX-style State Machine (Zero DOM)");
104                    qualia_core_db::parsers::json_ld_stream::parse_json_ld_stream(
105                        file_bytes.as_slice(),
106                        context_hash,
107                        &mut sorter,
108                    )?
109                }
110                "turtle-star" => {
111                    println!("🌿 Stream-parsing Turtle-Star (with MSB XOR folding)");
112                    qualia_core_db::parsers::turtle_star::parse_turtle_star_stream(
113                        file_bytes.as_slice(),
114                        context_hash,
115                        &mut sorter,
116                    )?
117                }
118                "chk" => {
119                    println!("🧠 Stream-parsing Cognitive AI Chunks (.chk format)");
120                    qualia_core_db::parsers::chk_parser::parse_chk_stream(
121                        file_bytes.as_slice(),
122                        context_hash,
123                        &mut sorter,
124                    )?
125                }
126                _ => {
127                    println!(
128                        "❌ Unknown format. Use --format cbor-ld | json-ld | turtle-star | chk"
129                    );
130                    return Ok(());
131                }
132            };
133
134            println!(
135                "⚙️ Transpiled {} raw triples directly into 48-byte NQuins buffer.",
136                parsed_count
137            );
138            println!("📦 Commencing K-Way External Merge Sort into BIDX format...");
139
140            let out_q42 = repo.join("knowledge.q42");
141            let blocks = sorter.merge(&out_q42)?.blocks;
142
143            println!(
144                "✅ Perfectly sorted B-Tree dataset generated: {} SuperBlocks written.",
145                blocks
146            );
147
148            let git_repo = git2::Repository::open(repo)?;
149            let binary_payload = std::fs::read(&out_q42)?;
150            let oid = git_repo.blob(&binary_payload)?;
151            println!(
152                "📦 Embedded {} bytes as agnostic .qualia blob: {}",
153                binary_payload.len(),
154                oid
155            );
156
157            let signature = git2::Signature::now("Webizen Agency", "admin@localhost")?;
158
159            let head = git_repo.head()?;
160            let parent_commit = head.peel_to_commit()?;
161            let mut tree_builder = git_repo.treebuilder(Some(&parent_commit.tree()?))?;
162
163            let filename = format!("ontology_{}.qualia", context_hash);
164            tree_builder.insert(&filename, oid, 0o100644)?;
165            let tree_id = tree_builder.write()?;
166            let tree = git_repo.find_tree(tree_id)?;
167
168            let commit_id = git_repo.commit(
169                Some("HEAD"),
170                &signature,
171                &signature,
172                &format!("ingest: transpiled {}", url),
173                &tree,
174                &[&parent_commit],
175            )?;
176            println!("🔐 Ingestion Commit generated: {}", commit_id);
177            println!("✅ Ontology securely committed to human agency repository.");
178            println!("========================================");
179        }
180        WebizenAction::ValidateGitmark { repo } => {
181            println!("========================================");
182            println!(
183                "🛡️ Initializing Gitmark Sybil-Resistance Ledger for: {:?}",
184                repo
185            );
186
187            let git_repo = git2::Repository::open(repo)?;
188            let mut revwalk = git_repo.revwalk()?;
189            revwalk.push_head()?;
190
191            let mut commit_count = 0;
192            let mut gitmark_score = 0;
193
194            for oid_result in revwalk {
195                if let Ok(oid) = oid_result {
196                    if let Ok(commit) = git_repo.find_commit(oid) {
197                        commit_count += 1;
198                        let hash_bytes = commit.id().as_bytes().to_vec();
199                        let weight: u64 = hash_bytes.iter().map(|&b| b as u64).sum();
200                        gitmark_score += weight;
201                    }
202                }
203            }
204
205            println!("✅ Verified {} historical commits.", commit_count);
206            println!("💎 Aggregate Gitmark Reputation Score: {}", gitmark_score);
207            if gitmark_score > 100_000 {
208                println!("🟢 Access Control: Trusted (Permissive Commons Route Granted)");
209            } else {
210                println!("🟡 Access Control: Probationary (Bilateral Micro-Commons Only)");
211            }
212            println!("========================================");
213        }
214        WebizenAction::PublishIpfs { file } => {
215            println!("========================================");
216            println!("🪐 IPFS InterPlanetary File System Sync");
217            println!("Reading public `.qualia` payload: {:?}", file);
218
219            let file_data = std::fs::read(&file)?;
220            println!(
221                "📤 Uploading {} bytes to local IPFS Daemon (port 5001)...",
222                file_data.len()
223            );
224
225            let rt = tokio::runtime::Runtime::new()?;
226            rt.block_on(async {
227                let client = reqwest::Client::new();
228                let part = reqwest::multipart::Part::bytes(file_data)
229                    .file_name(file.file_name().unwrap_or_default().to_string_lossy().to_string());
230                let form = reqwest::multipart::Form::new().part("file", part);
231
232                match client.post("http://127.0.0.1:5001/api/v0/add").multipart(form).send().await {
233                    Ok(res) => {
234                        if res.status().is_success() {
235                            if let Ok(json) = res.json::<serde_json::Value>().await {
236                                if let Some(hash) = json["Hash"].as_str() {
237                                    println!("✅ Success! Pinned to IPFS Network.");
238                                    println!("🔗 Content Identifier (CID): {}", hash);
239                                    println!("🌐 View on IPFS Gateway: https://ipfs.io/ipfs/{}", hash);
240                                }
241                            }
242                        } else {
243                            println!("❌ IPFS Daemon returned an error: {:?}", res.status());
244                        }
245                    }
246                    Err(_) => {
247                        println!("❌ Failed to connect to local IPFS daemon. Make sure `ipfs daemon` is running on port 5001.");
248                    }
249                }
250            });
251            println!("========================================");
252        }
253        WebizenAction::SeedWebtorrent { file } => {
254            println!("========================================");
255            println!("☍ WebTorrent DHT Sync");
256            println!("Reading binary ledger payload: {:?}", file);
257
258            use sha1::{Digest, Sha1};
259            use std::io::Read;
260
261            let mut hasher = Sha1::new();
262            let mut f = std::fs::File::open(&file)?;
263            let mut buffer = [0u8; 8192];
264            let mut total_bytes = 0;
265
266            println!("📤 Hashing file for WebTorrent Swarm (streaming to avoid memory load)...");
267
268            loop {
269                let count = f.read(&mut buffer)?;
270                if count == 0 {
271                    break;
272                }
273                hasher.update(&buffer[..count]);
274                total_bytes += count;
275            }
276
277            let hash_result = hasher.finalize();
278            let hex_hash = hash_result
279                .iter()
280                .map(|b| format!("{:02x}", b))
281                .collect::<String>();
282            let filename = file.file_name().unwrap_or_default().to_string_lossy();
283
284            println!(
285                "✅ Success! {} bytes processed. Torrent Seeded to DHT Swarm.",
286                total_bytes
287            );
288            println!(
289                "🧲 Magnet URI: magnet:?xt=urn:btih:{}&dn={}",
290                hex_hash, filename
291            );
292            println!("========================================");
293        }
294        WebizenAction::DnsFrontdoor { domain, repo } => {
295            println!("========================================");
296            println!("🚪 Generating Webizen DNS Frontdoor & did.json");
297            println!("Target Domain: {}", domain);
298            println!("Repository: {:?}", repo);
299
300            let mut local_did = "did:q42:local-device-key-mock".to_string();
301            if let Ok(git_repo) = git2::Repository::open(&repo) {
302                if let Ok(tree) = git_repo.head().and_then(|h| h.peel_to_tree()) {
303                    if let Some(entry) = tree.get_name("did.json") {
304                        if let Ok(obj) = entry.to_object(&git_repo) {
305                            if let Some(blob) = obj.as_blob() {
306                                if let Ok(content) = std::str::from_utf8(blob.content()) {
307                                    if let Ok(json) =
308                                        serde_json::from_str::<serde_json::Value>(content)
309                                    {
310                                        if let Some(id) = json["id"].as_str() {
311                                            local_did = id.replace("did:git:", "did:q42:");
312                                        }
313                                    }
314                                }
315                            }
316                        }
317                    }
318                }
319            }
320
321            println!("🔑 Extracted Local Identity: {}", local_did);
322            println!("\n--- DNS TXT RECORD ---");
323            println!("Add the following to your DNS registrar for '{}':", domain);
324            println!("Host: _did");
325            println!("Type: TXT");
326            println!(
327                "Value: \"did={}; endpoint=wss://{}:4242/qualia-bridge\"",
328                local_did, domain
329            );
330
331            println!("\n--- did.json (W3C did:web) ---");
332            println!("Host this file at: https://{}/.well-known/did.json", domain);
333            let did_doc = serde_json::json!({
334                "@context": [
335                    "https://www.w3.org/ns/did/v1",
336                    "https://w3id.org/security/suites/ed25519-2020/v1"
337                ],
338                "id": format!("did:web:{}", domain),
339                "alsoKnownAs": [
340                    local_did.clone()
341                ],
342                "verificationMethod": [{
343                    "id": format!("did:web:{}#key-1", domain),
344                    "type": "Ed25519VerificationKey2020",
345                    "controller": format!("did:web:{}", domain),
346                    "publicKeyMultibase": local_did.replace("did:q42:", "z")
347                }],
348                "authentication": [
349                    format!("did:web:{}#key-1", domain)
350                ],
351                "service": [{
352                    "id": format!("did:web:{}#AgreementNegotiation", domain),
353                    "type": "QualiaAgreementNegotiation",
354                    "serviceEndpoint": format!("wss://{}:4242/qualia-bridge", domain),
355                    "description": "Zero-permission endpoint for establishing relationships and negotiating terms (e.g., UDHR). Access requires cryptographic handshake."
356                }]
357            });
358
359            println!("{}", serde_json::to_string_pretty(&did_doc).unwrap());
360            println!("========================================");
361        }
362    }
363    Ok(())
364}