Skip to main content

ocp_types/
query.rs

1//! `context/query` request/response shapes
2//! (`docs/specs/stella-rust-cli/06-context-protocol.md` §3.3). Budget-aware
3//! by contract: every query carries `max_tokens`; a conforming provider
4//! never returns more than the budget and never lies about cost.
5
6use serde::{Deserialize, Serialize};
7
8use crate::frame::{ContextFrame, FrameKind};
9
10/// A request to an OCP provider for context frames relevant to a goal.
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12pub struct ContextQuery {
13    /// The task/turn goal driving retrieval.
14    pub goal: String,
15    #[serde(default, skip_serializing_if = "Option::is_none")]
16    pub query_text: Option<String>,
17    #[serde(default, skip_serializing_if = "Option::is_none")]
18    pub embedding: Option<Vec<f32>>,
19    #[serde(default, skip_serializing_if = "Vec::is_empty")]
20    pub kinds: Vec<FrameKind>,
21    /// Anchor URIs (open files, mentioned symbols) used for graph-proximity
22    /// scoring.
23    #[serde(default, skip_serializing_if = "Vec::is_empty")]
24    pub anchors: Vec<String>,
25    pub max_frames: u32,
26    pub max_tokens: u32,
27    /// Pin retrieval to a point in time for bi-temporal facts.
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub as_of: Option<String>,
30}
31
32/// The response to a `context/query` call.
33#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
34pub struct ContextQueryResult {
35    pub frames: Vec<ContextFrame>,
36    /// True if the provider had more candidates than fit the budget.
37    pub truncated: bool,
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub dropped_estimate: Option<u32>,
40}
41
42impl ContextQueryResult {
43    /// Sum of `token_cost` across returned frames — must never exceed the
44    /// query's `max_tokens` for a conforming provider (checked in
45    /// `ocp-conformance`, phase 3; this is the cheap client-side sanity
46    /// check any host can run today).
47    pub fn total_token_cost(&self) -> u64 {
48        self.frames.iter().map(|f| f.token_cost as u64).sum()
49    }
50
51    pub fn respects_budget(&self, max_tokens: u32) -> bool {
52        self.total_token_cost() <= max_tokens as u64
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59    use crate::frame::ContextFrame;
60
61    fn frame_with_cost(id: &str, cost: u32) -> ContextFrame {
62        ContextFrame {
63            id: id.into(),
64            kind: FrameKind::Snippet,
65            title: id.into(),
66            content: String::new(),
67            uri: None,
68            score: 0.5,
69            token_cost: cost,
70            valid_from: None,
71            valid_to: None,
72            recorded_at: None,
73            provenance: vec![],
74            citation_label: None,
75            embedding: None,
76            relations: vec![],
77        }
78    }
79
80    #[test]
81    fn context_query_roundtrips() {
82        let query = ContextQuery {
83            goal: "fix the failing test".into(),
84            query_text: Some("failing test".into()),
85            embedding: None,
86            kinds: vec![FrameKind::Symbol, FrameKind::Doc],
87            anchors: vec!["file:///repo/src/lib.rs".into()],
88            max_frames: 20,
89            max_tokens: 4000,
90            as_of: None,
91        };
92        let json = serde_json::to_string(&query).unwrap();
93        let back: ContextQuery = serde_json::from_str(&json).unwrap();
94        assert_eq!(back, query);
95    }
96
97    #[test]
98    fn respects_budget_true_when_under_or_at_limit() {
99        let result = ContextQueryResult {
100            frames: vec![frame_with_cost("a", 100), frame_with_cost("b", 200)],
101            truncated: false,
102            dropped_estimate: None,
103        };
104        assert_eq!(result.total_token_cost(), 300);
105        assert!(result.respects_budget(300));
106        assert!(result.respects_budget(500));
107    }
108
109    #[test]
110    fn respects_budget_false_when_provider_lies_about_cost() {
111        let result = ContextQueryResult {
112            frames: vec![frame_with_cost("a", 400)],
113            truncated: false,
114            dropped_estimate: None,
115        };
116        assert!(!result.respects_budget(300));
117    }
118}