Skip to main content

harn_stdlib/
lib.rs

1//! Canonical embedded Harn standard library source catalog.
2//!
3//! This crate intentionally contains only static source strings so runtime and
4//! static tooling crates can share the same stdlib modules without depending on
5//! each other.
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub struct StdlibSource {
9    pub module: &'static str,
10    pub source: &'static str,
11}
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct StdlibPromptAsset {
15    pub path: &'static str,
16    pub source: &'static str,
17}
18
19macro_rules! embedded_catalog {
20    ($entry:ident, $key:ident, [$($name:literal => $path:literal),* $(,)?]) => {
21        &[
22            $($entry {
23                $key: $name,
24                source: include_str!($path),
25            },)*
26        ]
27    };
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct StdlibPublicFunction {
32    pub name: String,
33    pub signature: String,
34    pub required_params: usize,
35    pub total_params: usize,
36    pub variadic: bool,
37    pub doc: Option<String>,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct StdlibEntrypointModule {
42    pub import_path: String,
43    pub category: String,
44}
45
46pub const STDLIB_SOURCES: &[StdlibSource] = embedded_catalog!(StdlibSource, module, [
47    "text" => "stdlib/stdlib_text.harn",
48    "semver" => "stdlib/stdlib_semver.harn",
49    "ansi" => "stdlib/stdlib_ansi.harn",
50    "table" => "stdlib/stdlib_table.harn",
51    "diff" => "stdlib/stdlib_diff.harn",
52    "edit" => "stdlib/stdlib_edit.harn",
53    "edit/capabilities" => "stdlib/edit/capabilities.harn",
54    "edit/internal" => "stdlib/edit/internal.harn",
55    "edit/patch" => "stdlib/edit/patch.harn",
56    "edit/safe_patch" => "stdlib/edit/safe_patch.harn",
57    "edit/fast_apply" => "stdlib/edit/fast_apply.harn",
58    "ast" => "stdlib/stdlib_ast.harn",
59    "rules" => "stdlib/stdlib_rules.harn",
60    "lint" => "stdlib/stdlib_lint.harn",
61    "artifact/web" => "stdlib/artifact/web.harn",
62    "collections" => "stdlib/stdlib_collections.harn",
63    "math" => "stdlib/stdlib_math.harn",
64    "slug" => "stdlib/stdlib_slug.harn",
65    "path" => "stdlib/stdlib_path.harn",
66    "fs" => "stdlib/stdlib_fs.harn",
67    "run_artifacts" => "stdlib/stdlib_run_artifacts.harn",
68    "os" => "stdlib/stdlib_os.harn",
69    "json" => "stdlib/stdlib_json.harn",
70    "json/stream" => "stdlib/stdlib_json_stream.harn",
71    "xml" => "stdlib/stdlib_xml.harn",
72    "cache" => "stdlib/stdlib_cache.harn",
73    "observability" => "stdlib/stdlib_observability.harn",
74    "timing" => "stdlib/stdlib_timing.harn",
75    "verification" => "stdlib/stdlib_verification.harn",
76    "tools" => "stdlib/stdlib_tools.harn",
77    "composition" => "stdlib/stdlib_composition.harn",
78    "web" => "stdlib/stdlib_web.harn",
79    "graphql" => "stdlib/stdlib_graphql.harn",
80    "code_librarian" => "stdlib/stdlib_code_librarian.harn",
81    "schema" => "stdlib/stdlib_schema.harn",
82    "identity" => "stdlib/stdlib_identity.harn",
83    "disclosure" => "stdlib/stdlib_disclosure.harn",
84    "testing" => "stdlib/stdlib_testing.harn",
85    "files" => "stdlib/stdlib_files.harn",
86    "document" => "stdlib/stdlib_document.harn",
87    "mcp" => "stdlib/stdlib_mcp.harn",
88    "vision" => "stdlib/stdlib_vision.harn",
89    "context" => "stdlib/stdlib_context.harn",
90    "context/maintenance" => "stdlib/context/maintenance.harn",
91    "context/eval" => "stdlib/context/eval.harn",
92    "eval/stats" => "stdlib/stdlib_eval_stats.harn",
93    "eval/agreement" => "stdlib/stdlib_eval_agreement.harn",
94    "runtime" => "stdlib/stdlib_runtime.harn",
95    "io" => "stdlib/stdlib_io.harn",
96    "net" => "stdlib/stdlib_net.harn",
97    "command" => "stdlib/stdlib_command.harn",
98    "signal" => "stdlib/stdlib_signal.harn",
99    "net_policy" => "stdlib/stdlib_net_policy.harn",
100    "review" => "stdlib/stdlib_review.harn",
101    "experiments" => "stdlib/stdlib_experiments.harn",
102    "project" => "stdlib/stdlib_project.harn",
103    "prompt_library" => "stdlib/stdlib_prompt_library.harn",
104    "async" => "stdlib/stdlib_async.harn",
105    "poll" => "stdlib/stdlib_poll.harn",
106    "coerce" => "stdlib/stdlib_coerce.harn",
107    "settled" => "stdlib/stdlib_settled.harn",
108    "cli" => "stdlib/stdlib_cli.harn",
109    "cli/argparse" => "stdlib/cli/argparse.harn",
110    "cli/render" => "stdlib/cli/render.harn",
111    "cli/models/batch_artifacts" => "stdlib/cli/models/batch_artifacts.harn",
112    "cli/models/batch_cancel" => "stdlib/cli/models/batch_cancel.harn",
113    "cli/models/batch_download" => "stdlib/cli/models/batch_download.harn",
114    "cli/models/batch_lifecycle" => "stdlib/cli/models/batch_lifecycle.harn",
115    "cli/models/batch_status" => "stdlib/cli/models/batch_status.harn",
116    "cli/models/batch_submit" => "stdlib/cli/models/batch_submit.harn",
117    "cli/models/batch_transport" => "stdlib/cli/models/batch_transport.harn",
118    "cli/models/lora_render" => "stdlib/cli/models/lora_render.harn",
119    "cli/paths" => "stdlib/cli/paths.harn",
120    "gha" => "stdlib/stdlib_gha.harn",
121    "tui" => "stdlib/stdlib_tui.harn",
122    "jsonl" => "stdlib/stdlib_jsonl.harn",
123    "config" => "stdlib/stdlib_config.harn",
124    "calendar" => "stdlib/stdlib_calendar.harn",
125    "agents" => "stdlib/stdlib_agents.harn",
126    "lifecycle/pool" => "stdlib/lifecycle/pool.harn",
127    "lifecycle/combinators" => "stdlib/lifecycle/combinators.harn",
128    "lifecycle/on_budget" => "stdlib/lifecycle/on_budget.harn",
129    "agent/prompts" => "stdlib/agent/prompts.harn",
130    "llm/media" => "stdlib/llm/media.harn",
131    "llm/options" => "stdlib/llm/options.harn",
132    "llm/catalog" => "stdlib/llm/catalog.harn",
133    "llm/safe" => "stdlib/llm/safe.harn",
134    "harness/policy" => "stdlib/harness/policy.harn",
135    "llm/budget" => "stdlib/llm/budget.harn",
136    "llm/economics" => "stdlib/llm/economics.harn",
137    "llm/prompts" => "stdlib/llm/prompts.harn",
138    "llm/defaults" => "stdlib/llm/defaults.harn",
139    "llm/handlers" => "stdlib/llm/handlers.harn",
140    "llm/tool_telemetry" => "stdlib/llm/tool_telemetry.harn",
141    "llm/tool_middleware" => "stdlib/llm/tool_middleware.harn",
142    "llm/tool_binder" => "stdlib/llm/tool_binder.harn",
143    "llm/structural_validator" => "stdlib/llm/structural_validator.harn",
144    "llm/missing_tool_call" => "stdlib/llm/missing_tool_call.harn",
145    "llm/scope_classifier" => "stdlib/llm/scope_classifier.harn",
146    "llm/refine" => "stdlib/llm/refine.harn",
147    "llm/ensemble" => "stdlib/llm/ensemble.harn",
148    "llm/rerank" => "stdlib/llm/rerank.harn",
149    "agent/reasoning" => "stdlib/agent/reasoning.harn",
150    "agent/options" => "stdlib/agent/options.harn",
151    "agent/llm_dispatch" => "stdlib/agent/llm_dispatch.harn",
152    "agent/prefill" => "stdlib/agent/prefill.harn",
153    "agent/retry" => "stdlib/agent/retry.harn",
154    "llm/judge" => "stdlib/llm/judge.harn",
155    "llm/faithfulness" => "stdlib/llm/faithfulness.harn",
156    "llm/optimize" => "stdlib/llm/optimize.harn",
157    "agent/events" => "stdlib/agent/events.harn",
158    "agent/completions" => "stdlib/agent/completions.harn",
159    "agent/transcript" => "stdlib/agent/transcript.harn",
160    "agent/primitives" => "stdlib/agent/primitives.harn",
161    "agent/progress" => "stdlib/agent/progress.harn",
162    "agent/required_tools" => "stdlib/agent/required_tools.harn",
163    "agent/monologue_actuation" => "stdlib/agent/monologue_actuation.harn",
164    "agent/monologue_actuation_types" => "stdlib/agent/monologue_actuation_types.harn",
165    "agent/stall_types" => "stdlib/agent/stall_types.harn",
166    "agent/stall" => "stdlib/agent/stall.harn",
167    "agent/governors" => "stdlib/agent/governors.harn",
168    "agent/control" => "stdlib/agent/control.harn",
169    "agent/action_graph" => "stdlib/agent/action_graph.harn",
170    "agent/result_text" => "stdlib/agent/result_text.harn",
171    "agent/best_of_n" => "stdlib/agent/best_of_n.harn",
172    "agent/loop" => "stdlib/agent/loop.harn",
173    "agent/chat" => "stdlib/agent/chat.harn",
174    "agent/user" => "stdlib/agent/user.harn",
175    "agent/tool_search" => "stdlib/agent/tool_search.harn",
176    "agent/tool_annotations" => "stdlib/agent/tool_annotations.harn",
177    "agent/turn" => "stdlib/agent/turn.harn",
178    "agent/workers" => "stdlib/agent/workers.harn",
179    "agent/introspection" => "stdlib/agent/introspection.harn",
180    "agent/resume_by" => "stdlib/agent/resume_by.harn",
181    "agent/state" => "stdlib/agent/state.harn",
182    "agent/canon" => "stdlib/agent/canon.harn",
183    "agent/skills" => "stdlib/agent/skills.harn",
184    "agent/autocompact" => "stdlib/agent/autocompact.harn",
185    "agent/mcp" => "stdlib/agent/mcp.harn",
186    "agent/command_capture" => "stdlib/agent/command_capture.harn",
187    "agent/host_tools" => "stdlib/agent/host_tools.harn",
188    "agent/host_injection" => "stdlib/agent/host_injection.harn",
189    "agent/budget" => "stdlib/agent/budget.harn",
190    "agent/daemon" => "stdlib/agent/daemon.harn",
191    "agent/preflight" => "stdlib/agent/preflight.harn",
192    "agent/postturn" => "stdlib/agent/postturn.harn",
193    "agent/stance" => "stdlib/agent/stance.harn",
194    "agent/lanes" => "stdlib/agent/lanes.harn",
195    "agent/overlays" => "stdlib/agent/overlays.harn",
196    "agent/sitrep" => "stdlib/agent/sitrep.harn",
197    "agent/judge_internals" => "stdlib/agent/judge_internals.harn",
198    "agent/judge" => "stdlib/agent/judge.harn",
199    "agent/guardrails" => "stdlib/agent/guardrails.harn",
200    "agent/step_judge" => "stdlib/agent/step_judge.harn",
201    "agent/scratchpad" => "stdlib/agent/scratchpad.harn",
202    "agent/fact" => "stdlib/agent/fact.harn",
203    "agent/hypothesis" => "stdlib/agent/hypothesis.harn",
204    "agent/pattern_knowledge" => "stdlib/agent/pattern_knowledge.harn",
205    "agent/probe" => "stdlib/agent/probe.harn",
206    "agent/stream" => "stdlib/agent/stream.harn",
207    "agent/presets" => "stdlib/agent/presets.harn",
208    "agent/pins" => "stdlib/agent/pins.harn",
209    "agent/goal" => "stdlib/agent/goal.harn",
210    "agent/task_plan" => "stdlib/agent/task_plan.harn",
211    "personas/compiler" => "stdlib/personas/compiler.harn",
212    "agent_state" => "stdlib/stdlib_agent_state.harn",
213    "memory" => "stdlib/stdlib_memory.harn",
214    "session-store" => "stdlib/stdlib_session_store.harn",
215    "coordination" => "stdlib/stdlib_coordination.harn",
216    "fleet/coordination" => "stdlib/fleet/coordination.harn",
217    "postgres" => "stdlib/stdlib_postgres.harn",
218    "postgres/query" => "stdlib/postgres/query.harn",
219    "sqlite" => "stdlib/stdlib_sqlite.harn",
220    "checkpoint" => "stdlib/stdlib_checkpoint.harn",
221    "host" => "stdlib/stdlib_host.harn",
222    "git" => "stdlib/stdlib_git.harn",
223    "hitl" => "stdlib/stdlib_hitl.harn",
224    "trust" => "stdlib/stdlib_trust.harn",
225    "corrections" => "stdlib/stdlib_corrections.harn",
226    "plan" => "stdlib/stdlib_plan.harn",
227    "waitpoints" => "stdlib/stdlib_waitpoints.harn",
228    "waitpoint" => "stdlib/stdlib_waitpoint.harn",
229    "monitors" => "stdlib/stdlib_monitors.harn",
230    "worktree" => "stdlib/stdlib_worktree.harn",
231    "acp" => "stdlib/stdlib_acp.harn",
232    "external_agent" => "stdlib/stdlib_external_agent.harn",
233    "triggers" => "stdlib/stdlib_triggers.harn",
234    "triage" => "stdlib/stdlib_triage.harn",
235    "dashboard/jobs" => "stdlib/dashboard/jobs.harn",
236    "ui_resource" => "stdlib/stdlib_ui_resource.harn",
237    "handoffs" => "stdlib/stdlib_handoffs.harn",
238    "lifecycle" => "stdlib/stdlib_lifecycle.harn",
239    "tool_hooks_catalogues" => "stdlib/stdlib_tool_hooks_catalogues.harn",
240    "tool_hooks" => "stdlib/stdlib_tool_hooks.harn",
241    "channel_guardrails" => "stdlib/stdlib_channel_guardrails.harn",
242    "personas/prelude" => "stdlib/stdlib_personas_prelude.harn",
243    "personas/bulletins" => "stdlib/stdlib_personas_bulletins.harn",
244    "connectors/shared" => "stdlib/stdlib_connectors_shared.harn",
245    "oauth/providers" => "stdlib/oauth/providers.harn",
246    "oauth/token_exchange_catalog" => "stdlib/oauth/token_exchange_catalog.harn",
247    "oauth/token_exchange" => "stdlib/oauth/token_exchange.harn",
248    "oauth/storage" => "stdlib/oauth/storage.harn",
249    "oauth/client" => "stdlib/oauth/client.harn",
250    "oauth/device_flow" => "stdlib/oauth/device_flow.harn",
251    "oauth/redaction" => "stdlib/oauth/redaction.harn",
252    "oauth/dynamic_registration" => "stdlib/oauth/dynamic_registration.harn",
253    "connectors/github" => "stdlib/stdlib_connectors_github.harn",
254    "connectors/linear" => "stdlib/stdlib_connectors_linear.harn",
255    "connectors/notion" => "stdlib/stdlib_connectors_notion.harn",
256    "connectors/slack" => "stdlib/stdlib_connectors_slack.harn",
257    "workflow/prompts" => "stdlib/workflow/prompts.harn",
258    "workflow/context" => "stdlib/workflow/context.harn",
259    "workflow/options" => "stdlib/workflow/options.harn",
260    "workflow/checkpoints" => "stdlib/workflow/checkpoints.harn",
261    "workflow/patterns" => "stdlib/workflow/patterns.harn",
262    "workflow/stage" => "stdlib/workflow/stage.harn",
263    "workflow/map" => "stdlib/workflow/map.harn",
264    "workflow/schedule" => "stdlib/workflow/schedule.harn",
265    "workflow/execute" => "stdlib/workflow/execute.harn",
266    "workflow/repair" => "stdlib/workflow/repair.harn",
267    "security" => "stdlib/stdlib_security.harn",
268    "pii" => "stdlib/stdlib_pii.harn",
269]);
270
271/// Canonical normalized connector event schemas, authored as Harn `type`
272/// declarations. This is the SOURCE OF TRUTH for the Rust event-payload
273/// structs in `crates/harn-vm/src/triggers/event/schemas_generated.rs`, which
274/// are generated from these declarations by `harn connector-schema-codegen`.
275///
276/// It is intentionally NOT registered in [`STDLIB_SOURCES`]: it is a codegen
277/// input (like `spec/openapi.yaml`), not a module loaded into every program.
278/// Exposing it as an embedded string keeps the generator independent of the
279/// current working directory.
280pub const CONNECTOR_EVENT_SCHEMAS_SOURCE: &str = include_str!("stdlib/stdlib_event_schemas.harn");
281
282pub const STDLIB_PROMPT_ASSETS: &[StdlibPromptAsset] = embedded_catalog!(StdlibPromptAsset, path, [
283    "agent/prompts/tool_contract_text.harn.prompt" => "stdlib/agent/prompts/tool_contract_text.harn.prompt",
284    "agent/prompts/tool_contract_json.harn.prompt" => "stdlib/agent/prompts/tool_contract_json.harn.prompt",
285    "agent/prompts/tool_contract_native.harn.prompt" => "stdlib/agent/prompts/tool_contract_native.harn.prompt",
286    "agent/prompts/tool_contract_text_response_protocol.harn.prompt" => "stdlib/agent/prompts/tool_contract_text_response_protocol.harn.prompt",
287    "agent/prompts/tool_contract_action_native.harn.prompt" => "stdlib/agent/prompts/tool_contract_action_native.harn.prompt",
288    "agent/prompts/tool_contract_action_text.harn.prompt" => "stdlib/agent/prompts/tool_contract_action_text.harn.prompt",
289    "agent/prompts/tool_contract_task_ledger.harn.prompt" => "stdlib/agent/prompts/tool_contract_task_ledger.harn.prompt",
290    "agent/prompts/tool_contract_deferred_tools.harn.prompt" => "stdlib/agent/prompts/tool_contract_deferred_tools.harn.prompt",
291    "agent/prompts/deferred_tool_listing.harn.prompt" => "stdlib/agent/prompts/deferred_tool_listing.harn.prompt",
292    "agent/prompts/agent_turn_preamble.harn.prompt" => "stdlib/agent/prompts/agent_turn_preamble.harn.prompt",
293    "agent/prompts/default_nudge.harn.prompt" => "stdlib/agent/prompts/default_nudge.harn.prompt",
294    "agent/prompts/agentic_user_system.harn.prompt" => "stdlib/agent/prompts/agentic_user_system.harn.prompt",
295    "agent/prompts/agentic_user_user.harn.prompt" => "stdlib/agent/prompts/agentic_user_user.harn.prompt",
296    "agent/prompts/loop_until_done_system.harn.prompt" => "stdlib/agent/prompts/loop_until_done_system.harn.prompt",
297    "agent/prompts/completion_judge_default.harn.prompt" => "stdlib/agent/prompts/completion_judge_default.harn.prompt",
298    "agent/prompts/completion_judge_feedback_fallback.harn.prompt" => "stdlib/agent/prompts/completion_judge_feedback_fallback.harn.prompt",
299    "agent/prompts/completion_judge_user.harn.prompt" => "stdlib/agent/prompts/completion_judge_user.harn.prompt",
300    "agent/prompts/step_judge_system_default.harn.prompt" => "stdlib/agent/prompts/step_judge_system_default.harn.prompt",
301    "agent/prompts/step_judge_system_adversarial.harn.prompt" => "stdlib/agent/prompts/step_judge_system_adversarial.harn.prompt",
302    "agent/prompts/step_judge_user.harn.prompt" => "stdlib/agent/prompts/step_judge_user.harn.prompt",
303    "agent/prompts/parse_guidance.harn.prompt" => "stdlib/agent/prompts/parse_guidance.harn.prompt",
304    "agent/prompts/native_tool_contract_feedback.harn.prompt" => "stdlib/agent/prompts/native_tool_contract_feedback.harn.prompt",
305    "agent/prompts/verification_gate_feedback.harn.prompt" => "stdlib/agent/prompts/verification_gate_feedback.harn.prompt",
306    "agent/prompts/daemon_watch_feedback.harn.prompt" => "stdlib/agent/prompts/daemon_watch_feedback.harn.prompt",
307    "agent/prompts/daemon_timer_feedback.harn.prompt" => "stdlib/agent/prompts/daemon_timer_feedback.harn.prompt",
308    "llm/prompts/completion_fallback_system.harn.prompt" => "stdlib/llm/prompts/completion_fallback_system.harn.prompt",
309    "llm/prompts/completion_fallback_user.harn.prompt" => "stdlib/llm/prompts/completion_fallback_user.harn.prompt",
310    "llm/prompts/transcript_summarize_user.harn.prompt" => "stdlib/llm/prompts/transcript_summarize_user.harn.prompt",
311    "llm/prompts/sitrep_user.harn.prompt" => "stdlib/llm/prompts/sitrep_user.harn.prompt",
312    "llm/prompts/structural_chain_of_draft.harn.prompt" => "stdlib/llm/prompts/structural_chain_of_draft.harn.prompt",
313    "llm/prompts/schema_recover_repair.harn.prompt" => "stdlib/llm/prompts/schema_recover_repair.harn.prompt",
314    "llm/prompts/structured_envelope_schema_contract.harn.prompt" => "stdlib/llm/prompts/structured_envelope_schema_contract.harn.prompt",
315    "llm/prompts/structured_envelope_repair.harn.prompt" => "stdlib/llm/prompts/structured_envelope_repair.harn.prompt",
316    "llm/prompts/pairwise_rerank_user.harn.prompt" => "stdlib/llm/prompts/pairwise_rerank_user.harn.prompt",
317    "llm/prompts/tool_binder_user.harn.prompt" => "stdlib/llm/prompts/tool_binder_user.harn.prompt",
318    "workflow/prompts/stage.harn.prompt" => "stdlib/workflow/prompts/stage.harn.prompt",
319    "workflow/prompts/verification_context_intro.harn.prompt" => "stdlib/workflow/prompts/verification_context_intro.harn.prompt",
320    "orchestration/prompts/compaction_summary.harn.prompt" => "stdlib/orchestration/prompts/compaction_summary.harn.prompt",
321    "orchestration/prompts/compaction_policy_replacement.harn.prompt" => "stdlib/orchestration/prompts/compaction_policy_replacement.harn.prompt",
322]);
323
324/// Embedded `.harn` script that backs a CLI subcommand. Looked up by
325/// the `harn-cli` dispatch wedge (see harn#2293 epic and harn#2294 G1)
326/// so subcommands can ship in Harn instead of Rust.
327#[derive(Debug, Clone, Copy, PartialEq, Eq)]
328pub struct StdlibCliScript {
329    /// Lookup name. For nested scripts this is the path under
330    /// `stdlib/cli/` without the `.harn` extension (e.g. `"eval/prompt"`
331    /// for `stdlib/cli/eval/prompt.harn`).
332    pub name: &'static str,
333    /// Embedded source. Run via the existing `harn run` codepath by the
334    /// dispatch wedge.
335    pub source: &'static str,
336}
337
338pub const STDLIB_CLI_SCRIPTS: &[StdlibCliScript] = embedded_catalog!(StdlibCliScript, name, [
339    "codemod" => "stdlib/cli/codemod.harn",
340    "canon/check" => "stdlib/cli/canon/check.harn",
341    "doctor" => "stdlib/cli/doctor.harn",
342    "echo" => "stdlib/cli/echo.harn",
343    // Helper module for the embedded `eval/*` scripts. Has a stub `main`
344    // that exits non-zero — sibling scripts inline its helpers until the
345    // dispatch wedge gains a cross-script import surface (#2300 / G7).
346    "eval/_runner" => "stdlib/cli/eval/_runner.harn",
347    "eval/context" => "stdlib/cli/eval/context.harn",
348    "eval/model_selector" => "stdlib/cli/eval/model_selector.harn",
349    "eval/tool_calls" => "stdlib/cli/eval/tool_calls.harn",
350    "eval/coding_agent" => "stdlib/cli/eval/coding_agent.harn",
351    "eval/scope_triage" => "stdlib/cli/eval/scope_triage.harn",
352    "eval/prompt" => "stdlib/cli/eval/prompt.harn",
353    "explain" => "stdlib/cli/explain.harn",
354    "graph" => "stdlib/cli/graph.harn",
355    "personas/compile_prompt" => "stdlib/cli/personas/compile_prompt.harn",
356    "personas/materialize" => "stdlib/cli/personas/materialize.harn",
357    "models/batch_plan" => "stdlib/cli/models/batch_plan.harn",
358    "models/list" => "stdlib/cli/models/list.harn",
359    "models/lora_inspect" => "stdlib/cli/models/lora_inspect.harn",
360    "models/lora_export" => "stdlib/cli/models/lora_export.harn",
361    "models/lora_manifest" => "stdlib/cli/models/lora_manifest.harn",
362    "models/lora_preflight" => "stdlib/cli/models/lora_preflight.harn",
363    "models/lora_promote" => "stdlib/cli/models/lora_promote.harn",
364    "models/lora_plan" => "stdlib/cli/models/lora_plan.harn",
365    "models/lora_train" => "stdlib/cli/models/lora_train.harn",
366    "models/recommend" => "stdlib/cli/models/recommend.harn",
367    "models/test" => "stdlib/cli/models/test.harn",
368    "precompile" => "stdlib/cli/precompile.harn",
369    "providers/cache_probe" => "stdlib/cli/providers/cache_probe.harn",
370    "providers/catalog" => "stdlib/cli/providers/catalog.harn",
371    "providers/probe" => "stdlib/cli/providers/probe.harn",
372    "providers/recommend" => "stdlib/cli/providers/recommend.harn",
373    "providers/tool_probe" => "stdlib/cli/providers/tool_probe.harn",
374    "providers/tool_scorecard" => "stdlib/cli/providers/tool_scorecard.harn",
375    "routes" => "stdlib/cli/routes.harn",
376    "scan" => "stdlib/cli/scan.harn",
377    "scaffold/init" => "stdlib/cli/scaffold/init.harn",
378    "scaffold/tool_new" => "stdlib/cli/scaffold/tool_new.harn",
379    "trace_import" => "stdlib/cli/trace_import.harn",
380    "try" => "stdlib/cli/try.harn",
381    "version" => "stdlib/cli/version.harn",
382]);
383
384pub fn get_stdlib_source(module: &str) -> Option<&'static str> {
385    STDLIB_SOURCES
386        .iter()
387        .find_map(|entry| (entry.module == module).then_some(entry.source))
388}
389
390/// Builtins a stdlib module re-exports under its own name, so
391/// `import { assert_eq } from "std/testing"` resolves.
392///
393/// Some of the standard library is implemented in Rust rather than Harn — the
394/// value differ behind `assert_eq` needs to walk the runtime representation of
395/// a value, which Harn source cannot do. Those builtins are callable without an
396/// import, but a reader who has just typed `import { assert_throws } from
397/// "std/testing"` has every reason to expect its sibling `assert_eq` to come
398/// from the same place, and no reason to know which side of the Rust/Harn line
399/// a given assertion happens to fall on. This table erases that seam: the
400/// module's export surface is its `pub fn`s plus the names listed here.
401///
402/// The list is explicit rather than derived from the builtins' `category`
403/// metadata: a category is a free-form label for docs and observability, and an
404/// export surface is an API contract. Deriving one from the other would let an
405/// unrelated metadata edit silently add or remove a public export.
406///
407/// `harn_vm::stdlib::tests` pins every name here to a registered builtin, so an
408/// entry cannot rot into a name that no longer exists.
409pub fn builtin_reexports(module: &str) -> &'static [&'static str] {
410    match module {
411        "testing" => &[
412            "assert",
413            "assert_approx",
414            "assert_eq",
415            "assert_matches",
416            "assert_ne",
417            "value_diff",
418        ],
419        _ => &[],
420    }
421}
422
423/// Find an embedded CLI subcommand script by name. Returns the embedded
424/// source string when present, or `None` if no script with that name is
425/// registered in [`STDLIB_CLI_SCRIPTS`].
426pub fn find_cli_script(name: &str) -> Option<&'static str> {
427    STDLIB_CLI_SCRIPTS
428        .iter()
429        .find_map(|entry| (entry.name == name).then_some(entry.source))
430}
431
432pub fn get_stdlib_prompt_asset(path: &str) -> Option<&'static str> {
433    let path = path.strip_prefix("std/").unwrap_or(path);
434    STDLIB_PROMPT_ASSETS
435        .iter()
436        .find_map(|entry| (entry.path == path).then_some(entry.source))
437}
438
439pub fn public_functions_for_module(module: &str) -> Vec<StdlibPublicFunction> {
440    let Some(source) = get_stdlib_source(module) else {
441        return Vec::new();
442    };
443    public_functions_from_source(source)
444}
445
446pub fn entrypoint_modules() -> Vec<StdlibEntrypointModule> {
447    STDLIB_SOURCES
448        .iter()
449        .filter_map(|entry| {
450            entrypoint_category_from_source(entry.source).map(|category| StdlibEntrypointModule {
451                import_path: format!("std/{}", entry.module),
452                category,
453            })
454        })
455        .collect()
456}
457
458fn entrypoint_category_from_source(source: &str) -> Option<String> {
459    for line in source.lines() {
460        let line = line.trim();
461        if line.is_empty() {
462            continue;
463        }
464        if let Some(category) = line.strip_prefix("// @harn-entrypoint-category ") {
465            let category = category.trim();
466            return (!category.is_empty()).then(|| category.to_string());
467        }
468        if !line.starts_with("//") {
469            return None;
470        }
471    }
472    None
473}
474
475fn public_functions_from_source(source: &str) -> Vec<StdlibPublicFunction> {
476    let mut out = Vec::new();
477    let mut doc: Option<String> = None;
478    let lines = source.lines().collect::<Vec<_>>();
479    let mut index = 0usize;
480    while index < lines.len() {
481        let line = lines[index].trim();
482        if line.starts_with("/**") {
483            let (parsed, next) = parse_harndoc(&lines, index);
484            doc = parsed;
485            index = next;
486            continue;
487        }
488        if line.starts_with("pub fn ") {
489            let (signature_line, next) = collect_public_function_signature(&lines, index);
490            if let Some(function) = parse_public_function_line(&signature_line, doc.take()) {
491                out.push(function);
492                index = next;
493                continue;
494            }
495        }
496        if let Some(function) = parse_public_function_line(line, doc.take()) {
497            out.push(function);
498        } else if !line.is_empty() && !line.starts_with("//") {
499            doc = None;
500        }
501        index += 1;
502    }
503    out
504}
505
506fn collect_public_function_signature(lines: &[&str], start: usize) -> (String, usize) {
507    let mut parts = Vec::new();
508    let mut index = start;
509    while index < lines.len() {
510        parts.push(lines[index].trim().to_string());
511        let candidate = parts.join(" ");
512        if public_function_signature_complete(&candidate) {
513            return (candidate, index + 1);
514        }
515        index += 1;
516    }
517    (parts.join(" "), index)
518}
519
520fn public_function_signature_complete(line: &str) -> bool {
521    let Some(rest) = line.strip_prefix("pub fn ") else {
522        return false;
523    };
524    let Some(name_end) = rest.find('(') else {
525        return false;
526    };
527    matching_paren_len(&rest[name_end + 1..]).is_some()
528}
529
530fn parse_harndoc(lines: &[&str], start: usize) -> (Option<String>, usize) {
531    let mut parts = Vec::new();
532    let mut index = start;
533    while index < lines.len() {
534        let mut line = lines[index].trim();
535        if index == start {
536            line = line.trim_start_matches("/**").trim();
537        }
538        let done = line.ends_with("*/");
539        line = line.trim_end_matches("*/").trim();
540        line = line.trim_start_matches('*').trim();
541        if !line.is_empty() {
542            parts.push(line.to_string());
543        }
544        index += 1;
545        if done {
546            break;
547        }
548    }
549    let text = parts.join("\n").trim().to_string();
550    ((!text.is_empty()).then_some(text), index)
551}
552
553fn parse_public_function_line(line: &str, doc: Option<String>) -> Option<StdlibPublicFunction> {
554    let rest = line.strip_prefix("pub fn ")?.trim();
555    let name_end = rest.find('(')?;
556    let name = rest[..name_end].trim();
557    if name.is_empty() {
558        return None;
559    }
560    let params_start = name_end + 1;
561    let params_len = matching_paren_len(&rest[params_start..])?;
562    let params = &rest[params_start..params_start + params_len];
563    let after = rest[params_start + params_len + 1..].trim();
564    let return_type = after
565        .strip_prefix("->")
566        .and_then(|tail| tail.split('{').next())
567        .map(str::trim)
568        .filter(|value| !value.is_empty());
569    let signature = match return_type {
570        Some(ret) => format!("{name}({params}) -> {ret}"),
571        None => format!("{name}({params})"),
572    };
573    let param_parts = split_top_level_params(params);
574    let total_params = param_parts
575        .iter()
576        .filter(|param| !param.trim().is_empty())
577        .count();
578    let variadic = param_parts
579        .iter()
580        .any(|param| param.trim_start().starts_with("..."));
581    let required_params = param_parts
582        .iter()
583        .filter(|param| {
584            let param = param.trim();
585            !param.is_empty() && !param.contains('=') && !param.starts_with("...")
586        })
587        .count();
588    Some(StdlibPublicFunction {
589        name: name.to_string(),
590        signature,
591        required_params,
592        total_params,
593        variadic,
594        doc,
595    })
596}
597
598fn matching_paren_len(input: &str) -> Option<usize> {
599    let mut depth = 1usize;
600    for (offset, ch) in input.char_indices() {
601        match ch {
602            '(' | '[' | '{' => depth += 1,
603            ')' | ']' | '}' => {
604                depth = depth.saturating_sub(1);
605                if depth == 0 {
606                    return Some(offset);
607                }
608            }
609            _ => {}
610        }
611    }
612    None
613}
614
615fn split_top_level_params(params: &str) -> Vec<&str> {
616    let mut out = Vec::new();
617    let mut depth = 0isize;
618    let mut start = 0usize;
619    for (offset, ch) in params.char_indices() {
620        match ch {
621            '(' | '[' | '{' => depth += 1,
622            ')' | ']' | '}' => depth -= 1,
623            ',' if depth == 0 => {
624                out.push(&params[start..offset]);
625                start = offset + 1;
626            }
627            _ => {}
628        }
629    }
630    out.push(&params[start..]);
631    out
632}
633
634#[cfg(test)]
635mod tests {
636    use std::collections::BTreeSet;
637
638    use super::{
639        entrypoint_modules, find_cli_script, get_stdlib_prompt_asset, get_stdlib_source,
640        matching_paren_len, parse_public_function_line, public_functions_for_module,
641        STDLIB_CLI_SCRIPTS, STDLIB_PROMPT_ASSETS, STDLIB_SOURCES,
642    };
643
644    #[test]
645    fn stdlib_sources_are_non_empty() {
646        for entry in STDLIB_SOURCES {
647            assert!(
648                !entry.source.trim().is_empty(),
649                "{} should have non-empty source",
650                entry.module
651            );
652        }
653    }
654
655    #[test]
656    fn cli_scripts_are_non_empty_and_uniquely_named() {
657        let mut seen = BTreeSet::new();
658        for entry in STDLIB_CLI_SCRIPTS {
659            assert!(
660                !entry.source.trim().is_empty(),
661                "cli/{} should have non-empty source",
662                entry.name
663            );
664            assert!(
665                seen.insert(entry.name),
666                "cli/{} is registered more than once in STDLIB_CLI_SCRIPTS",
667                entry.name
668            );
669        }
670    }
671
672    #[test]
673    fn find_cli_script_round_trips() {
674        for entry in STDLIB_CLI_SCRIPTS {
675            assert_eq!(find_cli_script(entry.name), Some(entry.source));
676        }
677        assert!(find_cli_script("not-a-real-script").is_none());
678    }
679
680    #[test]
681    fn stdlib_source_names_are_unique() {
682        let mut names = BTreeSet::new();
683        for entry in STDLIB_SOURCES {
684            assert!(names.insert(entry.module), "duplicate {}", entry.module);
685        }
686    }
687
688    #[test]
689    fn stdlib_prompt_assets_are_non_empty() {
690        for entry in STDLIB_PROMPT_ASSETS {
691            assert!(
692                !entry.source.trim().is_empty(),
693                "{} should have non-empty prompt asset source",
694                entry.path
695            );
696        }
697    }
698
699    #[test]
700    fn stdlib_prompt_asset_paths_are_unique() {
701        let mut paths = BTreeSet::new();
702        for entry in STDLIB_PROMPT_ASSETS {
703            assert!(paths.insert(entry.path), "duplicate {}", entry.path);
704        }
705    }
706
707    #[test]
708    fn key_stdlib_modules_resolve() {
709        for module in [
710            "context",
711            "context/maintenance",
712            "context/eval",
713            "eval/stats",
714            "eval/agreement",
715            "edit",
716            "verification",
717            "disclosure",
718            "artifact/web",
719            "command",
720            "waitpoint",
721            "llm/handlers",
722            "llm/tool_middleware",
723            "llm/tool_binder",
724            "llm/missing_tool_call",
725            "llm/ensemble",
726            "llm/rerank",
727            "personas/prelude",
728            "personas/bulletins",
729            "agent/host_tools",
730            "agent/host_injection",
731            "agent/user",
732            "agent/governors",
733            "agent/guardrails",
734            "cli/models/batch_artifacts",
735            "cli/models/batch_cancel",
736            "cli/models/batch_download",
737            "cli/models/batch_lifecycle",
738            "cli/models/batch_status",
739            "cli/models/batch_submit",
740            "cli/models/batch_transport",
741            "cli/models/lora_render",
742            "llm/optimize",
743            "llm/judge",
744            "llm/faithfulness",
745            "llm/refine",
746            "connectors/shared",
747            "connectors/github",
748            "connectors/linear",
749            "connectors/notion",
750            "connectors/slack",
751            "triage",
752            "dashboard/jobs",
753            "ui_resource",
754        ] {
755            assert!(
756                get_stdlib_source(module).is_some(),
757                "std/{module} should resolve"
758            );
759        }
760    }
761
762    #[test]
763    fn key_stdlib_prompt_assets_resolve() {
764        for path in [
765            "std/agent/prompts/tool_contract_text.harn.prompt",
766            "std/agent/prompts/default_nudge.harn.prompt",
767            "std/agent/prompts/completion_judge_default.harn.prompt",
768            "std/workflow/prompts/stage.harn.prompt",
769            "std/orchestration/prompts/compaction_summary.harn.prompt",
770            "std/orchestration/prompts/compaction_policy_replacement.harn.prompt",
771        ] {
772            assert!(
773                get_stdlib_prompt_asset(path).is_some(),
774                "{path} should resolve"
775            );
776        }
777    }
778
779    #[test]
780    fn public_function_catalog_derives_signatures_from_harn_source() {
781        let exports = public_functions_for_module("workflow/execute");
782        assert_eq!(exports.len(), 1);
783        assert_eq!(exports[0].name, "workflow_execute");
784        assert_eq!(
785            exports[0].signature,
786            "workflow_execute(task, graph, artifacts = nil, options = nil)"
787        );
788        assert_eq!(exports[0].required_params, 2);
789        assert_eq!(exports[0].total_params, 4);
790    }
791
792    #[test]
793    fn command_stdlib_module_exports_step_helpers() {
794        let exports = public_functions_for_module("command")
795            .into_iter()
796            .map(|function| function.name)
797            .collect::<BTreeSet<_>>();
798        for name in [
799            "command_run",
800            "command_wait",
801            "command_cancel",
802            "command_run_streaming",
803            "command_output_tail",
804            "command_json",
805            "command_json_step",
806            "command_try",
807            "command_step",
808            "command_steps_append",
809            "command_last_failed_step",
810            "command_step_ref",
811        ] {
812            assert!(exports.contains(name), "std/command should export {name}");
813        }
814    }
815
816    #[test]
817    fn disclosure_stdlib_module_exports_render_helpers() {
818        let exports = public_functions_for_module("disclosure")
819            .into_iter()
820            .map(|function| function.name)
821            .collect::<BTreeSet<_>>();
822        assert!(
823            exports.contains("render"),
824            "std/disclosure should export render"
825        );
826        assert!(
827            exports.contains("git_trailers"),
828            "std/disclosure should export git_trailers"
829        );
830        assert!(
831            exports.contains("slack_message_disclosure"),
832            "std/disclosure should export slack_message_disclosure"
833        );
834        assert!(
835            exports.contains("append_git_trailers"),
836            "std/disclosure should export append_git_trailers"
837        );
838    }
839
840    #[test]
841    fn async_stdlib_exports_predicate_backoff_name_only() {
842        let exports = public_functions_for_module("async")
843            .into_iter()
844            .map(|function| function.name)
845            .collect::<BTreeSet<_>>();
846        assert!(
847            exports.contains("retry_predicate_with_backoff"),
848            "std/async should export retry_predicate_with_backoff"
849        );
850        assert!(
851            !exports.contains("retry_with_backoff"),
852            "std/async should not retain the old retry_with_backoff export"
853        );
854    }
855
856    #[test]
857    fn signal_stdlib_module_exports_interrupt_helpers() {
858        let exports = public_functions_for_module("signal")
859            .into_iter()
860            .map(|function| function.name)
861            .collect::<BTreeSet<_>>();
862        for name in [
863            "on_interrupt",
864            "off_interrupt",
865            "interrupted",
866            "with_interrupt",
867        ] {
868            assert!(exports.contains(name), "std/signal should export {name}");
869        }
870    }
871
872    #[test]
873    fn git_stdlib_module_exports_local_wrappers() {
874        let exports = public_functions_for_module("git")
875            .into_iter()
876            .map(|function| function.name)
877            .collect::<BTreeSet<_>>();
878        for name in [
879            "git_run",
880            "git_status",
881            "git_current_branch",
882            "git_log",
883            "git_switch",
884            "git_pull_ff_only",
885            "git_find_tool",
886            "git_run_tool",
887            "git_tools",
888            "git_toolbox_tools",
889        ] {
890            assert!(exports.contains(name), "std/git should export {name}");
891        }
892    }
893
894    #[test]
895    fn agent_workers_exports_suspend_resume_wrappers() {
896        let exports = public_functions_for_module("agent/workers");
897        let suspend = exports
898            .iter()
899            .find(|function| function.name == "suspend_agent")
900            .expect("std/agent/workers should export suspend_agent");
901        assert_eq!(
902            suspend.signature,
903            "suspend_agent(worker, reason = \"\", options = nil)"
904        );
905        assert_eq!(suspend.required_params, 1);
906        assert_eq!(suspend.total_params, 3);
907
908        let resume = exports
909            .iter()
910            .find(|function| function.name == "resume_agent")
911            .expect("std/agent/workers should export resume_agent");
912        assert_eq!(
913            resume.signature,
914            "resume_agent(worker_or_snapshot, resume_input = nil, continue_transcript = true)"
915        );
916        assert_eq!(resume.required_params, 1);
917        assert_eq!(resume.total_params, 3);
918
919        let stop = exports
920            .iter()
921            .find(|function| function.name == "agent_stop")
922            .expect("std/agent/workers should export agent_stop");
923        assert_eq!(
924            stop.signature,
925            "agent_stop(worker, options: AgentStopOptions = nil)"
926        );
927        assert_eq!(stop.required_params, 1);
928        assert_eq!(stop.total_params, 2);
929
930        let parse_resume = exports
931            .iter()
932            .find(|function| function.name == "parse_resume_conditions")
933            .expect("std/agent/workers should export parse_resume_conditions");
934        assert_eq!(
935            parse_resume.signature,
936            "parse_resume_conditions(conditions = nil) -> ResumeConditions?"
937        );
938        assert_eq!(parse_resume.required_params, 0);
939        assert_eq!(parse_resume.total_params, 1);
940
941        let lifecycle = exports
942            .iter()
943            .find(|function| function.name == "agent_lifecycle_tools")
944            .expect("std/agent/workers should export agent_lifecycle_tools");
945        assert_eq!(
946            lifecycle.signature,
947            "agent_lifecycle_tools(registry = nil, options = nil)"
948        );
949        assert_eq!(lifecycle.required_params, 0);
950        assert_eq!(lifecycle.total_params, 2);
951    }
952
953    #[test]
954    fn tui_stdlib_module_exports_terminal_helpers() {
955        let exports = public_functions_for_module("tui")
956            .into_iter()
957            .map(|function| function.name)
958            .collect::<BTreeSet<_>>();
959        for name in ["page", "terminal_width", "rule", "clear", "select_from"] {
960            assert!(exports.contains(name), "std/tui should export {name}");
961        }
962    }
963
964    #[test]
965    fn semver_stdlib_module_exports_release_helpers() {
966        let exports = public_functions_for_module("semver")
967            .into_iter()
968            .map(|function| function.name)
969            .collect::<BTreeSet<_>>();
970        for name in [
971            "strip_v",
972            "add_v",
973            "is_v_semver",
974            "parse",
975            "next",
976            "bump_type",
977            "version_from_release_branch",
978            "version_from_tag",
979        ] {
980            assert!(exports.contains(name), "std/semver should export {name}");
981        }
982    }
983
984    #[test]
985    fn text_stdlib_module_exports_regex_and_pad_helpers() {
986        let exports = public_functions_for_module("text")
987            .into_iter()
988            .map(|function| function.name)
989            .collect::<BTreeSet<_>>();
990        for name in [
991            "pad_left",
992            "pad_right",
993            "repeat_string",
994            "regex_first_capture",
995            "regex_capture_groups",
996            "regex_all_first_captures",
997        ] {
998            assert!(exports.contains(name), "std/text should export {name}");
999        }
1000    }
1001
1002    #[test]
1003    fn harn_entrypoint_catalog_is_declared_by_stdlib_sources() {
1004        let modules = entrypoint_modules();
1005        let entries = modules
1006            .iter()
1007            .map(|module| (module.import_path.as_str(), module.category.as_str()))
1008            .collect::<BTreeSet<_>>();
1009        for entry in [
1010            ("std/agent/loop", "agent.stdlib"),
1011            ("std/agent/turn", "agent.stdlib"),
1012            ("std/agent/primitives", "agent.stdlib"),
1013            ("std/workflow/execute", "workflow.stdlib"),
1014        ] {
1015            assert!(entries.contains(&entry), "{entry:?} should be declared");
1016        }
1017    }
1018
1019    #[test]
1020    fn matching_paren_len_closes_on_every_bracket_kind() {
1021        // Each closer kind must terminate the scan once depth returns to zero,
1022        // mirroring the symmetric opener arm and `split_top_level_params`.
1023        assert_eq!(matching_paren_len("a, b)"), Some(4));
1024        assert_eq!(matching_paren_len("x: [int])"), Some(8));
1025        assert_eq!(matching_paren_len("x: {a: int})"), Some(11));
1026        // A top-level `]`/`}` is the matching close for the consumed opener and
1027        // must return rather than scanning to the end and yielding `None`.
1028        assert_eq!(matching_paren_len("x]"), Some(1));
1029        assert_eq!(matching_paren_len("x}"), Some(1));
1030        assert_eq!(matching_paren_len("unterminated"), None);
1031    }
1032
1033    #[test]
1034    fn parse_public_function_line_handles_record_typed_params() {
1035        let parsed =
1036            parse_public_function_line("pub fn configure(opts: {retries: int}) -> bool", None)
1037                .expect("signature with a record-typed parameter should parse");
1038        assert_eq!(parsed.name, "configure");
1039        assert_eq!(parsed.signature, "configure(opts: {retries: int}) -> bool");
1040        assert_eq!(parsed.total_params, 1);
1041        assert_eq!(parsed.required_params, 1);
1042    }
1043}