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