Skip to main content

hyprstream_workers_tcl/
lib.rs

1//! Tcl (molt) shell for the hyprstream VFS namespace.
2//!
3//! Provides a `TclShell` that wraps a molt interpreter with VFS builtins
4//! (`cat`, `ls`, `echo`, `ctl`, `help`, `mount`). Commands are evaluated
5//! as standard Tcl with VFS path operations. Unknown commands fall back
6//! to `/bin/{name}` resolution (Plan9 PATH model).
7//!
8//! **Security**: Dangerous molt commands (`source`, `exit`, `puts`, `rename`,
9//! `global`, `time`) are removed at construction. All host filesystem access
10//! goes through the VFS — the Tcl interpreter is a guest with no direct I/O.
11//!
12//! `TclShell` is `!Send`/`!Sync` (molt `Value` uses `Rc`). One interpreter
13//! per ChatApp or shell session.
14
15mod builtins;
16pub mod mount;
17
18use hyprstream_vfs::{Namespace, Subject};
19use molt::types::*;
20use molt::Interp;
21use std::sync::Arc;
22
23pub use mount::{TclCommand, TclMount};
24
25/// Context stored in the molt interpreter via `save_context()`.
26///
27/// VFS operations are called directly via the Namespace — no proxy channel needed.
28pub(crate) struct ShellContext {
29    pub subject: Subject,
30    pub namespace: Arc<Namespace>,
31}
32
33/// A Tcl shell backed by the hyprstream VFS namespace.
34///
35/// Contains a molt `Interp` which is `!Send` (uses `Rc` internally).
36/// Must be constructed and used on the same thread — use `spawn_blocking`
37/// to run on a dedicated thread, passing only `Send` arguments (subject, vfs_tx).
38pub struct TclShell {
39    interp: Interp,
40    ctx_id: ContextID,
41}
42
43impl TclShell {
44    /// Create a new Tcl shell bound to the given caller identity and VFS namespace.
45    ///
46    /// Builtins `.await` VFS operations directly on the namespace — no proxy channel.
47    ///
48    /// TclShell is `!Send` due to molt's `Rc`-based `Value`.
49    /// Must be used within a `LocalSet` or single-threaded executor.
50    ///
51    /// Dangerous commands are removed and the recursion limit is lowered.
52    /// All host I/O goes through the VFS — this is a guest interpreter.
53    pub fn new(subject: Subject, namespace: Arc<Namespace>) -> Self {
54        let mut interp = Interp::new();
55
56        // Remove dangerous commands — all host I/O goes through VFS.
57        // source: reads arbitrary host files via std::fs::read_to_string
58        // exit: calls std::process::exit(), kills the server
59        // puts: writes to server stdout (log injection)
60        // rename: can shadow/delete security-critical builtins
61        // global: scope manipulation unnecessary in VFS shell
62        // time: runs a command N times (user-controlled N, CPU bomb)
63        // parse/pdump/pclear: debug internals, not for users
64        // apply/eval/subst/uplevel: evaluate arbitrary code, enabling injection via field output
65        for cmd in &[
66            "source", "exit", "puts", "rename", "global", "time", "parse", "pdump", "pclear",
67            "apply", "eval", "subst", "uplevel",
68        ] {
69            if interp.has_command(cmd) {
70                interp.remove_command(cmd);
71            }
72        }
73        interp.set_recursion_limit(100);
74        interp.set_instruction_limit(100_000);
75
76        let ctx = ShellContext { subject, namespace };
77        let ctx_id = interp.save_context(ctx);
78        builtins::register_all(&mut interp, ctx_id);
79        Self { interp, ctx_id }
80    }
81
82    /// Evaluate a Tcl script. Returns Ok(output) or Err(error message).
83    ///
84    /// On "invalid command name" errors, tries `/bin/{name}` resolution
85    /// (Plan9 PATH model) before returning the error.
86    pub async fn eval(&mut self, script: &str) -> Result<String, String> {
87        self.interp.reset_instruction_count();
88        match self.interp.eval(script).await {
89            Ok(val) => Ok(val.to_string()),
90            Err(exception) => {
91                let msg = exception.value().to_string();
92                // Try /bin/ resolution on command-not-found.
93                if let Some(cmd_name) = extract_unknown_command(&msg) {
94                    if let Ok(result) = self.try_cmd_resolve(&cmd_name, script).await {
95                        return Ok(result);
96                    }
97                }
98                Err(msg)
99            }
100        }
101    }
102
103    /// Check if a command name is registered in the interpreter.
104    pub fn has_command(&self, name: &str) -> bool {
105        self.interp.has_command(name)
106    }
107
108    /// Set an env array variable safely, bypassing the Tcl evaluator.
109    ///
110    /// Uses `Interp::set_element` to avoid Tcl injection from values
111    /// containing unbalanced braces or bracket expressions.
112    pub fn set_env(&mut self, key: &str, value: &str) -> Result<(), String> {
113        self.interp
114            .set_element("env", key, molt::types::Value::from(value))
115            .map_err(|e| e.value().to_string())
116    }
117
118    /// Override the instruction limit (default: 100,000).
119    /// Set to 0 for unlimited (not recommended for untrusted input).
120    pub fn set_instruction_limit(&mut self, limit: usize) {
121        self.interp.set_instruction_limit(limit);
122    }
123
124    /// Process one command from the mount channel.
125    ///
126    /// Called from the owner thread's event loop (e.g., `ChatApp::tick()`).
127    /// Each command carries a oneshot response channel; the caller blocks
128    /// until we send the reply.
129    pub async fn process_command(&mut self, cmd: TclCommand) {
130        match cmd {
131            TclCommand::Eval { script, resp } => {
132                let _ = resp.send(self.eval(&script).await);
133            }
134            TclCommand::ListVars { resp } => {
135                let names: Vec<String> = self
136                    .interp
137                    .vars_in_scope()
138                    .iter()
139                    .map(|v| v.to_string())
140                    .collect();
141                let _ = resp.send(names);
142            }
143            TclCommand::GetVar { name, resp } => {
144                let val = self.interp.scalar(&name).ok().map(|v| v.to_string());
145                let _ = resp.send(val);
146            }
147            TclCommand::ListProcs { resp } => {
148                let names: Vec<String> = self
149                    .interp
150                    .proc_names()
151                    .iter()
152                    .map(|v| v.to_string())
153                    .collect();
154                let _ = resp.send(names);
155            }
156            TclCommand::GetProc { name, resp } => {
157                let body = self.interp.proc_body(&name).ok().map(|v| v.to_string());
158                let _ = resp.send(body);
159            }
160        }
161    }
162
163    /// Try resolving an unknown command via `/bin/{name}` (Plan9 PATH model).
164    ///
165    /// Two-phase resolution:
166    /// 1. Try ctl (write+read) — for Rust-backed service actions
167    /// 2. If ctl fails, try cat — for `.tcl` script files, then eval with args
168    async fn try_cmd_resolve(&mut self, cmd_name: &str, script: &str) -> Result<String, String> {
169        // Sanitize: reject path traversal in command names.
170        if cmd_name.contains('/') || cmd_name.contains("..") {
171            return Err(format!("invalid command name \"{cmd_name}\""));
172        }
173        let cmd_path = format!("/bin/{cmd_name}");
174        let raw_args = script.trim().strip_prefix(cmd_name).unwrap_or("").trim();
175
176        // Evaluate args through the Tcl evaluator to resolve variable and
177        // command substitutions (e.g., `[cat /config/token]` → actual value).
178        // Without this, raw bracket expressions reach ctl file handlers.
179        let evaluated_args = if raw_args.is_empty() {
180            String::new()
181        } else {
182            match self.interp.eval(&format!("list {raw_args}")).await {
183                Ok(val) => val.to_string(),
184                Err(e) => return Err(e.value().to_string()),
185            }
186        };
187
188        // Get namespace and subject for direct VFS access.
189        let ctx = self.interp.context::<ShellContext>(self.ctx_id);
190        let namespace = Arc::clone(&ctx.namespace);
191        let subject = ctx.subject.clone();
192
193        // Phase 1: Try ctl (service actions — CtlFile nodes).
194        if let Ok(resp) = namespace
195            .ctl(&cmd_path, evaluated_args.as_bytes(), &subject)
196            .await
197        {
198            return Ok(String::from_utf8_lossy(&resp).into_owned());
199        }
200
201        // Phase 2: Try cat (script files — ReadFile nodes).
202        // Read the script, prepend `set argv {args}`, and eval it.
203        match namespace.cat(&cmd_path, &subject).await {
204            Ok(script_bytes) => {
205                let tool_script = String::from_utf8_lossy(&script_bytes);
206                // Wrap: set argv before executing so the script can access args.
207                let wrapped = format!("set argv {{{evaluated_args}}}\n{tool_script}");
208                match self.interp.eval(&wrapped).await {
209                    Ok(val) => Ok(val.to_string()),
210                    Err(e) => Err(e.value().to_string()),
211                }
212            }
213            Err(_) => Err(format!("invalid command name \"{cmd_name}\"")),
214        }
215    }
216}
217
218/// Extract the command name from a molt "invalid command name" error.
219///
220/// The error format is: `invalid command name "foo"`
221fn extract_unknown_command(msg: &str) -> Option<String> {
222    let prefix = "invalid command name \"";
223    if let Some(rest) = msg.strip_prefix(prefix) {
224        rest.strip_suffix('"').map(|s| s.to_owned())
225    } else {
226        None
227    }
228}
229
230// ─────────────────────────────────────────────────────────────────────────────
231// Tests
232// ─────────────────────────────────────────────────────────────────────────────
233
234#[cfg(test)]
235#[allow(clippy::unwrap_used, clippy::disallowed_types)]
236mod tests {
237    use super::*;
238    use async_trait::async_trait;
239    use hyprstream_vfs::{DirEntry, Fid, Mount, MountError, Namespace, Stat};
240    use std::collections::HashMap;
241
242    /// Minimal in-memory mount for testing.
243    struct MemMount {
244        files: HashMap<String, Vec<u8>>,
245    }
246
247    impl MemMount {
248        fn new(files: Vec<(&str, &[u8])>) -> Self {
249            Self {
250                files: files
251                    .into_iter()
252                    .map(|(k, v)| (k.to_owned(), v.to_vec()))
253                    .collect(),
254            }
255        }
256    }
257
258    struct MemFid {
259        path: String,
260        write_buf: std::sync::Mutex<Vec<u8>>,
261    }
262
263    #[async_trait]
264    impl Mount for MemMount {
265        async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
266            let path = components.join("/");
267            let exists = self.files.contains_key(&path)
268                || self
269                    .files
270                    .keys()
271                    .any(|k| k.starts_with(&format!("{path}/")));
272            if !exists && !path.is_empty() {
273                return Err(MountError::NotFound(path));
274            }
275            Ok(Fid::new(MemFid {
276                path,
277                write_buf: std::sync::Mutex::new(Vec::new()),
278            }))
279        }
280
281        async fn open(
282            &self,
283            _fid: &mut Fid,
284            _mode: u8,
285            _caller: &Subject,
286        ) -> Result<(), MountError> {
287            Ok(())
288        }
289
290        async fn read(
291            &self,
292            fid: &Fid,
293            offset: u64,
294            _count: u32,
295            _caller: &Subject,
296        ) -> Result<Vec<u8>, MountError> {
297            let inner = fid
298                .downcast_ref::<MemFid>()
299                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
300            let wb = inner.write_buf.lock().unwrap();
301            if !wb.is_empty() {
302                let start = offset as usize;
303                if start >= wb.len() {
304                    return Ok(vec![]);
305                }
306                return Ok(wb[start..].to_vec());
307            }
308            drop(wb);
309            match self.files.get(&inner.path) {
310                Some(data) => {
311                    let start = offset as usize;
312                    if start >= data.len() {
313                        return Ok(vec![]);
314                    }
315                    Ok(data[start..].to_vec())
316                }
317                None => Err(MountError::NotFound(inner.path.clone())),
318            }
319        }
320
321        async fn write(
322            &self,
323            fid: &Fid,
324            _offset: u64,
325            data: &[u8],
326            _caller: &Subject,
327        ) -> Result<u32, MountError> {
328            let inner = fid
329                .downcast_ref::<MemFid>()
330                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
331            *inner.write_buf.lock().unwrap() =
332                format!("ok: {}", String::from_utf8_lossy(data)).into_bytes();
333            Ok(data.len() as u32)
334        }
335
336        async fn readdir(&self, fid: &Fid, _caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
337            let inner = fid
338                .downcast_ref::<MemFid>()
339                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
340            let prefix = if inner.path.is_empty() {
341                String::new()
342            } else {
343                format!("{}/", inner.path)
344            };
345            let mut entries = Vec::new();
346            for key in self.files.keys() {
347                if let Some(rest) = key.strip_prefix(&prefix) {
348                    if !rest.contains('/') {
349                        entries.push(DirEntry {
350                            name: rest.to_owned(),
351                            is_dir: false,
352                            size: 0,
353                            stat: None,
354                        });
355                    }
356                } else if inner.path.is_empty() && !key.contains('/') {
357                    entries.push(DirEntry {
358                        name: key.clone(),
359                        is_dir: false,
360                        size: 0,
361                        stat: None,
362                    });
363                }
364            }
365            Ok(entries)
366        }
367
368        async fn stat(&self, fid: &Fid, _caller: &Subject) -> Result<Stat, MountError> {
369            let inner = fid
370                .downcast_ref::<MemFid>()
371                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
372            Ok(Stat::unknown_qid(0, 0, inner.path.clone(), 0))
373        }
374
375        async fn clunk(&self, _fid: Fid, _caller: &Subject) {}
376    }
377
378    fn test_subject() -> Subject {
379        Subject::new("test")
380    }
381
382    fn make_namespace() -> Arc<Namespace> {
383        let mut ns = Namespace::new();
384        let mount = Arc::new(MemMount::new(vec![
385            ("temperature", b"0.7"),
386            ("status", b"loaded"),
387        ]));
388        ns.mount("/config", mount).unwrap();
389
390        let model_mount = Arc::new(MemMount::new(vec![("status", b"loaded")]));
391        ns.mount("/srv/model", model_mount).unwrap();
392
393        let bin_mount = Arc::new(MemMount::new(vec![("load", b"")]));
394        ns.mount("/bin", bin_mount).unwrap();
395
396        Arc::new(ns)
397    }
398
399    // Note: TclShell is !Send, so we use current_thread + LocalSet for all tests.
400
401    #[tokio::test(flavor = "current_thread")]
402    async fn eval_cat() {
403        let ns = make_namespace();
404        let local = tokio::task::LocalSet::new();
405        let result = local
406            .run_until(async {
407                let mut shell = TclShell::new(test_subject(), ns);
408                shell.eval("cat /config/temperature").await
409            })
410            .await
411            .unwrap();
412        assert_eq!(result, "0.7");
413    }
414
415    #[tokio::test(flavor = "current_thread")]
416    async fn eval_cat_multi() {
417        let ns = make_namespace();
418        let local = tokio::task::LocalSet::new();
419        let result = local
420            .run_until(async {
421                let mut shell = TclShell::new(test_subject(), ns);
422                shell.eval("cat /config/temperature /config/status").await
423            })
424            .await
425            .unwrap();
426        assert_eq!(result, "0.7loaded");
427    }
428
429    #[tokio::test(flavor = "current_thread")]
430    async fn eval_cat_not_found() {
431        let ns = make_namespace();
432        let local = tokio::task::LocalSet::new();
433        let result = local
434            .run_until(async {
435                let mut shell = TclShell::new(test_subject(), ns);
436                shell.eval("cat /config/nonexistent").await
437            })
438            .await;
439        assert!(result.is_err());
440    }
441
442    #[tokio::test(flavor = "current_thread")]
443    async fn eval_ls() {
444        let ns = make_namespace();
445        let local = tokio::task::LocalSet::new();
446        let result = local
447            .run_until(async {
448                let mut shell = TclShell::new(test_subject(), ns);
449                shell.eval("ls /config").await
450            })
451            .await
452            .unwrap();
453        assert!(result.contains("temperature"));
454        assert!(result.contains("status"));
455    }
456
457    #[tokio::test(flavor = "current_thread")]
458    async fn eval_ls_root() {
459        let ns = make_namespace();
460        let local = tokio::task::LocalSet::new();
461        let result = local
462            .run_until(async {
463                let mut shell = TclShell::new(test_subject(), ns);
464                shell.eval("ls").await
465            })
466            .await
467            .unwrap();
468        assert!(result.contains("srv"));
469        assert!(result.contains("config"));
470        assert!(result.contains("bin"));
471    }
472
473    #[tokio::test(flavor = "current_thread")]
474    async fn eval_write() {
475        let ns = make_namespace();
476        let local = tokio::task::LocalSet::new();
477        let result = local
478            .run_until(async {
479                let mut shell = TclShell::new(test_subject(), ns);
480                shell.eval("write /bin/load qwen3:main").await
481            })
482            .await;
483        assert!(result.is_ok());
484    }
485
486    #[tokio::test(flavor = "current_thread")]
487    async fn eval_ctl() {
488        let ns = make_namespace();
489        let local = tokio::task::LocalSet::new();
490        let result = local
491            .run_until(async {
492                let mut shell = TclShell::new(test_subject(), ns);
493                shell.eval("ctl /bin/load qwen3:main").await
494            })
495            .await
496            .unwrap();
497        assert_eq!(result, "ok: qwen3:main");
498    }
499
500    #[tokio::test(flavor = "current_thread")]
501    async fn eval_help() {
502        let ns = make_namespace();
503        let local = tokio::task::LocalSet::new();
504        let result = local
505            .run_until(async {
506                let mut shell = TclShell::new(test_subject(), ns);
507                shell.eval("help").await
508            })
509            .await
510            .unwrap();
511        assert!(result.contains("cat"));
512        assert!(result.contains("ls"));
513        assert!(result.contains("ctl"));
514        assert!(result.contains("write"));
515        assert!(result.contains("mount"));
516        assert!(result.contains("help"));
517    }
518
519    #[tokio::test(flavor = "current_thread")]
520    async fn eval_mount() {
521        let ns = make_namespace();
522        let local = tokio::task::LocalSet::new();
523        let result = local
524            .run_until(async {
525                let mut shell = TclShell::new(test_subject(), ns);
526                shell.eval("mount").await
527            })
528            .await
529            .unwrap();
530        assert!(result.contains("/config"));
531        assert!(result.contains("/srv/model"));
532        assert!(result.contains("/bin"));
533    }
534
535    #[tokio::test(flavor = "current_thread")]
536    async fn eval_mount_specific() {
537        let ns = make_namespace();
538        let local = tokio::task::LocalSet::new();
539        let result = local
540            .run_until(async {
541                let mut shell = TclShell::new(test_subject(), ns);
542                shell.eval("mount /config").await
543            })
544            .await
545            .unwrap();
546        assert_eq!(result, "mounted: /config");
547    }
548
549    #[tokio::test(flavor = "current_thread")]
550    async fn eval_mount_not_found() {
551        let ns = make_namespace();
552        let local = tokio::task::LocalSet::new();
553        let result = local
554            .run_until(async {
555                let mut shell = TclShell::new(test_subject(), ns);
556                shell.eval("mount /nonexistent").await
557            })
558            .await;
559        assert!(result.is_err());
560    }
561
562    #[tokio::test(flavor = "current_thread")]
563    async fn eval_tcl_builtins() {
564        let ns = make_namespace();
565        let local = tokio::task::LocalSet::new();
566        let result = local
567            .run_until(async {
568                let mut shell = TclShell::new(test_subject(), ns);
569                shell
570                    .eval("set x [cat /config/temperature]; string length $x")
571                    .await
572            })
573            .await
574            .unwrap();
575        assert_eq!(result, "3");
576    }
577
578    #[tokio::test(flavor = "current_thread")]
579    async fn eval_tcl_expr() {
580        let ns = make_namespace();
581        let local = tokio::task::LocalSet::new();
582        let result = local
583            .run_until(async {
584                let mut shell = TclShell::new(test_subject(), ns);
585                shell.eval("expr {2 + 3}").await
586            })
587            .await
588            .unwrap();
589        assert_eq!(result, "5");
590    }
591
592    #[tokio::test(flavor = "current_thread")]
593    async fn unknown_resolves_cmd() {
594        let ns = make_namespace();
595        let local = tokio::task::LocalSet::new();
596        let result = local
597            .run_until(async {
598                let mut shell = TclShell::new(test_subject(), ns);
599                shell.eval("load qwen3:main").await
600            })
601            .await
602            .unwrap();
603        assert_eq!(result, "ok: qwen3:main");
604    }
605
606    #[tokio::test(flavor = "current_thread")]
607    async fn unknown_fails_cleanly() {
608        let ns = make_namespace();
609        let local = tokio::task::LocalSet::new();
610        let result = local
611            .run_until(async {
612                let mut shell = TclShell::new(test_subject(), ns);
613                shell.eval("nonexistent_command arg1 arg2").await
614            })
615            .await;
616        assert!(result.is_err());
617        assert!(result.unwrap_err().contains("invalid command name"));
618    }
619
620    #[test]
621    fn has_command_builtin() {
622        let ns = make_namespace();
623        let shell = TclShell::new(test_subject(), ns);
624        assert!(shell.has_command("cat"));
625        assert!(shell.has_command("ls"));
626        assert!(shell.has_command("help"));
627        assert!(shell.has_command("expr"));
628        assert!(!shell.has_command("nonexistent"));
629    }
630
631    #[test]
632    fn extract_unknown_command_parse() {
633        assert_eq!(
634            extract_unknown_command("invalid command name \"foo\""),
635            Some("foo".to_owned())
636        );
637        assert_eq!(
638            extract_unknown_command("invalid command name \"load\""),
639            Some("load".to_owned())
640        );
641        assert_eq!(extract_unknown_command("some other error"), None);
642    }
643
644    // ── Hardening tests ──────────────────────────────────────────────────────
645
646    #[tokio::test(flavor = "current_thread")]
647    async fn source_command_removed() {
648        let ns = make_namespace();
649        let local = tokio::task::LocalSet::new();
650        let result = local
651            .run_until(async {
652                let mut shell = TclShell::new(test_subject(), ns);
653                shell.eval("source /etc/passwd").await
654            })
655            .await;
656        assert!(result.is_err());
657        assert!(result.unwrap_err().contains("invalid command name"));
658    }
659
660    #[tokio::test(flavor = "current_thread")]
661    async fn exit_command_removed() {
662        let ns = make_namespace();
663        let local = tokio::task::LocalSet::new();
664        let result = local
665            .run_until(async {
666                let mut shell = TclShell::new(test_subject(), ns);
667                shell.eval("exit").await
668            })
669            .await;
670        assert!(result.is_err());
671        assert!(result.unwrap_err().contains("invalid command name"));
672    }
673
674    #[tokio::test(flavor = "current_thread")]
675    async fn puts_command_removed() {
676        let ns = make_namespace();
677        let local = tokio::task::LocalSet::new();
678        let result = local
679            .run_until(async {
680                let mut shell = TclShell::new(test_subject(), ns);
681                shell.eval("puts hello").await
682            })
683            .await;
684        assert!(result.is_err());
685    }
686
687    #[tokio::test(flavor = "current_thread")]
688    async fn rename_command_removed() {
689        let ns = make_namespace();
690        let local = tokio::task::LocalSet::new();
691        let result = local
692            .run_until(async {
693                let mut shell = TclShell::new(test_subject(), ns);
694                shell.eval("rename cat {}").await
695            })
696            .await;
697        assert!(result.is_err());
698    }
699
700    #[tokio::test(flavor = "current_thread")]
701    async fn time_command_removed() {
702        let ns = make_namespace();
703        let local = tokio::task::LocalSet::new();
704        let result = local
705            .run_until(async {
706                let mut shell = TclShell::new(test_subject(), ns);
707                shell.eval("time {expr 1} 999999").await
708            })
709            .await;
710        assert!(result.is_err());
711    }
712
713    #[tokio::test(flavor = "current_thread")]
714    async fn cmd_name_path_traversal_rejected() {
715        let ns = make_namespace();
716        let local = tokio::task::LocalSet::new();
717        let result = local
718            .run_until(async {
719                let mut shell = TclShell::new(test_subject(), ns);
720                shell.eval("../srv/model/ctl something").await
721            })
722            .await;
723        assert!(result.is_err());
724    }
725
726    #[tokio::test(flavor = "current_thread")]
727    async fn safe_commands_still_work() {
728        let ns = make_namespace();
729        let local = tokio::task::LocalSet::new();
730        let results = local
731            .run_until(async {
732                let mut s = TclShell::new(test_subject(), ns);
733                vec![
734                    s.eval("expr {2 + 3}").await,
735                    s.eval("set x hello; string length $x").await,
736                    s.eval("if {1} {set y yes}").await,
737                    s.eval("list a b c").await,
738                ]
739            })
740            .await;
741        assert_eq!(results[0].as_ref().unwrap(), "5");
742        assert_eq!(results[1].as_ref().unwrap(), "5");
743        assert_eq!(results[2].as_ref().unwrap(), "yes");
744        assert_eq!(results[3].as_ref().unwrap(), "a b c");
745    }
746
747    #[tokio::test(flavor = "current_thread")]
748    async fn instruction_limit_catches_infinite_loop() {
749        let ns = make_namespace();
750        let local = tokio::task::LocalSet::new();
751        let result = local
752            .run_until(async {
753                let mut shell = TclShell::new(test_subject(), ns);
754                shell.set_instruction_limit(500);
755                shell.eval("while {1} {}").await
756            })
757            .await;
758        assert!(result.is_err());
759        assert!(
760            result.unwrap_err().contains("instruction limit"),
761            "error should mention instruction limit"
762        );
763    }
764
765    // ── json builtin tests ──────────────────────────────────────────────────
766
767    #[tokio::test(flavor = "current_thread")]
768    async fn json_parse_object() {
769        let ns = make_namespace();
770        let local = tokio::task::LocalSet::new();
771        let result = local
772            .run_until(async {
773                let mut s = TclShell::new(test_subject(), ns);
774                s.eval(r#"dict get [json parse {{"name":"alice","age":30}}] name"#)
775                    .await
776            })
777            .await
778            .unwrap();
779        assert_eq!(result, "alice");
780    }
781
782    #[tokio::test(flavor = "current_thread")]
783    async fn json_parse_number() {
784        let ns = make_namespace();
785        let local = tokio::task::LocalSet::new();
786        let result = local
787            .run_until(async {
788                let mut s = TclShell::new(test_subject(), ns);
789                s.eval(r#"dict get [json parse {{"name":"alice","age":30}}] age"#)
790                    .await
791            })
792            .await
793            .unwrap();
794        assert_eq!(result, "30");
795    }
796
797    #[tokio::test(flavor = "current_thread")]
798    async fn json_parse_nested() {
799        let ns = make_namespace();
800        let local = tokio::task::LocalSet::new();
801        let result = local
802            .run_until(async {
803                let mut s = TclShell::new(test_subject(), ns);
804                s.eval(r#"dict get [dict get [json parse {{"data":{"x":1}}}] data] x"#)
805                    .await
806            })
807            .await
808            .unwrap();
809        assert_eq!(result, "1");
810    }
811
812    #[tokio::test(flavor = "current_thread")]
813    async fn json_parse_invalid() {
814        let ns = make_namespace();
815        let local = tokio::task::LocalSet::new();
816        let result = local
817            .run_until(async {
818                let mut s = TclShell::new(test_subject(), ns);
819                s.eval(r#"json parse {not json}"#).await
820            })
821            .await;
822        assert!(result.is_err());
823        assert!(result.unwrap_err().contains("invalid JSON"));
824    }
825
826    #[tokio::test(flavor = "current_thread")]
827    async fn json_parse_array() {
828        let ns = make_namespace();
829        let local = tokio::task::LocalSet::new();
830        let result = local
831            .run_until(async {
832                let mut s = TclShell::new(test_subject(), ns);
833                s.eval(r#"lindex [json parse {[1, 2, 3]}] 1"#).await
834            })
835            .await
836            .unwrap();
837        assert_eq!(result, "2");
838    }
839
840    #[tokio::test(flavor = "current_thread")]
841    async fn json_parse_bool_null() {
842        let ns = make_namespace();
843        let local = tokio::task::LocalSet::new();
844        let result = local
845            .run_until(async {
846                let mut s = TclShell::new(test_subject(), ns);
847                s.eval(r#"dict get [json parse {{"flag":true,"empty":null}}] flag"#)
848                    .await
849            })
850            .await
851            .unwrap();
852        assert_eq!(result, "1");
853    }
854
855    #[tokio::test(flavor = "current_thread")]
856    async fn json_unknown_subcommand() {
857        let ns = make_namespace();
858        let local = tokio::task::LocalSet::new();
859        let result = local
860            .run_until(async {
861                let mut s = TclShell::new(test_subject(), ns);
862                s.eval(r#"json encode {something}"#).await
863            })
864            .await;
865        assert!(result.is_err());
866        assert!(result.unwrap_err().contains("unknown subcommand"));
867    }
868
869    #[tokio::test(flavor = "current_thread")]
870    async fn json_in_help() {
871        let ns = make_namespace();
872        let local = tokio::task::LocalSet::new();
873        let result = local
874            .run_until(async {
875                let mut s = TclShell::new(test_subject(), ns);
876                s.eval("help").await
877            })
878            .await
879            .unwrap();
880        assert!(result.contains("json"));
881    }
882}