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