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.
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub struct StdlibSource {
9    pub module: &'static str,
10    pub source: &'static str,
11}
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct StdlibPromptAsset {
15    pub path: &'static str,
16    pub source: &'static str,
17}
18
19macro_rules! embedded_catalog {
20    ($entry:ident, $key:ident, [$($name:literal => $path:literal),* $(,)?]) => {
21        &[
22            $($entry {
23                $key: $name,
24                source: include_str!($path),
25            },)*
26        ]
27    };
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct StdlibPublicFunction {
32    pub name: String,
33    pub signature: String,
34    pub required_params: usize,
35    pub total_params: usize,
36    pub variadic: bool,
37    pub doc: Option<String>,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct StdlibEntrypointModule {
42    pub import_path: String,
43    pub category: String,
44}
45
46pub const STDLIB_SOURCES: &[StdlibSource] = embedded_catalog!(StdlibSource, module, [
47    "text" => "stdlib/stdlib_text.harn",
48    "semver" => "stdlib/stdlib_semver.harn",
49    "ansi" => "stdlib/stdlib_ansi.harn",
50    "table" => "stdlib/stdlib_table.harn",
51    "diff" => "stdlib/stdlib_diff.harn",
52    "edit" => "stdlib/stdlib_edit.harn",
53    "ast" => "stdlib/stdlib_ast.harn",
54    "rules" => "stdlib/stdlib_rules.harn",
55    "lint" => "stdlib/stdlib_lint.harn",
56    "artifact/web" => "stdlib/artifact/web.harn",
57    "collections" => "stdlib/stdlib_collections.harn",
58    "math" => "stdlib/stdlib_math.harn",
59    "slug" => "stdlib/stdlib_slug.harn",
60    "path" => "stdlib/stdlib_path.harn",
61    "fs" => "stdlib/stdlib_fs.harn",
62    "run_artifacts" => "stdlib/stdlib_run_artifacts.harn",
63    "os" => "stdlib/stdlib_os.harn",
64    "json" => "stdlib/stdlib_json.harn",
65    "json/stream" => "stdlib/stdlib_json_stream.harn",
66    "xml" => "stdlib/stdlib_xml.harn",
67    "cache" => "stdlib/stdlib_cache.harn",
68    "observability" => "stdlib/stdlib_observability.harn",
69    "timing" => "stdlib/stdlib_timing.harn",
70    "verification" => "stdlib/stdlib_verification.harn",
71    "tools" => "stdlib/stdlib_tools.harn",
72    "composition" => "stdlib/stdlib_composition.harn",
73    "web" => "stdlib/stdlib_web.harn",
74    "graphql" => "stdlib/stdlib_graphql.harn",
75    "code_librarian" => "stdlib/stdlib_code_librarian.harn",
76    "schema" => "stdlib/stdlib_schema.harn",
77    "identity" => "stdlib/stdlib_identity.harn",
78    "disclosure" => "stdlib/stdlib_disclosure.harn",
79    "testing" => "stdlib/stdlib_testing.harn",
80    "files" => "stdlib/stdlib_files.harn",
81    "document" => "stdlib/stdlib_document.harn",
82    "mcp" => "stdlib/stdlib_mcp.harn",
83    "vision" => "stdlib/stdlib_vision.harn",
84    "context" => "stdlib/stdlib_context.harn",
85    "context/maintenance" => "stdlib/context/maintenance.harn",
86    "context/eval" => "stdlib/context/eval.harn",
87    "eval/stats" => "stdlib/stdlib_eval_stats.harn",
88    "eval/agreement" => "stdlib/stdlib_eval_agreement.harn",
89    "runtime" => "stdlib/stdlib_runtime.harn",
90    "io" => "stdlib/stdlib_io.harn",
91    "net" => "stdlib/stdlib_net.harn",
92    "command" => "stdlib/stdlib_command.harn",
93    "signal" => "stdlib/stdlib_signal.harn",
94    "net_policy" => "stdlib/stdlib_net_policy.harn",
95    "review" => "stdlib/stdlib_review.harn",
96    "experiments" => "stdlib/stdlib_experiments.harn",
97    "project" => "stdlib/stdlib_project.harn",
98    "prompt_library" => "stdlib/stdlib_prompt_library.harn",
99    "async" => "stdlib/stdlib_async.harn",
100    "poll" => "stdlib/stdlib_poll.harn",
101    "coerce" => "stdlib/stdlib_coerce.harn",
102    "settled" => "stdlib/stdlib_settled.harn",
103    "cli" => "stdlib/stdlib_cli.harn",
104    "cli/argparse" => "stdlib/cli/argparse.harn",
105    "cli/render" => "stdlib/cli/render.harn",
106    "cli/models/batch_artifacts" => "stdlib/cli/models/batch_artifacts.harn",
107    "cli/models/lora_render" => "stdlib/cli/models/lora_render.harn",
108    "cli/paths" => "stdlib/cli/paths.harn",
109    "gha" => "stdlib/stdlib_gha.harn",
110    "tui" => "stdlib/stdlib_tui.harn",
111    "jsonl" => "stdlib/stdlib_jsonl.harn",
112    "config" => "stdlib/stdlib_config.harn",
113    "calendar" => "stdlib/stdlib_calendar.harn",
114    "agents" => "stdlib/stdlib_agents.harn",
115    "lifecycle/pool" => "stdlib/lifecycle/pool.harn",
116    "lifecycle/combinators" => "stdlib/lifecycle/combinators.harn",
117    "lifecycle/on_budget" => "stdlib/lifecycle/on_budget.harn",
118    "agent/prompts" => "stdlib/agent/prompts.harn",
119    "llm/media" => "stdlib/llm/media.harn",
120    "llm/options" => "stdlib/llm/options.harn",
121    "llm/catalog" => "stdlib/llm/catalog.harn",
122    "llm/safe" => "stdlib/llm/safe.harn",
123    "harness/policy" => "stdlib/harness/policy.harn",
124    "llm/budget" => "stdlib/llm/budget.harn",
125    "llm/economics" => "stdlib/llm/economics.harn",
126    "llm/prompts" => "stdlib/llm/prompts.harn",
127    "llm/defaults" => "stdlib/llm/defaults.harn",
128    "llm/handlers" => "stdlib/llm/handlers.harn",
129    "llm/tool_telemetry" => "stdlib/llm/tool_telemetry.harn",
130    "llm/tool_middleware" => "stdlib/llm/tool_middleware.harn",
131    "llm/tool_binder" => "stdlib/llm/tool_binder.harn",
132    "llm/structural_validator" => "stdlib/llm/structural_validator.harn",
133    "llm/missing_tool_call" => "stdlib/llm/missing_tool_call.harn",
134    "llm/scope_classifier" => "stdlib/llm/scope_classifier.harn",
135    "llm/refine" => "stdlib/llm/refine.harn",
136    "llm/ensemble" => "stdlib/llm/ensemble.harn",
137    "llm/rerank" => "stdlib/llm/rerank.harn",
138    "agent/reasoning" => "stdlib/agent/reasoning.harn",
139    "agent/options" => "stdlib/agent/options.harn",
140    "llm/judge" => "stdlib/llm/judge.harn",
141    "llm/faithfulness" => "stdlib/llm/faithfulness.harn",
142    "llm/optimize" => "stdlib/llm/optimize.harn",
143    "agent/events" => "stdlib/agent/events.harn",
144    "agent/completions" => "stdlib/agent/completions.harn",
145    "agent/transcript" => "stdlib/agent/transcript.harn",
146    "agent/primitives" => "stdlib/agent/primitives.harn",
147    "agent/progress" => "stdlib/agent/progress.harn",
148    "agent/required_tools" => "stdlib/agent/required_tools.harn",
149    "agent/stall" => "stdlib/agent/stall.harn",
150    "agent/governors" => "stdlib/agent/governors.harn",
151    "agent/control" => "stdlib/agent/control.harn",
152    "agent/best_of_n" => "stdlib/agent/best_of_n.harn",
153    "agent/loop" => "stdlib/agent/loop.harn",
154    "agent/chat" => "stdlib/agent/chat.harn",
155    "agent/user" => "stdlib/agent/user.harn",
156    "agent/tool_search" => "stdlib/agent/tool_search.harn",
157    "agent/tool_annotations" => "stdlib/agent/tool_annotations.harn",
158    "agent/turn" => "stdlib/agent/turn.harn",
159    "agent/workers" => "stdlib/agent/workers.harn",
160    "agent/introspection" => "stdlib/agent/introspection.harn",
161    "agent/resume_by" => "stdlib/agent/resume_by.harn",
162    "agent/state" => "stdlib/agent/state.harn",
163    "agent/canon" => "stdlib/agent/canon.harn",
164    "agent/skills" => "stdlib/agent/skills.harn",
165    "agent/autocompact" => "stdlib/agent/autocompact.harn",
166    "agent/mcp" => "stdlib/agent/mcp.harn",
167    "agent/command_capture" => "stdlib/agent/command_capture.harn",
168    "agent/host_tools" => "stdlib/agent/host_tools.harn",
169    "agent/host_injection" => "stdlib/agent/host_injection.harn",
170    "agent/budget" => "stdlib/agent/budget.harn",
171    "agent/daemon" => "stdlib/agent/daemon.harn",
172    "agent/preflight" => "stdlib/agent/preflight.harn",
173    "agent/postturn" => "stdlib/agent/postturn.harn",
174    "agent/stance" => "stdlib/agent/stance.harn",
175    "agent/lanes" => "stdlib/agent/lanes.harn",
176    "agent/overlays" => "stdlib/agent/overlays.harn",
177    "agent/sitrep" => "stdlib/agent/sitrep.harn",
178    "agent/judge_internals" => "stdlib/agent/judge_internals.harn",
179    "agent/judge" => "stdlib/agent/judge.harn",
180    "agent/guardrails" => "stdlib/agent/guardrails.harn",
181    "agent/step_judge" => "stdlib/agent/step_judge.harn",
182    "agent/scratchpad" => "stdlib/agent/scratchpad.harn",
183    "agent/fact" => "stdlib/agent/fact.harn",
184    "agent/hypothesis" => "stdlib/agent/hypothesis.harn",
185    "agent/pattern_knowledge" => "stdlib/agent/pattern_knowledge.harn",
186    "agent/probe" => "stdlib/agent/probe.harn",
187    "agent/stream" => "stdlib/agent/stream.harn",
188    "agent/presets" => "stdlib/agent/presets.harn",
189    "agent/pins" => "stdlib/agent/pins.harn",
190    "agent/goal" => "stdlib/agent/goal.harn",
191    "agent/task_plan" => "stdlib/agent/task_plan.harn",
192    "agent_state" => "stdlib/stdlib_agent_state.harn",
193    "memory" => "stdlib/stdlib_memory.harn",
194    "session-store" => "stdlib/stdlib_session_store.harn",
195    "coordination" => "stdlib/stdlib_coordination.harn",
196    "fleet/coordination" => "stdlib/fleet/coordination.harn",
197    "postgres" => "stdlib/stdlib_postgres.harn",
198    "postgres/query" => "stdlib/postgres/query.harn",
199    "sqlite" => "stdlib/stdlib_sqlite.harn",
200    "checkpoint" => "stdlib/stdlib_checkpoint.harn",
201    "host" => "stdlib/stdlib_host.harn",
202    "git" => "stdlib/stdlib_git.harn",
203    "hitl" => "stdlib/stdlib_hitl.harn",
204    "trust" => "stdlib/stdlib_trust.harn",
205    "corrections" => "stdlib/stdlib_corrections.harn",
206    "plan" => "stdlib/stdlib_plan.harn",
207    "waitpoints" => "stdlib/stdlib_waitpoints.harn",
208    "waitpoint" => "stdlib/stdlib_waitpoint.harn",
209    "monitors" => "stdlib/stdlib_monitors.harn",
210    "worktree" => "stdlib/stdlib_worktree.harn",
211    "acp" => "stdlib/stdlib_acp.harn",
212    "external_agent" => "stdlib/stdlib_external_agent.harn",
213    "triggers" => "stdlib/stdlib_triggers.harn",
214    "triage" => "stdlib/stdlib_triage.harn",
215    "dashboard/jobs" => "stdlib/dashboard/jobs.harn",
216    "ui_resource" => "stdlib/stdlib_ui_resource.harn",
217    "handoffs" => "stdlib/stdlib_handoffs.harn",
218    "lifecycle" => "stdlib/stdlib_lifecycle.harn",
219    "tool_hooks_catalogues" => "stdlib/stdlib_tool_hooks_catalogues.harn",
220    "tool_hooks" => "stdlib/stdlib_tool_hooks.harn",
221    "channel_guardrails" => "stdlib/stdlib_channel_guardrails.harn",
222    "personas/prelude" => "stdlib/stdlib_personas_prelude.harn",
223    "personas/bulletins" => "stdlib/stdlib_personas_bulletins.harn",
224    "connectors/shared" => "stdlib/stdlib_connectors_shared.harn",
225    "oauth/providers" => "stdlib/oauth/providers.harn",
226    "oauth/token_exchange_catalog" => "stdlib/oauth/token_exchange_catalog.harn",
227    "oauth/token_exchange" => "stdlib/oauth/token_exchange.harn",
228    "oauth/storage" => "stdlib/oauth/storage.harn",
229    "oauth/client" => "stdlib/oauth/client.harn",
230    "oauth/device_flow" => "stdlib/oauth/device_flow.harn",
231    "oauth/redaction" => "stdlib/oauth/redaction.harn",
232    "oauth/dynamic_registration" => "stdlib/oauth/dynamic_registration.harn",
233    "connectors/github" => "stdlib/stdlib_connectors_github.harn",
234    "connectors/linear" => "stdlib/stdlib_connectors_linear.harn",
235    "connectors/notion" => "stdlib/stdlib_connectors_notion.harn",
236    "connectors/slack" => "stdlib/stdlib_connectors_slack.harn",
237    "workflow/prompts" => "stdlib/workflow/prompts.harn",
238    "workflow/context" => "stdlib/workflow/context.harn",
239    "workflow/options" => "stdlib/workflow/options.harn",
240    "workflow/checkpoints" => "stdlib/workflow/checkpoints.harn",
241    "workflow/patterns" => "stdlib/workflow/patterns.harn",
242    "workflow/stage" => "stdlib/workflow/stage.harn",
243    "workflow/map" => "stdlib/workflow/map.harn",
244    "workflow/schedule" => "stdlib/workflow/schedule.harn",
245    "workflow/execute" => "stdlib/workflow/execute.harn",
246    "workflow/repair" => "stdlib/workflow/repair.harn",
247    "security" => "stdlib/stdlib_security.harn",
248    "pii" => "stdlib/stdlib_pii.harn",
249]);
250
251/// Canonical normalized connector event schemas, authored as Harn `type`
252/// declarations. This is the SOURCE OF TRUTH for the Rust event-payload
253/// structs in `crates/harn-vm/src/triggers/event/schemas_generated.rs`, which
254/// are generated from these declarations by `harn connector-schema-codegen`.
255///
256/// It is intentionally NOT registered in [`STDLIB_SOURCES`]: it is a codegen
257/// input (like `spec/openapi.yaml`), not a module loaded into every program.
258/// Exposing it as an embedded string keeps the generator independent of the
259/// current working directory.
260pub const CONNECTOR_EVENT_SCHEMAS_SOURCE: &str = include_str!("stdlib/stdlib_event_schemas.harn");
261
262pub const STDLIB_PROMPT_ASSETS: &[StdlibPromptAsset] = embedded_catalog!(StdlibPromptAsset, path, [
263    "agent/prompts/tool_contract_text.harn.prompt" => "stdlib/agent/prompts/tool_contract_text.harn.prompt",
264    "agent/prompts/tool_contract_json.harn.prompt" => "stdlib/agent/prompts/tool_contract_json.harn.prompt",
265    "agent/prompts/tool_contract_native.harn.prompt" => "stdlib/agent/prompts/tool_contract_native.harn.prompt",
266    "agent/prompts/tool_contract_text_response_protocol.harn.prompt" => "stdlib/agent/prompts/tool_contract_text_response_protocol.harn.prompt",
267    "agent/prompts/tool_contract_action_native.harn.prompt" => "stdlib/agent/prompts/tool_contract_action_native.harn.prompt",
268    "agent/prompts/tool_contract_action_text.harn.prompt" => "stdlib/agent/prompts/tool_contract_action_text.harn.prompt",
269    "agent/prompts/tool_contract_task_ledger.harn.prompt" => "stdlib/agent/prompts/tool_contract_task_ledger.harn.prompt",
270    "agent/prompts/tool_contract_deferred_tools.harn.prompt" => "stdlib/agent/prompts/tool_contract_deferred_tools.harn.prompt",
271    "agent/prompts/deferred_tool_listing.harn.prompt" => "stdlib/agent/prompts/deferred_tool_listing.harn.prompt",
272    "agent/prompts/agent_turn_preamble.harn.prompt" => "stdlib/agent/prompts/agent_turn_preamble.harn.prompt",
273    "agent/prompts/default_nudge.harn.prompt" => "stdlib/agent/prompts/default_nudge.harn.prompt",
274    "agent/prompts/agentic_user_system.harn.prompt" => "stdlib/agent/prompts/agentic_user_system.harn.prompt",
275    "agent/prompts/agentic_user_user.harn.prompt" => "stdlib/agent/prompts/agentic_user_user.harn.prompt",
276    "agent/prompts/loop_until_done_system.harn.prompt" => "stdlib/agent/prompts/loop_until_done_system.harn.prompt",
277    "agent/prompts/completion_judge_default.harn.prompt" => "stdlib/agent/prompts/completion_judge_default.harn.prompt",
278    "agent/prompts/completion_judge_feedback_fallback.harn.prompt" => "stdlib/agent/prompts/completion_judge_feedback_fallback.harn.prompt",
279    "agent/prompts/completion_judge_user.harn.prompt" => "stdlib/agent/prompts/completion_judge_user.harn.prompt",
280    "agent/prompts/step_judge_system_default.harn.prompt" => "stdlib/agent/prompts/step_judge_system_default.harn.prompt",
281    "agent/prompts/step_judge_system_adversarial.harn.prompt" => "stdlib/agent/prompts/step_judge_system_adversarial.harn.prompt",
282    "agent/prompts/step_judge_user.harn.prompt" => "stdlib/agent/prompts/step_judge_user.harn.prompt",
283    "agent/prompts/parse_guidance.harn.prompt" => "stdlib/agent/prompts/parse_guidance.harn.prompt",
284    "agent/prompts/native_tool_contract_feedback.harn.prompt" => "stdlib/agent/prompts/native_tool_contract_feedback.harn.prompt",
285    "agent/prompts/verification_gate_feedback.harn.prompt" => "stdlib/agent/prompts/verification_gate_feedback.harn.prompt",
286    "agent/prompts/daemon_watch_feedback.harn.prompt" => "stdlib/agent/prompts/daemon_watch_feedback.harn.prompt",
287    "agent/prompts/daemon_timer_feedback.harn.prompt" => "stdlib/agent/prompts/daemon_timer_feedback.harn.prompt",
288    "llm/prompts/completion_fallback_system.harn.prompt" => "stdlib/llm/prompts/completion_fallback_system.harn.prompt",
289    "llm/prompts/completion_fallback_user.harn.prompt" => "stdlib/llm/prompts/completion_fallback_user.harn.prompt",
290    "llm/prompts/transcript_summarize_user.harn.prompt" => "stdlib/llm/prompts/transcript_summarize_user.harn.prompt",
291    "llm/prompts/sitrep_user.harn.prompt" => "stdlib/llm/prompts/sitrep_user.harn.prompt",
292    "llm/prompts/structural_chain_of_draft.harn.prompt" => "stdlib/llm/prompts/structural_chain_of_draft.harn.prompt",
293    "llm/prompts/schema_recover_repair.harn.prompt" => "stdlib/llm/prompts/schema_recover_repair.harn.prompt",
294    "llm/prompts/structured_envelope_schema_contract.harn.prompt" => "stdlib/llm/prompts/structured_envelope_schema_contract.harn.prompt",
295    "llm/prompts/structured_envelope_repair.harn.prompt" => "stdlib/llm/prompts/structured_envelope_repair.harn.prompt",
296    "llm/prompts/pairwise_rerank_user.harn.prompt" => "stdlib/llm/prompts/pairwise_rerank_user.harn.prompt",
297    "llm/prompts/tool_binder_user.harn.prompt" => "stdlib/llm/prompts/tool_binder_user.harn.prompt",
298    "workflow/prompts/stage.harn.prompt" => "stdlib/workflow/prompts/stage.harn.prompt",
299    "workflow/prompts/verification_context_intro.harn.prompt" => "stdlib/workflow/prompts/verification_context_intro.harn.prompt",
300    "orchestration/prompts/compaction_summary.harn.prompt" => "stdlib/orchestration/prompts/compaction_summary.harn.prompt",
301    "orchestration/prompts/compaction_policy_replacement.harn.prompt" => "stdlib/orchestration/prompts/compaction_policy_replacement.harn.prompt",
302]);
303
304/// Embedded `.harn` script that backs a CLI subcommand. Looked up by
305/// the `harn-cli` dispatch wedge (see harn#2293 epic and harn#2294 G1)
306/// so subcommands can ship in Harn instead of Rust.
307#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308pub struct StdlibCliScript {
309    /// Lookup name. For nested scripts this is the path under
310    /// `stdlib/cli/` without the `.harn` extension (e.g. `"eval/prompt"`
311    /// for `stdlib/cli/eval/prompt.harn`).
312    pub name: &'static str,
313    /// Embedded source. Run via the existing `harn run` codepath by the
314    /// dispatch wedge.
315    pub source: &'static str,
316}
317
318pub const STDLIB_CLI_SCRIPTS: &[StdlibCliScript] = embedded_catalog!(StdlibCliScript, name, [
319    "codemod" => "stdlib/cli/codemod.harn",
320    "canon/check" => "stdlib/cli/canon/check.harn",
321    "doctor" => "stdlib/cli/doctor.harn",
322    "echo" => "stdlib/cli/echo.harn",
323    // Helper module for the embedded `eval/*` scripts. Has a stub `main`
324    // that exits non-zero — sibling scripts inline its helpers until the
325    // dispatch wedge gains a cross-script import surface (#2300 / G7).
326    "eval/_runner" => "stdlib/cli/eval/_runner.harn",
327    "eval/context" => "stdlib/cli/eval/context.harn",
328    "eval/model_selector" => "stdlib/cli/eval/model_selector.harn",
329    "eval/tool_calls" => "stdlib/cli/eval/tool_calls.harn",
330    "eval/coding_agent" => "stdlib/cli/eval/coding_agent.harn",
331    "eval/scope_triage" => "stdlib/cli/eval/scope_triage.harn",
332    "eval/prompt" => "stdlib/cli/eval/prompt.harn",
333    "explain" => "stdlib/cli/explain.harn",
334    "graph" => "stdlib/cli/graph.harn",
335    "models/batch_plan" => "stdlib/cli/models/batch_plan.harn",
336    "models/list" => "stdlib/cli/models/list.harn",
337    "models/lora_inspect" => "stdlib/cli/models/lora_inspect.harn",
338    "models/lora_export" => "stdlib/cli/models/lora_export.harn",
339    "models/lora_manifest" => "stdlib/cli/models/lora_manifest.harn",
340    "models/lora_preflight" => "stdlib/cli/models/lora_preflight.harn",
341    "models/lora_promote" => "stdlib/cli/models/lora_promote.harn",
342    "models/lora_plan" => "stdlib/cli/models/lora_plan.harn",
343    "models/lora_train" => "stdlib/cli/models/lora_train.harn",
344    "models/recommend" => "stdlib/cli/models/recommend.harn",
345    "models/test" => "stdlib/cli/models/test.harn",
346    "precompile" => "stdlib/cli/precompile.harn",
347    "providers/cache_probe" => "stdlib/cli/providers/cache_probe.harn",
348    "providers/catalog" => "stdlib/cli/providers/catalog.harn",
349    "providers/probe" => "stdlib/cli/providers/probe.harn",
350    "providers/recommend" => "stdlib/cli/providers/recommend.harn",
351    "providers/tool_probe" => "stdlib/cli/providers/tool_probe.harn",
352    "providers/tool_scorecard" => "stdlib/cli/providers/tool_scorecard.harn",
353    "routes" => "stdlib/cli/routes.harn",
354    "scan" => "stdlib/cli/scan.harn",
355    "scaffold/init" => "stdlib/cli/scaffold/init.harn",
356    "scaffold/tool_new" => "stdlib/cli/scaffold/tool_new.harn",
357    "trace_import" => "stdlib/cli/trace_import.harn",
358    "try" => "stdlib/cli/try.harn",
359    "version" => "stdlib/cli/version.harn",
360]);
361
362pub fn get_stdlib_source(module: &str) -> Option<&'static str> {
363    STDLIB_SOURCES
364        .iter()
365        .find_map(|entry| (entry.module == module).then_some(entry.source))
366}
367
368/// Find an embedded CLI subcommand script by name. Returns the embedded
369/// source string when present, or `None` if no script with that name is
370/// registered in [`STDLIB_CLI_SCRIPTS`].
371pub fn find_cli_script(name: &str) -> Option<&'static str> {
372    STDLIB_CLI_SCRIPTS
373        .iter()
374        .find_map(|entry| (entry.name == name).then_some(entry.source))
375}
376
377pub fn get_stdlib_prompt_asset(path: &str) -> Option<&'static str> {
378    let path = path.strip_prefix("std/").unwrap_or(path);
379    STDLIB_PROMPT_ASSETS
380        .iter()
381        .find_map(|entry| (entry.path == path).then_some(entry.source))
382}
383
384pub fn public_functions_for_module(module: &str) -> Vec<StdlibPublicFunction> {
385    let Some(source) = get_stdlib_source(module) else {
386        return Vec::new();
387    };
388    public_functions_from_source(source)
389}
390
391pub fn entrypoint_modules() -> Vec<StdlibEntrypointModule> {
392    STDLIB_SOURCES
393        .iter()
394        .filter_map(|entry| {
395            entrypoint_category_from_source(entry.source).map(|category| StdlibEntrypointModule {
396                import_path: format!("std/{}", entry.module),
397                category,
398            })
399        })
400        .collect()
401}
402
403fn entrypoint_category_from_source(source: &str) -> Option<String> {
404    for line in source.lines() {
405        let line = line.trim();
406        if line.is_empty() {
407            continue;
408        }
409        if let Some(category) = line.strip_prefix("// @harn-entrypoint-category ") {
410            let category = category.trim();
411            return (!category.is_empty()).then(|| category.to_string());
412        }
413        if !line.starts_with("//") {
414            return None;
415        }
416    }
417    None
418}
419
420fn public_functions_from_source(source: &str) -> Vec<StdlibPublicFunction> {
421    let mut out = Vec::new();
422    let mut doc: Option<String> = None;
423    let lines = source.lines().collect::<Vec<_>>();
424    let mut index = 0usize;
425    while index < lines.len() {
426        let line = lines[index].trim();
427        if line.starts_with("/**") {
428            let (parsed, next) = parse_harndoc(&lines, index);
429            doc = parsed;
430            index = next;
431            continue;
432        }
433        if line.starts_with("pub fn ") {
434            let (signature_line, next) = collect_public_function_signature(&lines, index);
435            if let Some(function) = parse_public_function_line(&signature_line, doc.take()) {
436                out.push(function);
437                index = next;
438                continue;
439            }
440        }
441        if let Some(function) = parse_public_function_line(line, doc.take()) {
442            out.push(function);
443        } else if !line.is_empty() && !line.starts_with("//") {
444            doc = None;
445        }
446        index += 1;
447    }
448    out
449}
450
451fn collect_public_function_signature(lines: &[&str], start: usize) -> (String, usize) {
452    let mut parts = Vec::new();
453    let mut index = start;
454    while index < lines.len() {
455        parts.push(lines[index].trim().to_string());
456        let candidate = parts.join(" ");
457        if public_function_signature_complete(&candidate) {
458            return (candidate, index + 1);
459        }
460        index += 1;
461    }
462    (parts.join(" "), index)
463}
464
465fn public_function_signature_complete(line: &str) -> bool {
466    let Some(rest) = line.strip_prefix("pub fn ") else {
467        return false;
468    };
469    let Some(name_end) = rest.find('(') else {
470        return false;
471    };
472    matching_paren_len(&rest[name_end + 1..]).is_some()
473}
474
475fn parse_harndoc(lines: &[&str], start: usize) -> (Option<String>, usize) {
476    let mut parts = Vec::new();
477    let mut index = start;
478    while index < lines.len() {
479        let mut line = lines[index].trim();
480        if index == start {
481            line = line.trim_start_matches("/**").trim();
482        }
483        let done = line.ends_with("*/");
484        line = line.trim_end_matches("*/").trim();
485        line = line.trim_start_matches('*').trim();
486        if !line.is_empty() {
487            parts.push(line.to_string());
488        }
489        index += 1;
490        if done {
491            break;
492        }
493    }
494    let text = parts.join("\n").trim().to_string();
495    ((!text.is_empty()).then_some(text), index)
496}
497
498fn parse_public_function_line(line: &str, doc: Option<String>) -> Option<StdlibPublicFunction> {
499    let rest = line.strip_prefix("pub fn ")?.trim();
500    let name_end = rest.find('(')?;
501    let name = rest[..name_end].trim();
502    if name.is_empty() {
503        return None;
504    }
505    let params_start = name_end + 1;
506    let params_len = matching_paren_len(&rest[params_start..])?;
507    let params = &rest[params_start..params_start + params_len];
508    let after = rest[params_start + params_len + 1..].trim();
509    let return_type = after
510        .strip_prefix("->")
511        .and_then(|tail| tail.split('{').next())
512        .map(str::trim)
513        .filter(|value| !value.is_empty());
514    let signature = match return_type {
515        Some(ret) => format!("{name}({params}) -> {ret}"),
516        None => format!("{name}({params})"),
517    };
518    let param_parts = split_top_level_params(params);
519    let total_params = param_parts
520        .iter()
521        .filter(|param| !param.trim().is_empty())
522        .count();
523    let variadic = param_parts
524        .iter()
525        .any(|param| param.trim_start().starts_with("..."));
526    let required_params = param_parts
527        .iter()
528        .filter(|param| {
529            let param = param.trim();
530            !param.is_empty() && !param.contains('=') && !param.starts_with("...")
531        })
532        .count();
533    Some(StdlibPublicFunction {
534        name: name.to_string(),
535        signature,
536        required_params,
537        total_params,
538        variadic,
539        doc,
540    })
541}
542
543fn matching_paren_len(input: &str) -> Option<usize> {
544    let mut depth = 1usize;
545    for (offset, ch) in input.char_indices() {
546        match ch {
547            '(' | '[' | '{' => depth += 1,
548            ')' | ']' | '}' => {
549                depth = depth.saturating_sub(1);
550                if depth == 0 {
551                    return Some(offset);
552                }
553            }
554            _ => {}
555        }
556    }
557    None
558}
559
560fn split_top_level_params(params: &str) -> Vec<&str> {
561    let mut out = Vec::new();
562    let mut depth = 0isize;
563    let mut start = 0usize;
564    for (offset, ch) in params.char_indices() {
565        match ch {
566            '(' | '[' | '{' => depth += 1,
567            ')' | ']' | '}' => depth -= 1,
568            ',' if depth == 0 => {
569                out.push(&params[start..offset]);
570                start = offset + 1;
571            }
572            _ => {}
573        }
574    }
575    out.push(&params[start..]);
576    out
577}
578
579#[cfg(test)]
580mod tests {
581    use std::collections::BTreeSet;
582
583    use super::{
584        entrypoint_modules, find_cli_script, get_stdlib_prompt_asset, get_stdlib_source,
585        matching_paren_len, parse_public_function_line, public_functions_for_module,
586        STDLIB_CLI_SCRIPTS, STDLIB_PROMPT_ASSETS, STDLIB_SOURCES,
587    };
588
589    #[test]
590    fn stdlib_sources_are_non_empty() {
591        for entry in STDLIB_SOURCES {
592            assert!(
593                !entry.source.trim().is_empty(),
594                "{} should have non-empty source",
595                entry.module
596            );
597        }
598    }
599
600    #[test]
601    fn cli_scripts_are_non_empty_and_uniquely_named() {
602        let mut seen = BTreeSet::new();
603        for entry in STDLIB_CLI_SCRIPTS {
604            assert!(
605                !entry.source.trim().is_empty(),
606                "cli/{} should have non-empty source",
607                entry.name
608            );
609            assert!(
610                seen.insert(entry.name),
611                "cli/{} is registered more than once in STDLIB_CLI_SCRIPTS",
612                entry.name
613            );
614        }
615    }
616
617    #[test]
618    fn find_cli_script_round_trips() {
619        for entry in STDLIB_CLI_SCRIPTS {
620            assert_eq!(find_cli_script(entry.name), Some(entry.source));
621        }
622        assert!(find_cli_script("not-a-real-script").is_none());
623    }
624
625    #[test]
626    fn stdlib_source_names_are_unique() {
627        let mut names = BTreeSet::new();
628        for entry in STDLIB_SOURCES {
629            assert!(names.insert(entry.module), "duplicate {}", entry.module);
630        }
631    }
632
633    #[test]
634    fn stdlib_prompt_assets_are_non_empty() {
635        for entry in STDLIB_PROMPT_ASSETS {
636            assert!(
637                !entry.source.trim().is_empty(),
638                "{} should have non-empty prompt asset source",
639                entry.path
640            );
641        }
642    }
643
644    #[test]
645    fn stdlib_prompt_asset_paths_are_unique() {
646        let mut paths = BTreeSet::new();
647        for entry in STDLIB_PROMPT_ASSETS {
648            assert!(paths.insert(entry.path), "duplicate {}", entry.path);
649        }
650    }
651
652    #[test]
653    fn key_stdlib_modules_resolve() {
654        for module in [
655            "context",
656            "context/maintenance",
657            "context/eval",
658            "eval/stats",
659            "eval/agreement",
660            "edit",
661            "verification",
662            "disclosure",
663            "artifact/web",
664            "command",
665            "waitpoint",
666            "llm/handlers",
667            "llm/tool_middleware",
668            "llm/tool_binder",
669            "llm/missing_tool_call",
670            "llm/ensemble",
671            "llm/rerank",
672            "personas/prelude",
673            "personas/bulletins",
674            "agent/host_tools",
675            "agent/host_injection",
676            "agent/user",
677            "agent/governors",
678            "agent/guardrails",
679            "cli/models/batch_artifacts",
680            "cli/models/lora_render",
681            "llm/optimize",
682            "llm/judge",
683            "llm/faithfulness",
684            "llm/refine",
685            "connectors/shared",
686            "connectors/github",
687            "connectors/linear",
688            "connectors/notion",
689            "connectors/slack",
690            "triage",
691            "dashboard/jobs",
692            "ui_resource",
693        ] {
694            assert!(
695                get_stdlib_source(module).is_some(),
696                "std/{module} should resolve"
697            );
698        }
699    }
700
701    #[test]
702    fn key_stdlib_prompt_assets_resolve() {
703        for path in [
704            "std/agent/prompts/tool_contract_text.harn.prompt",
705            "std/agent/prompts/default_nudge.harn.prompt",
706            "std/agent/prompts/completion_judge_default.harn.prompt",
707            "std/workflow/prompts/stage.harn.prompt",
708            "std/orchestration/prompts/compaction_summary.harn.prompt",
709            "std/orchestration/prompts/compaction_policy_replacement.harn.prompt",
710        ] {
711            assert!(
712                get_stdlib_prompt_asset(path).is_some(),
713                "{path} should resolve"
714            );
715        }
716    }
717
718    #[test]
719    fn public_function_catalog_derives_signatures_from_harn_source() {
720        let exports = public_functions_for_module("workflow/execute");
721        assert_eq!(exports.len(), 1);
722        assert_eq!(exports[0].name, "workflow_execute");
723        assert_eq!(
724            exports[0].signature,
725            "workflow_execute(task, graph, artifacts = nil, options = nil)"
726        );
727        assert_eq!(exports[0].required_params, 2);
728        assert_eq!(exports[0].total_params, 4);
729    }
730
731    #[test]
732    fn command_stdlib_module_exports_step_helpers() {
733        let exports = public_functions_for_module("command")
734            .into_iter()
735            .map(|function| function.name)
736            .collect::<BTreeSet<_>>();
737        for name in [
738            "command_run",
739            "command_wait",
740            "command_cancel",
741            "command_run_streaming",
742            "command_output_tail",
743            "command_json",
744            "command_json_step",
745            "command_try",
746            "command_step",
747            "command_steps_append",
748            "command_last_failed_step",
749            "command_step_ref",
750        ] {
751            assert!(exports.contains(name), "std/command should export {name}");
752        }
753    }
754
755    #[test]
756    fn disclosure_stdlib_module_exports_render_helpers() {
757        let exports = public_functions_for_module("disclosure")
758            .into_iter()
759            .map(|function| function.name)
760            .collect::<BTreeSet<_>>();
761        assert!(
762            exports.contains("render"),
763            "std/disclosure should export render"
764        );
765        assert!(
766            exports.contains("git_trailers"),
767            "std/disclosure should export git_trailers"
768        );
769        assert!(
770            exports.contains("slack_message_disclosure"),
771            "std/disclosure should export slack_message_disclosure"
772        );
773        assert!(
774            exports.contains("append_git_trailers"),
775            "std/disclosure should export append_git_trailers"
776        );
777    }
778
779    #[test]
780    fn async_stdlib_exports_predicate_backoff_name_only() {
781        let exports = public_functions_for_module("async")
782            .into_iter()
783            .map(|function| function.name)
784            .collect::<BTreeSet<_>>();
785        assert!(
786            exports.contains("retry_predicate_with_backoff"),
787            "std/async should export retry_predicate_with_backoff"
788        );
789        assert!(
790            !exports.contains("retry_with_backoff"),
791            "std/async should not retain the old retry_with_backoff export"
792        );
793    }
794
795    #[test]
796    fn signal_stdlib_module_exports_interrupt_helpers() {
797        let exports = public_functions_for_module("signal")
798            .into_iter()
799            .map(|function| function.name)
800            .collect::<BTreeSet<_>>();
801        for name in [
802            "on_interrupt",
803            "off_interrupt",
804            "interrupted",
805            "with_interrupt",
806        ] {
807            assert!(exports.contains(name), "std/signal should export {name}");
808        }
809    }
810
811    #[test]
812    fn git_stdlib_module_exports_local_wrappers() {
813        let exports = public_functions_for_module("git")
814            .into_iter()
815            .map(|function| function.name)
816            .collect::<BTreeSet<_>>();
817        for name in [
818            "git_run",
819            "git_status",
820            "git_current_branch",
821            "git_log",
822            "git_switch",
823            "git_pull_ff_only",
824            "git_find_tool",
825            "git_run_tool",
826            "git_tools",
827            "git_toolbox_tools",
828        ] {
829            assert!(exports.contains(name), "std/git should export {name}");
830        }
831    }
832
833    #[test]
834    fn agent_workers_exports_suspend_resume_wrappers() {
835        let exports = public_functions_for_module("agent/workers");
836        let suspend = exports
837            .iter()
838            .find(|function| function.name == "suspend_agent")
839            .expect("std/agent/workers should export suspend_agent");
840        assert_eq!(
841            suspend.signature,
842            "suspend_agent(worker, reason = \"\", options = nil)"
843        );
844        assert_eq!(suspend.required_params, 1);
845        assert_eq!(suspend.total_params, 3);
846
847        let resume = exports
848            .iter()
849            .find(|function| function.name == "resume_agent")
850            .expect("std/agent/workers should export resume_agent");
851        assert_eq!(
852            resume.signature,
853            "resume_agent(worker_or_snapshot, resume_input = nil, continue_transcript = true)"
854        );
855        assert_eq!(resume.required_params, 1);
856        assert_eq!(resume.total_params, 3);
857
858        let stop = exports
859            .iter()
860            .find(|function| function.name == "agent_stop")
861            .expect("std/agent/workers should export agent_stop");
862        assert_eq!(
863            stop.signature,
864            "agent_stop(worker, options: AgentStopOptions = nil)"
865        );
866        assert_eq!(stop.required_params, 1);
867        assert_eq!(stop.total_params, 2);
868
869        let parse_resume = exports
870            .iter()
871            .find(|function| function.name == "parse_resume_conditions")
872            .expect("std/agent/workers should export parse_resume_conditions");
873        assert_eq!(
874            parse_resume.signature,
875            "parse_resume_conditions(conditions = nil) -> ResumeConditions?"
876        );
877        assert_eq!(parse_resume.required_params, 0);
878        assert_eq!(parse_resume.total_params, 1);
879
880        let lifecycle = exports
881            .iter()
882            .find(|function| function.name == "agent_lifecycle_tools")
883            .expect("std/agent/workers should export agent_lifecycle_tools");
884        assert_eq!(
885            lifecycle.signature,
886            "agent_lifecycle_tools(registry = nil, options = nil)"
887        );
888        assert_eq!(lifecycle.required_params, 0);
889        assert_eq!(lifecycle.total_params, 2);
890    }
891
892    #[test]
893    fn tui_stdlib_module_exports_terminal_helpers() {
894        let exports = public_functions_for_module("tui")
895            .into_iter()
896            .map(|function| function.name)
897            .collect::<BTreeSet<_>>();
898        for name in ["page", "terminal_width", "rule", "clear", "select_from"] {
899            assert!(exports.contains(name), "std/tui should export {name}");
900        }
901    }
902
903    #[test]
904    fn semver_stdlib_module_exports_release_helpers() {
905        let exports = public_functions_for_module("semver")
906            .into_iter()
907            .map(|function| function.name)
908            .collect::<BTreeSet<_>>();
909        for name in [
910            "strip_v",
911            "add_v",
912            "is_v_semver",
913            "parse",
914            "next",
915            "bump_type",
916            "version_from_release_branch",
917            "version_from_tag",
918        ] {
919            assert!(exports.contains(name), "std/semver should export {name}");
920        }
921    }
922
923    #[test]
924    fn text_stdlib_module_exports_regex_and_pad_helpers() {
925        let exports = public_functions_for_module("text")
926            .into_iter()
927            .map(|function| function.name)
928            .collect::<BTreeSet<_>>();
929        for name in [
930            "pad_left",
931            "pad_right",
932            "repeat_string",
933            "regex_first_capture",
934            "regex_capture_groups",
935            "regex_all_first_captures",
936        ] {
937            assert!(exports.contains(name), "std/text should export {name}");
938        }
939    }
940
941    #[test]
942    fn harn_entrypoint_catalog_is_declared_by_stdlib_sources() {
943        let modules = entrypoint_modules();
944        let entries = modules
945            .iter()
946            .map(|module| (module.import_path.as_str(), module.category.as_str()))
947            .collect::<BTreeSet<_>>();
948        for entry in [
949            ("std/agent/loop", "agent.stdlib"),
950            ("std/agent/turn", "agent.stdlib"),
951            ("std/agent/primitives", "agent.stdlib"),
952            ("std/workflow/execute", "workflow.stdlib"),
953        ] {
954            assert!(entries.contains(&entry), "{entry:?} should be declared");
955        }
956    }
957
958    #[test]
959    fn matching_paren_len_closes_on_every_bracket_kind() {
960        // Each closer kind must terminate the scan once depth returns to zero,
961        // mirroring the symmetric opener arm and `split_top_level_params`.
962        assert_eq!(matching_paren_len("a, b)"), Some(4));
963        assert_eq!(matching_paren_len("x: [int])"), Some(8));
964        assert_eq!(matching_paren_len("x: {a: int})"), Some(11));
965        // A top-level `]`/`}` is the matching close for the consumed opener and
966        // must return rather than scanning to the end and yielding `None`.
967        assert_eq!(matching_paren_len("x]"), Some(1));
968        assert_eq!(matching_paren_len("x}"), Some(1));
969        assert_eq!(matching_paren_len("unterminated"), None);
970    }
971
972    #[test]
973    fn parse_public_function_line_handles_record_typed_params() {
974        let parsed =
975            parse_public_function_line("pub fn configure(opts: {retries: int}) -> bool", None)
976                .expect("signature with a record-typed parameter should parse");
977        assert_eq!(parsed.name, "configure");
978        assert_eq!(parsed.signature, "configure(opts: {retries: int}) -> bool");
979        assert_eq!(parsed.total_params, 1);
980        assert_eq!(parsed.required_params, 1);
981    }
982}