repl-core 1.19.0

Core REPL engine for the Symbi platform
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
//! Core reasoning builtins for the DSL
//!
//! Provides async builtin functions that bridge the DSL with the
//! reasoning loop infrastructure: `reason`, `llm_call`, `parse_json`,
//! `delegate`, and `tool_call`.

use crate::dsl::agent_composition::{check_comm_policy, log_comm_message};
use crate::dsl::evaluator::DslValue;
use crate::error::{ReplError, Result};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use symbi_runtime::communication::policy_gate::CommunicationPolicyGate;
use symbi_runtime::communication::CommunicationBus;
use symbi_runtime::reasoning::agent_registry::AgentRegistry;
use symbi_runtime::reasoning::inference::InferenceProvider;
use symbi_runtime::reasoning::policy_bridge::ReasoningPolicyGate;
use symbi_runtime::types::{AgentId, MessageType, RequestId};

/// Shared state for async reasoning builtins.
#[derive(Clone, Default)]
pub struct ReasoningBuiltinContext {
    /// Inference provider for LLM calls.
    pub provider: Option<Arc<dyn InferenceProvider>>,
    /// Agent registry for multi-agent composition.
    pub agent_registry: Option<Arc<AgentRegistry>>,
    /// The AgentId of the calling agent (for communication tracking).
    pub sender_agent_id: Option<AgentId>,
    /// Communication bus for message tracking and audit.
    pub comm_bus: Option<Arc<dyn CommunicationBus + Send + Sync>>,
    /// Communication policy gate for inter-agent authorization.
    pub comm_policy: Option<Arc<CommunicationPolicyGate>>,
    /// Policy gate for the reasoning loop — governs tool calls and
    /// delegations inside `reason()`. If None, `DefaultPolicyGate::new()`
    /// is used (production-default, non-permissive). Production callers
    /// should install [`OpaPolicyGateBridge`] or another concrete gate
    /// instead of relying on the default.
    pub reasoning_policy_gate: Option<Arc<dyn ReasoningPolicyGate>>,
    /// Active session id (shared cell; settable after the context is frozen).
    #[cfg(feature = "session")]
    pub active_session: std::sync::Arc<std::sync::Mutex<Option<symbi_session::monitor::SessionId>>>,
    /// Session monitor for label derivation. Always present once a bridge exists.
    #[cfg(feature = "session")]
    pub session_monitor: Option<std::sync::Arc<symbi_session::monitor::SessionMonitor>>,
}

/// Execute the `reason` builtin: runs a full reasoning loop.
///
/// Arguments (positional or named):
/// - system: string — system prompt
/// - user: string — user message
/// - max_iterations: integer (optional, default 10)
/// - max_tokens: integer (optional, default 100000)
///
/// Returns a map with keys: response, iterations, total_tokens, termination_reason.
pub async fn builtin_reason(args: &[DslValue], ctx: &ReasoningBuiltinContext) -> Result<DslValue> {
    let provider = ctx
        .provider
        .as_ref()
        .ok_or_else(|| ReplError::Execution("No inference provider configured".into()))?;

    let (system, user, max_iterations, max_tokens) = parse_reason_args(args)?;

    use symbi_runtime::reasoning::circuit_breaker::CircuitBreakerRegistry;
    use symbi_runtime::reasoning::context_manager::DefaultContextManager;
    use symbi_runtime::reasoning::conversation::{Conversation, ConversationMessage};
    use symbi_runtime::reasoning::loop_types::{BufferedJournal, LoopConfig};
    use symbi_runtime::reasoning::policy_bridge::DefaultPolicyGate;
    use symbi_runtime::reasoning::reasoning_loop::ReasoningLoopRunner;

    // Prefer a caller-provided policy gate (e.g. OpaPolicyGateBridge wired
    // from the runtime). Fall back to the non-permissive default rather
    // than `DefaultPolicyGate::permissive_for_dev_only()` so `reason()`
    // no longer opts every DSL program into unrestricted tool calls
    // regardless of how the runtime was configured.
    let policy_gate: Arc<dyn ReasoningPolicyGate> = match ctx.reasoning_policy_gate.clone() {
        Some(gate) => gate,
        None => Arc::new(DefaultPolicyGate::new()),
    };

    let runner = ReasoningLoopRunner {
        provider: Arc::clone(provider),
        policy_gate,
        // Real tool execution when `tools/` has ToolClad manifests; falls
        // back to the honest no-backend executor otherwise (never
        // fabricates a tool-call success).
        executor: symbi_runtime::reasoning::build_tool_executor(std::path::Path::new("tools")),
        context_manager: Arc::new(DefaultContextManager::default()),
        circuit_breakers: Arc::new(CircuitBreakerRegistry::default()),
        journal: Arc::new(BufferedJournal::new(1000)),
        knowledge_bridge: None,
        delegation: None,
    };

    let mut conv = Conversation::with_system(&system);
    conv.push(ConversationMessage::user(&user));

    let config = LoopConfig {
        max_iterations,
        max_total_tokens: max_tokens,
        ..Default::default()
    };

    let result = runner.run(AgentId::new(), conv, config).await;

    let mut map = HashMap::new();
    map.insert("response".to_string(), DslValue::String(result.output));
    map.insert(
        "iterations".to_string(),
        DslValue::Integer(result.iterations as i64),
    );
    map.insert(
        "total_tokens".to_string(),
        DslValue::Integer(result.total_usage.total_tokens as i64),
    );
    map.insert(
        "termination_reason".to_string(),
        DslValue::String(format!("{:?}", result.termination_reason)),
    );

    Ok(DslValue::Map(map))
}

