1use crate::state::{app_meta_dir, APP_STATE};
14use serde::{Deserialize, Serialize};
15use std::path::PathBuf;
16use std::sync::Mutex;
17
18static QPU_CACHE: Mutex<Option<QpuOracleState>> = Mutex::new(None);
19
20const COMMITMENT_B64: &str = "SSBBZmZpcm0gTXkgQ29tbWl0bWVudCB0byBVbml2ZXJzYWwgSHVtYW4gUmlnaHRz";
21const COMMITMENT_TEXT: &str = "I Affirm My Commitment to Universal Human Rights";
22
23const IBM_MONTHLY_MINUTES: f64 = 10.0;
25const DWAVE_MONTHLY_MINUTES: f64 = 1.0;
26const IONQ_MONTHLY_MINUTES: f64 = 0.0; const RIGETTI_MONTHLY_MINUTES: f64 = 0.0; const AZURE_MONTHLY_MINUTES: f64 = 0.0; const BRAKET_MONTHLY_MINUTES: f64 = 0.0; const GOOGLE_MONTHLY_MINUTES: f64 = 0.0; const QUANTINUUM_MONTHLY_MINUTES: f64 = 0.0; fn qpu_config_path() -> PathBuf {
34 app_meta_dir().join("qpu_oracle.json")
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
38pub enum QpuArchitecture {
39 GateModel,
40 Annealer,
41 TrappedIon,
42 PhotonicGate,
43 NeutralAtom,
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
48pub enum QpuProvider {
49 Ibm,
51 DWave,
53 IonQ,
55 Rigetti,
57 Azure,
59 Braket,
61 Google,
63 Quantinuum,
65}
66
67impl QpuProvider {
68 pub fn name(self) -> &'static str {
70 match self {
71 Self::Ibm => "IBM Quantum",
72 Self::DWave => "D-Wave Leap",
73 Self::IonQ => "IonQ Cloud",
74 Self::Rigetti => "Rigetti QCS",
75 Self::Azure => "Azure Quantum",
76 Self::Braket => "Amazon Braket",
77 Self::Google => "Google Quantum AI",
78 Self::Quantinuum => "Quantinuum",
79 }
80 }
81
82 pub fn architecture(self) -> QpuArchitecture {
84 match self {
85 Self::DWave => QpuArchitecture::Annealer,
86 Self::IonQ | Self::Quantinuum => QpuArchitecture::TrappedIon,
87 Self::Ibm | Self::Rigetti | Self::Google => QpuArchitecture::GateModel,
88 Self::Azure | Self::Braket => QpuArchitecture::GateModel, }
90 }
91
92 pub fn docs_url(self) -> &'static str {
94 match self {
95 Self::Ibm => "https://quantum.cloud.ibm.com",
96 Self::DWave => "https://cloud.dwavesys.com/leap/",
97 Self::IonQ => "https://cloud.ionq.com",
98 Self::Rigetti => "https://qcs.rigetti.com",
99 Self::Azure => "https://azure.microsoft.com/products/quantum",
100 Self::Braket => "https://aws.amazon.com/braket/",
101 Self::Google => "https://quantumai.google",
102 Self::Quantinuum => "https://www.quantinuum.com/computingtechnology/nexus",
103 }
104 }
105}
106
107#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct QpuOracleState {
109 pub feature_unlocked: bool,
110 pub commitment_affirmed_at: Option<String>,
112
113 pub ibm_token_enc: String,
115 pub dwave_token_enc: String,
116 pub ionq_token_enc: String,
117 pub rigetti_token_enc: String,
118 pub azure_credentials_enc: String,
120 pub braket_credentials_enc: String,
122 pub google_token_enc: String,
123 pub quantinuum_token_enc: String,
124
125 pub ibm_minutes_used: f64,
127 pub dwave_minutes_used: f64,
128 pub ionq_minutes_used: f64,
129 pub rigetti_minutes_used: f64,
130 pub azure_minutes_used: f64,
131 pub braket_minutes_used: f64,
132 pub google_minutes_used: f64,
133 pub quantinuum_minutes_used: f64,
134
135 pub max_shots_per_task: u32,
137 pub fallback_to_classical: bool,
138 pub enable_qubo_routing: bool,
139 pub enable_dft_ground_state: bool,
140 pub enable_defeasible_resolution: bool,
141}
142
143impl Default for QpuOracleState {
144 fn default() -> Self {
145 Self {
146 feature_unlocked: false,
147 commitment_affirmed_at: None,
148 ibm_token_enc: String::new(),
149 dwave_token_enc: String::new(),
150 ionq_token_enc: String::new(),
151 rigetti_token_enc: String::new(),
152 azure_credentials_enc: String::new(),
153 braket_credentials_enc: String::new(),
154 google_token_enc: String::new(),
155 quantinuum_token_enc: String::new(),
156 ibm_minutes_used: 0.0,
157 dwave_minutes_used: 0.0,
158 ionq_minutes_used: 0.0,
159 rigetti_minutes_used: 0.0,
160 azure_minutes_used: 0.0,
161 braket_minutes_used: 0.0,
162 google_minutes_used: 0.0,
163 quantinuum_minutes_used: 0.0,
164 max_shots_per_task: 1000,
165 fallback_to_classical: true,
166 enable_qubo_routing: true,
167 enable_dft_ground_state: true,
168 enable_defeasible_resolution: false,
169 }
170 }
171}
172
173#[derive(Debug, Clone, Serialize, Deserialize)]
175pub struct QpuProviderStatus {
176 pub provider: String,
177 pub name: String,
178 pub architecture: String,
179 pub configured: bool,
180 pub docs_url: String,
181 pub minutes_used: f64,
182 pub monthly_quota: f64,
183}
184
185#[derive(Debug, Clone, Serialize, Deserialize)]
187pub struct QpuOracleSettings {
188 pub feature_unlocked: bool,
189 pub commitment_affirmed: bool,
190 pub ibm_token_configured: bool,
192 pub dwave_token_configured: bool,
193 pub providers: Vec<QpuProviderStatus>,
195 pub max_shots_per_task: u32,
197 pub fallback_to_classical: bool,
198 pub enable_qubo_routing: bool,
199 pub enable_dft_ground_state: bool,
200 pub enable_defeasible_resolution: bool,
201 pub ibm_quota_minutes_remaining: f64,
203 pub dwave_quota_minutes_remaining: f64,
204}
205
206#[derive(Debug, Clone, Serialize, Deserialize)]
208pub struct QpuOracleSettingsInput {
209 pub max_shots_per_task: u32,
210 pub fallback_to_classical: bool,
211 pub enable_qubo_routing: bool,
212 pub enable_dft_ground_state: bool,
213 pub enable_defeasible_resolution: bool,
214 pub ibm_token: Option<String>,
216 pub dwave_token: Option<String>,
217 pub ionq_token: Option<String>,
218 pub rigetti_token: Option<String>,
219 pub azure_credentials: Option<String>,
221 pub braket_credentials: Option<String>,
223 pub google_token: Option<String>,
224 pub quantinuum_token: Option<String>,
225}
226
227#[derive(Debug, Clone, Serialize, Deserialize)]
228pub struct QpuChatCommandResult {
229 pub handled: bool,
230 pub response: String,
231 pub feature_unlocked: bool,
232}
233
234fn encrypt_secret(plaintext: &str) -> Result<String, String> {
237 if plaintext.is_empty() {
238 return Ok(String::new());
239 }
240 let state = APP_STATE.get().ok_or("APP_STATE not initialized")?;
241 let vault = state.key_vault.lock().map_err(|e| e.to_string())?;
242 let key_bytes = vault.derive_key("qpu_oracle_secrets").to_bytes();
243 let encrypted: Vec<u8> = plaintext
244 .as_bytes()
245 .iter()
246 .enumerate()
247 .map(|(i, b)| b ^ key_bytes[i % 32])
248 .collect();
249 Ok(hex::encode(encrypted))
250}
251
252fn decrypt_secret(ciphertext_hex: &str) -> Result<String, String> {
253 if ciphertext_hex.is_empty() {
254 return Ok(String::new());
255 }
256 let state = APP_STATE.get().ok_or("APP_STATE not initialized")?;
257 let vault = state.key_vault.lock().map_err(|e| e.to_string())?;
258 let encrypted = hex::decode(ciphertext_hex).map_err(|_| "Invalid encrypted token")?;
259 let key_bytes = vault.derive_key("qpu_oracle_secrets").to_bytes();
260 let decrypted: Vec<u8> = encrypted
261 .iter()
262 .enumerate()
263 .map(|(i, b)| b ^ key_bytes[i % 32])
264 .collect();
265 String::from_utf8(decrypted).map_err(|_| "Token decryption failed".into())
266}
267
268fn load_state_from_disk() -> QpuOracleState {
271 std::fs::read_to_string(qpu_config_path())
272 .ok()
273 .and_then(|s| serde_json::from_str(&s).ok())
274 .unwrap_or_default()
275}
276
277fn persist_state(state: &QpuOracleState) -> Result<(), String> {
278 let meta = app_meta_dir();
279 std::fs::create_dir_all(&meta).map_err(|e| e.to_string())?;
280 let json = serde_json::to_string_pretty(state).map_err(|e| e.to_string())?;
281 std::fs::write(qpu_config_path(), json).map_err(|e| e.to_string())?;
282 Ok(())
283}
284
285fn cached_state() -> QpuOracleState {
286 let mut cache = QPU_CACHE.lock().unwrap();
287 if cache.is_none() {
288 *cache = Some(load_state_from_disk());
289 }
290 cache.clone().unwrap()
291}
292
293pub(crate) fn cached_state_internal() -> QpuOracleState {
295 cached_state()
296}
297
298fn update_state<F: FnOnce(&mut QpuOracleState)>(f: F) -> Result<QpuOracleState, String> {
299 let mut state = cached_state();
300 f(&mut state);
301 persist_state(&state)?;
302 *QPU_CACHE.lock().unwrap() = Some(state.clone());
303 Ok(state)
304}
305
306pub fn verify_commitment(input: &str) -> bool {
311 let trimmed = input.trim();
312 if trimmed.is_empty() {
315 return false;
316 }
317 if trimmed.eq_ignore_ascii_case(COMMITMENT_TEXT) {
318 return true;
319 }
320 if trimmed == COMMITMENT_B64 {
321 return true;
322 }
323 if let Ok(decoded) = base64_decode(COMMITMENT_B64) {
325 if trimmed.eq_ignore_ascii_case(&decoded) {
326 return true;
327 }
328 }
329 false
330}
331
332fn base64_decode(s: &str) -> Result<String, ()> {
333 let alphabet = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
335 let mut out = Vec::new();
336 let bytes: Vec<u8> = s.bytes().filter(|b| *b != b'=').collect();
337 let mut i = 0;
338 while i + 3 < bytes.len() + 1 {
339 let chunk = &bytes[i..i.min(bytes.len()).min(i + 4)];
340 if chunk.is_empty() {
341 break;
342 }
343 let vals: Vec<u8> = chunk
344 .iter()
345 .map(|b| alphabet.iter().position(|a| a == b).unwrap_or(0) as u8)
346 .collect();
347 if vals.len() >= 2 {
348 out.push((vals[0] << 2) | (vals[1] >> 4));
349 }
350 if vals.len() >= 3 {
351 out.push((vals[1] << 4) | (vals[2] >> 2));
352 }
353 if vals.len() >= 4 {
354 out.push((vals[2] << 6) | vals[3]);
355 }
356 i += 4;
357 }
358 String::from_utf8(out).map_err(|_| ())
359}
360
361pub fn activate_with_commitment(commitment_text: &str) -> Result<QpuOracleSettings, String> {
366 if !verify_commitment(commitment_text) {
367 return Err("Commitment not recognised. Please enter: \
368 \"I Affirm My Commitment to Universal Human Rights\""
369 .into());
370 }
371 let now = chrono::Utc::now().to_rfc3339();
372 update_state(|state| {
373 state.feature_unlocked = true;
374 state.commitment_affirmed_at = Some(now.clone());
375 })
376 .map(|s| to_public_settings(&s))
377}
378
379pub fn to_public_settings(state: &QpuOracleState) -> QpuOracleSettings {
383 let providers = vec![
384 QpuProviderStatus {
385 provider: "ibm".into(),
386 name: QpuProvider::Ibm.name().into(),
387 architecture: "GateModel".into(),
388 configured: !state.ibm_token_enc.is_empty(),
389 docs_url: QpuProvider::Ibm.docs_url().into(),
390 minutes_used: state.ibm_minutes_used,
391 monthly_quota: IBM_MONTHLY_MINUTES,
392 },
393 QpuProviderStatus {
394 provider: "dwave".into(),
395 name: QpuProvider::DWave.name().into(),
396 architecture: "Annealer".into(),
397 configured: !state.dwave_token_enc.is_empty(),
398 docs_url: QpuProvider::DWave.docs_url().into(),
399 minutes_used: state.dwave_minutes_used,
400 monthly_quota: DWAVE_MONTHLY_MINUTES,
401 },
402 QpuProviderStatus {
403 provider: "ionq".into(),
404 name: QpuProvider::IonQ.name().into(),
405 architecture: "TrappedIon".into(),
406 configured: !state.ionq_token_enc.is_empty(),
407 docs_url: QpuProvider::IonQ.docs_url().into(),
408 minutes_used: state.ionq_minutes_used,
409 monthly_quota: IONQ_MONTHLY_MINUTES,
410 },
411 QpuProviderStatus {
412 provider: "rigetti".into(),
413 name: QpuProvider::Rigetti.name().into(),
414 architecture: "GateModel".into(),
415 configured: !state.rigetti_token_enc.is_empty(),
416 docs_url: QpuProvider::Rigetti.docs_url().into(),
417 minutes_used: state.rigetti_minutes_used,
418 monthly_quota: RIGETTI_MONTHLY_MINUTES,
419 },
420 QpuProviderStatus {
421 provider: "azure".into(),
422 name: QpuProvider::Azure.name().into(),
423 architecture: "GateModel".into(),
424 configured: !state.azure_credentials_enc.is_empty(),
425 docs_url: QpuProvider::Azure.docs_url().into(),
426 minutes_used: state.azure_minutes_used,
427 monthly_quota: AZURE_MONTHLY_MINUTES,
428 },
429 QpuProviderStatus {
430 provider: "braket".into(),
431 name: QpuProvider::Braket.name().into(),
432 architecture: "GateModel".into(),
433 configured: !state.braket_credentials_enc.is_empty(),
434 docs_url: QpuProvider::Braket.docs_url().into(),
435 minutes_used: state.braket_minutes_used,
436 monthly_quota: BRAKET_MONTHLY_MINUTES,
437 },
438 QpuProviderStatus {
439 provider: "google".into(),
440 name: QpuProvider::Google.name().into(),
441 architecture: "GateModel".into(),
442 configured: !state.google_token_enc.is_empty(),
443 docs_url: QpuProvider::Google.docs_url().into(),
444 minutes_used: state.google_minutes_used,
445 monthly_quota: GOOGLE_MONTHLY_MINUTES,
446 },
447 QpuProviderStatus {
448 provider: "quantinuum".into(),
449 name: QpuProvider::Quantinuum.name().into(),
450 architecture: "TrappedIon".into(),
451 configured: !state.quantinuum_token_enc.is_empty(),
452 docs_url: QpuProvider::Quantinuum.docs_url().into(),
453 minutes_used: state.quantinuum_minutes_used,
454 monthly_quota: QUANTINUUM_MONTHLY_MINUTES,
455 },
456 ];
457
458 QpuOracleSettings {
459 feature_unlocked: state.feature_unlocked,
460 commitment_affirmed: state.commitment_affirmed_at.is_some(),
461 ibm_token_configured: !state.ibm_token_enc.is_empty(),
462 dwave_token_configured: !state.dwave_token_enc.is_empty(),
463 providers,
464 max_shots_per_task: state.max_shots_per_task,
465 fallback_to_classical: state.fallback_to_classical,
466 enable_qubo_routing: state.enable_qubo_routing,
467 enable_dft_ground_state: state.enable_dft_ground_state,
468 enable_defeasible_resolution: state.enable_defeasible_resolution,
469 ibm_quota_minutes_remaining: (IBM_MONTHLY_MINUTES - state.ibm_minutes_used).max(0.0),
470 dwave_quota_minutes_remaining: (DWAVE_MONTHLY_MINUTES - state.dwave_minutes_used).max(0.0),
471 }
472}
473
474pub fn get_qpu_settings() -> QpuOracleSettings {
476 to_public_settings(&cached_state())
477}
478
479pub fn is_qpu_feature_unlocked() -> bool {
481 cached_state().feature_unlocked
482}
483
484pub fn save_qpu_settings(input: QpuOracleSettingsInput) -> Result<QpuOracleSettings, String> {
486 if input.max_shots_per_task == 0 || input.max_shots_per_task > 1000 {
487 return Err("max_shots_per_task must be between 1 and 1000 (SHACL bound)".into());
488 }
489 update_state(|state| {
490 state.max_shots_per_task = input.max_shots_per_task;
491 state.fallback_to_classical = input.fallback_to_classical;
492 state.enable_qubo_routing = input.enable_qubo_routing;
493 state.enable_dft_ground_state = input.enable_dft_ground_state;
494 state.enable_defeasible_resolution = input.enable_defeasible_resolution;
495 if let Some(ref tok) = input.ibm_token {
496 state.ibm_token_enc = encrypt_secret(tok).unwrap_or_default();
497 }
498 if let Some(ref tok) = input.dwave_token {
499 state.dwave_token_enc = encrypt_secret(tok).unwrap_or_default();
500 }
501 if let Some(ref tok) = input.ionq_token {
502 state.ionq_token_enc = encrypt_secret(tok).unwrap_or_default();
503 }
504 if let Some(ref tok) = input.rigetti_token {
505 state.rigetti_token_enc = encrypt_secret(tok).unwrap_or_default();
506 }
507 if let Some(ref creds) = input.azure_credentials {
508 state.azure_credentials_enc = encrypt_secret(creds).unwrap_or_default();
509 }
510 if let Some(ref creds) = input.braket_credentials {
511 state.braket_credentials_enc = encrypt_secret(creds).unwrap_or_default();
512 }
513 if let Some(ref tok) = input.google_token {
514 state.google_token_enc = encrypt_secret(tok).unwrap_or_default();
515 }
516 if let Some(ref tok) = input.quantinuum_token {
517 state.quantinuum_token_enc = encrypt_secret(tok).unwrap_or_default();
518 }
519 })
520 .map(|s| to_public_settings(&s))
521}
522
523pub fn enable_qpu_feature() -> Result<QpuOracleSettings, String> {
525 update_state(|state| state.feature_unlocked = true).map(|s| to_public_settings(&s))
526}
527
528pub fn disable_qpu_feature() -> Result<QpuOracleSettings, String> {
530 update_state(|state| state.feature_unlocked = false).map(|s| to_public_settings(&s))
531}
532
533pub fn record_usage(arch: QpuArchitecture, minutes: f64) -> Result<(), String> {
535 update_state(|state| match arch {
536 QpuArchitecture::GateModel => state.ibm_minutes_used += minutes,
537 QpuArchitecture::Annealer => state.dwave_minutes_used += minutes,
538 QpuArchitecture::TrappedIon => state.ionq_minutes_used += minutes,
539 QpuArchitecture::PhotonicGate => state.google_minutes_used += minutes,
540 QpuArchitecture::NeutralAtom => state.braket_minutes_used += minutes,
541 })
542 .map(|_| ())
543}
544
545pub fn record_provider_usage(provider: QpuProvider, minutes: f64) -> Result<(), String> {
547 update_state(|state| match provider {
548 QpuProvider::Ibm => state.ibm_minutes_used += minutes,
549 QpuProvider::DWave => state.dwave_minutes_used += minutes,
550 QpuProvider::IonQ => state.ionq_minutes_used += minutes,
551 QpuProvider::Rigetti => state.rigetti_minutes_used += minutes,
552 QpuProvider::Azure => state.azure_minutes_used += minutes,
553 QpuProvider::Braket => state.braket_minutes_used += minutes,
554 QpuProvider::Google => state.google_minutes_used += minutes,
555 QpuProvider::Quantinuum => state.quantinuum_minutes_used += minutes,
556 })
557 .map(|_| ())
558}
559
560pub fn resolve_ibm_token() -> Option<String> {
564 let state = cached_state();
565 if !state.feature_unlocked || state.ibm_token_enc.is_empty() {
566 return None;
567 }
568 decrypt_secret(&state.ibm_token_enc).ok()
569}
570
571pub fn resolve_dwave_token() -> Option<String> {
573 let state = cached_state();
574 if !state.feature_unlocked || state.dwave_token_enc.is_empty() {
575 return None;
576 }
577 decrypt_secret(&state.dwave_token_enc).ok()
578}
579
580pub fn resolve_ionq_token() -> Option<String> {
582 let state = cached_state();
583 if !state.feature_unlocked || state.ionq_token_enc.is_empty() {
584 return None;
585 }
586 decrypt_secret(&state.ionq_token_enc).ok()
587}
588
589pub fn resolve_rigetti_token() -> Option<String> {
591 let state = cached_state();
592 if !state.feature_unlocked || state.rigetti_token_enc.is_empty() {
593 return None;
594 }
595 decrypt_secret(&state.rigetti_token_enc).ok()
596}
597
598pub fn resolve_azure_credentials() -> Option<(String, String, String, String)> {
600 let state = cached_state();
601 if !state.feature_unlocked || state.azure_credentials_enc.is_empty() {
602 return None;
603 }
604 let raw = decrypt_secret(&state.azure_credentials_enc).ok()?;
605 let parts: Vec<&str> = raw.splitn(4, '/').collect();
606 if parts.len() == 4 {
607 Some((
608 parts[0].to_string(),
609 parts[1].to_string(),
610 parts[2].to_string(),
611 parts[3].to_string(),
612 ))
613 } else {
614 None
615 }
616}
617
618pub fn resolve_braket_credentials() -> Option<(String, String, String)> {
620 let state = cached_state();
621 if !state.feature_unlocked || state.braket_credentials_enc.is_empty() {
622 return None;
623 }
624 let raw = decrypt_secret(&state.braket_credentials_enc).ok()?;
625 let parts: Vec<&str> = raw.splitn(3, '|').collect();
626 if parts.len() == 3 {
627 Some((
628 parts[0].to_string(),
629 parts[1].to_string(),
630 parts[2].to_string(),
631 ))
632 } else {
633 None
634 }
635}
636
637pub fn resolve_google_token() -> Option<String> {
639 let state = cached_state();
640 if !state.feature_unlocked || state.google_token_enc.is_empty() {
641 return None;
642 }
643 decrypt_secret(&state.google_token_enc).ok()
644}
645
646pub fn resolve_quantinuum_token() -> Option<String> {
648 let state = cached_state();
649 if !state.feature_unlocked || state.quantinuum_token_enc.is_empty() {
650 return None;
651 }
652 decrypt_secret(&state.quantinuum_token_enc).ok()
653}
654
655pub fn target_architecture(task: &str) -> Option<QpuArchitecture> {
659 let state = cached_state();
660 if !state.feature_unlocked {
661 return None;
662 }
663 match task {
664 "qubo_routing" if state.enable_qubo_routing => Some(QpuArchitecture::Annealer),
665 "dft_ground_state" if state.enable_dft_ground_state => Some(QpuArchitecture::GateModel),
666 "defeasible_resolution" if state.enable_defeasible_resolution => {
667 Some(QpuArchitecture::GateModel)
668 }
669 _ => None,
670 }
671}
672
673pub fn select_provider(task: &str) -> Option<QpuProvider> {
675 let state = cached_state();
676 if !state.feature_unlocked {
677 return None;
678 }
679 match task {
680 "qubo_routing" if state.enable_qubo_routing => {
681 if !state.dwave_token_enc.is_empty() {
683 Some(QpuProvider::DWave)
684 } else if !state.ionq_token_enc.is_empty() {
685 Some(QpuProvider::IonQ)
686 } else if !state.ibm_token_enc.is_empty() {
687 Some(QpuProvider::Ibm)
688 } else {
689 None
690 }
691 }
692 "dft_ground_state" if state.enable_dft_ground_state => {
693 if !state.quantinuum_token_enc.is_empty() {
695 Some(QpuProvider::Quantinuum)
696 } else if !state.ionq_token_enc.is_empty() {
697 Some(QpuProvider::IonQ)
698 } else if !state.ibm_token_enc.is_empty() {
699 Some(QpuProvider::Ibm)
700 } else if !state.rigetti_token_enc.is_empty() {
701 Some(QpuProvider::Rigetti)
702 } else if !state.google_token_enc.is_empty() {
703 Some(QpuProvider::Google)
704 } else {
705 None
706 }
707 }
708 _ => None,
709 }
710}
711
712pub fn handle_qpu_chat_command(text: &str) -> QpuChatCommandResult {
716 let normalized = text.trim();
717
718 let enable_cmds = [
719 "[enable_QPU]",
720 "[enable_QPU}",
721 "[enable_qpu]",
722 "[enable_qpu}",
723 ];
724 let disable_cmds = [
725 "[disable_QPU]",
726 "[disable_QPU}",
727 "[disable_qpu]",
728 "[disable_qpu}",
729 ];
730
731 if enable_cmds
732 .iter()
733 .any(|c| normalized.eq_ignore_ascii_case(c))
734 {
735 if !cached_state().commitment_affirmed_at.is_some() {
737 return QpuChatCommandResult {
738 handled: true,
739 feature_unlocked: false,
740 response: "⚛️ **QPU Oracle requires activation.**\n\n\
741 To activate, open **Settings → Advanced Capabilities** and affirm:\n\n\
742 > *\"I Affirm My Commitment to Universal Human Rights\"*\n\n\
743 Or pass the activation code in the Settings panel."
744 .to_string(),
745 };
746 }
747 match enable_qpu_feature() {
748 Ok(settings) => QpuChatCommandResult {
749 handled: true,
750 feature_unlocked: settings.feature_unlocked,
751 response: "⚛️ **QPU Oracle unlocked.**\n\n\
752 Open **Settings → QPU Oracle** to configure provider API keys.\n\n\
753 **Supported providers:** IBM Quantum, D-Wave Leap, IonQ, Rigetti QCS, \
754 Azure Quantum, Amazon Braket, Google Quantum AI, Quantinuum\n\n\
755 **Chat commands:**\n\
756 - `[qpu:qubo]` or `$$\\min_{x} ...$$` → Annealing / QUBO routing\n\
757 - `[qpu:dft]` or `$$\\hat{H}\\Psi = E\\Psi$$` → VQE ground states\n\
758 - `[qpu:defeasible]` → probabilistic obligation resolution\n\n\
759 Only anonymised numeric matrices egress; classified data is blocked by Sentinel."
760 .to_string(),
761 },
762 Err(e) => QpuChatCommandResult {
763 handled: true,
764 feature_unlocked: false,
765 response: format!("🔴 QPU unlock failed: {e}"),
766 },
767 }
768 } else if disable_cmds
769 .iter()
770 .any(|c| normalized.eq_ignore_ascii_case(c))
771 {
772 match disable_qpu_feature() {
773 Ok(settings) => QpuChatCommandResult {
774 handled: true,
775 feature_unlocked: settings.feature_unlocked,
776 response: "⚛️ **QPU Oracle suspended.** Type `[enable_QPU]` to restore."
777 .to_string(),
778 },
779 Err(e) => QpuChatCommandResult {
780 handled: true,
781 feature_unlocked: cached_state().feature_unlocked,
782 response: format!("🔴 QPU disable failed: {e}"),
783 },
784 }
785 } else {
786 QpuChatCommandResult {
787 handled: false,
788 response: String::new(),
789 feature_unlocked: cached_state().feature_unlocked,
790 }
791 }
792}
793
794#[cfg(test)]
795mod tests {
796 use super::*;
797
798 #[test]
799 fn commitment_text_verifies() {
800 assert!(verify_commitment(
801 "I Affirm My Commitment to Universal Human Rights"
802 ));
803 assert!(verify_commitment(
804 "SSBBZmZpcm0gTXkgQ29tbWl0bWVudCB0byBVbml2ZXJzYWwgSHVtYW4gUmlnaHRz"
805 ));
806 assert!(!verify_commitment("something else"));
807 assert!(!verify_commitment(""));
808 }
809
810 #[test]
811 fn chat_command_not_handled_for_normal_text() {
812 let r = handle_qpu_chat_command("hello world");
813 assert!(!r.handled);
814 }
815
816 #[test]
817 fn provider_names_non_empty() {
818 for p in [
819 QpuProvider::Ibm,
820 QpuProvider::DWave,
821 QpuProvider::IonQ,
822 QpuProvider::Rigetti,
823 QpuProvider::Azure,
824 QpuProvider::Braket,
825 QpuProvider::Google,
826 QpuProvider::Quantinuum,
827 ] {
828 assert!(!p.name().is_empty());
829 assert!(!p.docs_url().is_empty());
830 }
831 }
832}