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