Skip to main content

algocline_engine/
executor.rs

1//! Lua execution engine.
2//!
3//! Orchestrates StdLib injection and Lua execution for each session:
4//!
5//! 1. **Layer 0** — [`bridge::register`] injects Rust-backed `alc.*` primitives
6//! 2. **Layer 1** — [`PRELUDE`] adds Lua-based combinators (`alc.map`, etc.)
7//! 3. **Layer 2** — [`mlua_pkg::Registry`] makes `require("ucb")` etc.
8//!    resolve from `~/.algocline/packages/`
9//!
10//! ## Execution models
11//!
12//! - **`eval_simple`** — sync eval on a shared VM (no LLM bridge).
13//!   For lightweight ops like reading package metadata.
14//! - **`start_session`** — spawns a **dedicated VM per session**.
15//!   Each session gets an isolated Lua VM so concurrent sessions
16//!   cannot interfere with each other's globals (`alc`, `ctx`).
17//!   `alc.llm()` yields the coroutine, and the VM is cleaned up
18//!   when the session completes or is abandoned.
19
20use std::path::PathBuf;
21use std::sync::Arc;
22
23use algocline_core::{Budget, ExecutionMetrics, ExecutionSpec};
24use mlua::LuaSerdeExt;
25use mlua_isle::{AsyncIsle, AsyncIsleDriver, IsleError};
26use mlua_pkg::Registry;
27
28use crate::bridge;
29use crate::card::FileCardStore;
30use crate::llm_bridge::LlmRequest;
31use crate::resolver_factory::make_resolver;
32use crate::session::Session;
33use crate::state::JsonFileStore;
34use crate::variant_pkg::{register_variant_pkgs, VariantPkg};
35
36/// Layer 1: Prelude combinators (map, reduce, vote, filter).
37/// Embedded at compile time and loaded into every session.
38const PRELUDE: &str = include_str!("prelude.lua");
39
40/// Lua execution engine.
41///
42/// Holds a **shared VM** for lightweight stateless operations (`eval_simple`)
43/// and spawns **per-session VMs** for coroutine-based execution (`start_session`).
44///
45/// Per-session VMs eliminate global namespace pollution between concurrent
46/// sessions — each session's `alc`, `ctx`, and `package.loaded` are fully
47/// isolated.
48pub struct Executor {
49    /// Shared VM for eval_simple (stateless, no session globals).
50    isle: AsyncIsle,
51    _driver: AsyncIsleDriver,
52    /// Package resolver paths, cloned into each per-session VM.
53    lib_paths: Vec<PathBuf>,
54}
55
56impl Executor {
57    pub async fn new(lib_paths: Vec<PathBuf>) -> anyhow::Result<Self> {
58        let paths_for_shared = lib_paths.clone();
59        let (isle, driver) = AsyncIsle::spawn(move |lua| {
60            let mut reg = Registry::new();
61            for path in &paths_for_shared {
62                if let Some(resolver) = make_resolver(path) {
63                    reg.add(resolver);
64                }
65            }
66            reg.install(lua)?;
67            Ok(())
68        })
69        .await?;
70
71        Ok(Self {
72            isle,
73            _driver: driver,
74            lib_paths,
75        })
76    }
77
78    /// Evaluate Lua code without LLM bridge. For lightweight operations
79    /// like reading package metadata.
80    ///
81    /// Uses the shared VM. `extra_lib_paths` must be empty — use
82    /// [`Self::eval_simple_with_paths`] when project-local paths are needed.
83    pub async fn eval_simple(&self, code: String) -> Result<serde_json::Value, String> {
84        self.eval_simple_with_paths(code, vec![], vec![]).await
85    }
86
87    /// Evaluate Lua code without LLM bridge, with optional extra package paths
88    /// and variant pkgs.
89    ///
90    /// When both `extra_lib_paths` and `variant_pkgs` are empty, reuses the
91    /// shared VM (cheap). When either is non-empty, spawns a dedicated VM so
92    /// the extra resolvers are active (slightly more expensive, but `pkg_list`
93    /// is the only caller and it is low-frequency).
94    ///
95    /// The fast path does not register `alc.*` bridge primitives, so the
96    /// `state_store` / `card_store` / `scenarios_dir` handles that
97    /// [`Self::start_session`] requires are not threaded through here —
98    /// callers that need them go through `start_session`.
99    pub async fn eval_simple_with_paths(
100        &self,
101        code: String,
102        extra_lib_paths: Vec<PathBuf>,
103        variant_pkgs: Vec<VariantPkg>,
104    ) -> Result<serde_json::Value, String> {
105        if extra_lib_paths.is_empty() && variant_pkgs.is_empty() {
106            // Fast path: reuse the long-lived shared VM.
107            let task = self.isle.spawn_exec(move |lua| {
108                let result: mlua::Value = lua
109                    .load(&code)
110                    .eval()
111                    .map_err(|e| IsleError::Lua(e.to_string()))?;
112                let json: serde_json::Value = lua
113                    .from_value(result)
114                    .map_err(|e| IsleError::Lua(e.to_string()))?;
115                serde_json::to_string(&json)
116                    .map_err(|e| IsleError::Lua(format!("JSON serialize: {e}")))
117            });
118            let json_str = task.await.map_err(|e| e.to_string())?;
119            return serde_json::from_str(&json_str).map_err(|e| format!("JSON parse: {e}"));
120        }
121
122        // Slow path: spawn a dedicated VM with extra resolvers prepended.
123        let mut effective = extra_lib_paths;
124        effective.extend(self.lib_paths.iter().cloned());
125
126        let (tmp_isle, _tmp_driver) = AsyncIsle::spawn(move |lua| {
127            let mut reg = Registry::new();
128            // Variant pkgs first so alc.local.toml overrides win over global.
129            register_variant_pkgs(&mut reg, &variant_pkgs);
130            for path in &effective {
131                if let Some(resolver) = make_resolver(path) {
132                    reg.add(resolver);
133                }
134            }
135            reg.install(lua)?;
136            Ok(())
137        })
138        .await
139        .map_err(|e| format!("eval_simple VM spawn failed: {e}"))?;
140
141        let task = tmp_isle.spawn_exec(move |lua| {
142            let result: mlua::Value = lua
143                .load(&code)
144                .eval()
145                .map_err(|e| IsleError::Lua(e.to_string()))?;
146            let json: serde_json::Value = lua
147                .from_value(result)
148                .map_err(|e| IsleError::Lua(e.to_string()))?;
149            serde_json::to_string(&json).map_err(|e| IsleError::Lua(format!("JSON serialize: {e}")))
150        });
151
152        let json_str = task.await.map_err(|e| e.to_string())?;
153        serde_json::from_str(&json_str).map_err(|e| format!("JSON parse: {e}"))
154    }
155
156    /// Start a new Lua execution session on a **dedicated VM**.
157    ///
158    /// Each session gets its own Lua VM (OS thread + mlua instance) so
159    /// concurrent sessions cannot interfere with each other's globals.
160    /// The VM is cleaned up automatically when the session completes or
161    /// is abandoned (all senders drop → channel closes → thread exits).
162    ///
163    /// `extra_lib_paths` are prepended to `self.lib_paths` so project-local
164    /// packages take precedence over the global package directory.
165    /// `variant_pkgs` come from `alc.local.toml` and override both layers
166    /// (registered at the highest priority).
167    ///
168    /// `state_store` / `card_store` / `scenarios_dir` are resolved by the
169    /// service layer (typically from `AppConfig.app_dir()`) so the engine
170    /// crate never touches HOME. They flow through [`bridge::BridgeConfig`]
171    /// to back `alc.state.*` / `alc.card.*` / `alc._dirs.scenarios`.
172    #[allow(clippy::too_many_arguments)]
173    pub async fn start_session(
174        &self,
175        code: String,
176        ctx: serde_json::Value,
177        extra_lib_paths: Vec<PathBuf>,
178        variant_pkgs: Vec<VariantPkg>,
179        state_store: Arc<JsonFileStore>,
180        card_store: Arc<FileCardStore>,
181        scenarios_dir: PathBuf,
182    ) -> Result<Session, String> {
183        let spec = ExecutionSpec::new(code, ctx);
184        let metrics = ExecutionMetrics::new();
185
186        // Extract and apply budget from ctx.budget
187        if let Some(budget) = Budget::from_ctx(&spec.ctx) {
188            metrics.set_budget(budget);
189        }
190
191        let (llm_tx, llm_rx) = tokio::sync::mpsc::channel::<LlmRequest>(16);
192
193        // Build effective lib_paths: extra (project-local) first, then defaults.
194        // Priority: variant_pkgs > extra_lib_paths > self.lib_paths
195        // (ALC_PACKAGES_PATH + global default).
196        let mut effective = extra_lib_paths;
197        effective.extend(self.lib_paths.iter().cloned());
198
199        // Obtain the log-capture sink before moving `metrics` into BridgeConfig.
200        // The same Arc is shared with Session so snapshot() can read recent_logs.
201        let log_sink = metrics.log_sink_handle();
202
203        let bridge_config = bridge::BridgeConfig {
204            llm_tx: Some(llm_tx),
205            ns: spec.namespace.clone(),
206            custom_metrics: metrics.custom_metrics_handle(),
207            stats: metrics.stats_handle(),
208            budget: metrics.budget_handle(),
209            progress: metrics.progress_handle(),
210            lib_paths: effective.clone(), // fork child VMs inherit project paths
211            variant_pkgs: variant_pkgs.clone(), // fork child VMs inherit variant overrides
212            state_store,
213            card_store,
214            scenarios_dir,
215            log_sink: Some(log_sink.clone()),
216        };
217        let lua_ctx = spec.ctx.clone();
218        let lua_code = spec.code.clone();
219
220        // 1. Spawn a dedicated VM for this session.
221        let (session_isle, session_driver) = AsyncIsle::spawn(move |lua| {
222            let mut reg = Registry::new();
223            // Variant pkgs first so alc.local.toml overrides win over global.
224            register_variant_pkgs(&mut reg, &variant_pkgs);
225            for path in &effective {
226                if let Some(resolver) = make_resolver(path) {
227                    reg.add(resolver);
228                }
229            }
230            reg.install(lua)?;
231            Ok(())
232        })
233        .await
234        .map_err(|e| format!("Session VM spawn failed: {e}"))?;
235
236        // 2. Setup: register alc.* StdLib, set ctx, load prelude.
237        //    Safe to set globals — this VM is exclusively ours.
238        session_isle
239            .exec(move |lua| {
240                let alc_table = lua.create_table()?;
241                bridge::register(lua, &alc_table, bridge_config)?;
242                lua.globals().set("alc", alc_table)?;
243
244                let ctx_value = lua.to_value(&lua_ctx)?;
245                lua.globals().set("ctx", ctx_value)?;
246
247                lua.load(PRELUDE)
248                    .exec()
249                    .map_err(|e| IsleError::Lua(format!("Prelude load failed: {e}")))?;
250
251                // Note: `print()` redirect is handled by `bridge::register` via
252                // `data::register_print` when `BridgeConfig::log_sink` is Some.
253                // That implementation routes to both tracing (alc.lua.print) and
254                // the per-session LogSink ring buffer, keeping stdout clean for
255                // the rmcp JSON-RPC stdio transport.
256                //
257                // `io.write` is intentionally left unchanged — scripts that
258                // explicitly target stdout/stderr can still use it.
259
260                // No need to clear package.loaded — fresh VM.
261
262                Ok("ok".to_string())
263            })
264            .await
265            .map_err(|e| format!("Session setup failed: {e}"))?;
266
267        // 3. Execute user code as a coroutine on the session VM.
268        let wrapped_code = format!("return alc.json_encode((function()\n{lua_code}\nend)())");
269        let exec_task = session_isle.spawn_coroutine_eval(&wrapped_code);
270
271        // Handle no longer needed — all requests have been sent.
272        // The driver keeps the channel alive until the session completes.
273        drop(session_isle);
274
275        Ok(Session::new(llm_rx, exec_task, metrics, session_driver))
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282    use std::fs;
283
284    /// Create a temporary package directory with the given name and `init.lua` content.
285    fn make_pkg_dir(parent: &std::path::Path, pkg_name: &str, init_lua: &str) -> PathBuf {
286        let pkg_dir = parent.join(pkg_name);
287        fs::create_dir_all(&pkg_dir).unwrap();
288        fs::write(pkg_dir.join("init.lua"), init_lua).unwrap();
289        parent.to_path_buf()
290    }
291
292    /// `extra_lib_paths=vec![]` — eval_simple must work as before.
293    #[tokio::test]
294    async fn no_extra_lib_paths_eval_simple() {
295        let executor = Executor::new(vec![]).await.unwrap();
296        let result = executor.eval_simple("return 42".to_string()).await.unwrap();
297        assert_eq!(result, serde_json::json!(42));
298    }
299
300    /// `eval_simple_with_paths` with a project-local package.
301    ///
302    /// Creates a temp dir with `test_pkg/init.lua` returning `{value = 99}`,
303    /// then verifies `require("test_pkg").value` == 99 via the extra resolver.
304    #[tokio::test]
305    async fn extra_lib_paths_reachable_via_eval_simple_with_paths() {
306        let tmp = tempfile::tempdir().unwrap();
307        let pkg_root = make_pkg_dir(tmp.path(), "test_pkg", "return { value = 99 }");
308
309        let executor = Executor::new(vec![]).await.unwrap();
310        let code = r#"
311            local pkg = require("test_pkg")
312            return pkg.value
313        "#
314        .to_string();
315
316        let result = executor
317            .eval_simple_with_paths(code, vec![pkg_root], vec![])
318            .await
319            .unwrap();
320
321        assert_eq!(result, serde_json::json!(99));
322    }
323
324    /// Variant pkg with a non-matching directory name resolves via
325    /// `VariantRootResolver` + `PrefixResolver`.
326    #[tokio::test]
327    async fn variant_pkg_resolves_root_and_submodule() {
328        let tmp = tempfile::tempdir().unwrap();
329        // pkg dir name (`physical-dir`) intentionally differs from the
330        // require name (`logical_name`) — variant scope must support this.
331        let pkg_dir = tmp.path().join("physical-dir");
332        fs::create_dir_all(&pkg_dir).unwrap();
333        fs::write(
334            pkg_dir.join("init.lua"),
335            "return { greet = function(n) return 'hi-' .. n end, sub = require('logical_name.sub') }",
336        )
337        .unwrap();
338        fs::write(pkg_dir.join("sub.lua"), "return { value = 7 }").unwrap();
339
340        let executor = Executor::new(vec![]).await.unwrap();
341        let code = r#"
342            local pkg = require("logical_name")
343            return { msg = pkg.greet("there"), sub_value = pkg.sub.value }
344        "#
345        .to_string();
346
347        let result = executor
348            .eval_simple_with_paths(code, vec![], vec![VariantPkg::new("logical_name", pkg_dir)])
349            .await
350            .unwrap();
351
352        assert_eq!(result["msg"], serde_json::json!("hi-there"));
353        assert_eq!(result["sub_value"], serde_json::json!(7));
354    }
355
356    /// Variant pkg overrides a same-name global pkg (priority: variant > global).
357    #[tokio::test]
358    async fn variant_pkg_overrides_global_same_name() {
359        let global_tmp = tempfile::tempdir().unwrap();
360        let variant_tmp = tempfile::tempdir().unwrap();
361
362        // Global: my_pkg returns 1
363        make_pkg_dir(global_tmp.path(), "my_pkg", "return { value = 1 }");
364        // Variant: my_pkg returns 2 — must win
365        let variant_dir = variant_tmp.path().join("my_pkg");
366        fs::create_dir_all(&variant_dir).unwrap();
367        fs::write(variant_dir.join("init.lua"), "return { value = 2 }").unwrap();
368
369        let executor = Executor::new(vec![global_tmp.path().to_path_buf()])
370            .await
371            .unwrap();
372
373        let code = r#"
374            local pkg = require("my_pkg")
375            return pkg.value
376        "#
377        .to_string();
378
379        let result = executor
380            .eval_simple_with_paths(code, vec![], vec![VariantPkg::new("my_pkg", variant_dir)])
381            .await
382            .unwrap();
383
384        assert_eq!(result, serde_json::json!(2));
385    }
386
387    /// When `extra_lib_paths` has a pkg with the same name as one in global paths,
388    /// the extra one takes priority (it is prepended).
389    #[tokio::test]
390    async fn extra_lib_paths_priority_over_default() {
391        let global_tmp = tempfile::tempdir().unwrap();
392        let extra_tmp = tempfile::tempdir().unwrap();
393
394        // Global: test_pkg returns 1
395        make_pkg_dir(global_tmp.path(), "test_pkg", "return { value = 1 }");
396        // Extra (project-local): test_pkg returns 2
397        let extra_root = make_pkg_dir(extra_tmp.path(), "test_pkg", "return { value = 2 }");
398
399        // Executor has global as its lib_paths.
400        let executor = Executor::new(vec![global_tmp.path().to_path_buf()])
401            .await
402            .unwrap();
403
404        let code = r#"
405            local pkg = require("test_pkg")
406            return pkg.value
407        "#
408        .to_string();
409
410        let result = executor
411            .eval_simple_with_paths(code, vec![extra_root], vec![])
412            .await
413            .unwrap();
414
415        // extra (2) must win over global (1)
416        assert_eq!(result, serde_json::json!(2));
417    }
418}