Skip to main content

harn_stdlib/
lib.rs

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