enact-core 0.0.2

Core agent runtime for Enact - Graph-Native AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
//! Runtime Context - The spine of the enact-core runtime
//!
//! RuntimeContext carries all necessary context for execution, tracing,
//! and observability. It is created per Execution and inherited by child
//! executions (sub-agents) with appropriate field updates.
//!
//! ## Key Requirement: TenantContext is REQUIRED
//!
//! Every RuntimeContext must have a valid TenantContext. This ensures:
//! - Multi-tenant isolation
//! - Resource limit enforcement
//! - Audit compliance
//! - Billing attribution
//!
//! @see docs/TECHNICAL/01-EXECUTION-TELEMETRY.md

use super::tenant::TenantContext;
use super::trace::TraceContext;
use crate::kernel::{CancellationPolicy, ExecutionId, ParentLink, ParentType, SpawnMode, StepId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Session context for user-initiated flows
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionContext {
    /// Session ID
    pub session_id: String,
    /// Created timestamp
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// Last active timestamp
    pub last_active_at: Option<chrono::DateTime<chrono::Utc>>,
    /// Session metadata
    pub metadata: HashMap<String, serde_json::Value>,
}

impl SessionContext {
    /// Create a new SessionContext
    pub fn new(session_id: impl Into<String>) -> Self {
        Self {
            session_id: session_id.into(),
            created_at: chrono::Utc::now(),
            last_active_at: None,
            metadata: HashMap::new(),
        }
    }

    /// Touch the session (update last_active_at)
    pub fn touch(&mut self) {
        self.last_active_at = Some(chrono::Utc::now());
    }
}

/// RuntimeContext - The context passed through all execution
///
/// Created per Execution, inherited by child executions (sub-agents)
/// with appropriate field updates.
///
/// ## Usage
/// ```ignore
/// let tenant = TenantContext::new(TenantId::from("tenant_acme"))
///     .with_user(UserId::from("usr_alice"));
///
/// let ctx = RuntimeContext::new(
///     ExecutionId::new(),
///     ParentLink::from_user_message("msg_123"),
///     tenant,
/// );
///
/// // For sub-agent invocation:
/// let child_ctx = ctx.child_context(ExecutionId::new(), &step_id);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuntimeContext {
    // --- Execution Identity ---
    /// The current execution ID
    pub execution_id: ExecutionId,
    /// Current step ID (if within a step)
    pub step_id: Option<StepId>,

    // --- Parent Linkage ---
    /// What triggered this execution
    pub parent: ParentLink,

    // --- Tenant Context (REQUIRED) ---
    /// Tenant context for multi-tenant isolation
    pub tenant: TenantContext,

    // --- Trace Context ---
    /// OpenTelemetry trace context
    pub trace: TraceContext,

    // --- Session ---
    /// Session context (for user-initiated flows)
    pub session: Option<SessionContext>,

    // --- Timestamps ---
    /// When this context was created
    pub created_at: chrono::DateTime<chrono::Utc>,

    // --- SpawnMode (Execution Isolation Control) ---
    /// How this context was spawned (for inbox routing decisions)
    /// @see docs/TECHNICAL/32-SPAWN-MODE.md
    pub spawn_mode: Option<SpawnMode>,

    /// Cancellation policy for child executions spawned from this context
    pub cancellation_policy: CancellationPolicy,

    /// Parent execution ID (for Child spawn mode inbox routing)
    pub parent_execution_id: Option<ExecutionId>,

    // --- Metadata ---
    /// Extensible metadata
    pub metadata: HashMap<String, serde_json::Value>,
}

impl RuntimeContext {
    /// Create a new RuntimeContext for an execution
    ///
    /// TenantContext is REQUIRED - this ensures every execution
    /// runs within a tenant boundary.
    pub fn new(execution_id: ExecutionId, parent: ParentLink, tenant: TenantContext) -> Self {
        Self {
            execution_id,
            step_id: None,
            parent,
            tenant,
            trace: TraceContext::new(),
            session: None,
            created_at: chrono::Utc::now(),
            spawn_mode: None,
            cancellation_policy: CancellationPolicy::default(),
            parent_execution_id: None,
            metadata: HashMap::new(),
        }
    }

