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