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