Skip to main content

lean_ctx/core/context_kernel/
identity.rs

1//! Identity and cost-center attribution for context-kernel requests.
2
3use std::cmp::Reverse;
4use std::collections::HashSet;
5
6use serde::{Deserialize, Serialize};
7
8/// Identity metadata attached to a context-kernel caller.
9#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
10pub struct CallerIdentity {
11    /// Stable user identifier, when known.
12    pub user_id: Option<String>,
13    /// Stable team identifier, when known.
14    pub team_id: Option<String>,
15    /// Enterprise cost center charged for the request, when known.
16    pub cost_center: Option<String>,
17    /// Functional role of the caller.
18    pub role: CallerRole,
19    /// Session identifier used when no user identifier is available.
20    pub session_id: Option<String>,
21}
22
23/// Functional role associated with a caller.
24#[derive(
25    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
26)]
27pub enum CallerRole {
28    /// Software developer using context directly.
29    #[default]
30    Developer,
31    /// Human reviewer evaluating generated work.
32    Reviewer,
33    /// Autonomous or delegated software agent.
34    Agent,
35    /// Internal system process.
36    System,
37    /// Administrative caller.
38    Admin,
39}
40
41/// Accumulated token and outcome metrics for one caller identity.
42#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
43pub struct IdentityAttribution {
44    /// Identity represented by this attribution entry.
45    pub identity: CallerIdentity,
46    /// Tokens delivered after context processing.
47    pub tokens_consumed: usize,
48    /// Tokens avoided through context processing.
49    pub tokens_saved: usize,
50    /// Number of requests attributed to the identity.
51    pub request_count: usize,
52    /// Number of accepted outcomes attributed to the identity.
53    pub accepted_outcomes: usize,
54}
55
56/// In-memory attribution ledger grouped by the strongest available identity key.
57#[derive(Debug, Clone, Default)]
58pub struct IdentityLedger {
59    entries: std::collections::HashMap<String, IdentityAttribution>,
60}
61
62impl IdentityLedger {
63    /// Creates an empty identity ledger.
64    #[must_use]
65    pub fn new() -> Self {
66        Self::default()
67    }
68
69    /// Records token usage, savings, and outcome acceptance for a caller.
70    pub fn record(
71        &mut self,
72        identity: &CallerIdentity,
73        consumed: usize,
74        saved: usize,
75        accepted: bool,
76    ) {
77        let key = Self::ledger_key(identity);
78        let attribution = self
79            .entries
80            .entry(key)
81            .or_insert_with(|| IdentityAttribution {
82                identity: identity.clone(),
83                tokens_consumed: 0,
84                tokens_saved: 0,
85                request_count: 0,
86                accepted_outcomes: 0,
87            });
88        attribution.tokens_consumed = attribution.tokens_consumed.saturating_add(consumed);
89        attribution.tokens_saved = attribution.tokens_saved.saturating_add(saved);
90        attribution.request_count = attribution.request_count.saturating_add(1);
91        if accepted {
92            attribution.accepted_outcomes = attribution.accepted_outcomes.saturating_add(1);
93        }
94    }
95
96    /// Returns attribution recorded under an identity key.
97    #[must_use]
98    pub fn attribution_for(&self, key: &str) -> Option<&IdentityAttribution> {
99        self.entries.get(key)
100    }
101
102    /// Returns up to `limit` entries ordered by descending token consumption.
103    #[must_use]
104    pub fn top_consumers(&self, limit: usize) -> Vec<&IdentityAttribution> {
105        let mut entries: Vec<_> = self.entries.values().collect();
106        entries.sort_unstable_by_key(|entry| Reverse(entry.tokens_consumed));
107        entries.truncate(limit);
108        entries
109    }
110
111    /// Returns up to `limit` entries ordered by descending token savings.
112    #[must_use]
113    pub fn top_savers(&self, limit: usize) -> Vec<&IdentityAttribution> {
114        let mut entries: Vec<_> = self.entries.values().collect();
115        entries.sort_unstable_by_key(|entry| Reverse(entry.tokens_saved));
116        entries.truncate(limit);
117        entries
118    }
119
120    /// Returns total tokens consumed across all identities.
121    #[must_use]
122    pub fn total_tokens(&self) -> usize {
123        self.entries.values().fold(0, |total, entry| {
124            total.saturating_add(entry.tokens_consumed)
125        })
126    }
127
128    /// Returns total tokens saved across all identities.
129    #[must_use]
130    pub fn total_savings(&self) -> usize {
131        self.entries
132            .values()
133            .fold(0, |total, entry| total.saturating_add(entry.tokens_saved))
134    }
135
136    /// Summarizes distinct identities and aggregate token efficiency.
137    #[must_use]
138    pub fn summary(&self) -> IdentityLedgerSummary {
139        let users: HashSet<_> = self
140            .entries
141            .values()
142            .filter_map(|entry| entry.identity.user_id.as_deref())
143            .collect();
144        let teams: HashSet<_> = self
145            .entries
146            .values()
147            .filter_map(|entry| entry.identity.team_id.as_deref())
148            .collect();
149        let total_tokens = self.total_tokens();
150        let total_savings = self.total_savings();
151        let original_tokens = total_tokens.saturating_add(total_savings);
152        let savings_rate = if original_tokens == 0 {
153            0.0
154        } else {
155            total_savings as f64 / original_tokens as f64
156        };
157
158        IdentityLedgerSummary {
159            total_users: users.len(),
160            total_teams: teams.len(),
161            total_tokens,
162            total_savings,
163            savings_rate,
164        }
165    }
166
167    fn ledger_key(identity: &CallerIdentity) -> String {
168        identity
169            .user_id
170            .as_ref()
171            .or(identity.session_id.as_ref())
172            .or(identity.team_id.as_ref())
173            .or(identity.cost_center.as_ref())
174            .cloned()
175            .unwrap_or_else(|| {
176                match identity.role {
177                    CallerRole::Developer => "developer",
178                    CallerRole::Reviewer => "reviewer",
179                    CallerRole::Agent => "agent",
180                    CallerRole::System => "system",
181                    CallerRole::Admin => "admin",
182                }
183                .to_owned()
184            })
185    }
186}
187
188/// Aggregate identity-ledger metrics.
189#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
190pub struct IdentityLedgerSummary {
191    /// Number of distinct known users.
192    pub total_users: usize,
193    /// Number of distinct known teams.
194    pub total_teams: usize,
195    /// Tokens consumed across all identities.
196    pub total_tokens: usize,
197    /// Tokens saved across all identities.
198    pub total_savings: usize,
199    /// Fraction of original tokens eliminated by context processing.
200    pub savings_rate: f64,
201}
202
203#[cfg(test)]
204pub mod tests {
205    use super::{CallerIdentity, CallerRole, IdentityLedger};
206
207    fn identity(user: &str, team: &str) -> CallerIdentity {
208        CallerIdentity {
209            user_id: Some(user.to_owned()),
210            team_id: Some(team.to_owned()),
211            ..CallerIdentity::default()
212        }
213    }
214
215    #[test]
216    fn identity_default() {
217        assert_eq!(CallerIdentity::default().role, CallerRole::Developer);
218    }
219
220    #[test]
221    fn ledger_record_single() {
222        let mut ledger = IdentityLedger::new();
223        ledger.record(&identity("alice", "platform"), 80, 20, true);
224
225        let entry = ledger
226            .attribution_for("alice")
227            .expect("alice must have attribution");
228        assert_eq!(entry.tokens_consumed, 80);
229        assert_eq!(entry.tokens_saved, 20);
230        assert_eq!(entry.request_count, 1);
231        assert_eq!(entry.accepted_outcomes, 1);
232    }
233
234    #[test]
235    fn ledger_record_multiple_same_user() {
236        let mut ledger = IdentityLedger::new();
237        let caller = identity("alice", "platform");
238        ledger.record(&caller, 80, 20, true);
239        ledger.record(&caller, 40, 10, false);
240
241        let entry = ledger
242            .attribution_for("alice")
243            .expect("alice must have attribution");
244        assert_eq!(entry.tokens_consumed, 120);
245        assert_eq!(entry.tokens_saved, 30);
246        assert_eq!(entry.request_count, 2);
247        assert_eq!(entry.accepted_outcomes, 1);
248    }
249
250    #[test]
251    fn top_consumers_sorted() {
252        let mut ledger = IdentityLedger::new();
253        ledger.record(&identity("small", "one"), 10, 20, false);
254        ledger.record(&identity("large", "two"), 90, 5, false);
255
256        let consumers = ledger.top_consumers(2);
257        assert_eq!(consumers[0].identity.user_id.as_deref(), Some("large"));
258        assert_eq!(consumers[1].identity.user_id.as_deref(), Some("small"));
259    }
260
261    #[test]
262    fn top_savers_sorted() {
263        let mut ledger = IdentityLedger::new();
264        ledger.record(&identity("small", "one"), 90, 5, false);
265        ledger.record(&identity("large", "two"), 10, 20, false);
266
267        let savers = ledger.top_savers(2);
268        assert_eq!(savers[0].identity.user_id.as_deref(), Some("large"));
269        assert_eq!(savers[1].identity.user_id.as_deref(), Some("small"));
270    }
271
272    #[test]
273    fn summary_counts_unique() {
274        let mut ledger = IdentityLedger::new();
275        ledger.record(&identity("alice", "platform"), 80, 20, true);
276        ledger.record(&identity("bob", "platform"), 70, 30, false);
277
278        let summary = ledger.summary();
279        assert_eq!(summary.total_users, 2);
280        assert_eq!(summary.total_teams, 1);
281        assert_eq!(summary.total_tokens, 150);
282        assert_eq!(summary.total_savings, 50);
283        assert!((summary.savings_rate - 0.25).abs() < f64::EPSILON);
284    }
285
286    #[test]
287    fn serde_roundtrip() {
288        let original = CallerIdentity {
289            user_id: Some("alice".to_owned()),
290            team_id: Some("platform".to_owned()),
291            cost_center: Some("engineering".to_owned()),
292            role: CallerRole::Reviewer,
293            session_id: Some("session-1".to_owned()),
294        };
295        let json = serde_json::to_string(&original).expect("identity must serialize");
296        let decoded = serde_json::from_str(&json).expect("identity must deserialize");
297
298        assert_eq!(original, decoded);
299    }
300}
301
302/// Canonical task context carrying identifiers for the task lifecycle.
303/// Propagated through all runtime surfaces (envelope, MCP, proxy, hooks, events).
304#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
305pub struct TaskContext {
306    pub task_id: String,
307    pub trace_id: String,
308    pub parent_task_id: Option<String>,
309    pub session_id: Option<String>,
310    pub agent_id: Option<String>,
311    pub project_id: Option<String>,
312}
313
314impl TaskContext {
315    pub fn new_root() -> Self {
316        Self {
317            task_id: uuid::Uuid::new_v4().to_string(),
318            trace_id: uuid::Uuid::new_v4().to_string(),
319            parent_task_id: None,
320            session_id: None,
321            agent_id: None,
322            project_id: None,
323        }
324    }
325
326    pub fn new(task_id: impl Into<String>, trace_id: impl Into<String>) -> Self {
327        Self {
328            task_id: task_id.into(),
329            trace_id: trace_id.into(),
330            parent_task_id: None,
331            session_id: None,
332            agent_id: None,
333            project_id: None,
334        }
335    }
336}