Skip to main content

systemprompt_identifiers/
context.rs

1//! Execution-context identifier — UUID v4 only.
2
3use crate::GatewayConversationId;
4use crate::error::IdValidationError;
5
6crate::define_id!(ContextId, validated, schema, validate_uuid_v4);
7
8fn validate_uuid_v4(s: &str) -> Result<(), IdValidationError> {
9    uuid::Uuid::parse_str(s).map_err(|e| IdValidationError::invalid("ContextId", e.to_string()))?;
10    Ok(())
11}
12
13// Why: UUID v5 namespace for deriving a stable `ContextId` from a
14// `GatewayConversationId`. Hardcoded so derivations match across processes
15// and rebuilds; rotating it would orphan every prior gateway audit row.
16const GATEWAY_CONVERSATION_NAMESPACE: uuid::Uuid =
17    uuid::Uuid::from_u128(0x993f_3f2c_f4d9_463b_853a_d3f0_3e19_0898);
18
19// Why: UUID v5 namespace for deriving a stable `ContextId` from a messaging
20// surface's (platform, org, channel) triple. Hardcoded so derivations match
21// across processes and rebuilds; rotating it would orphan every prior Slack /
22// Teams conversation's audit history.
23const MESSAGING_NAMESPACE: uuid::Uuid =
24    uuid::Uuid::from_u128(0x6b1d_2a7e_9c84_4f31_b5e0_71a2_4d8c_3f06);
25
26impl ContextId {
27    pub fn generate() -> Self {
28        Self::new(uuid::Uuid::new_v4().to_string())
29    }
30
31    /// Mint a deterministic `ContextId` from a `GatewayConversationId`.
32    ///
33    /// Same gateway-conversation id always produces the same `ContextId`, so
34    /// the gateway boundary can satisfy the "every conversation has a UUID
35    /// `ContextId`" data-integrity invariant without trusting the upstream
36    /// LLM client's `x-context-id` header (which carries client-specific
37    /// non-UUID identifiers).
38    #[must_use]
39    pub fn derived_from_gateway_conversation(gw: &GatewayConversationId) -> Self {
40        Self::new(
41            uuid::Uuid::new_v5(&GATEWAY_CONVERSATION_NAMESPACE, gw.as_str().as_bytes()).to_string(),
42        )
43    }
44
45    /// Mint a deterministic `ContextId` for a chat-platform conversation.
46    ///
47    /// The same `(platform, org, channel)` triple — e.g.
48    /// `("slack", workspace_id, channel_id)` or
49    /// `("teams", tenant_id, conversation_id)` — always produces the same
50    /// `ContextId`, so the messaging dispatch boundary satisfies the "every
51    /// conversation has a UUID `ContextId`" invariant without a channel→context
52    /// mapping table.
53    #[must_use]
54    pub fn derived_from_messaging(platform: &str, org: &str, channel: &str) -> Self {
55        let key = format!("{platform}:{org}:{channel}");
56        Self::new(uuid::Uuid::new_v5(&MESSAGING_NAMESPACE, key.as_bytes()).to_string())
57    }
58}