/// Execute the `llm_call` builtin: one-shot LLM call.
///
/// Arguments:
/// - prompt: string — the prompt to send
/// - model: string (optional) — model override
/// - temperature: number (optional)
/// - max_tokens: integer (optional)
///
/// Returns a string.
pub async fn builtin_llm_call(
    args: &[DslValue],
    ctx: &ReasoningBuiltinContext,
) -> Result<DslValue> {
    let provider = ctx
        .provider
        .as_ref()
        .ok_or_else(|| ReplError::Execution("No inference provider configured".into()))?;

    let prompt = match args.first() {
        Some(DslValue::String(s)) => s.clone(),
        Some(DslValue::Map(map)) => map
            .get("prompt")
            .and_then(|v| match v {
                DslValue::String(s) => Some(s.clone()),
                _ => None,
            })
            .ok_or_else(|| ReplError::Execution("llm_call requires 'prompt' argument".into()))?,
        _ => {
            return Err(ReplError::Execution(
                "llm_call requires a string prompt".into(),
            ))
        }
    };

    use symbi_runtime::reasoning::conversation::{Conversation, ConversationMessage};
    use symbi_runtime::reasoning::inference::InferenceOptions;

    let mut conv = Conversation::new();
    conv.push(ConversationMessage::user(&prompt));

    let options = InferenceOptions::default();
    let response = provider
        .complete(&conv, &options)
        .await
        .map_err(|e| ReplError::Execution(format!("LLM call failed: {}", e)))?;

    Ok(DslValue::String(response.content))
}

/// Execute the `parse_json` builtin: parse a string as JSON.
///
/// Arguments:
/// - text: string — the JSON text to parse
///
/// Returns a DslValue (Map, List, String, Number, Boolean, or Null).
pub fn builtin_parse_json(args: &[DslValue]) -> Result<DslValue> {
    let text = match args.first() {
        Some(DslValue::String(s)) => s,
        _ => {
            return Err(ReplError::Execution(
                "parse_json requires a string argument".into(),
            ))
        }
    };

    let value: serde_json::Value = serde_json::from_str(text)
        .map_err(|e| ReplError::Execution(format!("JSON parse error: {}", e)))?;

    Ok(json_to_dsl_value(&value))
}

