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