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