/// Execute the `tool_call` builtin: explicit tool invocation.
///
/// Arguments:
/// - name: string — tool name
/// - args: map — tool arguments
///
/// Every call is evaluated by `ctx.reasoning_policy_gate` before dispatch —
/// same resolution `builtin_reason` uses (a caller-installed gate, or the
/// non-permissive `DefaultPolicyGate::new()` default). `tool_call` used to
/// take `_ctx` and never read it, so any caller that hadn't wired a gate got
/// unrestricted tool execution regardless of runtime configuration.
///
/// Returns the tool result as a string.
pub async fn builtin_tool_call(
    args: &[DslValue],
    ctx: &ReasoningBuiltinContext,
) -> Result<DslValue> {
    let (name, arguments) = match args {
        [DslValue::String(name), DslValue::Map(args_map)] => {
            let json_args: serde_json::Map<String, serde_json::Value> = args_map
                .iter()
                .map(|(k, v)| (k.clone(), v.to_json()))
                .collect();
            (
                name.clone(),
                serde_json::Value::Object(json_args).to_string(),
            )
        }
        [DslValue::String(name), DslValue::String(args_str)] => (name.clone(), args_str.clone()),
        [DslValue::String(name)] => (name.clone(), "{}".to_string()),
        _ => {
            return Err(ReplError::Execution(
                "tool_call requires (name: string, args?: map|string)".into(),
            ))
        }
    };

    use symbi_runtime::reasoning::circuit_breaker::CircuitBreakerRegistry;
    use symbi_runtime::reasoning::conversation::Conversation;
    use symbi_runtime::reasoning::loop_types::{
        LoopConfig, LoopDecision, LoopState, ProposedAction,
    };
    use symbi_runtime::reasoning::policy_bridge::DefaultPolicyGate;

    let policy_gate: Arc<dyn ReasoningPolicyGate> = match ctx.reasoning_policy_gate.clone() {
        Some(gate) => gate,
        None => Arc::new(DefaultPolicyGate::new()),
    };

    let agent_id = ctx.sender_agent_id.unwrap_or_default();
    let proposed = ProposedAction::ToolCall {
        call_id: "dsl_tool_call".to_string(),
        name: name.clone(),
        arguments: arguments.clone(),
    };
    let state = LoopState::new(agent_id, Conversation::new());
    let decision = policy_gate
        .evaluate_action(&agent_id, &proposed, &state)
        .await;

    let (name, arguments) = match decision {
        LoopDecision::Allow => (name, arguments),
        LoopDecision::Modify {
            modified_action,
            reason,
        } => match *modified_action {
            ProposedAction::ToolCall {
                name: new_name,
                arguments: new_arguments,
                ..
            } => {
                tracing::info!("tool_call: policy gate modified action: {}", reason);
                (new_name, new_arguments)
            }
            other => {
                // The gate replaced the tool call with a non-tool-call
                // action (e.g. a canned redirect). There is nothing left
                // here to dispatch — report that honestly rather than
                // silently running the original call.
                let mut result = HashMap::new();
                result.insert("tool".to_string(), DslValue::String(name));
                result.insert("arguments".to_string(), DslValue::String(arguments));
                result.insert("status".to_string(), DslValue::String("denied".to_string()));
                result.insert(
                    "reason".to_string(),
                    DslValue::String(format!(
                        "policy gate replaced this tool call with {other:?}: {reason}"
                    )),
                );
                return Ok(DslValue::Map(result));
            }
        },
        LoopDecision::Deny { reason } => {
            let mut result = HashMap::new();
            result.insert("tool".to_string(), DslValue::String(name));
            result.insert("arguments".to_string(), DslValue::String(arguments));
            result.insert("status".to_string(), DslValue::String("denied".to_string()));
            result.insert("reason".to_string(), DslValue::String(reason));
            return Ok(DslValue::Map(result));
        }
    };

    // Route through the built tool executor: real execution (shell, HTTP,
    // MCP-proxy, session, browser) when `tools/` has ToolClad manifests that
    // handle this tool name, otherwise fall through to the honest
    // `not_executed` result below — never fabricate a success.
    let executor = symbi_runtime::reasoning::build_tool_executor(std::path::Path::new("tools"));
    let handled = executor.tool_definitions().iter().any(|d| d.name == name);

    if handled {
        let action = ProposedAction::ToolCall {
            call_id: "dsl_tool_call".to_string(),
            name: name.clone(),
            arguments: arguments.clone(),
        };
        let config = LoopConfig::default();
        let circuit_breakers = CircuitBreakerRegistry::default();
        let observations = executor
            .execute_actions(&[action], &config, &circuit_breakers)
            .await;

        if let Some(obs) = observations.into_iter().next() {
            let mut result = HashMap::new();
            result.insert("tool".to_string(), DslValue::String(name));
            result.insert("arguments".to_string(), DslValue::String(arguments));
            result.insert(
                "status".to_string(),
                DslValue::String(if obs.is_error { "error" } else { "success" }.to_string()),
            );
            result.insert("result".to_string(), DslValue::String(obs.content));
            return Ok(DslValue::Map(result));
        }
    }

    // No `tools/` manifests handle this tool name (or the builder fell back
    // to `UnavailableToolExecutor`). Return an honest `not_executed` result
    // rather than fabricating a success — callers must not assume the tool
    // actually ran.
    let mut result = HashMap::new();
    result.insert("tool".to_string(), DslValue::String(name));
    result.insert("arguments".to_string(), DslValue::String(arguments));
    result.insert(
        "status".to_string(),
        DslValue::String("not_executed".to_string()),
    );
    result.insert(
        "reason".to_string(),
        DslValue::String(
            "no tool backend configured for this tool (add a matching tools/*.clad.toml manifest)"
                .to_string(),
        ),
    );

    Ok(DslValue::Map(result))
}

