Skip to main content

harn_stdlib/
lib.rs

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