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