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