Skip to main content

systemprompt_identifiers/
context.rs

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