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