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    "models/batch_plan" => "stdlib/cli/models/batch_plan.harn",
351    "models/list" => "stdlib/cli/models/list.harn",
352    "models/lora_inspect" => "stdlib/cli/models/lora_inspect.harn",
353    "models/lora_export" => "stdlib/cli/models/lora_export.harn",
354    "models/lora_manifest" => "stdlib/cli/models/lora_manifest.harn",
355    "models/lora_preflight" => "stdlib/cli/models/lora_preflight.harn",
356    "models/lora_promote" => "stdlib/cli/models/lora_promote.harn",
357    "models/lora_plan" => "stdlib/cli/models/lora_plan.harn",
358    "models/lora_train" => "stdlib/cli/models/lora_train.harn",
359    "models/recommend" => "stdlib/cli/models/recommend.harn",
360    "models/test" => "stdlib/cli/models/test.harn",
361    "precompile" => "stdlib/cli/precompile.harn",
362    "providers/cache_probe" => "stdlib/cli/providers/cache_probe.harn",
363    "providers/catalog" => "stdlib/cli/providers/catalog.harn",
364    "providers/probe" => "stdlib/cli/providers/probe.harn",
365    "providers/recommend" => "stdlib/cli/providers/recommend.harn",
366    "providers/tool_probe" => "stdlib/cli/providers/tool_probe.harn",
367    "providers/tool_scorecard" => "stdlib/cli/providers/tool_scorecard.harn",
368    "routes" => "stdlib/cli/routes.harn",
369    "scan" => "stdlib/cli/scan.harn",
370    "scaffold/init" => "stdlib/cli/scaffold/init.harn",
371    "scaffold/tool_new" => "stdlib/cli/scaffold/tool_new.harn",
372    "trace_import" => "stdlib/cli/trace_import.harn",
373    "try" => "stdlib/cli/try.harn",
374    "version" => "stdlib/cli/version.harn",
375]);
376
377pub fn get_stdlib_source(module: &str) -> Option<&'static str> {
378    STDLIB_SOURCES
379        .iter()
380        .find_map(|entry| (entry.module == module).then_some(entry.source))
381}
382
383/// Find an embedded CLI subcommand script by name. Returns the embedded
384/// source string when present, or `None` if no script with that name is
385/// registered in [`STDLIB_CLI_SCRIPTS`].
386pub fn find_cli_script(name: &str) -> Option<&'static str> {
387    STDLIB_CLI_SCRIPTS
388        .iter()
389        .find_map(|entry| (entry.name == name).then_some(entry.source))
390}
391
392pub fn get_stdlib_prompt_asset(path: &str) -> Option<&'static str> {
393    let path = path.strip_prefix("std/").unwrap_or(path);
394    STDLIB_PROMPT_ASSETS
395        .iter()
396        .find_map(|entry| (entry.path == path).then_some(entry.source))
397}
398
399pub fn public_functions_for_module(module: &str) -> Vec<StdlibPublicFunction> {
400    let Some(source) = get_stdlib_source(module) else {
401        return Vec::new();
402    };
403    public_functions_from_source(source)
404}
405
406pub fn entrypoint_modules() -> Vec<StdlibEntrypointModule> {
407    STDLIB_SOURCES
408        .iter()
409        .filter_map(|entry| {
410            entrypoint_category_from_source(entry.source).map(|category| StdlibEntrypointModule {
411                import_path: format!("std/{}", entry.module),
412                category,
413            })
414        })
415        .collect()
416}
417
418fn entrypoint_category_from_source(source: &str) -> Option<String> {
419    for line in source.lines() {
420        let line = line.trim();
421        if line.is_empty() {
422            continue;
423        }
424        if let Some(category) = line.strip_prefix("// @harn-entrypoint-category ") {
425            let category = category.trim();
426            return (!category.is_empty()).then(|| category.to_string());
427        }
428        if !line.starts_with("//") {
429            return None;
430        }
431    }
432    None
433}
434
435fn public_functions_from_source(source: &str) -> Vec<StdlibPublicFunction> {
436    let mut out = Vec::new();
437    let mut doc: Option<String> = None;
438    let lines = source.lines().collect::<Vec<_>>();
439    let mut index = 0usize;
440    while index < lines.len() {
441        let line = lines[index].trim();
442        if line.starts_with("/**") {
443            let (parsed, next) = parse_harndoc(&lines, index);
444            doc = parsed;
445            index = next;
446            continue;
447        }
448        if line.starts_with("pub fn ") {
449            let (signature_line, next) = collect_public_function_signature(&lines, index);
450            if let Some(function) = parse_public_function_line(&signature_line, doc.take()) {
451                out.push(function);
452                index = next;
453                continue;
454            }
455        }
456        if let Some(function) = parse_public_function_line(line, doc.take()) {
457            out.push(function);
458        } else if !line.is_empty() && !line.starts_with("//") {
459            doc = None;
460        }
461        index += 1;
462    }
463    out
464}
465
466fn collect_public_function_signature(lines: &[&str], start: usize) -> (String, usize) {
467    let mut parts = Vec::new();
468    let mut index = start;
469    while index < lines.len() {
470        parts.push(lines[index].trim().to_string());
471        let candidate = parts.join(" ");
472        if public_function_signature_complete(&candidate) {
473            return (candidate, index + 1);
474        }
475        index += 1;
476    }
477    (parts.join(" "), index)
478}
479
480fn public_function_signature_complete(line: &str) -> bool {
481    let Some(rest) = line.strip_prefix("pub fn ") else {
482        return false;
483    };
484    let Some(name_end) = rest.find('(') else {
485        return false;
486    };
487    matching_paren_len(&rest[name_end + 1..]).is_some()
488}
489
490fn parse_harndoc(lines: &[&str], start: usize) -> (Option<String>, usize) {
491    let mut parts = Vec::new();
492    let mut index = start;
493    while index < lines.len() {
494        let mut line = lines[index].trim();
495        if index == start {
496            line = line.trim_start_matches("/**").trim();
497        }
498        let done = line.ends_with("*/");
499        line = line.trim_end_matches("*/").trim();
500        line = line.trim_start_matches('*').trim();
501        if !line.is_empty() {
502            parts.push(line.to_string());
503        }
504        index += 1;
505        if done {
506            break;
507        }
508    }
509    let text = parts.join("\n").trim().to_string();
510    ((!text.is_empty()).then_some(text), index)
511}
512
513fn parse_public_function_line(line: &str, doc: Option<String>) -> Option<StdlibPublicFunction> {
514    let rest = line.strip_prefix("pub fn ")?.trim();
515    let name_end = rest.find('(')?;
516    let name = rest[..name_end].trim();
517    if name.is_empty() {
518        return None;
519    }
520    let params_start = name_end + 1;
521    let params_len = matching_paren_len(&rest[params_start..])?;
522    let params = &rest[params_start..params_start + params_len];
523    let after = rest[params_start + params_len + 1..].trim();
524    let return_type = after
525        .strip_prefix("->")
526        .and_then(|tail| tail.split('{').next())
527        .map(str::trim)
528        .filter(|value| !value.is_empty());
529    let signature = match return_type {
530        Some(ret) => format!("{name}({params}) -> {ret}"),
531        None => format!("{name}({params})"),
532    };
533    let param_parts = split_top_level_params(params);
534    let total_params = param_parts
535        .iter()
536        .filter(|param| !param.trim().is_empty())
537        .count();
538    let variadic = param_parts
539        .iter()
540        .any(|param| param.trim_start().starts_with("..."));
541    let required_params = param_parts
542        .iter()
543        .filter(|param| {
544            let param = param.trim();
545            !param.is_empty() && !param.contains('=') && !param.starts_with("...")
546        })
547        .count();
548    Some(StdlibPublicFunction {
549        name: name.to_string(),
550        signature,
551        required_params,
552        total_params,
553        variadic,
554        doc,
555    })
556}
557
558fn matching_paren_len(input: &str) -> Option<usize> {
559    let mut depth = 1usize;
560    for (offset, ch) in input.char_indices() {
561        match ch {
562            '(' | '[' | '{' => depth += 1,
563            ')' | ']' | '}' => {
564                depth = depth.saturating_sub(1);
565                if depth == 0 {
566                    return Some(offset);
567                }
568            }
569            _ => {}
570        }
571    }
572    None
573}
574
575fn split_top_level_params(params: &str) -> Vec<&str> {
576    let mut out = Vec::new();
577    let mut depth = 0isize;
578    let mut start = 0usize;
579    for (offset, ch) in params.char_indices() {
580        match ch {
581            '(' | '[' | '{' => depth += 1,
582            ')' | ']' | '}' => depth -= 1,
583            ',' if depth == 0 => {
584                out.push(&params[start..offset]);
585                start = offset + 1;
586            }
587            _ => {}
588        }
589    }
590    out.push(&params[start..]);
591    out
592}
593
594#[cfg(test)]
595mod tests {
596    use std::collections::BTreeSet;
597
598    use super::{
599        entrypoint_modules, find_cli_script, get_stdlib_prompt_asset, get_stdlib_source,
600        matching_paren_len, parse_public_function_line, public_functions_for_module,
601        STDLIB_CLI_SCRIPTS, STDLIB_PROMPT_ASSETS, STDLIB_SOURCES,
602    };
603
604    #[test]
605    fn stdlib_sources_are_non_empty() {
606        for entry in STDLIB_SOURCES {
607            assert!(
608                !entry.source.trim().is_empty(),
609                "{} should have non-empty source",
610                entry.module
611            );
612        }
613    }
614
615    #[test]
616    fn cli_scripts_are_non_empty_and_uniquely_named() {
617        let mut seen = BTreeSet::new();
618        for entry in STDLIB_CLI_SCRIPTS {
619            assert!(
620                !entry.source.trim().is_empty(),
621                "cli/{} should have non-empty source",
622                entry.name
623            );
624            assert!(
625                seen.insert(entry.name),
626                "cli/{} is registered more than once in STDLIB_CLI_SCRIPTS",
627                entry.name
628            );
629        }
630    }
631
632    #[test]
633    fn find_cli_script_round_trips() {
634        for entry in STDLIB_CLI_SCRIPTS {
635            assert_eq!(find_cli_script(entry.name), Some(entry.source));
636        }
637        assert!(find_cli_script("not-a-real-script").is_none());
638    }
639
640    #[test]
641    fn stdlib_source_names_are_unique() {
642        let mut names = BTreeSet::new();
643        for entry in STDLIB_SOURCES {
644            assert!(names.insert(entry.module), "duplicate {}", entry.module);
645        }
646    }
647
648    #[test]
649    fn stdlib_prompt_assets_are_non_empty() {
650        for entry in STDLIB_PROMPT_ASSETS {
651            assert!(
652                !entry.source.trim().is_empty(),
653                "{} should have non-empty prompt asset source",
654                entry.path
655            );
656        }
657    }
658
659    #[test]
660    fn stdlib_prompt_asset_paths_are_unique() {
661        let mut paths = BTreeSet::new();
662        for entry in STDLIB_PROMPT_ASSETS {
663            assert!(paths.insert(entry.path), "duplicate {}", entry.path);
664        }
665    }
666
667    #[test]
668    fn key_stdlib_modules_resolve() {
669        for module in [
670            "context",
671            "context/maintenance",
672            "context/eval",
673            "eval/stats",
674            "eval/agreement",
675            "edit",
676            "verification",
677            "disclosure",
678            "artifact/web",
679            "command",
680            "waitpoint",
681            "llm/handlers",
682            "llm/tool_middleware",
683            "llm/tool_binder",
684            "llm/missing_tool_call",
685            "llm/ensemble",
686            "llm/rerank",
687            "personas/prelude",
688            "personas/bulletins",
689            "agent/host_tools",
690            "agent/host_injection",
691            "agent/user",
692            "agent/governors",
693            "agent/guardrails",
694            "cli/models/batch_artifacts",
695            "cli/models/batch_cancel",
696            "cli/models/batch_download",
697            "cli/models/batch_lifecycle",
698            "cli/models/batch_status",
699            "cli/models/batch_submit",
700            "cli/models/batch_transport",
701            "cli/models/lora_render",
702            "llm/optimize",
703            "llm/judge",
704            "llm/faithfulness",
705            "llm/refine",
706            "connectors/shared",
707            "connectors/github",
708            "connectors/linear",
709            "connectors/notion",
710            "connectors/slack",
711            "triage",
712            "dashboard/jobs",
713            "ui_resource",
714        ] {
715            assert!(
716                get_stdlib_source(module).is_some(),
717                "std/{module} should resolve"
718            );
719        }
720    }
721
722    #[test]
723    fn key_stdlib_prompt_assets_resolve() {
724        for path in [
725            "std/agent/prompts/tool_contract_text.harn.prompt",
726            "std/agent/prompts/default_nudge.harn.prompt",
727            "std/agent/prompts/completion_judge_default.harn.prompt",
728            "std/workflow/prompts/stage.harn.prompt",
729            "std/orchestration/prompts/compaction_summary.harn.prompt",
730            "std/orchestration/prompts/compaction_policy_replacement.harn.prompt",
731        ] {
732            assert!(
733                get_stdlib_prompt_asset(path).is_some(),
734                "{path} should resolve"
735            );
736        }
737    }
738
739    #[test]
740    fn public_function_catalog_derives_signatures_from_harn_source() {
741        let exports = public_functions_for_module("workflow/execute");
742        assert_eq!(exports.len(), 1);
743        assert_eq!(exports[0].name, "workflow_execute");
744        assert_eq!(
745            exports[0].signature,
746            "workflow_execute(task, graph, artifacts = nil, options = nil)"
747        );
748        assert_eq!(exports[0].required_params, 2);
749        assert_eq!(exports[0].total_params, 4);
750    }
751
752    #[test]
753    fn command_stdlib_module_exports_step_helpers() {
754        let exports = public_functions_for_module("command")
755            .into_iter()
756            .map(|function| function.name)
757            .collect::<BTreeSet<_>>();
758        for name in [
759            "command_run",
760            "command_wait",
761            "command_cancel",
762            "command_run_streaming",
763            "command_output_tail",
764            "command_json",
765            "command_json_step",
766            "command_try",
767            "command_step",
768            "command_steps_append",
769            "command_last_failed_step",
770            "command_step_ref",
771        ] {
772            assert!(exports.contains(name), "std/command should export {name}");
773        }
774    }
775
776    #[test]
777    fn disclosure_stdlib_module_exports_render_helpers() {
778        let exports = public_functions_for_module("disclosure")
779            .into_iter()
780            .map(|function| function.name)
781            .collect::<BTreeSet<_>>();
782        assert!(
783            exports.contains("render"),
784            "std/disclosure should export render"
785        );
786        assert!(
787            exports.contains("git_trailers"),
788            "std/disclosure should export git_trailers"
789        );
790        assert!(
791            exports.contains("slack_message_disclosure"),
792            "std/disclosure should export slack_message_disclosure"
793        );
794        assert!(
795            exports.contains("append_git_trailers"),
796            "std/disclosure should export append_git_trailers"
797        );
798    }
799
800    #[test]
801    fn async_stdlib_exports_predicate_backoff_name_only() {
802        let exports = public_functions_for_module("async")
803            .into_iter()
804            .map(|function| function.name)
805            .collect::<BTreeSet<_>>();
806        assert!(
807            exports.contains("retry_predicate_with_backoff"),
808            "std/async should export retry_predicate_with_backoff"
809        );
810        assert!(
811            !exports.contains("retry_with_backoff"),
812            "std/async should not retain the old retry_with_backoff export"
813        );
814    }
815
816    #[test]
817    fn signal_stdlib_module_exports_interrupt_helpers() {
818        let exports = public_functions_for_module("signal")
819            .into_iter()
820            .map(|function| function.name)
821            .collect::<BTreeSet<_>>();
822        for name in [
823            "on_interrupt",
824            "off_interrupt",
825            "interrupted",
826            "with_interrupt",
827        ] {
828            assert!(exports.contains(name), "std/signal should export {name}");
829        }
830    }
831
832    #[test]
833    fn git_stdlib_module_exports_local_wrappers() {
834        let exports = public_functions_for_module("git")
835            .into_iter()
836            .map(|function| function.name)
837            .collect::<BTreeSet<_>>();
838        for name in [
839            "git_run",
840            "git_status",
841            "git_current_branch",
842            "git_log",
843            "git_switch",
844            "git_pull_ff_only",
845            "git_find_tool",
846            "git_run_tool",
847            "git_tools",
848            "git_toolbox_tools",
849        ] {
850            assert!(exports.contains(name), "std/git should export {name}");
851        }
852    }
853
854    #[test]
855    fn agent_workers_exports_suspend_resume_wrappers() {
856        let exports = public_functions_for_module("agent/workers");
857        let suspend = exports
858            .iter()
859            .find(|function| function.name == "suspend_agent")
860            .expect("std/agent/workers should export suspend_agent");
861        assert_eq!(
862            suspend.signature,
863            "suspend_agent(worker, reason = \"\", options = nil)"
864        );
865        assert_eq!(suspend.required_params, 1);
866        assert_eq!(suspend.total_params, 3);
867
868        let resume = exports
869            .iter()
870            .find(|function| function.name == "resume_agent")
871            .expect("std/agent/workers should export resume_agent");
872        assert_eq!(
873            resume.signature,
874            "resume_agent(worker_or_snapshot, resume_input = nil, continue_transcript = true)"
875        );
876        assert_eq!(resume.required_params, 1);
877        assert_eq!(resume.total_params, 3);
878
879        let stop = exports
880            .iter()
881            .find(|function| function.name == "agent_stop")
882            .expect("std/agent/workers should export agent_stop");
883        assert_eq!(
884            stop.signature,
885            "agent_stop(worker, options: AgentStopOptions = nil)"
886        );
887        assert_eq!(stop.required_params, 1);
888        assert_eq!(stop.total_params, 2);
889
890        let parse_resume = exports
891            .iter()
892            .find(|function| function.name == "parse_resume_conditions")
893            .expect("std/agent/workers should export parse_resume_conditions");
894        assert_eq!(
895            parse_resume.signature,
896            "parse_resume_conditions(conditions = nil) -> ResumeConditions?"
897        );
898        assert_eq!(parse_resume.required_params, 0);
899        assert_eq!(parse_resume.total_params, 1);
900
901        let lifecycle = exports
902            .iter()
903            .find(|function| function.name == "agent_lifecycle_tools")
904            .expect("std/agent/workers should export agent_lifecycle_tools");
905        assert_eq!(
906            lifecycle.signature,
907            "agent_lifecycle_tools(registry = nil, options = nil)"
908        );
909        assert_eq!(lifecycle.required_params, 0);
910        assert_eq!(lifecycle.total_params, 2);
911    }
912
913    #[test]
914    fn tui_stdlib_module_exports_terminal_helpers() {
915        let exports = public_functions_for_module("tui")
916            .into_iter()
917            .map(|function| function.name)
918            .collect::<BTreeSet<_>>();
919        for name in ["page", "terminal_width", "rule", "clear", "select_from"] {
920            assert!(exports.contains(name), "std/tui should export {name}");
921        }
922    }
923
924    #[test]
925    fn semver_stdlib_module_exports_release_helpers() {
926        let exports = public_functions_for_module("semver")
927            .into_iter()
928            .map(|function| function.name)
929            .collect::<BTreeSet<_>>();
930        for name in [
931            "strip_v",
932            "add_v",
933            "is_v_semver",
934            "parse",
935            "next",
936            "bump_type",
937            "version_from_release_branch",
938            "version_from_tag",
939        ] {
940            assert!(exports.contains(name), "std/semver should export {name}");
941        }
942    }
943
944    #[test]
945    fn text_stdlib_module_exports_regex_and_pad_helpers() {
946        let exports = public_functions_for_module("text")
947            .into_iter()
948            .map(|function| function.name)
949            .collect::<BTreeSet<_>>();
950        for name in [
951            "pad_left",
952            "pad_right",
953            "repeat_string",
954            "regex_first_capture",
955            "regex_capture_groups",
956            "regex_all_first_captures",
957        ] {
958            assert!(exports.contains(name), "std/text should export {name}");
959        }
960    }
961
962    #[test]
963    fn harn_entrypoint_catalog_is_declared_by_stdlib_sources() {
964        let modules = entrypoint_modules();
965        let entries = modules
966            .iter()
967            .map(|module| (module.import_path.as_str(), module.category.as_str()))
968            .collect::<BTreeSet<_>>();
969        for entry in [
970            ("std/agent/loop", "agent.stdlib"),
971            ("std/agent/turn", "agent.stdlib"),
972            ("std/agent/primitives", "agent.stdlib"),
973            ("std/workflow/execute", "workflow.stdlib"),
974        ] {
975            assert!(entries.contains(&entry), "{entry:?} should be declared");
976        }
977    }
978
979    #[test]
980    fn matching_paren_len_closes_on_every_bracket_kind() {
981        // Each closer kind must terminate the scan once depth returns to zero,
982        // mirroring the symmetric opener arm and `split_top_level_params`.
983        assert_eq!(matching_paren_len("a, b)"), Some(4));
984        assert_eq!(matching_paren_len("x: [int])"), Some(8));
985        assert_eq!(matching_paren_len("x: {a: int})"), Some(11));
986        // A top-level `]`/`}` is the matching close for the consumed opener and
987        // must return rather than scanning to the end and yielding `None`.
988        assert_eq!(matching_paren_len("x]"), Some(1));
989        assert_eq!(matching_paren_len("x}"), Some(1));
990        assert_eq!(matching_paren_len("unterminated"), None);
991    }
992
993    #[test]
994    fn parse_public_function_line_handles_record_typed_params() {
995        let parsed =
996            parse_public_function_line("pub fn configure(opts: {retries: int}) -> bool", None)
997                .expect("signature with a record-typed parameter should parse");
998        assert_eq!(parsed.name, "configure");
999        assert_eq!(parsed.signature, "configure(opts: {retries: int}) -> bool");
1000        assert_eq!(parsed.total_params, 1);
1001        assert_eq!(parsed.required_params, 1);
1002    }
1003}