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