Skip to main content

trusty_code/identity/
mod.rs

1//! Caller identity hierarchy for memory scoping in tcode.
2//!
3//! Why: Memory must be scoped according to who is calling — the operator
4//! (full access), the PM (bounded to a session), or a sub-agent (bounded to its
5//! own writes). Agents must not be able to self-elevate; the harness determines
6//! `CallerIdentity` at spawn time and enforces a recall ceiling so agent code
7//! can never bypass it.
8//! What: `CallerIdentity` is a sum type with three variants — `Ctrl`, `Pm`,
9//! `Agent` — each carrying the IDs needed to apply the right scope filter.
10//! `RecallCeiling` is the maximum scope a caller may recall.
11//! Test: See unit tests — agent identity caps recall at Agent; `auto_tags`
12//! returns the expected tag set for each variant.
13
14use serde::{Deserialize, Serialize};
15
16/// Env var name for spawn-time identity injection.
17///
18/// Why: Subprocesses cannot share Rust types with their parent; env vars ferry
19/// identity over the process boundary.
20/// What: `TCODE_CALLER` selects the variant (`ctrl`, `pm`, `agent`).
21/// Test: `caller_identity_from_env_*`.
22pub const ENV_CALLER: &str = "TCODE_CALLER";
23/// Session ID env var.
24pub const ENV_SESSION_ID: &str = "TCODE_SESSION_ID";
25/// Project ID env var.
26pub const ENV_PROJECT_ID: &str = "TCODE_PROJECT_ID";
27/// Agent ID env var.
28pub const ENV_AGENT_ID: &str = "TCODE_AGENT_ID";
29
30/// Which component is making a memory/context call.
31///
32/// Why: Each tier has different access rights to the memory store. Encoding
33/// the tier as a sum type makes the privilege boundary visible in every
34/// signature that needs to enforce it.
35/// What: `Ctrl` is the operator (unrestricted); `Pm` runs one session in a
36/// project; `Agent` is a single sub-agent inside that session.
37/// Test: `auto_tags_for_each_variant`, `max_recall_scope_for_each_variant`.
38#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
39#[serde(rename_all = "lowercase", tag = "kind")]
40pub enum CallerIdentity {
41    /// Operator / controller — unrestricted.
42    Ctrl,
43    /// PM — bounded to a single session within a project.
44    Pm {
45        session_id: String,
46        project_id: String,
47    },
48    /// Sub-agent — bounded to its own writes within a session.
49    Agent {
50        session_id: String,
51        project_id: String,
52        agent_id: String,
53    },
54}
55
56impl CallerIdentity {
57    /// Maximum scope this caller is allowed to recall.
58    ///
59    /// Why: Enforced by the harness — not by agent code. An agent that passes
60    /// `scope: "all"` is silently downgraded to `Agent`.
61    /// What: `Ctrl` → `All`, `Pm` → `Session`, `Agent` → `Agent`.
62    /// Test: `max_recall_scope_for_each_variant`.
63    pub fn max_recall_scope(&self) -> RecallCeiling {
64        match self {
65            Self::Ctrl => RecallCeiling::All,
66            Self::Pm { .. } => RecallCeiling::Session,
67            Self::Agent { .. } => RecallCeiling::Agent,
68        }
69    }
70
71    /// Tags to automatically apply when this caller stores a memory.
72    ///
73    /// Why: Auto-tagging at write time means future scope filters can match on
74    /// tags without trusting agent-supplied metadata.
75    /// What: `Ctrl` → `["scope/user"]`; `Pm` → session+project tags; `Agent`
76    /// → session+project+agent tags.
77    /// Test: `auto_tags_for_each_variant`.
78    pub fn auto_tags(&self) -> Vec<String> {
79        match self {
80            Self::Ctrl => vec!["scope/user".into()],
81            Self::Pm {
82                session_id,
83                project_id,
84            } => vec![
85                format!("session/{session_id}"),
86                format!("project/{project_id}"),
87            ],
88            Self::Agent {
89                session_id,
90                project_id,
91                agent_id,
92            } => vec![
93                format!("session/{session_id}"),
94                format!("project/{project_id}"),
95                format!("agent/{agent_id}"),
96            ],
97        }
98    }
99
100    /// Try to construct a `CallerIdentity` from environment variables.
101    ///
102    /// Why: Subprocesses receive identity as env vars; this constructor
103    /// centralises the parse logic.
104    /// What: Reads `TCODE_CALLER` and the corresponding ID vars.
105    /// Returns `None` if the env var is absent or unrecognised.
106    /// Test: `caller_identity_from_env_*`.
107    pub fn from_env() -> Option<Self> {
108        let kind = std::env::var(ENV_CALLER).ok()?;
109        match kind.as_str() {
110            "ctrl" => Some(Self::Ctrl),
111            "pm" => {
112                let session_id = std::env::var(ENV_SESSION_ID).ok()?;
113                let project_id = std::env::var(ENV_PROJECT_ID).ok()?;
114                Some(Self::Pm {
115                    session_id,
116                    project_id,
117                })
118            }
119            "agent" => {
120                let session_id = std::env::var(ENV_SESSION_ID).ok()?;
121                let project_id = std::env::var(ENV_PROJECT_ID).ok()?;
122                let agent_id = std::env::var(ENV_AGENT_ID).ok()?;
123                Some(Self::Agent {
124                    session_id,
125                    project_id,
126                    agent_id,
127                })
128            }
129            _ => None,
130        }
131    }
132
133    /// Return the session ID if this identity has one.
134    ///
135    /// Why: Memory tools that scope by session need to extract the ID
136    /// without pattern-matching on the full identity.
137    /// What: `Some(session_id)` for `Pm` and `Agent`, `None` for `Ctrl`.
138    /// Test: `session_id_for_each_variant`.
139    pub fn session_id(&self) -> Option<&str> {
140        match self {
141            Self::Ctrl => None,
142            Self::Pm { session_id, .. } => Some(session_id.as_str()),
143            Self::Agent { session_id, .. } => Some(session_id.as_str()),
144        }
145    }
146}
147
148/// Maximum recall scope for a `CallerIdentity`.
149///
150/// Why: Provides a named ceiling that the memory tool enforces server-side so
151/// agents can't request more than their tier allows.
152/// What: `All` > `Session` > `Agent` in scope breadth.
153/// Test: Covered by `max_recall_scope_for_each_variant`.
154#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
155#[serde(rename_all = "lowercase")]
156pub enum RecallCeiling {
157    /// May recall all memories.
158    All,
159    /// May recall memories scoped to the current session.
160    Session,
161    /// May recall only its own memories.
162    Agent,
163}
164
165// ── Tests ─────────────────────────────────────────────────────────────────────
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170
171    #[test]
172    fn max_recall_scope_for_each_variant() {
173        assert_eq!(CallerIdentity::Ctrl.max_recall_scope(), RecallCeiling::All);
174        assert_eq!(
175            CallerIdentity::Pm {
176                session_id: "s1".into(),
177                project_id: "p1".into()
178            }
179            .max_recall_scope(),
180            RecallCeiling::Session
181        );
182        assert_eq!(
183            CallerIdentity::Agent {
184                session_id: "s1".into(),
185                project_id: "p1".into(),
186                agent_id: "a1".into()
187            }
188            .max_recall_scope(),
189            RecallCeiling::Agent
190        );
191    }
192
193    #[test]
194    fn auto_tags_for_each_variant() {
195        let ctrl_tags = CallerIdentity::Ctrl.auto_tags();
196        assert_eq!(ctrl_tags, vec!["scope/user"]);
197
198        let pm_tags = CallerIdentity::Pm {
199            session_id: "s42".into(),
200            project_id: "p7".into(),
201        }
202        .auto_tags();
203        assert!(pm_tags.contains(&"session/s42".to_string()));
204        assert!(pm_tags.contains(&"project/p7".to_string()));
205        assert_eq!(pm_tags.len(), 2);
206
207        let agent_tags = CallerIdentity::Agent {
208            session_id: "s42".into(),
209            project_id: "p7".into(),
210            agent_id: "a99".into(),
211        }
212        .auto_tags();
213        assert!(agent_tags.contains(&"agent/a99".to_string()));
214        assert_eq!(agent_tags.len(), 3);
215    }
216
217    #[test]
218    fn session_id_for_each_variant() {
219        assert_eq!(CallerIdentity::Ctrl.session_id(), None);
220        assert_eq!(
221            CallerIdentity::Pm {
222                session_id: "sess".into(),
223                project_id: "proj".into()
224            }
225            .session_id(),
226            Some("sess")
227        );
228        assert_eq!(
229            CallerIdentity::Agent {
230                session_id: "sess".into(),
231                project_id: "proj".into(),
232                agent_id: "ag".into()
233            }
234            .session_id(),
235            Some("sess")
236        );
237    }
238
239    #[test]
240    fn caller_identity_roundtrips_json() {
241        let agent = CallerIdentity::Agent {
242            session_id: "s1".into(),
243            project_id: "p1".into(),
244            agent_id: "engineer".into(),
245        };
246        let json = serde_json::to_string(&agent).expect("serialize");
247        let back: CallerIdentity = serde_json::from_str(&json).expect("deserialize");
248        assert_eq!(agent, back);
249    }
250}