/// Execute the `delegate` builtin: send a message to another agent.
///
/// Arguments:
/// - agent: string — agent name
/// - message: string — message to send
/// - timeout: duration (optional)
///
/// Returns the agent's response as a string.
pub async fn builtin_delegate(
    args: &[DslValue],
    ctx: &ReasoningBuiltinContext,
) -> Result<DslValue> {
    let (agent_name, message) = match args {
        [DslValue::String(agent), DslValue::String(msg)] => (agent.clone(), msg.clone()),
        [DslValue::Map(map)] => {
            let agent = map
                .get("agent")
                .and_then(|v| match v {
                    DslValue::String(s) => Some(s.clone()),
                    _ => None,
                })
                .ok_or_else(|| ReplError::Execution("delegate requires 'agent' argument".into()))?;
            let msg = map
                .get("message")
                .and_then(|v| match v {
                    DslValue::String(s) => Some(s.clone()),
                    _ => None,
                })
                .ok_or_else(|| {
                    ReplError::Execution("delegate requires 'message' argument".into())
                })?;
            (agent, msg)
        }
        _ => {
            return Err(ReplError::Execution(
                "delegate requires (agent: string, message: string)".into(),
            ))
        }
    };

    // Communication bus wiring: resolve recipient (fallback for unregistered agents)
    let recipient_id = if let Some(registry) = &ctx.agent_registry {
        registry
            .get_agent(&agent_name)
            .await
            .map(|a| a.agent_id)
            .unwrap_or_default()
    } else {
        AgentId::new()
    };
    let sender_id = ctx.sender_agent_id.unwrap_or_default();
    let request_id = RequestId::new();
    let plabel = optional_protocol_label(args);

    check_comm_policy(
        ctx,
        sender_id,
        recipient_id,
        MessageType::Request(request_id),
        plabel.as_deref(),
    )?;
    log_comm_message(
        ctx,
        sender_id,
        recipient_id,
        &message,
        MessageType::Request(request_id),
        Duration::from_secs(30),
    )
    .await;

    // Use inference provider to simulate delegation (each agent is a separate conversation)
    let provider = ctx
        .provider
        .as_ref()
        .ok_or_else(|| ReplError::Execution("No inference provider configured".into()))?;

    use symbi_runtime::reasoning::conversation::{Conversation, ConversationMessage};
    use symbi_runtime::reasoning::inference::InferenceOptions;

    let mut conv = Conversation::with_system(format!(
        "You are agent '{}'. Respond to the delegated task.",
        agent_name
    ));
    conv.push(ConversationMessage::user(&message));

    let response = provider
        .complete(&conv, &InferenceOptions::default())
        .await
        .map_err(|e| {
            ReplError::Execution(format!("Delegation to '{}' failed: {}", agent_name, e))
        })?;

    log_comm_message(
        ctx,
        recipient_id,
        sender_id,
        &response.content,
        MessageType::Response(request_id),
        Duration::from_secs(30),
    )
    .await;

    Ok(DslValue::String(response.content))
}

// --- Helper functions ---

