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