1use chrono::Utc;
5use lean_ctx_protocol::{
6 AgentId, ProjectId, SessionId, TaskComplexity, TaskEnvelopeV1, TaskId, TaskProfileV1, TenantId,
7 TraceId,
8};
9use std::cell::RefCell;
10use std::collections::HashMap;
11use std::sync::{Arc, Mutex, OnceLock};
12
13pub type TaskProfileLocal = TaskProfileV1;
14
15thread_local! {
16 static CURRENT: RefCell<Option<TaskEnvelopeV1>> = const { RefCell::new(None) };
17}
18
19tokio::task_local! {
20 static SCOPED: Option<TaskEnvelopeV1>;
22}
23
24type SessionLineage = (String, String);
26type SessionLineages = Arc<Mutex<HashMap<(ProjectId, Option<TenantId>, String), SessionLineage>>>;
27static SESSION_LINEAGES: OnceLock<SessionLineages> = OnceLock::new();
28
29#[derive(Debug, Clone, PartialEq, Eq, Hash)]
31pub(crate) struct AdmittedTaskIdentity {
32 pub(crate) project_id: ProjectId,
33 pub(crate) tenant_id: TenantId,
34}
35
36#[derive(Debug, Clone, Default)]
37pub struct TaskSpine {
39 pub parent_id: Option<String>,
41 pub trace_id: String,
43}
44
45impl TaskSpine {
46 pub fn create_envelope(query: &str, session_id: &str, agent_id: &str) -> TaskEnvelopeV1 {
47 Self::create_envelope_in_project(query, session_id, agent_id, None)
48 }
49
50 pub(crate) fn create_envelope_in_project(
53 query: &str,
54 session_id: &str,
55 agent_id: &str,
56 project_root: Option<&str>,
57 ) -> TaskEnvelopeV1 {
58 Self::create_envelope_with_identity(query, session_id, agent_id, project_root, None)
59 }
60
61 pub(crate) fn create_envelope_with_identity(
62 query: &str,
63 session_id: &str,
64 agent_id: &str,
65 project_root: Option<&str>,
66 identity: Option<&AdmittedTaskIdentity>,
67 ) -> TaskEnvelopeV1 {
68 let project_id = identity
69 .map(|identity| identity.project_id.clone())
70 .or_else(|| project_root.and_then(|project| ProjectId::try_from(project).ok()))
71 .unwrap_or_else(|| {
72 ProjectId::try_from("unknown-project").expect("fallback project id is valid")
73 });
74 let task_id = TaskId::try_from(format!("mcp-task-{}", uuid::Uuid::new_v4()))
75 .expect("generated task id is valid");
76 let initial_trace_id = format!("trace-{}", uuid::Uuid::new_v4());
77 let tenant_id = identity.map(|identity| identity.tenant_id.clone());
78 let spine = Self::for_session(
79 &project_id,
80 tenant_id.as_ref(),
81 session_id,
82 task_id.as_str(),
83 &initial_trace_id,
84 );
85 let envelope = TaskEnvelopeV1 {
86 schema_version: TaskEnvelopeV1::SCHEMA_VERSION,
87 task_id,
88 trace_id: TraceId::try_from(spine.trace_id.clone())
89 .expect("generated trace id is valid"),
90 project_id,
91 session_id: SessionId::try_from(session_id.to_owned())
92 .expect("MCP session id is valid"),
93 agent_id: AgentId::try_from(agent_id.to_owned()).expect("MCP agent id is valid"),
94 complexity: TaskComplexity::Unknown,
95 created_at: Utc::now().to_rfc3339(),
96 parent_task_id: spine
97 .parent_id
98 .clone()
99 .map(TaskId::try_from)
100 .transpose()
101 .expect("stored parent task id is valid"),
102 tenant_id,
103 intent: (!query.trim().is_empty()).then(|| query.to_owned()),
104 task_class: None,
105 risk_class: None,
106 quality_requirement_milli: None,
107 cost_budget_micros: None,
108 latency_budget_ms: None,
109 data_classification: None,
110 region_policy_ref: None,
111 model_policy_ref: None,
112 context_state_ref: None,
113 outcome_contract_ref: None,
114 extensions: Default::default(),
115 };
116 Self::set(envelope.clone());
117 envelope
118 }
119
120 fn for_session(
121 project_id: &ProjectId,
122 tenant_id: Option<&TenantId>,
123 session_id: &str,
124 task_id: &str,
125 initial_trace_id: &str,
126 ) -> Self {
127 if session_id.trim().is_empty() {
128 return Self {
129 parent_id: None,
130 trace_id: initial_trace_id.to_owned(),
131 };
132 }
133
134 let mut lineages = Self::session_lineages()
135 .lock()
136 .unwrap_or_else(std::sync::PoisonError::into_inner);
137 let (parent_id, trace_id) = match lineages.entry((
138 project_id.clone(),
139 tenant_id.cloned(),
140 session_id.to_owned(),
141 )) {
142 std::collections::hash_map::Entry::Occupied(parent) => {
143 let (root_task_id, trace_id) = parent.get();
144 (Some(root_task_id.clone()), trace_id.clone())
145 }
146 std::collections::hash_map::Entry::Vacant(session) => {
147 session.insert((task_id.to_owned(), initial_trace_id.to_owned()));
148 (None, initial_trace_id.to_owned())
149 }
150 };
151 Self {
152 parent_id,
153 trace_id,
154 }
155 }
156
157 fn session_lineages() -> &'static SessionLineages {
158 SESSION_LINEAGES.get_or_init(|| Arc::new(Mutex::new(HashMap::new())))
159 }
160
161 pub fn enrich_from_triage(envelope: &mut TaskEnvelopeV1, profile: &TaskProfileLocal) {
162 envelope.intent = Some(profile.primary_intent.clone());
163 envelope.task_class = Some(profile.task_class.clone());
164 envelope.complexity = profile.complexity;
165 envelope.risk_class = Some(profile.risk_signal);
166 Self::set(envelope.clone());
167 }
168
169 pub fn task_id() -> Option<String> {
170 Self::current().map(|envelope| envelope.task_id.as_str().to_owned())
171 }
172
173 pub fn current() -> Option<TaskEnvelopeV1> {
174 SCOPED
175 .try_with(Clone::clone)
176 .unwrap_or_else(|_| CURRENT.with(|current| current.borrow().clone()))
177 }
178
179 pub(crate) fn scoped_current() -> Option<TaskEnvelopeV1> {
181 SCOPED.try_with(Clone::clone).ok().flatten()
182 }
183
184 pub fn set(envelope: TaskEnvelopeV1) {
186 if SCOPED.try_with(|_| ()).is_err() {
187 CURRENT.with(|current| *current.borrow_mut() = Some(envelope));
188 }
189 }
190
191 pub(crate) async fn scope<F: std::future::Future>(
192 envelope: Option<TaskEnvelopeV1>,
193 future: F,
194 ) -> F::Output {
195 SCOPED.scope(envelope, future).await
196 }
197
198 pub(crate) fn sync_scope<T>(
200 envelope: Option<TaskEnvelopeV1>,
201 operation: impl FnOnce() -> T,
202 ) -> T {
203 SCOPED.sync_scope(envelope, operation)
204 }
205
206 pub(crate) fn spawn_thread<T: Send + 'static>(
208 operation: impl FnOnce() -> T + Send + 'static,
209 ) -> std::thread::JoinHandle<T> {
210 let envelope = Self::current();
211 let project = crate::core::policy::runtime::REQUEST_PROJECT
212 .try_with(|slot| slot.borrow().clone())
213 .ok();
214 let source_view = crate::core::policy::runtime::inherited_source_view();
215 let admissions = crate::core::context_admission::capture::current();
217 let sources = crate::core::archive::authority::current_capture();
220 std::thread::spawn(move || {
221 let operation =
222 move || crate::core::archive::authority::CAPTURE.sync_scope(sources, operation);
223 crate::core::context_admission::capture::ADMISSIONS.sync_scope(admissions, || {
224 match project {
225 Some(project) => crate::core::policy::runtime::REQUEST_PROJECT.sync_scope(
226 std::cell::RefCell::new(project),
227 || {
228 crate::core::policy::runtime::with_inherited_source_view(
229 source_view,
230 || Self::sync_scope(envelope, operation),
231 )
232 },
233 ),
234 None => crate::core::policy::runtime::with_inherited_source_view(
235 source_view,
236 || Self::sync_scope(envelope, operation),
237 ),
238 }
239 })
240 })
241 }
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 #[test]
249 fn detached_read_workers_isolate_overlapping_policy_projects() {
250 use crate::core::policy::runtime::REQUEST_PROJECT;
251 let barrier = std::sync::Arc::new(std::sync::Barrier::new(3));
252 let workers = ["first-request-project", "second-request-project"].map(|name| {
253 let root = std::path::PathBuf::from(name);
254 let worker_barrier = barrier.clone();
255 let worker =
256 REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(root.clone())), || {
257 TaskSpine::spawn_thread(move || {
258 worker_barrier.wait();
259 REQUEST_PROJECT.with(|slot| slot.borrow().clone())
260 })
261 });
262 (root, worker)
263 });
264 barrier.wait();
265 for (root, worker) in workers {
266 assert_eq!(worker.join().unwrap(), Some(root));
267 }
268 }
269
270 #[test]
271 fn detached_worker_inherits_pinned_source_policy() {
272 use crate::core::policy::runtime::{self, REQUEST_PROJECT};
273 use std::fs;
274
275 let _data = crate::core::data_dir::isolated_data_dir();
276 let _override_guard = runtime::lock_test_override();
277 let root = tempfile::tempdir().expect("create project");
278 let policy_dir = root.path().join(".lean-ctx");
279 fs::create_dir_all(&policy_dir).expect("create policy directory");
280 let policy_path = policy_dir.join("policy.toml");
281 fs::write(
282 &policy_path,
283 "name = \"thread-a\"\nversion = \"1.0.0\"\ndescription = \"thread test\"\n",
284 )
285 .expect("write policy A");
286
287 let result =
288 REQUEST_PROJECT.sync_scope(RefCell::new(Some(root.path().to_path_buf())), || {
289 runtime::with_source_view(|| {
290 let worker = TaskSpine::spawn_thread(|| {
291 runtime::active().map(|policy| policy.resolved.name.clone())
292 });
293 fs::write(
294 &policy_path,
295 "name = \"thread-b\"\nversion = \"1.0.0\"\ndescription = \"thread test\"\n",
296 )
297 .expect("write policy B");
298 assert_eq!(worker.join().unwrap().as_deref(), Some("thread-a"));
299 })
300 });
301
302 assert!(result.is_err());
303 }
304
305 #[test]
306 fn detached_threads_preserve_bound_and_explicitly_unbound_identity() {
307 let task = TaskSpine::create_envelope("thread", "scoped-thread", "agent");
308 let worker = TaskSpine::sync_scope(Some(task.clone()), || {
309 TaskSpine::spawn_thread(TaskSpine::current)
310 });
311 assert_eq!(worker.join().unwrap(), Some(task));
312 let unbound = TaskSpine::sync_scope(None, || {
313 TaskSpine::spawn_thread(|| {
314 TaskSpine::create_envelope("decoy", "detached-decoy", "agent");
315 TaskSpine::current()
316 })
317 });
318 assert!(unbound.join().unwrap().is_none());
319 }
320
321 #[tokio::test(flavor = "current_thread")]
322 async fn async_scopes_isolate_interleaved_tasks_and_ignore_legacy_setters() {
323 let first = TaskSpine::create_envelope("first", "scoped-a", "agent-a");
324 let second = TaskSpine::create_envelope("second", "scoped-b", "agent-b");
325 let legacy = TaskSpine::current();
326 let check = |expected: TaskEnvelopeV1, other: TaskEnvelopeV1| async move {
327 TaskSpine::scope(Some(expected.clone()), async {
328 for _ in 0..5 {
329 TaskSpine::set(other.clone());
330 tokio::task::yield_now().await;
331 assert_eq!(TaskSpine::current(), Some(expected.clone()));
332 }
333 TaskSpine::scope(None, async {
334 assert!(TaskSpine::current().is_none());
335 TaskSpine::set(other);
336 assert!(TaskSpine::current().is_none());
337 })
338 .await;
339 assert_eq!(TaskSpine::current(), Some(expected));
340 })
341 .await;
342 };
343 tokio::join!(check(first.clone(), second.clone()), check(second, first));
344 assert_eq!(TaskSpine::current(), legacy);
345 }
346
347 #[test]
348 fn sync_scope_restores_identity_after_panic_and_masks_unbound_workers() {
349 let legacy = TaskSpine::create_envelope("legacy", "legacy-worker", "agent");
350 let scoped = TaskSpine::create_envelope("scoped", "scoped-worker", "agent");
351 TaskSpine::set(legacy.clone());
352 assert!(TaskSpine::scoped_current().is_none());
353 let panic = std::panic::catch_unwind(|| {
354 TaskSpine::sync_scope(Some(scoped.clone()), || {
355 assert_eq!(TaskSpine::scoped_current(), Some(scoped.clone()));
356 assert_eq!(TaskSpine::current(), Some(scoped));
357 panic!("fixture unwind");
358 })
359 });
360 assert!(panic.is_err());
361 assert_eq!(TaskSpine::current(), Some(legacy.clone()));
362 TaskSpine::sync_scope(None, || assert!(TaskSpine::current().is_none()));
363 assert_eq!(TaskSpine::current(), Some(legacy));
364 }
365
366 #[tokio::test(flavor = "current_thread")]
367 async fn cancelled_scope_does_not_replace_parent_identity() {
368 let parent = TaskSpine::create_envelope("parent", "cancel-parent", "agent");
369 let child = TaskSpine::create_envelope("child", "cancel-child", "agent");
370 TaskSpine::scope(Some(parent.clone()), async {
371 let task = TaskSpine::scope(Some(child), async {
372 std::future::pending::<()>().await;
373 });
374 assert!(
375 tokio::time::timeout(std::time::Duration::from_millis(10), task)
376 .await
377 .is_err()
378 );
379 assert_eq!(TaskSpine::current(), Some(parent));
380 })
381 .await;
382 }
383
384 #[test]
385 fn test_envelope_created_on_dispatch() {
386 let envelope =
387 TaskSpine::create_envelope("query", "session-task-spine", "agent-task-spine");
388 assert_eq!(
389 TaskSpine::task_id().as_deref(),
390 Some(envelope.task_id.as_str())
391 );
392 }
393
394 #[test]
395 fn test_envelope_has_valid_task_id() {
396 let first = TaskSpine::create_envelope("one", "session-task-spine", "agent-task-spine");
397 let second = TaskSpine::create_envelope("two", "session-task-spine", "agent-task-spine");
398 assert!(
399 !first.task_id.as_str().is_empty(),
400 "`first.task_id.as_str()` is empty"
401 );
402 assert_ne!(first.task_id, second.task_id);
403 }
404
405 #[test]
406 fn test_enrich_from_triage() {
407 let mut envelope =
408 TaskSpine::create_envelope("query", "session-task-spine", "agent-task-spine");
409 let profile = TaskProfileV1 {
410 primary_intent: "implement".into(),
411 task_class: "coding".into(),
412 complexity: TaskComplexity::High,
413 scope: Default::default(),
414 context_need_milli: 0,
415 reasoning_need_milli: 0,
416 risk_signal: lean_ctx_protocol::RiskClass::High,
417 confidence_milli: 0,
418 capability_id: None,
419 capability_version: None,
420 keywords: vec![],
421 language_hints: vec![],
422 };
423 TaskSpine::enrich_from_triage(&mut envelope, &profile);
424 assert_eq!(envelope.intent.as_deref(), Some("implement"));
425 assert_eq!(envelope.task_class.as_deref(), Some("coding"));
426 assert_eq!(envelope.complexity, TaskComplexity::High);
427 assert_eq!(
428 envelope.risk_class,
429 Some(lean_ctx_protocol::RiskClass::High)
430 );
431 }
432
433 #[test]
434 fn first_session_task_is_parent_of_subsequent_tasks() {
435 let session_id = format!("lineage-session-{}", uuid::Uuid::new_v4());
436 let parent = TaskSpine::create_envelope("first", &session_id, "agent");
437 let child = TaskSpine::create_envelope("second", &session_id, "agent");
438
439 assert!(parent.parent_task_id.is_none());
440 assert_eq!(child.trace_id, parent.trace_id);
441 child.validate_child_of(&parent).unwrap();
442 assert_eq!(
443 child
444 .parent_task_id
445 .as_ref()
446 .map(lean_ctx_protocol::TaskId::as_str),
447 Some(parent.task_id.as_str())
448 );
449 assert_eq!(
450 TaskSpine::current()
451 .as_ref()
452 .map(|envelope| envelope.task_id.as_str()),
453 Some(child.task_id.as_str())
454 );
455 }
456
457 #[test]
458 fn session_traces_are_isolated_and_shared_by_all_children() {
459 let first_session = format!("lineage-first-{}", uuid::Uuid::new_v4());
460 let second_session = format!("lineage-second-{}", uuid::Uuid::new_v4());
461 let first = TaskSpine::create_envelope("root", &first_session, "agent");
462 let second = TaskSpine::create_envelope("root", &second_session, "agent");
463 assert_ne!(first.trace_id, second.trace_id);
464 assert!(second.parent_task_id.is_none());
465 for _ in 0..3 {
466 let child = TaskSpine::create_envelope("child", &first_session, "agent");
467 child.validate_child_of(&first).unwrap();
468 assert_ne!(child.task_id, first.task_id);
469 }
470 }
471}