Skip to main content

harn_vm/
stdlib.rs

1//! Standard library builtins for the Harn VM.
2//!
3//! Every builtin is declared with the `#[harn_builtin]` proc-macro
4//! (`crate::stdlib::macros::harn_builtin`). Each annotation emits a sibling
5//! `static <FN>_DEF: VmBuiltinDef` carrying the signature, aliases, handler,
6//! and metadata, and registers it into the workspace-global
7//! [`macros::ALL_BUILTIN_DEFS`] distributed slice at link time. The CLI / LSP /
8//! lint / serve / dap binaries call [`force_link`] to defeat rlib dead-code
9//! stripping (linkme issue #36) so every static lands in the slice. Modules
10//! still expose a `register_<module>_builtins(vm)` helper for ordered eager
11//! registration (e.g. so `clock::timestamp` can override `process::timestamp`).
12//! `register_vm_stdlib` calls those helpers in order and then installs the
13//! aggregated signatures into the parser registry.
14//!
15//! See `CONTRIBUTING.md` ("Adding a stdlib builtin") for the full template.
16
17pub mod macros;
18
19mod agent_sessions;
20pub mod agent_state;
21pub(crate) mod agents;
22mod agents_daemon;
23mod artifact_emit;
24pub(crate) mod assemble;
25pub mod asset_paths;
26mod bytes;
27mod calendar;
28mod channel_guardrails;
29mod channels;
30pub(crate) mod clock;
31pub(crate) mod collections;
32mod command_policy;
33pub(crate) mod compaction;
34mod compression;
35mod concurrency;
36pub(crate) use concurrency::cancelled_vm_error;
37mod connectors;
38mod cookies;
39mod cron;
40mod crypto;
41mod csv;
42mod datetime;
43pub(crate) use datetime::date_dict_from_millis;
44mod document;
45mod durable_step;
46mod event_log;
47mod external_agent;
48pub(crate) mod files;
49mod flow;
50pub(crate) mod fs;
51mod git;
52pub(crate) mod git_topology;
53mod grounding;
54pub(crate) mod harn_entry;
55pub(crate) mod hitl;
56mod hitl_read;
57pub mod host;
58pub mod http_response;
59pub(crate) mod io;
60mod iter;
61pub(crate) mod json;
62mod json_query;
63pub(crate) mod json_stream;
64mod jsonrpc;
65mod junit;
66mod lifecycle_receipts;
67mod logging;
68pub mod long_running;
69mod math;
70pub(crate) use math::call_seeded_random_method;
71pub(crate) mod memory;
72mod monitors;
73mod multipart;
74mod net;
75mod net_policy;
76mod oauth_dynreg;
77mod oauth_storage;
78pub(crate) mod observability;
79pub(crate) mod options;
80mod package_snapshot;
81pub(crate) use package_snapshot::PackageSnapshotRegistry;
82mod path;
83pub(crate) mod path_scope_guard;
84pub(crate) mod pool;
85#[cfg(feature = "postgres")]
86mod postgres;
87#[cfg(feature = "postgres")]
88pub use postgres::install_shared_pool_registry;
89pub mod process;
90pub(crate) mod process_spawn;
91mod project;
92mod project_catalog;
93mod project_enrich;
94mod regex;
95mod review;
96mod runtime_scope;
97pub(crate) mod sandbox;
98pub mod secret_scan;
99pub(crate) mod session_store;
100mod sets;
101pub(crate) mod shapes;
102mod skills;
103#[cfg(feature = "sqlite")]
104mod sqlite;
105pub(crate) mod strings;
106pub(crate) mod supervisor;
107pub mod template;
108mod testbench;
109mod testing;
110mod timing;
111pub mod token_redaction;
112pub(crate) mod tool_hooks;
113pub(crate) mod tools;
114pub mod tracing;
115mod transcript_compact;
116pub(crate) mod transcript_project;
117mod triggers_stdlib;
118mod tui;
119mod types;
120mod url_parse;
121mod vision;
122pub(crate) mod waitpoint;
123mod web;
124pub mod workflow_messages;
125pub(crate) mod xml;
126
127use crate::http::register_http_builtins;
128use crate::llm::register_llm_builtins;
129use crate::mcp::register_mcp_builtins;
130use crate::mcp_server::register_mcp_server_builtins;
131use crate::vm::Vm;
132
133pub(crate) use crate::schema::{json_to_vm_value, schema_result_value};
134pub(crate) fn set_thread_source_dir(dir: &std::path::Path) {
135    process::set_thread_source_dir(dir);
136}
137
138/// Register core builtins: pure/deterministic, no I/O.
139pub fn register_core_stdlib(vm: &mut Vm) {
140    types::register_type_builtins(vm);
141    math::register_math_builtins(vm);
142    strings::register_string_builtins(vm);
143    json::register_json_builtins(vm);
144    json_stream::register_json_stream_builtins(vm);
145    xml::register_xml_builtins(vm);
146    datetime::register_datetime_builtins(vm);
147    document::register_document_builtins(vm);
148    calendar::register_calendar_builtins(vm);
149    cron::register_cron_builtins(vm);
150    regex::register_regex_builtins(vm);
151    bytes::register_bytes_builtins(vm);
152    compression::register_compression_builtins(vm);
153    command_policy::register_command_policy_builtins(vm);
154    runtime_scope::register_runtime_scope_builtins(vm);
155    crypto::register_crypto_builtins(vm);
156    csv::register_csv_builtins(vm);
157    junit::register_junit_builtins(vm);
158    multipart::register_multipart_builtins(vm);
159    url_parse::register_url_builtins(vm);
160    web::register_web_builtins(vm);
161    cookies::register_cookie_builtins(vm);
162    path::register_path_helper_builtins(vm);
163    sets::register_set_builtins(vm);
164    collections::register_collection_builtins(vm);
165    iter::register_iter_builtins(vm);
166    event_log::register_event_log_builtins(vm);
167    durable_step::register_durable_step_builtins(vm);
168    channels::register_channel_builtins(vm);
169    channel_guardrails::register_channel_guardrail_builtins(vm);
170    shapes::register_shape_builtins(vm);
171    testing::register_testing_builtins(vm);
172    flow::register_flow_builtins(vm);
173    lifecycle_receipts::register_lifecycle_receipt_builtins(vm);
174    net_policy::register_net_policy_builtins(vm);
175    http_response::register_http_response_builtins(vm);
176}
177
178/// Register I/O builtins (requires OS access).
179pub fn register_io_stdlib(vm: &mut Vm) {
180    io::register_io_builtins(vm);
181    host::register_host_builtins(vm);
182    fs::register_fs_builtins(vm);
183    package_snapshot::register_package_snapshot_builtins(vm);
184    files::register_file_builtins(vm);
185    git::register_git_builtins(vm);
186    vision::register_vision_builtins(vm);
187    agent_state::register_agent_state_builtins(vm);
188    memory::register_memory_builtins(vm);
189    session_store::register_session_store_builtins(vm);
190    net::register_net_builtins(vm);
191    process::register_process_builtins(vm);
192    process::register_path_builtins(vm);
193    sandbox::register_sandbox_builtins(vm);
194    // Clock builtins overlay process::timestamp/elapsed so they honor
195    // mock_time / advance_time. Register AFTER process to take precedence.
196    clock::register_clock_builtins(vm);
197    crate::durable_rate_limit::register_durable_rate_limit_builtins(vm);
198    testbench::register_testbench_builtins(vm);
199    project::register_project_builtins(vm);
200    grounding::register_grounding_builtins(vm);
201    tracing::register_tracing_builtins(vm);
202    observability::register_observability_builtins(vm);
203    timing::register_timing_builtins(vm);
204    tui::register_tui_builtins(vm);
205}
206
207fn register_agent_stdlib_before_llm(vm: &mut Vm) {
208    concurrency::register_concurrency_builtins(vm);
209    connectors::register_connector_builtins(vm);
210    review::register_review_builtins(vm);
211    secret_scan::register_secret_scan_builtins(vm);
212    tools::register_tool_builtins(vm);
213    tool_hooks::register_tool_hooks_builtins(vm);
214    crate::composition::register_composition_builtins(vm);
215    skills::register_skill_builtins(vm);
216    agents_daemon::register_daemon_builtins(vm);
217    triggers_stdlib::register_trigger_builtins(vm);
218    #[cfg(feature = "postgres")]
219    postgres::register_postgres_builtins(vm);
220    #[cfg(feature = "sqlite")]
221    sqlite::register_sqlite_builtins(vm);
222    monitors::register_monitor_builtins(vm);
223    hitl::register_hitl_builtins(vm);
224    hitl_read::register_hitl_read_builtins(vm);
225    waitpoint::register_waitpoint_builtins(vm);
226    supervisor::register_supervisor_builtins(vm);
227    agents::register_agent_builtins(vm);
228    pool::register_pool_builtins(vm);
229    oauth_storage::register_oauth_storage_builtins(vm);
230    oauth_dynreg::register_oauth_dynreg_builtins(vm);
231    token_redaction::register_token_redaction_builtins(vm);
232    agent_sessions::register_agent_session_builtins(vm);
233    artifact_emit::register_artifact_emit_builtins(vm);
234    external_agent::register_external_agent_builtins(vm);
235    path_scope_guard::register_path_scope_guard_builtins(vm);
236    workflow_messages::register_workflow_message_builtins(vm);
237    transcript_compact::register_transcript_compaction_builtins(vm);
238    compaction::register_compaction_builtins(vm);
239    transcript_project::register_transcript_projection_builtins(vm);
240    assemble::register_assemble_context_builtin(vm);
241    crate::egress::register_egress_builtins(vm);
242    crate::security::register_security_builtins(vm);
243    register_http_builtins(vm);
244    jsonrpc::register_jsonrpc_builtins(vm);
245}
246
247fn register_agent_stdlib_after_llm(vm: &mut Vm) {
248    register_mcp_builtins(vm);
249    register_mcp_server_builtins(vm);
250    crate::step_runtime::register_step_builtins(vm);
251}
252
253/// Register agent builtins (requires network access and async runtime).
254pub fn register_agent_stdlib(vm: &mut Vm) {
255    register_agent_stdlib_before_llm(vm);
256    register_llm_builtins(vm);
257    register_agent_stdlib_after_llm(vm);
258}
259
260/// Register all standard builtins on a VM (core + io + agent). Also
261/// installs the macro-emitted signature slice into the parser registry
262/// (idempotent under repeat calls with the same slice pointer).
263pub fn register_vm_stdlib(vm: &mut Vm) {
264    register_core_stdlib(vm);
265    register_io_stdlib(vm);
266    register_agent_stdlib(vm);
267    vm.project_declared_capability_methods();
268    if vm.harness().is_none() {
269        vm.set_harness(crate::harness::Harness::real());
270    }
271    if harn_parser::legacy_ambient_capabilities_enabled() && vm.global("harness").is_none() {
272        let harness = vm
273            .root_harness_value()
274            .expect("register_vm_stdlib installs a root Harness");
275        vm.set_global("harness", harness);
276    }
277    vm.project_legacy_capability_globals();
278    harn_builtin_registry::install_builtin_manifest(all_builtin_manifest());
279}
280
281pub(crate) fn rebind_execution_state_builtins(vm: &mut Vm) {
282    concurrency::register_concurrency_builtins(vm);
283}
284
285fn stdlib_probe_vm() -> Vm {
286    let mut vm = Vm::new();
287    register_vm_stdlib(&mut vm);
288    // Name-only/metadata introspection never accesses this path, but passing
289    // a real per-platform temp dir keeps registration logic honest if a
290    // callee someday validates its parent.
291    let tmp = std::env::temp_dir();
292    crate::store::register_store_builtins(&mut vm, &tmp);
293    crate::checkpoint::register_checkpoint_builtins(&mut vm, &tmp, "default");
294    crate::metadata::register_metadata_builtins(&mut vm, &tmp);
295    // Install the macro-emitted signatures into the parser registry so any
296    // probe-driven name/metadata query (e.g. the alignment test) sees the
297    // post-migration sig set. Idempotent under repeat install with the same
298    // pointer (which `all_builtin_manifest()` guarantees).
299    harn_builtin_registry::install_builtin_manifest(all_builtin_manifest());
300    vm
301}
302
303/// Aggregate of every `#[harn_builtin]`-emitted `VmBuiltinDef` in the stdlib.
304///
305/// Backed by the `linkme::distributed_slice` declared on
306/// [`crate::stdlib::macros::ALL_BUILTIN_DEFS`] — every annotated fn
307/// contributes one entry automatically at link time. Keep builtin registration
308/// on this distributed slice instead of per-module arrays plus a central
309/// hand-maintained aggregator.
310///
311/// **Force-link warning** (linkme issue #36): rlib dead-code stripping
312/// can drop these statics when `harn-vm` is linked transitively. Every
313/// binary that exercises builtins (`harn-cli`, `harn-lsp`, `harn-lint`,
314/// `harn-serve`, `harn-dap`) calls [`force_link`] near `main()` to defeat
315/// the stripping. The alignment test
316/// `linkme_distributed_slice_populates_with_all_builtins` catches a silent
317/// regression by asserting the slice is non-empty.
318pub fn all_builtin_defs() -> &'static [&'static macros::VmBuiltinDef] {
319    let defs = &macros::ALL_BUILTIN_DEFS;
320    validate_builtin_contracts(defs);
321    defs
322}
323
324fn validate_builtin_contracts(defs: &[&macros::VmBuiltinDef]) {
325    use harn_builtin_meta::BuiltinExposure;
326    let mut source_names = std::collections::BTreeSet::new();
327    let mut capability_methods = std::collections::BTreeSet::new();
328    for def in defs {
329        assert!(
330            def.contract.is_declared(),
331            "builtin `{}` has no typed exposure/effect contract",
332            def.sig.name
333        );
334        assert!(
335            !matches!(def.contract.exposure, BuiltinExposure::PureGlobal)
336                || def.contract.effects.is_empty(),
337            "ambient global builtin `{}` declares effects; effects must flow through Harness",
338            def.sig.name
339        );
340        if let BuiltinExposure::CapabilityFunction { authority_argument } = def.contract.exposure {
341            assert!(
342                !def.contract.effects.is_empty(),
343                "capability function `{}` must declare effects",
344                def.sig.name
345            );
346            assert!(
347                usize::from(authority_argument) < def.sig.params.len(),
348                "capability function `{}` authority argument is out of range",
349                def.sig.name
350            );
351        }
352        if def.runtime_only {
353            assert!(
354                matches!(def.contract.exposure, BuiltinExposure::RuntimeInternal),
355                "runtime_only builtin `{}` must use runtime_internal exposure",
356                def.sig.name
357            );
358        }
359        if let BuiltinExposure::HarnessMethod { method, .. } = def.contract.exposure {
360            assert!(
361                !method.is_empty(),
362                "harness method for `{}` cannot be empty",
363                def.sig.name
364            );
365            let BuiltinExposure::HarnessMethod { capability, method } = def.contract.exposure
366            else {
367                unreachable!()
368            };
369            assert!(
370                capability_methods.insert((capability, method)),
371                "duplicate contract for harness.{}.{}",
372                capability.field_name(),
373                method
374            );
375        }
376        if matches!(
377            def.contract.exposure,
378            BuiltinExposure::PureGlobal
379                | BuiltinExposure::CapabilityFunction { .. }
380                | BuiltinExposure::PrivilegedWire
381                | BuiltinExposure::HarnessMethod { .. }
382        ) {
383            assert!(
384                source_names.insert(def.sig.name),
385                "duplicate source contract name `{}`",
386                def.sig.name
387            );
388        }
389    }
390}
391
392/// Force-link entry point: a `pub fn` that touches `ALL_BUILTIN_DEFS` so
393/// the linker keeps every `#[harn_builtin]`-emitted static. Drivers
394/// (`harn-cli`, `harn-lsp`, etc.) call this once at startup. Doing nothing
395/// at runtime is fine — the side effect is purely a link-time signal.
396///
397/// See [`linkme issue #36`](https://github.com/dtolnay/linkme/issues/36)
398/// for why the explicit touch is necessary on every supported target.
399pub fn force_link() {
400    // `black_box` prevents LLVM from constant-folding the length read away.
401    // The `>= 1` guard never trips at runtime but is a load-bearing safety
402    // net: it converts a silent slice-empty regression into a panic that
403    // surfaces at the first builtin call instead of a confusing
404    // `HARN-NAM-002` somewhere down the line.
405    let len = std::hint::black_box(macros::ALL_BUILTIN_DEFS.len());
406    assert!(
407        len >= 1,
408        "linkme distributed_slice ALL_BUILTIN_DEFS is empty — \
409         the binary is missing `harn_vm::stdlib::force_link()` at startup, \
410         or the linker stripped the harn-vm rlib statics (see linkme issue #36)"
411    );
412}
413
414/// Driver-facing immutable manifest for parser, IR, policy, and docs.
415pub fn all_builtin_manifest() -> &'static [&'static harn_builtin_registry::BuiltinManifestEntry] {
416    use std::sync::OnceLock;
417    static AGG: OnceLock<Vec<&'static harn_builtin_registry::BuiltinManifestEntry>> =
418        OnceLock::new();
419    AGG.get_or_init(|| {
420        let mut out = Vec::new();
421        let mut capability_methods = std::collections::BTreeSet::new();
422        for def in all_builtin_defs() {
423            if def.runtime_only {
424                continue;
425            }
426            out.push(
427                Box::leak(Box::new(harn_builtin_registry::BuiltinManifestEntry {
428                    name: def.sig.name,
429                    signature: &def.sig,
430                    contract: def.contract,
431                })) as &'static harn_builtin_registry::BuiltinManifestEntry,
432            );
433            if let harn_builtin_meta::BuiltinExposure::HarnessMethod { capability, method } =
434                def.contract.exposure
435            {
436                capability_methods.insert((capability, method));
437            }
438            for alias in def.aliases {
439                let signature = Box::leak(Box::new(harn_builtin_meta::BuiltinSignature {
440                    name: alias,
441                    ..def.sig
442                }));
443                out.push(
444                    Box::leak(Box::new(harn_builtin_registry::BuiltinManifestEntry {
445                        name: alias,
446                        signature,
447                        contract: def.contract,
448                    })) as &'static harn_builtin_registry::BuiltinManifestEntry,
449                );
450            }
451        }
452        for entry in harn_capability_contracts::manifest() {
453            let harn_builtin_meta::BuiltinExposure::HarnessMethod { capability, method } =
454                entry.contract.exposure
455            else {
456                unreachable!("leaf capability manifest contains a non-method contract")
457            };
458            if !capability_methods.insert((capability, method)) {
459                let runtime_entry = out
460                    .iter()
461                    .find(|candidate| candidate.contract.exposure == entry.contract.exposure)
462                    .expect("duplicate capability key must have a runtime manifest entry");
463                assert_eq!(
464                    runtime_entry.contract,
465                    entry.contract,
466                    "runtime effect contract drift for harness.{}.{}",
467                    capability.field_name(),
468                    method
469                );
470                assert_eq!(
471                    runtime_entry.signature,
472                    entry.signature,
473                    "runtime signature drift for harness.{}.{}",
474                    capability.field_name(),
475                    method
476                );
477                continue;
478            }
479            out.push(*entry);
480        }
481        for group in harn_builtin_meta::host_capabilities::HOST_CAPABILITY_GROUPS {
482            for method in group.methods {
483                if !capability_methods.insert((group.capability, *method)) {
484                    continue;
485                }
486                let internal_name: &'static str = Box::leak(
487                    format!("__cap_{}_{}", group.capability.field_name(), method).into_boxed_str(),
488                );
489                let params: &'static [harn_builtin_meta::Param] =
490                    Box::leak(Box::new([harn_builtin_meta::Param::new(
491                        "request",
492                        harn_builtin_meta::Ty::Named("dict"),
493                    )]));
494                let signature = Box::leak(Box::new(harn_builtin_meta::BuiltinSignature::simple(
495                    internal_name,
496                    params,
497                    harn_builtin_meta::Ty::Named("dict"),
498                )));
499                out.push(Box::leak(Box::new(
500                    harn_builtin_registry::BuiltinManifestEntry {
501                        name: internal_name,
502                        signature,
503                        contract: harn_builtin_meta::BuiltinContract::harness(
504                            group.capability,
505                            method,
506                            group.effects,
507                        ),
508                    },
509                )));
510            }
511        }
512        out
513    })
514    .as_slice()
515}
516
517/// Indexed view of the authoritative builtin manifest.
518///
519/// Runtime dispatch reaches this boundary for every typed Harness call. Keep
520/// lookup policy here with the manifest owner instead of making each consumer
521/// linearly rescan the full registry. The nested capability map also accepts a
522/// borrowed `&str`, so a method call does not allocate an owned lookup key.
523struct BuiltinManifestIndex {
524    by_name: std::collections::HashMap<
525        &'static str,
526        &'static harn_builtin_registry::BuiltinManifestEntry,
527    >,
528    by_capability: std::collections::HashMap<
529        harn_builtin_meta::CapabilityId,
530        std::collections::HashMap<
531            &'static str,
532            &'static harn_builtin_registry::BuiltinManifestEntry,
533        >,
534    >,
535    recorded_effects_by_name: std::collections::HashMap<
536        &'static str,
537        &'static harn_builtin_registry::BuiltinManifestEntry,
538    >,
539}
540
541fn builtin_manifest_index() -> &'static BuiltinManifestIndex {
542    use harn_builtin_meta::BuiltinExposure;
543    use std::sync::OnceLock;
544
545    static INDEX: OnceLock<BuiltinManifestIndex> = OnceLock::new();
546    INDEX.get_or_init(|| {
547        let mut by_name = std::collections::HashMap::new();
548        let mut by_capability: std::collections::HashMap<
549            harn_builtin_meta::CapabilityId,
550            std::collections::HashMap<
551                &'static str,
552                &'static harn_builtin_registry::BuiltinManifestEntry,
553            >,
554        > = std::collections::HashMap::new();
555        let mut recorded_effects_by_name = std::collections::HashMap::new();
556        for entry in all_builtin_manifest() {
557            assert!(
558                by_name.insert(entry.name, *entry).is_none(),
559                "duplicate builtin manifest name `{}`",
560                entry.name
561            );
562            if let BuiltinExposure::HarnessMethod { capability, method } = entry.contract.exposure {
563                assert!(
564                    by_capability
565                        .entry(capability)
566                        .or_default()
567                        .insert(method, *entry)
568                        .is_none(),
569                    "duplicate Harness method manifest entry `harness.{}.{method}`",
570                    capability.field_name()
571                );
572            }
573            if matches!(
574                entry.contract.exposure,
575                BuiltinExposure::CapabilityFunction { .. } | BuiltinExposure::PrivilegedWire
576            ) && !entry.contract.effects.is_empty()
577            {
578                recorded_effects_by_name.insert(entry.name, *entry);
579            }
580        }
581        BuiltinManifestIndex {
582            by_name,
583            by_capability,
584            recorded_effects_by_name,
585        }
586    })
587}
588
589/// Resolve a source/runtime builtin contract without rescanning the manifest.
590pub fn builtin_manifest_entry(
591    name: &str,
592) -> Option<&'static harn_builtin_registry::BuiltinManifestEntry> {
593    builtin_manifest_index().by_name.get(name).copied()
594}
595
596/// Resolve the contract for one typed Harness method without allocation.
597pub fn capability_method_manifest_entry(
598    capability: harn_builtin_meta::CapabilityId,
599    method: &str,
600) -> Option<&'static harn_builtin_registry::BuiltinManifestEntry> {
601    builtin_manifest_index()
602        .by_capability
603        .get(&capability)
604        .and_then(|methods| methods.get(method))
605        .copied()
606}
607
608/// Resolve only builtin contracts that can emit runtime effect receipts.
609///
610/// Pure builtins dominate VM call volume. Keeping them out of this projection
611/// makes their receipt check one negative hash lookup instead of a full
612/// manifest lookup plus exposure classification on every call.
613pub fn recorded_effect_builtin_manifest_entry(
614    name: &str,
615) -> Option<&'static harn_builtin_registry::BuiltinManifestEntry> {
616    builtin_manifest_index()
617        .recorded_effects_by_name
618        .get(name)
619        .copied()
620}
621
622/// Register every `#[harn_builtin]`-emitted def on the given VM. Drivers
623/// that build the full stdlib via `register_vm_stdlib` get this for free —
624/// each module's `register_*_builtins` walks its `MODULE_BUILTINS` slice.
625/// This helper is exposed for embedders / tests that want a one-call entry.
626pub fn register_all_macro_builtins(vm: &mut Vm) {
627    for def in all_builtin_defs() {
628        vm.register_builtin_def(def);
629    }
630}
631
632/// Return the canonical list of all stdlib builtin names. Used by
633/// harn-lint and harn-lsp to avoid hardcoded duplicate lists.
634pub fn stdlib_builtin_names() -> Vec<String> {
635    let vm = stdlib_probe_vm();
636    let mut names = vm.builtin_names();
637    // Special opcodes/keywords, not registered builtins, but linter
638    // should recognize them as valid function calls.
639    for extra in harn_parser::builtin_signatures::LANGUAGE_INTRINSICS {
640        names.push(extra.to_string());
641    }
642    names
643}
644
645/// Return discoverable metadata for registered stdlib builtins.
646pub fn stdlib_builtin_metadata() -> Vec<crate::vm::VmBuiltinMetadata> {
647    stdlib_probe_vm().builtin_metadata()
648}
649
650/// Reset thread-local stdlib state. Call between test runs.
651///
652/// Note: `long_running::reset_state()` is intentionally NOT called here
653/// because that store is process-global, not thread-local. Wiping it
654/// from a per-test reset hook lets one test cancel another test's
655/// in-flight worker thread (and lose its `agent_inbox::push`
656/// notification), which surfaces as `walk_dir_long_running` /
657/// `glob_long_running` timing out under parallel test load. The two
658/// call sites that genuinely need a clean handle store —
659/// `stdlib::fs::tests::{walk_dir_long_running,glob_long_running}` — call
660/// `long_running::reset_state()` explicitly while holding
661/// `LONG_RUNNING_TEST_LOCK`.
662pub fn reset_stdlib_state() {
663    logging::reset_logging_state();
664    process::reset_process_state();
665    clock::reset_clock_state();
666    io::reset_io_state();
667    sandbox::reset_sandbox_state();
668    git::reset_git_state();
669    fs::reset_fs_state();
670    json::reset_json_state();
671    json_stream::reset_json_stream_state();
672    host::reset_host_state();
673    host::reset_scoped_host_state();
674    observability::reset_observability_state();
675    timing::reset_timing_state();
676    durable_step::reset_durable_step_state();
677    crate::egress::reset_egress_policy_for_host();
678    hitl::reset_hitl_state();
679    crate::http::reset_http_state();
680    crate::external_agent::reset_external_agent_state();
681    monitors::reset_monitor_state();
682    waitpoint::reset_waitpoint_state();
683    triggers_stdlib::reset_auto_resume_timeouts();
684    compaction::reset_compaction_state();
685    agents::reset_agent_worker_state();
686    agents::workflow::reset_workflow_run_states();
687    pool::reset_pool_state();
688    #[cfg(feature = "postgres")]
689    postgres::reset_postgres_state();
690    #[cfg(feature = "sqlite")]
691    sqlite::reset_sqlite_state();
692    supervisor::reset_supervisor_state();
693    agents::records::reset_eval_metrics();
694    agents::records::reset_friction_events();
695    tools::clear_current_tool_registry();
696    tools::clear_tool_synthesis_cache();
697    vision::reset_vision_state();
698    crate::skills::clear_current_skill_registry();
699    template::reset_prompt_registry();
700    crate::triggers::clear_webhook_intake_state();
701    crate::llm::cache::reset_in_process_cache_state();
702}
703
704#[cfg(test)]
705mod tests {
706    use super::*;
707
708    #[tokio::test(flavor = "current_thread")]
709    async fn register_vm_stdlib_passes_default_harness_only_to_main() {
710        let chunk = crate::compile_source(
711            r"
712fn __probe_harness_clock(clock: HarnessClock) {
713  const now = clock.now_ms()
714  return now >= 0
715}
716
717fn main(harness: Harness) {
718  return __probe_harness_clock(harness.clock)
719}
720",
721        )
722        .expect("compile harness clock probe");
723        let mut vm = Vm::new();
724        register_vm_stdlib(&mut vm);
725
726        assert!(vm.root_harness_value().is_some());
727        assert!(vm.global("harness").is_none());
728        let result = vm
729            .execute(&chunk)
730            .await
731            .expect("execute harness clock probe");
732        assert!(matches!(result, crate::value::VmValue::Bool(true)));
733    }
734
735    /// `harn_stdlib::builtin_reexports` names builtins from a crate that
736    /// cannot see the builtin registry, so nothing there can catch a typo or a
737    /// rename. This is that check: every re-exported name must resolve to a
738    /// real builtin, or `import { … } from "std/…"` binds a reference to
739    /// nothing and fails at the call site instead of the import.
740    #[test]
741    fn every_stdlib_builtin_reexport_names_a_registered_builtin() {
742        let registered: std::collections::HashSet<&str> = all_builtin_defs()
743            .iter()
744            .flat_map(|def| std::iter::once(def.sig.name).chain(def.aliases.iter().copied()))
745            .collect();
746
747        let mut checked = 0;
748        for entry in harn_stdlib::STDLIB_SOURCES {
749            for name in harn_stdlib::builtin_reexports(entry.module) {
750                assert!(
751                    registered.contains(name),
752                    "std/{} re-exports '{name}', which is not a registered builtin",
753                    entry.module
754                );
755                checked += 1;
756            }
757        }
758        assert!(
759            checked > 0,
760            "no re-exports were checked — the table or the module list is not being read"
761        );
762    }
763
764    #[test]
765    fn ambient_effect_builtin_allowlist_is_empty() {
766        let offenders = all_builtin_defs()
767            .iter()
768            .filter(|def| {
769                matches!(
770                    def.contract.exposure,
771                    harn_builtin_meta::BuiltinExposure::PureGlobal
772                ) && !def.contract.effects.is_empty()
773            })
774            .map(|def| def.sig.name)
775            .collect::<Vec<_>>();
776
777        assert!(
778            offenders.is_empty(),
779            "ambient effect builtins are forbidden; route these through Harness: {offenders:?}"
780        );
781    }
782
783    #[test]
784    fn every_source_named_runtime_callable_has_a_typed_contract() {
785        let manifest_names = all_builtin_manifest()
786            .iter()
787            .map(|entry| entry.name)
788            .collect::<std::collections::HashSet<_>>();
789        let offenders = stdlib_probe_vm()
790            .builtin_names()
791            .into_iter()
792            .filter(|name| {
793                !name.starts_with("__")
794                    && !manifest_names.contains(name.as_str())
795                    && !harn_parser::builtin_signatures::is_language_intrinsic(name)
796            })
797            .collect::<Vec<_>>();
798
799        assert!(
800            offenders.is_empty(),
801            "runtime callables without typed source contracts bypass the Harness gate: {offenders:?}"
802        );
803    }
804
805    #[test]
806    fn builtin_manifest_indexes_preserve_the_authoritative_contracts() {
807        use harn_builtin_meta::BuiltinExposure;
808
809        let mut capability_entries = 0;
810        for entry in all_builtin_manifest() {
811            assert!(
812                std::ptr::eq(
813                    builtin_manifest_entry(entry.name).expect("indexed builtin entry"),
814                    *entry,
815                ),
816                "name index projected a different contract for `{}`",
817                entry.name
818            );
819            let should_record = matches!(
820                entry.contract.exposure,
821                BuiltinExposure::CapabilityFunction { .. } | BuiltinExposure::PrivilegedWire
822            ) && !entry.contract.effects.is_empty();
823            assert_eq!(
824                recorded_effect_builtin_manifest_entry(entry.name).is_some(),
825                should_record,
826                "recorded-effect index drifted for `{}`",
827                entry.name
828            );
829            if let BuiltinExposure::HarnessMethod { capability, method } = entry.contract.exposure {
830                capability_entries += 1;
831                assert!(
832                    std::ptr::eq(
833                        capability_method_manifest_entry(capability, method)
834                            .expect("indexed Harness method entry"),
835                        *entry,
836                    ),
837                    "capability index projected a different contract for `harness.{}.{method}`",
838                    capability.field_name()
839                );
840            }
841        }
842        assert!(capability_entries > 0, "no Harness contracts were indexed");
843        assert!(builtin_manifest_entry("__definitely_missing_builtin").is_none());
844        assert!(capability_method_manifest_entry(
845            harn_builtin_meta::CapabilityId::Fs,
846            "__definitely_missing_method",
847        )
848        .is_none());
849    }
850}