fn parse_reason_args(args: &[DslValue]) -> Result<(String, String, u32, u32)> {
    match args {
        // Named arguments via map
        [DslValue::Map(map)] => {
            let system = map
                .get("system")
                .and_then(|v| match v {
                    DslValue::String(s) => Some(s.clone()),
                    _ => None,
                })
                .ok_or_else(|| ReplError::Execution("reason requires 'system' argument".into()))?;
            let user = map
                .get("user")
                .and_then(|v| match v {
                    DslValue::String(s) => Some(s.clone()),
                    _ => None,
                })
                .ok_or_else(|| ReplError::Execution("reason requires 'user' argument".into()))?;
            let max_iterations = map
                .get("max_iterations")
                .and_then(|v| match v {
                    DslValue::Integer(i) => Some(*i as u32),
                    DslValue::Number(n) => Some(*n as u32),
                    _ => None,
                })
                .unwrap_or(10);
            let max_tokens = map
                .get("max_tokens")
                .and_then(|v| match v {
                    DslValue::Integer(i) => Some(*i as u32),
                    DslValue::Number(n) => Some(*n as u32),
                    _ => None,
                })
                .unwrap_or(100_000);
            Ok((system, user, max_iterations, max_tokens))
        }
        // Positional: system, user
        [DslValue::String(system), DslValue::String(user)] => {
            Ok((system.clone(), user.clone(), 10, 100_000))
        }
        // Positional: system, user, max_iterations
        [DslValue::String(system), DslValue::String(user), DslValue::Integer(max_iter)] => {
            Ok((system.clone(), user.clone(), *max_iter as u32, 100_000))
        }
        _ => Err(ReplError::Execution(
            "reason requires (system: string, user: string, [max_iterations?, max_tokens?])".into(),
        )),
    }
}

/// Extract an optional `protocol_label` string from a DSL argument list.
///
/// Named args arrive as a single `DslValue::Map`. This helper looks up the
/// `"protocol_label"` key in that map and returns its value when it is a
/// `DslValue::String`. Returns `None` when the key is absent, has the wrong
/// type, or the args are positional-only (no map present).
pub(crate) fn optional_protocol_label(args: &[DslValue]) -> Option<String> {
    for arg in args {
        if let DslValue::Map(map) = arg {
            if let Some(DslValue::String(label)) = map.get("protocol_label") {
                return Some(label.clone());
            }
        }
    }
    None
}