    /// Create a RuntimeContext for a user message trigger
    pub fn from_user_message(
        execution_id: ExecutionId,
        message_id: impl Into<String>,
        tenant: TenantContext,
    ) -> Self {
        Self::new(
            execution_id,
            ParentLink::from_user_message(message_id),
            tenant,
        )
    }

    // --- Builder methods ---

    /// Set the current step
    pub fn with_step(mut self, step_id: StepId) -> Self {
        self.step_id = Some(step_id);
        self
    }

    /// Set trace context
    pub fn with_trace(mut self, trace: TraceContext) -> Self {
        self.trace = trace;
        self
    }

    /// Set session context
    pub fn with_session(mut self, session: SessionContext) -> Self {
        self.session = Some(session);
        self
    }

    /// Add metadata
    pub fn with_metadata(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        self.metadata.insert(key.into(), value);
        self
    }

    /// Set spawn mode
    pub fn with_spawn_mode(mut self, spawn_mode: SpawnMode) -> Self {
        self.spawn_mode = Some(spawn_mode);
        self
    }

    /// Set cancellation policy
    pub fn with_cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
        self.cancellation_policy = policy;
        self
    }

    // --- Child context creation ---

    /// Create a child RuntimeContext for a sub-agent invocation
    ///
    /// The child context:
    /// - Gets a new execution ID
    /// - Has parent pointing to the current step
    /// - Inherits tenant context (with same user or overridden)
    /// - Inherits trace context (new span ID)
    ///
    /// Uses default SpawnMode::Child with no background and no inbox inheritance.
    /// For custom SpawnMode, use `child_context_with_spawn_mode`.
    pub fn child_context(&self, child_execution_id: ExecutionId, parent_step_id: &StepId) -> Self {
        self.child_context_with_spawn_mode(
            child_execution_id,
            parent_step_id,
            SpawnMode::child(false, false),
        )
    }

    /// Create a child RuntimeContext with explicit SpawnMode
    ///
    /// @see docs/TECHNICAL/32-SPAWN-MODE.md
    pub fn child_context_with_spawn_mode(
        &self,
        child_execution_id: ExecutionId,
        parent_step_id: &StepId,
        spawn_mode: SpawnMode,
    ) -> Self {
        Self {
            execution_id: child_execution_id,
            step_id: None,
            parent: ParentLink::from_step(parent_step_id),
            tenant: self.tenant.child_context(None),
            trace: self.trace.child_span(),
            session: self.session.clone(),
            created_at: chrono::Utc::now(),
            spawn_mode: Some(spawn_mode),
            cancellation_policy: CancellationPolicy::default(),
            parent_execution_id: Some(self.execution_id.clone()),
            metadata: HashMap::new(), // Child starts with fresh metadata
        }
    }

    /// Enter a step (returns new context with step_id set)
    pub fn enter_step(&self, step_id: StepId) -> Self {
        let mut ctx = self.clone();
        ctx.step_id = Some(step_id);
        ctx.trace = ctx.trace.child_span();
        ctx
    }

    // --- Accessors ---

    /// Get the execution ID
    pub fn execution_id(&self) -> &ExecutionId {
        &self.execution_id
    }

    /// Get the step ID
    pub fn step_id(&self) -> Option<&StepId> {
        self.step_id.as_ref()
    }

    /// Get the tenant context
    pub fn tenant(&self) -> &TenantContext {
        &self.tenant
    }

    /// Get the trace ID
    pub fn trace_id(&self) -> &str {
        &self.trace.trace_id
    }

    /// Get the span ID
    pub fn span_id(&self) -> &str {
        &self.trace.span_id
    }

    /// Check if this is a root execution (not a sub-agent)
    pub fn is_root(&self) -> bool {
        !matches!(self.parent.parent_type, ParentType::StepExecution)
    }
}

/// Builder for creating RuntimeContext with fluent API
pub struct RuntimeContextBuilder {
    execution_id: ExecutionId,
    parent: ParentLink,
    tenant: TenantContext,
    trace: TraceContext,
    session: Option<SessionContext>,
    spawn_mode: Option<SpawnMode>,
    cancellation_policy: CancellationPolicy,
    parent_execution_id: Option<ExecutionId>,
    metadata: HashMap<String, serde_json::Value>,
}

