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