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 // Safe: UUID v4 from `uuid` crate is always a valid UUID string.
29 Self::new(uuid::Uuid::new_v4().to_string())
30 }
31
32 /// Mint a deterministic `ContextId` from a `GatewayConversationId`.
33 ///
34 /// Same gateway-conversation id always produces the same `ContextId`, so
35 /// the gateway boundary can satisfy the "every conversation has a UUID
36 /// `ContextId`" data-integrity invariant without trusting the upstream
37 /// LLM client's `x-context-id` header (which carries client-specific
38 /// non-UUID identifiers).
39 #[must_use]
40 pub fn derived_from_gateway_conversation(gw: &GatewayConversationId) -> Self {
41 // Safe: UUID v5 always produces a valid UUID string.
42 Self::new(
43 uuid::Uuid::new_v5(&GATEWAY_CONVERSATION_NAMESPACE, gw.as_str().as_bytes()).to_string(),
44 )
45 }
46
47 /// Mint a deterministic `ContextId` for a chat-platform conversation.
48 ///
49 /// The same `(platform, org, channel)` triple — e.g.
50 /// `("slack", workspace_id, channel_id)` or
51 /// `("teams", tenant_id, conversation_id)` — always produces the same
52 /// `ContextId`, so the messaging dispatch boundary satisfies the "every
53 /// conversation has a UUID `ContextId`" invariant without a channel→context
54 /// mapping table.
55 #[must_use]
56 pub fn derived_from_messaging(platform: &str, org: &str, channel: &str) -> Self {
57 let key = format!("{platform}:{org}:{channel}");
58 // Safe: UUID v5 always produces a valid UUID string.
59 Self::new(uuid::Uuid::new_v5(&MESSAGING_NAMESPACE, key.as_bytes()).to_string())
60 }
61}