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