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