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