Skip to main content

qualia_client_core/conditioning/
prepared.rs

1//! The shared prepared semantic request (Prompt Precision route carry).
2//!
3//! One profile document — the same JSON shape the POET HTTP API accepts under
4//! `conditioning` — is persisted at `{storage}/conditioning/active-profile.json`
5//! and compiled per turn by the core compiler
6//! (`poet_llm_conditioning::prepare_conditioned_prompt`). Every product route
7//! then lowers the *same plan*:
8//!
9//! - native / orchestrated chat: the rendered envelope is prepended to the
10//!   augmented prompt before decode;
11//! - Ollama: the envelope travels in the native `system` role field, with the
12//!   output budget carried as `num_predict`;
13//! - remote MCP: `lower_mcp_tool_arguments` produces structured or flattened
14//!   tool arguments with an explicit role-degradation receipt.
15//!
16//! "Same request" means same logical plan and traceability — wire syntax
17//! differs per backend capability and receipts say so honestly.
18
19use serde::{Deserialize, Serialize};
20use std::path::{Path, PathBuf};
21
22pub const ACTIVE_PROFILE_DIR: &str = "conditioning";
23pub const ACTIVE_PROFILE_FILENAME: &str = "active-profile.json";
24
25/// Active profile path.
26pub fn active_profile_path(storage: &Path) -> PathBuf {
27    storage
28        .join(ACTIVE_PROFILE_DIR)
29        .join(ACTIVE_PROFILE_FILENAME)
30}
31
32/// One compiled semantic request — route-neutral plan receipt plus the
33/// rendered request text the compiler produced for it.
34#[derive(Debug, Clone)]
35pub struct PreparedSemanticRequest {
36    pub profile_id: String,
37    pub plan_id: u64,
38    pub selected_evidence: usize,
39    pub token_budget: u32,
40    pub text: String,
41}
42
43/// Per-route lowering receipt attached to inference results. `route` is
44/// `"native"`, `"orchestrated"`, `"ollama"`, `"remote_mcp"` or `"http"`;
45/// `role_mode` records how the request reached the backend: `"envelope"`
46/// (merged into the prompt text), `"system"` (dedicated role field),
47/// `"structured"` (separate MCP arguments) or `"flattened"` (single argument).
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49pub struct PreparedRouteReceipt {
50    pub profile_id: String,
51    pub plan_id: u64,
52    pub selected_evidence: usize,
53    pub token_budget: u32,
54    pub route: String,
55    pub role_mode: String,
56    pub role_degraded: bool,
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub degradation_reason: Option<String>,
59}
60
61impl PreparedSemanticRequest {
62    /// Receipt.
63    pub fn receipt(
64        &self,
65        route: &str,
66        role_mode: &str,
67        role_degraded: bool,
68        degradation_reason: Option<String>,
69    ) -> PreparedRouteReceipt {
70        PreparedRouteReceipt {
71            profile_id: self.profile_id.clone(),
72            plan_id: self.plan_id,
73            selected_evidence: self.selected_evidence,
74            token_budget: self.token_budget,
75            route: route.to_string(),
76            role_mode: role_mode.to_string(),
77            role_degraded,
78            degradation_reason,
79        }
80    }
81}
82
83/// The persisted active profile document, if present and well-formed JSON.
84pub fn load_active_profile(storage: &Path) -> Option<serde_json::Value> {
85    let raw = std::fs::read(active_profile_path(storage)).ok()?;
86    serde_json::from_slice(&raw).ok()
87}
88
89/// Validate a profile by compiling it once against an empty context, then
90/// persist it as the active profile shared by all inference routes.
91/// Returns the probe plan receipt.
92pub fn activate_profile(
93    storage: &Path,
94    profile: &serde_json::Value,
95) -> Result<PreparedRouteReceipt, String> {
96    let probe = prepare_semantic_request(
97        profile,
98        "profile activation validation",
99        "urn:qualia:profile-activation",
100        "",
101        64,
102    )?;
103    let path = active_profile_path(storage);
104    if let Some(parent) = path.parent() {
105        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
106    }
107    let bytes = serde_json::to_vec_pretty(profile).map_err(|e| e.to_string())?;
108    std::fs::write(&path, bytes).map_err(|e| e.to_string())?;
109    Ok(probe.receipt("activation", "envelope", false, None))
110}
111
112/// Clear the active profile. Returns whether a profile was present.
113pub fn deactivate_profile(storage: &Path) -> bool {
114    let path = active_profile_path(storage);
115    path.is_file() && std::fs::remove_file(path).is_ok()
116}
117
118/// Current activation state for status surfaces.
119pub fn active_profile_status(storage: &Path) -> serde_json::Value {
120    match load_active_profile(storage) {
121        Some(profile) => serde_json::json!({
122            "active": true,
123            "profile_id": profile.get("profile_id").cloned().unwrap_or(serde_json::Value::Null),
124            "path": active_profile_path(storage).to_string_lossy(),
125        }),
126        None => serde_json::json!({ "active": false }),
127    }
128}
129
130/// Compile one profile document against one request. Never silently
131/// rewrites: failures mean the declared profile cannot run, so callers
132/// fail closed instead of dropping enforced requirements.
133#[cfg(not(target_arch = "wasm32"))]
134pub fn prepare_semantic_request(
135    profile: &serde_json::Value,
136    prompt: &str,
137    principal_did: &str,
138    graph_context: &str,
139    max_tokens: u32,
140) -> Result<PreparedSemanticRequest, String> {
141    let prepared = qualia_core_db::services::poet_llm_conditioning::prepare_conditioned_prompt(
142        profile,
143        prompt,
144        principal_did,
145        graph_context,
146        max_tokens,
147    )?;
148    Ok(PreparedSemanticRequest {
149        profile_id: prepared.profile_id.unwrap_or_default(),
150        plan_id: prepared.plan_id.unwrap_or(0),
151        selected_evidence: prepared.selected_evidence,
152        token_budget: prepared.token_budget,
153        text: prepared.text,
154    })
155}
156
157#[cfg(target_arch = "wasm32")]
158/// Prepares a semantic request.
159pub fn prepare_semantic_request(
160    _profile: &serde_json::Value,
161    _prompt: &str,
162    _principal_did: &str,
163    _graph_context: &str,
164    _max_tokens: u32,
165) -> Result<PreparedSemanticRequest, String> {
166    Err("the conditioning compiler is not available on wasm targets".to_string())
167}
168
169/// Compile the persisted active profile for this turn.
170/// `Ok(None)` when no profile is active — routes keep their legacy shape.
171pub fn prepare_active_semantic_request(
172    storage: &Path,
173    prompt: &str,
174    principal_did: &str,
175    graph_context: &str,
176    max_tokens: u32,
177) -> Result<Option<PreparedSemanticRequest>, String> {
178    match load_active_profile(storage) {
179        Some(profile) => {
180            prepare_semantic_request(&profile, prompt, principal_did, graph_context, max_tokens)
181                .map(Some)
182        }
183        None => Ok(None),
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    fn sample_profile() -> serde_json::Value {
192        serde_json::json!({
193            "schema_version": 1,
194            "profile_id": "urn:qualia:profile:test-suite",
195            "requirements": [
196                {"id": "r1", "class": "enforced", "rule": "Cite only supplied evidence", "validator": "provenance", "required": true, "priority": 1}
197            ],
198            "evidence": [
199                {"source_id": "doc:a", "content": "Qualia keeps the final user request intact."}
200            ]
201        })
202    }
203
204    #[test]
205    fn activate_compile_persist_load_roundtrip() {
206        let dir = tempfile::tempdir().unwrap();
207        let receipt = activate_profile(dir.path(), &sample_profile()).unwrap();
208        assert_eq!(receipt.profile_id, "urn:qualia:profile:test-suite");
209        assert!(receipt.plan_id != 0);
210        assert!(active_profile_path(dir.path()).is_file());
211
212        let loaded = load_active_profile(dir.path()).unwrap();
213        assert_eq!(loaded["profile_id"], "urn:qualia:profile:test-suite");
214        assert_eq!(active_profile_status(dir.path())["active"], true);
215
216        assert!(deactivate_profile(dir.path()));
217        assert!(load_active_profile(dir.path()).is_none());
218        assert!(!deactivate_profile(dir.path()));
219    }
220
221    #[test]
222    fn prepared_request_carries_plan_and_receipt() {
223        let dir = tempfile::tempdir().unwrap();
224        activate_profile(dir.path(), &sample_profile()).unwrap();
225        let prepared = prepare_active_semantic_request(
226            dir.path(),
227            "Summarise the evidence",
228            "did:example:alice",
229            "urn:test:ctx",
230            128,
231        )
232        .unwrap()
233        .expect("active profile should compile");
234
235        assert_eq!(prepared.profile_id, "urn:qualia:profile:test-suite");
236        assert!(prepared.text.contains("Cite only supplied evidence"));
237        assert!(prepared.text.contains("Summarise the evidence"));
238
239        let receipt = prepared.receipt("ollama", "system", false, None);
240        assert_eq!(receipt.route, "ollama");
241        assert_eq!(receipt.plan_id, prepared.plan_id);
242    }
243
244    #[test]
245    fn invalid_profile_fails_closed() {
246        let dir = tempfile::tempdir().unwrap();
247        let err =
248            activate_profile(dir.path(), &serde_json::json!({"requirements": 42})).unwrap_err();
249        assert!(err.contains("Invalid conditioning profile"));
250        assert!(load_active_profile(dir.path()).is_none());
251    }
252
253    #[test]
254    fn no_profile_is_ok_none() {
255        let dir = tempfile::tempdir().unwrap();
256        assert!(
257            prepare_active_semantic_request(dir.path(), "p", "d", "g", 64)
258                .unwrap()
259                .is_none()
260        );
261    }
262}