Skip to main content

qualia_client_core/inference_policy/
store.rs

1use super::{
2    actor::InferenceActorSession,
3    configuration::{self, InferenceHostConfiguration},
4    registry,
5};
6use qualia_cooperative_core::authoring::DocumentRevision;
7use qualia_core_db::{
8    key_vault::{KeyRole, KeyVault},
9    llm_agent::governed::{
10        GovernedTokenSession, InferenceAdmission, NativePolicyHost, PolicyError, PolicyRules,
11        PolicyStatus, MAX_POLICY_JSON_BYTES, POLICY_COLD_BUDGET_BYTES,
12    },
13    poet_host::native_authority::{NativeAuthority, SignedAdmission},
14};
15use std::{
16    path::{Path, PathBuf},
17    sync::{Arc, Mutex, OnceLock},
18};
19
20pub(super) struct ConfiguredHost {
21    root: PathBuf,
22    configuration_digest: [u8; 32],
23    pub owner: Arc<NativeAuthority>,
24    pub host: Arc<Mutex<NativePolicyHost>>,
25}
26impl Drop for ConfiguredHost {
27    fn drop(&mut self) {
28        self.host
29            .lock()
30            .unwrap_or_else(|e| e.into_inner())
31            .disconnect();
32    }
33}
34static HOST: OnceLock<Mutex<Option<ConfiguredHost>>> = OnceLock::new();
35
36/// Explicit logout/controller-loss hook. Dropping the policy host invalidates
37/// old admitted sessions; a new login cannot resurrect them.
38pub fn disconnect_inference_controller() {
39    registry::invalidate();
40    super::product::clear();
41    if let Some(host) = HOST.get() {
42        let mut slot = host.lock().unwrap_or_else(|e| e.into_inner());
43        *slot = None;
44    }
45    registry::revoke_tracked();
46}
47fn trust_failure(error: impl ToString) -> String {
48    disconnect_inference_controller();
49    error.to_string()
50}
51pub(super) fn meta_root() -> Result<PathBuf, String> {
52    let root = crate::state::app_meta_dir();
53    root.canonicalize()
54        .map_err(|_| "Application metadata directory is unavailable".into())
55}
56pub(super) fn child_directory(root: &Path, name: &str) -> Result<PathBuf, String> {
57    let path = root.join(name);
58    std::fs::create_dir_all(&path).map_err(|e| e.to_string())?;
59    let resolved = path.canonicalize().map_err(|e| e.to_string())?;
60    if !resolved.starts_with(root) {
61        return Err("Inference storage escapes configured metadata directory".into());
62    }
63    Ok(resolved)
64}
65pub(super) fn with_vault<T>(
66    operation: impl FnOnce(&KeyVault) -> Result<T, String>,
67) -> Result<T, String> {
68    let state = crate::state::APP_STATE
69        .get()
70        .ok_or_else(|| trust_failure("Application is not initialized"))?;
71    let vault = state
72        .key_vault
73        .lock()
74        .map_err(|_| trust_failure("Controller key vault lock failed"))?;
75    if vault.is_locked() {
76        return Err(trust_failure("Unlock the configured controller vault"));
77    }
78    operation(&vault)
79}
80pub(super) fn with_host<T>(
81    operation: impl FnOnce(
82        &mut ConfiguredHost,
83        &ed25519_dalek::SigningKey,
84        &KeyVault,
85    ) -> Result<T, String>,
86) -> Result<T, String> {
87    with_vault(|vault| {
88        let root = meta_root().map_err(trust_failure)?;
89        let key = vault.derive_key_for_role(KeyRole::ControllerSigning);
90        let (config, document) = configuration::load(&root, &key).map_err(trust_failure)?;
91        let digest = configuration::selection_digest(&config, &document);
92        let mut slot = match HOST.get_or_init(|| Mutex::new(None)).lock() {
93            Ok(s) => s,
94            Err(e) => {
95                let mut s = e.into_inner();
96                *s = None;
97                registry::invalidate();
98                registry::revoke_tracked();
99                return Err("Policy host lock failed; prior controller disconnected".into());
100            }
101        };
102        if slot
103            .as_ref()
104            .is_some_and(|h| h.root != root || h.configuration_digest != digest)
105        {
106            *slot = None;
107            registry::invalidate();
108            registry::revoke_tracked();
109        }
110        if slot.is_none() {
111            let owner = registry::open(&root, &config, &document, None)?;
112            let policy = child_directory(&root, "inference-policy")?;
113            let authority = child_directory(&root, "inference-policy-authority")?;
114            let host = NativePolicyHost::open(
115                &policy,
116                &authority,
117                config.trust()?,
118                POLICY_COLD_BUDGET_BYTES,
119            )
120            .map_err(|e| e.to_string())?;
121            *slot = Some(ConfiguredHost {
122                root,
123                configuration_digest: digest,
124                owner,
125                host: Arc::new(Mutex::new(host)),
126            });
127        }
128        operation(slot.as_mut().expect("host initialized"), &key, vault)
129    })
130}
131/// Privileged LOCAL host configuration, never an inference tool. Caller chooses
132/// an independent project trust anchor and supplies its actual signed admission
133/// and source revision. No configuration or policy is synthesized from a login.
134/// Typed inputs are caller-owned; earlier parsing allocations are outside this
135/// adapter budget. Existing native journal limits remain enforced independently.
136pub fn configure_inference_authority(
137    config: InferenceHostConfiguration,
138    admission: SignedAdmission,
139    document: DocumentRevision,
140    budget: usize,
141) -> Result<(), String> {
142    configuration::budget(budget)?;
143    with_vault(|vault| {
144        let key = vault.derive_key_for_role(KeyRole::ControllerSigning);
145        configuration::preflight(&config, &document, &key).map_err(trust_failure)?;
146        let root = meta_root().map_err(trust_failure)?;
147        // Local registry/epoch capacity refusals occur before invalidating state.
148        registry::preflight(&root, &config)?;
149        registry::preflight_epoch()?;
150        disconnect_inference_controller();
151        let result: Result<(), String> = (|| {
152            let owner = registry::open(&root, &config, &document, Some(admission))?;
153            let policy = child_directory(&root, "inference-policy")?;
154            let authority = child_directory(&root, "inference-policy-authority")?;
155            let host = NativePolicyHost::open(
156                &policy,
157                &authority,
158                config.trust()?,
159                POLICY_COLD_BUDGET_BYTES,
160            )
161            .map_err(|e| e.to_string())?;
162            configuration::save(&root, config.clone(), document.clone(), &key)?;
163            let mut slot = HOST
164                .get_or_init(|| Mutex::new(None))
165                .lock()
166                .map_err(|_| "Policy host lock failed")?;
167            *slot = Some(ConfiguredHost {
168                root,
169                configuration_digest: configuration::selection_digest(&config, &document),
170                owner,
171                host: Arc::new(Mutex::new(host)),
172            });
173            Ok(())
174        })();
175        result.map_err(trust_failure)
176    })
177}
178/// A real signed successor is verified by the existing project owner; no signing
179/// or enrollment authority is inferred from the acting inference session.
180pub fn replace_inference_admission(
181    replacement: SignedAdmission,
182    budget: usize,
183) -> Result<(), String> {
184    configuration::budget(budget)?;
185    let result = with_host(|h, _, _| {
186        h.host
187            .lock()
188            .map_err(|_| "Policy host lock failed")?
189            .disconnect();
190        registry::invalidate();
191        registry::revoke_tracked();
192        h.owner.replace_admission(replacement)
193    });
194    if result.is_err() {
195        disconnect_inference_controller();
196    }
197    result
198}
199pub fn install_policy(
200    rules_json: &str,
201    not_before: u64,
202    expires_at: u64,
203    now: u64,
204    expected_generation: u64,
205    budget: usize,
206) -> Result<PolicyStatus, String> {
207    if budget < POLICY_COLD_BUDGET_BYTES {
208        return Err(PolicyError::Budget.to_string());
209    }
210    if rules_json.len() > MAX_POLICY_JSON_BYTES {
211        return Err(PolicyError::Capacity.to_string());
212    }
213    let rules: PolicyRules =
214        serde_json::from_str(rules_json).map_err(|e| format!("Invalid Sentinel policy: {e}"))?;
215    with_host(|h, key, _| {
216        h.host
217            .lock()
218            .map_err(|_| "Policy host lock failed")?
219            .install(
220                key,
221                rules,
222                not_before,
223                expires_at,
224                now,
225                expected_generation,
226                budget,
227            )
228            .map_err(|e| e.to_string())
229    })
230}
231pub fn load_policy_status() -> Result<PolicyStatus, String> {
232    with_host(|h, _, _| {
233        Ok(h.host
234            .lock()
235            .map_err(|_| "Policy host lock failed")?
236            .status())
237    })
238}
239/// Install the actual V3 per-token evidence policy required by native products.
240/// Observation requirements are explicitly selected by the privileged host.
241pub fn install_evidence_policy(
242    rules_json: &str,
243    observations: qualia_core_db::llm_agent::governed::evidence::ObservationRequirements,
244    not_before: u64,
245    expires_at: u64,
246    expected_generation: u64,
247    budget: usize,
248) -> Result<PolicyStatus, String> {
249    if budget < POLICY_COLD_BUDGET_BYTES || rules_json.len() > MAX_POLICY_JSON_BYTES {
250        return Err(PolicyError::Budget.to_string());
251    }
252    let rules: PolicyRules =
253        serde_json::from_str(rules_json).map_err(|e| format!("Invalid Sentinel policy: {e}"))?;
254    with_host(|h, key, _| {
255        h.host
256            .lock()
257            .map_err(|_| "Policy host lock failed")?
258            .install_evidence(
259                key,
260                rules,
261                observations,
262                not_before,
263                expires_at,
264                expected_generation,
265                budget,
266            )
267            .map_err(|e| e.to_string())
268    })
269}
270pub fn revoke_policy(expected_generation: u64, budget: usize) -> Result<PolicyStatus, String> {
271    with_host(|h, key, _| {
272        h.host
273            .lock()
274            .map_err(|_| "Policy host lock failed")?
275            .revoke(key, expected_generation, budget)
276            .map_err(|e| e.to_string())
277    })
278}
279pub fn admit_inference(
280    request: InferenceAdmission,
281    actor: &InferenceActorSession,
282    budget: usize,
283) -> Result<GovernedTokenSession, String> {
284    with_host(|h, key, _| {
285        if !Arc::ptr_eq(&h.owner, actor.owner()) {
286            return Err("Actor belongs to a different configured authority".into());
287        }
288        let association = actor.bind()?;
289        h.host
290            .lock()
291            .map_err(|_| "Policy host lock failed")?
292            .admit(key, request, budget, Arc::clone(&h.owner), association)
293            .map_err(|e| e.to_string())
294    })
295}
296/// This native lifecycle entry invalidates policy before returning from vault lock.
297pub fn lock_inference_controller_vault() -> Result<(), String> {
298    let state = crate::state::APP_STATE
299        .get()
300        .ok_or("Application is not initialized")?;
301    let mut vault = state
302        .key_vault
303        .lock()
304        .map_err(|_| trust_failure("Controller key vault lock failed"))?;
305    vault.lock();
306    disconnect_inference_controller();
307    Ok(())
308}