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