/// Convert a serde_json::Value to a DslValue.
pub fn json_to_dsl_value(value: &serde_json::Value) -> DslValue {
    match value {
        serde_json::Value::Null => DslValue::Null,
        serde_json::Value::Bool(b) => DslValue::Boolean(*b),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                DslValue::Integer(i)
            } else if let Some(f) = n.as_f64() {
                DslValue::Number(f)
            } else {
                DslValue::Number(0.0)
            }
        }
        serde_json::Value::String(s) => DslValue::String(s.clone()),
        serde_json::Value::Array(arr) => {
            DslValue::List(arr.iter().map(json_to_dsl_value).collect())
        }
        serde_json::Value::Object(obj) => {
            let map: HashMap<String, DslValue> = obj
                .iter()
                .map(|(k, v)| (k.clone(), json_to_dsl_value(v)))
                .collect();
            DslValue::Map(map)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_json_valid() {
        let result =
            builtin_parse_json(&[DslValue::String(r#"{"key": "value", "num": 42}"#.into())])
                .unwrap();
        match result {
            DslValue::Map(map) => {
                assert_eq!(map.get("key"), Some(&DslValue::String("value".into())));
                assert_eq!(map.get("num"), Some(&DslValue::Integer(42)));
            }
            _ => panic!("Expected Map"),
        }
    }

    #[test]
    fn test_parse_json_array() {
        let result = builtin_parse_json(&[DslValue::String("[1, 2, 3]".into())]).unwrap();
        match result {
            DslValue::List(items) => {
                assert_eq!(items.len(), 3);
                assert_eq!(items[0], DslValue::Integer(1));
            }
            _ => panic!("Expected List"),
        }
    }

    #[test]
    fn test_parse_json_invalid() {
        let result = builtin_parse_json(&[DslValue::String("not json".into())]);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_json_nested() {
        let json = r#"{"tasks": [{"id": 1, "done": false}], "count": 1}"#;
        let result = builtin_parse_json(&[DslValue::String(json.into())]).unwrap();
        match result {
            DslValue::Map(map) => match map.get("tasks") {
                Some(DslValue::List(tasks)) => {
                    assert_eq!(tasks.len(), 1);
                    match &tasks[0] {
                        DslValue::Map(task) => {
                            assert_eq!(task.get("id"), Some(&DslValue::Integer(1)));
                            assert_eq!(task.get("done"), Some(&DslValue::Boolean(false)));
                        }
                        _ => panic!("Expected Map in list"),
                    }
                }
                _ => panic!("Expected List for tasks"),
            },
            _ => panic!("Expected Map"),
        }
    }

    #[test]
    fn test_json_to_dsl_value_all_types() {
        let json = serde_json::json!({
            "str": "hello",
            "int": 42,
            "float": 1.5,
            "bool": true,
            "null": null,
            "arr": [1, 2],
            "obj": {"nested": "value"}
        });

        let dsl = json_to_dsl_value(&json);
        match dsl {
            DslValue::Map(map) => {
                assert_eq!(map.get("str"), Some(&DslValue::String("hello".into())));
                assert_eq!(map.get("int"), Some(&DslValue::Integer(42)));
                assert_eq!(map.get("bool"), Some(&DslValue::Boolean(true)));
                assert_eq!(map.get("null"), Some(&DslValue::Null));
            }
            _ => panic!("Expected Map"),
        }
    }

    #[test]
    fn test_parse_reason_args_positional() {
        let args = vec![
            DslValue::String("system prompt".into()),
            DslValue::String("user message".into()),
        ];
        let (system, user, max_iter, max_tokens) = parse_reason_args(&args).unwrap();
        assert_eq!(system, "system prompt");
        assert_eq!(user, "user message");
        assert_eq!(max_iter, 10);
        assert_eq!(max_tokens, 100_000);
    }

    #[test]
    fn test_parse_reason_args_named() {
        let mut map = HashMap::new();
        map.insert("system".into(), DslValue::String("sys".into()));
        map.insert("user".into(), DslValue::String("usr".into()));
        map.insert("max_iterations".into(), DslValue::Integer(5));

        let args = vec![DslValue::Map(map)];
        let (system, user, max_iter, max_tokens) = parse_reason_args(&args).unwrap();
        assert_eq!(system, "sys");
        assert_eq!(user, "usr");
        assert_eq!(max_iter, 5);
        assert_eq!(max_tokens, 100_000);
    }

    #[test]
    fn test_parse_reason_args_missing_required() {
        let mut map = HashMap::new();
        map.insert("system".into(), DslValue::String("sys".into()));
        // Missing "user"

        let args = vec![DslValue::Map(map)];
        assert!(parse_reason_args(&args).is_err());
    }

    #[test]
    fn extracts_optional_protocol_label_named_arg() {
        // Named-arg map containing protocol_label alongside agent/message
        let mut map_with = HashMap::new();
        map_with.insert("agent".into(), DslValue::String("Worker".into()));
        map_with.insert("message".into(), DslValue::String("go".into()));
        map_with.insert("protocol_label".into(), DslValue::String("fast".into()));
        let with = vec![DslValue::Map(map_with)];
        assert_eq!(optional_protocol_label(&with), Some("fast".to_string()));

        // Positional-only — no protocol_label
        let without = vec![
            DslValue::String("Worker".into()),
            DslValue::String("go".into()),
        ];
        assert_eq!(optional_protocol_label(&without), None);

        // Named-arg map without protocol_label key
        let mut map_absent = HashMap::new();
        map_absent.insert("agent".into(), DslValue::String("Bot".into()));
        map_absent.insert("message".into(), DslValue::String("hi".into()));
        let no_label = vec![DslValue::Map(map_absent)];
        assert_eq!(optional_protocol_label(&no_label), None);

        // Wrong type for protocol_label — treated as absent
        let mut map_wrong = HashMap::new();
        map_wrong.insert("agent".into(), DslValue::String("Bot".into()));
        map_wrong.insert("message".into(), DslValue::String("hi".into()));
        map_wrong.insert("protocol_label".into(), DslValue::Integer(42));
        let wrong_type = vec![DslValue::Map(map_wrong)];
        assert_eq!(optional_protocol_label(&wrong_type), None);
    }

    // --- `tool_call` policy-gate tests ---
    //
    // `builtin_tool_call` resolves `tools/` relative to the process CWD (via
    // `build_tool_executor`), so these tests chdir into a tempdir containing
    // a real, side-effecting manifest (`touch <path>`) and check for the
    // marker file — not just the returned status string — to prove a
    // fail-closed gate actually prevents execution rather than merely
    // reporting an error. `CWD_LOCK` serializes them against each other
    // since `std::env::set_current_dir` is process-global.
    use symbi_runtime::reasoning::policy_bridge::DefaultPolicyGate;

    static CWD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Restores the original CWD (before the temp tools/ dir is deleted)
    /// and releases `CWD_LOCK` when dropped.
    struct CwdGuard {
        original: std::path::PathBuf,
        _lock: std::sync::MutexGuard<'static, ()>,
        _tempdir: tempfile::TempDir,
    }

    impl Drop for CwdGuard {
        fn drop(&mut self) {
            let _ = std::env::set_current_dir(&self.original);
        }
    }

    /// Chdir into a fresh tempdir with `tools/touch_marker.clad.toml` — a
    /// manifest that shells out to `touch {path}` — and return the path a
    /// successful call would create, plus a guard that restores CWD and
    /// cleans up on drop.
    fn setup_side_effecting_tool() -> (std::path::PathBuf, CwdGuard) {
        let lock = CWD_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let original = std::env::current_dir().expect("current dir");
        let tempdir = tempfile::tempdir().expect("tempdir");
        let tools_dir = tempdir.path().join("tools");
        std::fs::create_dir_all(&tools_dir).expect("mkdir tools/");
        std::fs::write(
            tools_dir.join("touch_marker.clad.toml"),
            r#"
[tool]
name = "touch_marker"
version = "1.0.0"
binary = "touch"
description = "test-only: creates a marker file to prove the tool actually ran"

[args.path]
position = 1
required = true
type = "string"
description = "marker file path"

[command]
template = "touch {path}"

[output]
format = "text"

[output.schema]
type = "object"
"#,
        )
        .expect("write manifest");
        std::env::set_current_dir(tempdir.path()).expect("chdir into tempdir");
        let marker = tempdir.path().join("marker.txt");
        (
            marker,
            CwdGuard {
                original,
                _lock: lock,
                _tempdir: tempdir,
            },
        )
    }

    fn touch_marker_call(marker: &std::path::Path) -> Vec<DslValue> {
        let mut args_map = HashMap::new();
        args_map.insert(
            "path".to_string(),
            DslValue::String(marker.display().to_string()),
        );
        vec![
            DslValue::String("touch_marker".to_string()),
            DslValue::Map(args_map),
        ]
    }

    #[tokio::test]
    async fn tool_call_denied_by_fail_closed_gate_never_executes() {
        let (marker, _guard) = setup_side_effecting_tool();
        let ctx = ReasoningBuiltinContext {
            reasoning_policy_gate: Some(Arc::new(DefaultPolicyGate::new())),
            ..Default::default()
        };

        let result = builtin_tool_call(&touch_marker_call(&marker), &ctx)
            .await
            .expect("builtin_tool_call should not error, just report denial");

        match result {
            DslValue::Map(map) => {
                assert_eq!(
                    map.get("status"),
                    Some(&DslValue::String("denied".to_string()))
                );
            }
            other => panic!("expected Map, got {other:?}"),
        }
        assert!(
            !marker.exists(),
            "fail-closed gate must prevent the tool from actually running, \
             not just report an error"
        );
    }

    #[tokio::test]
    async fn tool_call_with_no_gate_in_context_defaults_fail_closed() {
        // Mirrors `builtin_reason`'s default: a context that never had a
        // gate installed must NOT fall back to permissive.
        let (marker, _guard) = setup_side_effecting_tool();
        let ctx = ReasoningBuiltinContext::default();

        builtin_tool_call(&touch_marker_call(&marker), &ctx)
            .await
            .expect("builtin_tool_call should not error, just report denial");

        assert!(
            !marker.exists(),
            "no policy gate configured must default to fail-closed, never permissive"
        );
    }

    #[tokio::test]
    async fn tool_call_allowed_by_permissive_gate_executes() {
        let (marker, _guard) = setup_side_effecting_tool();
        let ctx = ReasoningBuiltinContext {
            reasoning_policy_gate: Some(Arc::new(DefaultPolicyGate::permissive_for_dev_only())),
            ..Default::default()
        };

        let result = builtin_tool_call(&touch_marker_call(&marker), &ctx)
            .await
            .expect("builtin_tool_call should not error");

        match result {
            DslValue::Map(map) => {
                assert_eq!(
                    map.get("status"),
                    Some(&DslValue::String("success".to_string()))
                );
            }
            other => panic!("expected Map, got {other:?}"),
        }
        assert!(
            marker.exists(),
            "permissive gate should allow the tool to actually run"
        );
    }
}