Skip to main content

harn_stdlib/
lib.rs

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