Skip to main content

harn_cli/commands/
playground.rs

1use std::collections::HashSet;
2use std::io::{self, Write};
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5
6use harn_parser::{DiagnosticSeverity, Node, SNode, TypeChecker};
7
8use crate::cli::PlaygroundArgs;
9use crate::commands::run::{
10    connect_mcp_servers, install_cli_llm_mock_mode, persist_cli_llm_mock_recording, CliLlmMockMode,
11};
12use crate::package;
13use crate::skill_loader::{
14    emit_loader_warnings, install_skills_global, load_skills, SkillLoaderInputs,
15};
16
17#[derive(Clone, Debug, PartialEq, Eq)]
18struct LlmOverride {
19    provider: String,
20    model: String,
21}
22
23/// Inputs to `execute_playground_inputs` — the in-process sibling of
24/// `harn playground`. Tests construct this directly instead of going through
25/// clap. The binary entry (`run_command`) builds this from `PlaygroundArgs`.
26#[derive(Clone, Debug)]
27pub struct PlaygroundInputs {
28    pub host: PathBuf,
29    pub script: PathBuf,
30    pub task: String,
31    /// Optional `provider:model` override, in the same format `--llm` accepts.
32    pub llm: Option<String>,
33    pub llm_mock_mode: CliLlmMockMode,
34}
35
36#[derive(Clone, Debug)]
37struct PlaygroundConfig {
38    host: PathBuf,
39    script: PathBuf,
40    task: String,
41    llm: Option<LlmOverride>,
42    llm_mock_mode: CliLlmMockMode,
43}
44
45pub(crate) async fn run_command(
46    args: PlaygroundArgs,
47    llm_mock_mode: CliLlmMockMode,
48) -> Result<(), String> {
49    let config = PlaygroundConfig {
50        host: canonicalize_or_err(&args.host)?,
51        script: canonicalize_or_err(&args.script)?,
52        task: args.task.unwrap_or_default(),
53        llm: args.llm.as_deref().map(parse_llm_override).transpose()?,
54        llm_mock_mode,
55    };
56
57    if args.watch {
58        run_watch(&config).await
59    } else {
60        let output = execute_playground(&config).await?;
61        if !output.is_empty() {
62            io::stdout()
63                .write_all(output.as_bytes())
64                .map_err(|error| format!("failed to write playground output: {error}"))?;
65        }
66        Ok(())
67    }
68}
69
70/// In-process entry point for `harn playground`. Returns the captured stdout
71/// the CLI dispatcher would have printed, or a rendered error string.
72///
73/// This is the path tests use to exercise the playground driver without
74/// spawning the `harn` binary. Watch mode is not supported here — it has no
75/// terminal output contract worth asserting on.
76pub async fn execute_playground_inputs(inputs: PlaygroundInputs) -> Result<String, String> {
77    let llm = inputs.llm.as_deref().map(parse_llm_override).transpose()?;
78    let config = PlaygroundConfig {
79        host: canonicalize_or_err(inputs.host.to_string_lossy().as_ref())?,
80        script: canonicalize_or_err(inputs.script.to_string_lossy().as_ref())?,
81        task: inputs.task,
82        llm,
83        llm_mock_mode: inputs.llm_mock_mode,
84    };
85    execute_playground(&config).await
86}
87
88async fn run_watch(config: &PlaygroundConfig) -> Result<(), String> {
89    use notify::{Event, EventKind, RecursiveMode, Watcher};
90
91    eprintln!(
92        "\x1b[2m[playground] running {} with host {}...\x1b[0m",
93        config.script.display(),
94        config.host.display()
95    );
96    emit_run_result(execute_playground(config).await);
97
98    let roots = watch_roots(&config.host, &config.script);
99    let (tx, mut rx) = tokio::sync::mpsc::channel::<()>(1);
100    let _watcher = {
101        let tx = tx.clone();
102        let mut watcher = notify::recommended_watcher(move |res: Result<Event, _>| {
103            if let Ok(event) = res {
104                if matches!(
105                    event.kind,
106                    EventKind::Modify(_) | EventKind::Create(_) | EventKind::Remove(_)
107                ) {
108                    let has_harn = event
109                        .paths
110                        .iter()
111                        .any(|path| path.extension().is_some_and(|ext| ext == "harn"));
112                    if has_harn {
113                        let _ = tx.blocking_send(());
114                    }
115                }
116            }
117        })
118        .map_err(|error| format!("failed to create playground watcher: {error}"))?;
119
120        for root in &roots {
121            watcher
122                .watch(root, RecursiveMode::Recursive)
123                .map_err(|error| format!("failed to watch {}: {error}", root.display()))?;
124        }
125        watcher
126    };
127
128    eprintln!(
129        "\x1b[2m[playground] watching {} (ctrl-c to stop)\x1b[0m",
130        roots
131            .iter()
132            .map(|path| path.display().to_string())
133            .collect::<Vec<_>>()
134            .join(", ")
135    );
136
137    loop {
138        rx.recv().await;
139        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
140        while rx.try_recv().is_ok() {}
141
142        eprintln!();
143        eprintln!(
144            "\x1b[2m[playground] change detected, re-running {}...\x1b[0m",
145            config.script.display()
146        );
147        emit_run_result(execute_playground(config).await);
148    }
149}
150
151fn emit_run_result(result: Result<String, String>) {
152    match result {
153        Ok(output) => {
154            if !output.is_empty() {
155                let _ = io::stdout().write_all(output.as_bytes());
156            }
157        }
158        Err(error) => eprint!("{error}"),
159    }
160}
161
162async fn execute_playground(config: &PlaygroundConfig) -> Result<String, String> {
163    let (host_source, host_program) = crate::parse_source_file(&config.host.to_string_lossy());
164    typecheck_program(&host_source, &host_program, &config.host, &HashSet::new())?;
165    let host_exports = exported_host_functions(&host_program);
166
167    let (script_source, script_program) =
168        crate::parse_source_file(&config.script.to_string_lossy());
169    typecheck_program(
170        &script_source,
171        &script_program,
172        &config.script,
173        &host_exports,
174    )?;
175
176    let chunk = harn_vm::Compiler::new()
177        .compile(&script_program)
178        .map_err(|error| format!("error: compile error: {error}\n"))?;
179
180    let env_guard = ScopedEnv::apply(config);
181    let source_parent = config
182        .script
183        .parent()
184        .unwrap_or_else(|| Path::new("."))
185        .to_path_buf();
186    let project_root = harn_vm::stdlib::process::find_project_root(&source_parent);
187    let store_base = project_root.as_deref().unwrap_or(source_parent.as_path());
188    let execution_cwd = std::env::current_dir()
189        .unwrap_or_else(|_| PathBuf::from("."))
190        .to_string_lossy()
191        .into_owned();
192    let source_dir = source_parent.to_string_lossy().into_owned();
193
194    let local = tokio::task::LocalSet::new();
195    let result = local
196        .run_until(async {
197            install_cli_llm_mock_mode(&config.llm_mock_mode)
198                .map_err(|error| format!("error: {error}\n"))?;
199            let host_vm = configured_vm(
200                &config.host,
201                &host_source,
202                project_root.as_deref(),
203                store_base,
204            )
205            .await?;
206            let bridge = Arc::new(
207                harn_vm::bridge::HostBridge::from_harn_module(host_vm, &config.host)
208                    .await
209                    .map_err(|error| format!("error: {error}\n"))?,
210            );
211
212            let mut vm = configured_vm(
213                &config.script,
214                &script_source,
215                project_root.as_deref(),
216                store_base,
217            )
218            .await?;
219            vm.set_bridge(bridge.clone());
220            harn_vm::llm::install_current_host_bridge(bridge.clone());
221            harn_vm::stdlib::process::set_thread_execution_context(Some(
222                harn_vm::orchestration::RunExecutionRecord {
223                    cwd: Some(execution_cwd),
224                    project_root: project_root
225                        .as_ref()
226                        .map(|root| root.to_string_lossy().into_owned()),
227                    source_dir: Some(source_dir),
228                    env: std::collections::BTreeMap::new(),
229                    adapter: None,
230                    repo_path: None,
231                    worktree_path: None,
232                    branch: None,
233                    base_ref: None,
234                    cleanup: None,
235                    grants: Vec::new(),
236                },
237            ));
238            let execution_result = match vm.execute(&chunk).await {
239                Ok(_) => Ok(vm.output().to_string()),
240                Err(error) => Err(vm.format_runtime_error(&error)),
241            };
242            harn_vm::llm::clear_current_host_bridge();
243            harn_vm::stdlib::process::set_thread_execution_context(None);
244            persist_cli_llm_mock_recording(&config.llm_mock_mode)
245                .map_err(|error| format!("error: {error}\n"))?;
246            execution_result
247        })
248        .await;
249    drop(env_guard);
250    result
251}
252
253async fn configured_vm(
254    path: &Path,
255    source: &str,
256    project_root: Option<&Path>,
257    store_base: &Path,
258) -> Result<harn_vm::Vm, String> {
259    let mut vm = harn_vm::Vm::new();
260    harn_vm::register_vm_stdlib(&mut vm);
261    crate::install_default_hostlib(&mut vm);
262    harn_vm::register_store_builtins(&mut vm, store_base);
263    harn_vm::register_metadata_builtins(&mut vm, store_base);
264    let pipeline_name = path
265        .file_stem()
266        .and_then(|stem| stem.to_str())
267        .unwrap_or("default");
268    harn_vm::register_checkpoint_builtins(&mut vm, store_base, pipeline_name);
269    vm.set_source_info(&path.to_string_lossy(), source);
270    if let Some(root) = project_root {
271        vm.set_project_root(root);
272    }
273    if let Some(parent) = path.parent() {
274        if !parent.as_os_str().is_empty() {
275            vm.set_source_dir(parent);
276        }
277    }
278    vm.set_global(
279        "argv",
280        harn_vm::VmValue::List(std::sync::Arc::new(Vec::new())),
281    );
282    vm.set_harness(harn_vm::Harness::real());
283
284    let loaded = load_skills(&SkillLoaderInputs {
285        cli_dirs: Vec::new(),
286        source_path: Some(path.to_path_buf()),
287    });
288    emit_loader_warnings(&loaded.loader_warnings);
289    install_skills_global(&mut vm, &loaded);
290
291    let extensions = package::load_runtime_extensions(path);
292    package::install_runtime_extensions(&extensions);
293    if let Some(manifest) = extensions.root_manifest.as_ref() {
294        if !manifest.mcp.is_empty() {
295            connect_mcp_servers(&manifest.mcp, &mut vm).await;
296        }
297    }
298    package::install_manifest_triggers(&mut vm, &extensions)
299        .await
300        .map_err(|error| format!("failed to install manifest triggers: {error}"))?;
301
302    Ok(vm)
303}
304
305fn typecheck_program(
306    source: &str,
307    program: &[SNode],
308    path: &Path,
309    extra_names: &HashSet<String>,
310) -> Result<(), String> {
311    let graph = harn_modules::build(&[path.to_path_buf()]);
312    let mut checker = TypeChecker::new();
313    let mut imported = graph.imported_names_for_file(path).unwrap_or_default();
314    imported.extend(extra_names.iter().cloned());
315    if !imported.is_empty() {
316        checker = checker.with_imported_names(imported);
317    }
318    if let Some(imported) = graph.imported_type_declarations_for_file(path) {
319        checker = checker.with_imported_type_decls(imported);
320    }
321    if let Some(imported) = graph.imported_callable_declarations_for_file(path) {
322        checker = checker.with_imported_callable_decls(imported);
323    }
324
325    let diagnostics = checker.check(program);
326    let mut rendered = String::new();
327    let mut had_error = false;
328    for diagnostic in &diagnostics {
329        if diagnostic.severity == DiagnosticSeverity::Error {
330            had_error = true;
331        }
332        rendered.push_str(&harn_parser::diagnostic::render_type_diagnostic(
333            source,
334            &path.to_string_lossy(),
335            diagnostic,
336        ));
337    }
338
339    if had_error {
340        return Err(rendered);
341    }
342    if !rendered.is_empty() {
343        eprint!("{rendered}");
344    }
345    Ok(())
346}
347
348fn exported_host_functions(program: &[SNode]) -> HashSet<String> {
349    let mut public_names = HashSet::new();
350    let mut all_names = HashSet::new();
351    let mut has_pub_fn = false;
352
353    for node in program {
354        let inner = match &node.node {
355            Node::AttributedDecl { inner, .. } => inner.as_ref(),
356            _ => node,
357        };
358        let Node::FnDecl { name, is_pub, .. } = &inner.node else {
359            continue;
360        };
361        all_names.insert(name.clone());
362        if *is_pub {
363            has_pub_fn = true;
364            public_names.insert(name.clone());
365        }
366    }
367
368    if has_pub_fn {
369        public_names
370    } else {
371        all_names
372    }
373}
374
375fn watch_roots(host: &Path, script: &Path) -> Vec<PathBuf> {
376    let mut roots = Vec::new();
377    for candidate in [
378        host.parent().unwrap_or_else(|| Path::new(".")),
379        script.parent().unwrap_or_else(|| Path::new(".")),
380    ] {
381        if !roots.iter().any(|existing| existing == candidate) {
382            roots.push(candidate.to_path_buf());
383        }
384    }
385    roots
386}
387
388fn parse_llm_override(raw: &str) -> Result<LlmOverride, String> {
389    let (provider, model) = raw
390        .split_once(':')
391        .ok_or_else(|| "playground --llm expects provider:model".to_string())?;
392    let provider = provider.trim();
393    let model = model.trim();
394    if provider.is_empty() || model.is_empty() {
395        return Err("playground --llm expects provider:model".to_string());
396    }
397    Ok(LlmOverride {
398        provider: provider.to_string(),
399        model: model.to_string(),
400    })
401}
402
403fn canonicalize_or_err(path: &str) -> Result<PathBuf, String> {
404    std::fs::canonicalize(path).map_err(|error| format!("failed to resolve {path}: {error}"))
405}
406
407struct ScopedEnv {
408    previous: Vec<(String, Option<String>)>,
409}
410
411impl ScopedEnv {
412    fn apply(config: &PlaygroundConfig) -> Self {
413        let mut previous = Vec::new();
414        Self::set("HARN_TASK", Some(config.task.as_str()), &mut previous);
415        if let Some(llm) = &config.llm {
416            Self::set(
417                "HARN_LLM_PROVIDER",
418                Some(llm.provider.as_str()),
419                &mut previous,
420            );
421            Self::set("HARN_LLM_MODEL", Some(llm.model.as_str()), &mut previous);
422        }
423        Self { previous }
424    }
425
426    fn set(key: &str, value: Option<&str>, previous: &mut Vec<(String, Option<String>)>) {
427        previous.push((key.to_string(), std::env::var(key).ok()));
428        match value {
429            Some(value) => std::env::set_var(key, value),
430            None => std::env::remove_var(key),
431        }
432    }
433}
434
435impl Drop for ScopedEnv {
436    fn drop(&mut self) {
437        for (key, previous) in self.previous.iter().rev() {
438            match previous {
439                Some(value) => std::env::set_var(key, value),
440                None => std::env::remove_var(key),
441            }
442        }
443    }
444}
445
446#[cfg(test)]
447mod tests {
448    use super::*;
449
450    fn write_file(path: &Path, contents: &str) {
451        if let Some(parent) = path.parent() {
452            std::fs::create_dir_all(parent).unwrap();
453        }
454        std::fs::write(path, contents).unwrap();
455    }
456
457    #[test]
458    fn exported_host_functions_prefers_pub_names() {
459        let temp = tempfile::tempdir().unwrap();
460        let path = temp.path().join("host_pub.harn");
461        let source = r"
462fn helper() {}
463pub fn run_shell(command) { return command }
464pub fn request_permission(tool_name, request_args) { return true }
465";
466        write_file(&path, source);
467        let (_, program) = crate::parse_source_file(path.to_string_lossy().as_ref());
468        let names = exported_host_functions(&program);
469        assert!(names.contains("run_shell"));
470        assert!(names.contains("request_permission"));
471        assert!(!names.contains("helper"));
472    }
473
474    #[test]
475    fn parse_llm_override_splits_provider_and_model() {
476        let parsed = parse_llm_override("ollama:qwen2.5-coder:latest").unwrap();
477        assert_eq!(parsed.provider, "ollama");
478        assert_eq!(parsed.model, "qwen2.5-coder:latest");
479    }
480
481    #[tokio::test(flavor = "current_thread")]
482    async fn playground_executes_host_backed_script() {
483        let _guard = crate::tests::common::env_lock::lock_env().lock().await;
484        let temp = tempfile::tempdir().unwrap();
485        let host = temp.path().join("host.harn");
486        let script = temp.path().join("pipeline.harn");
487        write_file(
488            &host,
489            r#"
490pub fn build_prompt(task) {
491  return "prompt: " + task
492}
493"#,
494        );
495        write_file(
496            &script,
497            r#"
498pipeline default(task) {
499  llm_mock({text: "done"})
500  const result = llm_call(build_prompt(env_or("HARN_TASK", "")), "You are concise.")
501  __io_println(result.text)
502}
503"#,
504        );
505
506        let output = execute_playground(&PlaygroundConfig {
507            host,
508            script,
509            task: "ship it".to_string(),
510            llm: Some(LlmOverride {
511                provider: "mock".to_string(),
512                model: "mock".to_string(),
513            }),
514            llm_mock_mode: CliLlmMockMode::Off,
515        })
516        .await
517        .unwrap();
518
519        assert!(output.contains("done"));
520    }
521
522    #[tokio::test(flavor = "current_thread")]
523    async fn playground_reports_missing_capability_with_caller_context() {
524        let _guard = crate::tests::common::env_lock::lock_env().lock().await;
525        let temp = tempfile::tempdir().unwrap();
526        let host = temp.path().join("host.harn");
527        let script = temp.path().join("pipeline.harn");
528        write_file(
529            &host,
530            r#"
531pub fn helper() {
532  return "ok"
533}
534"#,
535        );
536        write_file(
537            &script,
538            r#"
539pipeline default(task) {
540  run_shell("pwd")
541}
542"#,
543        );
544
545        let error = execute_playground(&PlaygroundConfig {
546            host,
547            script,
548            task: String::new(),
549            llm: None,
550            llm_mock_mode: CliLlmMockMode::Off,
551        })
552        .await
553        .unwrap_err();
554
555        assert!(error.contains("run_shell"));
556        assert!(error.contains("pipeline.harn:3:3"));
557    }
558
559    #[tokio::test(flavor = "current_thread")]
560    async fn playground_replays_cli_llm_mock_fixtures() {
561        let _guard = crate::tests::common::env_lock::lock_env().lock().await;
562        let temp = tempfile::tempdir().unwrap();
563        let host = temp.path().join("host.harn");
564        let script = temp.path().join("pipeline.harn");
565        let fixtures = temp.path().join("fixtures.jsonl");
566        write_file(
567            &host,
568            r#"
569pub fn build_prompt(task) {
570  return "prompt: " + task
571}
572"#,
573        );
574        write_file(
575            &script,
576            r#"
577pipeline default(task) {
578  const result = llm_call(build_prompt(env_or("HARN_TASK", "")), "You are concise.")
579  __io_println(result.text)
580}
581"#,
582        );
583        write_file(
584            &fixtures,
585            r#"{"text":"fixture replay","model":"fixture-model"}
586"#,
587        );
588
589        let output = execute_playground(&PlaygroundConfig {
590            host,
591            script,
592            task: "ship it".to_string(),
593            llm: Some(LlmOverride {
594                provider: "anthropic".to_string(),
595                model: "claude-sonnet".to_string(),
596            }),
597            llm_mock_mode: CliLlmMockMode::Replay {
598                fixture_path: fixtures,
599            },
600        })
601        .await
602        .unwrap();
603
604        assert!(output.contains("fixture replay"));
605    }
606
607    #[tokio::test(flavor = "current_thread")]
608    async fn playground_replays_cli_llm_mock_error_envelopes() {
609        let _guard = crate::tests::common::env_lock::lock_env().lock().await;
610        let temp = tempfile::tempdir().unwrap();
611        let host = temp.path().join("host.harn");
612        let script = temp.path().join("pipeline.harn");
613        let fixtures = temp.path().join("fixtures.jsonl");
614        write_file(&host, "");
615        write_file(
616            &script,
617            r#"
618pipeline default(task) {
619  const first = llm_call_safe("first", nil, {provider: "mock", model: "mock-model"})
620  __io_println(first.ok)
621  __io_println(first.error.status)
622  __io_println(first.error.kind)
623  __io_println(first.error.reason)
624  const second = llm_call("second", nil, {provider: "mock", model: "mock-model"})
625  __io_println(second.text)
626}
627"#,
628        );
629        write_file(
630            &fixtures,
631            r#"{"error":{"status":503,"kind":"transient","reason":"upstream_unavailable"}}
632{"text":"recovered","tool_calls":[]}
633"#,
634        );
635
636        let output = execute_playground(&PlaygroundConfig {
637            host,
638            script,
639            task: String::new(),
640            llm: None,
641            llm_mock_mode: CliLlmMockMode::Replay {
642                fixture_path: fixtures,
643            },
644        })
645        .await
646        .unwrap();
647
648        assert!(output.contains("false\n503\ntransient\nupstream_unavailable\nrecovered"));
649    }
650}