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