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        Box::pin(run_watch(&config)).await
59    } else {
60        let output = Box::pin(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(Box::pin(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(Box::pin(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 = crate::compiler_for_source(&config.script, &script_source)
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                    environment_policy: Default::default(),
236                    grants: Vec::new(),
237                },
238            ));
239            let execution_result = match vm.execute(&chunk).await {
240                Ok(_) => Ok(vm.output().to_string()),
241                Err(error) => Err(vm.format_runtime_error(&error)),
242            };
243            harn_vm::llm::clear_current_host_bridge();
244            harn_vm::stdlib::process::set_thread_execution_context(None);
245            persist_cli_llm_mock_recording(&config.llm_mock_mode)
246                .map_err(|error| format!("error: {error}\n"))?;
247            execution_result
248        })
249        .await;
250    // A playground invocation is a complete VM run. Clear runtime-owned
251    // thread-local state before a watch-mode rerun or the next in-process
252    // invocation can inherit mocks, policies, event sinks, or other ambient
253    // state from this run.
254    harn_vm::reset_thread_local_state();
255    drop(env_guard);
256    result
257}
258
259async fn configured_vm(
260    path: &Path,
261    source: &str,
262    project_root: Option<&Path>,
263    store_base: &Path,
264) -> Result<harn_vm::Vm, String> {
265    let mut vm = harn_vm::Vm::new();
266    harn_vm::register_vm_stdlib(&mut vm);
267    crate::install_default_hostlib(&mut vm);
268    harn_vm::register_store_builtins(&mut vm, store_base);
269    harn_vm::register_metadata_builtins(&mut vm, store_base);
270    let pipeline_name = path
271        .file_stem()
272        .and_then(|stem| stem.to_str())
273        .unwrap_or("default");
274    harn_vm::register_checkpoint_builtins(&mut vm, store_base, pipeline_name);
275    vm.set_source_info(&path.to_string_lossy(), source);
276    if let Some(root) = project_root {
277        vm.set_project_root(root);
278    }
279    if let Some(parent) = path.parent() {
280        if !parent.as_os_str().is_empty() {
281            vm.set_source_dir(parent);
282        }
283    }
284    vm.set_global(
285        "argv",
286        harn_vm::VmValue::List(std::sync::Arc::new(Vec::new())),
287    );
288    vm.set_harness(harn_vm::Harness::real());
289
290    let loaded = load_skills(&SkillLoaderInputs {
291        cli_dirs: Vec::new(),
292        source_path: Some(path.to_path_buf()),
293    });
294    emit_loader_warnings(&loaded.loader_warnings);
295    install_skills_global(&mut vm, &loaded);
296
297    let extensions = package::load_runtime_extensions(path);
298    package::install_runtime_extensions(&extensions);
299    if let Some(manifest) = extensions.root_manifest.as_ref() {
300        if !manifest.mcp.is_empty() {
301            connect_mcp_servers(&manifest.mcp, &mut vm).await;
302        }
303    }
304    package::install_manifest_triggers(&mut vm, &extensions)
305        .await
306        .map_err(|error| format!("failed to install manifest triggers: {error}"))?;
307
308    Ok(vm)
309}
310
311fn typecheck_program(
312    source: &str,
313    program: &[SNode],
314    path: &Path,
315    extra_names: &HashSet<String>,
316) -> Result<(), String> {
317    let graph = harn_modules::build(&[path.to_path_buf()]);
318    let mut checker = TypeChecker::new();
319    let mut imported = graph.imported_names_for_file(path).unwrap_or_default();
320    imported.extend(extra_names.iter().cloned());
321    if !imported.is_empty() {
322        checker = checker.with_imported_names(imported);
323    }
324    if let Some(imported) = graph.imported_type_declarations_for_file(path) {
325        checker = checker.with_imported_type_decls(imported);
326    }
327    if let Some(imported) = graph.imported_callable_declarations_for_file(path) {
328        checker = checker.with_imported_callable_decls(imported);
329    }
330
331    let diagnostics = checker.check(program);
332    let mut rendered = String::new();
333    let mut had_error = false;
334    for diagnostic in &diagnostics {
335        if diagnostic.severity == DiagnosticSeverity::Error {
336            had_error = true;
337        }
338        rendered.push_str(&harn_parser::diagnostic::render_type_diagnostic(
339            source,
340            &path.to_string_lossy(),
341            diagnostic,
342        ));
343    }
344
345    if had_error {
346        return Err(rendered);
347    }
348    if !rendered.is_empty() {
349        eprint!("{rendered}");
350    }
351    Ok(())
352}
353
354fn exported_host_functions(program: &[SNode]) -> HashSet<String> {
355    let mut public_names = HashSet::new();
356    let mut all_names = HashSet::new();
357    let mut has_pub_fn = false;
358
359    for node in program {
360        let inner = match &node.node {
361            Node::AttributedDecl { inner, .. } => inner.as_ref(),
362            _ => node,
363        };
364        let Node::FnDecl { name, is_pub, .. } = &inner.node else {
365            continue;
366        };
367        all_names.insert(name.clone());
368        if *is_pub {
369            has_pub_fn = true;
370            public_names.insert(name.clone());
371        }
372    }
373
374    if has_pub_fn {
375        public_names
376    } else {
377        all_names
378    }
379}
380
381fn watch_roots(host: &Path, script: &Path) -> Vec<PathBuf> {
382    let mut roots = Vec::new();
383    for candidate in [
384        host.parent().unwrap_or_else(|| Path::new(".")),
385        script.parent().unwrap_or_else(|| Path::new(".")),
386    ] {
387        if !roots.iter().any(|existing| existing == candidate) {
388            roots.push(candidate.to_path_buf());
389        }
390    }
391    roots
392}
393
394fn parse_llm_override(raw: &str) -> Result<LlmOverride, String> {
395    let (provider, model) = raw
396        .split_once(':')
397        .ok_or_else(|| "playground --llm expects provider:model".to_string())?;
398    let provider = provider.trim();
399    let model = model.trim();
400    if provider.is_empty() || model.is_empty() {
401        return Err("playground --llm expects provider:model".to_string());
402    }
403    Ok(LlmOverride {
404        provider: provider.to_string(),
405        model: model.to_string(),
406    })
407}
408
409fn canonicalize_or_err(path: &str) -> Result<PathBuf, String> {
410    std::fs::canonicalize(path).map_err(|error| format!("failed to resolve {path}: {error}"))
411}
412
413struct ScopedEnv {
414    previous: Vec<(String, Option<String>)>,
415}
416
417impl ScopedEnv {
418    fn apply(config: &PlaygroundConfig) -> Self {
419        let mut previous = Vec::new();
420        Self::set("HARN_TASK", Some(config.task.as_str()), &mut previous);
421        if let Some(llm) = &config.llm {
422            Self::set(
423                "HARN_LLM_PROVIDER",
424                Some(llm.provider.as_str()),
425                &mut previous,
426            );
427            Self::set("HARN_LLM_MODEL", Some(llm.model.as_str()), &mut previous);
428        }
429        Self { previous }
430    }
431
432    fn set(key: &str, value: Option<&str>, previous: &mut Vec<(String, Option<String>)>) {
433        previous.push((key.to_string(), std::env::var(key).ok()));
434        match value {
435            Some(value) => std::env::set_var(key, value),
436            None => std::env::remove_var(key),
437        }
438    }
439}
440
441impl Drop for ScopedEnv {
442    fn drop(&mut self) {
443        for (key, previous) in self.previous.iter().rev() {
444            match previous {
445                Some(value) => std::env::set_var(key, value),
446                None => std::env::remove_var(key),
447            }
448        }
449    }
450}
451
452#[cfg(test)]
453mod tests {
454    use super::*;
455
456    fn write_file(path: &Path, contents: &str) {
457        if let Some(parent) = path.parent() {
458            std::fs::create_dir_all(parent).unwrap();
459        }
460        std::fs::write(path, contents).unwrap();
461    }
462
463    #[test]
464    fn exported_host_functions_prefers_pub_names() {
465        let temp = tempfile::tempdir().unwrap();
466        let path = temp.path().join("host_pub.harn");
467        let source = r"
468fn helper() {}
469pub fn run_shell(command) { return command }
470pub fn request_permission(tool_name, request_args) { return true }
471";
472        write_file(&path, source);
473        let (_, program) = crate::parse_source_file(path.to_string_lossy().as_ref());
474        let names = exported_host_functions(&program);
475        assert!(names.contains("run_shell"));
476        assert!(names.contains("request_permission"));
477        assert!(!names.contains("helper"));
478    }
479
480    #[test]
481    fn parse_llm_override_splits_provider_and_model() {
482        let parsed = parse_llm_override("ollama:qwen2.5-coder:latest").unwrap();
483        assert_eq!(parsed.provider, "ollama");
484        assert_eq!(parsed.model, "qwen2.5-coder:latest");
485    }
486
487    #[tokio::test(flavor = "current_thread")]
488    async fn playground_executes_host_backed_script() {
489        let _env_guard = crate::tests::common::harn_state_lock::lock_harn_state_async().await;
490        let temp = tempfile::tempdir().unwrap();
491        let host = temp.path().join("host.harn");
492        let script = temp.path().join("pipeline.harn");
493        write_file(
494            &host,
495            r#"
496pub fn build_prompt(task) {
497  return "prompt: " + task
498}
499"#,
500        );
501        write_file(
502            &script,
503            r#"
504pipeline default(harness: Harness, task) {
505  harness.llm.mock_enqueue({text: "done"})
506  const result = harness.llm.call(
507    build_prompt(harness.env.get_or("HARN_TASK", "")),
508    "You are concise.",
509  )
510  harness.llm.mock_enqueue({text: "stale if the run is not reset"})
511  harness.stdio.println(result.text)
512}
513"#,
514        );
515
516        let output = execute_playground(&PlaygroundConfig {
517            host: host.clone(),
518            script: script.clone(),
519            task: "ship it".to_string(),
520            llm: Some(LlmOverride {
521                provider: "mock".to_string(),
522                model: "mock".to_string(),
523            }),
524            llm_mock_mode: CliLlmMockMode::Off,
525        })
526        .await
527        .unwrap();
528
529        assert!(output.contains("done"));
530
531        write_file(
532            &script,
533            r"
534pipeline default(harness: Harness, task) {
535  const snapshot = harness.llm.mock_snapshot()
536  harness.stdio.println(len(keys(snapshot.queue_remaining)))
537}
538",
539        );
540        let next_output = execute_playground(&PlaygroundConfig {
541            host,
542            script,
543            task: "ship it again".to_string(),
544            llm: None,
545            llm_mock_mode: CliLlmMockMode::Off,
546        })
547        .await
548        .unwrap();
549        assert_eq!(next_output.trim(), "0");
550    }
551
552    #[tokio::test(flavor = "current_thread")]
553    async fn playground_reports_missing_capability_with_caller_context() {
554        let _env_guard = crate::tests::common::harn_state_lock::lock_harn_state_async().await;
555        let temp = tempfile::tempdir().unwrap();
556        let host = temp.path().join("host.harn");
557        let script = temp.path().join("pipeline.harn");
558        write_file(
559            &host,
560            r#"
561pub fn helper() {
562  return "ok"
563}
564"#,
565        );
566        write_file(
567            &script,
568            r#"
569pipeline default(task) {
570  run_shell("pwd")
571}
572"#,
573        );
574
575        let error = execute_playground(&PlaygroundConfig {
576            host,
577            script,
578            task: String::new(),
579            llm: None,
580            llm_mock_mode: CliLlmMockMode::Off,
581        })
582        .await
583        .unwrap_err();
584
585        assert!(error.contains("run_shell"));
586        assert!(error.contains("pipeline.harn:3:3"));
587    }
588
589    #[tokio::test(flavor = "current_thread")]
590    async fn playground_replays_cli_llm_mock_fixtures() {
591        let _env_guard = crate::tests::common::harn_state_lock::lock_harn_state_async().await;
592        let temp = tempfile::tempdir().unwrap();
593        let host = temp.path().join("host.harn");
594        let script = temp.path().join("pipeline.harn");
595        let fixtures = temp.path().join("fixtures.jsonl");
596        write_file(
597            &host,
598            r#"
599pub fn build_prompt(task) {
600  return "prompt: " + task
601}
602"#,
603        );
604        write_file(
605            &script,
606            r#"
607pipeline default(harness: Harness, task) {
608  const result = harness.llm.call(
609    build_prompt(harness.env.get_or("HARN_TASK", "")),
610    "You are concise.",
611  )
612  harness.stdio.println(result.text)
613}
614"#,
615        );
616        write_file(
617            &fixtures,
618            r#"{"text":"fixture replay","model":"fixture-model"}
619"#,
620        );
621
622        let output = execute_playground(&PlaygroundConfig {
623            host,
624            script,
625            task: "ship it".to_string(),
626            llm: Some(LlmOverride {
627                provider: "anthropic".to_string(),
628                model: "claude-sonnet".to_string(),
629            }),
630            llm_mock_mode: CliLlmMockMode::Replay {
631                fixture_path: fixtures,
632            },
633        })
634        .await
635        .unwrap();
636
637        assert!(output.contains("fixture replay"));
638    }
639
640    #[tokio::test(flavor = "current_thread")]
641    async fn playground_replays_cli_llm_mock_error_envelopes() {
642        let _env_guard = crate::tests::common::harn_state_lock::lock_harn_state_async().await;
643        let temp = tempfile::tempdir().unwrap();
644        let host = temp.path().join("host.harn");
645        let script = temp.path().join("pipeline.harn");
646        let fixtures = temp.path().join("fixtures.jsonl");
647        write_file(&host, "");
648        write_file(
649            &script,
650            r#"
651pipeline default(harness: Harness, task) {
652  const first = harness.llm.call_safe("first", nil, {provider: "mock", model: "mock-model"})
653  harness.stdio.println(first.ok)
654  harness.stdio.println(first.error.status)
655  harness.stdio.println(first.error.kind)
656  harness.stdio.println(first.error.reason)
657  const second = harness.llm.call("second", nil, {provider: "mock", model: "mock-model"})
658  harness.stdio.println(second.text)
659}
660"#,
661        );
662        write_file(
663            &fixtures,
664            r#"{"error":{"status":503,"kind":"transient","reason":"upstream_unavailable"}}
665{"text":"recovered","tool_calls":[]}
666"#,
667        );
668
669        let output = execute_playground(&PlaygroundConfig {
670            host,
671            script,
672            task: String::new(),
673            llm: None,
674            llm_mock_mode: CliLlmMockMode::Replay {
675                fixture_path: fixtures,
676            },
677        })
678        .await
679        .unwrap();
680
681        assert!(output.contains("false\n503\ntransient\nupstream_unavailable\nrecovered"));
682    }
683}