impl RuntimeContextBuilder {
    /// Start building a new RuntimeContext
    ///
    /// TenantContext is REQUIRED.
    pub fn new(execution_id: ExecutionId, parent: ParentLink, tenant: TenantContext) -> Self {
        Self {
            execution_id,
            parent,
            tenant,
            trace: TraceContext::new(),
            session: None,
            spawn_mode: None,
            cancellation_policy: CancellationPolicy::default(),
            parent_execution_id: None,
            metadata: HashMap::new(),
        }
    }

    /// Set trace context
    pub fn trace(mut self, trace: TraceContext) -> Self {
        self.trace = trace;
        self
    }

    /// Set session
    pub fn session(mut self, session: SessionContext) -> Self {
        self.session = Some(session);
        self
    }

    /// Add metadata
    pub fn metadata(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        self.metadata.insert(key.into(), value);
        self
    }

    /// Set spawn mode
    pub fn spawn_mode(mut self, spawn_mode: SpawnMode) -> Self {
        self.spawn_mode = Some(spawn_mode);
        self
    }

    /// Set cancellation policy
    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
        self.cancellation_policy = policy;
        self
    }

    /// Set parent execution ID
    pub fn parent_execution_id(mut self, parent_exec_id: ExecutionId) -> Self {
        self.parent_execution_id = Some(parent_exec_id);
        self
    }

    /// Build the RuntimeContext
    pub fn build(self) -> RuntimeContext {
        RuntimeContext {
            execution_id: self.execution_id,
            step_id: None,
            parent: self.parent,
            tenant: self.tenant,
            trace: self.trace,
            session: self.session,
            created_at: chrono::Utc::now(),
            spawn_mode: self.spawn_mode,
            cancellation_policy: self.cancellation_policy,
            parent_execution_id: self.parent_execution_id,
            metadata: self.metadata,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::kernel::{TenantId, UserId};

    // =========================================================================
    // SessionContext Tests
    // =========================================================================

    #[test]
    fn test_session_context_new() {
        let session = SessionContext::new("sess_123");
        assert_eq!(session.session_id, "sess_123");
        assert!(session.last_active_at.is_none());
        assert!(session.metadata.is_empty());
    }

    #[test]
    fn test_session_context_new_owned_string() {
        let session = SessionContext::new(String::from("sess_owned"));
        assert_eq!(session.session_id, "sess_owned");
    }

    #[test]
    fn test_session_context_touch() {
        let mut session = SessionContext::new("sess_touch");
        assert!(session.last_active_at.is_none());

        session.touch();
        assert!(session.last_active_at.is_some());

        let first_touch = session.last_active_at.unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));
        session.touch();

        assert!(session.last_active_at.unwrap() >= first_touch);
    }

    #[test]
    fn test_session_context_metadata() {
        let mut session = SessionContext::new("sess_meta");
        session
            .metadata
            .insert("key".to_string(), serde_json::json!("value"));

        assert_eq!(
            session.metadata.get("key"),
            Some(&serde_json::json!("value"))
        );
    }

    #[test]
    fn test_session_context_serde() {
        let session = SessionContext::new("sess_serde");
        let json = serde_json::to_string(&session).unwrap();
        let parsed: SessionContext = serde_json::from_str(&json).unwrap();
        assert_eq!(session.session_id, parsed.session_id);
    }

    // =========================================================================
    // RuntimeContext Tests
    // =========================================================================

    fn create_test_tenant() -> TenantContext {
        TenantContext::new(TenantId::from_string("tenant_test"))
    }

    #[test]
    fn test_runtime_context_new() {
        let exec_id = ExecutionId::from_string("exec_test");
        let parent = ParentLink::from_user_message("msg_123");
        let tenant = create_test_tenant();

        let ctx = RuntimeContext::new(exec_id.clone(), parent, tenant);

        assert_eq!(ctx.execution_id.as_str(), "exec_test");
        assert!(ctx.step_id.is_none());
        assert!(ctx.session.is_none());
        assert!(ctx.metadata.is_empty());
    }

    #[test]
    fn test_runtime_context_from_user_message() {
        let exec_id = ExecutionId::from_string("exec_msg");
        let tenant = create_test_tenant();

        let ctx = RuntimeContext::from_user_message(exec_id, "msg_456", tenant);

        assert_eq!(ctx.parent.parent_type, ParentType::UserMessage);
        assert_eq!(ctx.parent.parent_id, "msg_456");
    }

    #[test]
    fn test_runtime_context_with_step() {
        let exec_id = ExecutionId::from_string("exec_step");
        let parent = ParentLink::system();
        let tenant = create_test_tenant();
        let step_id = StepId::from_string("step_ctx");

        let ctx = RuntimeContext::new(exec_id, parent, tenant).with_step(step_id.clone());

        assert!(ctx.step_id.is_some());
        assert_eq!(ctx.step_id.unwrap().as_str(), "step_ctx");
    }

    #[test]
    fn test_runtime_context_with_trace() {
        let exec_id = ExecutionId::from_string("exec_trace");
        let parent = ParentLink::system();
        let tenant = create_test_tenant();
        let trace = TraceContext::from_traceparent(
            "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",
        )
        .unwrap();

        let ctx = RuntimeContext::new(exec_id, parent, tenant).with_trace(trace);

        assert_eq!(ctx.trace_id(), "0123456789abcdef0123456789abcdef");
    }

    #[test]
    fn test_runtime_context_with_session() {
        let exec_id = ExecutionId::from_string("exec_sess");
        let parent = ParentLink::system();
        let tenant = create_test_tenant();
        let session = SessionContext::new("sess_runtime");

        let ctx = RuntimeContext::new(exec_id, parent, tenant).with_session(session);

        assert!(ctx.session.is_some());
        assert_eq!(ctx.session.unwrap().session_id, "sess_runtime");
    }

    #[test]
    fn test_runtime_context_with_metadata() {
        let exec_id = ExecutionId::from_string("exec_meta");
        let parent = ParentLink::system();
        let tenant = create_test_tenant();

        let ctx = RuntimeContext::new(exec_id, parent, tenant)
            .with_metadata("key1", serde_json::json!("value1"))
            .with_metadata("key2", serde_json::json!(42));

        assert_eq!(ctx.metadata.len(), 2);
        assert_eq!(ctx.metadata.get("key1"), Some(&serde_json::json!("value1")));
        assert_eq!(ctx.metadata.get("key2"), Some(&serde_json::json!(42)));
    }

    #[test]
    fn test_runtime_context_child_context() {
        let exec_id = ExecutionId::from_string("exec_parent");
        let parent = ParentLink::from_user_message("msg_parent");
        let tenant = TenantContext::new(TenantId::from_string("tenant_parent"))
            .with_user(UserId::from_string("user_parent"));

        let parent_ctx = RuntimeContext::new(exec_id, parent, tenant)
            .with_session(SessionContext::new("sess_inherit"))
            .with_metadata("parent_key", serde_json::json!("should_not_inherit"));

        let child_exec_id = ExecutionId::from_string("exec_child");
        let parent_step_id = StepId::from_string("step_that_spawned");
        let child_ctx = parent_ctx.child_context(child_exec_id.clone(), &parent_step_id);

        // Child should have new execution ID
        assert_eq!(child_ctx.execution_id.as_str(), "exec_child");

        // Child should have parent pointing to the step
        assert_eq!(child_ctx.parent.parent_type, ParentType::StepExecution);
        assert_eq!(child_ctx.parent.parent_id, "step_that_spawned");

        // Child inherits tenant
        assert_eq!(child_ctx.tenant.tenant_id().as_str(), "tenant_parent");

        // Child inherits session
        assert!(child_ctx.session.is_some());
        assert_eq!(child_ctx.session.unwrap().session_id, "sess_inherit");

        // Child has same trace ID but different span
        assert_eq!(child_ctx.trace.trace_id, parent_ctx.trace.trace_id);
        assert_ne!(child_ctx.trace.span_id, parent_ctx.trace.span_id);

        // Child has fresh metadata
        assert!(child_ctx.metadata.is_empty());
    }

    #[test]
    fn test_runtime_context_enter_step() {
        let exec_id = ExecutionId::from_string("exec_enter");
        let parent = ParentLink::system();
        let tenant = create_test_tenant();
        let original_ctx = RuntimeContext::new(exec_id, parent, tenant);

        let step_id = StepId::from_string("step_enter");
        let step_ctx = original_ctx.enter_step(step_id.clone());

        // Step context should have the step ID set
        assert!(step_ctx.step_id.is_some());
        assert_eq!(step_ctx.step_id.unwrap().as_str(), "step_enter");

        // Same trace ID but different span
        assert_eq!(step_ctx.trace.trace_id, original_ctx.trace.trace_id);
        assert_ne!(step_ctx.trace.span_id, original_ctx.trace.span_id);

        // Original context unchanged
        assert!(original_ctx.step_id.is_none());
    }

    #[test]
    fn test_runtime_context_accessors() {
        let exec_id = ExecutionId::from_string("exec_access");
        let step_id = StepId::from_string("step_access");
        let parent = ParentLink::system();
        let tenant = TenantContext::new(TenantId::from_string("tenant_access"))
            .with_user(UserId::from_string("user_access"));

        let ctx = RuntimeContext::new(exec_id, parent, tenant).with_step(step_id);

        assert_eq!(ctx.execution_id().as_str(), "exec_access");
        assert_eq!(ctx.step_id().unwrap().as_str(), "step_access");
        assert_eq!(ctx.tenant().tenant_id().as_str(), "tenant_access");
        assert!(!ctx.trace_id().is_empty());
        assert!(!ctx.span_id().is_empty());
    }

    #[test]
    fn test_runtime_context_is_root_user_message() {
        let exec_id = ExecutionId::from_string("exec_root");
        let parent = ParentLink::from_user_message("msg_root");
        let tenant = create_test_tenant();

        let ctx = RuntimeContext::new(exec_id, parent, tenant);
        assert!(ctx.is_root());
    }

    #[test]
    fn test_runtime_context_is_root_system() {
        let exec_id = ExecutionId::from_string("exec_root");
        let parent = ParentLink::system();
        let tenant = create_test_tenant();

        let ctx = RuntimeContext::new(exec_id, parent, tenant);
        assert!(ctx.is_root());
    }

    #[test]
    fn test_runtime_context_is_not_root_step_execution() {
        let exec_id = ExecutionId::from_string("exec_child");
        let parent_step = StepId::from_string("step_parent");
        let parent = ParentLink::from_step(&parent_step);
        let tenant = create_test_tenant();

        let ctx = RuntimeContext::new(exec_id, parent, tenant);
        assert!(!ctx.is_root());
    }

    #[test]
    fn test_runtime_context_serde() {
        let exec_id = ExecutionId::from_string("exec_serde");
        let parent = ParentLink::system();
        let tenant = create_test_tenant();

        let ctx = RuntimeContext::new(exec_id, parent, tenant);
        let json = serde_json::to_string(&ctx).unwrap();
        let parsed: RuntimeContext = serde_json::from_str(&json).unwrap();

        assert_eq!(ctx.execution_id.as_str(), parsed.execution_id.as_str());
    }

    // =========================================================================
    // RuntimeContextBuilder Tests
    // =========================================================================

    #[test]
    fn test_builder_new() {
        let exec_id = ExecutionId::from_string("exec_builder");
        let parent = ParentLink::system();
        let tenant = create_test_tenant();

        let builder = RuntimeContextBuilder::new(exec_id.clone(), parent, tenant);
        let ctx = builder.build();

        assert_eq!(ctx.execution_id.as_str(), "exec_builder");
    }

    #[test]
    fn test_builder_with_trace() {
        let exec_id = ExecutionId::from_string("exec_builder_trace");
        let parent = ParentLink::system();
        let tenant = create_test_tenant();
        let trace = TraceContext::from_traceparent(
            "00-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1-bbbbbbbbbbbbbb11-01",
        )
        .unwrap();

        let ctx = RuntimeContextBuilder::new(exec_id, parent, tenant)
            .trace(trace)
            .build();

        assert_eq!(ctx.trace.trace_id, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1");
    }

    #[test]
    fn test_builder_with_session() {
        let exec_id = ExecutionId::from_string("exec_builder_sess");
        let parent = ParentLink::system();
        let tenant = create_test_tenant();
        let session = SessionContext::new("sess_builder");

        let ctx = RuntimeContextBuilder::new(exec_id, parent, tenant)
            .session(session)
            .build();

        assert!(ctx.session.is_some());
        assert_eq!(ctx.session.unwrap().session_id, "sess_builder");
    }

    #[test]
    fn test_builder_with_metadata() {
        let exec_id = ExecutionId::from_string("exec_builder_meta");
        let parent = ParentLink::system();
        let tenant = create_test_tenant();

        let ctx = RuntimeContextBuilder::new(exec_id, parent, tenant)
            .metadata("build_key", serde_json::json!("build_value"))
            .build();

        assert_eq!(
            ctx.metadata.get("build_key"),
            Some(&serde_json::json!("build_value"))
        );
    }

    #[test]
    fn test_builder_full_chain() {
        let exec_id = ExecutionId::from_string("exec_full");
        let parent = ParentLink::from_user_message("msg_full");
        let tenant = TenantContext::new(TenantId::from_string("tenant_full"))
            .with_user(UserId::from_string("user_full"));
        let session = SessionContext::new("sess_full");
        let trace = TraceContext::new();

        let ctx = RuntimeContextBuilder::new(exec_id, parent, tenant)
            .trace(trace.clone())
            .session(session)
            .metadata("key1", serde_json::json!(1))
            .metadata("key2", serde_json::json!(2))
            .build();

        assert_eq!(ctx.execution_id.as_str(), "exec_full");
        assert_eq!(ctx.parent.parent_id, "msg_full");
        assert_eq!(ctx.tenant.tenant_id().as_str(), "tenant_full");
        assert!(ctx.session.is_some());
        assert_eq!(ctx.metadata.len(), 2);
    }

    // =========================================================================
    // Integration Tests
    // =========================================================================

    #[test]
    fn test_nested_execution_hierarchy() {
        // Root execution from user message
        let root_exec_id = ExecutionId::from_string("exec_root");
        let tenant = TenantContext::new(TenantId::from_string("tenant_hier"))
            .with_user(UserId::from_string("user_hier"));
        let root_ctx = RuntimeContext::from_user_message(root_exec_id, "msg_root", tenant);

        assert!(root_ctx.is_root());

        // First-level child (sub-agent)
        let step1_id = StepId::from_string("step_1");
        let child1_ctx = root_ctx.child_context(ExecutionId::from_string("exec_child1"), &step1_id);

        assert!(!child1_ctx.is_root());
        assert_eq!(child1_ctx.trace.trace_id, root_ctx.trace.trace_id);

        // Second-level child (sub-sub-agent)
        let step2_id = StepId::from_string("step_2");
        let child2_ctx =
            child1_ctx.child_context(ExecutionId::from_string("exec_child2"), &step2_id);

        assert!(!child2_ctx.is_root());
        // All share the same trace ID
        assert_eq!(child2_ctx.trace.trace_id, root_ctx.trace.trace_id);
        // But all have unique span IDs
        assert_ne!(child2_ctx.trace.span_id, child1_ctx.trace.span_id);
        assert_ne!(child1_ctx.trace.span_id, root_ctx.trace.span_id);
    }

    #[test]
    fn test_step_execution_creates_correct_spans() {
        let exec_id = ExecutionId::from_string("exec_spans");
        let tenant = create_test_tenant();
        let root_ctx = RuntimeContext::new(exec_id, ParentLink::system(), tenant);

        let step1 = StepId::from_string("step_a");
        let step2 = StepId::from_string("step_b");

        let ctx_step1 = root_ctx.enter_step(step1.clone());
        let ctx_step2 = root_ctx.enter_step(step2.clone());

        // Both steps should share the same trace ID
        assert_eq!(ctx_step1.trace.trace_id, ctx_step2.trace.trace_id);
        // But have different span IDs
        assert_ne!(ctx_step1.trace.span_id, ctx_step2.trace.span_id);
        // And different step IDs
        assert_ne!(
            ctx_step1.step_id.unwrap().as_str(),
            ctx_step2.step_id.unwrap().as_str()
        );
    }
}