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